tinymce.js 1.0 MB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349163501635116352163531635416355163561635716358163591636016361163621636316364163651636616367163681636916370163711637216373163741637516376163771637816379163801638116382163831638416385163861638716388163891639016391163921639316394163951639616397163981639916400164011640216403164041640516406164071640816409164101641116412164131641416415164161641716418164191642016421164221642316424164251642616427164281642916430164311643216433164341643516436164371643816439164401644116442164431644416445164461644716448164491645016451164521645316454164551645616457164581645916460164611646216463164641646516466164671646816469164701647116472164731647416475164761647716478164791648016481164821648316484164851648616487164881648916490164911649216493164941649516496164971649816499165001650116502165031650416505165061650716508165091651016511165121651316514165151651616517165181651916520165211652216523165241652516526165271652816529165301653116532165331653416535165361653716538165391654016541165421654316544165451654616547165481654916550165511655216553165541655516556165571655816559165601656116562165631656416565165661656716568165691657016571165721657316574165751657616577165781657916580165811658216583165841658516586165871658816589165901659116592165931659416595165961659716598165991660016601166021660316604166051660616607166081660916610166111661216613166141661516616166171661816619166201662116622166231662416625166261662716628166291663016631166321663316634166351663616637166381663916640166411664216643166441664516646166471664816649166501665116652166531665416655166561665716658166591666016661166621666316664166651666616667166681666916670166711667216673166741667516676166771667816679166801668116682166831668416685166861668716688166891669016691166921669316694166951669616697166981669916700167011670216703167041670516706167071670816709167101671116712167131671416715167161671716718167191672016721167221672316724167251672616727167281672916730167311673216733167341673516736167371673816739167401674116742167431674416745167461674716748167491675016751167521675316754167551675616757167581675916760167611676216763167641676516766167671676816769167701677116772167731677416775167761677716778167791678016781167821678316784167851678616787167881678916790167911679216793167941679516796167971679816799168001680116802168031680416805168061680716808168091681016811168121681316814168151681616817168181681916820168211682216823168241682516826168271682816829168301683116832168331683416835168361683716838168391684016841168421684316844168451684616847168481684916850168511685216853168541685516856168571685816859168601686116862168631686416865168661686716868168691687016871168721687316874168751687616877168781687916880168811688216883168841688516886168871688816889168901689116892168931689416895168961689716898168991690016901169021690316904169051690616907169081690916910169111691216913169141691516916169171691816919169201692116922169231692416925169261692716928169291693016931169321693316934169351693616937169381693916940169411694216943169441694516946169471694816949169501695116952169531695416955169561695716958169591696016961169621696316964169651696616967169681696916970169711697216973169741697516976169771697816979169801698116982169831698416985169861698716988169891699016991169921699316994169951699616997169981699917000170011700217003170041700517006170071700817009170101701117012170131701417015170161701717018170191702017021170221702317024170251702617027170281702917030170311703217033170341703517036170371703817039170401704117042170431704417045170461704717048170491705017051170521705317054170551705617057170581705917060170611706217063170641706517066170671706817069170701707117072170731707417075170761707717078170791708017081170821708317084170851708617087170881708917090170911709217093170941709517096170971709817099171001710117102171031710417105171061710717108171091711017111171121711317114171151711617117171181711917120171211712217123171241712517126171271712817129171301713117132171331713417135171361713717138171391714017141171421714317144171451714617147171481714917150171511715217153171541715517156171571715817159171601716117162171631716417165171661716717168171691717017171171721717317174171751717617177171781717917180171811718217183171841718517186171871718817189171901719117192171931719417195171961719717198171991720017201172021720317204172051720617207172081720917210172111721217213172141721517216172171721817219172201722117222172231722417225172261722717228172291723017231172321723317234172351723617237172381723917240172411724217243172441724517246172471724817249172501725117252172531725417255172561725717258172591726017261172621726317264172651726617267172681726917270172711727217273172741727517276172771727817279172801728117282172831728417285172861728717288172891729017291172921729317294172951729617297172981729917300173011730217303173041730517306173071730817309173101731117312173131731417315173161731717318173191732017321173221732317324173251732617327173281732917330173311733217333173341733517336173371733817339173401734117342173431734417345173461734717348173491735017351173521735317354173551735617357173581735917360173611736217363173641736517366173671736817369173701737117372173731737417375173761737717378173791738017381173821738317384173851738617387173881738917390173911739217393173941739517396173971739817399174001740117402174031740417405174061740717408174091741017411174121741317414174151741617417174181741917420174211742217423174241742517426174271742817429174301743117432174331743417435174361743717438174391744017441174421744317444174451744617447174481744917450174511745217453174541745517456174571745817459174601746117462174631746417465174661746717468174691747017471174721747317474174751747617477174781747917480174811748217483174841748517486174871748817489174901749117492174931749417495174961749717498174991750017501175021750317504175051750617507175081750917510175111751217513175141751517516175171751817519175201752117522175231752417525175261752717528175291753017531175321753317534175351753617537175381753917540175411754217543175441754517546175471754817549175501755117552175531755417555175561755717558175591756017561175621756317564175651756617567175681756917570175711757217573175741757517576175771757817579175801758117582175831758417585175861758717588175891759017591175921759317594175951759617597175981759917600176011760217603176041760517606176071760817609176101761117612176131761417615176161761717618176191762017621176221762317624176251762617627176281762917630176311763217633176341763517636176371763817639176401764117642176431764417645176461764717648176491765017651176521765317654176551765617657176581765917660176611766217663176641766517666176671766817669176701767117672176731767417675176761767717678176791768017681176821768317684176851768617687176881768917690176911769217693176941769517696176971769817699177001770117702177031770417705177061770717708177091771017711177121771317714177151771617717177181771917720177211772217723177241772517726177271772817729177301773117732177331773417735177361773717738177391774017741177421774317744177451774617747177481774917750177511775217753177541775517756177571775817759177601776117762177631776417765177661776717768177691777017771177721777317774177751777617777177781777917780177811778217783177841778517786177871778817789177901779117792177931779417795177961779717798177991780017801178021780317804178051780617807178081780917810178111781217813178141781517816178171781817819178201782117822178231782417825178261782717828178291783017831178321783317834178351783617837178381783917840178411784217843178441784517846178471784817849178501785117852178531785417855178561785717858178591786017861178621786317864178651786617867178681786917870178711787217873178741787517876178771787817879178801788117882178831788417885178861788717888178891789017891178921789317894178951789617897178981789917900179011790217903179041790517906179071790817909179101791117912179131791417915179161791717918179191792017921179221792317924179251792617927179281792917930179311793217933179341793517936179371793817939179401794117942179431794417945179461794717948179491795017951179521795317954179551795617957179581795917960179611796217963179641796517966179671796817969179701797117972179731797417975179761797717978179791798017981179821798317984179851798617987179881798917990179911799217993179941799517996179971799817999180001800118002180031800418005180061800718008180091801018011180121801318014180151801618017180181801918020180211802218023180241802518026180271802818029180301803118032180331803418035180361803718038180391804018041180421804318044180451804618047180481804918050180511805218053180541805518056180571805818059180601806118062180631806418065180661806718068180691807018071180721807318074180751807618077180781807918080180811808218083180841808518086180871808818089180901809118092180931809418095180961809718098180991810018101181021810318104181051810618107181081810918110181111811218113181141811518116181171811818119181201812118122181231812418125181261812718128181291813018131181321813318134181351813618137181381813918140181411814218143181441814518146181471814818149181501815118152181531815418155181561815718158181591816018161181621816318164181651816618167181681816918170181711817218173181741817518176181771817818179181801818118182181831818418185181861818718188181891819018191181921819318194181951819618197181981819918200182011820218203182041820518206182071820818209182101821118212182131821418215182161821718218182191822018221182221822318224182251822618227182281822918230182311823218233182341823518236182371823818239182401824118242182431824418245182461824718248182491825018251182521825318254182551825618257182581825918260182611826218263182641826518266182671826818269182701827118272182731827418275182761827718278182791828018281182821828318284182851828618287182881828918290182911829218293182941829518296182971829818299183001830118302183031830418305183061830718308183091831018311183121831318314183151831618317183181831918320183211832218323183241832518326183271832818329183301833118332183331833418335183361833718338183391834018341183421834318344183451834618347183481834918350183511835218353183541835518356183571835818359183601836118362183631836418365183661836718368183691837018371183721837318374183751837618377183781837918380183811838218383183841838518386183871838818389183901839118392183931839418395183961839718398183991840018401184021840318404184051840618407184081840918410184111841218413184141841518416184171841818419184201842118422184231842418425184261842718428184291843018431184321843318434184351843618437184381843918440184411844218443184441844518446184471844818449184501845118452184531845418455184561845718458184591846018461184621846318464184651846618467184681846918470184711847218473184741847518476184771847818479184801848118482184831848418485184861848718488184891849018491184921849318494184951849618497184981849918500185011850218503185041850518506185071850818509185101851118512185131851418515185161851718518185191852018521185221852318524185251852618527185281852918530185311853218533185341853518536185371853818539185401854118542185431854418545185461854718548185491855018551185521855318554185551855618557185581855918560185611856218563185641856518566185671856818569185701857118572185731857418575185761857718578185791858018581185821858318584185851858618587185881858918590185911859218593185941859518596185971859818599186001860118602186031860418605186061860718608186091861018611186121861318614186151861618617186181861918620186211862218623186241862518626186271862818629186301863118632186331863418635186361863718638186391864018641186421864318644186451864618647186481864918650186511865218653186541865518656186571865818659186601866118662186631866418665186661866718668186691867018671186721867318674186751867618677186781867918680186811868218683186841868518686186871868818689186901869118692186931869418695186961869718698186991870018701187021870318704187051870618707187081870918710187111871218713187141871518716187171871818719187201872118722187231872418725187261872718728187291873018731187321873318734187351873618737187381873918740187411874218743187441874518746187471874818749187501875118752187531875418755187561875718758187591876018761187621876318764187651876618767187681876918770187711877218773187741877518776187771877818779187801878118782187831878418785187861878718788187891879018791187921879318794187951879618797187981879918800188011880218803188041880518806188071880818809188101881118812188131881418815188161881718818188191882018821188221882318824188251882618827188281882918830188311883218833188341883518836188371883818839188401884118842188431884418845188461884718848188491885018851188521885318854188551885618857188581885918860188611886218863188641886518866188671886818869188701887118872188731887418875188761887718878188791888018881188821888318884188851888618887188881888918890188911889218893188941889518896188971889818899189001890118902189031890418905189061890718908189091891018911189121891318914189151891618917189181891918920189211892218923189241892518926189271892818929189301893118932189331893418935189361893718938189391894018941189421894318944189451894618947189481894918950189511895218953189541895518956189571895818959189601896118962189631896418965189661896718968189691897018971189721897318974189751897618977189781897918980189811898218983189841898518986189871898818989189901899118992189931899418995189961899718998189991900019001190021900319004190051900619007190081900919010190111901219013190141901519016190171901819019190201902119022190231902419025190261902719028190291903019031190321903319034190351903619037190381903919040190411904219043190441904519046190471904819049190501905119052190531905419055190561905719058190591906019061190621906319064190651906619067190681906919070190711907219073190741907519076190771907819079190801908119082190831908419085190861908719088190891909019091190921909319094190951909619097190981909919100191011910219103191041910519106191071910819109191101911119112191131911419115191161911719118191191912019121191221912319124191251912619127191281912919130191311913219133191341913519136191371913819139191401914119142191431914419145191461914719148191491915019151191521915319154191551915619157191581915919160191611916219163191641916519166191671916819169191701917119172191731917419175191761917719178191791918019181191821918319184191851918619187191881918919190191911919219193191941919519196191971919819199192001920119202192031920419205192061920719208192091921019211192121921319214192151921619217192181921919220192211922219223192241922519226192271922819229192301923119232192331923419235192361923719238192391924019241192421924319244192451924619247192481924919250192511925219253192541925519256192571925819259192601926119262192631926419265192661926719268192691927019271192721927319274192751927619277192781927919280192811928219283192841928519286192871928819289192901929119292192931929419295192961929719298192991930019301193021930319304193051930619307193081930919310193111931219313193141931519316193171931819319193201932119322193231932419325193261932719328193291933019331193321933319334193351933619337193381933919340193411934219343193441934519346193471934819349193501935119352193531935419355193561935719358193591936019361193621936319364193651936619367193681936919370193711937219373193741937519376193771937819379193801938119382193831938419385193861938719388193891939019391193921939319394193951939619397193981939919400194011940219403194041940519406194071940819409194101941119412194131941419415194161941719418194191942019421194221942319424194251942619427194281942919430194311943219433194341943519436194371943819439194401944119442194431944419445194461944719448194491945019451194521945319454194551945619457194581945919460194611946219463194641946519466194671946819469194701947119472194731947419475194761947719478194791948019481194821948319484194851948619487194881948919490194911949219493194941949519496194971949819499195001950119502195031950419505195061950719508195091951019511195121951319514195151951619517195181951919520195211952219523195241952519526195271952819529195301953119532195331953419535195361953719538195391954019541195421954319544195451954619547195481954919550195511955219553195541955519556195571955819559195601956119562195631956419565195661956719568195691957019571195721957319574195751957619577195781957919580195811958219583195841958519586195871958819589195901959119592195931959419595195961959719598195991960019601196021960319604196051960619607196081960919610196111961219613196141961519616196171961819619196201962119622196231962419625196261962719628196291963019631196321963319634196351963619637196381963919640196411964219643196441964519646196471964819649196501965119652196531965419655196561965719658196591966019661196621966319664196651966619667196681966919670196711967219673196741967519676196771967819679196801968119682196831968419685196861968719688196891969019691196921969319694196951969619697196981969919700197011970219703197041970519706197071970819709197101971119712197131971419715197161971719718197191972019721197221972319724197251972619727197281972919730197311973219733197341973519736197371973819739197401974119742197431974419745197461974719748197491975019751197521975319754197551975619757197581975919760197611976219763197641976519766197671976819769197701977119772197731977419775197761977719778197791978019781197821978319784197851978619787197881978919790197911979219793197941979519796197971979819799198001980119802198031980419805198061980719808198091981019811198121981319814198151981619817198181981919820198211982219823198241982519826198271982819829198301983119832198331983419835198361983719838198391984019841198421984319844198451984619847198481984919850198511985219853198541985519856198571985819859198601986119862198631986419865198661986719868198691987019871198721987319874198751987619877198781987919880198811988219883198841988519886198871988819889198901989119892198931989419895198961989719898198991990019901199021990319904199051990619907199081990919910199111991219913199141991519916199171991819919199201992119922199231992419925199261992719928199291993019931199321993319934199351993619937199381993919940199411994219943199441994519946199471994819949199501995119952199531995419955199561995719958199591996019961199621996319964199651996619967199681996919970199711997219973199741997519976199771997819979199801998119982199831998419985199861998719988199891999019991199921999319994199951999619997199981999920000200012000220003200042000520006200072000820009200102001120012200132001420015200162001720018200192002020021200222002320024200252002620027200282002920030200312003220033200342003520036200372003820039200402004120042200432004420045200462004720048200492005020051200522005320054200552005620057200582005920060200612006220063200642006520066200672006820069200702007120072200732007420075200762007720078200792008020081200822008320084200852008620087200882008920090200912009220093200942009520096200972009820099201002010120102201032010420105201062010720108201092011020111201122011320114201152011620117201182011920120201212012220123201242012520126201272012820129201302013120132201332013420135201362013720138201392014020141201422014320144201452014620147201482014920150201512015220153201542015520156201572015820159201602016120162201632016420165201662016720168201692017020171201722017320174201752017620177201782017920180201812018220183201842018520186201872018820189201902019120192201932019420195201962019720198201992020020201202022020320204202052020620207202082020920210202112021220213202142021520216202172021820219202202022120222202232022420225202262022720228202292023020231202322023320234202352023620237202382023920240202412024220243202442024520246202472024820249202502025120252202532025420255202562025720258202592026020261202622026320264202652026620267202682026920270202712027220273202742027520276202772027820279202802028120282202832028420285202862028720288202892029020291202922029320294202952029620297202982029920300203012030220303203042030520306203072030820309203102031120312203132031420315203162031720318203192032020321203222032320324203252032620327203282032920330203312033220333203342033520336203372033820339203402034120342203432034420345203462034720348203492035020351203522035320354203552035620357203582035920360203612036220363203642036520366203672036820369203702037120372203732037420375203762037720378203792038020381203822038320384203852038620387203882038920390203912039220393203942039520396203972039820399204002040120402204032040420405204062040720408204092041020411204122041320414204152041620417204182041920420204212042220423204242042520426204272042820429204302043120432204332043420435204362043720438204392044020441204422044320444204452044620447204482044920450204512045220453204542045520456204572045820459204602046120462204632046420465204662046720468204692047020471204722047320474204752047620477204782047920480204812048220483204842048520486204872048820489204902049120492204932049420495204962049720498204992050020501205022050320504205052050620507205082050920510205112051220513205142051520516205172051820519205202052120522205232052420525205262052720528205292053020531205322053320534205352053620537205382053920540205412054220543205442054520546205472054820549205502055120552205532055420555205562055720558205592056020561205622056320564205652056620567205682056920570205712057220573205742057520576205772057820579205802058120582205832058420585205862058720588205892059020591205922059320594205952059620597205982059920600206012060220603206042060520606206072060820609206102061120612206132061420615206162061720618206192062020621206222062320624206252062620627206282062920630206312063220633206342063520636206372063820639206402064120642206432064420645206462064720648206492065020651206522065320654206552065620657206582065920660206612066220663206642066520666206672066820669206702067120672206732067420675206762067720678206792068020681206822068320684206852068620687206882068920690206912069220693206942069520696206972069820699207002070120702207032070420705207062070720708207092071020711207122071320714207152071620717207182071920720207212072220723207242072520726207272072820729207302073120732207332073420735207362073720738207392074020741207422074320744207452074620747207482074920750207512075220753207542075520756207572075820759207602076120762207632076420765207662076720768207692077020771207722077320774207752077620777207782077920780207812078220783207842078520786207872078820789207902079120792207932079420795207962079720798207992080020801208022080320804208052080620807208082080920810208112081220813208142081520816208172081820819208202082120822208232082420825208262082720828208292083020831208322083320834208352083620837208382083920840208412084220843208442084520846208472084820849208502085120852208532085420855208562085720858208592086020861208622086320864208652086620867208682086920870208712087220873208742087520876208772087820879208802088120882208832088420885208862088720888208892089020891208922089320894208952089620897208982089920900209012090220903209042090520906209072090820909209102091120912209132091420915209162091720918209192092020921209222092320924209252092620927209282092920930209312093220933209342093520936209372093820939209402094120942209432094420945209462094720948209492095020951209522095320954209552095620957209582095920960209612096220963209642096520966209672096820969209702097120972209732097420975209762097720978209792098020981209822098320984209852098620987209882098920990209912099220993209942099520996209972099820999210002100121002210032100421005210062100721008210092101021011210122101321014210152101621017210182101921020210212102221023210242102521026210272102821029210302103121032210332103421035210362103721038210392104021041210422104321044210452104621047210482104921050210512105221053210542105521056210572105821059210602106121062210632106421065210662106721068210692107021071210722107321074210752107621077210782107921080210812108221083210842108521086210872108821089210902109121092210932109421095210962109721098210992110021101211022110321104211052110621107211082110921110211112111221113211142111521116211172111821119211202112121122211232112421125211262112721128211292113021131211322113321134211352113621137211382113921140211412114221143211442114521146211472114821149211502115121152211532115421155211562115721158211592116021161211622116321164211652116621167211682116921170211712117221173211742117521176211772117821179211802118121182211832118421185211862118721188211892119021191211922119321194211952119621197211982119921200212012120221203212042120521206212072120821209212102121121212212132121421215212162121721218212192122021221212222122321224212252122621227212282122921230212312123221233212342123521236212372123821239212402124121242212432124421245212462124721248212492125021251212522125321254212552125621257212582125921260212612126221263212642126521266212672126821269212702127121272212732127421275212762127721278212792128021281212822128321284212852128621287212882128921290212912129221293212942129521296212972129821299213002130121302213032130421305213062130721308213092131021311213122131321314213152131621317213182131921320213212132221323213242132521326213272132821329213302133121332213332133421335213362133721338213392134021341213422134321344213452134621347213482134921350213512135221353213542135521356213572135821359213602136121362213632136421365213662136721368213692137021371213722137321374213752137621377213782137921380213812138221383213842138521386213872138821389213902139121392213932139421395213962139721398213992140021401214022140321404214052140621407214082140921410214112141221413214142141521416214172141821419214202142121422214232142421425214262142721428214292143021431214322143321434214352143621437214382143921440214412144221443214442144521446214472144821449214502145121452214532145421455214562145721458214592146021461214622146321464214652146621467214682146921470214712147221473214742147521476214772147821479214802148121482214832148421485214862148721488214892149021491214922149321494214952149621497214982149921500215012150221503215042150521506215072150821509215102151121512215132151421515215162151721518215192152021521215222152321524215252152621527215282152921530215312153221533215342153521536215372153821539215402154121542215432154421545215462154721548215492155021551215522155321554215552155621557215582155921560215612156221563215642156521566215672156821569215702157121572215732157421575215762157721578215792158021581215822158321584215852158621587215882158921590215912159221593215942159521596215972159821599216002160121602216032160421605216062160721608216092161021611216122161321614216152161621617216182161921620216212162221623216242162521626216272162821629216302163121632216332163421635216362163721638216392164021641216422164321644216452164621647216482164921650216512165221653216542165521656216572165821659216602166121662216632166421665216662166721668216692167021671216722167321674216752167621677216782167921680216812168221683216842168521686216872168821689216902169121692216932169421695216962169721698216992170021701217022170321704217052170621707217082170921710217112171221713217142171521716217172171821719217202172121722217232172421725217262172721728217292173021731217322173321734217352173621737217382173921740217412174221743217442174521746217472174821749217502175121752217532175421755217562175721758217592176021761217622176321764217652176621767217682176921770217712177221773217742177521776217772177821779217802178121782217832178421785217862178721788217892179021791217922179321794217952179621797217982179921800218012180221803218042180521806218072180821809218102181121812218132181421815218162181721818218192182021821218222182321824218252182621827218282182921830218312183221833218342183521836218372183821839218402184121842218432184421845218462184721848218492185021851218522185321854218552185621857218582185921860218612186221863218642186521866218672186821869218702187121872218732187421875218762187721878218792188021881218822188321884218852188621887218882188921890218912189221893218942189521896218972189821899219002190121902219032190421905219062190721908219092191021911219122191321914219152191621917219182191921920219212192221923219242192521926219272192821929219302193121932219332193421935219362193721938219392194021941219422194321944219452194621947219482194921950219512195221953219542195521956219572195821959219602196121962219632196421965219662196721968219692197021971219722197321974219752197621977219782197921980219812198221983219842198521986219872198821989219902199121992219932199421995219962199721998219992200022001220022200322004220052200622007220082200922010220112201222013220142201522016220172201822019220202202122022220232202422025220262202722028220292203022031220322203322034220352203622037220382203922040220412204222043220442204522046220472204822049220502205122052220532205422055220562205722058220592206022061220622206322064220652206622067220682206922070220712207222073220742207522076220772207822079220802208122082220832208422085220862208722088220892209022091220922209322094220952209622097220982209922100221012210222103221042210522106221072210822109221102211122112221132211422115221162211722118221192212022121221222212322124221252212622127221282212922130221312213222133221342213522136221372213822139221402214122142221432214422145221462214722148221492215022151221522215322154221552215622157221582215922160221612216222163221642216522166221672216822169221702217122172221732217422175221762217722178221792218022181221822218322184221852218622187221882218922190221912219222193221942219522196221972219822199222002220122202222032220422205222062220722208222092221022211222122221322214222152221622217222182221922220222212222222223222242222522226222272222822229222302223122232222332223422235222362223722238222392224022241222422224322244222452224622247222482224922250222512225222253222542225522256222572225822259222602226122262222632226422265222662226722268222692227022271222722227322274222752227622277222782227922280222812228222283222842228522286222872228822289222902229122292222932229422295222962229722298222992230022301223022230322304223052230622307223082230922310223112231222313223142231522316223172231822319223202232122322223232232422325223262232722328223292233022331223322233322334223352233622337223382233922340223412234222343223442234522346223472234822349223502235122352223532235422355223562235722358223592236022361223622236322364223652236622367223682236922370223712237222373223742237522376223772237822379223802238122382223832238422385223862238722388223892239022391223922239322394223952239622397223982239922400224012240222403224042240522406224072240822409224102241122412224132241422415224162241722418224192242022421224222242322424224252242622427224282242922430224312243222433224342243522436224372243822439224402244122442224432244422445224462244722448224492245022451224522245322454224552245622457224582245922460224612246222463224642246522466224672246822469224702247122472224732247422475224762247722478224792248022481224822248322484224852248622487224882248922490224912249222493224942249522496224972249822499225002250122502225032250422505225062250722508225092251022511225122251322514225152251622517225182251922520225212252222523225242252522526225272252822529225302253122532225332253422535225362253722538225392254022541225422254322544225452254622547225482254922550225512255222553225542255522556225572255822559225602256122562225632256422565225662256722568225692257022571225722257322574225752257622577225782257922580225812258222583225842258522586225872258822589225902259122592225932259422595225962259722598225992260022601226022260322604226052260622607226082260922610226112261222613226142261522616226172261822619226202262122622226232262422625226262262722628226292263022631226322263322634226352263622637226382263922640226412264222643226442264522646226472264822649226502265122652226532265422655226562265722658226592266022661226622266322664226652266622667226682266922670226712267222673226742267522676226772267822679226802268122682226832268422685226862268722688226892269022691226922269322694226952269622697226982269922700227012270222703227042270522706227072270822709227102271122712227132271422715227162271722718227192272022721227222272322724227252272622727227282272922730227312273222733227342273522736227372273822739227402274122742227432274422745227462274722748227492275022751227522275322754227552275622757227582275922760227612276222763227642276522766227672276822769227702277122772227732277422775227762277722778227792278022781227822278322784227852278622787227882278922790227912279222793227942279522796227972279822799228002280122802228032280422805228062280722808228092281022811228122281322814228152281622817228182281922820228212282222823228242282522826228272282822829228302283122832228332283422835228362283722838228392284022841228422284322844228452284622847228482284922850228512285222853228542285522856228572285822859228602286122862228632286422865228662286722868228692287022871228722287322874228752287622877228782287922880228812288222883228842288522886228872288822889228902289122892228932289422895228962289722898228992290022901229022290322904229052290622907229082290922910229112291222913229142291522916229172291822919229202292122922229232292422925229262292722928229292293022931229322293322934229352293622937229382293922940229412294222943229442294522946229472294822949229502295122952229532295422955229562295722958229592296022961229622296322964229652296622967229682296922970229712297222973229742297522976229772297822979229802298122982229832298422985229862298722988229892299022991229922299322994229952299622997229982299923000230012300223003230042300523006230072300823009230102301123012230132301423015230162301723018230192302023021230222302323024230252302623027230282302923030230312303223033230342303523036230372303823039230402304123042230432304423045230462304723048230492305023051230522305323054230552305623057230582305923060230612306223063230642306523066230672306823069230702307123072230732307423075230762307723078230792308023081230822308323084230852308623087230882308923090230912309223093230942309523096230972309823099231002310123102231032310423105231062310723108231092311023111231122311323114231152311623117231182311923120231212312223123231242312523126231272312823129231302313123132231332313423135231362313723138231392314023141231422314323144231452314623147231482314923150231512315223153231542315523156231572315823159231602316123162231632316423165231662316723168231692317023171231722317323174231752317623177231782317923180231812318223183231842318523186231872318823189231902319123192231932319423195231962319723198231992320023201232022320323204232052320623207232082320923210232112321223213232142321523216232172321823219232202322123222232232322423225232262322723228232292323023231232322323323234232352323623237232382323923240232412324223243232442324523246232472324823249232502325123252232532325423255232562325723258232592326023261232622326323264232652326623267232682326923270232712327223273232742327523276232772327823279232802328123282232832328423285232862328723288232892329023291232922329323294232952329623297232982329923300233012330223303233042330523306233072330823309233102331123312233132331423315233162331723318233192332023321233222332323324233252332623327233282332923330233312333223333233342333523336233372333823339233402334123342233432334423345233462334723348233492335023351233522335323354233552335623357233582335923360233612336223363233642336523366233672336823369233702337123372233732337423375233762337723378233792338023381233822338323384233852338623387233882338923390233912339223393233942339523396233972339823399234002340123402234032340423405234062340723408234092341023411234122341323414234152341623417234182341923420234212342223423234242342523426234272342823429234302343123432234332343423435234362343723438234392344023441234422344323444234452344623447234482344923450234512345223453234542345523456234572345823459234602346123462234632346423465234662346723468234692347023471234722347323474234752347623477234782347923480234812348223483234842348523486234872348823489234902349123492234932349423495234962349723498234992350023501235022350323504235052350623507235082350923510235112351223513235142351523516235172351823519235202352123522235232352423525235262352723528235292353023531235322353323534235352353623537235382353923540235412354223543235442354523546235472354823549235502355123552235532355423555235562355723558235592356023561235622356323564235652356623567235682356923570235712357223573235742357523576235772357823579235802358123582235832358423585235862358723588235892359023591235922359323594235952359623597235982359923600236012360223603236042360523606236072360823609236102361123612236132361423615236162361723618236192362023621236222362323624236252362623627236282362923630236312363223633236342363523636236372363823639236402364123642236432364423645236462364723648236492365023651236522365323654236552365623657236582365923660236612366223663236642366523666236672366823669236702367123672236732367423675236762367723678236792368023681236822368323684236852368623687236882368923690236912369223693236942369523696236972369823699237002370123702237032370423705237062370723708237092371023711237122371323714237152371623717237182371923720237212372223723237242372523726237272372823729237302373123732237332373423735237362373723738237392374023741237422374323744237452374623747237482374923750237512375223753237542375523756237572375823759237602376123762237632376423765237662376723768237692377023771237722377323774237752377623777237782377923780237812378223783237842378523786237872378823789237902379123792237932379423795237962379723798237992380023801238022380323804238052380623807238082380923810238112381223813238142381523816238172381823819238202382123822238232382423825238262382723828238292383023831238322383323834238352383623837238382383923840238412384223843238442384523846238472384823849238502385123852238532385423855238562385723858238592386023861238622386323864238652386623867238682386923870238712387223873238742387523876238772387823879238802388123882238832388423885238862388723888238892389023891238922389323894238952389623897238982389923900239012390223903239042390523906239072390823909239102391123912239132391423915239162391723918239192392023921239222392323924239252392623927239282392923930239312393223933239342393523936239372393823939239402394123942239432394423945239462394723948239492395023951239522395323954239552395623957239582395923960239612396223963239642396523966239672396823969239702397123972239732397423975239762397723978239792398023981239822398323984239852398623987239882398923990239912399223993239942399523996239972399823999240002400124002240032400424005240062400724008240092401024011240122401324014240152401624017240182401924020240212402224023240242402524026240272402824029240302403124032240332403424035240362403724038240392404024041240422404324044240452404624047240482404924050240512405224053240542405524056240572405824059240602406124062240632406424065240662406724068240692407024071240722407324074240752407624077240782407924080240812408224083240842408524086240872408824089240902409124092240932409424095240962409724098240992410024101241022410324104241052410624107241082410924110241112411224113241142411524116241172411824119241202412124122241232412424125241262412724128241292413024131241322413324134241352413624137241382413924140241412414224143241442414524146241472414824149241502415124152241532415424155241562415724158241592416024161241622416324164241652416624167241682416924170241712417224173241742417524176241772417824179241802418124182241832418424185241862418724188241892419024191241922419324194241952419624197241982419924200242012420224203242042420524206242072420824209242102421124212242132421424215242162421724218242192422024221242222422324224242252422624227242282422924230242312423224233242342423524236242372423824239242402424124242242432424424245242462424724248242492425024251242522425324254242552425624257242582425924260242612426224263242642426524266242672426824269242702427124272242732427424275242762427724278242792428024281242822428324284242852428624287242882428924290242912429224293242942429524296242972429824299243002430124302243032430424305243062430724308243092431024311243122431324314243152431624317243182431924320243212432224323243242432524326243272432824329243302433124332243332433424335243362433724338243392434024341243422434324344243452434624347243482434924350243512435224353243542435524356243572435824359243602436124362243632436424365243662436724368243692437024371243722437324374243752437624377243782437924380243812438224383243842438524386243872438824389243902439124392243932439424395243962439724398243992440024401244022440324404244052440624407244082440924410244112441224413244142441524416244172441824419244202442124422244232442424425244262442724428244292443024431244322443324434244352443624437244382443924440244412444224443244442444524446244472444824449244502445124452244532445424455244562445724458244592446024461244622446324464244652446624467244682446924470244712447224473244742447524476244772447824479244802448124482244832448424485244862448724488244892449024491244922449324494244952449624497244982449924500245012450224503245042450524506245072450824509245102451124512245132451424515245162451724518245192452024521245222452324524245252452624527245282452924530245312453224533245342453524536245372453824539245402454124542245432454424545245462454724548245492455024551245522455324554245552455624557245582455924560245612456224563245642456524566245672456824569245702457124572245732457424575245762457724578245792458024581245822458324584245852458624587245882458924590245912459224593245942459524596245972459824599246002460124602246032460424605246062460724608246092461024611246122461324614246152461624617246182461924620246212462224623246242462524626246272462824629246302463124632246332463424635246362463724638246392464024641246422464324644246452464624647246482464924650246512465224653246542465524656246572465824659246602466124662246632466424665246662466724668246692467024671246722467324674246752467624677246782467924680246812468224683246842468524686246872468824689246902469124692246932469424695246962469724698246992470024701247022470324704247052470624707247082470924710247112471224713247142471524716247172471824719247202472124722247232472424725247262472724728247292473024731247322473324734247352473624737247382473924740247412474224743247442474524746247472474824749247502475124752247532475424755247562475724758247592476024761247622476324764247652476624767247682476924770247712477224773247742477524776247772477824779247802478124782247832478424785247862478724788247892479024791247922479324794247952479624797247982479924800248012480224803248042480524806248072480824809248102481124812248132481424815248162481724818248192482024821248222482324824248252482624827248282482924830248312483224833248342483524836248372483824839248402484124842248432484424845248462484724848248492485024851248522485324854248552485624857248582485924860248612486224863248642486524866248672486824869248702487124872248732487424875248762487724878248792488024881248822488324884248852488624887248882488924890248912489224893248942489524896248972489824899249002490124902249032490424905249062490724908249092491024911249122491324914249152491624917249182491924920249212492224923249242492524926249272492824929249302493124932249332493424935249362493724938249392494024941249422494324944249452494624947249482494924950249512495224953249542495524956249572495824959249602496124962249632496424965249662496724968249692497024971249722497324974249752497624977249782497924980249812498224983249842498524986249872498824989249902499124992249932499424995249962499724998249992500025001250022500325004250052500625007250082500925010250112501225013250142501525016250172501825019250202502125022250232502425025250262502725028250292503025031250322503325034250352503625037250382503925040250412504225043250442504525046250472504825049250502505125052250532505425055250562505725058250592506025061250622506325064250652506625067250682506925070250712507225073250742507525076250772507825079250802508125082250832508425085250862508725088250892509025091250922509325094250952509625097250982509925100251012510225103251042510525106251072510825109251102511125112251132511425115251162511725118251192512025121251222512325124251252512625127251282512925130251312513225133251342513525136251372513825139251402514125142251432514425145251462514725148251492515025151251522515325154251552515625157251582515925160251612516225163251642516525166251672516825169251702517125172251732517425175251762517725178251792518025181251822518325184251852518625187251882518925190251912519225193251942519525196251972519825199252002520125202252032520425205252062520725208252092521025211252122521325214252152521625217252182521925220252212522225223252242522525226252272522825229252302523125232252332523425235252362523725238252392524025241252422524325244252452524625247252482524925250252512525225253252542525525256252572525825259252602526125262252632526425265252662526725268252692527025271252722527325274252752527625277252782527925280252812528225283252842528525286252872528825289252902529125292252932529425295252962529725298252992530025301253022530325304253052530625307253082530925310253112531225313253142531525316253172531825319253202532125322253232532425325253262532725328253292533025331253322533325334253352533625337253382533925340253412534225343253442534525346253472534825349253502535125352253532535425355253562535725358253592536025361253622536325364253652536625367253682536925370253712537225373253742537525376253772537825379253802538125382253832538425385253862538725388253892539025391253922539325394253952539625397253982539925400254012540225403254042540525406254072540825409254102541125412254132541425415254162541725418254192542025421254222542325424254252542625427254282542925430254312543225433254342543525436254372543825439254402544125442254432544425445254462544725448254492545025451254522545325454254552545625457254582545925460254612546225463254642546525466254672546825469254702547125472254732547425475254762547725478254792548025481254822548325484254852548625487254882548925490254912549225493254942549525496254972549825499255002550125502255032550425505255062550725508255092551025511255122551325514255152551625517255182551925520255212552225523255242552525526255272552825529255302553125532255332553425535255362553725538255392554025541255422554325544255452554625547255482554925550255512555225553255542555525556255572555825559255602556125562255632556425565255662556725568255692557025571255722557325574255752557625577255782557925580255812558225583255842558525586255872558825589255902559125592255932559425595255962559725598255992560025601256022560325604256052560625607256082560925610256112561225613256142561525616256172561825619256202562125622256232562425625256262562725628256292563025631256322563325634256352563625637256382563925640256412564225643256442564525646256472564825649256502565125652256532565425655256562565725658256592566025661256622566325664256652566625667256682566925670256712567225673256742567525676256772567825679256802568125682256832568425685256862568725688256892569025691256922569325694256952569625697256982569925700257012570225703257042570525706257072570825709257102571125712257132571425715257162571725718257192572025721257222572325724257252572625727257282572925730257312573225733257342573525736257372573825739257402574125742257432574425745257462574725748257492575025751257522575325754257552575625757257582575925760257612576225763257642576525766257672576825769257702577125772257732577425775257762577725778257792578025781257822578325784257852578625787257882578925790257912579225793257942579525796257972579825799258002580125802258032580425805258062580725808258092581025811258122581325814258152581625817258182581925820258212582225823258242582525826258272582825829258302583125832258332583425835258362583725838258392584025841258422584325844258452584625847258482584925850258512585225853258542585525856258572585825859258602586125862258632586425865258662586725868258692587025871258722587325874258752587625877258782587925880258812588225883258842588525886258872588825889258902589125892258932589425895258962589725898258992590025901259022590325904259052590625907259082590925910259112591225913259142591525916259172591825919259202592125922259232592425925259262592725928259292593025931259322593325934259352593625937259382593925940259412594225943259442594525946259472594825949259502595125952259532595425955259562595725958259592596025961259622596325964259652596625967259682596925970259712597225973259742597525976259772597825979259802598125982259832598425985259862598725988259892599025991259922599325994259952599625997259982599926000260012600226003260042600526006260072600826009260102601126012260132601426015260162601726018260192602026021260222602326024260252602626027260282602926030260312603226033260342603526036260372603826039260402604126042260432604426045260462604726048260492605026051260522605326054260552605626057260582605926060260612606226063260642606526066260672606826069260702607126072260732607426075260762607726078260792608026081260822608326084260852608626087260882608926090260912609226093260942609526096260972609826099261002610126102261032610426105261062610726108261092611026111261122611326114261152611626117261182611926120261212612226123261242612526126261272612826129261302613126132261332613426135261362613726138261392614026141261422614326144261452614626147261482614926150261512615226153261542615526156261572615826159261602616126162261632616426165261662616726168261692617026171261722617326174261752617626177261782617926180261812618226183261842618526186261872618826189261902619126192261932619426195261962619726198261992620026201262022620326204262052620626207262082620926210262112621226213262142621526216262172621826219262202622126222262232622426225262262622726228262292623026231262322623326234262352623626237262382623926240262412624226243262442624526246262472624826249262502625126252262532625426255262562625726258262592626026261262622626326264262652626626267262682626926270262712627226273262742627526276262772627826279262802628126282262832628426285262862628726288262892629026291262922629326294262952629626297262982629926300263012630226303263042630526306263072630826309263102631126312263132631426315263162631726318263192632026321263222632326324263252632626327263282632926330263312633226333263342633526336263372633826339263402634126342263432634426345263462634726348263492635026351263522635326354263552635626357263582635926360263612636226363263642636526366263672636826369263702637126372263732637426375263762637726378263792638026381263822638326384263852638626387263882638926390263912639226393263942639526396263972639826399264002640126402264032640426405264062640726408264092641026411264122641326414264152641626417264182641926420264212642226423264242642526426264272642826429264302643126432264332643426435264362643726438264392644026441264422644326444264452644626447264482644926450264512645226453264542645526456264572645826459264602646126462264632646426465264662646726468264692647026471264722647326474264752647626477264782647926480264812648226483264842648526486264872648826489264902649126492264932649426495264962649726498264992650026501265022650326504265052650626507265082650926510265112651226513265142651526516265172651826519265202652126522265232652426525265262652726528265292653026531265322653326534265352653626537265382653926540265412654226543265442654526546265472654826549265502655126552265532655426555265562655726558265592656026561265622656326564265652656626567265682656926570265712657226573265742657526576265772657826579265802658126582265832658426585265862658726588265892659026591265922659326594265952659626597265982659926600266012660226603266042660526606266072660826609266102661126612266132661426615266162661726618266192662026621266222662326624266252662626627266282662926630266312663226633266342663526636266372663826639266402664126642266432664426645266462664726648266492665026651266522665326654266552665626657266582665926660266612666226663266642666526666266672666826669266702667126672266732667426675266762667726678266792668026681266822668326684266852668626687266882668926690266912669226693266942669526696266972669826699267002670126702267032670426705267062670726708267092671026711267122671326714267152671626717267182671926720267212672226723267242672526726267272672826729267302673126732267332673426735267362673726738267392674026741267422674326744267452674626747267482674926750267512675226753267542675526756267572675826759267602676126762267632676426765267662676726768267692677026771267722677326774267752677626777267782677926780267812678226783267842678526786267872678826789267902679126792267932679426795267962679726798267992680026801268022680326804268052680626807268082680926810268112681226813268142681526816268172681826819268202682126822268232682426825268262682726828268292683026831268322683326834268352683626837268382683926840268412684226843268442684526846268472684826849268502685126852268532685426855268562685726858268592686026861268622686326864268652686626867268682686926870268712687226873268742687526876268772687826879268802688126882268832688426885268862688726888268892689026891268922689326894268952689626897268982689926900269012690226903269042690526906269072690826909269102691126912269132691426915269162691726918269192692026921269222692326924269252692626927269282692926930269312693226933269342693526936269372693826939269402694126942269432694426945269462694726948269492695026951269522695326954269552695626957269582695926960269612696226963269642696526966269672696826969269702697126972269732697426975269762697726978269792698026981269822698326984269852698626987269882698926990269912699226993269942699526996269972699826999270002700127002270032700427005270062700727008270092701027011270122701327014270152701627017270182701927020270212702227023270242702527026270272702827029270302703127032270332703427035270362703727038270392704027041270422704327044270452704627047270482704927050270512705227053270542705527056270572705827059270602706127062270632706427065270662706727068270692707027071270722707327074270752707627077270782707927080270812708227083270842708527086270872708827089270902709127092270932709427095270962709727098270992710027101271022710327104271052710627107271082710927110271112711227113271142711527116271172711827119271202712127122271232712427125271262712727128271292713027131271322713327134271352713627137271382713927140271412714227143271442714527146271472714827149271502715127152271532715427155271562715727158271592716027161271622716327164271652716627167271682716927170271712717227173271742717527176271772717827179271802718127182271832718427185271862718727188271892719027191271922719327194271952719627197271982719927200272012720227203272042720527206272072720827209272102721127212272132721427215272162721727218272192722027221272222722327224272252722627227272282722927230272312723227233272342723527236272372723827239272402724127242272432724427245272462724727248272492725027251272522725327254272552725627257272582725927260272612726227263272642726527266272672726827269272702727127272272732727427275272762727727278272792728027281272822728327284272852728627287272882728927290272912729227293272942729527296272972729827299273002730127302273032730427305273062730727308273092731027311273122731327314273152731627317273182731927320273212732227323273242732527326273272732827329273302733127332273332733427335273362733727338273392734027341273422734327344273452734627347273482734927350273512735227353273542735527356273572735827359273602736127362273632736427365273662736727368273692737027371273722737327374273752737627377273782737927380273812738227383273842738527386273872738827389273902739127392273932739427395273962739727398273992740027401274022740327404274052740627407274082740927410274112741227413274142741527416274172741827419274202742127422274232742427425274262742727428274292743027431274322743327434274352743627437274382743927440274412744227443274442744527446274472744827449274502745127452274532745427455274562745727458274592746027461274622746327464274652746627467274682746927470274712747227473274742747527476274772747827479274802748127482274832748427485274862748727488274892749027491274922749327494274952749627497274982749927500275012750227503275042750527506275072750827509275102751127512275132751427515275162751727518275192752027521275222752327524275252752627527275282752927530275312753227533275342753527536275372753827539275402754127542275432754427545275462754727548275492755027551275522755327554275552755627557275582755927560275612756227563275642756527566275672756827569275702757127572275732757427575275762757727578275792758027581275822758327584275852758627587275882758927590275912759227593275942759527596275972759827599276002760127602276032760427605276062760727608276092761027611276122761327614276152761627617276182761927620276212762227623276242762527626276272762827629276302763127632276332763427635276362763727638276392764027641276422764327644276452764627647276482764927650276512765227653276542765527656276572765827659276602766127662276632766427665276662766727668276692767027671276722767327674276752767627677276782767927680276812768227683276842768527686276872768827689276902769127692276932769427695276962769727698276992770027701277022770327704277052770627707277082770927710277112771227713277142771527716277172771827719277202772127722277232772427725277262772727728277292773027731277322773327734277352773627737277382773927740277412774227743277442774527746277472774827749277502775127752277532775427755277562775727758277592776027761277622776327764277652776627767277682776927770277712777227773277742777527776277772777827779277802778127782277832778427785277862778727788277892779027791277922779327794277952779627797277982779927800278012780227803278042780527806278072780827809278102781127812278132781427815278162781727818278192782027821278222782327824278252782627827278282782927830278312783227833278342783527836278372783827839278402784127842278432784427845278462784727848278492785027851278522785327854278552785627857278582785927860278612786227863278642786527866278672786827869278702787127872278732787427875278762787727878278792788027881278822788327884278852788627887278882788927890278912789227893278942789527896278972789827899279002790127902279032790427905279062790727908279092791027911279122791327914279152791627917279182791927920279212792227923279242792527926279272792827929279302793127932279332793427935279362793727938279392794027941279422794327944279452794627947279482794927950279512795227953279542795527956279572795827959279602796127962279632796427965279662796727968279692797027971279722797327974279752797627977279782797927980279812798227983279842798527986279872798827989279902799127992279932799427995279962799727998279992800028001280022800328004280052800628007280082800928010280112801228013280142801528016280172801828019280202802128022280232802428025280262802728028280292803028031280322803328034280352803628037280382803928040280412804228043280442804528046280472804828049280502805128052280532805428055280562805728058280592806028061280622806328064280652806628067280682806928070280712807228073280742807528076280772807828079280802808128082280832808428085280862808728088280892809028091280922809328094280952809628097280982809928100281012810228103281042810528106281072810828109281102811128112281132811428115281162811728118281192812028121281222812328124281252812628127281282812928130281312813228133281342813528136281372813828139281402814128142281432814428145281462814728148281492815028151281522815328154281552815628157281582815928160281612816228163281642816528166281672816828169281702817128172281732817428175281762817728178281792818028181281822818328184281852818628187281882818928190281912819228193281942819528196281972819828199282002820128202282032820428205282062820728208282092821028211282122821328214282152821628217282182821928220282212822228223282242822528226282272822828229282302823128232282332823428235282362823728238282392824028241282422824328244282452824628247282482824928250282512825228253282542825528256282572825828259282602826128262282632826428265282662826728268282692827028271282722827328274282752827628277282782827928280282812828228283282842828528286282872828828289282902829128292282932829428295282962829728298282992830028301283022830328304283052830628307283082830928310283112831228313283142831528316283172831828319283202832128322283232832428325283262832728328283292833028331283322833328334283352833628337283382833928340283412834228343283442834528346283472834828349283502835128352283532835428355283562835728358283592836028361283622836328364283652836628367283682836928370283712837228373283742837528376283772837828379283802838128382283832838428385283862838728388283892839028391283922839328394283952839628397283982839928400284012840228403284042840528406284072840828409284102841128412284132841428415284162841728418284192842028421284222842328424284252842628427284282842928430284312843228433284342843528436284372843828439284402844128442284432844428445284462844728448284492845028451284522845328454284552845628457284582845928460284612846228463284642846528466284672846828469284702847128472284732847428475284762847728478284792848028481284822848328484284852848628487284882848928490284912849228493284942849528496284972849828499285002850128502285032850428505285062850728508285092851028511285122851328514285152851628517285182851928520285212852228523285242852528526285272852828529285302853128532285332853428535285362853728538285392854028541285422854328544285452854628547285482854928550285512855228553285542855528556285572855828559285602856128562285632856428565285662856728568285692857028571285722857328574285752857628577285782857928580285812858228583285842858528586285872858828589285902859128592285932859428595285962859728598285992860028601286022860328604286052860628607286082860928610286112861228613286142861528616286172861828619286202862128622286232862428625286262862728628286292863028631286322863328634286352863628637286382863928640286412864228643286442864528646286472864828649286502865128652286532865428655286562865728658286592866028661286622866328664286652866628667286682866928670286712867228673286742867528676286772867828679286802868128682286832868428685286862868728688286892869028691286922869328694286952869628697286982869928700287012870228703287042870528706287072870828709287102871128712287132871428715287162871728718287192872028721287222872328724287252872628727287282872928730287312873228733287342873528736287372873828739287402874128742287432874428745287462874728748287492875028751287522875328754287552875628757287582875928760287612876228763287642876528766287672876828769287702877128772287732877428775287762877728778287792878028781287822878328784287852878628787287882878928790287912879228793287942879528796287972879828799288002880128802288032880428805288062880728808288092881028811288122881328814288152881628817288182881928820288212882228823288242882528826288272882828829288302883128832288332883428835288362883728838288392884028841288422884328844288452884628847288482884928850288512885228853288542885528856288572885828859288602886128862288632886428865288662886728868288692887028871288722887328874288752887628877288782887928880288812888228883288842888528886288872888828889288902889128892288932889428895288962889728898288992890028901289022890328904289052890628907289082890928910289112891228913289142891528916289172891828919289202892128922289232892428925289262892728928289292893028931289322893328934289352893628937289382893928940289412894228943289442894528946289472894828949289502895128952289532895428955289562895728958289592896028961289622896328964289652896628967289682896928970289712897228973289742897528976289772897828979289802898128982289832898428985289862898728988289892899028991289922899328994289952899628997289982899929000290012900229003290042900529006290072900829009290102901129012290132901429015290162901729018290192902029021290222902329024290252902629027290282902929030290312903229033290342903529036290372903829039290402904129042290432904429045290462904729048290492905029051290522905329054290552905629057290582905929060290612906229063290642906529066290672906829069290702907129072290732907429075290762907729078290792908029081290822908329084290852908629087290882908929090290912909229093290942909529096290972909829099291002910129102291032910429105291062910729108291092911029111291122911329114291152911629117291182911929120291212912229123291242912529126291272912829129291302913129132291332913429135291362913729138291392914029141291422914329144291452914629147291482914929150291512915229153291542915529156291572915829159291602916129162291632916429165291662916729168291692917029171291722917329174291752917629177291782917929180291812918229183291842918529186291872918829189291902919129192291932919429195291962919729198291992920029201292022920329204292052920629207292082920929210292112921229213292142921529216292172921829219292202922129222292232922429225292262922729228292292923029231292322923329234292352923629237292382923929240292412924229243292442924529246292472924829249292502925129252292532925429255292562925729258292592926029261292622926329264292652926629267292682926929270292712927229273292742927529276292772927829279292802928129282292832928429285292862928729288292892929029291292922929329294292952929629297292982929929300293012930229303293042930529306293072930829309293102931129312293132931429315293162931729318293192932029321293222932329324293252932629327293282932929330293312933229333293342933529336293372933829339293402934129342293432934429345293462934729348293492935029351293522935329354293552935629357293582935929360293612936229363293642936529366293672936829369293702937129372293732937429375293762937729378293792938029381293822938329384293852938629387293882938929390293912939229393293942939529396293972939829399294002940129402
  1. /**
  2. * TinyMCE version 6.1.0 (2022-06-29)
  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$f = (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$f(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$e = (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$e(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$e(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$e(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$f(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$d = (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$d(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$d(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$d(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$d,
  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$a = 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$e(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$b = (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$a = (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$b(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$9 = (element, clazz) => remove$a(element, 'class', clazz);
  1170. const toggle$2 = (element, clazz) => {
  1171. if (contains$2(get$8(element), clazz)) {
  1172. return remove$9(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$b(element, 'class');
  1188. }
  1189. };
  1190. const remove$8 = (element, clazz) => {
  1191. if (supports(element)) {
  1192. const classList = element.dom.classList;
  1193. classList.remove(clazz);
  1194. } else {
  1195. remove$9(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$a(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$e(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$7 = (element, property) => {
  1413. const dom = element.dom;
  1414. internalRemove(dom, property);
  1415. if (is$2(getOpt(element, 'style').map(trim$3), '')) {
  1416. remove$b(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$f(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$f(elements, x => {
  1460. append$1(parent, x);
  1461. });
  1462. };
  1463. const empty = element => {
  1464. element.dom.textContent = '';
  1465. each$f(children(element), rogue => {
  1466. remove$6(rogue);
  1467. });
  1468. };
  1469. const remove$6 = 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$6(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$9 = 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$6 = matchNodeNames(['br']);
  1698. const isImg = matchNodeNames(['img']);
  1699. const isContentEditableTrue$5 = hasContentEditableState('true');
  1700. const isContentEditableFalse$b = 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$6);
  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$f(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$f(urls, url => {
  1950. unload(url);
  1951. });
  1952. };
  1953. return {
  1954. load,
  1955. loadAll,
  1956. unload,
  1957. unloadAll,
  1958. _setReferrerPolicy
  1959. };
  1960. };
  1961. const create$d = () => {
  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$d();
  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, 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, shallow) {
  2020. let sibling, parent, child;
  2021. if (node) {
  2022. sibling = node.previousSibling;
  2023. if (this.rootNode && sibling === this.rootNode) {
  2024. return;
  2025. }
  2026. if (sibling) {
  2027. if (!shallow) {
  2028. for (child = sibling.lastChild; child; child = child.lastChild) {
  2029. if (!child.lastChild) {
  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 wrapBlockElements = ['pre'].concat(headings);
  2153. const lazyLookup = items => {
  2154. let lookup;
  2155. return node => {
  2156. lookup = lookup ? lookup : mapToObject(items, always);
  2157. return has$2(lookup, name(node));
  2158. };
  2159. };
  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$5 = 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 isWrapBlockElement = lazyLookup(wrapBlockElements);
  2171. const isWrapElement = node => isWrapBlockElement(node) || isInline$1(node);
  2172. const ancestor$1 = (scope, selector, isRoot) => ancestor$2(scope, selector, isRoot).isSome();
  2173. const zeroWidth = '\uFEFF';
  2174. const nbsp = '\xA0';
  2175. const isZwsp$1 = char => char === zeroWidth;
  2176. const removeZwsp = s => s.replace(/\uFEFF/g, '');
  2177. const ZWSP$1 = zeroWidth;
  2178. const isZwsp = isZwsp$1;
  2179. const trim$1 = removeZwsp;
  2180. const isElement$5 = isElement$6;
  2181. const isText$8 = isText$9;
  2182. const isCaretContainerBlock$1 = node => {
  2183. if (isText$8(node)) {
  2184. node = node.parentNode;
  2185. }
  2186. return isElement$5(node) && node.hasAttribute('data-mce-caret');
  2187. };
  2188. const isCaretContainerInline = node => isText$8(node) && isZwsp(node.data);
  2189. const isCaretContainer$2 = node => isCaretContainerBlock$1(node) || isCaretContainerInline(node);
  2190. const hasContent = node => node.firstChild !== node.lastChild || !isBr$6(node.firstChild);
  2191. const insertInline$1 = (node, before) => {
  2192. const doc = node.ownerDocument;
  2193. const textNode = doc.createTextNode(ZWSP$1);
  2194. const parentNode = node.parentNode;
  2195. if (!before) {
  2196. const sibling = node.nextSibling;
  2197. if (isText$8(sibling)) {
  2198. if (isCaretContainer$2(sibling)) {
  2199. return sibling;
  2200. }
  2201. if (startsWithCaretContainer$1(sibling)) {
  2202. sibling.splitText(1);
  2203. return sibling;
  2204. }
  2205. }
  2206. if (node.nextSibling) {
  2207. parentNode.insertBefore(textNode, node.nextSibling);
  2208. } else {
  2209. parentNode.appendChild(textNode);
  2210. }
  2211. } else {
  2212. const sibling = node.previousSibling;
  2213. if (isText$8(sibling)) {
  2214. if (isCaretContainer$2(sibling)) {
  2215. return sibling;
  2216. }
  2217. if (endsWithCaretContainer$1(sibling)) {
  2218. return sibling.splitText(sibling.data.length - 1);
  2219. }
  2220. }
  2221. parentNode.insertBefore(textNode, node);
  2222. }
  2223. return textNode;
  2224. };
  2225. const isBeforeInline = pos => {
  2226. const container = pos.container();
  2227. if (!isText$9(container)) {
  2228. return false;
  2229. }
  2230. return container.data.charAt(pos.offset()) === ZWSP$1 || pos.isAtStart() && isCaretContainerInline(container.previousSibling);
  2231. };
  2232. const isAfterInline = pos => {
  2233. const container = pos.container();
  2234. if (!isText$9(container)) {
  2235. return false;
  2236. }
  2237. return container.data.charAt(pos.offset() - 1) === ZWSP$1 || pos.isAtEnd() && isCaretContainerInline(container.nextSibling);
  2238. };
  2239. const createBogusBr = () => {
  2240. const br = document.createElement('br');
  2241. br.setAttribute('data-mce-bogus', '1');
  2242. return br;
  2243. };
  2244. const insertBlock = (blockName, node, before) => {
  2245. const doc = node.ownerDocument;
  2246. const blockNode = doc.createElement(blockName);
  2247. blockNode.setAttribute('data-mce-caret', before ? 'before' : 'after');
  2248. blockNode.setAttribute('data-mce-bogus', 'all');
  2249. blockNode.appendChild(createBogusBr());
  2250. const parentNode = node.parentNode;
  2251. if (!before) {
  2252. if (node.nextSibling) {
  2253. parentNode.insertBefore(blockNode, node.nextSibling);
  2254. } else {
  2255. parentNode.appendChild(blockNode);
  2256. }
  2257. } else {
  2258. parentNode.insertBefore(blockNode, node);
  2259. }
  2260. return blockNode;
  2261. };
  2262. const startsWithCaretContainer$1 = node => isText$8(node) && node.data[0] === ZWSP$1;
  2263. const endsWithCaretContainer$1 = node => isText$8(node) && node.data[node.data.length - 1] === ZWSP$1;
  2264. const trimBogusBr = elm => {
  2265. const brs = elm.getElementsByTagName('br');
  2266. const lastBr = brs[brs.length - 1];
  2267. if (isBogus$2(lastBr)) {
  2268. lastBr.parentNode.removeChild(lastBr);
  2269. }
  2270. };
  2271. const showCaretContainerBlock = caretContainer => {
  2272. if (caretContainer && caretContainer.hasAttribute('data-mce-caret')) {
  2273. trimBogusBr(caretContainer);
  2274. caretContainer.removeAttribute('data-mce-caret');
  2275. caretContainer.removeAttribute('data-mce-bogus');
  2276. caretContainer.removeAttribute('style');
  2277. caretContainer.removeAttribute('data-mce-style');
  2278. caretContainer.removeAttribute('_moz_abspos');
  2279. return caretContainer;
  2280. }
  2281. return null;
  2282. };
  2283. const isRangeInCaretContainerBlock = range => isCaretContainerBlock$1(range.startContainer);
  2284. const isContentEditableTrue$4 = isContentEditableTrue$5;
  2285. const isContentEditableFalse$a = isContentEditableFalse$b;
  2286. const isBr$4 = isBr$6;
  2287. const isText$7 = isText$9;
  2288. const isInvalidTextElement = matchNodeNames([
  2289. 'script',
  2290. 'style',
  2291. 'textarea'
  2292. ]);
  2293. const isAtomicInline = matchNodeNames([
  2294. 'img',
  2295. 'input',
  2296. 'textarea',
  2297. 'hr',
  2298. 'iframe',
  2299. 'video',
  2300. 'audio',
  2301. 'object',
  2302. 'embed'
  2303. ]);
  2304. const isTable$1 = matchNodeNames(['table']);
  2305. const isCaretContainer$1 = isCaretContainer$2;
  2306. const isCaretCandidate$3 = node => {
  2307. if (isCaretContainer$1(node)) {
  2308. return false;
  2309. }
  2310. if (isText$7(node)) {
  2311. return !isInvalidTextElement(node.parentNode);
  2312. }
  2313. return isAtomicInline(node) || isBr$4(node) || isTable$1(node) || isNonUiContentEditableFalse(node);
  2314. };
  2315. const isUnselectable = node => isElement$6(node) && node.getAttribute('unselectable') === 'true';
  2316. const isNonUiContentEditableFalse = node => isUnselectable(node) === false && isContentEditableFalse$a(node);
  2317. const isInEditable = (node, root) => {
  2318. for (node = node.parentNode; node && node !== root; node = node.parentNode) {
  2319. if (isNonUiContentEditableFalse(node)) {
  2320. return false;
  2321. }
  2322. if (isContentEditableTrue$4(node)) {
  2323. return true;
  2324. }
  2325. }
  2326. return true;
  2327. };
  2328. const isAtomicContentEditableFalse = node => {
  2329. if (!isNonUiContentEditableFalse(node)) {
  2330. return false;
  2331. }
  2332. return foldl(from(node.getElementsByTagName('*')), (result, elm) => {
  2333. return result || isContentEditableTrue$4(elm);
  2334. }, false) !== true;
  2335. };
  2336. const isAtomic$1 = node => isAtomicInline(node) || isAtomicContentEditableFalse(node);
  2337. const isEditableCaretCandidate$1 = (node, root) => isCaretCandidate$3(node) && isInEditable(node, root);
  2338. const whiteSpaceRegExp = /^[ \t\r\n]*$/;
  2339. const isWhitespaceText = text => whiteSpaceRegExp.test(text);
  2340. const isCollapsibleWhitespace$1 = c => ' \f\t\x0B'.indexOf(c) !== -1;
  2341. const isNewLineChar = c => c === '\n' || c === '\r';
  2342. const isNewline = (text, idx) => idx < text.length && idx >= 0 ? isNewLineChar(text[idx]) : false;
  2343. const normalize$4 = (text, tabSpaces = 4, isStartOfContent = true, isEndOfContent = true) => {
  2344. const tabSpace = repeat(' ', tabSpaces);
  2345. const normalizedText = text.replace(/\t/g, tabSpace);
  2346. const result = foldl(normalizedText, (acc, c) => {
  2347. if (isCollapsibleWhitespace$1(c) || c === nbsp) {
  2348. if (acc.pcIsSpace || acc.str === '' && isStartOfContent || acc.str.length === normalizedText.length - 1 && isEndOfContent || isNewline(normalizedText, acc.str.length + 1)) {
  2349. return {
  2350. pcIsSpace: false,
  2351. str: acc.str + nbsp
  2352. };
  2353. } else {
  2354. return {
  2355. pcIsSpace: true,
  2356. str: acc.str + ' '
  2357. };
  2358. }
  2359. } else {
  2360. return {
  2361. pcIsSpace: isNewLineChar(c),
  2362. str: acc.str + c
  2363. };
  2364. }
  2365. }, {
  2366. pcIsSpace: false,
  2367. str: ''
  2368. });
  2369. return result.str;
  2370. };
  2371. const hasWhitespacePreserveParent = (node, rootNode) => {
  2372. const rootElement = SugarElement.fromDom(rootNode);
  2373. const startNode = SugarElement.fromDom(node);
  2374. return ancestor$1(startNode, 'pre,code', curry(eq, rootElement));
  2375. };
  2376. const isWhitespace$1 = (node, rootNode) => {
  2377. return isText$9(node) && isWhitespaceText(node.data) && hasWhitespacePreserveParent(node, rootNode) === false;
  2378. };
  2379. const isNamedAnchor = node => {
  2380. return isElement$6(node) && node.nodeName === 'A' && !node.hasAttribute('href') && (node.hasAttribute('name') || node.hasAttribute('id'));
  2381. };
  2382. const isContent$1 = (node, rootNode) => {
  2383. return isCaretCandidate$3(node) && isWhitespace$1(node, rootNode) === false || isNamedAnchor(node) || isBookmark(node);
  2384. };
  2385. const isBookmark = hasAttribute('data-mce-bookmark');
  2386. const isBogus$1 = hasAttribute('data-mce-bogus');
  2387. const isBogusAll = hasAttributeValue('data-mce-bogus', 'all');
  2388. const isEmptyNode = (targetNode, skipBogus) => {
  2389. let brCount = 0;
  2390. if (isContent$1(targetNode, targetNode)) {
  2391. return false;
  2392. } else {
  2393. let node = targetNode.firstChild;
  2394. if (!node) {
  2395. return true;
  2396. }
  2397. const walker = new DomTreeWalker(node, targetNode);
  2398. do {
  2399. if (skipBogus) {
  2400. if (isBogusAll(node)) {
  2401. node = walker.next(true);
  2402. continue;
  2403. }
  2404. if (isBogus$1(node)) {
  2405. node = walker.next();
  2406. continue;
  2407. }
  2408. }
  2409. if (isBr$6(node)) {
  2410. brCount++;
  2411. node = walker.next();
  2412. continue;
  2413. }
  2414. if (isContent$1(node, targetNode)) {
  2415. return false;
  2416. }
  2417. node = walker.next();
  2418. } while (node);
  2419. return brCount <= 1;
  2420. }
  2421. };
  2422. const isEmpty$2 = (elm, skipBogus = true) => isEmptyNode(elm.dom, skipBogus);
  2423. const isSpan = node => node.nodeName.toLowerCase() === 'span';
  2424. const isInlineContent = (node, root) => isNonNullable(node) && (isContent$1(node, root) || isInline$1(SugarElement.fromDom(node)));
  2425. const surroundedByInlineContent = (node, root) => {
  2426. const prev = new DomTreeWalker(node, root).prev(false);
  2427. const next = new DomTreeWalker(node, root).next(false);
  2428. const prevIsInline = isUndefined(prev) || isInlineContent(prev, root);
  2429. const nextIsInline = isUndefined(next) || isInlineContent(next, root);
  2430. return prevIsInline && nextIsInline;
  2431. };
  2432. const isBookmarkNode$2 = node => isSpan(node) && node.getAttribute('data-mce-type') === 'bookmark';
  2433. const isKeepTextNode = (node, root) => isText$9(node) && node.data.length > 0 && surroundedByInlineContent(node, root);
  2434. const isKeepElement = node => isElement$6(node) ? node.childNodes.length > 0 : false;
  2435. const isDocument = node => isDocumentFragment(node) || isDocument$1(node);
  2436. const trimNode = (dom, node, root) => {
  2437. const rootNode = root || node;
  2438. if (isElement$6(node) && isBookmarkNode$2(node)) {
  2439. return node;
  2440. }
  2441. const children = node.childNodes;
  2442. for (let i = children.length - 1; i >= 0; i--) {
  2443. trimNode(dom, children[i], rootNode);
  2444. }
  2445. if (isElement$6(node)) {
  2446. const currentChildren = node.childNodes;
  2447. if (currentChildren.length === 1 && isBookmarkNode$2(currentChildren[0])) {
  2448. node.parentNode.insertBefore(currentChildren[0], node);
  2449. }
  2450. }
  2451. if (!isDocument(node) && !isContent$1(node, rootNode) && !isKeepElement(node) && !isKeepTextNode(node, rootNode)) {
  2452. dom.remove(node);
  2453. }
  2454. return node;
  2455. };
  2456. const makeMap$3 = Tools.makeMap;
  2457. const attrsCharsRegExp = /[&<>\"\u0060\u007E-\uD7FF\uE000-\uFFEF]|[\uD800-\uDBFF][\uDC00-\uDFFF]/g;
  2458. const textCharsRegExp = /[<>&\u007E-\uD7FF\uE000-\uFFEF]|[\uD800-\uDBFF][\uDC00-\uDFFF]/g;
  2459. const rawCharsRegExp = /[<>&\"\']/g;
  2460. const entityRegExp = /&#([a-z0-9]+);?|&([a-z0-9]+);/gi;
  2461. const asciiMap = {
  2462. 128: '\u20AC',
  2463. 130: '\u201A',
  2464. 131: '\u0192',
  2465. 132: '\u201E',
  2466. 133: '\u2026',
  2467. 134: '\u2020',
  2468. 135: '\u2021',
  2469. 136: '\u02c6',
  2470. 137: '\u2030',
  2471. 138: '\u0160',
  2472. 139: '\u2039',
  2473. 140: '\u0152',
  2474. 142: '\u017d',
  2475. 145: '\u2018',
  2476. 146: '\u2019',
  2477. 147: '\u201C',
  2478. 148: '\u201D',
  2479. 149: '\u2022',
  2480. 150: '\u2013',
  2481. 151: '\u2014',
  2482. 152: '\u02DC',
  2483. 153: '\u2122',
  2484. 154: '\u0161',
  2485. 155: '\u203A',
  2486. 156: '\u0153',
  2487. 158: '\u017e',
  2488. 159: '\u0178'
  2489. };
  2490. const baseEntities = {
  2491. '"': '&quot;',
  2492. '\'': '&#39;',
  2493. '<': '&lt;',
  2494. '>': '&gt;',
  2495. '&': '&amp;',
  2496. '`': '&#96;'
  2497. };
  2498. const reverseEntities = {
  2499. '&lt;': '<',
  2500. '&gt;': '>',
  2501. '&amp;': '&',
  2502. '&quot;': '"',
  2503. '&apos;': `'`
  2504. };
  2505. const nativeDecode = text => {
  2506. const elm = SugarElement.fromTag('div').dom;
  2507. elm.innerHTML = text;
  2508. return elm.textContent || elm.innerText || text;
  2509. };
  2510. const buildEntitiesLookup = (items, radix) => {
  2511. let i, chr, entity;
  2512. const lookup = {};
  2513. if (items) {
  2514. items = items.split(',');
  2515. radix = radix || 10;
  2516. for (i = 0; i < items.length; i += 2) {
  2517. chr = String.fromCharCode(parseInt(items[i], radix));
  2518. if (!baseEntities[chr]) {
  2519. entity = '&' + items[i + 1] + ';';
  2520. lookup[chr] = entity;
  2521. lookup[entity] = chr;
  2522. }
  2523. }
  2524. return lookup;
  2525. }
  2526. };
  2527. 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);
  2528. const encodeRaw = (text, attr) => text.replace(attr ? attrsCharsRegExp : textCharsRegExp, chr => {
  2529. return baseEntities[chr] || chr;
  2530. });
  2531. const encodeAllRaw = text => ('' + text).replace(rawCharsRegExp, chr => {
  2532. return baseEntities[chr] || chr;
  2533. });
  2534. const encodeNumeric = (text, attr) => text.replace(attr ? attrsCharsRegExp : textCharsRegExp, chr => {
  2535. if (chr.length > 1) {
  2536. return '&#' + ((chr.charCodeAt(0) - 55296) * 1024 + (chr.charCodeAt(1) - 56320) + 65536) + ';';
  2537. }
  2538. return baseEntities[chr] || '&#' + chr.charCodeAt(0) + ';';
  2539. });
  2540. const encodeNamed = (text, attr, entities) => {
  2541. entities = entities || namedEntities;
  2542. return text.replace(attr ? attrsCharsRegExp : textCharsRegExp, chr => {
  2543. return baseEntities[chr] || entities[chr] || chr;
  2544. });
  2545. };
  2546. const getEncodeFunc = (name, entities) => {
  2547. const entitiesMap = buildEntitiesLookup(entities) || namedEntities;
  2548. const encodeNamedAndNumeric = (text, attr) => text.replace(attr ? attrsCharsRegExp : textCharsRegExp, chr => {
  2549. if (baseEntities[chr] !== undefined) {
  2550. return baseEntities[chr];
  2551. }
  2552. if (entitiesMap[chr] !== undefined) {
  2553. return entitiesMap[chr];
  2554. }
  2555. if (chr.length > 1) {
  2556. return '&#' + ((chr.charCodeAt(0) - 55296) * 1024 + (chr.charCodeAt(1) - 56320) + 65536) + ';';
  2557. }
  2558. return '&#' + chr.charCodeAt(0) + ';';
  2559. });
  2560. const encodeCustomNamed = (text, attr) => {
  2561. return encodeNamed(text, attr, entitiesMap);
  2562. };
  2563. const nameMap = makeMap$3(name.replace(/\+/g, ','));
  2564. if (nameMap.named && nameMap.numeric) {
  2565. return encodeNamedAndNumeric;
  2566. }
  2567. if (nameMap.named) {
  2568. if (entities) {
  2569. return encodeCustomNamed;
  2570. }
  2571. return encodeNamed;
  2572. }
  2573. if (nameMap.numeric) {
  2574. return encodeNumeric;
  2575. }
  2576. return encodeRaw;
  2577. };
  2578. const decode = text => text.replace(entityRegExp, (all, numeric) => {
  2579. if (numeric) {
  2580. if (numeric.charAt(0).toLowerCase() === 'x') {
  2581. numeric = parseInt(numeric.substr(1), 16);
  2582. } else {
  2583. numeric = parseInt(numeric, 10);
  2584. }
  2585. if (numeric > 65535) {
  2586. numeric -= 65536;
  2587. return String.fromCharCode(55296 + (numeric >> 10), 56320 + (numeric & 1023));
  2588. }
  2589. return asciiMap[numeric] || String.fromCharCode(numeric);
  2590. }
  2591. return reverseEntities[all] || namedEntities[all] || nativeDecode(all);
  2592. });
  2593. const Entities = {
  2594. encodeRaw,
  2595. encodeAllRaw,
  2596. encodeNumeric,
  2597. encodeNamed,
  2598. getEncodeFunc,
  2599. decode
  2600. };
  2601. const mapCache = {}, dummyObj = {};
  2602. const makeMap$2 = Tools.makeMap, each$c = Tools.each, extend$2 = Tools.extend, explode$2 = Tools.explode, inArray = Tools.inArray;
  2603. const split$1 = (items, delim) => {
  2604. items = Tools.trim(items);
  2605. return items ? items.split(delim || ' ') : [];
  2606. };
  2607. const createMap = (defaultValue, extendWith) => {
  2608. const value = makeMap$2(defaultValue, ' ', makeMap$2(defaultValue.toUpperCase(), ' '));
  2609. return extend$2(value, extendWith);
  2610. };
  2611. const getTextRootBlockElements = schema => createMap('td th li dt dd figcaption caption details summary', schema.getTextBlockElements());
  2612. const compileSchema = type => {
  2613. const schema = {};
  2614. let globalAttributes, blockContent;
  2615. let phrasingContent, flowContent, html4BlockContent, html4PhrasingContent;
  2616. const add = (name, attributes = '', children = '') => {
  2617. const childNames = split$1(children);
  2618. const names = split$1(name);
  2619. let ni = names.length;
  2620. while (ni--) {
  2621. const attributesOrder = split$1([
  2622. globalAttributes,
  2623. attributes
  2624. ].join(' '));
  2625. schema[names[ni]] = {
  2626. attributes: mapToObject(attributesOrder, () => ({})),
  2627. attributesOrder,
  2628. children: mapToObject(childNames, constant(dummyObj))
  2629. };
  2630. }
  2631. };
  2632. const addAttrs = (name, attributes) => {
  2633. const names = split$1(name);
  2634. const attrs = split$1(attributes);
  2635. let ni = names.length;
  2636. while (ni--) {
  2637. const schemaItem = schema[names[ni]];
  2638. for (let i = 0, l = attrs.length; i < l; i++) {
  2639. schemaItem.attributes[attrs[i]] = {};
  2640. schemaItem.attributesOrder.push(attrs[i]);
  2641. }
  2642. }
  2643. };
  2644. if (mapCache[type]) {
  2645. return mapCache[type];
  2646. }
  2647. globalAttributes = 'id accesskey class dir lang style tabindex title role';
  2648. blockContent = 'address blockquote div dl fieldset form h1 h2 h3 h4 h5 h6 hr menu ol p pre table ul';
  2649. 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';
  2650. if (type !== 'html4') {
  2651. globalAttributes += ' contenteditable contextmenu draggable dropzone ' + 'hidden spellcheck translate';
  2652. blockContent += ' article aside details dialog figure main header footer hgroup section nav';
  2653. phrasingContent += ' audio canvas command datalist mark meter output picture ' + 'progress time wbr video ruby bdi keygen';
  2654. }
  2655. if (type !== 'html5-strict') {
  2656. globalAttributes += ' xml:lang';
  2657. html4PhrasingContent = 'acronym applet basefont big font strike tt';
  2658. phrasingContent = [
  2659. phrasingContent,
  2660. html4PhrasingContent
  2661. ].join(' ');
  2662. each$c(split$1(html4PhrasingContent), name => {
  2663. add(name, '', phrasingContent);
  2664. });
  2665. html4BlockContent = 'center dir isindex noframes';
  2666. blockContent = [
  2667. blockContent,
  2668. html4BlockContent
  2669. ].join(' ');
  2670. flowContent = [
  2671. blockContent,
  2672. phrasingContent
  2673. ].join(' ');
  2674. each$c(split$1(html4BlockContent), name => {
  2675. add(name, '', flowContent);
  2676. });
  2677. }
  2678. flowContent = flowContent || [
  2679. blockContent,
  2680. phrasingContent
  2681. ].join(' ');
  2682. add('html', 'manifest', 'head body');
  2683. add('head', '', 'base command link meta noscript script style title');
  2684. add('title hr noscript br');
  2685. add('base', 'href target');
  2686. add('link', 'href rel media hreflang type sizes hreflang');
  2687. add('meta', 'name http-equiv content charset');
  2688. add('style', 'media type scoped');
  2689. add('script', 'src async defer type charset');
  2690. add('body', 'onafterprint onbeforeprint onbeforeunload onblur onerror onfocus ' + 'onhashchange onload onmessage onoffline ononline onpagehide onpageshow ' + 'onpopstate onresize onscroll onstorage onunload', flowContent);
  2691. add('address dt dd div caption', '', flowContent);
  2692. 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);
  2693. add('blockquote', 'cite', flowContent);
  2694. add('ol', 'reversed start type', 'li');
  2695. add('ul', '', 'li');
  2696. add('li', 'value', flowContent);
  2697. add('dl', '', 'dt dd');
  2698. add('a', 'href target rel media hreflang type', phrasingContent);
  2699. add('q', 'cite', phrasingContent);
  2700. add('ins del', 'cite datetime', flowContent);
  2701. add('img', 'src sizes srcset alt usemap ismap width height');
  2702. add('iframe', 'src name width height', flowContent);
  2703. add('embed', 'src type width height');
  2704. add('object', 'data type typemustmatch name usemap form width height', [
  2705. flowContent,
  2706. 'param'
  2707. ].join(' '));
  2708. add('param', 'name value');
  2709. add('map', 'name', [
  2710. flowContent,
  2711. 'area'
  2712. ].join(' '));
  2713. add('area', 'alt coords shape href target rel media hreflang type');
  2714. add('table', 'border', 'caption colgroup thead tfoot tbody tr' + (type === 'html4' ? ' col' : ''));
  2715. add('colgroup', 'span', 'col');
  2716. add('col', 'span');
  2717. add('tbody thead tfoot', '', 'tr');
  2718. add('tr', '', 'td th');
  2719. add('td', 'colspan rowspan headers', flowContent);
  2720. add('th', 'colspan rowspan headers scope abbr', flowContent);
  2721. add('form', 'accept-charset action autocomplete enctype method name novalidate target', flowContent);
  2722. add('fieldset', 'disabled form name', [
  2723. flowContent,
  2724. 'legend'
  2725. ].join(' '));
  2726. add('label', 'form for', phrasingContent);
  2727. 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');
  2728. add('button', 'disabled form formaction formenctype formmethod formnovalidate formtarget name type value', type === 'html4' ? flowContent : phrasingContent);
  2729. add('select', 'disabled form multiple name required size', 'option optgroup');
  2730. add('optgroup', 'disabled label', 'option');
  2731. add('option', 'disabled label selected value');
  2732. add('textarea', 'cols dirname disabled form maxlength name readonly required rows wrap');
  2733. add('menu', 'type label', [
  2734. flowContent,
  2735. 'li'
  2736. ].join(' '));
  2737. add('noscript', '', flowContent);
  2738. if (type !== 'html4') {
  2739. add('wbr');
  2740. add('ruby', '', [
  2741. phrasingContent,
  2742. 'rt rp'
  2743. ].join(' '));
  2744. add('figcaption', '', flowContent);
  2745. add('mark rt rp summary bdi', '', phrasingContent);
  2746. add('canvas', 'width height', flowContent);
  2747. add('video', 'src crossorigin poster preload autoplay mediagroup loop ' + 'muted controls width height buffered', [
  2748. flowContent,
  2749. 'track source'
  2750. ].join(' '));
  2751. add('audio', 'src crossorigin preload autoplay mediagroup loop muted controls ' + 'buffered volume', [
  2752. flowContent,
  2753. 'track source'
  2754. ].join(' '));
  2755. add('picture', '', 'img source');
  2756. add('source', 'src srcset type media sizes');
  2757. add('track', 'kind src srclang label default');
  2758. add('datalist', '', [
  2759. phrasingContent,
  2760. 'option'
  2761. ].join(' '));
  2762. add('article section nav aside main header footer', '', flowContent);
  2763. add('hgroup', '', 'h1 h2 h3 h4 h5 h6');
  2764. add('figure', '', [
  2765. flowContent,
  2766. 'figcaption'
  2767. ].join(' '));
  2768. add('time', 'datetime', phrasingContent);
  2769. add('dialog', 'open', flowContent);
  2770. add('command', 'type label icon disabled checked radiogroup command');
  2771. add('output', 'for form name', phrasingContent);
  2772. add('progress', 'value max', phrasingContent);
  2773. add('meter', 'value min max low high optimum', phrasingContent);
  2774. add('details', 'open', [
  2775. flowContent,
  2776. 'summary'
  2777. ].join(' '));
  2778. add('keygen', 'autofocus challenge disabled form keytype name');
  2779. }
  2780. if (type !== 'html5-strict') {
  2781. addAttrs('script', 'language xml:space');
  2782. addAttrs('style', 'xml:space');
  2783. addAttrs('object', 'declare classid code codebase codetype archive standby align border hspace vspace');
  2784. addAttrs('embed', 'align name hspace vspace');
  2785. addAttrs('param', 'valuetype type');
  2786. addAttrs('a', 'charset name rev shape coords');
  2787. addAttrs('br', 'clear');
  2788. addAttrs('applet', 'codebase archive code object alt name width height align hspace vspace');
  2789. addAttrs('img', 'name longdesc align border hspace vspace');
  2790. addAttrs('iframe', 'longdesc frameborder marginwidth marginheight scrolling align');
  2791. addAttrs('font basefont', 'size color face');
  2792. addAttrs('input', 'usemap align');
  2793. addAttrs('select');
  2794. addAttrs('textarea');
  2795. addAttrs('h1 h2 h3 h4 h5 h6 div p legend caption', 'align');
  2796. addAttrs('ul', 'type compact');
  2797. addAttrs('li', 'type');
  2798. addAttrs('ol dl menu dir', 'compact');
  2799. addAttrs('pre', 'width xml:space');
  2800. addAttrs('hr', 'align noshade size width');
  2801. addAttrs('isindex', 'prompt');
  2802. addAttrs('table', 'summary width frame rules cellspacing cellpadding align bgcolor');
  2803. addAttrs('col', 'width align char charoff valign');
  2804. addAttrs('colgroup', 'width align char charoff valign');
  2805. addAttrs('thead', 'align char charoff valign');
  2806. addAttrs('tr', 'align char charoff valign bgcolor');
  2807. addAttrs('th', 'axis align char charoff valign nowrap bgcolor width height');
  2808. addAttrs('form', 'accept');
  2809. addAttrs('td', 'abbr axis scope align char charoff valign nowrap bgcolor width height');
  2810. addAttrs('tfoot', 'align char charoff valign');
  2811. addAttrs('tbody', 'align char charoff valign');
  2812. addAttrs('area', 'nohref');
  2813. addAttrs('body', 'background bgcolor text link vlink alink');
  2814. }
  2815. if (type !== 'html4') {
  2816. addAttrs('input button select textarea', 'autofocus');
  2817. addAttrs('input textarea', 'placeholder');
  2818. addAttrs('a', 'download');
  2819. addAttrs('link script img', 'crossorigin');
  2820. addAttrs('img', 'loading');
  2821. addAttrs('iframe', 'sandbox seamless allowfullscreen loading');
  2822. }
  2823. if (type !== 'html4') {
  2824. each$f([
  2825. schema.video,
  2826. schema.audio
  2827. ], item => {
  2828. delete item.children.audio;
  2829. delete item.children.video;
  2830. });
  2831. }
  2832. each$c(split$1('a form meter progress dfn'), name => {
  2833. if (schema[name]) {
  2834. delete schema[name].children[name];
  2835. }
  2836. });
  2837. delete schema.caption.children.table;
  2838. delete schema.script;
  2839. mapCache[type] = schema;
  2840. return schema;
  2841. };
  2842. const compileElementMap = (value, mode) => {
  2843. let styles;
  2844. if (value) {
  2845. styles = {};
  2846. if (typeof value === 'string') {
  2847. value = { '*': value };
  2848. }
  2849. each$c(value, (value, key) => {
  2850. styles[key] = styles[key.toUpperCase()] = mode === 'map' ? makeMap$2(value, /[, ]/) : explode$2(value, /[, ]/);
  2851. });
  2852. }
  2853. return styles;
  2854. };
  2855. const Schema = settings => {
  2856. var _a;
  2857. const elements = {};
  2858. const children = {};
  2859. let patternElements = [];
  2860. const customElementsMap = {}, specialElements = {};
  2861. const createLookupTable = (option, defaultValue, extendWith) => {
  2862. let value = settings[option];
  2863. if (!value) {
  2864. value = mapCache[option];
  2865. if (!value) {
  2866. value = createMap(defaultValue, extendWith);
  2867. mapCache[option] = value;
  2868. }
  2869. } else {
  2870. value = makeMap$2(value, /[, ]/, makeMap$2(value.toUpperCase(), /[, ]/));
  2871. }
  2872. return value;
  2873. };
  2874. settings = settings || {};
  2875. const schemaType = (_a = settings.schema) !== null && _a !== void 0 ? _a : 'html5';
  2876. const schemaItems = compileSchema(schemaType);
  2877. if (settings.verify_html === false) {
  2878. settings.valid_elements = '*[*]';
  2879. }
  2880. const validStyles = compileElementMap(settings.valid_styles);
  2881. const invalidStyles = compileElementMap(settings.invalid_styles, 'map');
  2882. const validClasses = compileElementMap(settings.valid_classes, 'map');
  2883. const whitespaceElementsMap = createLookupTable('whitespace_elements', 'pre script noscript style textarea video audio iframe object code');
  2884. const selfClosingElementsMap = createLookupTable('self_closing_elements', 'colgroup dd dt li option p td tfoot th thead tr');
  2885. const voidElementsMap = createLookupTable('void_elements', 'area base basefont br col frame hr img input isindex link ' + 'meta param embed source wbr track');
  2886. const boolAttrMap = createLookupTable('boolean_attributes', 'checked compact declare defer disabled ismap multiple nohref noresize ' + 'noshade nowrap readonly selected autoplay loop controls allowfullscreen');
  2887. const nonEmptyOrMoveCaretBeforeOnEnter = 'td th iframe video audio object script code';
  2888. const nonEmptyElementsMap = createLookupTable('non_empty_elements', nonEmptyOrMoveCaretBeforeOnEnter + ' pre', voidElementsMap);
  2889. const moveCaretBeforeOnEnterElementsMap = createLookupTable('move_caret_before_on_enter_elements', nonEmptyOrMoveCaretBeforeOnEnter + ' table', voidElementsMap);
  2890. 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');
  2891. 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);
  2892. const textInlineElementsMap = createLookupTable('text_inline_elements', 'span strong b em i font s strike u var cite ' + 'dfn code mark q sup sub samp');
  2893. each$c('script noscript iframe noframes noembed title style textarea xmp plaintext'.split(' '), name => {
  2894. specialElements[name] = new RegExp('</' + name + '[^>]*>', 'gi');
  2895. });
  2896. const patternToRegExp = str => new RegExp('^' + str.replace(/([?+*])/g, '.$1') + '$');
  2897. const addValidElements = validElements => {
  2898. let ei, el, ai, al, matches, element, attr, attrData, elementName, attrName, attrType, attributes, attributesOrder, prefix, outputName, globalAttributes, globalAttributesOrder, value;
  2899. const elementRuleRegExp = /^([#+\-])?([^\[!\/]+)(?:\/([^\[!]+))?(?:(!?)\[([^\]]+)])?$/, attrRuleRegExp = /^([!\-])?(\w+[\\:]:\w+|[^=~<]+)?(?:([=~<])(.*))?$/, hasPatternsRegExp = /[*?+]/;
  2900. if (validElements) {
  2901. const validElementsArr = split$1(validElements, ',');
  2902. if (elements['@']) {
  2903. globalAttributes = elements['@'].attributes;
  2904. globalAttributesOrder = elements['@'].attributesOrder;
  2905. }
  2906. for (ei = 0, el = validElementsArr.length; ei < el; ei++) {
  2907. matches = elementRuleRegExp.exec(validElementsArr[ei]);
  2908. if (matches) {
  2909. prefix = matches[1];
  2910. elementName = matches[2];
  2911. outputName = matches[3];
  2912. attrData = matches[5];
  2913. attributes = {};
  2914. attributesOrder = [];
  2915. element = {
  2916. attributes,
  2917. attributesOrder
  2918. };
  2919. if (prefix === '#') {
  2920. element.paddEmpty = true;
  2921. }
  2922. if (prefix === '-') {
  2923. element.removeEmpty = true;
  2924. }
  2925. if (matches[4] === '!') {
  2926. element.removeEmptyAttrs = true;
  2927. }
  2928. if (globalAttributes) {
  2929. each$e(globalAttributes, (value, key) => {
  2930. attributes[key] = value;
  2931. });
  2932. attributesOrder.push.apply(attributesOrder, globalAttributesOrder);
  2933. }
  2934. if (attrData) {
  2935. attrData = split$1(attrData, '|');
  2936. for (ai = 0, al = attrData.length; ai < al; ai++) {
  2937. matches = attrRuleRegExp.exec(attrData[ai]);
  2938. if (matches) {
  2939. attr = {};
  2940. attrType = matches[1];
  2941. attrName = matches[2].replace(/[\\:]:/g, ':');
  2942. prefix = matches[3];
  2943. value = matches[4];
  2944. if (attrType === '!') {
  2945. element.attributesRequired = element.attributesRequired || [];
  2946. element.attributesRequired.push(attrName);
  2947. attr.required = true;
  2948. }
  2949. if (attrType === '-') {
  2950. delete attributes[attrName];
  2951. attributesOrder.splice(inArray(attributesOrder, attrName), 1);
  2952. continue;
  2953. }
  2954. if (prefix) {
  2955. if (prefix === '=') {
  2956. element.attributesDefault = element.attributesDefault || [];
  2957. element.attributesDefault.push({
  2958. name: attrName,
  2959. value
  2960. });
  2961. attr.defaultValue = value;
  2962. }
  2963. if (prefix === '~') {
  2964. element.attributesForced = element.attributesForced || [];
  2965. element.attributesForced.push({
  2966. name: attrName,
  2967. value
  2968. });
  2969. attr.forcedValue = value;
  2970. }
  2971. if (prefix === '<') {
  2972. attr.validValues = makeMap$2(value, '?');
  2973. }
  2974. }
  2975. if (hasPatternsRegExp.test(attrName)) {
  2976. element.attributePatterns = element.attributePatterns || [];
  2977. attr.pattern = patternToRegExp(attrName);
  2978. element.attributePatterns.push(attr);
  2979. } else {
  2980. if (!attributes[attrName]) {
  2981. attributesOrder.push(attrName);
  2982. }
  2983. attributes[attrName] = attr;
  2984. }
  2985. }
  2986. }
  2987. }
  2988. if (!globalAttributes && elementName === '@') {
  2989. globalAttributes = attributes;
  2990. globalAttributesOrder = attributesOrder;
  2991. }
  2992. if (outputName) {
  2993. element.outputName = elementName;
  2994. elements[outputName] = element;
  2995. }
  2996. if (hasPatternsRegExp.test(elementName)) {
  2997. element.pattern = patternToRegExp(elementName);
  2998. patternElements.push(element);
  2999. } else {
  3000. elements[elementName] = element;
  3001. }
  3002. }
  3003. }
  3004. }
  3005. };
  3006. const setValidElements = validElements => {
  3007. patternElements = [];
  3008. each$f(keys(elements), name => {
  3009. delete elements[name];
  3010. });
  3011. addValidElements(validElements);
  3012. each$c(schemaItems, (element, name) => {
  3013. children[name] = element.children;
  3014. });
  3015. };
  3016. const addCustomElements = customElements => {
  3017. const customElementRegExp = /^(~)?(.+)$/;
  3018. if (customElements) {
  3019. mapCache.text_block_elements = mapCache.block_elements = null;
  3020. each$c(split$1(customElements, ','), rule => {
  3021. const matches = customElementRegExp.exec(rule), inline = matches[1] === '~', cloneName = inline ? 'span' : 'div', name = matches[2];
  3022. children[name] = children[cloneName];
  3023. customElementsMap[name] = cloneName;
  3024. nonEmptyElementsMap[name.toUpperCase()] = {};
  3025. nonEmptyElementsMap[name] = {};
  3026. if (!inline) {
  3027. blockElementsMap[name.toUpperCase()] = {};
  3028. blockElementsMap[name] = {};
  3029. }
  3030. if (!elements[name]) {
  3031. let customRule = elements[cloneName];
  3032. customRule = extend$2({}, customRule);
  3033. delete customRule.removeEmptyAttrs;
  3034. delete customRule.removeEmpty;
  3035. elements[name] = customRule;
  3036. }
  3037. each$c(children, (element, elmName) => {
  3038. if (element[cloneName]) {
  3039. children[elmName] = element = extend$2({}, children[elmName]);
  3040. element[name] = element[cloneName];
  3041. }
  3042. });
  3043. });
  3044. }
  3045. };
  3046. const addValidChildren = validChildren => {
  3047. 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]+)\[([^\]]+)]$/;
  3048. mapCache[schemaType] = null;
  3049. if (validChildren) {
  3050. each$c(split$1(validChildren, ','), rule => {
  3051. const matches = childRuleRegExp.exec(rule);
  3052. let parent, prefix;
  3053. if (matches) {
  3054. prefix = matches[1];
  3055. if (prefix) {
  3056. parent = children[matches[2]];
  3057. } else {
  3058. parent = children[matches[2]] = { '#comment': {} };
  3059. }
  3060. parent = children[matches[2]];
  3061. each$c(split$1(matches[3], '|'), child => {
  3062. if (prefix === '-') {
  3063. delete parent[child];
  3064. } else {
  3065. parent[child] = {};
  3066. }
  3067. });
  3068. }
  3069. });
  3070. }
  3071. };
  3072. const getElementRule = name => {
  3073. let element = elements[name], i;
  3074. if (element) {
  3075. return element;
  3076. }
  3077. i = patternElements.length;
  3078. while (i--) {
  3079. element = patternElements[i];
  3080. if (element.pattern.test(name)) {
  3081. return element;
  3082. }
  3083. }
  3084. };
  3085. if (!settings.valid_elements) {
  3086. each$c(schemaItems, (element, name) => {
  3087. elements[name] = {
  3088. attributes: element.attributes,
  3089. attributesOrder: element.attributesOrder
  3090. };
  3091. children[name] = element.children;
  3092. });
  3093. each$c(split$1('strong/b em/i'), item => {
  3094. const items = split$1(item, '/');
  3095. elements[items[1]].outputName = items[0];
  3096. });
  3097. each$c(textInlineElementsMap, (_val, name) => {
  3098. if (elements[name]) {
  3099. if (settings.padd_empty_block_inline_children) {
  3100. elements[name].paddInEmptyBlock = true;
  3101. }
  3102. elements[name].removeEmpty = true;
  3103. }
  3104. });
  3105. each$c(split$1('ol ul blockquote a table tbody'), name => {
  3106. if (elements[name]) {
  3107. elements[name].removeEmpty = true;
  3108. }
  3109. });
  3110. each$c(split$1('p h1 h2 h3 h4 h5 h6 th td pre div address caption li'), name => {
  3111. elements[name].paddEmpty = true;
  3112. });
  3113. each$c(split$1('span'), name => {
  3114. elements[name].removeEmptyAttrs = true;
  3115. });
  3116. } else {
  3117. setValidElements(settings.valid_elements);
  3118. }
  3119. addCustomElements(settings.custom_elements);
  3120. addValidChildren(settings.valid_children);
  3121. addValidElements(settings.extended_valid_elements);
  3122. addValidChildren('+ol[ul|ol],+ul[ul|ol]');
  3123. each$c({
  3124. dd: 'dl',
  3125. dt: 'dl',
  3126. li: 'ul ol',
  3127. td: 'tr',
  3128. th: 'tr',
  3129. tr: 'tbody thead tfoot',
  3130. tbody: 'table',
  3131. thead: 'table',
  3132. tfoot: 'table',
  3133. legend: 'fieldset',
  3134. area: 'map',
  3135. param: 'video audio object'
  3136. }, (parents, item) => {
  3137. if (elements[item]) {
  3138. elements[item].parentsRequired = split$1(parents);
  3139. }
  3140. });
  3141. if (settings.invalid_elements) {
  3142. each$c(explode$2(settings.invalid_elements), item => {
  3143. if (elements[item]) {
  3144. delete elements[item];
  3145. }
  3146. });
  3147. }
  3148. if (!getElementRule('span')) {
  3149. addValidElements('span[!data-mce-type|*]');
  3150. }
  3151. const getValidStyles = constant(validStyles);
  3152. const getInvalidStyles = constant(invalidStyles);
  3153. const getValidClasses = constant(validClasses);
  3154. const getBoolAttrs = constant(boolAttrMap);
  3155. const getBlockElements = constant(blockElementsMap);
  3156. const getTextBlockElements = constant(textBlockElementsMap);
  3157. const getTextInlineElements = constant(textInlineElementsMap);
  3158. const getVoidElements = constant(Object.seal(voidElementsMap));
  3159. const getSelfClosingElements = constant(selfClosingElementsMap);
  3160. const getNonEmptyElements = constant(nonEmptyElementsMap);
  3161. const getMoveCaretBeforeOnEnterElements = constant(moveCaretBeforeOnEnterElementsMap);
  3162. const getWhitespaceElements = constant(whitespaceElementsMap);
  3163. const getSpecialElements = constant(Object.seal(specialElements));
  3164. const isValidChild = (name, child) => {
  3165. const parent = children[name.toLowerCase()];
  3166. return !!(parent && parent[child.toLowerCase()]);
  3167. };
  3168. const isValid = (name, attr) => {
  3169. let attrPatterns, i;
  3170. const rule = getElementRule(name);
  3171. if (rule) {
  3172. if (attr) {
  3173. if (rule.attributes[attr]) {
  3174. return true;
  3175. }
  3176. attrPatterns = rule.attributePatterns;
  3177. if (attrPatterns) {
  3178. i = attrPatterns.length;
  3179. while (i--) {
  3180. if (attrPatterns[i].pattern.test(attr)) {
  3181. return true;
  3182. }
  3183. }
  3184. }
  3185. } else {
  3186. return true;
  3187. }
  3188. }
  3189. return false;
  3190. };
  3191. const getCustomElements = constant(customElementsMap);
  3192. return {
  3193. type: schemaType,
  3194. children,
  3195. elements,
  3196. getValidStyles,
  3197. getValidClasses,
  3198. getBlockElements,
  3199. getInvalidStyles,
  3200. getVoidElements,
  3201. getTextBlockElements,
  3202. getTextInlineElements,
  3203. getBoolAttrs,
  3204. getElementRule,
  3205. getSelfClosingElements,
  3206. getNonEmptyElements,
  3207. getMoveCaretBeforeOnEnterElements,
  3208. getWhitespaceElements,
  3209. getSpecialElements,
  3210. isValidChild,
  3211. isValid,
  3212. getCustomElements,
  3213. addValidElements,
  3214. setValidElements,
  3215. addCustomElements,
  3216. addValidChildren
  3217. };
  3218. };
  3219. const Styles = (settings, schema) => {
  3220. const urlOrStrRegExp = /(?:url(?:(?:\(\s*\"([^\"]+)\"\s*\))|(?:\(\s*\'([^\']+)\'\s*\))|(?:\(\s*([^)\s]+)\s*\))))|(?:\'([^\']+)\')|(?:\"([^\"]+)\")/gi;
  3221. const styleRegExp = /\s*([^:]+):\s*([^;]+);?/g;
  3222. const trimRightRegExp = /\s+$/;
  3223. let i;
  3224. const encodingLookup = {};
  3225. let validStyles;
  3226. let invalidStyles;
  3227. const invisibleChar = zeroWidth;
  3228. settings = settings || {};
  3229. if (schema) {
  3230. validStyles = schema.getValidStyles();
  3231. invalidStyles = schema.getInvalidStyles();
  3232. }
  3233. const encodingItems = (`\\" \\' \\; \\: ; : ` + invisibleChar).split(' ');
  3234. for (i = 0; i < encodingItems.length; i++) {
  3235. encodingLookup[encodingItems[i]] = invisibleChar + i;
  3236. encodingLookup[invisibleChar + i] = encodingItems[i];
  3237. }
  3238. const self = {
  3239. parse: css => {
  3240. const styles = {};
  3241. let matches, name, value, isEncoded;
  3242. const urlConverter = settings.url_converter;
  3243. const urlConverterScope = settings.url_converter_scope || self;
  3244. const compress = (prefix, suffix, noJoin) => {
  3245. const top = styles[prefix + '-top' + suffix];
  3246. if (!top) {
  3247. return;
  3248. }
  3249. const right = styles[prefix + '-right' + suffix];
  3250. if (!right) {
  3251. return;
  3252. }
  3253. const bottom = styles[prefix + '-bottom' + suffix];
  3254. if (!bottom) {
  3255. return;
  3256. }
  3257. const left = styles[prefix + '-left' + suffix];
  3258. if (!left) {
  3259. return;
  3260. }
  3261. const box = [
  3262. top,
  3263. right,
  3264. bottom,
  3265. left
  3266. ];
  3267. i = box.length - 1;
  3268. while (i--) {
  3269. if (box[i] !== box[i + 1]) {
  3270. break;
  3271. }
  3272. }
  3273. if (i > -1 && noJoin) {
  3274. return;
  3275. }
  3276. styles[prefix + suffix] = i === -1 ? box[0] : box.join(' ');
  3277. delete styles[prefix + '-top' + suffix];
  3278. delete styles[prefix + '-right' + suffix];
  3279. delete styles[prefix + '-bottom' + suffix];
  3280. delete styles[prefix + '-left' + suffix];
  3281. };
  3282. const canCompress = key => {
  3283. let value = styles[key], i;
  3284. if (!value) {
  3285. return;
  3286. }
  3287. value = value.split(' ');
  3288. i = value.length;
  3289. while (i--) {
  3290. if (value[i] !== value[0]) {
  3291. return false;
  3292. }
  3293. }
  3294. styles[key] = value[0];
  3295. return true;
  3296. };
  3297. const compress2 = (target, a, b, c) => {
  3298. if (!canCompress(a)) {
  3299. return;
  3300. }
  3301. if (!canCompress(b)) {
  3302. return;
  3303. }
  3304. if (!canCompress(c)) {
  3305. return;
  3306. }
  3307. styles[target] = styles[a] + ' ' + styles[b] + ' ' + styles[c];
  3308. delete styles[a];
  3309. delete styles[b];
  3310. delete styles[c];
  3311. };
  3312. const encode = str => {
  3313. isEncoded = true;
  3314. return encodingLookup[str];
  3315. };
  3316. const decode = (str, keepSlashes) => {
  3317. if (isEncoded) {
  3318. str = str.replace(/\uFEFF[0-9]/g, str => {
  3319. return encodingLookup[str];
  3320. });
  3321. }
  3322. if (!keepSlashes) {
  3323. str = str.replace(/\\([\'\";:])/g, '$1');
  3324. }
  3325. return str;
  3326. };
  3327. const decodeSingleHexSequence = escSeq => {
  3328. return String.fromCharCode(parseInt(escSeq.slice(1), 16));
  3329. };
  3330. const decodeHexSequences = value => {
  3331. return value.replace(/\\[0-9a-f]+/gi, decodeSingleHexSequence);
  3332. };
  3333. const processUrl = (match, url, url2, url3, str, str2) => {
  3334. str = str || str2;
  3335. if (str) {
  3336. str = decode(str);
  3337. return `'` + str.replace(/\'/g, `\\'`) + `'`;
  3338. }
  3339. url = decode(url || url2 || url3);
  3340. if (!settings.allow_script_urls) {
  3341. const scriptUrl = url.replace(/[\s\r\n]+/g, '');
  3342. if (/(java|vb)script:/i.test(scriptUrl)) {
  3343. return '';
  3344. }
  3345. if (!settings.allow_svg_data_urls && /^data:image\/svg/i.test(scriptUrl)) {
  3346. return '';
  3347. }
  3348. }
  3349. if (urlConverter) {
  3350. url = urlConverter.call(urlConverterScope, url, 'style');
  3351. }
  3352. return `url('` + url.replace(/\'/g, `\\'`) + `')`;
  3353. };
  3354. if (css) {
  3355. css = css.replace(/[\u0000-\u001F]/g, '');
  3356. css = css.replace(/\\[\"\';:\uFEFF]/g, encode).replace(/\"[^\"]+\"|\'[^\']+\'/g, str => {
  3357. return str.replace(/[;:]/g, encode);
  3358. });
  3359. while (matches = styleRegExp.exec(css)) {
  3360. styleRegExp.lastIndex = matches.index + matches[0].length;
  3361. name = matches[1].replace(trimRightRegExp, '').toLowerCase();
  3362. value = matches[2].replace(trimRightRegExp, '');
  3363. if (name && value) {
  3364. name = decodeHexSequences(name);
  3365. value = decodeHexSequences(value);
  3366. if (name.indexOf(invisibleChar) !== -1 || name.indexOf('"') !== -1) {
  3367. continue;
  3368. }
  3369. if (!settings.allow_script_urls && (name === 'behavior' || /expression\s*\(|\/\*|\*\//.test(value))) {
  3370. continue;
  3371. }
  3372. if (name === 'font-weight' && value === '700') {
  3373. value = 'bold';
  3374. } else if (name === 'color' || name === 'background-color') {
  3375. value = value.toLowerCase();
  3376. }
  3377. value = value.replace(urlOrStrRegExp, processUrl);
  3378. styles[name] = isEncoded ? decode(value, true) : value;
  3379. }
  3380. }
  3381. compress('border', '', true);
  3382. compress('border', '-width');
  3383. compress('border', '-color');
  3384. compress('border', '-style');
  3385. compress('padding', '');
  3386. compress('margin', '');
  3387. compress2('border', 'border-width', 'border-style', 'border-color');
  3388. if (styles.border === 'medium none') {
  3389. delete styles.border;
  3390. }
  3391. if (styles['border-image'] === 'none') {
  3392. delete styles['border-image'];
  3393. }
  3394. }
  3395. return styles;
  3396. },
  3397. serialize: (styles, elementName) => {
  3398. let css = '';
  3399. const serializeStyles = name => {
  3400. let value;
  3401. const styleList = validStyles[name];
  3402. if (styleList) {
  3403. for (let i = 0, l = styleList.length; i < l; i++) {
  3404. name = styleList[i];
  3405. value = styles[name];
  3406. if (value) {
  3407. css += (css.length > 0 ? ' ' : '') + name + ': ' + value + ';';
  3408. }
  3409. }
  3410. }
  3411. };
  3412. const isValid = (name, elementName) => {
  3413. let styleMap = invalidStyles['*'];
  3414. if (styleMap && styleMap[name]) {
  3415. return false;
  3416. }
  3417. styleMap = invalidStyles[elementName];
  3418. return !(styleMap && styleMap[name]);
  3419. };
  3420. if (elementName && validStyles) {
  3421. serializeStyles('*');
  3422. serializeStyles(elementName);
  3423. } else {
  3424. each$e(styles, (value, name) => {
  3425. if (value && (!invalidStyles || isValid(name, elementName))) {
  3426. css += (css.length > 0 ? ' ' : '') + name + ': ' + value + ';';
  3427. }
  3428. });
  3429. }
  3430. return css;
  3431. }
  3432. };
  3433. return self;
  3434. };
  3435. const deprecated = {
  3436. keyLocation: true,
  3437. layerX: true,
  3438. layerY: true,
  3439. returnValue: true,
  3440. webkitMovementX: true,
  3441. webkitMovementY: true,
  3442. keyIdentifier: true,
  3443. mozPressure: true
  3444. };
  3445. const isNativeEvent = event => event instanceof Event || isFunction(event.initEvent);
  3446. const hasIsDefaultPrevented = event => event.isDefaultPrevented === always || event.isDefaultPrevented === never;
  3447. const needsNormalizing = event => isNullable(event.preventDefault) || isNativeEvent(event);
  3448. const clone$3 = (originalEvent, data) => {
  3449. const event = data !== null && data !== void 0 ? data : {};
  3450. for (const name in originalEvent) {
  3451. if (!has$2(deprecated, name)) {
  3452. event[name] = originalEvent[name];
  3453. }
  3454. }
  3455. if (isNonNullable(event.composedPath)) {
  3456. event.composedPath = () => originalEvent.composedPath();
  3457. }
  3458. return event;
  3459. };
  3460. const normalize$3 = (type, originalEvent, fallbackTarget, data) => {
  3461. var _a;
  3462. const event = clone$3(originalEvent, data);
  3463. event.type = type;
  3464. if (isNullable(event.target)) {
  3465. event.target = (_a = event.srcElement) !== null && _a !== void 0 ? _a : fallbackTarget;
  3466. }
  3467. if (needsNormalizing(originalEvent)) {
  3468. event.preventDefault = () => {
  3469. event.defaultPrevented = true;
  3470. event.isDefaultPrevented = always;
  3471. if (isFunction(originalEvent.preventDefault)) {
  3472. originalEvent.preventDefault();
  3473. }
  3474. };
  3475. event.stopPropagation = () => {
  3476. event.cancelBubble = true;
  3477. event.isPropagationStopped = always;
  3478. if (isFunction(originalEvent.stopPropagation)) {
  3479. originalEvent.stopPropagation();
  3480. }
  3481. };
  3482. event.stopImmediatePropagation = () => {
  3483. event.isImmediatePropagationStopped = always;
  3484. event.stopPropagation();
  3485. };
  3486. if (!hasIsDefaultPrevented(event)) {
  3487. event.isDefaultPrevented = event.defaultPrevented === true ? always : never;
  3488. event.isPropagationStopped = event.cancelBubble === true ? always : never;
  3489. event.isImmediatePropagationStopped = never;
  3490. }
  3491. }
  3492. return event;
  3493. };
  3494. const eventExpandoPrefix = 'mce-data-';
  3495. const mouseEventRe = /^(?:mouse|contextmenu)|click/;
  3496. const addEvent = (target, name, callback, capture) => {
  3497. if (target.addEventListener) {
  3498. target.addEventListener(name, callback, capture || false);
  3499. } else if (target.attachEvent) {
  3500. target.attachEvent('on' + name, callback);
  3501. }
  3502. };
  3503. const removeEvent = (target, name, callback, capture) => {
  3504. if (target.removeEventListener) {
  3505. target.removeEventListener(name, callback, capture || false);
  3506. } else if (target.detachEvent) {
  3507. target.detachEvent('on' + name, callback);
  3508. }
  3509. };
  3510. const isMouseEvent = event => isNonNullable(event) && mouseEventRe.test(event.type);
  3511. const fix = (originalEvent, data) => {
  3512. const event = normalize$3(originalEvent.type, originalEvent, document, data);
  3513. if (isMouseEvent(originalEvent) && isUndefined(originalEvent.pageX) && !isUndefined(originalEvent.clientX)) {
  3514. const eventDoc = event.target.ownerDocument || document;
  3515. const doc = eventDoc.documentElement;
  3516. const body = eventDoc.body;
  3517. const mouseEvent = event;
  3518. mouseEvent.pageX = originalEvent.clientX + (doc && doc.scrollLeft || body && body.scrollLeft || 0) - (doc && doc.clientLeft || body && body.clientLeft || 0);
  3519. mouseEvent.pageY = originalEvent.clientY + (doc && doc.scrollTop || body && body.scrollTop || 0) - (doc && doc.clientTop || body && body.clientTop || 0);
  3520. }
  3521. return event;
  3522. };
  3523. const bindOnReady = (win, callback, eventUtils) => {
  3524. const doc = win.document, event = { type: 'ready' };
  3525. if (eventUtils.domLoaded) {
  3526. callback(event);
  3527. return;
  3528. }
  3529. const isDocReady = () => {
  3530. return doc.readyState === 'complete' || doc.readyState === 'interactive' && doc.body;
  3531. };
  3532. const readyHandler = () => {
  3533. removeEvent(win, 'DOMContentLoaded', readyHandler);
  3534. removeEvent(win, 'load', readyHandler);
  3535. if (!eventUtils.domLoaded) {
  3536. eventUtils.domLoaded = true;
  3537. callback(event);
  3538. }
  3539. win = null;
  3540. };
  3541. if (isDocReady()) {
  3542. readyHandler();
  3543. } else {
  3544. addEvent(win, 'DOMContentLoaded', readyHandler);
  3545. }
  3546. if (!eventUtils.domLoaded) {
  3547. addEvent(win, 'load', readyHandler);
  3548. }
  3549. };
  3550. class EventUtils {
  3551. constructor() {
  3552. this.domLoaded = false;
  3553. this.events = {};
  3554. this.count = 1;
  3555. this.expando = eventExpandoPrefix + (+new Date()).toString(32);
  3556. this.hasMouseEnterLeave = 'onmouseenter' in document.documentElement;
  3557. this.hasFocusIn = 'onfocusin' in document.documentElement;
  3558. this.count = 1;
  3559. }
  3560. bind(target, names, callback, scope) {
  3561. const self = this;
  3562. let id, callbackList, i, name, fakeName, nativeHandler, capture;
  3563. const win = window;
  3564. const defaultNativeHandler = evt => {
  3565. self.executeHandlers(fix(evt || win.event), id);
  3566. };
  3567. if (!target || target.nodeType === 3 || target.nodeType === 8) {
  3568. return;
  3569. }
  3570. if (!target[self.expando]) {
  3571. id = self.count++;
  3572. target[self.expando] = id;
  3573. self.events[id] = {};
  3574. } else {
  3575. id = target[self.expando];
  3576. }
  3577. scope = scope || target;
  3578. const namesList = names.split(' ');
  3579. i = namesList.length;
  3580. while (i--) {
  3581. name = namesList[i];
  3582. nativeHandler = defaultNativeHandler;
  3583. fakeName = capture = false;
  3584. if (name === 'DOMContentLoaded') {
  3585. name = 'ready';
  3586. }
  3587. if (self.domLoaded && name === 'ready' && target.readyState === 'complete') {
  3588. callback.call(scope, fix({ type: name }));
  3589. continue;
  3590. }
  3591. if (!self.hasMouseEnterLeave) {
  3592. fakeName = self.mouseEnterLeave[name];
  3593. if (fakeName) {
  3594. nativeHandler = evt => {
  3595. const current = evt.currentTarget;
  3596. let related = evt.relatedTarget;
  3597. if (related && current.contains) {
  3598. related = current.contains(related);
  3599. } else {
  3600. while (related && related !== current) {
  3601. related = related.parentNode;
  3602. }
  3603. }
  3604. if (!related) {
  3605. evt = fix(evt || win.event);
  3606. evt.type = evt.type === 'mouseout' ? 'mouseleave' : 'mouseenter';
  3607. evt.target = current;
  3608. self.executeHandlers(evt, id);
  3609. }
  3610. };
  3611. }
  3612. }
  3613. if (!self.hasFocusIn && (name === 'focusin' || name === 'focusout')) {
  3614. capture = true;
  3615. fakeName = name === 'focusin' ? 'focus' : 'blur';
  3616. nativeHandler = evt => {
  3617. evt = fix(evt || win.event);
  3618. evt.type = evt.type === 'focus' ? 'focusin' : 'focusout';
  3619. self.executeHandlers(evt, id);
  3620. };
  3621. }
  3622. callbackList = self.events[id][name];
  3623. if (!callbackList) {
  3624. self.events[id][name] = callbackList = [{
  3625. func: callback,
  3626. scope
  3627. }];
  3628. callbackList.fakeName = fakeName;
  3629. callbackList.capture = capture;
  3630. callbackList.nativeHandler = nativeHandler;
  3631. if (name === 'ready') {
  3632. bindOnReady(target, nativeHandler, self);
  3633. } else {
  3634. addEvent(target, fakeName || name, nativeHandler, capture);
  3635. }
  3636. } else {
  3637. if (name === 'ready' && self.domLoaded) {
  3638. callback(fix({ type: name }));
  3639. } else {
  3640. callbackList.push({
  3641. func: callback,
  3642. scope
  3643. });
  3644. }
  3645. }
  3646. }
  3647. target = callbackList = null;
  3648. return callback;
  3649. }
  3650. unbind(target, names, callback) {
  3651. let callbackList, i, ci, name, eventMap;
  3652. if (!target || target.nodeType === 3 || target.nodeType === 8) {
  3653. return this;
  3654. }
  3655. const id = target[this.expando];
  3656. if (id) {
  3657. eventMap = this.events[id];
  3658. if (names) {
  3659. const namesList = names.split(' ');
  3660. i = namesList.length;
  3661. while (i--) {
  3662. name = namesList[i];
  3663. callbackList = eventMap[name];
  3664. if (callbackList) {
  3665. if (callback) {
  3666. ci = callbackList.length;
  3667. while (ci--) {
  3668. if (callbackList[ci].func === callback) {
  3669. const nativeHandler = callbackList.nativeHandler;
  3670. const fakeName = callbackList.fakeName, capture = callbackList.capture;
  3671. callbackList = callbackList.slice(0, ci).concat(callbackList.slice(ci + 1));
  3672. callbackList.nativeHandler = nativeHandler;
  3673. callbackList.fakeName = fakeName;
  3674. callbackList.capture = capture;
  3675. eventMap[name] = callbackList;
  3676. }
  3677. }
  3678. }
  3679. if (!callback || callbackList.length === 0) {
  3680. delete eventMap[name];
  3681. removeEvent(target, callbackList.fakeName || name, callbackList.nativeHandler, callbackList.capture);
  3682. }
  3683. }
  3684. }
  3685. } else {
  3686. each$e(eventMap, (callbackList, name) => {
  3687. removeEvent(target, callbackList.fakeName || name, callbackList.nativeHandler, callbackList.capture);
  3688. });
  3689. eventMap = {};
  3690. }
  3691. for (name in eventMap) {
  3692. if (has$2(eventMap, name)) {
  3693. return this;
  3694. }
  3695. }
  3696. delete this.events[id];
  3697. try {
  3698. delete target[this.expando];
  3699. } catch (ex) {
  3700. target[this.expando] = null;
  3701. }
  3702. }
  3703. return this;
  3704. }
  3705. fire(target, name, args) {
  3706. return this.dispatch(target, name, args);
  3707. }
  3708. dispatch(target, name, args) {
  3709. let id;
  3710. if (!target || target.nodeType === 3 || target.nodeType === 8) {
  3711. return this;
  3712. }
  3713. const event = fix({
  3714. type: name,
  3715. target
  3716. }, args);
  3717. do {
  3718. id = target[this.expando];
  3719. if (id) {
  3720. this.executeHandlers(event, id);
  3721. }
  3722. target = target.parentNode || target.ownerDocument || target.defaultView || target.parentWindow;
  3723. } while (target && !event.isPropagationStopped());
  3724. return this;
  3725. }
  3726. clean(target) {
  3727. let i, children;
  3728. if (!target || target.nodeType === 3 || target.nodeType === 8) {
  3729. return this;
  3730. }
  3731. if (target[this.expando]) {
  3732. this.unbind(target);
  3733. }
  3734. if (!target.getElementsByTagName) {
  3735. target = target.document;
  3736. }
  3737. if (target && target.getElementsByTagName) {
  3738. this.unbind(target);
  3739. children = target.getElementsByTagName('*');
  3740. i = children.length;
  3741. while (i--) {
  3742. target = children[i];
  3743. if (target[this.expando]) {
  3744. this.unbind(target);
  3745. }
  3746. }
  3747. }
  3748. return this;
  3749. }
  3750. destroy() {
  3751. this.events = {};
  3752. }
  3753. cancel(e) {
  3754. if (e) {
  3755. e.preventDefault();
  3756. e.stopImmediatePropagation();
  3757. }
  3758. return false;
  3759. }
  3760. executeHandlers(evt, id) {
  3761. const container = this.events[id];
  3762. const callbackList = container && container[evt.type];
  3763. if (callbackList) {
  3764. for (let i = 0, l = callbackList.length; i < l; i++) {
  3765. const callback = callbackList[i];
  3766. if (callback && callback.func.call(callback.scope, evt) === false) {
  3767. evt.preventDefault();
  3768. }
  3769. if (evt.isImmediatePropagationStopped()) {
  3770. return;
  3771. }
  3772. }
  3773. }
  3774. }
  3775. }
  3776. EventUtils.Event = new EventUtils();
  3777. const each$b = Tools.each;
  3778. const grep = Tools.grep;
  3779. const internalStyleName = 'data-mce-style';
  3780. const legacySetAttribute = (elm, name, value) => {
  3781. if (isNullable(value) || value === '') {
  3782. remove$b(elm, name);
  3783. } else {
  3784. set$2(elm, name, value);
  3785. }
  3786. };
  3787. const setupAttrHooks = (styles, settings, getContext) => {
  3788. const keepValues = settings.keep_values;
  3789. const keepUrlHook = {
  3790. set: (elm, value, name) => {
  3791. const sugarElm = SugarElement.fromDom(elm);
  3792. if (isFunction(settings.url_converter) && isNonNullable(value)) {
  3793. value = settings.url_converter.call(settings.url_converter_scope || getContext(), value, name, elm[0]);
  3794. }
  3795. const internalName = 'data-mce-' + name;
  3796. legacySetAttribute(sugarElm, internalName, value);
  3797. legacySetAttribute(sugarElm, name, value);
  3798. },
  3799. get: (elm, name) => {
  3800. const sugarElm = SugarElement.fromDom(elm);
  3801. return get$9(sugarElm, 'data-mce-' + name) || get$9(sugarElm, name);
  3802. }
  3803. };
  3804. const attrHooks = {
  3805. style: {
  3806. set: (elm, value) => {
  3807. const sugarElm = SugarElement.fromDom(elm);
  3808. if (isObject(value)) {
  3809. setAll(sugarElm, value);
  3810. return;
  3811. }
  3812. if (keepValues) {
  3813. legacySetAttribute(sugarElm, internalStyleName, value);
  3814. }
  3815. remove$b(sugarElm, 'style');
  3816. if (isString(value)) {
  3817. setAll(sugarElm, styles.parse(value));
  3818. }
  3819. },
  3820. get: elm => {
  3821. const sugarElm = SugarElement.fromDom(elm);
  3822. const value = get$9(sugarElm, internalStyleName) || get$9(sugarElm, 'style');
  3823. return styles.serialize(styles.parse(value), name(sugarElm));
  3824. }
  3825. }
  3826. };
  3827. if (keepValues) {
  3828. attrHooks.href = attrHooks.src = keepUrlHook;
  3829. }
  3830. return attrHooks;
  3831. };
  3832. const updateInternalStyleAttr = (styles, elm) => {
  3833. const rawValue = get$9(elm, 'style');
  3834. const value = styles.serialize(styles.parse(rawValue), name(elm));
  3835. legacySetAttribute(elm, internalStyleName, value);
  3836. };
  3837. const findNodeIndex = (node, normalized) => {
  3838. let idx = 0, lastNodeType, nodeType;
  3839. if (node) {
  3840. for (lastNodeType = node.nodeType, node = node.previousSibling; node; node = node.previousSibling) {
  3841. nodeType = node.nodeType;
  3842. if (normalized && nodeType === 3) {
  3843. if (nodeType === lastNodeType || !node.nodeValue.length) {
  3844. continue;
  3845. }
  3846. }
  3847. idx++;
  3848. lastNodeType = nodeType;
  3849. }
  3850. }
  3851. return idx;
  3852. };
  3853. const numericalCssMap = Tools.makeMap('fill-opacity font-weight line-height opacity orphans widows z-index zoom', ' ');
  3854. const camelCaseToHyphens = name => name.replace(/[A-Z]/g, v => '-' + v.toLowerCase());
  3855. const DOMUtils = (doc, settings = {}) => {
  3856. const addedStyles = {};
  3857. const win = window;
  3858. const files = {};
  3859. let counter = 0;
  3860. const stdMode = true;
  3861. const boxModel = true;
  3862. const styleSheetLoader = instance.forElement(SugarElement.fromDom(doc), {
  3863. contentCssCors: settings.contentCssCors,
  3864. referrerPolicy: settings.referrerPolicy
  3865. });
  3866. const boundEvents = [];
  3867. const schema = settings.schema ? settings.schema : Schema({});
  3868. const styles = Styles({
  3869. url_converter: settings.url_converter,
  3870. url_converter_scope: settings.url_converter_scope
  3871. }, settings.schema);
  3872. const events = settings.ownEvents ? new EventUtils() : EventUtils.Event;
  3873. const blockElementsMap = schema.getBlockElements();
  3874. const isBlock = node => {
  3875. if (isString(node)) {
  3876. return has$2(blockElementsMap, node);
  3877. } else {
  3878. return isElement$6(node) && has$2(blockElementsMap, node.nodeName);
  3879. }
  3880. };
  3881. const get = elm => elm && doc && isString(elm) ? doc.getElementById(elm) : elm;
  3882. const _get = elm => {
  3883. const value = get(elm);
  3884. return isNonNullable(value) ? SugarElement.fromDom(value) : null;
  3885. };
  3886. const getAttrib = (elm, name, defaultVal) => {
  3887. let value;
  3888. const $elm = _get(elm);
  3889. if (isNonNullable($elm) && isElement$7($elm)) {
  3890. const hook = attrHooks[name];
  3891. if (hook && hook.get) {
  3892. value = hook.get($elm.dom, name);
  3893. } else {
  3894. value = get$9($elm, name);
  3895. }
  3896. }
  3897. return isNonNullable(value) ? value : defaultVal !== null && defaultVal !== void 0 ? defaultVal : '';
  3898. };
  3899. const getAttribs = elm => {
  3900. const node = get(elm);
  3901. return isNullable(node) ? [] : node.attributes;
  3902. };
  3903. const setAttrib = (elm, name, value) => {
  3904. run(elm, e => {
  3905. if (isElement$6(e)) {
  3906. const $elm = SugarElement.fromDom(e);
  3907. if (value === '') {
  3908. value = null;
  3909. }
  3910. const originalValue = get$9($elm, name);
  3911. const hook = attrHooks[name];
  3912. if (hook && hook.set) {
  3913. hook.set($elm.dom, value, name);
  3914. } else {
  3915. legacySetAttribute($elm, name, value);
  3916. }
  3917. if (originalValue !== value && settings.onSetAttrib) {
  3918. settings.onSetAttrib({
  3919. attrElm: $elm,
  3920. attrName: name,
  3921. attrValue: value
  3922. });
  3923. }
  3924. }
  3925. });
  3926. };
  3927. const clone = (node, deep) => {
  3928. return node.cloneNode(deep);
  3929. };
  3930. const getRoot = () => settings.root_element || doc.body;
  3931. const getViewPort = argWin => {
  3932. const vp = getBounds(argWin);
  3933. return {
  3934. x: vp.x,
  3935. y: vp.y,
  3936. w: vp.width,
  3937. h: vp.height
  3938. };
  3939. };
  3940. const getPos$1 = (elm, rootElm) => getPos(doc.body, get(elm), rootElm);
  3941. const setStyle = (elm, name, value) => {
  3942. const convertStyleToString = (cssValue, cssName) => {
  3943. if (isString(cssValue)) {
  3944. return cssValue;
  3945. } else if (isNumber(cssValue)) {
  3946. return has$2(numericalCssMap, cssName) ? cssValue + '' : cssValue + 'px';
  3947. } else {
  3948. return map$2(cssValue, convertStyleToString);
  3949. }
  3950. };
  3951. const applyStyle = ($elm, cssName, cssValue) => {
  3952. const normalizedName = camelCaseToHyphens(cssName);
  3953. if (isNullable(cssValue) || cssValue === '') {
  3954. remove$7($elm, normalizedName);
  3955. } else {
  3956. set$1($elm, normalizedName, convertStyleToString(cssValue, normalizedName));
  3957. }
  3958. };
  3959. run(elm, e => {
  3960. const $elm = SugarElement.fromDom(e);
  3961. if (isString(name)) {
  3962. applyStyle($elm, name, value);
  3963. } else {
  3964. each$e(name, (v, n) => {
  3965. applyStyle($elm, n, v);
  3966. });
  3967. }
  3968. if (settings.update_styles) {
  3969. updateInternalStyleAttr(styles, $elm);
  3970. }
  3971. });
  3972. };
  3973. const setStyles = (elm, stylesArg) => {
  3974. setStyle(elm, stylesArg);
  3975. };
  3976. const getStyle = (elm, name, computed) => {
  3977. const $elm = get(elm);
  3978. if (isNullable($elm) || !isElement$6($elm)) {
  3979. return undefined;
  3980. }
  3981. if (computed) {
  3982. return get$7(SugarElement.fromDom($elm), camelCaseToHyphens(name));
  3983. } else {
  3984. name = name.replace(/-(\D)/g, (a, b) => b.toUpperCase());
  3985. if (name === 'float') {
  3986. name = 'cssFloat';
  3987. }
  3988. return $elm.style ? $elm.style[name] : undefined;
  3989. }
  3990. };
  3991. const getSize = elm => {
  3992. let w, h;
  3993. const $elm = get(elm);
  3994. w = getStyle($elm, 'width');
  3995. h = getStyle($elm, 'height');
  3996. if (w.indexOf('px') === -1) {
  3997. w = 0;
  3998. }
  3999. if (h.indexOf('px') === -1) {
  4000. h = 0;
  4001. }
  4002. return {
  4003. w: parseInt(w, 10) || $elm.offsetWidth || $elm.clientWidth,
  4004. h: parseInt(h, 10) || $elm.offsetHeight || $elm.clientHeight
  4005. };
  4006. };
  4007. const getRect = elm => {
  4008. const $elm = get(elm);
  4009. const pos = getPos$1($elm);
  4010. const size = getSize($elm);
  4011. return {
  4012. x: pos.x,
  4013. y: pos.y,
  4014. w: size.w,
  4015. h: size.h
  4016. };
  4017. };
  4018. const is = (elm, selector) => {
  4019. if (!elm) {
  4020. return false;
  4021. }
  4022. const elms = isArray$1(elm) ? elm : [elm];
  4023. return exists(elms, e => {
  4024. return is$1(SugarElement.fromDom(e), selector);
  4025. });
  4026. };
  4027. const getParents = (elm, selector, root, collect) => {
  4028. const result = [];
  4029. let selectorVal;
  4030. let node = get(elm);
  4031. collect = collect === undefined;
  4032. root = root || (getRoot().nodeName !== 'BODY' ? getRoot().parentNode : null);
  4033. if (isString(selector)) {
  4034. selectorVal = selector;
  4035. if (selector === '*') {
  4036. selector = isElement$6;
  4037. } else {
  4038. selector = node => is(node, selectorVal);
  4039. }
  4040. }
  4041. while (node) {
  4042. if (node === root || isNullable(node.nodeType) || isDocument$1(node) || isDocumentFragment(node)) {
  4043. break;
  4044. }
  4045. if (!selector || selector(node)) {
  4046. if (collect) {
  4047. result.push(node);
  4048. } else {
  4049. return [node];
  4050. }
  4051. }
  4052. node = node.parentNode;
  4053. }
  4054. return collect ? result : null;
  4055. };
  4056. const getParent = (node, selector, root) => {
  4057. const parents = getParents(node, selector, root, false);
  4058. return parents && parents.length > 0 ? parents[0] : null;
  4059. };
  4060. const _findSib = (node, selector, name) => {
  4061. let func = selector;
  4062. if (node) {
  4063. if (isString(selector)) {
  4064. func = node => {
  4065. return is(node, selector);
  4066. };
  4067. }
  4068. for (node = node[name]; node; node = node[name]) {
  4069. if (isFunction(func) && func(node)) {
  4070. return node;
  4071. }
  4072. }
  4073. }
  4074. return null;
  4075. };
  4076. const getNext = (node, selector) => _findSib(node, selector, 'nextSibling');
  4077. const getPrev = (node, selector) => _findSib(node, selector, 'previousSibling');
  4078. const select = (selector, scope) => {
  4079. var _a, _b;
  4080. const elm = (_b = (_a = get(scope)) !== null && _a !== void 0 ? _a : settings.root_element) !== null && _b !== void 0 ? _b : doc;
  4081. return from(elm.querySelectorAll(selector));
  4082. };
  4083. const run = function (elm, func, scope) {
  4084. const context = scope !== null && scope !== void 0 ? scope : this;
  4085. const node = isString(elm) ? get(elm) : elm;
  4086. if (!node) {
  4087. return false;
  4088. }
  4089. if (isArray$1(node) && (node.length || node.length === 0)) {
  4090. const result = [];
  4091. each$b(node, (elm, i) => {
  4092. if (elm) {
  4093. result.push(func.call(context, isString(elm) ? get(elm) : elm, i));
  4094. }
  4095. });
  4096. return result;
  4097. } else {
  4098. return func.call(context, node);
  4099. }
  4100. };
  4101. const setAttribs = (elm, attrs) => {
  4102. run(elm, $elm => {
  4103. each$e(attrs, (value, name) => {
  4104. setAttrib($elm, name, value);
  4105. });
  4106. });
  4107. };
  4108. const setHTML = (elm, html) => {
  4109. run(elm, e => {
  4110. const $elm = SugarElement.fromDom(e);
  4111. set($elm, html);
  4112. });
  4113. };
  4114. const add = (parentElm, name, attrs, html, create) => run(parentElm, parentElm => {
  4115. const newElm = isString(name) ? doc.createElement(name) : name;
  4116. if (isNonNullable(attrs)) {
  4117. setAttribs(newElm, attrs);
  4118. }
  4119. if (html) {
  4120. if (!isString(html) && html.nodeType) {
  4121. newElm.appendChild(html);
  4122. } else if (isString(html)) {
  4123. setHTML(newElm, html);
  4124. }
  4125. }
  4126. return !create ? parentElm.appendChild(newElm) : newElm;
  4127. });
  4128. const create = (name, attrs, html) => add(doc.createElement(name), name, attrs, html, true);
  4129. const decode = Entities.decode;
  4130. const encode = Entities.encodeAllRaw;
  4131. const createHTML = (name, attrs, html = '') => {
  4132. let outHtml = '', key;
  4133. outHtml += '<' + name;
  4134. for (key in attrs) {
  4135. if (hasNonNullableKey(attrs, key)) {
  4136. outHtml += ' ' + key + '="' + encode(attrs[key]) + '"';
  4137. }
  4138. }
  4139. if (isEmpty$3(html) && has$2(schema.getVoidElements(), name)) {
  4140. return outHtml + ' />';
  4141. } else {
  4142. return outHtml + '>' + html + '</' + name + '>';
  4143. }
  4144. };
  4145. const createFragment = html => {
  4146. let node;
  4147. const container = doc.createElement('div');
  4148. const frag = doc.createDocumentFragment();
  4149. frag.appendChild(container);
  4150. if (html) {
  4151. container.innerHTML = html;
  4152. }
  4153. while (node = container.firstChild) {
  4154. frag.appendChild(node);
  4155. }
  4156. frag.removeChild(container);
  4157. return frag;
  4158. };
  4159. const remove = (node, keepChildren) => {
  4160. return run(node, n => {
  4161. const $node = SugarElement.fromDom(n);
  4162. if (keepChildren) {
  4163. each$f(children($node), child => {
  4164. if (isText$a(child) && child.dom.length === 0) {
  4165. remove$6(child);
  4166. } else {
  4167. before$3($node, child);
  4168. }
  4169. });
  4170. }
  4171. remove$6($node);
  4172. return $node.dom;
  4173. });
  4174. };
  4175. const removeAllAttribs = e => run(e, e => {
  4176. const attrs = e.attributes;
  4177. for (let i = attrs.length - 1; i >= 0; i--) {
  4178. e.removeAttributeNode(attrs.item(i));
  4179. }
  4180. });
  4181. const parseStyle = cssText => styles.parse(cssText);
  4182. const serializeStyle = (stylesArg, name) => styles.serialize(stylesArg, name);
  4183. const addStyle = cssText => {
  4184. let head, styleElm;
  4185. if (self !== DOMUtils.DOM && doc === document) {
  4186. if (addedStyles[cssText]) {
  4187. return;
  4188. }
  4189. addedStyles[cssText] = true;
  4190. }
  4191. styleElm = doc.getElementById('mceDefaultStyles');
  4192. if (!styleElm) {
  4193. styleElm = doc.createElement('style');
  4194. styleElm.id = 'mceDefaultStyles';
  4195. styleElm.type = 'text/css';
  4196. head = doc.getElementsByTagName('head')[0];
  4197. if (head.firstChild) {
  4198. head.insertBefore(styleElm, head.firstChild);
  4199. } else {
  4200. head.appendChild(styleElm);
  4201. }
  4202. }
  4203. if (styleElm.styleSheet) {
  4204. styleElm.styleSheet.cssText += cssText;
  4205. } else {
  4206. styleElm.appendChild(doc.createTextNode(cssText));
  4207. }
  4208. };
  4209. const loadCSS = urls => {
  4210. if (!urls) {
  4211. urls = '';
  4212. }
  4213. each$f(urls.split(','), url => {
  4214. files[url] = true;
  4215. styleSheetLoader.load(url).catch(noop);
  4216. });
  4217. };
  4218. const toggleClass = (elm, cls, state) => {
  4219. run(elm, e => {
  4220. if (isElement$6(e)) {
  4221. const $elm = SugarElement.fromDom(e);
  4222. const classes = cls.split(' ');
  4223. each$f(classes, c => {
  4224. if (isNonNullable(state)) {
  4225. const fn = state ? add$2 : remove$8;
  4226. fn($elm, c);
  4227. } else {
  4228. toggle$1($elm, c);
  4229. }
  4230. });
  4231. }
  4232. });
  4233. };
  4234. const addClass = (elm, cls) => {
  4235. toggleClass(elm, cls, true);
  4236. };
  4237. const removeClass = (elm, cls) => {
  4238. toggleClass(elm, cls, false);
  4239. };
  4240. const hasClass = (elm, cls) => {
  4241. const $elm = _get(elm);
  4242. const classes = cls.split(' ');
  4243. return forall(classes, c => has($elm, c));
  4244. };
  4245. const show = elm => {
  4246. run(elm, e => remove$7(SugarElement.fromDom(e), 'display'));
  4247. };
  4248. const hide = elm => {
  4249. run(elm, e => set$1(SugarElement.fromDom(e), 'display', 'none'));
  4250. };
  4251. const isHidden = elm => {
  4252. const $elm = _get(elm);
  4253. return is$2(getRaw$1($elm, 'display'), 'none');
  4254. };
  4255. const uniqueId = prefix => (!prefix ? 'mce_' : prefix) + counter++;
  4256. const getOuterHTML = elm => {
  4257. const $elm = _get(elm);
  4258. return isElement$6($elm.dom) ? $elm.dom.outerHTML : getOuter($elm);
  4259. };
  4260. const setOuterHTML = (elm, html) => {
  4261. run(elm, $elm => {
  4262. if (isElement$6($elm)) {
  4263. $elm.outerHTML = html;
  4264. }
  4265. });
  4266. };
  4267. const insertAfter = (node, reference) => {
  4268. const referenceNode = get(reference);
  4269. return run(node, node => {
  4270. const parent = referenceNode.parentNode;
  4271. const nextSibling = referenceNode.nextSibling;
  4272. if (nextSibling) {
  4273. parent.insertBefore(node, nextSibling);
  4274. } else {
  4275. parent.appendChild(node);
  4276. }
  4277. return node;
  4278. });
  4279. };
  4280. const replace = (newElm, oldElm, keepChildren) => run(oldElm, oldElm => {
  4281. if (isArray$1(oldElm)) {
  4282. newElm = newElm.cloneNode(true);
  4283. }
  4284. if (keepChildren) {
  4285. each$b(grep(oldElm.childNodes), node => {
  4286. newElm.appendChild(node);
  4287. });
  4288. }
  4289. return oldElm.parentNode.replaceChild(newElm, oldElm);
  4290. });
  4291. const rename = (elm, name) => {
  4292. let newElm;
  4293. if (elm.nodeName !== name.toUpperCase()) {
  4294. newElm = create(name);
  4295. each$b(getAttribs(elm), attrNode => {
  4296. setAttrib(newElm, attrNode.nodeName, getAttrib(elm, attrNode.nodeName));
  4297. });
  4298. replace(newElm, elm, true);
  4299. }
  4300. return newElm || elm;
  4301. };
  4302. const findCommonAncestor = (a, b) => {
  4303. let ps = a, pe;
  4304. while (ps) {
  4305. pe = b;
  4306. while (pe && ps !== pe) {
  4307. pe = pe.parentNode;
  4308. }
  4309. if (ps === pe) {
  4310. break;
  4311. }
  4312. ps = ps.parentNode;
  4313. }
  4314. if (!ps && a.ownerDocument) {
  4315. return a.ownerDocument.documentElement;
  4316. }
  4317. return ps;
  4318. };
  4319. const isNonEmptyElement = node => {
  4320. if (isElement$6(node)) {
  4321. const isNamedAnchor = node.nodeName.toLowerCase() === 'a' && !getAttrib(node, 'href') && getAttrib(node, 'id');
  4322. if (getAttrib(node, 'name') || getAttrib(node, 'data-mce-bookmark') || isNamedAnchor) {
  4323. return true;
  4324. }
  4325. }
  4326. return false;
  4327. };
  4328. const isEmpty = (node, elements) => {
  4329. let type, name, brCount = 0;
  4330. if (isNonEmptyElement(node)) {
  4331. return false;
  4332. }
  4333. node = node.firstChild;
  4334. if (node) {
  4335. const walker = new DomTreeWalker(node, node.parentNode);
  4336. const whitespace = schema ? schema.getWhitespaceElements() : {};
  4337. elements = elements || (schema ? schema.getNonEmptyElements() : null);
  4338. do {
  4339. type = node.nodeType;
  4340. if (isElement$6(node)) {
  4341. const bogusVal = node.getAttribute('data-mce-bogus');
  4342. if (bogusVal) {
  4343. node = walker.next(bogusVal === 'all');
  4344. continue;
  4345. }
  4346. name = node.nodeName.toLowerCase();
  4347. if (elements && elements[name]) {
  4348. if (name === 'br') {
  4349. brCount++;
  4350. node = walker.next();
  4351. continue;
  4352. }
  4353. return false;
  4354. }
  4355. if (isNonEmptyElement(node)) {
  4356. return false;
  4357. }
  4358. }
  4359. if (type === 8) {
  4360. return false;
  4361. }
  4362. if (type === 3 && !isWhitespaceText(node.nodeValue)) {
  4363. return false;
  4364. }
  4365. if (type === 3 && node.parentNode && whitespace[node.parentNode.nodeName] && isWhitespaceText(node.nodeValue)) {
  4366. return false;
  4367. }
  4368. node = walker.next();
  4369. } while (node);
  4370. }
  4371. return brCount <= 1;
  4372. };
  4373. const createRng = () => doc.createRange();
  4374. const split = (parentElm, splitElm, replacementElm) => {
  4375. let range = createRng();
  4376. let beforeFragment;
  4377. let afterFragment;
  4378. let parentNode;
  4379. if (parentElm && splitElm) {
  4380. range.setStart(parentElm.parentNode, findNodeIndex(parentElm));
  4381. range.setEnd(splitElm.parentNode, findNodeIndex(splitElm));
  4382. beforeFragment = range.extractContents();
  4383. range = createRng();
  4384. range.setStart(splitElm.parentNode, findNodeIndex(splitElm) + 1);
  4385. range.setEnd(parentElm.parentNode, findNodeIndex(parentElm) + 1);
  4386. afterFragment = range.extractContents();
  4387. parentNode = parentElm.parentNode;
  4388. parentNode.insertBefore(trimNode(self, beforeFragment), parentElm);
  4389. if (replacementElm) {
  4390. parentNode.insertBefore(replacementElm, parentElm);
  4391. } else {
  4392. parentNode.insertBefore(splitElm, parentElm);
  4393. }
  4394. parentNode.insertBefore(trimNode(self, afterFragment), parentElm);
  4395. remove(parentElm);
  4396. return replacementElm || splitElm;
  4397. }
  4398. };
  4399. const bind = (target, name, func, scope) => {
  4400. if (isArray$1(target)) {
  4401. let i = target.length;
  4402. const rv = [];
  4403. while (i--) {
  4404. rv[i] = bind(target[i], name, func, scope);
  4405. }
  4406. return rv;
  4407. } else {
  4408. if (settings.collect && (target === doc || target === win)) {
  4409. boundEvents.push([
  4410. target,
  4411. name,
  4412. func,
  4413. scope
  4414. ]);
  4415. }
  4416. return events.bind(target, name, func, scope || self);
  4417. }
  4418. };
  4419. const unbind = (target, name, func) => {
  4420. if (isArray$1(target)) {
  4421. let i = target.length;
  4422. const rv = [];
  4423. while (i--) {
  4424. rv[i] = unbind(target[i], name, func);
  4425. }
  4426. return rv;
  4427. } else {
  4428. if (boundEvents.length > 0 && (target === doc || target === win)) {
  4429. let i = boundEvents.length;
  4430. while (i--) {
  4431. const item = boundEvents[i];
  4432. if (target === item[0] && (!name || name === item[1]) && (!func || func === item[2])) {
  4433. events.unbind(item[0], item[1], item[2]);
  4434. }
  4435. }
  4436. }
  4437. return events.unbind(target, name, func);
  4438. }
  4439. };
  4440. const dispatch = (target, name, evt) => events.dispatch(target, name, evt);
  4441. const fire = (target, name, evt) => events.dispatch(target, name, evt);
  4442. const getContentEditable = node => {
  4443. if (node && isElement$6(node)) {
  4444. const contentEditable = node.getAttribute('data-mce-contenteditable');
  4445. if (contentEditable && contentEditable !== 'inherit') {
  4446. return contentEditable;
  4447. }
  4448. return node.contentEditable !== 'inherit' ? node.contentEditable : null;
  4449. } else {
  4450. return null;
  4451. }
  4452. };
  4453. const getContentEditableParent = node => {
  4454. const root = getRoot();
  4455. let state = null;
  4456. for (; node && node !== root; node = node.parentNode) {
  4457. state = getContentEditable(node);
  4458. if (state !== null) {
  4459. break;
  4460. }
  4461. }
  4462. return state;
  4463. };
  4464. const destroy = () => {
  4465. if (boundEvents.length > 0) {
  4466. let i = boundEvents.length;
  4467. while (i--) {
  4468. const item = boundEvents[i];
  4469. events.unbind(item[0], item[1], item[2]);
  4470. }
  4471. }
  4472. each$e(files, (_, url) => {
  4473. styleSheetLoader.unload(url);
  4474. delete files[url];
  4475. });
  4476. };
  4477. const isChildOf = (node, parent) => {
  4478. return node === parent || parent.contains(node);
  4479. };
  4480. const dumpRng = r => 'startContainer: ' + r.startContainer.nodeName + ', startOffset: ' + r.startOffset + ', endContainer: ' + r.endContainer.nodeName + ', endOffset: ' + r.endOffset;
  4481. const self = {
  4482. doc,
  4483. settings,
  4484. win,
  4485. files,
  4486. stdMode,
  4487. boxModel,
  4488. styleSheetLoader,
  4489. boundEvents,
  4490. styles,
  4491. schema,
  4492. events,
  4493. isBlock,
  4494. root: null,
  4495. clone,
  4496. getRoot,
  4497. getViewPort,
  4498. getRect,
  4499. getSize,
  4500. getParent,
  4501. getParents,
  4502. get,
  4503. getNext,
  4504. getPrev,
  4505. select,
  4506. is,
  4507. add,
  4508. create,
  4509. createHTML,
  4510. createFragment,
  4511. remove,
  4512. setStyle,
  4513. getStyle,
  4514. setStyles,
  4515. removeAllAttribs,
  4516. setAttrib,
  4517. setAttribs,
  4518. getAttrib,
  4519. getPos: getPos$1,
  4520. parseStyle,
  4521. serializeStyle,
  4522. addStyle,
  4523. loadCSS,
  4524. addClass,
  4525. removeClass,
  4526. hasClass,
  4527. toggleClass,
  4528. show,
  4529. hide,
  4530. isHidden,
  4531. uniqueId,
  4532. setHTML,
  4533. getOuterHTML,
  4534. setOuterHTML,
  4535. decode,
  4536. encode,
  4537. insertAfter,
  4538. replace,
  4539. rename,
  4540. findCommonAncestor,
  4541. run,
  4542. getAttribs,
  4543. isEmpty,
  4544. createRng,
  4545. nodeIndex: findNodeIndex,
  4546. split,
  4547. bind: bind,
  4548. unbind: unbind,
  4549. fire,
  4550. dispatch,
  4551. getContentEditable,
  4552. getContentEditableParent,
  4553. destroy,
  4554. isChildOf,
  4555. dumpRng
  4556. };
  4557. const attrHooks = setupAttrHooks(styles, settings, constant(self));
  4558. return self;
  4559. };
  4560. DOMUtils.DOM = DOMUtils(document);
  4561. DOMUtils.nodeIndex = findNodeIndex;
  4562. const DOM$b = DOMUtils.DOM;
  4563. const QUEUED = 0;
  4564. const LOADING = 1;
  4565. const LOADED = 2;
  4566. const FAILED = 3;
  4567. class ScriptLoader {
  4568. constructor(settings = {}) {
  4569. this.states = {};
  4570. this.queue = [];
  4571. this.scriptLoadedCallbacks = {};
  4572. this.queueLoadedCallbacks = [];
  4573. this.loading = false;
  4574. this.settings = settings;
  4575. }
  4576. _setReferrerPolicy(referrerPolicy) {
  4577. this.settings.referrerPolicy = referrerPolicy;
  4578. }
  4579. loadScript(url) {
  4580. return new Promise((resolve, reject) => {
  4581. const dom = DOM$b;
  4582. let elm;
  4583. const cleanup = () => {
  4584. dom.remove(id);
  4585. if (elm) {
  4586. elm.onerror = elm.onload = elm = null;
  4587. }
  4588. };
  4589. const done = () => {
  4590. cleanup();
  4591. resolve();
  4592. };
  4593. const error = () => {
  4594. cleanup();
  4595. reject('Failed to load script: ' + url);
  4596. };
  4597. const id = dom.uniqueId();
  4598. elm = document.createElement('script');
  4599. elm.id = id;
  4600. elm.type = 'text/javascript';
  4601. elm.src = Tools._addCacheSuffix(url);
  4602. if (this.settings.referrerPolicy) {
  4603. dom.setAttrib(elm, 'referrerpolicy', this.settings.referrerPolicy);
  4604. }
  4605. elm.onload = done;
  4606. elm.onerror = error;
  4607. (document.getElementsByTagName('head')[0] || document.body).appendChild(elm);
  4608. });
  4609. }
  4610. isDone(url) {
  4611. return this.states[url] === LOADED;
  4612. }
  4613. markDone(url) {
  4614. this.states[url] = LOADED;
  4615. }
  4616. add(url) {
  4617. const self = this;
  4618. self.queue.push(url);
  4619. const state = self.states[url];
  4620. if (state === undefined) {
  4621. self.states[url] = QUEUED;
  4622. }
  4623. return new Promise((resolve, reject) => {
  4624. if (!self.scriptLoadedCallbacks[url]) {
  4625. self.scriptLoadedCallbacks[url] = [];
  4626. }
  4627. self.scriptLoadedCallbacks[url].push({
  4628. resolve,
  4629. reject
  4630. });
  4631. });
  4632. }
  4633. load(url) {
  4634. return this.add(url);
  4635. }
  4636. remove(url) {
  4637. delete this.states[url];
  4638. delete this.scriptLoadedCallbacks[url];
  4639. }
  4640. loadQueue() {
  4641. const queue = this.queue;
  4642. this.queue = [];
  4643. return this.loadScripts(queue);
  4644. }
  4645. loadScripts(scripts) {
  4646. const self = this;
  4647. const execCallbacks = (name, url) => {
  4648. get$a(self.scriptLoadedCallbacks, url).each(callbacks => {
  4649. each$f(callbacks, callback => callback[name](url));
  4650. });
  4651. delete self.scriptLoadedCallbacks[url];
  4652. };
  4653. const processResults = results => {
  4654. const failures = filter$6(results, result => result.status === 'rejected');
  4655. if (failures.length > 0) {
  4656. return Promise.reject(bind$3(failures, ({reason}) => isArray$1(reason) ? reason : [reason]));
  4657. } else {
  4658. return Promise.resolve();
  4659. }
  4660. };
  4661. const load = urls => Promise.allSettled(map$3(urls, url => {
  4662. if (self.states[url] === LOADED) {
  4663. execCallbacks('resolve', url);
  4664. return Promise.resolve();
  4665. } else if (self.states[url] === FAILED) {
  4666. execCallbacks('reject', url);
  4667. return Promise.reject(url);
  4668. } else {
  4669. self.states[url] = LOADING;
  4670. return self.loadScript(url).then(() => {
  4671. self.states[url] = LOADED;
  4672. execCallbacks('resolve', url);
  4673. const queue = self.queue;
  4674. if (queue.length > 0) {
  4675. self.queue = [];
  4676. return load(queue).then(processResults);
  4677. }
  4678. }, () => {
  4679. self.states[url] = FAILED;
  4680. execCallbacks('reject', url);
  4681. return Promise.reject(url);
  4682. });
  4683. }
  4684. }));
  4685. const processQueue = urls => {
  4686. self.loading = true;
  4687. return load(urls).then(results => {
  4688. self.loading = false;
  4689. const nextQueuedItem = self.queueLoadedCallbacks.shift();
  4690. Optional.from(nextQueuedItem).each(call);
  4691. return processResults(results);
  4692. });
  4693. };
  4694. const uniqueScripts = stringArray(scripts);
  4695. if (self.loading) {
  4696. return new Promise((resolve, reject) => {
  4697. self.queueLoadedCallbacks.push(() => processQueue(uniqueScripts).then(resolve, reject));
  4698. });
  4699. } else {
  4700. return processQueue(uniqueScripts);
  4701. }
  4702. }
  4703. }
  4704. ScriptLoader.ScriptLoader = new ScriptLoader();
  4705. const Cell = initial => {
  4706. let value = initial;
  4707. const get = () => {
  4708. return value;
  4709. };
  4710. const set = v => {
  4711. value = v;
  4712. };
  4713. return {
  4714. get,
  4715. set
  4716. };
  4717. };
  4718. const isRaw = str => isObject(str) && has$2(str, 'raw');
  4719. const isTokenised = str => isArray$1(str) && str.length > 1;
  4720. const data = {};
  4721. const currentCode = Cell('en');
  4722. const getLanguageData = () => get$a(data, currentCode.get());
  4723. const getData$1 = () => map$2(data, value => ({ ...value }));
  4724. const setCode = newCode => {
  4725. if (newCode) {
  4726. currentCode.set(newCode);
  4727. }
  4728. };
  4729. const getCode = () => currentCode.get();
  4730. const add$1 = (code, items) => {
  4731. let langData = data[code];
  4732. if (!langData) {
  4733. data[code] = langData = {};
  4734. }
  4735. each$e(items, (translation, name) => {
  4736. langData[name.toLowerCase()] = translation;
  4737. });
  4738. };
  4739. const translate = text => {
  4740. const langData = getLanguageData().getOr({});
  4741. const toString = obj => {
  4742. if (isFunction(obj)) {
  4743. return Object.prototype.toString.call(obj);
  4744. }
  4745. return !isEmpty(obj) ? '' + obj : '';
  4746. };
  4747. const isEmpty = text => text === '' || text === null || text === undefined;
  4748. const getLangData = text => {
  4749. const textstr = toString(text);
  4750. return get$a(langData, textstr.toLowerCase()).map(toString).getOr(textstr);
  4751. };
  4752. const removeContext = str => str.replace(/{context:\w+}$/, '');
  4753. if (isEmpty(text)) {
  4754. return '';
  4755. }
  4756. if (isRaw(text)) {
  4757. return toString(text.raw);
  4758. }
  4759. if (isTokenised(text)) {
  4760. const values = text.slice(1);
  4761. const substitued = getLangData(text[0]).replace(/\{([0-9]+)\}/g, ($1, $2) => has$2(values, $2) ? toString(values[$2]) : $1);
  4762. return removeContext(substitued);
  4763. }
  4764. return removeContext(getLangData(text));
  4765. };
  4766. const isRtl$1 = () => getLanguageData().bind(items => get$a(items, '_dir')).exists(dir => dir === 'rtl');
  4767. const hasCode = code => has$2(data, code);
  4768. const I18n = {
  4769. getData: getData$1,
  4770. setCode,
  4771. getCode,
  4772. add: add$1,
  4773. translate,
  4774. isRtl: isRtl$1,
  4775. hasCode
  4776. };
  4777. const AddOnManager = () => {
  4778. const items = [];
  4779. const urls = {};
  4780. const lookup = {};
  4781. const _listeners = [];
  4782. const runListeners = (name, state) => {
  4783. const matchedListeners = filter$6(_listeners, listener => listener.name === name && listener.state === state);
  4784. each$f(matchedListeners, listener => listener.resolve());
  4785. };
  4786. const isLoaded = name => has$2(urls, name);
  4787. const isAdded = name => has$2(lookup, name);
  4788. const get = name => {
  4789. if (lookup[name]) {
  4790. return lookup[name].instance;
  4791. }
  4792. return undefined;
  4793. };
  4794. const loadLanguagePack = (name, languages) => {
  4795. const language = I18n.getCode();
  4796. const wrappedLanguages = ',' + (languages || '') + ',';
  4797. if (!language || languages && wrappedLanguages.indexOf(',' + language + ',') === -1) {
  4798. return;
  4799. }
  4800. ScriptLoader.ScriptLoader.add(urls[name] + '/langs/' + language + '.js');
  4801. };
  4802. const requireLangPack = (name, languages) => {
  4803. if (AddOnManager.languageLoad !== false) {
  4804. if (isLoaded(name)) {
  4805. loadLanguagePack(name, languages);
  4806. } else {
  4807. waitFor(name, 'loaded').then(() => loadLanguagePack(name, languages));
  4808. }
  4809. }
  4810. };
  4811. const add = (id, addOn) => {
  4812. items.push(addOn);
  4813. lookup[id] = { instance: addOn };
  4814. runListeners(id, 'added');
  4815. return addOn;
  4816. };
  4817. const remove = name => {
  4818. delete urls[name];
  4819. delete lookup[name];
  4820. };
  4821. const createUrl = (baseUrl, dep) => {
  4822. if (isString(dep)) {
  4823. return isString(baseUrl) ? {
  4824. prefix: '',
  4825. resource: dep,
  4826. suffix: ''
  4827. } : {
  4828. prefix: baseUrl.prefix,
  4829. resource: dep,
  4830. suffix: baseUrl.suffix
  4831. };
  4832. } else {
  4833. return dep;
  4834. }
  4835. };
  4836. const load = (name, addOnUrl) => {
  4837. if (urls[name]) {
  4838. return Promise.resolve();
  4839. }
  4840. let urlString = isString(addOnUrl) ? addOnUrl : addOnUrl.prefix + addOnUrl.resource + addOnUrl.suffix;
  4841. if (urlString.indexOf('/') !== 0 && urlString.indexOf('://') === -1) {
  4842. urlString = AddOnManager.baseURL + '/' + urlString;
  4843. }
  4844. urls[name] = urlString.substring(0, urlString.lastIndexOf('/'));
  4845. const done = () => {
  4846. runListeners(name, 'loaded');
  4847. return Promise.resolve();
  4848. };
  4849. if (lookup[name]) {
  4850. return done();
  4851. } else {
  4852. return ScriptLoader.ScriptLoader.add(urlString).then(done);
  4853. }
  4854. };
  4855. const waitFor = (name, state = 'added') => {
  4856. if (state === 'added' && isAdded(name)) {
  4857. return Promise.resolve();
  4858. } else if (state === 'loaded' && isLoaded(name)) {
  4859. return Promise.resolve();
  4860. } else {
  4861. return new Promise(resolve => {
  4862. _listeners.push({
  4863. name,
  4864. state,
  4865. resolve
  4866. });
  4867. });
  4868. }
  4869. };
  4870. return {
  4871. items,
  4872. urls,
  4873. lookup,
  4874. get,
  4875. requireLangPack,
  4876. add,
  4877. remove,
  4878. createUrl,
  4879. load,
  4880. waitFor
  4881. };
  4882. };
  4883. AddOnManager.languageLoad = true;
  4884. AddOnManager.baseURL = '';
  4885. AddOnManager.PluginManager = AddOnManager();
  4886. AddOnManager.ThemeManager = AddOnManager();
  4887. AddOnManager.ModelManager = AddOnManager();
  4888. const singleton = doRevoke => {
  4889. const subject = Cell(Optional.none());
  4890. const revoke = () => subject.get().each(doRevoke);
  4891. const clear = () => {
  4892. revoke();
  4893. subject.set(Optional.none());
  4894. };
  4895. const isSet = () => subject.get().isSome();
  4896. const get = () => subject.get();
  4897. const set = s => {
  4898. revoke();
  4899. subject.set(Optional.some(s));
  4900. };
  4901. return {
  4902. clear,
  4903. isSet,
  4904. get,
  4905. set
  4906. };
  4907. };
  4908. const value$2 = () => {
  4909. const subject = singleton(noop);
  4910. const on = f => subject.get().each(f);
  4911. return {
  4912. ...subject,
  4913. on
  4914. };
  4915. };
  4916. const first$1 = (fn, rate) => {
  4917. let timer = null;
  4918. const cancel = () => {
  4919. if (!isNull(timer)) {
  4920. clearTimeout(timer);
  4921. timer = null;
  4922. }
  4923. };
  4924. const throttle = (...args) => {
  4925. if (isNull(timer)) {
  4926. timer = setTimeout(() => {
  4927. timer = null;
  4928. fn.apply(null, args);
  4929. }, rate);
  4930. }
  4931. };
  4932. return {
  4933. cancel,
  4934. throttle
  4935. };
  4936. };
  4937. const last$1 = (fn, rate) => {
  4938. let timer = null;
  4939. const cancel = () => {
  4940. if (!isNull(timer)) {
  4941. clearTimeout(timer);
  4942. timer = null;
  4943. }
  4944. };
  4945. const throttle = (...args) => {
  4946. cancel();
  4947. timer = setTimeout(() => {
  4948. timer = null;
  4949. fn.apply(null, args);
  4950. }, rate);
  4951. };
  4952. return {
  4953. cancel,
  4954. throttle
  4955. };
  4956. };
  4957. const descendants$1 = (scope, predicate) => {
  4958. let result = [];
  4959. each$f(children(scope), x => {
  4960. if (predicate(x)) {
  4961. result = result.concat([x]);
  4962. }
  4963. result = result.concat(descendants$1(x, predicate));
  4964. });
  4965. return result;
  4966. };
  4967. const descendants = (scope, selector) => all(selector, scope);
  4968. const annotation = constant('mce-annotation');
  4969. const dataAnnotation = constant('data-mce-annotation');
  4970. const dataAnnotationId = constant('data-mce-annotation-uid');
  4971. const dataAnnotationActive = constant('data-mce-annotation-active');
  4972. const dataAnnotationClasses = constant('data-mce-annotation-classes');
  4973. const dataAnnotationAttributes = constant('data-mce-annotation-attrs');
  4974. const isRoot$1 = root => node => eq(node, root);
  4975. const identify = (editor, annotationName) => {
  4976. const rng = editor.selection.getRng();
  4977. const start = SugarElement.fromDom(rng.startContainer);
  4978. const root = SugarElement.fromDom(editor.getBody());
  4979. const selector = annotationName.fold(() => '.' + annotation(), an => `[${ dataAnnotation() }="${ an }"]`);
  4980. const newStart = child$1(start, rng.startOffset).getOr(start);
  4981. const closest = closest$3(newStart, selector, isRoot$1(root));
  4982. const getAttr = (c, property) => {
  4983. if (has$1(c, property)) {
  4984. return Optional.some(get$9(c, property));
  4985. } else {
  4986. return Optional.none();
  4987. }
  4988. };
  4989. return closest.bind(c => getAttr(c, `${ dataAnnotationId() }`).bind(uid => getAttr(c, `${ dataAnnotation() }`).map(name => {
  4990. const elements = findMarkers(editor, uid);
  4991. return {
  4992. uid,
  4993. name,
  4994. elements
  4995. };
  4996. })));
  4997. };
  4998. const isAnnotation = elem => isElement$7(elem) && has(elem, annotation());
  4999. const isBogusElement = (elem, root) => has$1(elem, 'data-mce-bogus') || ancestor$1(elem, '[data-mce-bogus="all"]', isRoot$1(root));
  5000. const findMarkers = (editor, uid) => {
  5001. const body = SugarElement.fromDom(editor.getBody());
  5002. const descendants$1 = descendants(body, `[${ dataAnnotationId() }="${ uid }"]`);
  5003. return filter$6(descendants$1, descendant => !isBogusElement(descendant, body));
  5004. };
  5005. const findAll = (editor, name) => {
  5006. const body = SugarElement.fromDom(editor.getBody());
  5007. const markers = descendants(body, `[${ dataAnnotation() }="${ name }"]`);
  5008. const directory = {};
  5009. each$f(markers, m => {
  5010. if (!isBogusElement(m, body)) {
  5011. const uid = get$9(m, dataAnnotationId());
  5012. const nodesAlready = get$a(directory, uid).getOr([]);
  5013. directory[uid] = nodesAlready.concat([m]);
  5014. }
  5015. });
  5016. return directory;
  5017. };
  5018. const setup$x = (editor, registry) => {
  5019. const changeCallbacks = Cell({});
  5020. const initData = () => ({
  5021. listeners: [],
  5022. previous: value$2()
  5023. });
  5024. const withCallbacks = (name, f) => {
  5025. updateCallbacks(name, data => {
  5026. f(data);
  5027. return data;
  5028. });
  5029. };
  5030. const updateCallbacks = (name, f) => {
  5031. const callbackMap = changeCallbacks.get();
  5032. const data = get$a(callbackMap, name).getOrThunk(initData);
  5033. const outputData = f(data);
  5034. callbackMap[name] = outputData;
  5035. changeCallbacks.set(callbackMap);
  5036. };
  5037. const fireCallbacks = (name, uid, elements) => {
  5038. withCallbacks(name, data => {
  5039. each$f(data.listeners, f => f(true, name, {
  5040. uid,
  5041. nodes: map$3(elements, elem => elem.dom)
  5042. }));
  5043. });
  5044. };
  5045. const fireNoAnnotation = name => {
  5046. withCallbacks(name, data => {
  5047. each$f(data.listeners, f => f(false, name));
  5048. });
  5049. };
  5050. const toggleActiveAttr = (uid, state) => {
  5051. each$f(findMarkers(editor, uid), elem => {
  5052. if (state) {
  5053. set$2(elem, dataAnnotationActive(), 'true');
  5054. } else {
  5055. remove$b(elem, dataAnnotationActive());
  5056. }
  5057. });
  5058. };
  5059. const onNodeChange = last$1(() => {
  5060. const annotations = sort(registry.getNames());
  5061. each$f(annotations, name => {
  5062. updateCallbacks(name, data => {
  5063. const prev = data.previous.get();
  5064. identify(editor, Optional.some(name)).fold(() => {
  5065. prev.each(uid => {
  5066. fireNoAnnotation(name);
  5067. data.previous.clear();
  5068. toggleActiveAttr(uid, false);
  5069. });
  5070. }, ({uid, name, elements}) => {
  5071. if (!is$2(prev, uid)) {
  5072. prev.each(uid => toggleActiveAttr(uid, false));
  5073. fireCallbacks(name, uid, elements);
  5074. data.previous.set(uid);
  5075. toggleActiveAttr(uid, true);
  5076. }
  5077. });
  5078. return {
  5079. previous: data.previous,
  5080. listeners: data.listeners
  5081. };
  5082. });
  5083. });
  5084. }, 30);
  5085. editor.on('remove', () => {
  5086. onNodeChange.cancel();
  5087. });
  5088. editor.on('NodeChange', () => {
  5089. onNodeChange.throttle();
  5090. });
  5091. const addListener = (name, f) => {
  5092. updateCallbacks(name, data => ({
  5093. previous: data.previous,
  5094. listeners: data.listeners.concat([f])
  5095. }));
  5096. };
  5097. return { addListener };
  5098. };
  5099. const setup$w = (editor, registry) => {
  5100. const dataAnnotation$1 = dataAnnotation();
  5101. const identifyParserNode = node => Optional.from(node.attr(dataAnnotation$1)).bind(registry.lookup);
  5102. const removeDirectAnnotation = node => {
  5103. var _a, _b;
  5104. node.attr(dataAnnotationId(), null);
  5105. node.attr(dataAnnotation(), null);
  5106. node.attr(dataAnnotationActive(), null);
  5107. const customAttrNames = Optional.from(node.attr(dataAnnotationAttributes())).map(names => names.split(',')).getOr([]);
  5108. const customClasses = Optional.from(node.attr(dataAnnotationClasses())).map(names => names.split(',')).getOr([]);
  5109. each$f(customAttrNames, name => node.attr(name, null));
  5110. const classList = (_b = (_a = node.attr('class')) === null || _a === void 0 ? void 0 : _a.split(' ')) !== null && _b !== void 0 ? _b : [];
  5111. const newClassList = difference(classList, [annotation()].concat(customClasses));
  5112. node.attr('class', newClassList.length > 0 ? newClassList.join(' ') : null);
  5113. node.attr(dataAnnotationClasses(), null);
  5114. node.attr(dataAnnotationAttributes(), null);
  5115. };
  5116. editor.serializer.addTempAttr(dataAnnotationActive());
  5117. editor.serializer.addAttributeFilter(dataAnnotation$1, nodes => {
  5118. for (const node of nodes) {
  5119. identifyParserNode(node).each(settings => {
  5120. if (settings.persistent === false) {
  5121. if (node.name === 'span') {
  5122. node.unwrap();
  5123. } else {
  5124. removeDirectAnnotation(node);
  5125. }
  5126. }
  5127. });
  5128. }
  5129. });
  5130. };
  5131. const create$c = () => {
  5132. const annotations = {};
  5133. const register = (name, settings) => {
  5134. annotations[name] = {
  5135. name,
  5136. settings
  5137. };
  5138. };
  5139. const lookup = name => get$a(annotations, name).map(a => a.settings);
  5140. const getNames = () => keys(annotations);
  5141. return {
  5142. register,
  5143. lookup,
  5144. getNames
  5145. };
  5146. };
  5147. let unique = 0;
  5148. const generate$1 = prefix => {
  5149. const date = new Date();
  5150. const time = date.getTime();
  5151. const random = Math.floor(Math.random() * 1000000000);
  5152. unique++;
  5153. return prefix + '_' + random + unique + String(time);
  5154. };
  5155. const add = (element, classes) => {
  5156. each$f(classes, x => {
  5157. add$2(element, x);
  5158. });
  5159. };
  5160. const remove$5 = (element, classes) => {
  5161. each$f(classes, x => {
  5162. remove$8(element, x);
  5163. });
  5164. };
  5165. const clone$2 = (original, isDeep) => SugarElement.fromDom(original.dom.cloneNode(isDeep));
  5166. const shallow$1 = original => clone$2(original, false);
  5167. const deep$1 = original => clone$2(original, true);
  5168. const shallowAs = (original, tag) => {
  5169. const nu = SugarElement.fromTag(tag);
  5170. const attributes = clone$4(original);
  5171. setAll$1(nu, attributes);
  5172. return nu;
  5173. };
  5174. const mutate = (original, tag) => {
  5175. const nu = shallowAs(original, tag);
  5176. after$4(original, nu);
  5177. const children$1 = children(original);
  5178. append(nu, children$1);
  5179. remove$6(original);
  5180. return nu;
  5181. };
  5182. const TextWalker = (startNode, rootNode, isBoundary = never) => {
  5183. const walker = new DomTreeWalker(startNode, rootNode);
  5184. const walk = direction => {
  5185. let next;
  5186. do {
  5187. next = walker[direction]();
  5188. } while (next && !isText$9(next) && !isBoundary(next));
  5189. return Optional.from(next).filter(isText$9);
  5190. };
  5191. return {
  5192. current: () => Optional.from(walker.current()).filter(isText$9),
  5193. next: () => walk('next'),
  5194. prev: () => walk('prev'),
  5195. prev2: () => walk('prev2')
  5196. };
  5197. };
  5198. const TextSeeker = (dom, isBoundary) => {
  5199. const isBlockBoundary = isBoundary ? isBoundary : node => dom.isBlock(node) || isBr$6(node) || isContentEditableFalse$b(node);
  5200. const walk = (node, offset, walker, process) => {
  5201. if (isText$9(node)) {
  5202. const newOffset = process(node, offset, node.data);
  5203. if (newOffset !== -1) {
  5204. return Optional.some({
  5205. container: node,
  5206. offset: newOffset
  5207. });
  5208. }
  5209. }
  5210. return walker().bind(next => walk(next.container, next.offset, walker, process));
  5211. };
  5212. const backwards = (node, offset, process, root) => {
  5213. const walker = TextWalker(node, root, isBlockBoundary);
  5214. return walk(node, offset, () => walker.prev().map(prev => ({
  5215. container: prev,
  5216. offset: prev.length
  5217. })), process).getOrNull();
  5218. };
  5219. const forwards = (node, offset, process, root) => {
  5220. const walker = TextWalker(node, root, isBlockBoundary);
  5221. return walk(node, offset, () => walker.next().map(next => ({
  5222. container: next,
  5223. offset: 0
  5224. })), process).getOrNull();
  5225. };
  5226. return {
  5227. backwards,
  5228. forwards
  5229. };
  5230. };
  5231. const round$2 = Math.round;
  5232. const clone$1 = rect => {
  5233. if (!rect) {
  5234. return {
  5235. left: 0,
  5236. top: 0,
  5237. bottom: 0,
  5238. right: 0,
  5239. width: 0,
  5240. height: 0
  5241. };
  5242. }
  5243. return {
  5244. left: round$2(rect.left),
  5245. top: round$2(rect.top),
  5246. bottom: round$2(rect.bottom),
  5247. right: round$2(rect.right),
  5248. width: round$2(rect.width),
  5249. height: round$2(rect.height)
  5250. };
  5251. };
  5252. const collapse = (rect, toStart) => {
  5253. rect = clone$1(rect);
  5254. if (toStart) {
  5255. rect.right = rect.left;
  5256. } else {
  5257. rect.left = rect.left + rect.width;
  5258. rect.right = rect.left;
  5259. }
  5260. rect.width = 0;
  5261. return rect;
  5262. };
  5263. const isEqual = (rect1, rect2) => rect1.left === rect2.left && rect1.top === rect2.top && rect1.bottom === rect2.bottom && rect1.right === rect2.right;
  5264. const isValidOverflow = (overflowY, rect1, rect2) => overflowY >= 0 && overflowY <= Math.min(rect1.height, rect2.height) / 2;
  5265. const isAbove$1 = (rect1, rect2) => {
  5266. const halfHeight = Math.min(rect2.height / 2, rect1.height / 2);
  5267. if (rect1.bottom - halfHeight < rect2.top) {
  5268. return true;
  5269. }
  5270. if (rect1.top > rect2.bottom) {
  5271. return false;
  5272. }
  5273. return isValidOverflow(rect2.top - rect1.bottom, rect1, rect2);
  5274. };
  5275. const isBelow$1 = (rect1, rect2) => {
  5276. if (rect1.top > rect2.bottom) {
  5277. return true;
  5278. }
  5279. if (rect1.bottom < rect2.top) {
  5280. return false;
  5281. }
  5282. return isValidOverflow(rect2.bottom - rect1.top, rect1, rect2);
  5283. };
  5284. const containsXY = (rect, clientX, clientY) => clientX >= rect.left && clientX <= rect.right && clientY >= rect.top && clientY <= rect.bottom;
  5285. const boundingClientRectFromRects = rects => {
  5286. return foldl(rects, (acc, rect) => {
  5287. return acc.fold(() => Optional.some(rect), prevRect => {
  5288. const left = Math.min(rect.left, prevRect.left);
  5289. const top = Math.min(rect.top, prevRect.top);
  5290. const right = Math.max(rect.right, prevRect.right);
  5291. const bottom = Math.max(rect.bottom, prevRect.bottom);
  5292. return Optional.some({
  5293. top,
  5294. right,
  5295. bottom,
  5296. left,
  5297. width: right - left,
  5298. height: bottom - top
  5299. });
  5300. });
  5301. }, Optional.none());
  5302. };
  5303. const distanceToRectEdgeFromXY = (rect, x, y) => {
  5304. const cx = Math.max(Math.min(x, rect.left + rect.width), rect.left);
  5305. const cy = Math.max(Math.min(y, rect.top + rect.height), rect.top);
  5306. return Math.sqrt((x - cx) * (x - cx) + (y - cy) * (y - cy));
  5307. };
  5308. const overlapY = (r1, r2) => Math.max(0, Math.min(r1.bottom, r2.bottom) - Math.max(r1.top, r2.top));
  5309. const clamp$2 = (value, min, max) => Math.min(Math.max(value, min), max);
  5310. const getSelectedNode = range => {
  5311. const startContainer = range.startContainer, startOffset = range.startOffset;
  5312. if (startContainer === range.endContainer && startContainer.hasChildNodes() && range.endOffset === startOffset + 1) {
  5313. return startContainer.childNodes[startOffset];
  5314. }
  5315. return null;
  5316. };
  5317. const getNode$1 = (container, offset) => {
  5318. if (isElement$6(container) && container.hasChildNodes()) {
  5319. const childNodes = container.childNodes;
  5320. const safeOffset = clamp$2(offset, 0, childNodes.length - 1);
  5321. return childNodes[safeOffset];
  5322. } else {
  5323. return container;
  5324. }
  5325. };
  5326. const getNodeUnsafe = (container, offset) => {
  5327. if (offset < 0 && isElement$6(container) && container.hasChildNodes()) {
  5328. return undefined;
  5329. } else {
  5330. return getNode$1(container, offset);
  5331. }
  5332. };
  5333. 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]');
  5334. const isExtendingChar = ch => typeof ch === 'string' && ch.charCodeAt(0) >= 768 && extendingChars.test(ch);
  5335. const or = (...args) => {
  5336. return x => {
  5337. for (let i = 0; i < args.length; i++) {
  5338. if (args[i](x)) {
  5339. return true;
  5340. }
  5341. }
  5342. return false;
  5343. };
  5344. };
  5345. const and = (...args) => {
  5346. return x => {
  5347. for (let i = 0; i < args.length; i++) {
  5348. if (!args[i](x)) {
  5349. return false;
  5350. }
  5351. }
  5352. return true;
  5353. };
  5354. };
  5355. const isElement$4 = isElement$6;
  5356. const isCaretCandidate$2 = isCaretCandidate$3;
  5357. const isBlock$1 = matchStyleValues('display', 'block table');
  5358. const isFloated = matchStyleValues('float', 'left right');
  5359. const isValidElementCaretCandidate = and(isElement$4, isCaretCandidate$2, not(isFloated));
  5360. const isNotPre = not(matchStyleValues('white-space', 'pre pre-line pre-wrap'));
  5361. const isText$6 = isText$9;
  5362. const isBr$3 = isBr$6;
  5363. const nodeIndex$1 = DOMUtils.nodeIndex;
  5364. const resolveIndex$1 = getNodeUnsafe;
  5365. const createRange$1 = doc => 'createRange' in doc ? doc.createRange() : DOMUtils.DOM.createRng();
  5366. const isWhiteSpace$1 = chr => chr && /[\r\n\t ]/.test(chr);
  5367. const isRange = rng => !!rng.setStart && !!rng.setEnd;
  5368. const isHiddenWhiteSpaceRange = range => {
  5369. const container = range.startContainer;
  5370. const offset = range.startOffset;
  5371. if (isWhiteSpace$1(range.toString()) && isNotPre(container.parentNode) && isText$9(container)) {
  5372. const text = container.data;
  5373. if (isWhiteSpace$1(text[offset - 1]) || isWhiteSpace$1(text[offset + 1])) {
  5374. return true;
  5375. }
  5376. }
  5377. return false;
  5378. };
  5379. const getBrClientRect = brNode => {
  5380. const doc = brNode.ownerDocument;
  5381. const rng = createRange$1(doc);
  5382. const nbsp$1 = doc.createTextNode(nbsp);
  5383. const parentNode = brNode.parentNode;
  5384. parentNode.insertBefore(nbsp$1, brNode);
  5385. rng.setStart(nbsp$1, 0);
  5386. rng.setEnd(nbsp$1, 1);
  5387. const clientRect = clone$1(rng.getBoundingClientRect());
  5388. parentNode.removeChild(nbsp$1);
  5389. return clientRect;
  5390. };
  5391. const getBoundingClientRectWebKitText = rng => {
  5392. const sc = rng.startContainer;
  5393. const ec = rng.endContainer;
  5394. const so = rng.startOffset;
  5395. const eo = rng.endOffset;
  5396. if (sc === ec && isText$9(ec) && so === 0 && eo === 1) {
  5397. const newRng = rng.cloneRange();
  5398. newRng.setEndAfter(ec);
  5399. return getBoundingClientRect$1(newRng);
  5400. } else {
  5401. return null;
  5402. }
  5403. };
  5404. const isZeroRect = r => r.left === 0 && r.right === 0 && r.top === 0 && r.bottom === 0;
  5405. const getBoundingClientRect$1 = item => {
  5406. let clientRect;
  5407. const clientRects = item.getClientRects();
  5408. if (clientRects.length > 0) {
  5409. clientRect = clone$1(clientRects[0]);
  5410. } else {
  5411. clientRect = clone$1(item.getBoundingClientRect());
  5412. }
  5413. if (!isRange(item) && isBr$3(item) && isZeroRect(clientRect)) {
  5414. return getBrClientRect(item);
  5415. }
  5416. if (isZeroRect(clientRect) && isRange(item)) {
  5417. return getBoundingClientRectWebKitText(item);
  5418. }
  5419. return clientRect;
  5420. };
  5421. const collapseAndInflateWidth = (clientRect, toStart) => {
  5422. const newClientRect = collapse(clientRect, toStart);
  5423. newClientRect.width = 1;
  5424. newClientRect.right = newClientRect.left + 1;
  5425. return newClientRect;
  5426. };
  5427. const getCaretPositionClientRects = caretPosition => {
  5428. const clientRects = [];
  5429. const addUniqueAndValidRect = clientRect => {
  5430. if (clientRect.height === 0) {
  5431. return;
  5432. }
  5433. if (clientRects.length > 0) {
  5434. if (isEqual(clientRect, clientRects[clientRects.length - 1])) {
  5435. return;
  5436. }
  5437. }
  5438. clientRects.push(clientRect);
  5439. };
  5440. const addCharacterOffset = (container, offset) => {
  5441. const range = createRange$1(container.ownerDocument);
  5442. if (offset < container.data.length) {
  5443. if (isExtendingChar(container.data[offset])) {
  5444. return clientRects;
  5445. }
  5446. if (isExtendingChar(container.data[offset - 1])) {
  5447. range.setStart(container, offset);
  5448. range.setEnd(container, offset + 1);
  5449. if (!isHiddenWhiteSpaceRange(range)) {
  5450. addUniqueAndValidRect(collapseAndInflateWidth(getBoundingClientRect$1(range), false));
  5451. return clientRects;
  5452. }
  5453. }
  5454. }
  5455. if (offset > 0) {
  5456. range.setStart(container, offset - 1);
  5457. range.setEnd(container, offset);
  5458. if (!isHiddenWhiteSpaceRange(range)) {
  5459. addUniqueAndValidRect(collapseAndInflateWidth(getBoundingClientRect$1(range), false));
  5460. }
  5461. }
  5462. if (offset < container.data.length) {
  5463. range.setStart(container, offset);
  5464. range.setEnd(container, offset + 1);
  5465. if (!isHiddenWhiteSpaceRange(range)) {
  5466. addUniqueAndValidRect(collapseAndInflateWidth(getBoundingClientRect$1(range), true));
  5467. }
  5468. }
  5469. };
  5470. const container = caretPosition.container();
  5471. const offset = caretPosition.offset();
  5472. if (isText$6(container)) {
  5473. addCharacterOffset(container, offset);
  5474. return clientRects;
  5475. }
  5476. if (isElement$4(container)) {
  5477. if (caretPosition.isAtEnd()) {
  5478. const node = resolveIndex$1(container, offset);
  5479. if (isText$6(node)) {
  5480. addCharacterOffset(node, node.data.length);
  5481. }
  5482. if (isValidElementCaretCandidate(node) && !isBr$3(node)) {
  5483. addUniqueAndValidRect(collapseAndInflateWidth(getBoundingClientRect$1(node), false));
  5484. }
  5485. } else {
  5486. const node = resolveIndex$1(container, offset);
  5487. if (isText$6(node)) {
  5488. addCharacterOffset(node, 0);
  5489. }
  5490. if (isValidElementCaretCandidate(node) && caretPosition.isAtEnd()) {
  5491. addUniqueAndValidRect(collapseAndInflateWidth(getBoundingClientRect$1(node), false));
  5492. return clientRects;
  5493. }
  5494. const beforeNode = resolveIndex$1(caretPosition.container(), caretPosition.offset() - 1);
  5495. if (isValidElementCaretCandidate(beforeNode) && !isBr$3(beforeNode)) {
  5496. if (isBlock$1(beforeNode) || isBlock$1(node) || !isValidElementCaretCandidate(node)) {
  5497. addUniqueAndValidRect(collapseAndInflateWidth(getBoundingClientRect$1(beforeNode), false));
  5498. }
  5499. }
  5500. if (isValidElementCaretCandidate(node)) {
  5501. addUniqueAndValidRect(collapseAndInflateWidth(getBoundingClientRect$1(node), true));
  5502. }
  5503. }
  5504. }
  5505. return clientRects;
  5506. };
  5507. const CaretPosition = (container, offset, clientRects) => {
  5508. const isAtStart = () => {
  5509. if (isText$6(container)) {
  5510. return offset === 0;
  5511. }
  5512. return offset === 0;
  5513. };
  5514. const isAtEnd = () => {
  5515. if (isText$6(container)) {
  5516. return offset >= container.data.length;
  5517. }
  5518. return offset >= container.childNodes.length;
  5519. };
  5520. const toRange = () => {
  5521. const range = createRange$1(container.ownerDocument);
  5522. range.setStart(container, offset);
  5523. range.setEnd(container, offset);
  5524. return range;
  5525. };
  5526. const getClientRects = () => {
  5527. if (!clientRects) {
  5528. clientRects = getCaretPositionClientRects(CaretPosition(container, offset));
  5529. }
  5530. return clientRects;
  5531. };
  5532. const isVisible = () => getClientRects().length > 0;
  5533. const isEqual = caretPosition => caretPosition && container === caretPosition.container() && offset === caretPosition.offset();
  5534. const getNode = before => resolveIndex$1(container, before ? offset - 1 : offset);
  5535. return {
  5536. container: constant(container),
  5537. offset: constant(offset),
  5538. toRange,
  5539. getClientRects,
  5540. isVisible,
  5541. isAtStart,
  5542. isAtEnd,
  5543. isEqual,
  5544. getNode
  5545. };
  5546. };
  5547. CaretPosition.fromRangeStart = range => CaretPosition(range.startContainer, range.startOffset);
  5548. CaretPosition.fromRangeEnd = range => CaretPosition(range.endContainer, range.endOffset);
  5549. CaretPosition.after = node => CaretPosition(node.parentNode, nodeIndex$1(node) + 1);
  5550. CaretPosition.before = node => CaretPosition(node.parentNode, nodeIndex$1(node));
  5551. CaretPosition.isAbove = (pos1, pos2) => lift2(head(pos2.getClientRects()), last$3(pos1.getClientRects()), isAbove$1).getOr(false);
  5552. CaretPosition.isBelow = (pos1, pos2) => lift2(last$3(pos2.getClientRects()), head(pos1.getClientRects()), isBelow$1).getOr(false);
  5553. CaretPosition.isAtStart = pos => pos ? pos.isAtStart() : false;
  5554. CaretPosition.isAtEnd = pos => pos ? pos.isAtEnd() : false;
  5555. CaretPosition.isTextPosition = pos => pos ? isText$9(pos.container()) : false;
  5556. CaretPosition.isElementPosition = pos => CaretPosition.isTextPosition(pos) === false;
  5557. const trimEmptyTextNode$1 = (dom, node) => {
  5558. if (isText$9(node) && node.data.length === 0) {
  5559. dom.remove(node);
  5560. }
  5561. };
  5562. const insertNode = (dom, rng, node) => {
  5563. rng.insertNode(node);
  5564. trimEmptyTextNode$1(dom, node.previousSibling);
  5565. trimEmptyTextNode$1(dom, node.nextSibling);
  5566. };
  5567. const insertFragment = (dom, rng, frag) => {
  5568. const firstChild = Optional.from(frag.firstChild);
  5569. const lastChild = Optional.from(frag.lastChild);
  5570. rng.insertNode(frag);
  5571. firstChild.each(child => trimEmptyTextNode$1(dom, child.previousSibling));
  5572. lastChild.each(child => trimEmptyTextNode$1(dom, child.nextSibling));
  5573. };
  5574. const rangeInsertNode = (dom, rng, node) => {
  5575. if (isDocumentFragment(node)) {
  5576. insertFragment(dom, rng, node);
  5577. } else {
  5578. insertNode(dom, rng, node);
  5579. }
  5580. };
  5581. const isText$5 = isText$9;
  5582. const isBogus = isBogus$2;
  5583. const nodeIndex = DOMUtils.nodeIndex;
  5584. const normalizedParent = node => {
  5585. const parentNode = node.parentNode;
  5586. if (isBogus(parentNode)) {
  5587. return normalizedParent(parentNode);
  5588. }
  5589. return parentNode;
  5590. };
  5591. const getChildNodes = node => {
  5592. if (!node) {
  5593. return [];
  5594. }
  5595. return reduce(node.childNodes, (result, node) => {
  5596. if (isBogus(node) && node.nodeName !== 'BR') {
  5597. result = result.concat(getChildNodes(node));
  5598. } else {
  5599. result.push(node);
  5600. }
  5601. return result;
  5602. }, []);
  5603. };
  5604. const normalizedTextOffset = (node, offset) => {
  5605. while (node = node.previousSibling) {
  5606. if (!isText$5(node)) {
  5607. break;
  5608. }
  5609. offset += node.data.length;
  5610. }
  5611. return offset;
  5612. };
  5613. const equal = a => b => a === b;
  5614. const normalizedNodeIndex = node => {
  5615. let nodes, index;
  5616. nodes = getChildNodes(normalizedParent(node));
  5617. index = findIndex$1(nodes, equal(node), node);
  5618. nodes = nodes.slice(0, index + 1);
  5619. const numTextFragments = reduce(nodes, (result, node, i) => {
  5620. if (isText$5(node) && isText$5(nodes[i - 1])) {
  5621. result++;
  5622. }
  5623. return result;
  5624. }, 0);
  5625. nodes = filter$4(nodes, matchNodeNames([node.nodeName]));
  5626. index = findIndex$1(nodes, equal(node), node);
  5627. return index - numTextFragments;
  5628. };
  5629. const createPathItem = node => {
  5630. let name;
  5631. if (isText$5(node)) {
  5632. name = 'text()';
  5633. } else {
  5634. name = node.nodeName.toLowerCase();
  5635. }
  5636. return name + '[' + normalizedNodeIndex(node) + ']';
  5637. };
  5638. const parentsUntil$1 = (root, node, predicate) => {
  5639. const parents = [];
  5640. for (node = node.parentNode; node !== root; node = node.parentNode) {
  5641. if (predicate && predicate(node)) {
  5642. break;
  5643. }
  5644. parents.push(node);
  5645. }
  5646. return parents;
  5647. };
  5648. const create$b = (root, caretPosition) => {
  5649. let container, offset, path = [], outputOffset, childNodes, parents;
  5650. container = caretPosition.container();
  5651. offset = caretPosition.offset();
  5652. if (isText$5(container)) {
  5653. outputOffset = normalizedTextOffset(container, offset);
  5654. } else {
  5655. childNodes = container.childNodes;
  5656. if (offset >= childNodes.length) {
  5657. outputOffset = 'after';
  5658. offset = childNodes.length - 1;
  5659. } else {
  5660. outputOffset = 'before';
  5661. }
  5662. container = childNodes[offset];
  5663. }
  5664. path.push(createPathItem(container));
  5665. parents = parentsUntil$1(root, container);
  5666. parents = filter$4(parents, not(isBogus$2));
  5667. path = path.concat(map$1(parents, node => {
  5668. return createPathItem(node);
  5669. }));
  5670. return path.reverse().join('/') + ',' + outputOffset;
  5671. };
  5672. const resolvePathItem = (node, name, index) => {
  5673. let nodes = getChildNodes(node);
  5674. nodes = filter$4(nodes, (node, index) => {
  5675. return !isText$5(node) || !isText$5(nodes[index - 1]);
  5676. });
  5677. nodes = filter$4(nodes, matchNodeNames([name]));
  5678. return nodes[index];
  5679. };
  5680. const findTextPosition = (container, offset) => {
  5681. let node = container, targetOffset = 0, dataLen;
  5682. while (isText$5(node)) {
  5683. dataLen = node.data.length;
  5684. if (offset >= targetOffset && offset <= targetOffset + dataLen) {
  5685. container = node;
  5686. offset = offset - targetOffset;
  5687. break;
  5688. }
  5689. if (!isText$5(node.nextSibling)) {
  5690. container = node;
  5691. offset = dataLen;
  5692. break;
  5693. }
  5694. targetOffset += dataLen;
  5695. node = node.nextSibling;
  5696. }
  5697. if (isText$5(container) && offset > container.data.length) {
  5698. offset = container.data.length;
  5699. }
  5700. return CaretPosition(container, offset);
  5701. };
  5702. const resolve$1 = (root, path) => {
  5703. let offset;
  5704. if (!path) {
  5705. return null;
  5706. }
  5707. const parts = path.split(',');
  5708. const paths = parts[0].split('/');
  5709. offset = parts.length > 1 ? parts[1] : 'before';
  5710. const container = reduce(paths, (result, value) => {
  5711. const match = /([\w\-\(\)]+)\[([0-9]+)\]/.exec(value);
  5712. if (!match) {
  5713. return null;
  5714. }
  5715. if (match[1] === 'text()') {
  5716. match[1] = '#text';
  5717. }
  5718. return resolvePathItem(result, match[1], parseInt(match[2], 10));
  5719. }, root);
  5720. if (!container) {
  5721. return null;
  5722. }
  5723. if (!isText$5(container)) {
  5724. if (offset === 'after') {
  5725. offset = nodeIndex(container) + 1;
  5726. } else {
  5727. offset = nodeIndex(container);
  5728. }
  5729. return CaretPosition(container.parentNode, offset);
  5730. }
  5731. return findTextPosition(container, parseInt(offset, 10));
  5732. };
  5733. const isContentEditableFalse$9 = isContentEditableFalse$b;
  5734. const getNormalizedTextOffset = (trim, container, offset) => {
  5735. let node, trimmedOffset;
  5736. trimmedOffset = trim(container.data.slice(0, offset)).length;
  5737. for (node = container.previousSibling; node && isText$9(node); node = node.previousSibling) {
  5738. trimmedOffset += trim(node.data).length;
  5739. }
  5740. return trimmedOffset;
  5741. };
  5742. const getPoint = (dom, trim, normalized, rng, start) => {
  5743. let container = rng[start ? 'startContainer' : 'endContainer'];
  5744. let offset = rng[start ? 'startOffset' : 'endOffset'];
  5745. const point = [];
  5746. let childNodes, after = 0;
  5747. const root = dom.getRoot();
  5748. if (isText$9(container)) {
  5749. point.push(normalized ? getNormalizedTextOffset(trim, container, offset) : offset);
  5750. } else {
  5751. childNodes = container.childNodes;
  5752. if (offset >= childNodes.length && childNodes.length) {
  5753. after = 1;
  5754. offset = Math.max(0, childNodes.length - 1);
  5755. }
  5756. point.push(dom.nodeIndex(childNodes[offset], normalized) + after);
  5757. }
  5758. for (; container && container !== root; container = container.parentNode) {
  5759. point.push(dom.nodeIndex(container, normalized));
  5760. }
  5761. return point;
  5762. };
  5763. const getLocation = (trim, selection, normalized, rng) => {
  5764. const dom = selection.dom;
  5765. const start = getPoint(dom, trim, normalized, rng, true);
  5766. const forward = selection.isForward();
  5767. const fakeCaret = isRangeInCaretContainerBlock(rng) ? { isFakeCaret: true } : {};
  5768. if (!selection.isCollapsed()) {
  5769. const end = getPoint(dom, trim, normalized, rng, false);
  5770. return {
  5771. start,
  5772. end,
  5773. forward,
  5774. ...fakeCaret
  5775. };
  5776. } else {
  5777. return {
  5778. start,
  5779. forward,
  5780. ...fakeCaret
  5781. };
  5782. }
  5783. };
  5784. const findIndex = (dom, name, element) => {
  5785. let count = 0;
  5786. Tools.each(dom.select(name), node => {
  5787. if (node.getAttribute('data-mce-bogus') === 'all') {
  5788. return;
  5789. }
  5790. if (node === element) {
  5791. return false;
  5792. }
  5793. count++;
  5794. });
  5795. return count;
  5796. };
  5797. const moveEndPoint$1 = (rng, start) => {
  5798. let container, offset;
  5799. const prefix = start ? 'start' : 'end';
  5800. container = rng[prefix + 'Container'];
  5801. offset = rng[prefix + 'Offset'];
  5802. if (isElement$6(container) && container.nodeName === 'TR') {
  5803. const childNodes = container.childNodes;
  5804. container = childNodes[Math.min(start ? offset : offset - 1, childNodes.length - 1)];
  5805. if (container) {
  5806. offset = start ? 0 : container.childNodes.length;
  5807. rng['set' + (start ? 'Start' : 'End')](container, offset);
  5808. }
  5809. }
  5810. };
  5811. const normalizeTableCellSelection = rng => {
  5812. moveEndPoint$1(rng, true);
  5813. moveEndPoint$1(rng, false);
  5814. return rng;
  5815. };
  5816. const findSibling = (node, offset) => {
  5817. let sibling;
  5818. if (isElement$6(node)) {
  5819. node = getNode$1(node, offset);
  5820. if (isContentEditableFalse$9(node)) {
  5821. return node;
  5822. }
  5823. }
  5824. if (isCaretContainer$2(node)) {
  5825. if (isText$9(node) && isCaretContainerBlock$1(node)) {
  5826. node = node.parentNode;
  5827. }
  5828. sibling = node.previousSibling;
  5829. if (isContentEditableFalse$9(sibling)) {
  5830. return sibling;
  5831. }
  5832. sibling = node.nextSibling;
  5833. if (isContentEditableFalse$9(sibling)) {
  5834. return sibling;
  5835. }
  5836. }
  5837. };
  5838. const findAdjacentContentEditableFalseElm = rng => {
  5839. return findSibling(rng.startContainer, rng.startOffset) || findSibling(rng.endContainer, rng.endOffset);
  5840. };
  5841. const getOffsetBookmark = (trim, normalized, selection) => {
  5842. const element = selection.getNode();
  5843. let name = element ? element.nodeName : null;
  5844. const rng = selection.getRng();
  5845. if (isContentEditableFalse$9(element) || name === 'IMG') {
  5846. return {
  5847. name,
  5848. index: findIndex(selection.dom, name, element)
  5849. };
  5850. }
  5851. const sibling = findAdjacentContentEditableFalseElm(rng);
  5852. if (sibling) {
  5853. name = sibling.tagName;
  5854. return {
  5855. name,
  5856. index: findIndex(selection.dom, name, sibling)
  5857. };
  5858. }
  5859. return getLocation(trim, selection, normalized, rng);
  5860. };
  5861. const getCaretBookmark = selection => {
  5862. const rng = selection.getRng();
  5863. return {
  5864. start: create$b(selection.dom.getRoot(), CaretPosition.fromRangeStart(rng)),
  5865. end: create$b(selection.dom.getRoot(), CaretPosition.fromRangeEnd(rng)),
  5866. forward: selection.isForward()
  5867. };
  5868. };
  5869. const getRangeBookmark = selection => {
  5870. return {
  5871. rng: selection.getRng(),
  5872. forward: selection.isForward()
  5873. };
  5874. };
  5875. const createBookmarkSpan = (dom, id, filled) => {
  5876. const args = {
  5877. 'data-mce-type': 'bookmark',
  5878. id,
  5879. 'style': 'overflow:hidden;line-height:0px'
  5880. };
  5881. return filled ? dom.create('span', args, '&#xFEFF;') : dom.create('span', args);
  5882. };
  5883. const getPersistentBookmark = (selection, filled) => {
  5884. const dom = selection.dom;
  5885. let rng = selection.getRng();
  5886. const id = dom.uniqueId();
  5887. const collapsed = selection.isCollapsed();
  5888. const element = selection.getNode();
  5889. const name = element.nodeName;
  5890. const forward = selection.isForward();
  5891. if (name === 'IMG') {
  5892. return {
  5893. name,
  5894. index: findIndex(dom, name, element)
  5895. };
  5896. }
  5897. const rng2 = normalizeTableCellSelection(rng.cloneRange());
  5898. if (!collapsed) {
  5899. rng2.collapse(false);
  5900. const endBookmarkNode = createBookmarkSpan(dom, id + '_end', filled);
  5901. rangeInsertNode(dom, rng2, endBookmarkNode);
  5902. }
  5903. rng = normalizeTableCellSelection(rng);
  5904. rng.collapse(true);
  5905. const startBookmarkNode = createBookmarkSpan(dom, id + '_start', filled);
  5906. rangeInsertNode(dom, rng, startBookmarkNode);
  5907. selection.moveToBookmark({
  5908. id,
  5909. keep: true,
  5910. forward
  5911. });
  5912. return {
  5913. id,
  5914. forward
  5915. };
  5916. };
  5917. const getBookmark$2 = (selection, type, normalized) => {
  5918. if (type === 2) {
  5919. return getOffsetBookmark(trim$1, normalized, selection);
  5920. } else if (type === 3) {
  5921. return getCaretBookmark(selection);
  5922. } else if (type) {
  5923. return getRangeBookmark(selection);
  5924. } else {
  5925. return getPersistentBookmark(selection, false);
  5926. }
  5927. };
  5928. const getUndoBookmark = curry(getOffsetBookmark, identity, true);
  5929. const value$1 = value => {
  5930. const applyHelper = fn => fn(value);
  5931. const constHelper = constant(value);
  5932. const outputHelper = () => output;
  5933. const output = {
  5934. tag: true,
  5935. inner: value,
  5936. fold: (_onError, onValue) => onValue(value),
  5937. isValue: always,
  5938. isError: never,
  5939. map: mapper => Result.value(mapper(value)),
  5940. mapError: outputHelper,
  5941. bind: applyHelper,
  5942. exists: applyHelper,
  5943. forall: applyHelper,
  5944. getOr: constHelper,
  5945. or: outputHelper,
  5946. getOrThunk: constHelper,
  5947. orThunk: outputHelper,
  5948. getOrDie: constHelper,
  5949. each: fn => {
  5950. fn(value);
  5951. },
  5952. toOptional: () => Optional.some(value)
  5953. };
  5954. return output;
  5955. };
  5956. const error = error => {
  5957. const outputHelper = () => output;
  5958. const output = {
  5959. tag: false,
  5960. inner: error,
  5961. fold: (onError, _onValue) => onError(error),
  5962. isValue: never,
  5963. isError: always,
  5964. map: outputHelper,
  5965. mapError: mapper => Result.error(mapper(error)),
  5966. bind: outputHelper,
  5967. exists: never,
  5968. forall: always,
  5969. getOr: identity,
  5970. or: identity,
  5971. getOrThunk: apply$1,
  5972. orThunk: apply$1,
  5973. getOrDie: die(String(error)),
  5974. each: noop,
  5975. toOptional: Optional.none
  5976. };
  5977. return output;
  5978. };
  5979. const fromOption = (optional, err) => optional.fold(() => error(err), value$1);
  5980. const Result = {
  5981. value: value$1,
  5982. error,
  5983. fromOption
  5984. };
  5985. const generate = cases => {
  5986. if (!isArray$1(cases)) {
  5987. throw new Error('cases must be an array');
  5988. }
  5989. if (cases.length === 0) {
  5990. throw new Error('there must be at least one case');
  5991. }
  5992. const constructors = [];
  5993. const adt = {};
  5994. each$f(cases, (acase, count) => {
  5995. const keys$1 = keys(acase);
  5996. if (keys$1.length !== 1) {
  5997. throw new Error('one and only one name per case');
  5998. }
  5999. const key = keys$1[0];
  6000. const value = acase[key];
  6001. if (adt[key] !== undefined) {
  6002. throw new Error('duplicate key detected:' + key);
  6003. } else if (key === 'cata') {
  6004. throw new Error('cannot have a case named cata (sorry)');
  6005. } else if (!isArray$1(value)) {
  6006. throw new Error('case arguments must be an array');
  6007. }
  6008. constructors.push(key);
  6009. adt[key] = (...args) => {
  6010. const argLength = args.length;
  6011. if (argLength !== value.length) {
  6012. throw new Error('Wrong number of arguments to case ' + key + '. Expected ' + value.length + ' (' + value + '), got ' + argLength);
  6013. }
  6014. const match = branches => {
  6015. const branchKeys = keys(branches);
  6016. if (constructors.length !== branchKeys.length) {
  6017. throw new Error('Wrong number of arguments to match. Expected: ' + constructors.join(',') + '\nActual: ' + branchKeys.join(','));
  6018. }
  6019. const allReqd = forall(constructors, reqKey => {
  6020. return contains$2(branchKeys, reqKey);
  6021. });
  6022. if (!allReqd) {
  6023. throw new Error('Not all branches were specified when using match. Specified: ' + branchKeys.join(', ') + '\nRequired: ' + constructors.join(', '));
  6024. }
  6025. return branches[key].apply(null, args);
  6026. };
  6027. return {
  6028. fold: (...foldArgs) => {
  6029. if (foldArgs.length !== cases.length) {
  6030. throw new Error('Wrong number of arguments to fold. Expected ' + cases.length + ', got ' + foldArgs.length);
  6031. }
  6032. const target = foldArgs[count];
  6033. return target.apply(null, args);
  6034. },
  6035. match,
  6036. log: label => {
  6037. console.log(label, {
  6038. constructors,
  6039. constructor: key,
  6040. params: args
  6041. });
  6042. }
  6043. };
  6044. };
  6045. });
  6046. return adt;
  6047. };
  6048. const Adt = { generate };
  6049. Adt.generate([
  6050. {
  6051. bothErrors: [
  6052. 'error1',
  6053. 'error2'
  6054. ]
  6055. },
  6056. {
  6057. firstError: [
  6058. 'error1',
  6059. 'value2'
  6060. ]
  6061. },
  6062. {
  6063. secondError: [
  6064. 'value1',
  6065. 'error2'
  6066. ]
  6067. },
  6068. {
  6069. bothValues: [
  6070. 'value1',
  6071. 'value2'
  6072. ]
  6073. }
  6074. ]);
  6075. const partition$1 = results => {
  6076. const errors = [];
  6077. const values = [];
  6078. each$f(results, result => {
  6079. result.fold(err => {
  6080. errors.push(err);
  6081. }, value => {
  6082. values.push(value);
  6083. });
  6084. });
  6085. return {
  6086. errors,
  6087. values
  6088. };
  6089. };
  6090. const isInlinePattern = pattern => pattern.type === 'inline-command' || pattern.type === 'inline-format';
  6091. const isBlockPattern = pattern => pattern.type === 'block-command' || pattern.type === 'block-format';
  6092. const sortPatterns = patterns => sort(patterns, (a, b) => {
  6093. if (a.start.length === b.start.length) {
  6094. return 0;
  6095. }
  6096. return a.start.length > b.start.length ? -1 : 1;
  6097. });
  6098. const normalizePattern = pattern => {
  6099. const err = message => Result.error({
  6100. message,
  6101. pattern
  6102. });
  6103. const formatOrCmd = (name, onFormat, onCommand) => {
  6104. if (pattern.format !== undefined) {
  6105. let formats;
  6106. if (isArray$1(pattern.format)) {
  6107. if (!forall(pattern.format, isString)) {
  6108. return err(name + ' pattern has non-string items in the `format` array');
  6109. }
  6110. formats = pattern.format;
  6111. } else if (isString(pattern.format)) {
  6112. formats = [pattern.format];
  6113. } else {
  6114. return err(name + ' pattern has non-string `format` parameter');
  6115. }
  6116. return Result.value(onFormat(formats));
  6117. } else if (pattern.cmd !== undefined) {
  6118. if (!isString(pattern.cmd)) {
  6119. return err(name + ' pattern has non-string `cmd` parameter');
  6120. }
  6121. return Result.value(onCommand(pattern.cmd, pattern.value));
  6122. } else {
  6123. return err(name + ' pattern is missing both `format` and `cmd` parameters');
  6124. }
  6125. };
  6126. if (!isObject(pattern)) {
  6127. return err('Raw pattern is not an object');
  6128. }
  6129. if (!isString(pattern.start)) {
  6130. return err('Raw pattern is missing `start` parameter');
  6131. }
  6132. if (pattern.end !== undefined) {
  6133. if (!isString(pattern.end)) {
  6134. return err('Inline pattern has non-string `end` parameter');
  6135. }
  6136. if (pattern.start.length === 0 && pattern.end.length === 0) {
  6137. return err('Inline pattern has empty `start` and `end` parameters');
  6138. }
  6139. let start = pattern.start;
  6140. let end = pattern.end;
  6141. if (end.length === 0) {
  6142. end = start;
  6143. start = '';
  6144. }
  6145. return formatOrCmd('Inline', format => ({
  6146. type: 'inline-format',
  6147. start,
  6148. end,
  6149. format
  6150. }), (cmd, value) => ({
  6151. type: 'inline-command',
  6152. start,
  6153. end,
  6154. cmd,
  6155. value
  6156. }));
  6157. } else if (pattern.replacement !== undefined) {
  6158. if (!isString(pattern.replacement)) {
  6159. return err('Replacement pattern has non-string `replacement` parameter');
  6160. }
  6161. if (pattern.start.length === 0) {
  6162. return err('Replacement pattern has empty `start` parameter');
  6163. }
  6164. return Result.value({
  6165. type: 'inline-command',
  6166. start: '',
  6167. end: pattern.start,
  6168. cmd: 'mceInsertContent',
  6169. value: pattern.replacement
  6170. });
  6171. } else {
  6172. if (pattern.start.length === 0) {
  6173. return err('Block pattern has empty `start` parameter');
  6174. }
  6175. return formatOrCmd('Block', formats => ({
  6176. type: 'block-format',
  6177. start: pattern.start,
  6178. format: formats[0]
  6179. }), (command, commandValue) => ({
  6180. type: 'block-command',
  6181. start: pattern.start,
  6182. cmd: command,
  6183. value: commandValue
  6184. }));
  6185. }
  6186. };
  6187. const getBlockPatterns = patterns => sortPatterns(filter$6(patterns, isBlockPattern));
  6188. const getInlinePatterns = patterns => filter$6(patterns, isInlinePattern);
  6189. const createPatternSet = patterns => ({
  6190. inlinePatterns: getInlinePatterns(patterns),
  6191. blockPatterns: getBlockPatterns(patterns)
  6192. });
  6193. const fromRawPatterns = patterns => {
  6194. const normalized = partition$1(map$3(patterns, normalizePattern));
  6195. each$f(normalized.errors, err => console.error(err.message, err.pattern));
  6196. return normalized.values;
  6197. };
  6198. const deviceDetection$1 = detect$2().deviceType;
  6199. const isTouch = deviceDetection$1.isTouch();
  6200. const DOM$a = DOMUtils.DOM;
  6201. const getHash = value => {
  6202. const items = value.indexOf('=') > 0 ? value.split(/[;,](?![^=;,]*(?:[;,]|$))/) : value.split(',');
  6203. return foldl(items, (output, item) => {
  6204. const arr = item.split('=');
  6205. const key = arr[0];
  6206. const val = arr.length > 1 ? arr[1] : key;
  6207. output[trim$3(key)] = trim$3(val);
  6208. return output;
  6209. }, {});
  6210. };
  6211. const isRegExp = x => is$4(x, RegExp);
  6212. const option = name => editor => editor.options.get(name);
  6213. const stringOrObjectProcessor = value => isString(value) || isObject(value);
  6214. const bodyOptionProcessor = (editor, defaultValue = '') => value => {
  6215. const valid = isString(value);
  6216. if (valid) {
  6217. if (value.indexOf('=') !== -1) {
  6218. const bodyObj = getHash(value);
  6219. return {
  6220. value: get$a(bodyObj, editor.id).getOr(defaultValue),
  6221. valid
  6222. };
  6223. } else {
  6224. return {
  6225. value,
  6226. valid
  6227. };
  6228. }
  6229. } else {
  6230. return {
  6231. valid: false,
  6232. message: 'Must be a string.'
  6233. };
  6234. }
  6235. };
  6236. const register$7 = editor => {
  6237. const registerOption = editor.options.register;
  6238. registerOption('id', {
  6239. processor: 'string',
  6240. default: editor.id
  6241. });
  6242. registerOption('selector', { processor: 'string' });
  6243. registerOption('target', { processor: 'object' });
  6244. registerOption('suffix', { processor: 'string' });
  6245. registerOption('cache_suffix', { processor: 'string' });
  6246. registerOption('base_url', { processor: 'string' });
  6247. registerOption('referrer_policy', {
  6248. processor: 'string',
  6249. default: ''
  6250. });
  6251. registerOption('language_load', { processor: 'boolean' });
  6252. registerOption('inline', {
  6253. processor: 'boolean',
  6254. default: false
  6255. });
  6256. registerOption('iframe_attrs', {
  6257. processor: 'object',
  6258. default: {}
  6259. });
  6260. registerOption('doctype', {
  6261. processor: 'string',
  6262. default: '<!DOCTYPE html>'
  6263. });
  6264. registerOption('document_base_url', {
  6265. processor: 'string',
  6266. default: editor.documentBaseUrl
  6267. });
  6268. registerOption('body_id', {
  6269. processor: bodyOptionProcessor(editor, 'tinymce'),
  6270. default: 'tinymce'
  6271. });
  6272. registerOption('body_class', {
  6273. processor: bodyOptionProcessor(editor),
  6274. default: ''
  6275. });
  6276. registerOption('content_security_policy', {
  6277. processor: 'string',
  6278. default: ''
  6279. });
  6280. registerOption('br_in_pre', {
  6281. processor: 'boolean',
  6282. default: true
  6283. });
  6284. registerOption('forced_root_block', {
  6285. processor: value => {
  6286. const valid = isString(value) && isNotEmpty(value);
  6287. if (valid) {
  6288. return {
  6289. value,
  6290. valid
  6291. };
  6292. } else {
  6293. return {
  6294. valid: false,
  6295. message: 'Must be a non-empty string.'
  6296. };
  6297. }
  6298. },
  6299. default: 'p'
  6300. });
  6301. registerOption('forced_root_block_attrs', {
  6302. processor: 'object',
  6303. default: {}
  6304. });
  6305. registerOption('newline_behavior', {
  6306. processor: value => {
  6307. const valid = contains$2([
  6308. 'block',
  6309. 'linebreak',
  6310. 'invert',
  6311. 'default'
  6312. ], value);
  6313. return valid ? {
  6314. value,
  6315. valid
  6316. } : {
  6317. valid: false,
  6318. message: 'Must be one of: block, linebreak, invert or default.'
  6319. };
  6320. },
  6321. default: 'default'
  6322. });
  6323. registerOption('br_newline_selector', {
  6324. processor: 'string',
  6325. default: '.mce-toc h2,figcaption,caption'
  6326. });
  6327. registerOption('no_newline_selector', {
  6328. processor: 'string',
  6329. default: ''
  6330. });
  6331. registerOption('keep_styles', {
  6332. processor: 'boolean',
  6333. default: true
  6334. });
  6335. registerOption('end_container_on_empty_block', {
  6336. processor: value => {
  6337. if (isBoolean(value)) {
  6338. return {
  6339. valid: true,
  6340. value
  6341. };
  6342. } else if (isString(value)) {
  6343. return {
  6344. valid: true,
  6345. value
  6346. };
  6347. } else {
  6348. return {
  6349. valid: false,
  6350. message: 'Must be boolean or a string'
  6351. };
  6352. }
  6353. },
  6354. default: 'blockquote'
  6355. });
  6356. registerOption('font_size_style_values', {
  6357. processor: 'string',
  6358. default: 'xx-small,x-small,small,medium,large,x-large,xx-large'
  6359. });
  6360. registerOption('font_size_legacy_values', {
  6361. processor: 'string',
  6362. default: 'xx-small,small,medium,large,x-large,xx-large,300%'
  6363. });
  6364. registerOption('font_size_classes', {
  6365. processor: 'string',
  6366. default: ''
  6367. });
  6368. registerOption('automatic_uploads', {
  6369. processor: 'boolean',
  6370. default: true
  6371. });
  6372. registerOption('images_reuse_filename', {
  6373. processor: 'boolean',
  6374. default: false
  6375. });
  6376. registerOption('images_replace_blob_uris', {
  6377. processor: 'boolean',
  6378. default: true
  6379. });
  6380. registerOption('icons', {
  6381. processor: 'string',
  6382. default: ''
  6383. });
  6384. registerOption('icons_url', {
  6385. processor: 'string',
  6386. default: ''
  6387. });
  6388. registerOption('images_upload_url', {
  6389. processor: 'string',
  6390. default: ''
  6391. });
  6392. registerOption('images_upload_base_path', {
  6393. processor: 'string',
  6394. default: ''
  6395. });
  6396. registerOption('images_upload_base_path', {
  6397. processor: 'string',
  6398. default: ''
  6399. });
  6400. registerOption('images_upload_credentials', {
  6401. processor: 'boolean',
  6402. default: false
  6403. });
  6404. registerOption('images_upload_handler', { processor: 'function' });
  6405. registerOption('language', {
  6406. processor: 'string',
  6407. default: 'en'
  6408. });
  6409. registerOption('language_url', {
  6410. processor: 'string',
  6411. default: ''
  6412. });
  6413. registerOption('entity_encoding', {
  6414. processor: 'string',
  6415. default: 'named'
  6416. });
  6417. registerOption('indent', {
  6418. processor: 'boolean',
  6419. default: true
  6420. });
  6421. registerOption('indent_before', {
  6422. processor: 'string',
  6423. 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'
  6424. });
  6425. registerOption('indent_after', {
  6426. processor: 'string',
  6427. 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'
  6428. });
  6429. registerOption('indent_use_margin', {
  6430. processor: 'boolean',
  6431. default: false
  6432. });
  6433. registerOption('indentation', {
  6434. processor: 'string',
  6435. default: '40px'
  6436. });
  6437. registerOption('content_css', {
  6438. processor: value => {
  6439. const valid = value === false || isString(value) || isArrayOf(value, isString);
  6440. if (valid) {
  6441. if (isString(value)) {
  6442. return {
  6443. value: map$3(value.split(','), trim$3),
  6444. valid
  6445. };
  6446. } else if (isArray$1(value)) {
  6447. return {
  6448. value,
  6449. valid
  6450. };
  6451. } else if (value === false) {
  6452. return {
  6453. value: [],
  6454. valid
  6455. };
  6456. } else {
  6457. return {
  6458. value,
  6459. valid
  6460. };
  6461. }
  6462. } else {
  6463. return {
  6464. valid: false,
  6465. message: 'Must be false, a string or an array of strings.'
  6466. };
  6467. }
  6468. },
  6469. default: isInline(editor) ? [] : ['default']
  6470. });
  6471. registerOption('content_style', { processor: 'string' });
  6472. registerOption('content_css_cors', {
  6473. processor: 'boolean',
  6474. default: false
  6475. });
  6476. registerOption('font_css', {
  6477. processor: value => {
  6478. const valid = isString(value) || isArrayOf(value, isString);
  6479. if (valid) {
  6480. const newValue = isArray$1(value) ? value : map$3(value.split(','), trim$3);
  6481. return {
  6482. value: newValue,
  6483. valid
  6484. };
  6485. } else {
  6486. return {
  6487. valid: false,
  6488. message: 'Must be a string or an array of strings.'
  6489. };
  6490. }
  6491. },
  6492. default: []
  6493. });
  6494. registerOption('inline_boundaries', {
  6495. processor: 'boolean',
  6496. default: true
  6497. });
  6498. registerOption('inline_boundaries_selector', {
  6499. processor: 'string',
  6500. default: 'a[href],code,span.mce-annotation'
  6501. });
  6502. registerOption('object_resizing', {
  6503. processor: value => {
  6504. const valid = isBoolean(value) || isString(value);
  6505. if (valid) {
  6506. if (value === false || deviceDetection$1.isiPhone() || deviceDetection$1.isiPad()) {
  6507. return {
  6508. value: '',
  6509. valid
  6510. };
  6511. } else {
  6512. return {
  6513. value: value === true ? 'table,img,figure.image,div,video,iframe' : value,
  6514. valid
  6515. };
  6516. }
  6517. } else {
  6518. return {
  6519. valid: false,
  6520. message: 'Must be boolean or a string'
  6521. };
  6522. }
  6523. },
  6524. default: !isTouch
  6525. });
  6526. registerOption('resize_img_proportional', {
  6527. processor: 'boolean',
  6528. default: true
  6529. });
  6530. registerOption('event_root', { processor: 'object' });
  6531. registerOption('service_message', { processor: 'string' });
  6532. registerOption('theme', {
  6533. processor: value => value === false || isString(value) || isFunction(value),
  6534. default: 'silver'
  6535. });
  6536. registerOption('theme_url', { processor: 'string' });
  6537. registerOption('formats', { processor: 'object' });
  6538. registerOption('format_empty_lines', {
  6539. processor: 'boolean',
  6540. default: false
  6541. });
  6542. registerOption('preview_styles', {
  6543. processor: value => {
  6544. const valid = value === false || isString(value);
  6545. if (valid) {
  6546. return {
  6547. value: value === false ? '' : value,
  6548. valid
  6549. };
  6550. } else {
  6551. return {
  6552. valid: false,
  6553. message: 'Must be false or a string'
  6554. };
  6555. }
  6556. },
  6557. default: 'font-family font-size font-weight font-style text-decoration text-transform color background-color border border-radius outline text-shadow'
  6558. });
  6559. registerOption('custom_ui_selector', {
  6560. processor: 'string',
  6561. default: ''
  6562. });
  6563. registerOption('hidden_input', {
  6564. processor: 'boolean',
  6565. default: true
  6566. });
  6567. registerOption('submit_patch', {
  6568. processor: 'boolean',
  6569. default: true
  6570. });
  6571. registerOption('encoding', { processor: 'string' });
  6572. registerOption('add_form_submit_trigger', {
  6573. processor: 'boolean',
  6574. default: true
  6575. });
  6576. registerOption('add_unload_trigger', {
  6577. processor: 'boolean',
  6578. default: true
  6579. });
  6580. registerOption('custom_undo_redo_levels', {
  6581. processor: 'number',
  6582. default: 0
  6583. });
  6584. registerOption('disable_nodechange', {
  6585. processor: 'boolean',
  6586. default: false
  6587. });
  6588. registerOption('readonly', {
  6589. processor: 'boolean',
  6590. default: false
  6591. });
  6592. registerOption('plugins', {
  6593. processor: 'string[]',
  6594. default: []
  6595. });
  6596. registerOption('external_plugins', { processor: 'object' });
  6597. registerOption('forced_plugins', { processor: 'string[]' });
  6598. registerOption('model', {
  6599. processor: 'string',
  6600. default: editor.hasPlugin('rtc') ? 'plugin' : 'dom'
  6601. });
  6602. registerOption('model_url', { processor: 'string' });
  6603. registerOption('block_unsupported_drop', {
  6604. processor: 'boolean',
  6605. default: true
  6606. });
  6607. registerOption('visual', {
  6608. processor: 'boolean',
  6609. default: true
  6610. });
  6611. registerOption('visual_table_class', {
  6612. processor: 'string',
  6613. default: 'mce-item-table'
  6614. });
  6615. registerOption('visual_anchor_class', {
  6616. processor: 'string',
  6617. default: 'mce-item-anchor'
  6618. });
  6619. registerOption('iframe_aria_text', {
  6620. processor: 'string',
  6621. default: 'Rich Text Area. Press ALT-0 for help.'
  6622. });
  6623. registerOption('setup', { processor: 'function' });
  6624. registerOption('init_instance_callback', { processor: 'function' });
  6625. registerOption('url_converter', {
  6626. processor: 'function',
  6627. default: editor.convertURL
  6628. });
  6629. registerOption('url_converter_scope', {
  6630. processor: 'object',
  6631. default: editor
  6632. });
  6633. registerOption('urlconverter_callback', { processor: 'function' });
  6634. registerOption('allow_conditional_comments', {
  6635. processor: 'boolean',
  6636. default: false
  6637. });
  6638. registerOption('allow_html_data_urls', {
  6639. processor: 'boolean',
  6640. default: false
  6641. });
  6642. registerOption('allow_svg_data_urls', { processor: 'boolean' });
  6643. registerOption('allow_html_in_named_anchor', {
  6644. processor: 'boolean',
  6645. default: false
  6646. });
  6647. registerOption('allow_script_urls', {
  6648. processor: 'boolean',
  6649. default: false
  6650. });
  6651. registerOption('allow_unsafe_link_target', {
  6652. processor: 'boolean',
  6653. default: false
  6654. });
  6655. registerOption('convert_fonts_to_spans', {
  6656. processor: 'boolean',
  6657. default: true,
  6658. deprecated: true
  6659. });
  6660. registerOption('fix_list_elements', {
  6661. processor: 'boolean',
  6662. default: false
  6663. });
  6664. registerOption('preserve_cdata', {
  6665. processor: 'boolean',
  6666. default: false
  6667. });
  6668. registerOption('remove_trailing_brs', { processor: 'boolean' });
  6669. registerOption('inline_styles', {
  6670. processor: 'boolean',
  6671. default: true,
  6672. deprecated: true
  6673. });
  6674. registerOption('element_format', {
  6675. processor: 'string',
  6676. default: 'html'
  6677. });
  6678. registerOption('entities', { processor: 'string' });
  6679. registerOption('schema', {
  6680. processor: 'string',
  6681. default: 'html5'
  6682. });
  6683. registerOption('convert_urls', {
  6684. processor: 'boolean',
  6685. default: true
  6686. });
  6687. registerOption('relative_urls', {
  6688. processor: 'boolean',
  6689. default: true
  6690. });
  6691. registerOption('remove_script_host', {
  6692. processor: 'boolean',
  6693. default: true
  6694. });
  6695. registerOption('custom_elements', { processor: 'string' });
  6696. registerOption('extended_valid_elements', { processor: 'string' });
  6697. registerOption('invalid_elements', { processor: 'string' });
  6698. registerOption('invalid_styles', { processor: stringOrObjectProcessor });
  6699. registerOption('valid_children', { processor: 'string' });
  6700. registerOption('valid_classes', { processor: stringOrObjectProcessor });
  6701. registerOption('valid_elements', { processor: 'string' });
  6702. registerOption('valid_styles', { processor: stringOrObjectProcessor });
  6703. registerOption('verify_html', {
  6704. processor: 'boolean',
  6705. default: true
  6706. });
  6707. registerOption('auto_focus', { processor: value => isString(value) || value === true });
  6708. registerOption('browser_spellcheck', {
  6709. processor: 'boolean',
  6710. default: false
  6711. });
  6712. registerOption('protect', { processor: 'array' });
  6713. registerOption('images_file_types', {
  6714. processor: 'string',
  6715. default: 'jpeg,jpg,jpe,jfi,jif,jfif,png,gif,bmp,webp'
  6716. });
  6717. registerOption('deprecation_warnings', {
  6718. processor: 'boolean',
  6719. default: true
  6720. });
  6721. registerOption('a11y_advanced_options', {
  6722. processor: 'boolean',
  6723. default: false
  6724. });
  6725. registerOption('api_key', { processor: 'string' });
  6726. registerOption('paste_block_drop', {
  6727. processor: 'boolean',
  6728. default: false
  6729. });
  6730. registerOption('paste_data_images', {
  6731. processor: 'boolean',
  6732. default: true
  6733. });
  6734. registerOption('paste_preprocess', { processor: 'function' });
  6735. registerOption('paste_postprocess', { processor: 'function' });
  6736. registerOption('paste_webkit_styles', {
  6737. processor: 'string',
  6738. default: 'none'
  6739. });
  6740. registerOption('paste_remove_styles_if_webkit', {
  6741. processor: 'boolean',
  6742. default: true
  6743. });
  6744. registerOption('paste_merge_formats', {
  6745. processor: 'boolean',
  6746. default: true
  6747. });
  6748. registerOption('smart_paste', {
  6749. processor: 'boolean',
  6750. default: true
  6751. });
  6752. registerOption('paste_as_text', {
  6753. processor: 'boolean',
  6754. default: false
  6755. });
  6756. registerOption('paste_tab_spaces', {
  6757. processor: 'number',
  6758. default: 4
  6759. });
  6760. registerOption('text_patterns', {
  6761. processor: value => {
  6762. if (isArrayOf(value, isObject) || value === false) {
  6763. const patterns = value === false ? [] : value;
  6764. return {
  6765. value: fromRawPatterns(patterns),
  6766. valid: true
  6767. };
  6768. } else {
  6769. return {
  6770. valid: false,
  6771. message: 'Must be an array of objects or false.'
  6772. };
  6773. }
  6774. },
  6775. default: [
  6776. {
  6777. start: '*',
  6778. end: '*',
  6779. format: 'italic'
  6780. },
  6781. {
  6782. start: '**',
  6783. end: '**',
  6784. format: 'bold'
  6785. },
  6786. {
  6787. start: '#',
  6788. format: 'h1'
  6789. },
  6790. {
  6791. start: '##',
  6792. format: 'h2'
  6793. },
  6794. {
  6795. start: '###',
  6796. format: 'h3'
  6797. },
  6798. {
  6799. start: '####',
  6800. format: 'h4'
  6801. },
  6802. {
  6803. start: '#####',
  6804. format: 'h5'
  6805. },
  6806. {
  6807. start: '######',
  6808. format: 'h6'
  6809. },
  6810. {
  6811. start: '1. ',
  6812. cmd: 'InsertOrderedList'
  6813. },
  6814. {
  6815. start: '* ',
  6816. cmd: 'InsertUnorderedList'
  6817. },
  6818. {
  6819. start: '- ',
  6820. cmd: 'InsertUnorderedList'
  6821. }
  6822. ]
  6823. });
  6824. registerOption('noneditable_class', {
  6825. processor: 'string',
  6826. default: 'mceNonEditable'
  6827. });
  6828. registerOption('editable_class', {
  6829. processor: 'string',
  6830. default: 'mceEditable'
  6831. });
  6832. registerOption('noneditable_regexp', {
  6833. processor: value => {
  6834. if (isArrayOf(value, isRegExp)) {
  6835. return {
  6836. value,
  6837. valid: true
  6838. };
  6839. } else if (isRegExp(value)) {
  6840. return {
  6841. value: [value],
  6842. valid: true
  6843. };
  6844. } else {
  6845. return {
  6846. valid: false,
  6847. message: 'Must be a RegExp or an array of RegExp.'
  6848. };
  6849. }
  6850. },
  6851. default: []
  6852. });
  6853. registerOption('table_tab_navigation', {
  6854. processor: 'boolean',
  6855. default: true
  6856. });
  6857. editor.on('ScriptsLoaded', () => {
  6858. registerOption('directionality', {
  6859. processor: 'string',
  6860. default: I18n.isRtl() ? 'rtl' : undefined
  6861. });
  6862. registerOption('placeholder', {
  6863. processor: 'string',
  6864. default: DOM$a.getAttrib(editor.getElement(), 'placeholder')
  6865. });
  6866. });
  6867. };
  6868. const getIframeAttrs = option('iframe_attrs');
  6869. const getDocType = option('doctype');
  6870. const getDocumentBaseUrl = option('document_base_url');
  6871. const getBodyId = option('body_id');
  6872. const getBodyClass = option('body_class');
  6873. const getContentSecurityPolicy = option('content_security_policy');
  6874. const shouldPutBrInPre$1 = option('br_in_pre');
  6875. const getForcedRootBlock = option('forced_root_block');
  6876. const getForcedRootBlockAttrs = option('forced_root_block_attrs');
  6877. const getNewlineBehavior = option('newline_behavior');
  6878. const getBrNewLineSelector = option('br_newline_selector');
  6879. const getNoNewLineSelector = option('no_newline_selector');
  6880. const shouldKeepStyles = option('keep_styles');
  6881. const shouldEndContainerOnEmptyBlock = option('end_container_on_empty_block');
  6882. const isAutomaticUploadsEnabled = option('automatic_uploads');
  6883. const shouldReuseFileName = option('images_reuse_filename');
  6884. const shouldReplaceBlobUris = option('images_replace_blob_uris');
  6885. const getIconPackName = option('icons');
  6886. const getIconsUrl = option('icons_url');
  6887. const getImageUploadUrl = option('images_upload_url');
  6888. const getImageUploadBasePath = option('images_upload_base_path');
  6889. const getImagesUploadCredentials = option('images_upload_credentials');
  6890. const getImagesUploadHandler = option('images_upload_handler');
  6891. const shouldUseContentCssCors = option('content_css_cors');
  6892. const getReferrerPolicy = option('referrer_policy');
  6893. const getLanguageCode = option('language');
  6894. const getLanguageUrl = option('language_url');
  6895. const shouldIndentUseMargin = option('indent_use_margin');
  6896. const getIndentation = option('indentation');
  6897. const getContentCss = option('content_css');
  6898. const getContentStyle = option('content_style');
  6899. const getFontCss = option('font_css');
  6900. const getDirectionality = option('directionality');
  6901. const getInlineBoundarySelector = option('inline_boundaries_selector');
  6902. const getObjectResizing = option('object_resizing');
  6903. const getResizeImgProportional = option('resize_img_proportional');
  6904. const getPlaceholder = option('placeholder');
  6905. const getEventRoot = option('event_root');
  6906. const getServiceMessage = option('service_message');
  6907. const getTheme = option('theme');
  6908. const getThemeUrl = option('theme_url');
  6909. const getModel = option('model');
  6910. const getModelUrl = option('model_url');
  6911. const isInlineBoundariesEnabled = option('inline_boundaries');
  6912. const getFormats = option('formats');
  6913. const getPreviewStyles = option('preview_styles');
  6914. const canFormatEmptyLines = option('format_empty_lines');
  6915. const getCustomUiSelector = option('custom_ui_selector');
  6916. const isInline = option('inline');
  6917. const hasHiddenInput = option('hidden_input');
  6918. const shouldPatchSubmit = option('submit_patch');
  6919. const shouldAddFormSubmitTrigger = option('add_form_submit_trigger');
  6920. const shouldAddUnloadTrigger = option('add_unload_trigger');
  6921. const getCustomUndoRedoLevels = option('custom_undo_redo_levels');
  6922. const shouldDisableNodeChange = option('disable_nodechange');
  6923. const isReadOnly$1 = option('readonly');
  6924. const hasContentCssCors = option('content_css_cors');
  6925. const getPlugins = option('plugins');
  6926. const getExternalPlugins$1 = option('external_plugins');
  6927. const shouldBlockUnsupportedDrop = option('block_unsupported_drop');
  6928. const isVisualAidsEnabled = option('visual');
  6929. const getVisualAidsTableClass = option('visual_table_class');
  6930. const getVisualAidsAnchorClass = option('visual_anchor_class');
  6931. const getIframeAriaText = option('iframe_aria_text');
  6932. const getSetupCallback = option('setup');
  6933. const getInitInstanceCallback = option('init_instance_callback');
  6934. const getUrlConverterCallback = option('urlconverter_callback');
  6935. const getAutoFocus = option('auto_focus');
  6936. const shouldBrowserSpellcheck = option('browser_spellcheck');
  6937. const getProtect = option('protect');
  6938. const shouldPasteBlockDrop = option('paste_block_drop');
  6939. const shouldPasteDataImages = option('paste_data_images');
  6940. const getPastePreProcess = option('paste_preprocess');
  6941. const getPastePostProcess = option('paste_postprocess');
  6942. const getPasteWebkitStyles = option('paste_webkit_styles');
  6943. const shouldPasteRemoveWebKitStyles = option('paste_remove_styles_if_webkit');
  6944. const shouldPasteMergeFormats = option('paste_merge_formats');
  6945. const isSmartPasteEnabled = option('smart_paste');
  6946. const isPasteAsTextEnabled = option('paste_as_text');
  6947. const getPasteTabSpaces = option('paste_tab_spaces');
  6948. const shouldAllowHtmlDataUrls = option('allow_html_data_urls');
  6949. const getTextPatterns = option('text_patterns');
  6950. const getNonEditableClass = option('noneditable_class');
  6951. const getEditableClass = option('editable_class');
  6952. const getNonEditableRegExps = option('noneditable_regexp');
  6953. const getFontStyleValues = editor => Tools.explode(editor.options.get('font_size_style_values'));
  6954. const getFontSizeClasses = editor => Tools.explode(editor.options.get('font_size_classes'));
  6955. const isEncodingXml = editor => editor.options.get('encoding') === 'xml';
  6956. const getAllowedImageFileTypes = editor => Tools.explode(editor.options.get('images_file_types'));
  6957. const hasTableTabNavigation = option('table_tab_navigation');
  6958. const isElement$3 = isElement$6;
  6959. const isText$4 = isText$9;
  6960. const removeNode$1 = node => {
  6961. const parentNode = node.parentNode;
  6962. if (parentNode) {
  6963. parentNode.removeChild(node);
  6964. }
  6965. };
  6966. const trimCount = text => {
  6967. const trimmedText = trim$1(text);
  6968. return {
  6969. count: text.length - trimmedText.length,
  6970. text: trimmedText
  6971. };
  6972. };
  6973. const deleteZwspChars = caretContainer => {
  6974. let idx;
  6975. while ((idx = caretContainer.data.lastIndexOf(ZWSP$1)) !== -1) {
  6976. caretContainer.deleteData(idx, 1);
  6977. }
  6978. };
  6979. const removeUnchanged = (caretContainer, pos) => {
  6980. remove$4(caretContainer);
  6981. return pos;
  6982. };
  6983. const removeTextAndReposition = (caretContainer, pos) => {
  6984. const before = trimCount(caretContainer.data.substr(0, pos.offset()));
  6985. const after = trimCount(caretContainer.data.substr(pos.offset()));
  6986. const text = before.text + after.text;
  6987. if (text.length > 0) {
  6988. deleteZwspChars(caretContainer);
  6989. return CaretPosition(caretContainer, pos.offset() - before.count);
  6990. } else {
  6991. return pos;
  6992. }
  6993. };
  6994. const removeElementAndReposition = (caretContainer, pos) => {
  6995. const parentNode = pos.container();
  6996. const newPosition = indexOf$1(from(parentNode.childNodes), caretContainer).map(index => {
  6997. return index < pos.offset() ? CaretPosition(parentNode, pos.offset() - 1) : pos;
  6998. }).getOr(pos);
  6999. remove$4(caretContainer);
  7000. return newPosition;
  7001. };
  7002. const removeTextCaretContainer = (caretContainer, pos) => isText$4(caretContainer) && pos.container() === caretContainer ? removeTextAndReposition(caretContainer, pos) : removeUnchanged(caretContainer, pos);
  7003. const removeElementCaretContainer = (caretContainer, pos) => pos.container() === caretContainer.parentNode ? removeElementAndReposition(caretContainer, pos) : removeUnchanged(caretContainer, pos);
  7004. const removeAndReposition = (container, pos) => CaretPosition.isTextPosition(pos) ? removeTextCaretContainer(container, pos) : removeElementCaretContainer(container, pos);
  7005. const remove$4 = caretContainerNode => {
  7006. if (isElement$3(caretContainerNode) && isCaretContainer$2(caretContainerNode)) {
  7007. if (hasContent(caretContainerNode)) {
  7008. caretContainerNode.removeAttribute('data-mce-caret');
  7009. } else {
  7010. removeNode$1(caretContainerNode);
  7011. }
  7012. }
  7013. if (isText$4(caretContainerNode)) {
  7014. deleteZwspChars(caretContainerNode);
  7015. if (caretContainerNode.data.length === 0) {
  7016. removeNode$1(caretContainerNode);
  7017. }
  7018. }
  7019. };
  7020. const isContentEditableFalse$8 = isContentEditableFalse$b;
  7021. const isMedia$1 = isMedia$2;
  7022. const isTableCell$3 = isTableCell$5;
  7023. const inlineFakeCaretSelector = '*[contentEditable=false],video,audio,embed,object';
  7024. const getAbsoluteClientRect = (root, element, before) => {
  7025. const clientRect = collapse(element.getBoundingClientRect(), before);
  7026. let scrollX;
  7027. let scrollY;
  7028. if (root.tagName === 'BODY') {
  7029. const docElm = root.ownerDocument.documentElement;
  7030. scrollX = root.scrollLeft || docElm.scrollLeft;
  7031. scrollY = root.scrollTop || docElm.scrollTop;
  7032. } else {
  7033. const rootRect = root.getBoundingClientRect();
  7034. scrollX = root.scrollLeft - rootRect.left;
  7035. scrollY = root.scrollTop - rootRect.top;
  7036. }
  7037. clientRect.left += scrollX;
  7038. clientRect.right += scrollX;
  7039. clientRect.top += scrollY;
  7040. clientRect.bottom += scrollY;
  7041. clientRect.width = 1;
  7042. let margin = element.offsetWidth - element.clientWidth;
  7043. if (margin > 0) {
  7044. if (before) {
  7045. margin *= -1;
  7046. }
  7047. clientRect.left += margin;
  7048. clientRect.right += margin;
  7049. }
  7050. return clientRect;
  7051. };
  7052. const trimInlineCaretContainers = root => {
  7053. const fakeCaretTargetNodes = descendants(SugarElement.fromDom(root), inlineFakeCaretSelector);
  7054. for (let i = 0; i < fakeCaretTargetNodes.length; i++) {
  7055. const node = fakeCaretTargetNodes[i].dom;
  7056. let sibling = node.previousSibling;
  7057. if (endsWithCaretContainer$1(sibling)) {
  7058. const data = sibling.data;
  7059. if (data.length === 1) {
  7060. sibling.parentNode.removeChild(sibling);
  7061. } else {
  7062. sibling.deleteData(data.length - 1, 1);
  7063. }
  7064. }
  7065. sibling = node.nextSibling;
  7066. if (startsWithCaretContainer$1(sibling)) {
  7067. const data = sibling.data;
  7068. if (data.length === 1) {
  7069. sibling.parentNode.removeChild(sibling);
  7070. } else {
  7071. sibling.deleteData(0, 1);
  7072. }
  7073. }
  7074. }
  7075. };
  7076. const FakeCaret = (editor, root, isBlock, hasFocus) => {
  7077. const lastVisualCaret = value$2();
  7078. let cursorInterval;
  7079. let caretContainerNode;
  7080. const caretBlock = getForcedRootBlock(editor);
  7081. const dom = editor.dom;
  7082. const show = (before, element) => {
  7083. let rng;
  7084. hide();
  7085. if (isTableCell$3(element)) {
  7086. return null;
  7087. }
  7088. if (isBlock(element)) {
  7089. caretContainerNode = insertBlock(caretBlock, element, before);
  7090. const clientRect = getAbsoluteClientRect(root, element, before);
  7091. dom.setStyle(caretContainerNode, 'top', clientRect.top);
  7092. const caret = dom.create('div', {
  7093. 'class': 'mce-visual-caret',
  7094. 'data-mce-bogus': 'all'
  7095. });
  7096. dom.setStyles(caret, { ...clientRect });
  7097. dom.add(root, caret);
  7098. lastVisualCaret.set({
  7099. caret,
  7100. element,
  7101. before
  7102. });
  7103. if (before) {
  7104. dom.addClass(caret, 'mce-visual-caret-before');
  7105. }
  7106. startBlink();
  7107. rng = element.ownerDocument.createRange();
  7108. rng.setStart(caretContainerNode, 0);
  7109. rng.setEnd(caretContainerNode, 0);
  7110. } else {
  7111. caretContainerNode = insertInline$1(element, before);
  7112. rng = element.ownerDocument.createRange();
  7113. if (isInlineFakeCaretTarget(caretContainerNode.nextSibling)) {
  7114. rng.setStart(caretContainerNode, 0);
  7115. rng.setEnd(caretContainerNode, 0);
  7116. } else {
  7117. rng.setStart(caretContainerNode, 1);
  7118. rng.setEnd(caretContainerNode, 1);
  7119. }
  7120. return rng;
  7121. }
  7122. return rng;
  7123. };
  7124. const hide = () => {
  7125. trimInlineCaretContainers(root);
  7126. if (caretContainerNode) {
  7127. remove$4(caretContainerNode);
  7128. caretContainerNode = null;
  7129. }
  7130. lastVisualCaret.on(caretState => {
  7131. dom.remove(caretState.caret);
  7132. lastVisualCaret.clear();
  7133. });
  7134. if (cursorInterval) {
  7135. clearInterval(cursorInterval);
  7136. cursorInterval = undefined;
  7137. }
  7138. };
  7139. const startBlink = () => {
  7140. cursorInterval = setInterval(() => {
  7141. lastVisualCaret.on(caretState => {
  7142. if (hasFocus()) {
  7143. dom.toggleClass(caretState.caret, 'mce-visual-caret-hidden');
  7144. } else {
  7145. dom.addClass(caretState.caret, 'mce-visual-caret-hidden');
  7146. }
  7147. });
  7148. }, 500);
  7149. };
  7150. const reposition = () => {
  7151. lastVisualCaret.on(caretState => {
  7152. const clientRect = getAbsoluteClientRect(root, caretState.element, caretState.before);
  7153. dom.setStyles(caretState.caret, { ...clientRect });
  7154. });
  7155. };
  7156. const destroy = () => clearInterval(cursorInterval);
  7157. 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;' + '}';
  7158. return {
  7159. show,
  7160. hide,
  7161. getCss,
  7162. reposition,
  7163. destroy
  7164. };
  7165. };
  7166. const isFakeCaretTableBrowser = () => Env.browser.isFirefox();
  7167. const isInlineFakeCaretTarget = node => isContentEditableFalse$8(node) || isMedia$1(node);
  7168. const isFakeCaretTarget = node => isInlineFakeCaretTarget(node) || isTable$3(node) && isFakeCaretTableBrowser();
  7169. const isContentEditableTrue$3 = isContentEditableTrue$5;
  7170. const isContentEditableFalse$7 = isContentEditableFalse$b;
  7171. const isMedia = isMedia$2;
  7172. const isBlockLike = matchStyleValues('display', 'block table table-cell table-caption list-item');
  7173. const isCaretContainer = isCaretContainer$2;
  7174. const isCaretContainerBlock = isCaretContainerBlock$1;
  7175. const isElement$2 = isElement$6;
  7176. const isCaretCandidate$1 = isCaretCandidate$3;
  7177. const isForwards = direction => direction > 0;
  7178. const isBackwards = direction => direction < 0;
  7179. const skipCaretContainers = (walk, shallow) => {
  7180. let node;
  7181. while (node = walk(shallow)) {
  7182. if (!isCaretContainerBlock(node)) {
  7183. return node;
  7184. }
  7185. }
  7186. return null;
  7187. };
  7188. const findNode = (node, direction, predicateFn, rootNode, shallow) => {
  7189. const walker = new DomTreeWalker(node, rootNode);
  7190. const isCefOrCaretContainer = isContentEditableFalse$7(node) || isCaretContainerBlock(node);
  7191. if (isBackwards(direction)) {
  7192. if (isCefOrCaretContainer) {
  7193. node = skipCaretContainers(walker.prev.bind(walker), true);
  7194. if (predicateFn(node)) {
  7195. return node;
  7196. }
  7197. }
  7198. while (node = skipCaretContainers(walker.prev.bind(walker), shallow)) {
  7199. if (predicateFn(node)) {
  7200. return node;
  7201. }
  7202. }
  7203. }
  7204. if (isForwards(direction)) {
  7205. if (isCefOrCaretContainer) {
  7206. node = skipCaretContainers(walker.next.bind(walker), true);
  7207. if (predicateFn(node)) {
  7208. return node;
  7209. }
  7210. }
  7211. while (node = skipCaretContainers(walker.next.bind(walker), shallow)) {
  7212. if (predicateFn(node)) {
  7213. return node;
  7214. }
  7215. }
  7216. }
  7217. return null;
  7218. };
  7219. const getEditingHost = (node, rootNode) => {
  7220. const isCETrue = node => isContentEditableTrue$3(node.dom);
  7221. const isRoot = node => node.dom === rootNode;
  7222. return ancestor$3(SugarElement.fromDom(node), isCETrue, isRoot).map(elm => elm.dom).getOr(rootNode);
  7223. };
  7224. const getParentBlock$3 = (node, rootNode) => {
  7225. while (node && node !== rootNode) {
  7226. if (isBlockLike(node)) {
  7227. return node;
  7228. }
  7229. node = node.parentNode;
  7230. }
  7231. return null;
  7232. };
  7233. const isInSameBlock = (caretPosition1, caretPosition2, rootNode) => getParentBlock$3(caretPosition1.container(), rootNode) === getParentBlock$3(caretPosition2.container(), rootNode);
  7234. const getChildNodeAtRelativeOffset = (relativeOffset, caretPosition) => {
  7235. if (!caretPosition) {
  7236. return null;
  7237. }
  7238. const container = caretPosition.container();
  7239. const offset = caretPosition.offset();
  7240. if (!isElement$2(container)) {
  7241. return null;
  7242. }
  7243. return container.childNodes[offset + relativeOffset];
  7244. };
  7245. const beforeAfter = (before, node) => {
  7246. const range = node.ownerDocument.createRange();
  7247. if (before) {
  7248. range.setStartBefore(node);
  7249. range.setEndBefore(node);
  7250. } else {
  7251. range.setStartAfter(node);
  7252. range.setEndAfter(node);
  7253. }
  7254. return range;
  7255. };
  7256. const isNodesInSameBlock = (root, node1, node2) => getParentBlock$3(node1, root) === getParentBlock$3(node2, root);
  7257. const lean = (left, root, node) => {
  7258. const siblingName = left ? 'previousSibling' : 'nextSibling';
  7259. while (node && node !== root) {
  7260. let sibling = node[siblingName];
  7261. if (isCaretContainer(sibling)) {
  7262. sibling = sibling[siblingName];
  7263. }
  7264. if (isContentEditableFalse$7(sibling) || isMedia(sibling)) {
  7265. if (isNodesInSameBlock(root, sibling, node)) {
  7266. return sibling;
  7267. }
  7268. break;
  7269. }
  7270. if (isCaretCandidate$1(sibling)) {
  7271. break;
  7272. }
  7273. node = node.parentNode;
  7274. }
  7275. return null;
  7276. };
  7277. const before$2 = curry(beforeAfter, true);
  7278. const after$2 = curry(beforeAfter, false);
  7279. const normalizeRange = (direction, root, range) => {
  7280. let node;
  7281. const leanLeft = curry(lean, true, root);
  7282. const leanRight = curry(lean, false, root);
  7283. let container = range.startContainer;
  7284. const offset = range.startOffset;
  7285. if (isCaretContainerBlock$1(container)) {
  7286. if (!isElement$2(container)) {
  7287. container = container.parentNode;
  7288. }
  7289. const location = container.getAttribute('data-mce-caret');
  7290. if (location === 'before') {
  7291. node = container.nextSibling;
  7292. if (isFakeCaretTarget(node)) {
  7293. return before$2(node);
  7294. }
  7295. }
  7296. if (location === 'after') {
  7297. node = container.previousSibling;
  7298. if (isFakeCaretTarget(node)) {
  7299. return after$2(node);
  7300. }
  7301. }
  7302. }
  7303. if (!range.collapsed) {
  7304. return range;
  7305. }
  7306. if (isText$9(container)) {
  7307. if (isCaretContainer(container)) {
  7308. if (direction === 1) {
  7309. node = leanRight(container);
  7310. if (node) {
  7311. return before$2(node);
  7312. }
  7313. node = leanLeft(container);
  7314. if (node) {
  7315. return after$2(node);
  7316. }
  7317. }
  7318. if (direction === -1) {
  7319. node = leanLeft(container);
  7320. if (node) {
  7321. return after$2(node);
  7322. }
  7323. node = leanRight(container);
  7324. if (node) {
  7325. return before$2(node);
  7326. }
  7327. }
  7328. return range;
  7329. }
  7330. if (endsWithCaretContainer$1(container) && offset >= container.data.length - 1) {
  7331. if (direction === 1) {
  7332. node = leanRight(container);
  7333. if (node) {
  7334. return before$2(node);
  7335. }
  7336. }
  7337. return range;
  7338. }
  7339. if (startsWithCaretContainer$1(container) && offset <= 1) {
  7340. if (direction === -1) {
  7341. node = leanLeft(container);
  7342. if (node) {
  7343. return after$2(node);
  7344. }
  7345. }
  7346. return range;
  7347. }
  7348. if (offset === container.data.length) {
  7349. node = leanRight(container);
  7350. if (node) {
  7351. return before$2(node);
  7352. }
  7353. return range;
  7354. }
  7355. if (offset === 0) {
  7356. node = leanLeft(container);
  7357. if (node) {
  7358. return after$2(node);
  7359. }
  7360. return range;
  7361. }
  7362. }
  7363. return range;
  7364. };
  7365. const getRelativeCefElm = (forward, caretPosition) => Optional.from(getChildNodeAtRelativeOffset(forward ? 0 : -1, caretPosition)).filter(isContentEditableFalse$7);
  7366. const getNormalizedRangeEndPoint = (direction, root, range) => {
  7367. const normalizedRange = normalizeRange(direction, root, range);
  7368. if (direction === -1) {
  7369. return CaretPosition.fromRangeStart(normalizedRange);
  7370. }
  7371. return CaretPosition.fromRangeEnd(normalizedRange);
  7372. };
  7373. const getElementFromPosition = pos => Optional.from(pos.getNode()).map(SugarElement.fromDom);
  7374. const getElementFromPrevPosition = pos => Optional.from(pos.getNode(true)).map(SugarElement.fromDom);
  7375. const getVisualCaretPosition = (walkFn, caretPosition) => {
  7376. while (caretPosition = walkFn(caretPosition)) {
  7377. if (caretPosition.isVisible()) {
  7378. return caretPosition;
  7379. }
  7380. }
  7381. return caretPosition;
  7382. };
  7383. const isMoveInsideSameBlock = (from, to) => {
  7384. const inSameBlock = isInSameBlock(from, to);
  7385. if (!inSameBlock && isBr$6(from.getNode())) {
  7386. return true;
  7387. }
  7388. return inSameBlock;
  7389. };
  7390. var HDirection;
  7391. (function (HDirection) {
  7392. HDirection[HDirection['Backwards'] = -1] = 'Backwards';
  7393. HDirection[HDirection['Forwards'] = 1] = 'Forwards';
  7394. }(HDirection || (HDirection = {})));
  7395. const isContentEditableFalse$6 = isContentEditableFalse$b;
  7396. const isText$3 = isText$9;
  7397. const isElement$1 = isElement$6;
  7398. const isBr$2 = isBr$6;
  7399. const isCaretCandidate = isCaretCandidate$3;
  7400. const isAtomic = isAtomic$1;
  7401. const isEditableCaretCandidate = isEditableCaretCandidate$1;
  7402. const getParents$3 = (node, root) => {
  7403. const parents = [];
  7404. while (node && node !== root) {
  7405. parents.push(node);
  7406. node = node.parentNode;
  7407. }
  7408. return parents;
  7409. };
  7410. const nodeAtIndex = (container, offset) => {
  7411. if (container.hasChildNodes() && offset < container.childNodes.length) {
  7412. return container.childNodes[offset];
  7413. }
  7414. return null;
  7415. };
  7416. const getCaretCandidatePosition = (direction, node) => {
  7417. if (isForwards(direction)) {
  7418. if (isCaretCandidate(node.previousSibling) && !isText$3(node.previousSibling)) {
  7419. return CaretPosition.before(node);
  7420. }
  7421. if (isText$3(node)) {
  7422. return CaretPosition(node, 0);
  7423. }
  7424. }
  7425. if (isBackwards(direction)) {
  7426. if (isCaretCandidate(node.nextSibling) && !isText$3(node.nextSibling)) {
  7427. return CaretPosition.after(node);
  7428. }
  7429. if (isText$3(node)) {
  7430. return CaretPosition(node, node.data.length);
  7431. }
  7432. }
  7433. if (isBackwards(direction)) {
  7434. if (isBr$2(node)) {
  7435. return CaretPosition.before(node);
  7436. }
  7437. return CaretPosition.after(node);
  7438. }
  7439. return CaretPosition.before(node);
  7440. };
  7441. const moveForwardFromBr = (root, nextNode) => {
  7442. const nextSibling = nextNode.nextSibling;
  7443. if (nextSibling && isCaretCandidate(nextSibling)) {
  7444. if (isText$3(nextSibling)) {
  7445. return CaretPosition(nextSibling, 0);
  7446. } else {
  7447. return CaretPosition.before(nextSibling);
  7448. }
  7449. } else {
  7450. return findCaretPosition$1(HDirection.Forwards, CaretPosition.after(nextNode), root);
  7451. }
  7452. };
  7453. const findCaretPosition$1 = (direction, startPos, root) => {
  7454. let node;
  7455. let nextNode;
  7456. let innerNode;
  7457. let caretPosition;
  7458. if (!isElement$1(root) || !startPos) {
  7459. return null;
  7460. }
  7461. if (startPos.isEqual(CaretPosition.after(root)) && root.lastChild) {
  7462. caretPosition = CaretPosition.after(root.lastChild);
  7463. if (isBackwards(direction) && isCaretCandidate(root.lastChild) && isElement$1(root.lastChild)) {
  7464. return isBr$2(root.lastChild) ? CaretPosition.before(root.lastChild) : caretPosition;
  7465. }
  7466. } else {
  7467. caretPosition = startPos;
  7468. }
  7469. const container = caretPosition.container();
  7470. let offset = caretPosition.offset();
  7471. if (isText$3(container)) {
  7472. if (isBackwards(direction) && offset > 0) {
  7473. return CaretPosition(container, --offset);
  7474. }
  7475. if (isForwards(direction) && offset < container.length) {
  7476. return CaretPosition(container, ++offset);
  7477. }
  7478. node = container;
  7479. } else {
  7480. if (isBackwards(direction) && offset > 0) {
  7481. nextNode = nodeAtIndex(container, offset - 1);
  7482. if (isCaretCandidate(nextNode)) {
  7483. if (!isAtomic(nextNode)) {
  7484. innerNode = findNode(nextNode, direction, isEditableCaretCandidate, nextNode);
  7485. if (innerNode) {
  7486. if (isText$3(innerNode)) {
  7487. return CaretPosition(innerNode, innerNode.data.length);
  7488. }
  7489. return CaretPosition.after(innerNode);
  7490. }
  7491. }
  7492. if (isText$3(nextNode)) {
  7493. return CaretPosition(nextNode, nextNode.data.length);
  7494. }
  7495. return CaretPosition.before(nextNode);
  7496. }
  7497. }
  7498. if (isForwards(direction) && offset < container.childNodes.length) {
  7499. nextNode = nodeAtIndex(container, offset);
  7500. if (isCaretCandidate(nextNode)) {
  7501. if (isBr$2(nextNode)) {
  7502. return moveForwardFromBr(root, nextNode);
  7503. }
  7504. if (!isAtomic(nextNode)) {
  7505. innerNode = findNode(nextNode, direction, isEditableCaretCandidate, nextNode);
  7506. if (innerNode) {
  7507. if (isText$3(innerNode)) {
  7508. return CaretPosition(innerNode, 0);
  7509. }
  7510. return CaretPosition.before(innerNode);
  7511. }
  7512. }
  7513. if (isText$3(nextNode)) {
  7514. return CaretPosition(nextNode, 0);
  7515. }
  7516. return CaretPosition.after(nextNode);
  7517. }
  7518. }
  7519. node = nextNode ? nextNode : caretPosition.getNode();
  7520. }
  7521. if (isForwards(direction) && caretPosition.isAtEnd() || isBackwards(direction) && caretPosition.isAtStart()) {
  7522. node = findNode(node, direction, always, root, true);
  7523. if (isEditableCaretCandidate(node, root)) {
  7524. return getCaretCandidatePosition(direction, node);
  7525. }
  7526. }
  7527. nextNode = findNode(node, direction, isEditableCaretCandidate, root);
  7528. const rootContentEditableFalseElm = last$2(filter$6(getParents$3(container, root), isContentEditableFalse$6));
  7529. if (rootContentEditableFalseElm && (!nextNode || !rootContentEditableFalseElm.contains(nextNode))) {
  7530. if (isForwards(direction)) {
  7531. caretPosition = CaretPosition.after(rootContentEditableFalseElm);
  7532. } else {
  7533. caretPosition = CaretPosition.before(rootContentEditableFalseElm);
  7534. }
  7535. return caretPosition;
  7536. }
  7537. if (nextNode) {
  7538. return getCaretCandidatePosition(direction, nextNode);
  7539. }
  7540. return null;
  7541. };
  7542. const CaretWalker = root => ({
  7543. next: caretPosition => {
  7544. return findCaretPosition$1(HDirection.Forwards, caretPosition, root);
  7545. },
  7546. prev: caretPosition => {
  7547. return findCaretPosition$1(HDirection.Backwards, caretPosition, root);
  7548. }
  7549. });
  7550. const walkToPositionIn = (forward, root, start) => {
  7551. const position = forward ? CaretPosition.before(start) : CaretPosition.after(start);
  7552. return fromPosition(forward, root, position);
  7553. };
  7554. const afterElement = node => isBr$6(node) ? CaretPosition.before(node) : CaretPosition.after(node);
  7555. const isBeforeOrStart = position => {
  7556. if (CaretPosition.isTextPosition(position)) {
  7557. return position.offset() === 0;
  7558. } else {
  7559. return isCaretCandidate$3(position.getNode());
  7560. }
  7561. };
  7562. const isAfterOrEnd = position => {
  7563. if (CaretPosition.isTextPosition(position)) {
  7564. const container = position.container();
  7565. return position.offset() === container.data.length;
  7566. } else {
  7567. return isCaretCandidate$3(position.getNode(true));
  7568. }
  7569. };
  7570. const isBeforeAfterSameElement = (from, to) => !CaretPosition.isTextPosition(from) && !CaretPosition.isTextPosition(to) && from.getNode() === to.getNode(true);
  7571. const isAtBr = position => !CaretPosition.isTextPosition(position) && isBr$6(position.getNode());
  7572. const shouldSkipPosition = (forward, from, to) => {
  7573. if (forward) {
  7574. return !isBeforeAfterSameElement(from, to) && !isAtBr(from) && isAfterOrEnd(from) && isBeforeOrStart(to);
  7575. } else {
  7576. return !isBeforeAfterSameElement(to, from) && isBeforeOrStart(from) && isAfterOrEnd(to);
  7577. }
  7578. };
  7579. const fromPosition = (forward, root, pos) => {
  7580. const walker = CaretWalker(root);
  7581. return Optional.from(forward ? walker.next(pos) : walker.prev(pos));
  7582. };
  7583. const navigate = (forward, root, from) => fromPosition(forward, root, from).bind(to => {
  7584. if (isInSameBlock(from, to, root) && shouldSkipPosition(forward, from, to)) {
  7585. return fromPosition(forward, root, to);
  7586. } else {
  7587. return Optional.some(to);
  7588. }
  7589. });
  7590. const navigateIgnore = (forward, root, from, ignoreFilter) => navigate(forward, root, from).bind(pos => ignoreFilter(pos) ? navigateIgnore(forward, root, pos, ignoreFilter) : Optional.some(pos));
  7591. const positionIn = (forward, element) => {
  7592. const startNode = forward ? element.firstChild : element.lastChild;
  7593. if (isText$9(startNode)) {
  7594. return Optional.some(CaretPosition(startNode, forward ? 0 : startNode.data.length));
  7595. } else if (startNode) {
  7596. if (isCaretCandidate$3(startNode)) {
  7597. return Optional.some(forward ? CaretPosition.before(startNode) : afterElement(startNode));
  7598. } else {
  7599. return walkToPositionIn(forward, element, startNode);
  7600. }
  7601. } else {
  7602. return Optional.none();
  7603. }
  7604. };
  7605. const nextPosition = curry(fromPosition, true);
  7606. const prevPosition = curry(fromPosition, false);
  7607. const firstPositionIn = curry(positionIn, true);
  7608. const lastPositionIn = curry(positionIn, false);
  7609. const CARET_ID$1 = '_mce_caret';
  7610. const isCaretNode = node => isElement$6(node) && node.id === CARET_ID$1;
  7611. const getParentCaretContainer = (body, node) => {
  7612. while (node && node !== body) {
  7613. if (node.id === CARET_ID$1) {
  7614. return node;
  7615. }
  7616. node = node.parentNode;
  7617. }
  7618. return null;
  7619. };
  7620. const isStringPathBookmark = bookmark => isString(bookmark.start);
  7621. const isRangeBookmark = bookmark => has$2(bookmark, 'rng');
  7622. const isIdBookmark = bookmark => has$2(bookmark, 'id');
  7623. const isIndexBookmark = bookmark => has$2(bookmark, 'name');
  7624. const isPathBookmark = bookmark => Tools.isArray(bookmark.start);
  7625. const isForwardBookmark = bookmark => !isIndexBookmark(bookmark) && isBoolean(bookmark.forward) ? bookmark.forward : true;
  7626. const addBogus = (dom, node) => {
  7627. if (isElement$6(node) && dom.isBlock(node) && !node.innerHTML) {
  7628. node.innerHTML = '<br data-mce-bogus="1" />';
  7629. }
  7630. return node;
  7631. };
  7632. const resolveCaretPositionBookmark = (dom, bookmark) => {
  7633. const range = dom.createRng();
  7634. const startPos = resolve$1(dom.getRoot(), bookmark.start);
  7635. range.setStart(startPos.container(), startPos.offset());
  7636. const endPos = resolve$1(dom.getRoot(), bookmark.end);
  7637. range.setEnd(endPos.container(), endPos.offset());
  7638. return {
  7639. range,
  7640. forward: isForwardBookmark(bookmark)
  7641. };
  7642. };
  7643. const insertZwsp = (node, rng) => {
  7644. const textNode = node.ownerDocument.createTextNode(ZWSP$1);
  7645. node.appendChild(textNode);
  7646. rng.setStart(textNode, 0);
  7647. rng.setEnd(textNode, 0);
  7648. };
  7649. const isEmpty$1 = node => node.hasChildNodes() === false;
  7650. const tryFindRangePosition = (node, rng) => lastPositionIn(node).fold(never, pos => {
  7651. rng.setStart(pos.container(), pos.offset());
  7652. rng.setEnd(pos.container(), pos.offset());
  7653. return true;
  7654. });
  7655. const padEmptyCaretContainer = (root, node, rng) => {
  7656. if (isEmpty$1(node) && getParentCaretContainer(root, node)) {
  7657. insertZwsp(node, rng);
  7658. return true;
  7659. } else {
  7660. return false;
  7661. }
  7662. };
  7663. const setEndPoint = (dom, start, bookmark, rng) => {
  7664. const point = bookmark[start ? 'start' : 'end'];
  7665. let i, node, offset, children;
  7666. const root = dom.getRoot();
  7667. if (point) {
  7668. offset = point[0];
  7669. for (node = root, i = point.length - 1; i >= 1; i--) {
  7670. children = node.childNodes;
  7671. if (padEmptyCaretContainer(root, node, rng)) {
  7672. return true;
  7673. }
  7674. if (point[i] > children.length - 1) {
  7675. if (padEmptyCaretContainer(root, node, rng)) {
  7676. return true;
  7677. }
  7678. return tryFindRangePosition(node, rng);
  7679. }
  7680. node = children[point[i]];
  7681. }
  7682. if (node.nodeType === 3) {
  7683. offset = Math.min(point[0], node.nodeValue.length);
  7684. }
  7685. if (node.nodeType === 1) {
  7686. offset = Math.min(point[0], node.childNodes.length);
  7687. }
  7688. if (start) {
  7689. rng.setStart(node, offset);
  7690. } else {
  7691. rng.setEnd(node, offset);
  7692. }
  7693. }
  7694. return true;
  7695. };
  7696. const isValidTextNode = node => isText$9(node) && node.data.length > 0;
  7697. const restoreEndPoint = (dom, suffix, bookmark) => {
  7698. let marker = dom.get(bookmark.id + '_' + suffix), node, idx, next, prev;
  7699. const keep = bookmark.keep;
  7700. let container, offset;
  7701. if (marker) {
  7702. node = marker.parentNode;
  7703. if (suffix === 'start') {
  7704. if (!keep) {
  7705. idx = dom.nodeIndex(marker);
  7706. } else {
  7707. if (marker.hasChildNodes()) {
  7708. node = marker.firstChild;
  7709. idx = 1;
  7710. } else if (isValidTextNode(marker.nextSibling)) {
  7711. node = marker.nextSibling;
  7712. idx = 0;
  7713. } else if (isValidTextNode(marker.previousSibling)) {
  7714. node = marker.previousSibling;
  7715. idx = marker.previousSibling.data.length;
  7716. } else {
  7717. node = marker.parentNode;
  7718. idx = dom.nodeIndex(marker) + 1;
  7719. }
  7720. }
  7721. container = node;
  7722. offset = idx;
  7723. } else {
  7724. if (!keep) {
  7725. idx = dom.nodeIndex(marker);
  7726. } else {
  7727. if (marker.hasChildNodes()) {
  7728. node = marker.firstChild;
  7729. idx = 1;
  7730. } else if (isValidTextNode(marker.previousSibling)) {
  7731. node = marker.previousSibling;
  7732. idx = marker.previousSibling.data.length;
  7733. } else {
  7734. node = marker.parentNode;
  7735. idx = dom.nodeIndex(marker);
  7736. }
  7737. }
  7738. container = node;
  7739. offset = idx;
  7740. }
  7741. if (!keep) {
  7742. prev = marker.previousSibling;
  7743. next = marker.nextSibling;
  7744. Tools.each(Tools.grep(marker.childNodes), node => {
  7745. if (isText$9(node)) {
  7746. node.nodeValue = node.nodeValue.replace(/\uFEFF/g, '');
  7747. }
  7748. });
  7749. while (marker = dom.get(bookmark.id + '_' + suffix)) {
  7750. dom.remove(marker, true);
  7751. }
  7752. if (prev && next && prev.nodeType === next.nodeType && isText$9(prev) && !Env.browser.isOpera()) {
  7753. idx = prev.nodeValue.length;
  7754. prev.appendData(next.nodeValue);
  7755. dom.remove(next);
  7756. container = prev;
  7757. offset = idx;
  7758. }
  7759. }
  7760. return Optional.some(CaretPosition(container, offset));
  7761. } else {
  7762. return Optional.none();
  7763. }
  7764. };
  7765. const resolvePaths = (dom, bookmark) => {
  7766. const range = dom.createRng();
  7767. if (setEndPoint(dom, true, bookmark, range) && setEndPoint(dom, false, bookmark, range)) {
  7768. return Optional.some({
  7769. range,
  7770. forward: isForwardBookmark(bookmark)
  7771. });
  7772. } else {
  7773. return Optional.none();
  7774. }
  7775. };
  7776. const resolveId = (dom, bookmark) => {
  7777. const startPos = restoreEndPoint(dom, 'start', bookmark);
  7778. const endPos = restoreEndPoint(dom, 'end', bookmark);
  7779. return lift2(startPos, endPos.or(startPos), (spos, epos) => {
  7780. const range = dom.createRng();
  7781. range.setStart(addBogus(dom, spos.container()), spos.offset());
  7782. range.setEnd(addBogus(dom, epos.container()), epos.offset());
  7783. return {
  7784. range,
  7785. forward: isForwardBookmark(bookmark)
  7786. };
  7787. });
  7788. };
  7789. const resolveIndex = (dom, bookmark) => Optional.from(dom.select(bookmark.name)[bookmark.index]).map(elm => {
  7790. const range = dom.createRng();
  7791. range.selectNode(elm);
  7792. return {
  7793. range,
  7794. forward: true
  7795. };
  7796. });
  7797. const resolve = (selection, bookmark) => {
  7798. const dom = selection.dom;
  7799. if (bookmark) {
  7800. if (isPathBookmark(bookmark)) {
  7801. return resolvePaths(dom, bookmark);
  7802. } else if (isStringPathBookmark(bookmark)) {
  7803. return Optional.some(resolveCaretPositionBookmark(dom, bookmark));
  7804. } else if (isIdBookmark(bookmark)) {
  7805. return resolveId(dom, bookmark);
  7806. } else if (isIndexBookmark(bookmark)) {
  7807. return resolveIndex(dom, bookmark);
  7808. } else if (isRangeBookmark(bookmark)) {
  7809. return Optional.some({
  7810. range: bookmark.rng,
  7811. forward: isForwardBookmark(bookmark)
  7812. });
  7813. }
  7814. }
  7815. return Optional.none();
  7816. };
  7817. const getBookmark$1 = (selection, type, normalized) => {
  7818. return getBookmark$2(selection, type, normalized);
  7819. };
  7820. const moveToBookmark = (selection, bookmark) => {
  7821. resolve(selection, bookmark).each(({range, forward}) => {
  7822. selection.setRng(range, forward);
  7823. });
  7824. };
  7825. const isBookmarkNode$1 = node => {
  7826. return isElement$6(node) && node.tagName === 'SPAN' && node.getAttribute('data-mce-type') === 'bookmark';
  7827. };
  7828. const is = expected => actual => expected === actual;
  7829. const isNbsp = is(nbsp);
  7830. const isWhiteSpace = chr => chr !== '' && ' \f\n\r\t\x0B'.indexOf(chr) !== -1;
  7831. const isContent = chr => !isWhiteSpace(chr) && !isNbsp(chr) && !isZwsp$1(chr);
  7832. const hexColour = value => ({ value });
  7833. const toHex = component => {
  7834. const hex = component.toString(16);
  7835. return (hex.length === 1 ? '0' + hex : hex).toUpperCase();
  7836. };
  7837. const fromRgba = rgbaColour => {
  7838. const value = toHex(rgbaColour.red) + toHex(rgbaColour.green) + toHex(rgbaColour.blue);
  7839. return hexColour(value);
  7840. };
  7841. const rgbRegex = /^\s*rgb\s*\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*\)\s*$/i;
  7842. const rgbaRegex = /^\s*rgba\s*\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d?(?:\.\d+)?)\s*\)\s*$/i;
  7843. const rgbaColour = (red, green, blue, alpha) => ({
  7844. red,
  7845. green,
  7846. blue,
  7847. alpha
  7848. });
  7849. const fromStringValues = (red, green, blue, alpha) => {
  7850. const r = parseInt(red, 10);
  7851. const g = parseInt(green, 10);
  7852. const b = parseInt(blue, 10);
  7853. const a = parseFloat(alpha);
  7854. return rgbaColour(r, g, b, a);
  7855. };
  7856. const fromString = rgbaString => {
  7857. if (rgbaString === 'transparent') {
  7858. return Optional.some(rgbaColour(0, 0, 0, 0));
  7859. }
  7860. const rgbMatch = rgbRegex.exec(rgbaString);
  7861. if (rgbMatch !== null) {
  7862. return Optional.some(fromStringValues(rgbMatch[1], rgbMatch[2], rgbMatch[3], '1'));
  7863. }
  7864. const rgbaMatch = rgbaRegex.exec(rgbaString);
  7865. if (rgbaMatch !== null) {
  7866. return Optional.some(fromStringValues(rgbaMatch[1], rgbaMatch[2], rgbaMatch[3], rgbaMatch[4]));
  7867. }
  7868. return Optional.none();
  7869. };
  7870. const rgbaToHexString = color => fromString(color).map(fromRgba).map(h => '#' + h.value).getOr(color);
  7871. const isNode = node => !!node.nodeType;
  7872. const isInlineBlock = node => {
  7873. return node && /^(IMG)$/.test(node.nodeName);
  7874. };
  7875. const moveStart = (dom, selection, rng) => {
  7876. const offset = rng.startOffset;
  7877. let container = rng.startContainer;
  7878. if (container === rng.endContainer) {
  7879. if (isInlineBlock(container.childNodes[offset])) {
  7880. return;
  7881. }
  7882. }
  7883. if (isElement$6(container)) {
  7884. const nodes = container.childNodes;
  7885. let walker;
  7886. if (offset < nodes.length) {
  7887. container = nodes[offset];
  7888. walker = new DomTreeWalker(container, dom.getParent(container, dom.isBlock));
  7889. } else {
  7890. container = nodes[nodes.length - 1];
  7891. walker = new DomTreeWalker(container, dom.getParent(container, dom.isBlock));
  7892. walker.next(true);
  7893. }
  7894. for (let node = walker.current(); node; node = walker.next()) {
  7895. if (isText$9(node) && !isWhiteSpaceNode$1(node)) {
  7896. rng.setStart(node, 0);
  7897. selection.setRng(rng);
  7898. return;
  7899. }
  7900. }
  7901. }
  7902. };
  7903. const getNonWhiteSpaceSibling = (node, next, inc) => {
  7904. if (node) {
  7905. const nextName = next ? 'nextSibling' : 'previousSibling';
  7906. for (node = inc ? node : node[nextName]; node; node = node[nextName]) {
  7907. if (isElement$6(node) || !isWhiteSpaceNode$1(node)) {
  7908. return node;
  7909. }
  7910. }
  7911. }
  7912. };
  7913. const isTextBlock$1 = (editor, name) => {
  7914. if (isNode(name)) {
  7915. name = name.nodeName;
  7916. }
  7917. return !!editor.schema.getTextBlockElements()[name.toLowerCase()];
  7918. };
  7919. const isValid = (ed, parent, child) => {
  7920. return ed.schema.isValidChild(parent, child);
  7921. };
  7922. const isWhiteSpaceNode$1 = (node, allowSpaces = false) => {
  7923. if (isNonNullable(node) && isText$9(node)) {
  7924. const data = allowSpaces ? node.data.replace(/ /g, '\xA0') : node.data;
  7925. return isWhitespaceText(data);
  7926. } else {
  7927. return false;
  7928. }
  7929. };
  7930. const isEmptyTextNode$1 = node => {
  7931. return isNonNullable(node) && isText$9(node) && node.length === 0;
  7932. };
  7933. const replaceVars = (value, vars) => {
  7934. if (isFunction(value)) {
  7935. value = value(vars);
  7936. } else if (isNonNullable(vars)) {
  7937. value = value.replace(/%(\w+)/g, (str, name) => {
  7938. return vars[name] || str;
  7939. });
  7940. }
  7941. return value;
  7942. };
  7943. const isEq$5 = (str1, str2) => {
  7944. str1 = str1 || '';
  7945. str2 = str2 || '';
  7946. str1 = '' + (str1.nodeName || str1);
  7947. str2 = '' + (str2.nodeName || str2);
  7948. return str1.toLowerCase() === str2.toLowerCase();
  7949. };
  7950. const normalizeStyleValue = (value, name) => {
  7951. if (name === 'color' || name === 'backgroundColor') {
  7952. value = rgbaToHexString(value);
  7953. }
  7954. if (name === 'fontWeight' && value === 700) {
  7955. value = 'bold';
  7956. }
  7957. if (name === 'fontFamily') {
  7958. value = value.replace(/[\'\"]/g, '').replace(/,\s+/g, ',');
  7959. }
  7960. return '' + value;
  7961. };
  7962. const getStyle = (dom, node, name) => {
  7963. return normalizeStyleValue(dom.getStyle(node, name), name);
  7964. };
  7965. const getTextDecoration = (dom, node) => {
  7966. let decoration;
  7967. dom.getParent(node, n => {
  7968. decoration = dom.getStyle(n, 'text-decoration');
  7969. return decoration && decoration !== 'none';
  7970. });
  7971. return decoration;
  7972. };
  7973. const getParents$2 = (dom, node, selector) => {
  7974. return dom.getParents(node, selector, dom.getRoot());
  7975. };
  7976. const isVariableFormatName = (editor, formatName) => {
  7977. const hasVariableValues = format => {
  7978. const isVariableValue = val => val.length > 1 && val.charAt(0) === '%';
  7979. return exists([
  7980. 'styles',
  7981. 'attributes'
  7982. ], key => get$a(format, key).exists(field => {
  7983. const fieldValues = isArray$1(field) ? field : values(field);
  7984. return exists(fieldValues, isVariableValue);
  7985. }));
  7986. };
  7987. return exists(editor.formatter.get(formatName), hasVariableValues);
  7988. };
  7989. const areSimilarFormats = (editor, formatName, otherFormatName) => {
  7990. const validKeys = [
  7991. 'inline',
  7992. 'block',
  7993. 'selector',
  7994. 'attributes',
  7995. 'styles',
  7996. 'classes'
  7997. ];
  7998. const filterObj = format => filter$5(format, (_, key) => exists(validKeys, validKey => validKey === key));
  7999. return exists(editor.formatter.get(formatName), fmt1 => {
  8000. const filteredFmt1 = filterObj(fmt1);
  8001. return exists(editor.formatter.get(otherFormatName), fmt2 => {
  8002. const filteredFmt2 = filterObj(fmt2);
  8003. return equal$1(filteredFmt1, filteredFmt2);
  8004. });
  8005. });
  8006. };
  8007. const isBlockFormat = format => hasNonNullableKey(format, 'block');
  8008. const isSelectorFormat = format => hasNonNullableKey(format, 'selector');
  8009. const isInlineFormat = format => hasNonNullableKey(format, 'inline');
  8010. const isMixedFormat = format => isSelectorFormat(format) && isInlineFormat(format) && is$2(get$a(format, 'mixed'), true);
  8011. const shouldExpandToSelector = format => isSelectorFormat(format) && format.expand !== false && !isInlineFormat(format);
  8012. const isBookmarkNode = isBookmarkNode$1;
  8013. const getParents$1 = getParents$2;
  8014. const isWhiteSpaceNode = isWhiteSpaceNode$1;
  8015. const isTextBlock = isTextBlock$1;
  8016. const isBogusBr = node => {
  8017. return isBr$6(node) && node.getAttribute('data-mce-bogus') && !node.nextSibling;
  8018. };
  8019. const findParentContentEditable = (dom, node) => {
  8020. let parent = node;
  8021. while (parent) {
  8022. if (isElement$6(parent) && dom.getContentEditable(parent)) {
  8023. return dom.getContentEditable(parent) === 'false' ? parent : node;
  8024. }
  8025. parent = parent.parentNode;
  8026. }
  8027. return node;
  8028. };
  8029. const walkText = (start, node, offset, predicate) => {
  8030. const str = node.data;
  8031. for (let i = offset; start ? i >= 0 : i < str.length; start ? i-- : i++) {
  8032. if (predicate(str.charAt(i))) {
  8033. return start ? i + 1 : i;
  8034. }
  8035. }
  8036. return -1;
  8037. };
  8038. const findSpace = (start, node, offset) => walkText(start, node, offset, c => isNbsp(c) || isWhiteSpace(c));
  8039. const findContent = (start, node, offset) => walkText(start, node, offset, isContent);
  8040. const findWordEndPoint = (dom, body, container, offset, start, includeTrailingSpaces) => {
  8041. let lastTextNode;
  8042. const rootNode = dom.getParent(container, dom.isBlock) || body;
  8043. const walk = (container, offset, pred) => {
  8044. const textSeeker = TextSeeker(dom);
  8045. const walker = start ? textSeeker.backwards : textSeeker.forwards;
  8046. return Optional.from(walker(container, offset, (text, textOffset) => {
  8047. if (isBookmarkNode(text.parentNode)) {
  8048. return -1;
  8049. } else {
  8050. lastTextNode = text;
  8051. return pred(start, text, textOffset);
  8052. }
  8053. }, rootNode));
  8054. };
  8055. const spaceResult = walk(container, offset, findSpace);
  8056. return spaceResult.bind(result => includeTrailingSpaces ? walk(result.container, result.offset + (start ? -1 : 0), findContent) : Optional.some(result)).orThunk(() => lastTextNode ? Optional.some({
  8057. container: lastTextNode,
  8058. offset: start ? 0 : lastTextNode.length
  8059. }) : Optional.none());
  8060. };
  8061. const findSelectorEndPoint = (dom, formatList, rng, container, siblingName) => {
  8062. if (isText$9(container) && isEmpty$3(container.data) && container[siblingName]) {
  8063. container = container[siblingName];
  8064. }
  8065. const parents = getParents$1(dom, container);
  8066. for (let i = 0; i < parents.length; i++) {
  8067. for (let y = 0; y < formatList.length; y++) {
  8068. const curFormat = formatList[y];
  8069. if (isNonNullable(curFormat.collapsed) && curFormat.collapsed !== rng.collapsed) {
  8070. continue;
  8071. }
  8072. if (isSelectorFormat(curFormat) && dom.is(parents[i], curFormat.selector)) {
  8073. return parents[i];
  8074. }
  8075. }
  8076. }
  8077. return container;
  8078. };
  8079. const findBlockEndPoint = (editor, formatList, container, siblingName) => {
  8080. let node = container;
  8081. const dom = editor.dom;
  8082. const root = dom.getRoot();
  8083. const format = formatList[0];
  8084. if (isBlockFormat(format)) {
  8085. node = format.wrapper ? null : dom.getParent(container, format.block, root);
  8086. }
  8087. if (!node) {
  8088. const scopeRoot = dom.getParent(container, 'LI,TD,TH');
  8089. node = dom.getParent(isText$9(container) ? container.parentNode : container, node => node !== root && isTextBlock(editor, node), scopeRoot);
  8090. }
  8091. if (node && isBlockFormat(format) && format.wrapper) {
  8092. node = getParents$1(dom, node, 'ul,ol').reverse()[0] || node;
  8093. }
  8094. if (!node) {
  8095. node = container;
  8096. while (node[siblingName] && !dom.isBlock(node[siblingName])) {
  8097. node = node[siblingName];
  8098. if (isEq$5(node, 'br')) {
  8099. break;
  8100. }
  8101. }
  8102. }
  8103. return node || container;
  8104. };
  8105. const isAtBlockBoundary$1 = (dom, root, container, siblingName) => {
  8106. const parent = container.parentNode;
  8107. if (isNonNullable(container[siblingName])) {
  8108. return false;
  8109. } else if (parent === root || isNullable(parent) || dom.isBlock(parent)) {
  8110. return true;
  8111. } else {
  8112. return isAtBlockBoundary$1(dom, root, parent, siblingName);
  8113. }
  8114. };
  8115. const findParentContainer = (dom, formatList, container, offset, start) => {
  8116. let parent = container;
  8117. const siblingName = start ? 'previousSibling' : 'nextSibling';
  8118. const root = dom.getRoot();
  8119. if (isText$9(container) && !isWhiteSpaceNode(container)) {
  8120. if (start ? offset > 0 : offset < container.data.length) {
  8121. return container;
  8122. }
  8123. }
  8124. while (true) {
  8125. if (!formatList[0].block_expand && dom.isBlock(parent)) {
  8126. return parent;
  8127. }
  8128. for (let sibling = parent[siblingName]; sibling; sibling = sibling[siblingName]) {
  8129. const allowSpaces = isText$9(sibling) && !isAtBlockBoundary$1(dom, root, sibling, siblingName);
  8130. if (!isBookmarkNode(sibling) && !isBogusBr(sibling) && !isWhiteSpaceNode(sibling, allowSpaces)) {
  8131. return parent;
  8132. }
  8133. }
  8134. if (parent === root || parent.parentNode === root) {
  8135. container = parent;
  8136. break;
  8137. }
  8138. parent = parent.parentNode;
  8139. }
  8140. return container;
  8141. };
  8142. const isSelfOrParentBookmark = container => isBookmarkNode(container.parentNode) || isBookmarkNode(container);
  8143. const expandRng = (editor, rng, formatList, includeTrailingSpace = false) => {
  8144. let {startContainer, startOffset, endContainer, endOffset} = rng;
  8145. const dom = editor.dom;
  8146. const format = formatList[0];
  8147. if (isElement$6(startContainer) && startContainer.hasChildNodes()) {
  8148. startContainer = getNode$1(startContainer, startOffset);
  8149. if (isText$9(startContainer)) {
  8150. startOffset = 0;
  8151. }
  8152. }
  8153. if (isElement$6(endContainer) && endContainer.hasChildNodes()) {
  8154. endContainer = getNode$1(endContainer, rng.collapsed ? endOffset : endOffset - 1);
  8155. if (isText$9(endContainer)) {
  8156. endOffset = endContainer.nodeValue.length;
  8157. }
  8158. }
  8159. startContainer = findParentContentEditable(dom, startContainer);
  8160. endContainer = findParentContentEditable(dom, endContainer);
  8161. if (isSelfOrParentBookmark(startContainer)) {
  8162. startContainer = isBookmarkNode(startContainer) ? startContainer : startContainer.parentNode;
  8163. if (rng.collapsed) {
  8164. startContainer = startContainer.previousSibling || startContainer;
  8165. } else {
  8166. startContainer = startContainer.nextSibling || startContainer;
  8167. }
  8168. if (isText$9(startContainer)) {
  8169. startOffset = rng.collapsed ? startContainer.length : 0;
  8170. }
  8171. }
  8172. if (isSelfOrParentBookmark(endContainer)) {
  8173. endContainer = isBookmarkNode(endContainer) ? endContainer : endContainer.parentNode;
  8174. if (rng.collapsed) {
  8175. endContainer = endContainer.nextSibling || endContainer;
  8176. } else {
  8177. endContainer = endContainer.previousSibling || endContainer;
  8178. }
  8179. if (isText$9(endContainer)) {
  8180. endOffset = rng.collapsed ? 0 : endContainer.length;
  8181. }
  8182. }
  8183. if (rng.collapsed) {
  8184. const startPoint = findWordEndPoint(dom, editor.getBody(), startContainer, startOffset, true, includeTrailingSpace);
  8185. startPoint.each(({container, offset}) => {
  8186. startContainer = container;
  8187. startOffset = offset;
  8188. });
  8189. const endPoint = findWordEndPoint(dom, editor.getBody(), endContainer, endOffset, false, includeTrailingSpace);
  8190. endPoint.each(({container, offset}) => {
  8191. endContainer = container;
  8192. endOffset = offset;
  8193. });
  8194. }
  8195. if (isInlineFormat(format) || format.block_expand) {
  8196. if (!isInlineFormat(format) || (!isText$9(startContainer) || startOffset === 0)) {
  8197. startContainer = findParentContainer(dom, formatList, startContainer, startOffset, true);
  8198. }
  8199. if (!isInlineFormat(format) || (!isText$9(endContainer) || endOffset === endContainer.nodeValue.length)) {
  8200. endContainer = findParentContainer(dom, formatList, endContainer, endOffset, false);
  8201. }
  8202. }
  8203. if (shouldExpandToSelector(format)) {
  8204. startContainer = findSelectorEndPoint(dom, formatList, rng, startContainer, 'previousSibling');
  8205. endContainer = findSelectorEndPoint(dom, formatList, rng, endContainer, 'nextSibling');
  8206. }
  8207. if (isBlockFormat(format) || isSelectorFormat(format)) {
  8208. startContainer = findBlockEndPoint(editor, formatList, startContainer, 'previousSibling');
  8209. endContainer = findBlockEndPoint(editor, formatList, endContainer, 'nextSibling');
  8210. if (isBlockFormat(format)) {
  8211. if (!dom.isBlock(startContainer)) {
  8212. startContainer = findParentContainer(dom, formatList, startContainer, startOffset, true);
  8213. }
  8214. if (!dom.isBlock(endContainer)) {
  8215. endContainer = findParentContainer(dom, formatList, endContainer, endOffset, false);
  8216. }
  8217. }
  8218. }
  8219. if (isElement$6(startContainer)) {
  8220. startOffset = dom.nodeIndex(startContainer);
  8221. startContainer = startContainer.parentNode;
  8222. }
  8223. if (isElement$6(endContainer)) {
  8224. endOffset = dom.nodeIndex(endContainer) + 1;
  8225. endContainer = endContainer.parentNode;
  8226. }
  8227. return {
  8228. startContainer,
  8229. startOffset,
  8230. endContainer,
  8231. endOffset
  8232. };
  8233. };
  8234. const walk$3 = (dom, rng, callback) => {
  8235. const startOffset = rng.startOffset;
  8236. const startContainer = getNode$1(rng.startContainer, startOffset);
  8237. const endOffset = rng.endOffset;
  8238. const endContainer = getNode$1(rng.endContainer, endOffset - 1);
  8239. const exclude = nodes => {
  8240. const firstNode = nodes[0];
  8241. if (isText$9(firstNode) && firstNode === startContainer && startOffset >= firstNode.data.length) {
  8242. nodes.splice(0, 1);
  8243. }
  8244. const lastNode = nodes[nodes.length - 1];
  8245. if (endOffset === 0 && nodes.length > 0 && lastNode === endContainer && isText$9(lastNode)) {
  8246. nodes.splice(nodes.length - 1, 1);
  8247. }
  8248. return nodes;
  8249. };
  8250. const collectSiblings = (node, name, endNode) => {
  8251. const siblings = [];
  8252. for (; node && node !== endNode; node = node[name]) {
  8253. siblings.push(node);
  8254. }
  8255. return siblings;
  8256. };
  8257. const findEndPoint = (node, root) => dom.getParent(node, node => node.parentNode === root, root);
  8258. const walkBoundary = (startNode, endNode, next) => {
  8259. const siblingName = next ? 'nextSibling' : 'previousSibling';
  8260. for (let node = startNode, parent = node.parentNode; node && node !== endNode; node = parent) {
  8261. parent = node.parentNode;
  8262. const siblings = collectSiblings(node === startNode ? node : node[siblingName], siblingName);
  8263. if (siblings.length) {
  8264. if (!next) {
  8265. siblings.reverse();
  8266. }
  8267. callback(exclude(siblings));
  8268. }
  8269. }
  8270. };
  8271. if (startContainer === endContainer) {
  8272. return callback(exclude([startContainer]));
  8273. }
  8274. const ancestor = dom.findCommonAncestor(startContainer, endContainer);
  8275. if (dom.isChildOf(startContainer, endContainer)) {
  8276. return walkBoundary(startContainer, ancestor, true);
  8277. }
  8278. if (dom.isChildOf(endContainer, startContainer)) {
  8279. return walkBoundary(endContainer, ancestor);
  8280. }
  8281. const startPoint = findEndPoint(startContainer, ancestor) || startContainer;
  8282. const endPoint = findEndPoint(endContainer, ancestor) || endContainer;
  8283. walkBoundary(startContainer, startPoint, true);
  8284. const siblings = collectSiblings(startPoint === startContainer ? startPoint : startPoint.nextSibling, 'nextSibling', endPoint === endContainer ? endPoint.nextSibling : endPoint);
  8285. if (siblings.length) {
  8286. callback(exclude(siblings));
  8287. }
  8288. walkBoundary(endContainer, endPoint);
  8289. };
  8290. const getRanges$1 = selection => {
  8291. const ranges = [];
  8292. if (selection) {
  8293. for (let i = 0; i < selection.rangeCount; i++) {
  8294. ranges.push(selection.getRangeAt(i));
  8295. }
  8296. }
  8297. return ranges;
  8298. };
  8299. const getSelectedNodes = ranges => {
  8300. return bind$3(ranges, range => {
  8301. const node = getSelectedNode(range);
  8302. return node ? [SugarElement.fromDom(node)] : [];
  8303. });
  8304. };
  8305. const hasMultipleRanges = selection => {
  8306. return getRanges$1(selection).length > 1;
  8307. };
  8308. const getCellsFromRanges = ranges => filter$6(getSelectedNodes(ranges), isTableCell$4);
  8309. const getCellsFromElement = elm => descendants(elm, 'td[data-mce-selected],th[data-mce-selected]');
  8310. const getCellsFromElementOrRanges = (ranges, element) => {
  8311. const selectedCells = getCellsFromElement(element);
  8312. return selectedCells.length > 0 ? selectedCells : getCellsFromRanges(ranges);
  8313. };
  8314. const getCellsFromEditor = editor => getCellsFromElementOrRanges(getRanges$1(editor.selection.getSel()), SugarElement.fromDom(editor.getBody()));
  8315. const getClosestTable = (cell, isRoot) => ancestor$2(cell, 'table', isRoot);
  8316. const getStartNode = rng => {
  8317. const sc = rng.startContainer, so = rng.startOffset;
  8318. if (isText$9(sc)) {
  8319. return so === 0 ? Optional.some(SugarElement.fromDom(sc)) : Optional.none();
  8320. } else {
  8321. return Optional.from(sc.childNodes[so]).map(SugarElement.fromDom);
  8322. }
  8323. };
  8324. const getEndNode = rng => {
  8325. const ec = rng.endContainer, eo = rng.endOffset;
  8326. if (isText$9(ec)) {
  8327. return eo === ec.data.length ? Optional.some(SugarElement.fromDom(ec)) : Optional.none();
  8328. } else {
  8329. return Optional.from(ec.childNodes[eo - 1]).map(SugarElement.fromDom);
  8330. }
  8331. };
  8332. const getFirstChildren = node => {
  8333. return firstChild(node).fold(constant([node]), child => {
  8334. return [node].concat(getFirstChildren(child));
  8335. });
  8336. };
  8337. const getLastChildren$1 = node => {
  8338. return lastChild(node).fold(constant([node]), child => {
  8339. if (name(child) === 'br') {
  8340. return prevSibling(child).map(sibling => {
  8341. return [node].concat(getLastChildren$1(sibling));
  8342. }).getOr([]);
  8343. } else {
  8344. return [node].concat(getLastChildren$1(child));
  8345. }
  8346. });
  8347. };
  8348. const hasAllContentsSelected = (elm, rng) => {
  8349. return lift2(getStartNode(rng), getEndNode(rng), (startNode, endNode) => {
  8350. const start = find$2(getFirstChildren(elm), curry(eq, startNode));
  8351. const end = find$2(getLastChildren$1(elm), curry(eq, endNode));
  8352. return start.isSome() && end.isSome();
  8353. }).getOr(false);
  8354. };
  8355. const moveEndPoint = (dom, rng, node, start) => {
  8356. const root = node, walker = new DomTreeWalker(node, root);
  8357. const moveCaretBeforeOnEnterElementsMap = filter$5(dom.schema.getMoveCaretBeforeOnEnterElements(), (_, name) => !contains$2([
  8358. 'td',
  8359. 'th',
  8360. 'table'
  8361. ], name.toLowerCase()));
  8362. do {
  8363. if (isText$9(node) && Tools.trim(node.nodeValue).length !== 0) {
  8364. if (start) {
  8365. rng.setStart(node, 0);
  8366. } else {
  8367. rng.setEnd(node, node.nodeValue.length);
  8368. }
  8369. return;
  8370. }
  8371. if (moveCaretBeforeOnEnterElementsMap[node.nodeName]) {
  8372. if (start) {
  8373. rng.setStartBefore(node);
  8374. } else {
  8375. if (node.nodeName === 'BR') {
  8376. rng.setEndBefore(node);
  8377. } else {
  8378. rng.setEndAfter(node);
  8379. }
  8380. }
  8381. return;
  8382. }
  8383. } while (node = start ? walker.next() : walker.prev());
  8384. if (root.nodeName === 'BODY') {
  8385. if (start) {
  8386. rng.setStart(root, 0);
  8387. } else {
  8388. rng.setEnd(root, root.childNodes.length);
  8389. }
  8390. }
  8391. };
  8392. const hasAnyRanges = editor => {
  8393. const sel = editor.selection.getSel();
  8394. return sel && sel.rangeCount > 0;
  8395. };
  8396. const runOnRanges = (editor, executor) => {
  8397. const fakeSelectionNodes = getCellsFromEditor(editor);
  8398. if (fakeSelectionNodes.length > 0) {
  8399. each$f(fakeSelectionNodes, elem => {
  8400. const node = elem.dom;
  8401. const fakeNodeRng = editor.dom.createRng();
  8402. fakeNodeRng.setStartBefore(node);
  8403. fakeNodeRng.setEndAfter(node);
  8404. executor(fakeNodeRng, true);
  8405. });
  8406. } else {
  8407. executor(editor.selection.getRng(), false);
  8408. }
  8409. };
  8410. const preserve = (selection, fillBookmark, executor) => {
  8411. const bookmark = getPersistentBookmark(selection, fillBookmark);
  8412. executor(bookmark);
  8413. selection.moveToBookmark(bookmark);
  8414. };
  8415. const NodeValue = (is, name) => {
  8416. const get = element => {
  8417. if (!is(element)) {
  8418. throw new Error('Can only get ' + name + ' value of a ' + name + ' node');
  8419. }
  8420. return getOption(element).getOr('');
  8421. };
  8422. const getOption = element => is(element) ? Optional.from(element.dom.nodeValue) : Optional.none();
  8423. const set = (element, value) => {
  8424. if (!is(element)) {
  8425. throw new Error('Can only set raw ' + name + ' value of a ' + name + ' node');
  8426. }
  8427. element.dom.nodeValue = value;
  8428. };
  8429. return {
  8430. get,
  8431. getOption,
  8432. set
  8433. };
  8434. };
  8435. const api$1 = NodeValue(isText$a, 'text');
  8436. const get$3 = element => api$1.get(element);
  8437. const getOption = element => api$1.getOption(element);
  8438. const validBlocks = [
  8439. 'pre[class*=language-][contenteditable="false"]',
  8440. 'figure.image',
  8441. 'div[data-ephox-embed-iri]',
  8442. 'div.tiny-pageembed',
  8443. 'div.mce-toc',
  8444. 'div[data-mce-toc]'
  8445. ];
  8446. const isZeroWidth = elem => isText$a(elem) && get$3(elem) === ZWSP$1;
  8447. const context = (editor, elem, wrapName, nodeName) => parent(elem).fold(() => 'skipping', parent => {
  8448. if (nodeName === 'br' || isZeroWidth(elem)) {
  8449. return 'valid';
  8450. } else if (isAnnotation(elem)) {
  8451. return 'existing';
  8452. } else if (isCaretNode(elem.dom)) {
  8453. return 'caret';
  8454. } else if (exists(validBlocks, selector => is$1(elem, selector))) {
  8455. return 'valid-block';
  8456. } else if (!isValid(editor, wrapName, nodeName) || !isValid(editor, name(parent), wrapName)) {
  8457. return 'invalid-child';
  8458. } else {
  8459. return 'valid';
  8460. }
  8461. });
  8462. const applyWordGrab = (editor, rng) => {
  8463. const r = expandRng(editor, rng, [{ inline: 'span' }]);
  8464. rng.setStart(r.startContainer, r.startOffset);
  8465. rng.setEnd(r.endContainer, r.endOffset);
  8466. editor.selection.setRng(rng);
  8467. };
  8468. const applyAnnotation = (elem, masterUId, data, annotationName, decorate, directAnnotation) => {
  8469. const {uid = masterUId, ...otherData} = data;
  8470. add$2(elem, annotation());
  8471. set$2(elem, `${ dataAnnotationId() }`, uid);
  8472. set$2(elem, `${ dataAnnotation() }`, annotationName);
  8473. const {attributes = {}, classes = []} = decorate(uid, otherData);
  8474. setAll$1(elem, attributes);
  8475. add(elem, classes);
  8476. if (directAnnotation) {
  8477. if (classes.length > 0) {
  8478. set$2(elem, `${ dataAnnotationClasses() }`, classes.join(','));
  8479. }
  8480. const attributeNames = keys(attributes);
  8481. if (attributeNames.length > 0) {
  8482. set$2(elem, `${ dataAnnotationAttributes() }`, attributeNames.join(','));
  8483. }
  8484. }
  8485. };
  8486. const removeDirectAnnotation = elem => {
  8487. remove$8(elem, annotation());
  8488. remove$b(elem, `${ dataAnnotationId() }`);
  8489. remove$b(elem, `${ dataAnnotation() }`);
  8490. remove$b(elem, `${ dataAnnotationActive() }`);
  8491. const customAttrNames = getOpt(elem, `${ dataAnnotationAttributes() }`).map(names => names.split(',')).getOr([]);
  8492. const customClasses = getOpt(elem, `${ dataAnnotationClasses() }`).map(names => names.split(',')).getOr([]);
  8493. each$f(customAttrNames, name => remove$b(elem, name));
  8494. remove$5(elem, customClasses);
  8495. remove$b(elem, `${ dataAnnotationClasses() }`);
  8496. remove$b(elem, `${ dataAnnotationAttributes() }`);
  8497. };
  8498. const makeAnnotation = (eDoc, uid, data, annotationName, decorate) => {
  8499. const master = SugarElement.fromTag('span', eDoc);
  8500. applyAnnotation(master, uid, data, annotationName, decorate, false);
  8501. return master;
  8502. };
  8503. const annotate = (editor, rng, uid, annotationName, decorate, data) => {
  8504. const newWrappers = [];
  8505. const master = makeAnnotation(editor.getDoc(), uid, data, annotationName, decorate);
  8506. const wrapper = value$2();
  8507. const finishWrapper = () => {
  8508. wrapper.clear();
  8509. };
  8510. const getOrOpenWrapper = () => wrapper.get().getOrThunk(() => {
  8511. const nu = shallow$1(master);
  8512. newWrappers.push(nu);
  8513. wrapper.set(nu);
  8514. return nu;
  8515. });
  8516. const processElements = elems => {
  8517. each$f(elems, processElement);
  8518. };
  8519. const processElement = elem => {
  8520. const ctx = context(editor, elem, 'span', name(elem));
  8521. switch (ctx) {
  8522. case 'invalid-child': {
  8523. finishWrapper();
  8524. const children$1 = children(elem);
  8525. processElements(children$1);
  8526. finishWrapper();
  8527. break;
  8528. }
  8529. case 'valid-block': {
  8530. finishWrapper();
  8531. applyAnnotation(elem, uid, data, annotationName, decorate, true);
  8532. break;
  8533. }
  8534. case 'valid': {
  8535. const w = getOrOpenWrapper();
  8536. wrap$2(elem, w);
  8537. break;
  8538. }
  8539. }
  8540. };
  8541. const processNodes = nodes => {
  8542. const elems = map$3(nodes, SugarElement.fromDom);
  8543. processElements(elems);
  8544. };
  8545. walk$3(editor.dom, rng, nodes => {
  8546. finishWrapper();
  8547. processNodes(nodes);
  8548. });
  8549. return newWrappers;
  8550. };
  8551. const annotateWithBookmark = (editor, name, settings, data) => {
  8552. editor.undoManager.transact(() => {
  8553. const selection = editor.selection;
  8554. const initialRng = selection.getRng();
  8555. const hasFakeSelection = getCellsFromEditor(editor).length > 0;
  8556. const masterUid = generate$1('mce-annotation');
  8557. if (initialRng.collapsed && !hasFakeSelection) {
  8558. applyWordGrab(editor, initialRng);
  8559. }
  8560. if (selection.getRng().collapsed && !hasFakeSelection) {
  8561. const wrapper = makeAnnotation(editor.getDoc(), masterUid, data, name, settings.decorate);
  8562. set(wrapper, nbsp);
  8563. selection.getRng().insertNode(wrapper.dom);
  8564. selection.select(wrapper.dom);
  8565. } else {
  8566. preserve(selection, false, () => {
  8567. runOnRanges(editor, selectionRng => {
  8568. annotate(editor, selectionRng, masterUid, name, settings.decorate, data);
  8569. });
  8570. });
  8571. }
  8572. });
  8573. };
  8574. const Annotator = editor => {
  8575. const registry = create$c();
  8576. setup$w(editor, registry);
  8577. const changes = setup$x(editor, registry);
  8578. const isSpan = isTag('span');
  8579. const removeAnnotations = elements => {
  8580. each$f(elements, element => {
  8581. if (isSpan(element)) {
  8582. unwrap(element);
  8583. } else {
  8584. removeDirectAnnotation(element);
  8585. }
  8586. });
  8587. };
  8588. return {
  8589. register: (name, settings) => {
  8590. registry.register(name, settings);
  8591. },
  8592. annotate: (name, data) => {
  8593. registry.lookup(name).each(settings => {
  8594. annotateWithBookmark(editor, name, settings, data);
  8595. });
  8596. },
  8597. annotationChanged: (name, callback) => {
  8598. changes.addListener(name, callback);
  8599. },
  8600. remove: name => {
  8601. const bookmark = editor.selection.getBookmark();
  8602. identify(editor, Optional.some(name)).each(({elements}) => {
  8603. removeAnnotations(elements);
  8604. });
  8605. editor.selection.moveToBookmark(bookmark);
  8606. },
  8607. removeAll: name => {
  8608. const bookmark = editor.selection.getBookmark();
  8609. each$e(findAll(editor, name), (elements, _) => {
  8610. removeAnnotations(elements);
  8611. });
  8612. editor.selection.moveToBookmark(bookmark);
  8613. },
  8614. getAll: name => {
  8615. const directory = findAll(editor, name);
  8616. return map$2(directory, elems => map$3(elems, elem => elem.dom));
  8617. }
  8618. };
  8619. };
  8620. const BookmarkManager = selection => {
  8621. return {
  8622. getBookmark: curry(getBookmark$1, selection),
  8623. moveToBookmark: curry(moveToBookmark, selection)
  8624. };
  8625. };
  8626. BookmarkManager.isBookmarkNode = isBookmarkNode$1;
  8627. const isXYWithinRange = (clientX, clientY, range) => {
  8628. if (range.collapsed) {
  8629. return false;
  8630. } else {
  8631. return exists(range.getClientRects(), rect => containsXY(rect, clientX, clientY));
  8632. }
  8633. };
  8634. const firePreProcess = (editor, args) => editor.dispatch('PreProcess', args);
  8635. const firePostProcess = (editor, args) => editor.dispatch('PostProcess', args);
  8636. const fireRemove = editor => editor.dispatch('remove');
  8637. const fireDetach = editor => editor.dispatch('detach');
  8638. const fireSwitchMode = (editor, mode) => editor.dispatch('SwitchMode', { mode });
  8639. const fireObjectResizeStart = (editor, target, width, height, origin) => {
  8640. editor.dispatch('ObjectResizeStart', {
  8641. target,
  8642. width,
  8643. height,
  8644. origin
  8645. });
  8646. };
  8647. const fireObjectResized = (editor, target, width, height, origin) => {
  8648. editor.dispatch('ObjectResized', {
  8649. target,
  8650. width,
  8651. height,
  8652. origin
  8653. });
  8654. };
  8655. const firePreInit = editor => editor.dispatch('PreInit');
  8656. const firePostRender = editor => editor.dispatch('PostRender');
  8657. const fireInit = editor => editor.dispatch('Init');
  8658. const firePlaceholderToggle = (editor, state) => editor.dispatch('PlaceholderToggle', { state });
  8659. const fireError = (editor, errorType, error) => editor.dispatch(errorType, error);
  8660. const fireFormatApply = (editor, format, node, vars) => editor.dispatch('FormatApply', {
  8661. format,
  8662. node,
  8663. vars
  8664. });
  8665. const fireFormatRemove = (editor, format, node, vars) => editor.dispatch('FormatRemove', {
  8666. format,
  8667. node,
  8668. vars
  8669. });
  8670. const fireBeforeSetContent = (editor, args) => editor.dispatch('BeforeSetContent', args);
  8671. const fireSetContent = (editor, args) => editor.dispatch('SetContent', args);
  8672. const fireBeforeGetContent = (editor, args) => editor.dispatch('BeforeGetContent', args);
  8673. const fireGetContent = (editor, args) => editor.dispatch('GetContent', args);
  8674. const fireAutocompleterStart = (editor, args) => editor.dispatch('AutocompleterStart', args);
  8675. const fireAutocompleterUpdate = (editor, args) => editor.dispatch('AutocompleterUpdate', args);
  8676. const fireAutocompleterEnd = editor => editor.dispatch('AutocompleterEnd');
  8677. const firePastePreProcess = (editor, html, internal) => editor.dispatch('PastePreProcess', {
  8678. content: html,
  8679. internal
  8680. });
  8681. const firePastePostProcess = (editor, node, internal) => editor.dispatch('PastePostProcess', {
  8682. node,
  8683. internal
  8684. });
  8685. const firePastePlainTextToggle = (editor, state) => editor.dispatch('PastePlainTextToggle', { state });
  8686. const VK = {
  8687. BACKSPACE: 8,
  8688. DELETE: 46,
  8689. DOWN: 40,
  8690. ENTER: 13,
  8691. ESC: 27,
  8692. LEFT: 37,
  8693. RIGHT: 39,
  8694. SPACEBAR: 32,
  8695. TAB: 9,
  8696. UP: 38,
  8697. PAGE_UP: 33,
  8698. PAGE_DOWN: 34,
  8699. END: 35,
  8700. HOME: 36,
  8701. modifierPressed: e => {
  8702. return e.shiftKey || e.ctrlKey || e.altKey || VK.metaKeyPressed(e);
  8703. },
  8704. metaKeyPressed: e => {
  8705. return Env.os.isMacOS() || Env.os.isiOS() ? e.metaKey : e.ctrlKey && !e.altKey;
  8706. }
  8707. };
  8708. const elementSelectionAttr = 'data-mce-selected';
  8709. const controlElmSelector = 'table,img,figure.image,hr,video,span.mce-preview-object';
  8710. const abs = Math.abs;
  8711. const round$1 = Math.round;
  8712. const resizeHandles = {
  8713. nw: [
  8714. 0,
  8715. 0,
  8716. -1,
  8717. -1
  8718. ],
  8719. ne: [
  8720. 1,
  8721. 0,
  8722. 1,
  8723. -1
  8724. ],
  8725. se: [
  8726. 1,
  8727. 1,
  8728. 1,
  8729. 1
  8730. ],
  8731. sw: [
  8732. 0,
  8733. 1,
  8734. -1,
  8735. 1
  8736. ]
  8737. };
  8738. const isTouchEvent = evt => evt.type === 'longpress' || evt.type.indexOf('touch') === 0;
  8739. const ControlSelection = (selection, editor) => {
  8740. const dom = editor.dom;
  8741. const editableDoc = editor.getDoc();
  8742. const rootDocument = document;
  8743. const rootElement = editor.getBody();
  8744. let selectedElm, selectedElmGhost, resizeHelper, selectedHandle, resizeBackdrop;
  8745. let startX, startY, selectedElmX, selectedElmY, startW, startH, ratio, resizeStarted;
  8746. let width;
  8747. let height;
  8748. let startScrollWidth;
  8749. let startScrollHeight;
  8750. const isImage = elm => isNonNullable(elm) && (isImg(elm) || dom.is(elm, 'figure.image'));
  8751. const isMedia = elm => isMedia$2(elm) || dom.hasClass(elm, 'mce-preview-object');
  8752. const isEventOnImageOutsideRange = (evt, range) => {
  8753. if (isTouchEvent(evt)) {
  8754. const touch = evt.touches[0];
  8755. return isImage(evt.target) && !isXYWithinRange(touch.clientX, touch.clientY, range);
  8756. } else {
  8757. return isImage(evt.target) && !isXYWithinRange(evt.clientX, evt.clientY, range);
  8758. }
  8759. };
  8760. const contextMenuSelectImage = evt => {
  8761. const target = evt.target;
  8762. if (isEventOnImageOutsideRange(evt, editor.selection.getRng()) && !evt.isDefaultPrevented()) {
  8763. editor.selection.select(target);
  8764. }
  8765. };
  8766. const getResizeTargets = elm => {
  8767. if (dom.is(elm, 'figure.image')) {
  8768. return [elm.querySelector('img')];
  8769. } else if (dom.hasClass(elm, 'mce-preview-object') && isNonNullable(elm.firstElementChild)) {
  8770. return [
  8771. elm,
  8772. elm.firstElementChild
  8773. ];
  8774. } else {
  8775. return [elm];
  8776. }
  8777. };
  8778. const isResizable = elm => {
  8779. const selector = getObjectResizing(editor);
  8780. if (!selector) {
  8781. return false;
  8782. }
  8783. if (elm.getAttribute('data-mce-resize') === 'false') {
  8784. return false;
  8785. }
  8786. if (elm === editor.getBody()) {
  8787. return false;
  8788. }
  8789. if (dom.hasClass(elm, 'mce-preview-object')) {
  8790. return is$1(SugarElement.fromDom(elm.firstElementChild), selector);
  8791. } else {
  8792. return is$1(SugarElement.fromDom(elm), selector);
  8793. }
  8794. };
  8795. const createGhostElement = elm => {
  8796. if (isMedia(elm)) {
  8797. return dom.create('img', { src: Env.transparentSrc });
  8798. } else {
  8799. return elm.cloneNode(true);
  8800. }
  8801. };
  8802. const setSizeProp = (element, name, value) => {
  8803. if (isNonNullable(value)) {
  8804. const targets = getResizeTargets(element);
  8805. each$f(targets, target => {
  8806. if (target.style[name] || !editor.schema.isValid(target.nodeName.toLowerCase(), name)) {
  8807. dom.setStyle(target, name, value);
  8808. } else {
  8809. dom.setAttrib(target, name, '' + value);
  8810. }
  8811. });
  8812. }
  8813. };
  8814. const setGhostElmSize = (ghostElm, width, height) => {
  8815. setSizeProp(ghostElm, 'width', width);
  8816. setSizeProp(ghostElm, 'height', height);
  8817. };
  8818. const resizeGhostElement = e => {
  8819. let deltaX, deltaY, proportional;
  8820. let resizeHelperX, resizeHelperY;
  8821. deltaX = e.screenX - startX;
  8822. deltaY = e.screenY - startY;
  8823. width = deltaX * selectedHandle[2] + startW;
  8824. height = deltaY * selectedHandle[3] + startH;
  8825. width = width < 5 ? 5 : width;
  8826. height = height < 5 ? 5 : height;
  8827. if ((isImage(selectedElm) || isMedia(selectedElm)) && getResizeImgProportional(editor) !== false) {
  8828. proportional = !VK.modifierPressed(e);
  8829. } else {
  8830. proportional = VK.modifierPressed(e);
  8831. }
  8832. if (proportional) {
  8833. if (abs(deltaX) > abs(deltaY)) {
  8834. height = round$1(width * ratio);
  8835. width = round$1(height / ratio);
  8836. } else {
  8837. width = round$1(height / ratio);
  8838. height = round$1(width * ratio);
  8839. }
  8840. }
  8841. setGhostElmSize(selectedElmGhost, width, height);
  8842. resizeHelperX = selectedHandle.startPos.x + deltaX;
  8843. resizeHelperY = selectedHandle.startPos.y + deltaY;
  8844. resizeHelperX = resizeHelperX > 0 ? resizeHelperX : 0;
  8845. resizeHelperY = resizeHelperY > 0 ? resizeHelperY : 0;
  8846. dom.setStyles(resizeHelper, {
  8847. left: resizeHelperX,
  8848. top: resizeHelperY,
  8849. display: 'block'
  8850. });
  8851. resizeHelper.innerHTML = width + ' &times; ' + height;
  8852. if (selectedHandle[2] < 0 && selectedElmGhost.clientWidth <= width) {
  8853. dom.setStyle(selectedElmGhost, 'left', selectedElmX + (startW - width));
  8854. }
  8855. if (selectedHandle[3] < 0 && selectedElmGhost.clientHeight <= height) {
  8856. dom.setStyle(selectedElmGhost, 'top', selectedElmY + (startH - height));
  8857. }
  8858. deltaX = rootElement.scrollWidth - startScrollWidth;
  8859. deltaY = rootElement.scrollHeight - startScrollHeight;
  8860. if (deltaX + deltaY !== 0) {
  8861. dom.setStyles(resizeHelper, {
  8862. left: resizeHelperX - deltaX,
  8863. top: resizeHelperY - deltaY
  8864. });
  8865. }
  8866. if (!resizeStarted) {
  8867. fireObjectResizeStart(editor, selectedElm, startW, startH, 'corner-' + selectedHandle.name);
  8868. resizeStarted = true;
  8869. }
  8870. };
  8871. const endGhostResize = () => {
  8872. const wasResizeStarted = resizeStarted;
  8873. resizeStarted = false;
  8874. if (wasResizeStarted) {
  8875. setSizeProp(selectedElm, 'width', width);
  8876. setSizeProp(selectedElm, 'height', height);
  8877. }
  8878. dom.unbind(editableDoc, 'mousemove', resizeGhostElement);
  8879. dom.unbind(editableDoc, 'mouseup', endGhostResize);
  8880. if (rootDocument !== editableDoc) {
  8881. dom.unbind(rootDocument, 'mousemove', resizeGhostElement);
  8882. dom.unbind(rootDocument, 'mouseup', endGhostResize);
  8883. }
  8884. dom.remove(selectedElmGhost);
  8885. dom.remove(resizeHelper);
  8886. dom.remove(resizeBackdrop);
  8887. showResizeRect(selectedElm);
  8888. if (wasResizeStarted) {
  8889. fireObjectResized(editor, selectedElm, width, height, 'corner-' + selectedHandle.name);
  8890. dom.setAttrib(selectedElm, 'style', dom.getAttrib(selectedElm, 'style'));
  8891. }
  8892. editor.nodeChanged();
  8893. };
  8894. const showResizeRect = targetElm => {
  8895. unbindResizeHandleEvents();
  8896. const position = dom.getPos(targetElm, rootElement);
  8897. const selectedElmX = position.x;
  8898. const selectedElmY = position.y;
  8899. const rect = targetElm.getBoundingClientRect();
  8900. const targetWidth = rect.width || rect.right - rect.left;
  8901. const targetHeight = rect.height || rect.bottom - rect.top;
  8902. if (selectedElm !== targetElm) {
  8903. hideResizeRect();
  8904. selectedElm = targetElm;
  8905. width = height = 0;
  8906. }
  8907. const e = editor.dispatch('ObjectSelected', { target: targetElm });
  8908. if (isResizable(targetElm) && !e.isDefaultPrevented()) {
  8909. each$e(resizeHandles, (handle, name) => {
  8910. let handleElm;
  8911. const startDrag = e => {
  8912. const target = getResizeTargets(selectedElm)[0];
  8913. startX = e.screenX;
  8914. startY = e.screenY;
  8915. startW = target.clientWidth;
  8916. startH = target.clientHeight;
  8917. ratio = startH / startW;
  8918. selectedHandle = handle;
  8919. selectedHandle.name = name;
  8920. selectedHandle.startPos = {
  8921. x: targetWidth * handle[0] + selectedElmX,
  8922. y: targetHeight * handle[1] + selectedElmY
  8923. };
  8924. startScrollWidth = rootElement.scrollWidth;
  8925. startScrollHeight = rootElement.scrollHeight;
  8926. resizeBackdrop = dom.add(rootElement, 'div', {
  8927. 'class': 'mce-resize-backdrop',
  8928. 'data-mce-bogus': 'all'
  8929. });
  8930. dom.setStyles(resizeBackdrop, {
  8931. position: 'fixed',
  8932. left: '0',
  8933. top: '0',
  8934. width: '100%',
  8935. height: '100%'
  8936. });
  8937. selectedElmGhost = createGhostElement(selectedElm);
  8938. dom.addClass(selectedElmGhost, 'mce-clonedresizable');
  8939. dom.setAttrib(selectedElmGhost, 'data-mce-bogus', 'all');
  8940. selectedElmGhost.contentEditable = 'false';
  8941. dom.setStyles(selectedElmGhost, {
  8942. left: selectedElmX,
  8943. top: selectedElmY,
  8944. margin: 0
  8945. });
  8946. setGhostElmSize(selectedElmGhost, targetWidth, targetHeight);
  8947. selectedElmGhost.removeAttribute(elementSelectionAttr);
  8948. rootElement.appendChild(selectedElmGhost);
  8949. dom.bind(editableDoc, 'mousemove', resizeGhostElement);
  8950. dom.bind(editableDoc, 'mouseup', endGhostResize);
  8951. if (rootDocument !== editableDoc) {
  8952. dom.bind(rootDocument, 'mousemove', resizeGhostElement);
  8953. dom.bind(rootDocument, 'mouseup', endGhostResize);
  8954. }
  8955. resizeHelper = dom.add(rootElement, 'div', {
  8956. 'class': 'mce-resize-helper',
  8957. 'data-mce-bogus': 'all'
  8958. }, startW + ' &times; ' + startH);
  8959. };
  8960. handleElm = dom.get('mceResizeHandle' + name);
  8961. if (handleElm) {
  8962. dom.remove(handleElm);
  8963. }
  8964. handleElm = dom.add(rootElement, 'div', {
  8965. 'id': 'mceResizeHandle' + name,
  8966. 'data-mce-bogus': 'all',
  8967. 'class': 'mce-resizehandle',
  8968. 'unselectable': true,
  8969. 'style': 'cursor:' + name + '-resize; margin:0; padding:0'
  8970. });
  8971. dom.bind(handleElm, 'mousedown', e => {
  8972. e.stopImmediatePropagation();
  8973. e.preventDefault();
  8974. startDrag(e);
  8975. });
  8976. handle.elm = handleElm;
  8977. dom.setStyles(handleElm, {
  8978. left: targetWidth * handle[0] + selectedElmX - handleElm.offsetWidth / 2,
  8979. top: targetHeight * handle[1] + selectedElmY - handleElm.offsetHeight / 2
  8980. });
  8981. });
  8982. } else {
  8983. hideResizeRect(false);
  8984. }
  8985. };
  8986. const throttledShowResizeRect = first$1(showResizeRect, 0);
  8987. const hideResizeRect = (removeSelected = true) => {
  8988. throttledShowResizeRect.cancel();
  8989. unbindResizeHandleEvents();
  8990. if (selectedElm && removeSelected) {
  8991. selectedElm.removeAttribute(elementSelectionAttr);
  8992. }
  8993. each$e(resizeHandles, (value, name) => {
  8994. const handleElm = dom.get('mceResizeHandle' + name);
  8995. if (handleElm) {
  8996. dom.unbind(handleElm);
  8997. dom.remove(handleElm);
  8998. }
  8999. });
  9000. };
  9001. const isChildOrEqual = (node, parent) => isNonNullable(node) && dom.isChildOf(node, parent);
  9002. const updateResizeRect = e => {
  9003. if (resizeStarted || editor.removed || editor.composing) {
  9004. return;
  9005. }
  9006. const targetElm = e.type === 'mousedown' ? e.target : selection.getNode();
  9007. const controlElm = closest$3(SugarElement.fromDom(targetElm), controlElmSelector).map(e => e.dom).getOrUndefined();
  9008. const selectedValue = isNonNullable(controlElm) ? dom.getAttrib(controlElm, elementSelectionAttr, '1') : '1';
  9009. each$f(dom.select(`img[${ elementSelectionAttr }],hr[${ elementSelectionAttr }]`), img => {
  9010. img.removeAttribute(elementSelectionAttr);
  9011. });
  9012. if (isChildOrEqual(controlElm, rootElement)) {
  9013. disableGeckoResize();
  9014. const startElm = selection.getStart(true);
  9015. if (isChildOrEqual(startElm, controlElm) && isChildOrEqual(selection.getEnd(true), controlElm)) {
  9016. dom.setAttrib(controlElm, elementSelectionAttr, selectedValue);
  9017. throttledShowResizeRect.throttle(controlElm);
  9018. return;
  9019. }
  9020. }
  9021. hideResizeRect();
  9022. };
  9023. const unbindResizeHandleEvents = () => {
  9024. each$e(resizeHandles, handle => {
  9025. if (handle.elm) {
  9026. dom.unbind(handle.elm);
  9027. delete handle.elm;
  9028. }
  9029. });
  9030. };
  9031. const disableGeckoResize = () => {
  9032. try {
  9033. editor.getDoc().execCommand('enableObjectResizing', false, 'false');
  9034. } catch (ex) {
  9035. }
  9036. };
  9037. editor.on('init', () => {
  9038. disableGeckoResize();
  9039. editor.on('NodeChange ResizeEditor ResizeWindow ResizeContent drop', updateResizeRect);
  9040. editor.on('keyup compositionend', e => {
  9041. if (selectedElm && selectedElm.nodeName === 'TABLE') {
  9042. updateResizeRect(e);
  9043. }
  9044. });
  9045. editor.on('hide blur', hideResizeRect);
  9046. editor.on('contextmenu longpress', contextMenuSelectImage, true);
  9047. });
  9048. editor.on('remove', unbindResizeHandleEvents);
  9049. const destroy = () => {
  9050. throttledShowResizeRect.cancel();
  9051. selectedElm = selectedElmGhost = resizeBackdrop = null;
  9052. };
  9053. return {
  9054. isResizable,
  9055. showResizeRect,
  9056. hideResizeRect,
  9057. updateResizeRect,
  9058. destroy
  9059. };
  9060. };
  9061. const setStart = (rng, situ) => {
  9062. situ.fold(e => {
  9063. rng.setStartBefore(e.dom);
  9064. }, (e, o) => {
  9065. rng.setStart(e.dom, o);
  9066. }, e => {
  9067. rng.setStartAfter(e.dom);
  9068. });
  9069. };
  9070. const setFinish = (rng, situ) => {
  9071. situ.fold(e => {
  9072. rng.setEndBefore(e.dom);
  9073. }, (e, o) => {
  9074. rng.setEnd(e.dom, o);
  9075. }, e => {
  9076. rng.setEndAfter(e.dom);
  9077. });
  9078. };
  9079. const relativeToNative = (win, startSitu, finishSitu) => {
  9080. const range = win.document.createRange();
  9081. setStart(range, startSitu);
  9082. setFinish(range, finishSitu);
  9083. return range;
  9084. };
  9085. const exactToNative = (win, start, soffset, finish, foffset) => {
  9086. const rng = win.document.createRange();
  9087. rng.setStart(start.dom, soffset);
  9088. rng.setEnd(finish.dom, foffset);
  9089. return rng;
  9090. };
  9091. const adt$3 = Adt.generate([
  9092. {
  9093. ltr: [
  9094. 'start',
  9095. 'soffset',
  9096. 'finish',
  9097. 'foffset'
  9098. ]
  9099. },
  9100. {
  9101. rtl: [
  9102. 'start',
  9103. 'soffset',
  9104. 'finish',
  9105. 'foffset'
  9106. ]
  9107. }
  9108. ]);
  9109. const fromRange = (win, type, range) => type(SugarElement.fromDom(range.startContainer), range.startOffset, SugarElement.fromDom(range.endContainer), range.endOffset);
  9110. const getRanges = (win, selection) => selection.match({
  9111. domRange: rng => {
  9112. return {
  9113. ltr: constant(rng),
  9114. rtl: Optional.none
  9115. };
  9116. },
  9117. relative: (startSitu, finishSitu) => {
  9118. return {
  9119. ltr: cached(() => relativeToNative(win, startSitu, finishSitu)),
  9120. rtl: cached(() => Optional.some(relativeToNative(win, finishSitu, startSitu)))
  9121. };
  9122. },
  9123. exact: (start, soffset, finish, foffset) => {
  9124. return {
  9125. ltr: cached(() => exactToNative(win, start, soffset, finish, foffset)),
  9126. rtl: cached(() => Optional.some(exactToNative(win, finish, foffset, start, soffset)))
  9127. };
  9128. }
  9129. });
  9130. const doDiagnose = (win, ranges) => {
  9131. const rng = ranges.ltr();
  9132. if (rng.collapsed) {
  9133. const reversed = ranges.rtl().filter(rev => rev.collapsed === false);
  9134. 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));
  9135. } else {
  9136. return fromRange(win, adt$3.ltr, rng);
  9137. }
  9138. };
  9139. const diagnose = (win, selection) => {
  9140. const ranges = getRanges(win, selection);
  9141. return doDiagnose(win, ranges);
  9142. };
  9143. adt$3.ltr;
  9144. adt$3.rtl;
  9145. const create$a = (start, soffset, finish, foffset) => ({
  9146. start,
  9147. soffset,
  9148. finish,
  9149. foffset
  9150. });
  9151. const SimRange = { create: create$a };
  9152. const caretPositionFromPoint = (doc, x, y) => {
  9153. var _a, _b;
  9154. return Optional.from((_b = (_a = doc.dom).caretPositionFromPoint) === null || _b === void 0 ? void 0 : _b.call(_a, x, y)).bind(pos => {
  9155. if (pos.offsetNode === null) {
  9156. return Optional.none();
  9157. }
  9158. const r = doc.dom.createRange();
  9159. r.setStart(pos.offsetNode, pos.offset);
  9160. r.collapse();
  9161. return Optional.some(r);
  9162. });
  9163. };
  9164. const caretRangeFromPoint = (doc, x, y) => {
  9165. var _a, _b;
  9166. return Optional.from((_b = (_a = doc.dom).caretRangeFromPoint) === null || _b === void 0 ? void 0 : _b.call(_a, x, y));
  9167. };
  9168. const availableSearch = (() => {
  9169. if (document.caretPositionFromPoint) {
  9170. return caretPositionFromPoint;
  9171. } else if (document.caretRangeFromPoint) {
  9172. return caretRangeFromPoint;
  9173. } else {
  9174. return Optional.none;
  9175. }
  9176. })();
  9177. const fromPoint$1 = (win, x, y) => {
  9178. const doc = SugarElement.fromDom(win.document);
  9179. return availableSearch(doc, x, y).map(rng => SimRange.create(SugarElement.fromDom(rng.startContainer), rng.startOffset, SugarElement.fromDom(rng.endContainer), rng.endOffset));
  9180. };
  9181. const adt$2 = Adt.generate([
  9182. { before: ['element'] },
  9183. {
  9184. on: [
  9185. 'element',
  9186. 'offset'
  9187. ]
  9188. },
  9189. { after: ['element'] }
  9190. ]);
  9191. const cata = (subject, onBefore, onOn, onAfter) => subject.fold(onBefore, onOn, onAfter);
  9192. const getStart$2 = situ => situ.fold(identity, identity, identity);
  9193. const before$1 = adt$2.before;
  9194. const on = adt$2.on;
  9195. const after$1 = adt$2.after;
  9196. const Situ = {
  9197. before: before$1,
  9198. on,
  9199. after: after$1,
  9200. cata,
  9201. getStart: getStart$2
  9202. };
  9203. const adt$1 = Adt.generate([
  9204. { domRange: ['rng'] },
  9205. {
  9206. relative: [
  9207. 'startSitu',
  9208. 'finishSitu'
  9209. ]
  9210. },
  9211. {
  9212. exact: [
  9213. 'start',
  9214. 'soffset',
  9215. 'finish',
  9216. 'foffset'
  9217. ]
  9218. }
  9219. ]);
  9220. const exactFromRange = simRange => adt$1.exact(simRange.start, simRange.soffset, simRange.finish, simRange.foffset);
  9221. const getStart$1 = selection => selection.match({
  9222. domRange: rng => SugarElement.fromDom(rng.startContainer),
  9223. relative: (startSitu, _finishSitu) => Situ.getStart(startSitu),
  9224. exact: (start, _soffset, _finish, _foffset) => start
  9225. });
  9226. const domRange = adt$1.domRange;
  9227. const relative = adt$1.relative;
  9228. const exact = adt$1.exact;
  9229. const getWin = selection => {
  9230. const start = getStart$1(selection);
  9231. return defaultView(start);
  9232. };
  9233. const range = SimRange.create;
  9234. const SimSelection = {
  9235. domRange,
  9236. relative,
  9237. exact,
  9238. exactFromRange,
  9239. getWin,
  9240. range
  9241. };
  9242. const beforeSpecial = (element, offset) => {
  9243. const name$1 = name(element);
  9244. if ('input' === name$1) {
  9245. return Situ.after(element);
  9246. } else if (!contains$2([
  9247. 'br',
  9248. 'img'
  9249. ], name$1)) {
  9250. return Situ.on(element, offset);
  9251. } else {
  9252. return offset === 0 ? Situ.before(element) : Situ.after(element);
  9253. }
  9254. };
  9255. const preprocessRelative = (startSitu, finishSitu) => {
  9256. const start = startSitu.fold(Situ.before, beforeSpecial, Situ.after);
  9257. const finish = finishSitu.fold(Situ.before, beforeSpecial, Situ.after);
  9258. return SimSelection.relative(start, finish);
  9259. };
  9260. const preprocessExact = (start, soffset, finish, foffset) => {
  9261. const startSitu = beforeSpecial(start, soffset);
  9262. const finishSitu = beforeSpecial(finish, foffset);
  9263. return SimSelection.relative(startSitu, finishSitu);
  9264. };
  9265. const preprocess = selection => selection.match({
  9266. domRange: rng => {
  9267. const start = SugarElement.fromDom(rng.startContainer);
  9268. const finish = SugarElement.fromDom(rng.endContainer);
  9269. return preprocessExact(start, rng.startOffset, finish, rng.endOffset);
  9270. },
  9271. relative: preprocessRelative,
  9272. exact: preprocessExact
  9273. });
  9274. const fromElements = (elements, scope) => {
  9275. const doc = scope || document;
  9276. const fragment = doc.createDocumentFragment();
  9277. each$f(elements, element => {
  9278. fragment.appendChild(element.dom);
  9279. });
  9280. return SugarElement.fromDom(fragment);
  9281. };
  9282. const toNative = selection => {
  9283. const win = SimSelection.getWin(selection).dom;
  9284. const getDomRange = (start, soffset, finish, foffset) => exactToNative(win, start, soffset, finish, foffset);
  9285. const filtered = preprocess(selection);
  9286. return diagnose(win, filtered).match({
  9287. ltr: getDomRange,
  9288. rtl: getDomRange
  9289. });
  9290. };
  9291. const getAtPoint = (win, x, y) => fromPoint$1(win, x, y);
  9292. const fromPoint = (clientX, clientY, doc) => getAtPoint(doc.defaultView, clientX, clientY).map(simRange => {
  9293. const rng = doc.createRange();
  9294. rng.setStart(simRange.start.dom, simRange.soffset);
  9295. rng.setEnd(simRange.finish.dom, simRange.foffset);
  9296. return rng;
  9297. }).getOrUndefined();
  9298. const isEq$4 = (rng1, rng2) => {
  9299. return rng1 && rng2 && (rng1.startContainer === rng2.startContainer && rng1.startOffset === rng2.startOffset) && (rng1.endContainer === rng2.endContainer && rng1.endOffset === rng2.endOffset);
  9300. };
  9301. const findParent = (node, rootNode, predicate) => {
  9302. while (node && node !== rootNode) {
  9303. if (predicate(node)) {
  9304. return node;
  9305. }
  9306. node = node.parentNode;
  9307. }
  9308. return null;
  9309. };
  9310. const hasParent$1 = (node, rootNode, predicate) => findParent(node, rootNode, predicate) !== null;
  9311. const hasParentWithName = (node, rootNode, name) => hasParent$1(node, rootNode, node => {
  9312. return node.nodeName === name;
  9313. });
  9314. const isTable = node => node && node.nodeName === 'TABLE';
  9315. const isTableCell$2 = node => node && /^(TD|TH|CAPTION)$/.test(node.nodeName);
  9316. const isCeFalseCaretContainer = (node, rootNode) => isCaretContainer$2(node) && hasParent$1(node, rootNode, isCaretNode) === false;
  9317. const hasBrBeforeAfter = (dom, node, left) => {
  9318. const walker = new DomTreeWalker(node, dom.getParent(node.parentNode, dom.isBlock) || dom.getRoot());
  9319. while (node = walker[left ? 'prev' : 'next']()) {
  9320. if (isBr$6(node)) {
  9321. return true;
  9322. }
  9323. }
  9324. };
  9325. const isPrevNode = (node, name) => node.previousSibling && node.previousSibling.nodeName === name;
  9326. const hasContentEditableFalseParent = (body, node) => {
  9327. while (node && node !== body) {
  9328. if (isContentEditableFalse$b(node)) {
  9329. return true;
  9330. }
  9331. node = node.parentNode;
  9332. }
  9333. return false;
  9334. };
  9335. const findTextNodeRelative = (dom, isAfterNode, collapsed, left, startNode) => {
  9336. let lastInlineElement;
  9337. const body = dom.getRoot();
  9338. let node;
  9339. const nonEmptyElementsMap = dom.schema.getNonEmptyElements();
  9340. const parentBlockContainer = dom.getParent(startNode.parentNode, dom.isBlock) || body;
  9341. if (left && isBr$6(startNode) && isAfterNode && dom.isEmpty(parentBlockContainer)) {
  9342. return Optional.some(CaretPosition(startNode.parentNode, dom.nodeIndex(startNode)));
  9343. }
  9344. const walker = new DomTreeWalker(startNode, parentBlockContainer);
  9345. while (node = walker[left ? 'prev' : 'next']()) {
  9346. if (dom.getContentEditableParent(node) === 'false' || isCeFalseCaretContainer(node, body)) {
  9347. return Optional.none();
  9348. }
  9349. if (isText$9(node) && node.nodeValue.length > 0) {
  9350. if (hasParentWithName(node, body, 'A') === false) {
  9351. return Optional.some(CaretPosition(node, left ? node.nodeValue.length : 0));
  9352. }
  9353. return Optional.none();
  9354. }
  9355. if (dom.isBlock(node) || nonEmptyElementsMap[node.nodeName.toLowerCase()]) {
  9356. return Optional.none();
  9357. }
  9358. lastInlineElement = node;
  9359. }
  9360. if (isComment(lastInlineElement)) {
  9361. return Optional.none();
  9362. }
  9363. if (collapsed && lastInlineElement) {
  9364. return Optional.some(CaretPosition(lastInlineElement, 0));
  9365. }
  9366. return Optional.none();
  9367. };
  9368. const normalizeEndPoint = (dom, collapsed, start, rng) => {
  9369. let container, offset;
  9370. const body = dom.getRoot();
  9371. let node;
  9372. let directionLeft, normalized = false;
  9373. container = rng[(start ? 'start' : 'end') + 'Container'];
  9374. offset = rng[(start ? 'start' : 'end') + 'Offset'];
  9375. const isAfterNode = isElement$6(container) && offset === container.childNodes.length;
  9376. const nonEmptyElementsMap = dom.schema.getNonEmptyElements();
  9377. directionLeft = start;
  9378. if (isCaretContainer$2(container)) {
  9379. return Optional.none();
  9380. }
  9381. if (isElement$6(container) && offset > container.childNodes.length - 1) {
  9382. directionLeft = false;
  9383. }
  9384. if (isDocument$1(container)) {
  9385. container = body;
  9386. offset = 0;
  9387. }
  9388. if (container === body) {
  9389. if (directionLeft) {
  9390. node = container.childNodes[offset > 0 ? offset - 1 : 0];
  9391. if (node) {
  9392. if (isCaretContainer$2(node)) {
  9393. return Optional.none();
  9394. }
  9395. if (nonEmptyElementsMap[node.nodeName] || isTable(node)) {
  9396. return Optional.none();
  9397. }
  9398. }
  9399. }
  9400. if (container.hasChildNodes()) {
  9401. offset = Math.min(!directionLeft && offset > 0 ? offset - 1 : offset, container.childNodes.length - 1);
  9402. container = container.childNodes[offset];
  9403. offset = isText$9(container) && isAfterNode ? container.data.length : 0;
  9404. if (!collapsed && container === body.lastChild && isTable(container)) {
  9405. return Optional.none();
  9406. }
  9407. if (hasContentEditableFalseParent(body, container) || isCaretContainer$2(container)) {
  9408. return Optional.none();
  9409. }
  9410. if (container.hasChildNodes() && isTable(container) === false) {
  9411. node = container;
  9412. const walker = new DomTreeWalker(container, body);
  9413. do {
  9414. if (isContentEditableFalse$b(node) || isCaretContainer$2(node)) {
  9415. normalized = false;
  9416. break;
  9417. }
  9418. if (isText$9(node) && node.nodeValue.length > 0) {
  9419. offset = directionLeft ? 0 : node.nodeValue.length;
  9420. container = node;
  9421. normalized = true;
  9422. break;
  9423. }
  9424. if (nonEmptyElementsMap[node.nodeName.toLowerCase()] && !isTableCell$2(node)) {
  9425. offset = dom.nodeIndex(node);
  9426. container = node.parentNode;
  9427. if (!directionLeft) {
  9428. offset++;
  9429. }
  9430. normalized = true;
  9431. break;
  9432. }
  9433. } while (node = directionLeft ? walker.next() : walker.prev());
  9434. }
  9435. }
  9436. }
  9437. if (collapsed) {
  9438. if (isText$9(container) && offset === 0) {
  9439. findTextNodeRelative(dom, isAfterNode, collapsed, true, container).each(pos => {
  9440. container = pos.container();
  9441. offset = pos.offset();
  9442. normalized = true;
  9443. });
  9444. }
  9445. if (isElement$6(container)) {
  9446. node = container.childNodes[offset];
  9447. if (!node) {
  9448. node = container.childNodes[offset - 1];
  9449. }
  9450. if (node && isBr$6(node) && !isPrevNode(node, 'A') && !hasBrBeforeAfter(dom, node, false) && !hasBrBeforeAfter(dom, node, true)) {
  9451. findTextNodeRelative(dom, isAfterNode, collapsed, true, node).each(pos => {
  9452. container = pos.container();
  9453. offset = pos.offset();
  9454. normalized = true;
  9455. });
  9456. }
  9457. }
  9458. }
  9459. if (directionLeft && !collapsed && isText$9(container) && offset === container.nodeValue.length) {
  9460. findTextNodeRelative(dom, isAfterNode, collapsed, false, container).each(pos => {
  9461. container = pos.container();
  9462. offset = pos.offset();
  9463. normalized = true;
  9464. });
  9465. }
  9466. return normalized ? Optional.some(CaretPosition(container, offset)) : Optional.none();
  9467. };
  9468. const normalize$2 = (dom, rng) => {
  9469. const collapsed = rng.collapsed, normRng = rng.cloneRange();
  9470. const startPos = CaretPosition.fromRangeStart(rng);
  9471. normalizeEndPoint(dom, collapsed, true, normRng).each(pos => {
  9472. if (!collapsed || !CaretPosition.isAbove(startPos, pos)) {
  9473. normRng.setStart(pos.container(), pos.offset());
  9474. }
  9475. });
  9476. if (!collapsed) {
  9477. normalizeEndPoint(dom, collapsed, false, normRng).each(pos => {
  9478. normRng.setEnd(pos.container(), pos.offset());
  9479. });
  9480. }
  9481. if (collapsed) {
  9482. normRng.collapse(true);
  9483. }
  9484. return isEq$4(rng, normRng) ? Optional.none() : Optional.some(normRng);
  9485. };
  9486. const splitText = (node, offset) => {
  9487. return node.splitText(offset);
  9488. };
  9489. const split = rng => {
  9490. let startContainer = rng.startContainer, startOffset = rng.startOffset, endContainer = rng.endContainer, endOffset = rng.endOffset;
  9491. if (startContainer === endContainer && isText$9(startContainer)) {
  9492. if (startOffset > 0 && startOffset < startContainer.nodeValue.length) {
  9493. endContainer = splitText(startContainer, startOffset);
  9494. startContainer = endContainer.previousSibling;
  9495. if (endOffset > startOffset) {
  9496. endOffset = endOffset - startOffset;
  9497. startContainer = endContainer = splitText(endContainer, endOffset).previousSibling;
  9498. endOffset = endContainer.nodeValue.length;
  9499. startOffset = 0;
  9500. } else {
  9501. endOffset = 0;
  9502. }
  9503. }
  9504. } else {
  9505. if (isText$9(startContainer) && startOffset > 0 && startOffset < startContainer.nodeValue.length) {
  9506. startContainer = splitText(startContainer, startOffset);
  9507. startOffset = 0;
  9508. }
  9509. if (isText$9(endContainer) && endOffset > 0 && endOffset < endContainer.nodeValue.length) {
  9510. endContainer = splitText(endContainer, endOffset).previousSibling;
  9511. endOffset = endContainer.nodeValue.length;
  9512. }
  9513. }
  9514. return {
  9515. startContainer,
  9516. startOffset,
  9517. endContainer,
  9518. endOffset
  9519. };
  9520. };
  9521. const RangeUtils = dom => {
  9522. const walk = (rng, callback) => {
  9523. return walk$3(dom, rng, callback);
  9524. };
  9525. const split$1 = split;
  9526. const normalize = rng => {
  9527. return normalize$2(dom, rng).fold(never, normalizedRng => {
  9528. rng.setStart(normalizedRng.startContainer, normalizedRng.startOffset);
  9529. rng.setEnd(normalizedRng.endContainer, normalizedRng.endOffset);
  9530. return true;
  9531. });
  9532. };
  9533. return {
  9534. walk,
  9535. split: split$1,
  9536. normalize
  9537. };
  9538. };
  9539. RangeUtils.compareRanges = isEq$4;
  9540. RangeUtils.getCaretRangeFromPoint = fromPoint;
  9541. RangeUtils.getSelectedNode = getSelectedNode;
  9542. RangeUtils.getNode = getNode$1;
  9543. const Dimension = (name, getOffset) => {
  9544. const set = (element, h) => {
  9545. if (!isNumber(h) && !h.match(/^[0-9]+$/)) {
  9546. throw new Error(name + '.set accepts only positive integer values. Value was ' + h);
  9547. }
  9548. const dom = element.dom;
  9549. if (isSupported$1(dom)) {
  9550. dom.style[name] = h + 'px';
  9551. }
  9552. };
  9553. const get = element => {
  9554. const r = getOffset(element);
  9555. if (r <= 0 || r === null) {
  9556. const css = get$7(element, name);
  9557. return parseFloat(css) || 0;
  9558. }
  9559. return r;
  9560. };
  9561. const getOuter = get;
  9562. const aggregate = (element, properties) => foldl(properties, (acc, property) => {
  9563. const val = get$7(element, property);
  9564. const value = val === undefined ? 0 : parseInt(val, 10);
  9565. return isNaN(value) ? acc : acc + value;
  9566. }, 0);
  9567. const max = (element, value, properties) => {
  9568. const cumulativeInclusions = aggregate(element, properties);
  9569. const absoluteMax = value > cumulativeInclusions ? value - cumulativeInclusions : 0;
  9570. return absoluteMax;
  9571. };
  9572. return {
  9573. set,
  9574. get,
  9575. getOuter,
  9576. aggregate,
  9577. max
  9578. };
  9579. };
  9580. const api = Dimension('height', element => {
  9581. const dom = element.dom;
  9582. return inBody(element) ? dom.getBoundingClientRect().height : dom.offsetHeight;
  9583. });
  9584. const get$2 = element => api.get(element);
  9585. const getDocument = () => SugarElement.fromDom(document);
  9586. const walkUp = (navigation, doc) => {
  9587. const frame = navigation.view(doc);
  9588. return frame.fold(constant([]), f => {
  9589. const parent = navigation.owner(f);
  9590. const rest = walkUp(navigation, parent);
  9591. return [f].concat(rest);
  9592. });
  9593. };
  9594. const pathTo = (element, navigation) => {
  9595. const d = navigation.owner(element);
  9596. return walkUp(navigation, d);
  9597. };
  9598. const view = doc => {
  9599. var _a;
  9600. const element = doc.dom === document ? Optional.none() : Optional.from((_a = doc.dom.defaultView) === null || _a === void 0 ? void 0 : _a.frameElement);
  9601. return element.map(SugarElement.fromDom);
  9602. };
  9603. const owner = element => documentOrOwner(element);
  9604. var Navigation = /*#__PURE__*/Object.freeze({
  9605. __proto__: null,
  9606. view: view,
  9607. owner: owner
  9608. });
  9609. const find = element => {
  9610. const doc = getDocument();
  9611. const scroll = get$5(doc);
  9612. const frames = pathTo(element, Navigation);
  9613. const offset = viewport(element);
  9614. const r = foldr(frames, (b, a) => {
  9615. const loc = viewport(a);
  9616. return {
  9617. left: b.left + loc.left,
  9618. top: b.top + loc.top
  9619. };
  9620. }, {
  9621. left: 0,
  9622. top: 0
  9623. });
  9624. return SugarPosition(r.left + offset.left + scroll.left, r.top + offset.top + scroll.top);
  9625. };
  9626. const excludeFromDescend = element => name(element) === 'textarea';
  9627. const fireScrollIntoViewEvent = (editor, data) => {
  9628. const scrollEvent = editor.dispatch('ScrollIntoView', data);
  9629. return scrollEvent.isDefaultPrevented();
  9630. };
  9631. const fireAfterScrollIntoViewEvent = (editor, data) => {
  9632. editor.dispatch('AfterScrollIntoView', data);
  9633. };
  9634. const descend = (element, offset) => {
  9635. const children$1 = children(element);
  9636. if (children$1.length === 0 || excludeFromDescend(element)) {
  9637. return {
  9638. element,
  9639. offset
  9640. };
  9641. } else if (offset < children$1.length && !excludeFromDescend(children$1[offset])) {
  9642. return {
  9643. element: children$1[offset],
  9644. offset: 0
  9645. };
  9646. } else {
  9647. const last = children$1[children$1.length - 1];
  9648. if (excludeFromDescend(last)) {
  9649. return {
  9650. element,
  9651. offset
  9652. };
  9653. } else {
  9654. if (name(last) === 'img') {
  9655. return {
  9656. element: last,
  9657. offset: 1
  9658. };
  9659. } else if (isText$a(last)) {
  9660. return {
  9661. element: last,
  9662. offset: get$3(last).length
  9663. };
  9664. } else {
  9665. return {
  9666. element: last,
  9667. offset: children(last).length
  9668. };
  9669. }
  9670. }
  9671. }
  9672. };
  9673. const markerInfo = (element, cleanupFun) => {
  9674. const pos = absolute(element);
  9675. const height = get$2(element);
  9676. return {
  9677. element,
  9678. bottom: pos.top + height,
  9679. height,
  9680. pos,
  9681. cleanup: cleanupFun
  9682. };
  9683. };
  9684. const createMarker$1 = (element, offset) => {
  9685. const startPoint = descend(element, offset);
  9686. const span = SugarElement.fromHtml('<span data-mce-bogus="all" style="display: inline-block;">' + ZWSP$1 + '</span>');
  9687. before$3(startPoint.element, span);
  9688. return markerInfo(span, () => remove$6(span));
  9689. };
  9690. const elementMarker = element => markerInfo(SugarElement.fromDom(element), noop);
  9691. const withMarker = (editor, f, rng, alignToTop) => {
  9692. preserveWith(editor, (_s, _e) => applyWithMarker(editor, f, rng, alignToTop), rng);
  9693. };
  9694. const withScrollEvents = (editor, doc, f, marker, alignToTop) => {
  9695. const data = {
  9696. elm: marker.element.dom,
  9697. alignToTop
  9698. };
  9699. if (fireScrollIntoViewEvent(editor, data)) {
  9700. return;
  9701. }
  9702. const scrollTop = get$5(doc).top;
  9703. f(doc, scrollTop, marker, alignToTop);
  9704. fireAfterScrollIntoViewEvent(editor, data);
  9705. };
  9706. const applyWithMarker = (editor, f, rng, alignToTop) => {
  9707. const body = SugarElement.fromDom(editor.getBody());
  9708. const doc = SugarElement.fromDom(editor.getDoc());
  9709. reflow(body);
  9710. const marker = createMarker$1(SugarElement.fromDom(rng.startContainer), rng.startOffset);
  9711. withScrollEvents(editor, doc, f, marker, alignToTop);
  9712. marker.cleanup();
  9713. };
  9714. const withElement = (editor, element, f, alignToTop) => {
  9715. const doc = SugarElement.fromDom(editor.getDoc());
  9716. withScrollEvents(editor, doc, f, elementMarker(element), alignToTop);
  9717. };
  9718. const preserveWith = (editor, f, rng) => {
  9719. const startElement = rng.startContainer;
  9720. const startOffset = rng.startOffset;
  9721. const endElement = rng.endContainer;
  9722. const endOffset = rng.endOffset;
  9723. f(SugarElement.fromDom(startElement), SugarElement.fromDom(endElement));
  9724. const newRng = editor.dom.createRng();
  9725. newRng.setStart(startElement, startOffset);
  9726. newRng.setEnd(endElement, endOffset);
  9727. editor.selection.setRng(rng);
  9728. };
  9729. const scrollToMarker = (marker, viewHeight, alignToTop, doc) => {
  9730. const pos = marker.pos;
  9731. if (alignToTop) {
  9732. to(pos.left, pos.top, doc);
  9733. } else {
  9734. const y = pos.top - viewHeight + marker.height;
  9735. to(pos.left, y, doc);
  9736. }
  9737. };
  9738. const intoWindowIfNeeded = (doc, scrollTop, viewHeight, marker, alignToTop) => {
  9739. const viewportBottom = viewHeight + scrollTop;
  9740. const markerTop = marker.pos.top;
  9741. const markerBottom = marker.bottom;
  9742. const largerThanViewport = markerBottom - markerTop >= viewHeight;
  9743. if (markerTop < scrollTop) {
  9744. scrollToMarker(marker, viewHeight, alignToTop !== false, doc);
  9745. } else if (markerTop > viewportBottom) {
  9746. const align = largerThanViewport ? alignToTop !== false : alignToTop === true;
  9747. scrollToMarker(marker, viewHeight, align, doc);
  9748. } else if (markerBottom > viewportBottom && !largerThanViewport) {
  9749. scrollToMarker(marker, viewHeight, alignToTop === true, doc);
  9750. }
  9751. };
  9752. const intoWindow = (doc, scrollTop, marker, alignToTop) => {
  9753. const viewHeight = doc.dom.defaultView.innerHeight;
  9754. intoWindowIfNeeded(doc, scrollTop, viewHeight, marker, alignToTop);
  9755. };
  9756. const intoFrame = (doc, scrollTop, marker, alignToTop) => {
  9757. const frameViewHeight = doc.dom.defaultView.innerHeight;
  9758. intoWindowIfNeeded(doc, scrollTop, frameViewHeight, marker, alignToTop);
  9759. const op = find(marker.element);
  9760. const viewportBounds = getBounds(window);
  9761. if (op.top < viewportBounds.y) {
  9762. intoView(marker.element, alignToTop !== false);
  9763. } else if (op.top > viewportBounds.bottom) {
  9764. intoView(marker.element, alignToTop === true);
  9765. }
  9766. };
  9767. const rangeIntoWindow = (editor, rng, alignToTop) => withMarker(editor, intoWindow, rng, alignToTop);
  9768. const elementIntoWindow = (editor, element, alignToTop) => withElement(editor, element, intoWindow, alignToTop);
  9769. const rangeIntoFrame = (editor, rng, alignToTop) => withMarker(editor, intoFrame, rng, alignToTop);
  9770. const elementIntoFrame = (editor, element, alignToTop) => withElement(editor, element, intoFrame, alignToTop);
  9771. const scrollElementIntoView = (editor, element, alignToTop) => {
  9772. const scroller = editor.inline ? elementIntoWindow : elementIntoFrame;
  9773. scroller(editor, element, alignToTop);
  9774. };
  9775. const scrollRangeIntoView = (editor, rng, alignToTop) => {
  9776. const scroller = editor.inline ? rangeIntoWindow : rangeIntoFrame;
  9777. scroller(editor, rng, alignToTop);
  9778. };
  9779. const focus$1 = element => element.dom.focus();
  9780. const hasFocus$1 = element => {
  9781. const root = getRootNode(element).dom;
  9782. return element.dom === root.activeElement;
  9783. };
  9784. const active$1 = (root = getDocument()) => Optional.from(root.dom.activeElement).map(SugarElement.fromDom);
  9785. const search = element => active$1(getRootNode(element)).filter(e => element.dom.contains(e.dom));
  9786. const clamp$1 = (offset, element) => {
  9787. const max = isText$a(element) ? get$3(element).length : children(element).length + 1;
  9788. if (offset > max) {
  9789. return max;
  9790. } else if (offset < 0) {
  9791. return 0;
  9792. }
  9793. return offset;
  9794. };
  9795. const normalizeRng = rng => SimSelection.range(rng.start, clamp$1(rng.soffset, rng.start), rng.finish, clamp$1(rng.foffset, rng.finish));
  9796. const isOrContains = (root, elm) => !isRestrictedNode(elm.dom) && (contains(root, elm) || eq(root, elm));
  9797. const isRngInRoot = root => rng => isOrContains(root, rng.start) && isOrContains(root, rng.finish);
  9798. const shouldStore = editor => editor.inline;
  9799. const nativeRangeToSelectionRange = r => SimSelection.range(SugarElement.fromDom(r.startContainer), r.startOffset, SugarElement.fromDom(r.endContainer), r.endOffset);
  9800. const readRange = win => {
  9801. const selection = win.getSelection();
  9802. const rng = !selection || selection.rangeCount === 0 ? Optional.none() : Optional.from(selection.getRangeAt(0));
  9803. return rng.map(nativeRangeToSelectionRange);
  9804. };
  9805. const getBookmark = root => {
  9806. const win = defaultView(root);
  9807. return readRange(win.dom).filter(isRngInRoot(root));
  9808. };
  9809. const validate = (root, bookmark) => Optional.from(bookmark).filter(isRngInRoot(root)).map(normalizeRng);
  9810. const bookmarkToNativeRng = bookmark => {
  9811. const rng = document.createRange();
  9812. try {
  9813. rng.setStart(bookmark.start.dom, bookmark.soffset);
  9814. rng.setEnd(bookmark.finish.dom, bookmark.foffset);
  9815. return Optional.some(rng);
  9816. } catch (_) {
  9817. return Optional.none();
  9818. }
  9819. };
  9820. const store = editor => {
  9821. const newBookmark = shouldStore(editor) ? getBookmark(SugarElement.fromDom(editor.getBody())) : Optional.none();
  9822. editor.bookmark = newBookmark.isSome() ? newBookmark : editor.bookmark;
  9823. };
  9824. const getRng = editor => {
  9825. const bookmark = editor.bookmark ? editor.bookmark : Optional.none();
  9826. return bookmark.bind(x => validate(SugarElement.fromDom(editor.getBody()), x)).bind(bookmarkToNativeRng);
  9827. };
  9828. const restore = editor => {
  9829. getRng(editor).each(rng => editor.selection.setRng(rng));
  9830. };
  9831. const isEditorUIElement$1 = elm => {
  9832. const className = elm.className.toString();
  9833. return className.indexOf('tox-') !== -1 || className.indexOf('mce-') !== -1;
  9834. };
  9835. const FocusManager = { isEditorUIElement: isEditorUIElement$1 };
  9836. const wrappedSetTimeout = (callback, time) => {
  9837. if (!isNumber(time)) {
  9838. time = 0;
  9839. }
  9840. return setTimeout(callback, time);
  9841. };
  9842. const wrappedSetInterval = (callback, time) => {
  9843. if (!isNumber(time)) {
  9844. time = 0;
  9845. }
  9846. return setInterval(callback, time);
  9847. };
  9848. const Delay = {
  9849. setEditorTimeout: (editor, callback, time) => {
  9850. return wrappedSetTimeout(() => {
  9851. if (!editor.removed) {
  9852. callback();
  9853. }
  9854. }, time);
  9855. },
  9856. setEditorInterval: (editor, callback, time) => {
  9857. const timer = wrappedSetInterval(() => {
  9858. if (!editor.removed) {
  9859. callback();
  9860. } else {
  9861. clearInterval(timer);
  9862. }
  9863. }, time);
  9864. return timer;
  9865. }
  9866. };
  9867. const isManualNodeChange = e => {
  9868. return e.type === 'nodechange' && e.selectionChange;
  9869. };
  9870. const registerPageMouseUp = (editor, throttledStore) => {
  9871. const mouseUpPage = () => {
  9872. throttledStore.throttle();
  9873. };
  9874. DOMUtils.DOM.bind(document, 'mouseup', mouseUpPage);
  9875. editor.on('remove', () => {
  9876. DOMUtils.DOM.unbind(document, 'mouseup', mouseUpPage);
  9877. });
  9878. };
  9879. const registerMouseUp = (editor, throttledStore) => {
  9880. editor.on('mouseup touchend', _e => {
  9881. throttledStore.throttle();
  9882. });
  9883. };
  9884. const registerEditorEvents = (editor, throttledStore) => {
  9885. registerMouseUp(editor, throttledStore);
  9886. editor.on('keyup NodeChange AfterSetSelectionRange', e => {
  9887. if (!isManualNodeChange(e)) {
  9888. store(editor);
  9889. }
  9890. });
  9891. };
  9892. const register$6 = editor => {
  9893. const throttledStore = first$1(() => {
  9894. store(editor);
  9895. }, 0);
  9896. editor.on('init', () => {
  9897. if (editor.inline) {
  9898. registerPageMouseUp(editor, throttledStore);
  9899. }
  9900. registerEditorEvents(editor, throttledStore);
  9901. });
  9902. editor.on('remove', () => {
  9903. throttledStore.cancel();
  9904. });
  9905. };
  9906. let documentFocusInHandler;
  9907. const DOM$9 = DOMUtils.DOM;
  9908. const isEditorUIElement = elm => {
  9909. return FocusManager.isEditorUIElement(elm);
  9910. };
  9911. const isEditorContentAreaElement = elm => {
  9912. const classList = elm.classList;
  9913. if (classList !== undefined) {
  9914. return classList.contains('tox-edit-area') || classList.contains('tox-edit-area__iframe') || classList.contains('mce-content-body');
  9915. } else {
  9916. return false;
  9917. }
  9918. };
  9919. const isUIElement = (editor, elm) => {
  9920. const customSelector = getCustomUiSelector(editor);
  9921. const parent = DOM$9.getParent(elm, elm => {
  9922. return isEditorUIElement(elm) || (customSelector ? editor.dom.is(elm, customSelector) : false);
  9923. });
  9924. return parent !== null;
  9925. };
  9926. const getActiveElement = editor => {
  9927. try {
  9928. const root = getRootNode(SugarElement.fromDom(editor.getElement()));
  9929. return active$1(root).fold(() => document.body, x => x.dom);
  9930. } catch (ex) {
  9931. return document.body;
  9932. }
  9933. };
  9934. const registerEvents$1 = (editorManager, e) => {
  9935. const editor = e.editor;
  9936. register$6(editor);
  9937. editor.on('focusin', () => {
  9938. const focusedEditor = editorManager.focusedEditor;
  9939. if (focusedEditor !== editor) {
  9940. if (focusedEditor) {
  9941. focusedEditor.dispatch('blur', { focusedEditor: editor });
  9942. }
  9943. editorManager.setActive(editor);
  9944. editorManager.focusedEditor = editor;
  9945. editor.dispatch('focus', { blurredEditor: focusedEditor });
  9946. editor.focus(true);
  9947. }
  9948. });
  9949. editor.on('focusout', () => {
  9950. Delay.setEditorTimeout(editor, () => {
  9951. const focusedEditor = editorManager.focusedEditor;
  9952. if (!isUIElement(editor, getActiveElement(editor)) && focusedEditor === editor) {
  9953. editor.dispatch('blur', { focusedEditor: null });
  9954. editorManager.focusedEditor = null;
  9955. }
  9956. });
  9957. });
  9958. if (!documentFocusInHandler) {
  9959. documentFocusInHandler = e => {
  9960. const activeEditor = editorManager.activeEditor;
  9961. if (activeEditor) {
  9962. getOriginalEventTarget(e).each(target => {
  9963. if (target.ownerDocument === document) {
  9964. if (target !== document.body && !isUIElement(activeEditor, target) && editorManager.focusedEditor === activeEditor) {
  9965. activeEditor.dispatch('blur', { focusedEditor: null });
  9966. editorManager.focusedEditor = null;
  9967. }
  9968. }
  9969. });
  9970. }
  9971. };
  9972. DOM$9.bind(document, 'focusin', documentFocusInHandler);
  9973. }
  9974. };
  9975. const unregisterDocumentEvents = (editorManager, e) => {
  9976. if (editorManager.focusedEditor === e.editor) {
  9977. editorManager.focusedEditor = null;
  9978. }
  9979. if (!editorManager.activeEditor) {
  9980. DOM$9.unbind(document, 'focusin', documentFocusInHandler);
  9981. documentFocusInHandler = null;
  9982. }
  9983. };
  9984. const setup$v = editorManager => {
  9985. editorManager.on('AddEditor', curry(registerEvents$1, editorManager));
  9986. editorManager.on('RemoveEditor', curry(unregisterDocumentEvents, editorManager));
  9987. };
  9988. const getContentEditableHost = (editor, node) => editor.dom.getParent(node, node => editor.dom.getContentEditable(node) === 'true');
  9989. const getCollapsedNode = rng => rng.collapsed ? Optional.from(getNode$1(rng.startContainer, rng.startOffset)).map(SugarElement.fromDom) : Optional.none();
  9990. const getFocusInElement = (root, rng) => getCollapsedNode(rng).bind(node => {
  9991. if (isTableSection(node)) {
  9992. return Optional.some(node);
  9993. } else if (contains(root, node) === false) {
  9994. return Optional.some(root);
  9995. } else {
  9996. return Optional.none();
  9997. }
  9998. });
  9999. const normalizeSelection = (editor, rng) => {
  10000. getFocusInElement(SugarElement.fromDom(editor.getBody()), rng).bind(elm => {
  10001. return firstPositionIn(elm.dom);
  10002. }).fold(() => {
  10003. editor.selection.normalize();
  10004. return;
  10005. }, caretPos => editor.selection.setRng(caretPos.toRange()));
  10006. };
  10007. const focusBody = body => {
  10008. if (body.setActive) {
  10009. try {
  10010. body.setActive();
  10011. } catch (ex) {
  10012. body.focus();
  10013. }
  10014. } else {
  10015. body.focus();
  10016. }
  10017. };
  10018. const hasElementFocus = elm => hasFocus$1(elm) || search(elm).isSome();
  10019. const hasIframeFocus = editor => editor.iframeElement && hasFocus$1(SugarElement.fromDom(editor.iframeElement));
  10020. const hasInlineFocus = editor => {
  10021. const rawBody = editor.getBody();
  10022. return rawBody && hasElementFocus(SugarElement.fromDom(rawBody));
  10023. };
  10024. const hasUiFocus = editor => {
  10025. const dos = getRootNode(SugarElement.fromDom(editor.getElement()));
  10026. return active$1(dos).filter(elem => !isEditorContentAreaElement(elem.dom) && isUIElement(editor, elem.dom)).isSome();
  10027. };
  10028. const hasFocus = editor => editor.inline ? hasInlineFocus(editor) : hasIframeFocus(editor);
  10029. const hasEditorOrUiFocus = editor => hasFocus(editor) || hasUiFocus(editor);
  10030. const focusEditor = editor => {
  10031. const selection = editor.selection;
  10032. const body = editor.getBody();
  10033. let rng = selection.getRng();
  10034. editor.quirks.refreshContentEditable();
  10035. if (editor.bookmark !== undefined && hasFocus(editor) === false) {
  10036. getRng(editor).each(bookmarkRng => {
  10037. editor.selection.setRng(bookmarkRng);
  10038. rng = bookmarkRng;
  10039. });
  10040. }
  10041. const contentEditableHost = getContentEditableHost(editor, selection.getNode());
  10042. if (editor.dom.isChildOf(contentEditableHost, body)) {
  10043. focusBody(contentEditableHost);
  10044. normalizeSelection(editor, rng);
  10045. activateEditor(editor);
  10046. return;
  10047. }
  10048. if (!editor.inline) {
  10049. if (!Env.browser.isOpera()) {
  10050. focusBody(body);
  10051. }
  10052. editor.getWin().focus();
  10053. }
  10054. if (Env.browser.isFirefox() || editor.inline) {
  10055. focusBody(body);
  10056. normalizeSelection(editor, rng);
  10057. }
  10058. activateEditor(editor);
  10059. };
  10060. const activateEditor = editor => editor.editorManager.setActive(editor);
  10061. const focus = (editor, skipFocus) => {
  10062. if (editor.removed) {
  10063. return;
  10064. }
  10065. if (skipFocus) {
  10066. activateEditor(editor);
  10067. } else {
  10068. focusEditor(editor);
  10069. }
  10070. };
  10071. const getEndpointElement = (root, rng, start, real, resolve) => {
  10072. const container = start ? rng.startContainer : rng.endContainer;
  10073. const offset = start ? rng.startOffset : rng.endOffset;
  10074. 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);
  10075. };
  10076. const getStart = (root, rng, real) => getEndpointElement(root, rng, true, real, (elm, offset) => Math.min(childNodesCount(elm), offset));
  10077. const getEnd$1 = (root, rng, real) => getEndpointElement(root, rng, false, real, (elm, offset) => offset > 0 ? offset - 1 : offset);
  10078. const skipEmptyTextNodes = (node, forwards) => {
  10079. const orig = node;
  10080. while (node && isText$9(node) && node.length === 0) {
  10081. node = forwards ? node.nextSibling : node.previousSibling;
  10082. }
  10083. return node || orig;
  10084. };
  10085. const getNode = (root, rng) => {
  10086. let elm, startContainer, endContainer;
  10087. if (!rng) {
  10088. return root;
  10089. }
  10090. startContainer = rng.startContainer;
  10091. endContainer = rng.endContainer;
  10092. const startOffset = rng.startOffset;
  10093. const endOffset = rng.endOffset;
  10094. elm = rng.commonAncestorContainer;
  10095. if (!rng.collapsed) {
  10096. if (startContainer === endContainer) {
  10097. if (endOffset - startOffset < 2) {
  10098. if (startContainer.hasChildNodes()) {
  10099. elm = startContainer.childNodes[startOffset];
  10100. }
  10101. }
  10102. }
  10103. if (startContainer.nodeType === 3 && endContainer.nodeType === 3) {
  10104. if (startContainer.length === startOffset) {
  10105. startContainer = skipEmptyTextNodes(startContainer.nextSibling, true);
  10106. } else {
  10107. startContainer = startContainer.parentNode;
  10108. }
  10109. if (endOffset === 0) {
  10110. endContainer = skipEmptyTextNodes(endContainer.previousSibling, false);
  10111. } else {
  10112. endContainer = endContainer.parentNode;
  10113. }
  10114. if (startContainer && startContainer === endContainer) {
  10115. return startContainer;
  10116. }
  10117. }
  10118. }
  10119. if (elm && elm.nodeType === 3) {
  10120. return elm.parentNode;
  10121. }
  10122. return elm;
  10123. };
  10124. const getSelectedBlocks = (dom, rng, startElm, endElm) => {
  10125. let node;
  10126. const selectedBlocks = [];
  10127. const root = dom.getRoot();
  10128. startElm = dom.getParent(startElm || getStart(root, rng, rng.collapsed), dom.isBlock);
  10129. endElm = dom.getParent(endElm || getEnd$1(root, rng, rng.collapsed), dom.isBlock);
  10130. if (startElm && startElm !== root) {
  10131. selectedBlocks.push(startElm);
  10132. }
  10133. if (startElm && endElm && startElm !== endElm) {
  10134. node = startElm;
  10135. const walker = new DomTreeWalker(startElm, root);
  10136. while ((node = walker.next()) && node !== endElm) {
  10137. if (dom.isBlock(node)) {
  10138. selectedBlocks.push(node);
  10139. }
  10140. }
  10141. }
  10142. if (endElm && startElm !== endElm && endElm !== root) {
  10143. selectedBlocks.push(endElm);
  10144. }
  10145. return selectedBlocks;
  10146. };
  10147. const select = (dom, node, content) => Optional.from(node).map(node => {
  10148. const idx = dom.nodeIndex(node);
  10149. const rng = dom.createRng();
  10150. rng.setStart(node.parentNode, idx);
  10151. rng.setEnd(node.parentNode, idx + 1);
  10152. if (content) {
  10153. moveEndPoint(dom, rng, node, true);
  10154. moveEndPoint(dom, rng, node, false);
  10155. }
  10156. return rng;
  10157. });
  10158. const processRanges = (editor, ranges) => map$3(ranges, range => {
  10159. const evt = editor.dispatch('GetSelectionRange', { range });
  10160. return evt.range !== range ? evt.range : range;
  10161. });
  10162. const getEnd = element => name(element) === 'img' ? 1 : getOption(element).fold(() => children(element).length, v => v.length);
  10163. const isTextNodeWithCursorPosition = el => getOption(el).filter(text => text.trim().length !== 0 || text.indexOf(nbsp) > -1).isSome();
  10164. const elementsWithCursorPosition = [
  10165. 'img',
  10166. 'br'
  10167. ];
  10168. const isCursorPosition = elem => {
  10169. const hasCursorPosition = isTextNodeWithCursorPosition(elem);
  10170. return hasCursorPosition || contains$2(elementsWithCursorPosition, name(elem));
  10171. };
  10172. const first = element => descendant$1(element, isCursorPosition);
  10173. const last = element => descendantRtl(element, isCursorPosition);
  10174. const descendantRtl = (scope, predicate) => {
  10175. const descend = element => {
  10176. const children$1 = children(element);
  10177. for (let i = children$1.length - 1; i >= 0; i--) {
  10178. const child = children$1[i];
  10179. if (predicate(child)) {
  10180. return Optional.some(child);
  10181. }
  10182. const res = descend(child);
  10183. if (res.isSome()) {
  10184. return res;
  10185. }
  10186. }
  10187. return Optional.none();
  10188. };
  10189. return descend(scope);
  10190. };
  10191. const autocompleteSelector = '[data-mce-autocompleter]';
  10192. const create$9 = (editor, range) => {
  10193. if (findIn(SugarElement.fromDom(editor.getBody())).isNone()) {
  10194. const wrapper = SugarElement.fromHtml('<span data-mce-autocompleter="1" data-mce-bogus="1"></span>', editor.getDoc());
  10195. append$1(wrapper, SugarElement.fromDom(range.extractContents()));
  10196. range.insertNode(wrapper.dom);
  10197. parent(wrapper).each(elm => elm.dom.normalize());
  10198. last(wrapper).map(last => {
  10199. editor.selection.setCursorLocation(last.dom, getEnd(last));
  10200. });
  10201. }
  10202. };
  10203. const detect$1 = elm => closest$3(elm, autocompleteSelector);
  10204. const findIn = elm => descendant(elm, autocompleteSelector);
  10205. const remove$3 = (editor, elm) => findIn(elm).each(wrapper => {
  10206. const bookmark = editor.selection.getBookmark();
  10207. unwrap(wrapper);
  10208. editor.selection.moveToBookmark(bookmark);
  10209. });
  10210. const typeLookup = {
  10211. '#text': 3,
  10212. '#comment': 8,
  10213. '#cdata': 4,
  10214. '#pi': 7,
  10215. '#doctype': 10,
  10216. '#document-fragment': 11
  10217. };
  10218. const walk$2 = (node, root, prev) => {
  10219. const startName = prev ? 'lastChild' : 'firstChild';
  10220. const siblingName = prev ? 'prev' : 'next';
  10221. if (node[startName]) {
  10222. return node[startName];
  10223. }
  10224. if (node !== root) {
  10225. let sibling = node[siblingName];
  10226. if (sibling) {
  10227. return sibling;
  10228. }
  10229. for (let parent = node.parent; parent && parent !== root; parent = parent.parent) {
  10230. sibling = parent[siblingName];
  10231. if (sibling) {
  10232. return sibling;
  10233. }
  10234. }
  10235. }
  10236. };
  10237. const isEmptyTextNode = node => {
  10238. if (!isWhitespaceText(node.value)) {
  10239. return false;
  10240. }
  10241. const parentNode = node.parent;
  10242. if (parentNode && (parentNode.name !== 'span' || parentNode.attr('style')) && /^[ ]+$/.test(node.value)) {
  10243. return false;
  10244. }
  10245. return true;
  10246. };
  10247. const isNonEmptyElement = node => {
  10248. const isNamedAnchor = node.name === 'a' && !node.attr('href') && node.attr('id');
  10249. return node.attr('name') || node.attr('id') && !node.firstChild || node.attr('data-mce-bookmark') || isNamedAnchor;
  10250. };
  10251. class AstNode {
  10252. constructor(name, type) {
  10253. this.name = name;
  10254. this.type = type;
  10255. if (type === 1) {
  10256. this.attributes = [];
  10257. this.attributes.map = {};
  10258. }
  10259. }
  10260. static create(name, attrs) {
  10261. const node = new AstNode(name, typeLookup[name] || 1);
  10262. if (attrs) {
  10263. each$e(attrs, (value, attrName) => {
  10264. node.attr(attrName, value);
  10265. });
  10266. }
  10267. return node;
  10268. }
  10269. replace(node) {
  10270. const self = this;
  10271. if (node.parent) {
  10272. node.remove();
  10273. }
  10274. self.insert(node, self);
  10275. self.remove();
  10276. return self;
  10277. }
  10278. attr(name, value) {
  10279. const self = this;
  10280. let attrs;
  10281. if (typeof name !== 'string') {
  10282. if (name !== undefined && name !== null) {
  10283. each$e(name, (value, key) => {
  10284. self.attr(key, value);
  10285. });
  10286. }
  10287. return self;
  10288. }
  10289. if (attrs = self.attributes) {
  10290. if (value !== undefined) {
  10291. if (value === null) {
  10292. if (name in attrs.map) {
  10293. delete attrs.map[name];
  10294. let i = attrs.length;
  10295. while (i--) {
  10296. if (attrs[i].name === name) {
  10297. attrs.splice(i, 1);
  10298. return self;
  10299. }
  10300. }
  10301. }
  10302. return self;
  10303. }
  10304. if (name in attrs.map) {
  10305. let i = attrs.length;
  10306. while (i--) {
  10307. if (attrs[i].name === name) {
  10308. attrs[i].value = value;
  10309. break;
  10310. }
  10311. }
  10312. } else {
  10313. attrs.push({
  10314. name,
  10315. value
  10316. });
  10317. }
  10318. attrs.map[name] = value;
  10319. return self;
  10320. }
  10321. return attrs.map[name];
  10322. }
  10323. }
  10324. clone() {
  10325. const self = this;
  10326. const clone = new AstNode(self.name, self.type);
  10327. let selfAttrs;
  10328. if (selfAttrs = self.attributes) {
  10329. const cloneAttrs = [];
  10330. cloneAttrs.map = {};
  10331. for (let i = 0, l = selfAttrs.length; i < l; i++) {
  10332. const selfAttr = selfAttrs[i];
  10333. if (selfAttr.name !== 'id') {
  10334. cloneAttrs[cloneAttrs.length] = {
  10335. name: selfAttr.name,
  10336. value: selfAttr.value
  10337. };
  10338. cloneAttrs.map[selfAttr.name] = selfAttr.value;
  10339. }
  10340. }
  10341. clone.attributes = cloneAttrs;
  10342. }
  10343. clone.value = self.value;
  10344. return clone;
  10345. }
  10346. wrap(wrapper) {
  10347. const self = this;
  10348. self.parent.insert(wrapper, self);
  10349. wrapper.append(self);
  10350. return self;
  10351. }
  10352. unwrap() {
  10353. const self = this;
  10354. for (let node = self.firstChild; node;) {
  10355. const next = node.next;
  10356. self.insert(node, self, true);
  10357. node = next;
  10358. }
  10359. self.remove();
  10360. }
  10361. remove() {
  10362. const self = this, parent = self.parent, next = self.next, prev = self.prev;
  10363. if (parent) {
  10364. if (parent.firstChild === self) {
  10365. parent.firstChild = next;
  10366. if (next) {
  10367. next.prev = null;
  10368. }
  10369. } else {
  10370. prev.next = next;
  10371. }
  10372. if (parent.lastChild === self) {
  10373. parent.lastChild = prev;
  10374. if (prev) {
  10375. prev.next = null;
  10376. }
  10377. } else {
  10378. next.prev = prev;
  10379. }
  10380. self.parent = self.next = self.prev = null;
  10381. }
  10382. return self;
  10383. }
  10384. append(node) {
  10385. const self = this;
  10386. if (node.parent) {
  10387. node.remove();
  10388. }
  10389. const last = self.lastChild;
  10390. if (last) {
  10391. last.next = node;
  10392. node.prev = last;
  10393. self.lastChild = node;
  10394. } else {
  10395. self.lastChild = self.firstChild = node;
  10396. }
  10397. node.parent = self;
  10398. return node;
  10399. }
  10400. insert(node, refNode, before) {
  10401. if (node.parent) {
  10402. node.remove();
  10403. }
  10404. const parent = refNode.parent || this;
  10405. if (before) {
  10406. if (refNode === parent.firstChild) {
  10407. parent.firstChild = node;
  10408. } else {
  10409. refNode.prev.next = node;
  10410. }
  10411. node.prev = refNode.prev;
  10412. node.next = refNode;
  10413. refNode.prev = node;
  10414. } else {
  10415. if (refNode === parent.lastChild) {
  10416. parent.lastChild = node;
  10417. } else {
  10418. refNode.next.prev = node;
  10419. }
  10420. node.next = refNode.next;
  10421. node.prev = refNode;
  10422. refNode.next = node;
  10423. }
  10424. node.parent = parent;
  10425. return node;
  10426. }
  10427. getAll(name) {
  10428. const self = this;
  10429. const collection = [];
  10430. for (let node = self.firstChild; node; node = walk$2(node, self)) {
  10431. if (node.name === name) {
  10432. collection.push(node);
  10433. }
  10434. }
  10435. return collection;
  10436. }
  10437. children() {
  10438. const self = this;
  10439. const collection = [];
  10440. for (let node = self.firstChild; node; node = node.next) {
  10441. collection.push(node);
  10442. }
  10443. return collection;
  10444. }
  10445. empty() {
  10446. const self = this;
  10447. if (self.firstChild) {
  10448. const nodes = [];
  10449. for (let node = self.firstChild; node; node = walk$2(node, self)) {
  10450. nodes.push(node);
  10451. }
  10452. let i = nodes.length;
  10453. while (i--) {
  10454. const node = nodes[i];
  10455. node.parent = node.firstChild = node.lastChild = node.next = node.prev = null;
  10456. }
  10457. }
  10458. self.firstChild = self.lastChild = null;
  10459. return self;
  10460. }
  10461. isEmpty(elements, whitespace = {}, predicate) {
  10462. const self = this;
  10463. let node = self.firstChild;
  10464. if (isNonEmptyElement(self)) {
  10465. return false;
  10466. }
  10467. if (node) {
  10468. do {
  10469. if (node.type === 1) {
  10470. if (node.attr('data-mce-bogus')) {
  10471. continue;
  10472. }
  10473. if (elements[node.name]) {
  10474. return false;
  10475. }
  10476. if (isNonEmptyElement(node)) {
  10477. return false;
  10478. }
  10479. }
  10480. if (node.type === 8) {
  10481. return false;
  10482. }
  10483. if (node.type === 3 && !isEmptyTextNode(node)) {
  10484. return false;
  10485. }
  10486. if (node.type === 3 && node.parent && whitespace[node.parent.name] && isWhitespaceText(node.value)) {
  10487. return false;
  10488. }
  10489. if (predicate && predicate(node)) {
  10490. return false;
  10491. }
  10492. } while (node = walk$2(node, self));
  10493. }
  10494. return true;
  10495. }
  10496. walk(prev) {
  10497. return walk$2(this, null, prev);
  10498. }
  10499. }
  10500. const isConditionalComment = (html, startIndex) => /^\s*\[if [\w\W]+\]>.*<!\[endif\](--!?)?>/.test(html.substr(startIndex));
  10501. const findCommentEndIndex = (html, isBogus, startIndex = 0) => {
  10502. const lcHtml = html.toLowerCase();
  10503. if (lcHtml.indexOf('[if ', startIndex) !== -1 && isConditionalComment(lcHtml, startIndex)) {
  10504. const endIfIndex = lcHtml.indexOf('[endif]', startIndex);
  10505. return lcHtml.indexOf('>', endIfIndex);
  10506. } else {
  10507. if (isBogus) {
  10508. const endIndex = lcHtml.indexOf('>', startIndex);
  10509. return endIndex !== -1 ? endIndex : lcHtml.length;
  10510. } else {
  10511. const endCommentRegexp = /--!?>/g;
  10512. endCommentRegexp.lastIndex = startIndex;
  10513. const match = endCommentRegexp.exec(html);
  10514. return match ? match.index + match[0].length : lcHtml.length;
  10515. }
  10516. }
  10517. };
  10518. const findMatchingEndTagIndex = (schema, html, startIndex) => {
  10519. const startTagRegExp = /<([!?\/])?([A-Za-z0-9\-_:.]+)/g;
  10520. const endTagRegExp = /(?:\s(?:[^'">]+(?:"[^"]*"|'[^']*'))*[^"'>]*(?:"[^">]*|'[^'>]*)?|\s*|\/)>/g;
  10521. const voidElements = schema.getVoidElements();
  10522. let count = 1, index = startIndex;
  10523. while (count !== 0) {
  10524. startTagRegExp.lastIndex = index;
  10525. while (true) {
  10526. const startMatch = startTagRegExp.exec(html);
  10527. if (startMatch === null) {
  10528. return index;
  10529. } else if (startMatch[1] === '!') {
  10530. if (startsWith(startMatch[2], '--')) {
  10531. index = findCommentEndIndex(html, false, startMatch.index + '!--'.length);
  10532. } else {
  10533. index = findCommentEndIndex(html, true, startMatch.index + 1);
  10534. }
  10535. break;
  10536. } else {
  10537. endTagRegExp.lastIndex = startTagRegExp.lastIndex;
  10538. const endMatch = endTagRegExp.exec(html);
  10539. if (isNull(endMatch) || endMatch.index !== startTagRegExp.lastIndex) {
  10540. continue;
  10541. }
  10542. if (startMatch[1] === '/') {
  10543. count -= 1;
  10544. } else if (!has$2(voidElements, startMatch[2])) {
  10545. count += 1;
  10546. }
  10547. index = startTagRegExp.lastIndex + endMatch[0].length;
  10548. break;
  10549. }
  10550. }
  10551. }
  10552. return index;
  10553. };
  10554. const trimHtml$1 = (tempAttrs, html) => {
  10555. const trimContentRegExp = new RegExp(['\\s?(' + tempAttrs.join('|') + ')="[^"]+"'].join('|'), 'gi');
  10556. return html.replace(trimContentRegExp, '');
  10557. };
  10558. const trimInternal = (serializer, html) => {
  10559. const bogusAllRegExp = /<(\w+) [^>]*data-mce-bogus="all"[^>]*>/g;
  10560. const schema = serializer.schema;
  10561. let content = trimHtml$1(serializer.getTempAttrs(), html);
  10562. const voidElements = schema.getVoidElements();
  10563. let matches;
  10564. while (matches = bogusAllRegExp.exec(content)) {
  10565. const index = bogusAllRegExp.lastIndex;
  10566. const matchLength = matches[0].length;
  10567. let endTagIndex;
  10568. if (voidElements[matches[1]]) {
  10569. endTagIndex = index;
  10570. } else {
  10571. endTagIndex = findMatchingEndTagIndex(schema, content, index);
  10572. }
  10573. content = content.substring(0, index - matchLength) + content.substring(endTagIndex);
  10574. bogusAllRegExp.lastIndex = index - matchLength;
  10575. }
  10576. return trim$1(content);
  10577. };
  10578. const trimExternal = trimInternal;
  10579. const trimEmptyContents = (editor, html) => {
  10580. const blockName = getForcedRootBlock(editor);
  10581. const emptyRegExp = new RegExp(`^(<${ blockName }[^>]*>(&nbsp;|&#160;|\\s|\u00a0|<br \\/>|)<\\/${ blockName }>[\r\n]*|<br \\/>[\r\n]*)$`);
  10582. return html.replace(emptyRegExp, '');
  10583. };
  10584. const getContentFromBody = (editor, args, body) => {
  10585. let content;
  10586. if (args.format === 'raw') {
  10587. content = Tools.trim(trimExternal(editor.serializer, body.innerHTML));
  10588. } else if (args.format === 'text') {
  10589. content = trim$1(body.innerText);
  10590. content = content === '\n' ? '' : content;
  10591. } else if (args.format === 'tree') {
  10592. content = editor.serializer.serialize(body, args);
  10593. } else {
  10594. content = trimEmptyContents(editor, editor.serializer.serialize(body, args));
  10595. }
  10596. const shouldTrim = args.format !== 'text' && !isWsPreserveElement(SugarElement.fromDom(body));
  10597. return shouldTrim && isString(content) ? Tools.trim(content) : content;
  10598. };
  10599. const getContentInternal = (editor, args) => Optional.from(editor.getBody()).fold(constant(args.format === 'tree' ? new AstNode('body', 11) : ''), body => getContentFromBody(editor, args, body));
  10600. const each$a = Tools.each;
  10601. const ElementUtils = dom => {
  10602. const compare = (node1, node2) => {
  10603. if (node1.nodeName !== node2.nodeName) {
  10604. return false;
  10605. }
  10606. const getAttribs = node => {
  10607. const attribs = {};
  10608. each$a(dom.getAttribs(node), attr => {
  10609. const name = attr.nodeName.toLowerCase();
  10610. if (name.indexOf('_') !== 0 && name !== 'style' && name.indexOf('data-') !== 0) {
  10611. attribs[name] = dom.getAttrib(node, name);
  10612. }
  10613. });
  10614. return attribs;
  10615. };
  10616. const compareObjects = (obj1, obj2) => {
  10617. let value, name;
  10618. for (name in obj1) {
  10619. if (has$2(obj1, name)) {
  10620. value = obj2[name];
  10621. if (typeof value === 'undefined') {
  10622. return false;
  10623. }
  10624. if (obj1[name] !== value) {
  10625. return false;
  10626. }
  10627. delete obj2[name];
  10628. }
  10629. }
  10630. for (name in obj2) {
  10631. if (has$2(obj2, name)) {
  10632. return false;
  10633. }
  10634. }
  10635. return true;
  10636. };
  10637. if (!compareObjects(getAttribs(node1), getAttribs(node2))) {
  10638. return false;
  10639. }
  10640. if (!compareObjects(dom.parseStyle(dom.getAttrib(node1, 'style')), dom.parseStyle(dom.getAttrib(node2, 'style')))) {
  10641. return false;
  10642. }
  10643. return !isBookmarkNode$1(node1) && !isBookmarkNode$1(node2);
  10644. };
  10645. return { compare };
  10646. };
  10647. const makeMap$1 = Tools.makeMap;
  10648. const Writer = settings => {
  10649. const html = [];
  10650. settings = settings || {};
  10651. const indent = settings.indent;
  10652. const indentBefore = makeMap$1(settings.indent_before || '');
  10653. const indentAfter = makeMap$1(settings.indent_after || '');
  10654. const encode = Entities.getEncodeFunc(settings.entity_encoding || 'raw', settings.entities);
  10655. const htmlOutput = settings.element_format !== 'xhtml';
  10656. return {
  10657. start: (name, attrs, empty) => {
  10658. let i, l, attr, value;
  10659. if (indent && indentBefore[name] && html.length > 0) {
  10660. value = html[html.length - 1];
  10661. if (value.length > 0 && value !== '\n') {
  10662. html.push('\n');
  10663. }
  10664. }
  10665. html.push('<', name);
  10666. if (attrs) {
  10667. for (i = 0, l = attrs.length; i < l; i++) {
  10668. attr = attrs[i];
  10669. html.push(' ', attr.name, '="', encode(attr.value, true), '"');
  10670. }
  10671. }
  10672. if (!empty || htmlOutput) {
  10673. html[html.length] = '>';
  10674. } else {
  10675. html[html.length] = ' />';
  10676. }
  10677. if (empty && indent && indentAfter[name] && html.length > 0) {
  10678. value = html[html.length - 1];
  10679. if (value.length > 0 && value !== '\n') {
  10680. html.push('\n');
  10681. }
  10682. }
  10683. },
  10684. end: name => {
  10685. let value;
  10686. html.push('</', name, '>');
  10687. if (indent && indentAfter[name] && html.length > 0) {
  10688. value = html[html.length - 1];
  10689. if (value.length > 0 && value !== '\n') {
  10690. html.push('\n');
  10691. }
  10692. }
  10693. },
  10694. text: (text, raw) => {
  10695. if (text.length > 0) {
  10696. html[html.length] = raw ? text : encode(text);
  10697. }
  10698. },
  10699. cdata: text => {
  10700. html.push('<![CDATA[', text, ']]>');
  10701. },
  10702. comment: text => {
  10703. html.push('<!--', text, '-->');
  10704. },
  10705. pi: (name, text) => {
  10706. if (text) {
  10707. html.push('<?', name, ' ', encode(text), '?>');
  10708. } else {
  10709. html.push('<?', name, '?>');
  10710. }
  10711. if (indent) {
  10712. html.push('\n');
  10713. }
  10714. },
  10715. doctype: text => {
  10716. html.push('<!DOCTYPE', text, '>', indent ? '\n' : '');
  10717. },
  10718. reset: () => {
  10719. html.length = 0;
  10720. },
  10721. getContent: () => {
  10722. return html.join('').replace(/\n$/, '');
  10723. }
  10724. };
  10725. };
  10726. const HtmlSerializer = (settings, schema = Schema()) => {
  10727. const writer = Writer(settings);
  10728. settings = settings || {};
  10729. settings.validate = 'validate' in settings ? settings.validate : true;
  10730. const serialize = node => {
  10731. const validate = settings.validate;
  10732. const handlers = {
  10733. 3: node => {
  10734. writer.text(node.value, node.raw);
  10735. },
  10736. 8: node => {
  10737. writer.comment(node.value);
  10738. },
  10739. 7: node => {
  10740. writer.pi(node.name, node.value);
  10741. },
  10742. 10: node => {
  10743. writer.doctype(node.value);
  10744. },
  10745. 4: node => {
  10746. writer.cdata(node.value);
  10747. },
  10748. 11: node => {
  10749. if (node = node.firstChild) {
  10750. do {
  10751. walk(node);
  10752. } while (node = node.next);
  10753. }
  10754. }
  10755. };
  10756. writer.reset();
  10757. const walk = node => {
  10758. const handler = handlers[node.type];
  10759. if (!handler) {
  10760. const name = node.name;
  10761. const isEmpty = name in schema.getVoidElements();
  10762. let attrs = node.attributes;
  10763. if (validate && attrs && attrs.length > 1) {
  10764. const sortedAttrs = [];
  10765. sortedAttrs.map = {};
  10766. const elementRule = schema.getElementRule(node.name);
  10767. if (elementRule) {
  10768. for (let i = 0, l = elementRule.attributesOrder.length; i < l; i++) {
  10769. const attrName = elementRule.attributesOrder[i];
  10770. if (attrName in attrs.map) {
  10771. const attrValue = attrs.map[attrName];
  10772. sortedAttrs.map[attrName] = attrValue;
  10773. sortedAttrs.push({
  10774. name: attrName,
  10775. value: attrValue
  10776. });
  10777. }
  10778. }
  10779. for (let i = 0, l = attrs.length; i < l; i++) {
  10780. const attrName = attrs[i].name;
  10781. if (!(attrName in sortedAttrs.map)) {
  10782. const attrValue = attrs.map[attrName];
  10783. sortedAttrs.map[attrName] = attrValue;
  10784. sortedAttrs.push({
  10785. name: attrName,
  10786. value: attrValue
  10787. });
  10788. }
  10789. }
  10790. attrs = sortedAttrs;
  10791. }
  10792. }
  10793. writer.start(name, attrs, isEmpty);
  10794. if (!isEmpty) {
  10795. let child = node.firstChild;
  10796. if (child) {
  10797. if ((name === 'pre' || name === 'textarea') && child.type === 3 && child.value[0] === '\n') {
  10798. writer.text('\n', true);
  10799. }
  10800. do {
  10801. walk(child);
  10802. } while (child = child.next);
  10803. }
  10804. writer.end(name);
  10805. }
  10806. } else {
  10807. handler(node);
  10808. }
  10809. };
  10810. if (node.type === 1 && !settings.inner) {
  10811. walk(node);
  10812. } else if (node.type === 3) {
  10813. handlers[3](node);
  10814. } else {
  10815. handlers[11](node);
  10816. }
  10817. return writer.getContent();
  10818. };
  10819. return { serialize };
  10820. };
  10821. const nonInheritableStyles = new Set();
  10822. (() => {
  10823. const nonInheritableStylesArr = [
  10824. 'margin',
  10825. 'margin-left',
  10826. 'margin-right',
  10827. 'margin-top',
  10828. 'margin-bottom',
  10829. 'padding',
  10830. 'padding-left',
  10831. 'padding-right',
  10832. 'padding-top',
  10833. 'padding-bottom',
  10834. 'border',
  10835. 'border-width',
  10836. 'border-style',
  10837. 'border-color',
  10838. 'background',
  10839. 'background-attachment',
  10840. 'background-clip',
  10841. 'background-color',
  10842. 'background-image',
  10843. 'background-origin',
  10844. 'background-position',
  10845. 'background-repeat',
  10846. 'background-size',
  10847. 'float',
  10848. 'position',
  10849. 'left',
  10850. 'right',
  10851. 'top',
  10852. 'bottom',
  10853. 'z-index',
  10854. 'display',
  10855. 'transform',
  10856. 'width',
  10857. 'max-width',
  10858. 'min-width',
  10859. 'height',
  10860. 'max-height',
  10861. 'min-height',
  10862. 'overflow',
  10863. 'overflow-x',
  10864. 'overflow-y',
  10865. 'text-overflow',
  10866. 'vertical-align',
  10867. 'transition',
  10868. 'transition-delay',
  10869. 'transition-duration',
  10870. 'transition-property',
  10871. 'transition-timing-function'
  10872. ];
  10873. each$f(nonInheritableStylesArr, style => {
  10874. nonInheritableStyles.add(style);
  10875. });
  10876. })();
  10877. const shorthandStyleProps = [
  10878. 'font',
  10879. 'text-decoration',
  10880. 'text-emphasis'
  10881. ];
  10882. const getStyleProps = (dom, node) => keys(dom.parseStyle(dom.getAttrib(node, 'style')));
  10883. const isNonInheritableStyle = style => nonInheritableStyles.has(style);
  10884. const hasInheritableStyles = (dom, node) => forall(getStyleProps(dom, node), style => !isNonInheritableStyle(style));
  10885. const getLonghandStyleProps = styles => filter$6(styles, style => exists(shorthandStyleProps, prop => startsWith(style, prop)));
  10886. const hasStyleConflict = (dom, node, parentNode) => {
  10887. const nodeStyleProps = getStyleProps(dom, node);
  10888. const parentNodeStyleProps = getStyleProps(dom, parentNode);
  10889. const valueMismatch = prop => {
  10890. var _a, _b;
  10891. const nodeValue = (_a = dom.getStyle(node, prop)) !== null && _a !== void 0 ? _a : '';
  10892. const parentValue = (_b = dom.getStyle(parentNode, prop)) !== null && _b !== void 0 ? _b : '';
  10893. return isNotEmpty(nodeValue) && isNotEmpty(parentValue) && nodeValue !== parentValue;
  10894. };
  10895. return exists(nodeStyleProps, nodeStyleProp => {
  10896. const propExists = props => exists(props, prop => prop === nodeStyleProp);
  10897. if (!propExists(parentNodeStyleProps) && propExists(shorthandStyleProps)) {
  10898. const longhandProps = getLonghandStyleProps(parentNodeStyleProps);
  10899. return exists(longhandProps, valueMismatch);
  10900. } else {
  10901. return valueMismatch(nodeStyleProp);
  10902. }
  10903. });
  10904. };
  10905. const isChar = (forward, predicate, pos) => Optional.from(pos.container()).filter(isText$9).exists(text => {
  10906. const delta = forward ? 0 : -1;
  10907. return predicate(text.data.charAt(pos.offset() + delta));
  10908. });
  10909. const isBeforeSpace = curry(isChar, true, isWhiteSpace);
  10910. const isAfterSpace = curry(isChar, false, isWhiteSpace);
  10911. const isEmptyText = pos => {
  10912. const container = pos.container();
  10913. return isText$9(container) && (container.data.length === 0 || isZwsp(container.data) && BookmarkManager.isBookmarkNode(container.parentNode));
  10914. };
  10915. const matchesElementPosition = (before, predicate) => pos => Optional.from(getChildNodeAtRelativeOffset(before ? 0 : -1, pos)).filter(predicate).isSome();
  10916. const isImageBlock = node => isImg(node) && get$7(SugarElement.fromDom(node), 'display') === 'block';
  10917. const isCefNode = node => isContentEditableFalse$b(node) && !isBogusAll$1(node);
  10918. const isBeforeImageBlock = matchesElementPosition(true, isImageBlock);
  10919. const isAfterImageBlock = matchesElementPosition(false, isImageBlock);
  10920. const isBeforeMedia = matchesElementPosition(true, isMedia$2);
  10921. const isAfterMedia = matchesElementPosition(false, isMedia$2);
  10922. const isBeforeTable = matchesElementPosition(true, isTable$3);
  10923. const isAfterTable = matchesElementPosition(false, isTable$3);
  10924. const isBeforeContentEditableFalse = matchesElementPosition(true, isCefNode);
  10925. const isAfterContentEditableFalse = matchesElementPosition(false, isCefNode);
  10926. const getLastChildren = elm => {
  10927. const children = [];
  10928. let rawNode = elm.dom;
  10929. while (rawNode) {
  10930. children.push(SugarElement.fromDom(rawNode));
  10931. rawNode = rawNode.lastChild;
  10932. }
  10933. return children;
  10934. };
  10935. const removeTrailingBr = elm => {
  10936. const allBrs = descendants(elm, 'br');
  10937. const brs = filter$6(getLastChildren(elm).slice(-1), isBr$5);
  10938. if (allBrs.length === brs.length) {
  10939. each$f(brs, remove$6);
  10940. }
  10941. };
  10942. const fillWithPaddingBr = elm => {
  10943. empty(elm);
  10944. append$1(elm, SugarElement.fromHtml('<br data-mce-bogus="1">'));
  10945. };
  10946. const trimBlockTrailingBr = elm => {
  10947. lastChild(elm).each(lastChild => {
  10948. prevSibling(lastChild).each(lastChildPrevSibling => {
  10949. if (isBlock$2(elm) && isBr$5(lastChild) && isBlock$2(lastChildPrevSibling)) {
  10950. remove$6(lastChild);
  10951. }
  10952. });
  10953. });
  10954. };
  10955. const dropLast = xs => xs.slice(0, -1);
  10956. const parentsUntil = (start, root, predicate) => {
  10957. if (contains(root, start)) {
  10958. return dropLast(parents$1(start, elm => {
  10959. return predicate(elm) || eq(elm, root);
  10960. }));
  10961. } else {
  10962. return [];
  10963. }
  10964. };
  10965. const parents = (start, root) => parentsUntil(start, root, never);
  10966. const parentsAndSelf = (start, root) => [start].concat(parents(start, root));
  10967. const navigateIgnoreEmptyTextNodes = (forward, root, from) => navigateIgnore(forward, root, from, isEmptyText);
  10968. const getClosestBlock$1 = (root, pos) => find$2(parentsAndSelf(SugarElement.fromDom(pos.container()), root), isBlock$2);
  10969. 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()))));
  10970. 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());
  10971. const isAtStartOfBlock = curry(isAtBlockBoundary, false);
  10972. const isAtEndOfBlock = curry(isAtBlockBoundary, true);
  10973. const isBeforeBlock = curry(isAtBeforeAfterBlockBoundary, false);
  10974. const isAfterBlock = curry(isAtBeforeAfterBlockBoundary, true);
  10975. const isBr$1 = pos => getElementFromPosition(pos).exists(isBr$5);
  10976. const findBr = (forward, root, pos) => {
  10977. const parentBlocks = filter$6(parentsAndSelf(SugarElement.fromDom(pos.container()), root), isBlock$2);
  10978. const scope = head(parentBlocks).getOr(root);
  10979. return fromPosition(forward, scope.dom, pos).filter(isBr$1);
  10980. };
  10981. const isBeforeBr$1 = (root, pos) => getElementFromPosition(pos).exists(isBr$5) || findBr(true, root, pos).isSome();
  10982. const isAfterBr = (root, pos) => getElementFromPrevPosition(pos).exists(isBr$5) || findBr(false, root, pos).isSome();
  10983. const findPreviousBr = curry(findBr, false);
  10984. const findNextBr = curry(findBr, true);
  10985. const isInMiddleOfText = pos => CaretPosition.isTextPosition(pos) && !pos.isAtStart() && !pos.isAtEnd();
  10986. const getClosestBlock = (root, pos) => {
  10987. const parentBlocks = filter$6(parentsAndSelf(SugarElement.fromDom(pos.container()), root), isBlock$2);
  10988. return head(parentBlocks).getOr(root);
  10989. };
  10990. const hasSpaceBefore = (root, pos) => {
  10991. if (isInMiddleOfText(pos)) {
  10992. return isAfterSpace(pos);
  10993. } else {
  10994. return isAfterSpace(pos) || prevPosition(getClosestBlock(root, pos).dom, pos).exists(isAfterSpace);
  10995. }
  10996. };
  10997. const hasSpaceAfter = (root, pos) => {
  10998. if (isInMiddleOfText(pos)) {
  10999. return isBeforeSpace(pos);
  11000. } else {
  11001. return isBeforeSpace(pos) || nextPosition(getClosestBlock(root, pos).dom, pos).exists(isBeforeSpace);
  11002. }
  11003. };
  11004. const isPreValue = value => contains$2([
  11005. 'pre',
  11006. 'pre-wrap'
  11007. ], value);
  11008. const isInPre = pos => getElementFromPosition(pos).bind(elm => closest$4(elm, isElement$7)).exists(elm => isPreValue(get$7(elm, 'white-space')));
  11009. const isAtBeginningOfBody = (root, pos) => prevPosition(root.dom, pos).isNone();
  11010. const isAtEndOfBody = (root, pos) => nextPosition(root.dom, pos).isNone();
  11011. const isAtLineBoundary = (root, pos) => isAtBeginningOfBody(root, pos) || isAtEndOfBody(root, pos) || isAtStartOfBlock(root, pos) || isAtEndOfBlock(root, pos) || isAfterBr(root, pos) || isBeforeBr$1(root, pos);
  11012. const isCefBlock = node => isNonNullable(node) && isContentEditableFalse$b(node) && isBlockLike(node);
  11013. const isSiblingCefBlock = root => container => isCefBlock(new DomTreeWalker(container, root).next());
  11014. const isBeforeCefBlock = (root, pos) => {
  11015. const nextPos = nextPosition(root.dom, pos).getOr(pos);
  11016. const isNextCefBlock = isSiblingCefBlock(root.dom);
  11017. return pos.isAtEnd() && (isNextCefBlock(pos.container()) || isNextCefBlock(nextPos.container()));
  11018. };
  11019. const needsToHaveNbsp = (root, pos) => {
  11020. if (isInPre(pos)) {
  11021. return false;
  11022. } else {
  11023. return isAtLineBoundary(root, pos) || hasSpaceBefore(root, pos) || hasSpaceAfter(root, pos);
  11024. }
  11025. };
  11026. const needsToBeNbspLeft = (root, pos) => {
  11027. if (isInPre(pos)) {
  11028. return false;
  11029. } else {
  11030. return isAtStartOfBlock(root, pos) || isBeforeBlock(root, pos) || isAfterBr(root, pos) || hasSpaceBefore(root, pos);
  11031. }
  11032. };
  11033. const leanRight = pos => {
  11034. const container = pos.container();
  11035. const offset = pos.offset();
  11036. if (isText$9(container) && offset < container.data.length) {
  11037. return CaretPosition(container, offset + 1);
  11038. } else {
  11039. return pos;
  11040. }
  11041. };
  11042. const needsToBeNbspRight = (root, pos) => {
  11043. if (isInPre(pos)) {
  11044. return false;
  11045. } else {
  11046. return isAtEndOfBlock(root, pos) || isAfterBlock(root, pos) || isBeforeBr$1(root, pos) || hasSpaceAfter(root, pos) || isBeforeCefBlock(root, pos);
  11047. }
  11048. };
  11049. const needsToBeNbsp = (root, pos) => needsToBeNbspLeft(root, pos) || needsToBeNbspRight(root, leanRight(pos));
  11050. const isNbspAt = (text, offset) => isNbsp(text.charAt(offset));
  11051. const hasNbsp = pos => {
  11052. const container = pos.container();
  11053. return isText$9(container) && contains$1(container.data, nbsp);
  11054. };
  11055. const normalizeNbspMiddle = text => {
  11056. const chars = text.split('');
  11057. return map$3(chars, (chr, i) => {
  11058. if (isNbsp(chr) && i > 0 && i < chars.length - 1 && isContent(chars[i - 1]) && isContent(chars[i + 1])) {
  11059. return ' ';
  11060. } else {
  11061. return chr;
  11062. }
  11063. }).join('');
  11064. };
  11065. const normalizeNbspAtStart = (root, node) => {
  11066. const text = node.data;
  11067. const firstPos = CaretPosition(node, 0);
  11068. if (isNbspAt(text, 0) && !needsToBeNbsp(root, firstPos)) {
  11069. node.data = ' ' + text.slice(1);
  11070. return true;
  11071. } else {
  11072. return false;
  11073. }
  11074. };
  11075. const normalizeNbspInMiddleOfTextNode = node => {
  11076. const text = node.data;
  11077. const newText = normalizeNbspMiddle(text);
  11078. if (newText !== text) {
  11079. node.data = newText;
  11080. return true;
  11081. } else {
  11082. return false;
  11083. }
  11084. };
  11085. const normalizeNbspAtEnd = (root, node) => {
  11086. const text = node.data;
  11087. const lastPos = CaretPosition(node, text.length - 1);
  11088. if (isNbspAt(text, text.length - 1) && !needsToBeNbsp(root, lastPos)) {
  11089. node.data = text.slice(0, -1) + ' ';
  11090. return true;
  11091. } else {
  11092. return false;
  11093. }
  11094. };
  11095. const normalizeNbsps = (root, pos) => Optional.some(pos).filter(hasNbsp).bind(pos => {
  11096. const container = pos.container();
  11097. const normalized = normalizeNbspAtStart(root, container) || normalizeNbspInMiddleOfTextNode(container) || normalizeNbspAtEnd(root, container);
  11098. return normalized ? Optional.some(pos) : Optional.none();
  11099. });
  11100. const normalizeNbspsInEditor = editor => {
  11101. const root = SugarElement.fromDom(editor.getBody());
  11102. if (editor.selection.isCollapsed()) {
  11103. normalizeNbsps(root, CaretPosition.fromRangeStart(editor.selection.getRng())).each(pos => {
  11104. editor.selection.setRng(pos.toRange());
  11105. });
  11106. }
  11107. };
  11108. const normalize$1 = (node, offset, count) => {
  11109. if (count === 0) {
  11110. return;
  11111. }
  11112. const elm = SugarElement.fromDom(node);
  11113. const root = ancestor$3(elm, isBlock$2).getOr(elm);
  11114. const whitespace = node.data.slice(offset, offset + count);
  11115. const isEndOfContent = offset + count >= node.data.length && needsToBeNbspRight(root, CaretPosition(node, node.data.length));
  11116. const isStartOfContent = offset === 0 && needsToBeNbspLeft(root, CaretPosition(node, 0));
  11117. node.replaceData(offset, count, normalize$4(whitespace, 4, isStartOfContent, isEndOfContent));
  11118. };
  11119. const normalizeWhitespaceAfter = (node, offset) => {
  11120. const content = node.data.slice(offset);
  11121. const whitespaceCount = content.length - lTrim(content).length;
  11122. normalize$1(node, offset, whitespaceCount);
  11123. };
  11124. const normalizeWhitespaceBefore = (node, offset) => {
  11125. const content = node.data.slice(0, offset);
  11126. const whitespaceCount = content.length - rTrim(content).length;
  11127. normalize$1(node, offset - whitespaceCount, whitespaceCount);
  11128. };
  11129. const mergeTextNodes = (prevNode, nextNode, normalizeWhitespace, mergeToPrev = true) => {
  11130. const whitespaceOffset = rTrim(prevNode.data).length;
  11131. const newNode = mergeToPrev ? prevNode : nextNode;
  11132. const removeNode = mergeToPrev ? nextNode : prevNode;
  11133. if (mergeToPrev) {
  11134. newNode.appendData(removeNode.data);
  11135. } else {
  11136. newNode.insertData(0, removeNode.data);
  11137. }
  11138. remove$6(SugarElement.fromDom(removeNode));
  11139. if (normalizeWhitespace) {
  11140. normalizeWhitespaceAfter(newNode, whitespaceOffset);
  11141. }
  11142. return newNode;
  11143. };
  11144. const needsReposition = (pos, elm) => {
  11145. const container = pos.container();
  11146. const offset = pos.offset();
  11147. return CaretPosition.isTextPosition(pos) === false && container === elm.parentNode && offset > CaretPosition.before(elm).offset();
  11148. };
  11149. const reposition = (elm, pos) => needsReposition(pos, elm) ? CaretPosition(pos.container(), pos.offset() - 1) : pos;
  11150. const beforeOrStartOf = node => isText$9(node) ? CaretPosition(node, 0) : CaretPosition.before(node);
  11151. const afterOrEndOf = node => isText$9(node) ? CaretPosition(node, node.data.length) : CaretPosition.after(node);
  11152. const getPreviousSiblingCaretPosition = elm => {
  11153. if (isCaretCandidate$3(elm.previousSibling)) {
  11154. return Optional.some(afterOrEndOf(elm.previousSibling));
  11155. } else {
  11156. return elm.previousSibling ? lastPositionIn(elm.previousSibling) : Optional.none();
  11157. }
  11158. };
  11159. const getNextSiblingCaretPosition = elm => {
  11160. if (isCaretCandidate$3(elm.nextSibling)) {
  11161. return Optional.some(beforeOrStartOf(elm.nextSibling));
  11162. } else {
  11163. return elm.nextSibling ? firstPositionIn(elm.nextSibling) : Optional.none();
  11164. }
  11165. };
  11166. const findCaretPositionBackwardsFromElm = (rootElement, elm) => {
  11167. const startPosition = CaretPosition.before(elm.previousSibling ? elm.previousSibling : elm.parentNode);
  11168. return prevPosition(rootElement, startPosition).fold(() => nextPosition(rootElement, CaretPosition.after(elm)), Optional.some);
  11169. };
  11170. const findCaretPositionForwardsFromElm = (rootElement, elm) => nextPosition(rootElement, CaretPosition.after(elm)).fold(() => prevPosition(rootElement, CaretPosition.before(elm)), Optional.some);
  11171. const findCaretPositionBackwards = (rootElement, elm) => getPreviousSiblingCaretPosition(elm).orThunk(() => getNextSiblingCaretPosition(elm)).orThunk(() => findCaretPositionBackwardsFromElm(rootElement, elm));
  11172. const findCaretPositionForward = (rootElement, elm) => getNextSiblingCaretPosition(elm).orThunk(() => getPreviousSiblingCaretPosition(elm)).orThunk(() => findCaretPositionForwardsFromElm(rootElement, elm));
  11173. const findCaretPosition = (forward, rootElement, elm) => forward ? findCaretPositionForward(rootElement, elm) : findCaretPositionBackwards(rootElement, elm);
  11174. const findCaretPosOutsideElmAfterDelete = (forward, rootElement, elm) => findCaretPosition(forward, rootElement, elm).map(curry(reposition, elm));
  11175. const setSelection$1 = (editor, forward, pos) => {
  11176. pos.fold(() => {
  11177. editor.focus();
  11178. }, pos => {
  11179. editor.selection.setRng(pos.toRange(), forward);
  11180. });
  11181. };
  11182. const eqRawNode = rawNode => elm => elm.dom === rawNode;
  11183. const isBlock = (editor, elm) => elm && has$2(editor.schema.getBlockElements(), name(elm));
  11184. const paddEmptyBlock = elm => {
  11185. if (isEmpty$2(elm)) {
  11186. const br = SugarElement.fromHtml('<br data-mce-bogus="1">');
  11187. empty(elm);
  11188. append$1(elm, br);
  11189. return Optional.some(CaretPosition.before(br.dom));
  11190. } else {
  11191. return Optional.none();
  11192. }
  11193. };
  11194. const deleteNormalized = (elm, afterDeletePosOpt, normalizeWhitespace) => {
  11195. const prevTextOpt = prevSibling(elm).filter(isText$a);
  11196. const nextTextOpt = nextSibling(elm).filter(isText$a);
  11197. remove$6(elm);
  11198. return lift3(prevTextOpt, nextTextOpt, afterDeletePosOpt, (prev, next, pos) => {
  11199. const prevNode = prev.dom, nextNode = next.dom;
  11200. const offset = prevNode.data.length;
  11201. mergeTextNodes(prevNode, nextNode, normalizeWhitespace);
  11202. return pos.container() === nextNode ? CaretPosition(prevNode, offset) : pos;
  11203. }).orThunk(() => {
  11204. if (normalizeWhitespace) {
  11205. prevTextOpt.each(elm => normalizeWhitespaceBefore(elm.dom, elm.dom.length));
  11206. nextTextOpt.each(elm => normalizeWhitespaceAfter(elm.dom, 0));
  11207. }
  11208. return afterDeletePosOpt;
  11209. });
  11210. };
  11211. const isInlineElement = (editor, element) => has$2(editor.schema.getTextInlineElements(), name(element));
  11212. const deleteElement$2 = (editor, forward, elm, moveCaret = true) => {
  11213. const afterDeletePos = findCaretPosOutsideElmAfterDelete(forward, editor.getBody(), elm.dom);
  11214. const parentBlock = ancestor$3(elm, curry(isBlock, editor), eqRawNode(editor.getBody()));
  11215. const normalizedAfterDeletePos = deleteNormalized(elm, afterDeletePos, isInlineElement(editor, elm));
  11216. if (editor.dom.isEmpty(editor.getBody())) {
  11217. editor.setContent('');
  11218. editor.selection.setCursorLocation();
  11219. } else {
  11220. parentBlock.bind(paddEmptyBlock).fold(() => {
  11221. if (moveCaret) {
  11222. setSelection$1(editor, forward, normalizedAfterDeletePos);
  11223. }
  11224. }, paddPos => {
  11225. if (moveCaret) {
  11226. setSelection$1(editor, forward, Optional.some(paddPos));
  11227. }
  11228. });
  11229. }
  11230. };
  11231. const strongRtl = /[\u0591-\u07FF\uFB1D-\uFDFF\uFE70-\uFEFC]/;
  11232. const hasStrongRtl = text => strongRtl.test(text);
  11233. const isInlineTarget = (editor, elm) => is$1(SugarElement.fromDom(elm), getInlineBoundarySelector(editor));
  11234. const isRtl = element => DOMUtils.DOM.getStyle(element, 'direction', true) === 'rtl' || hasStrongRtl(element.textContent);
  11235. const findInlineParents = (isInlineTarget, rootNode, pos) => filter$6(DOMUtils.DOM.getParents(pos.container(), '*', rootNode), isInlineTarget);
  11236. const findRootInline = (isInlineTarget, rootNode, pos) => {
  11237. const parents = findInlineParents(isInlineTarget, rootNode, pos);
  11238. return Optional.from(parents[parents.length - 1]);
  11239. };
  11240. const hasSameParentBlock = (rootNode, node1, node2) => {
  11241. const block1 = getParentBlock$3(node1, rootNode);
  11242. const block2 = getParentBlock$3(node2, rootNode);
  11243. return block1 && block1 === block2;
  11244. };
  11245. const isAtZwsp = pos => isBeforeInline(pos) || isAfterInline(pos);
  11246. const normalizePosition = (forward, pos) => {
  11247. if (!pos) {
  11248. return pos;
  11249. }
  11250. const container = pos.container(), offset = pos.offset();
  11251. if (forward) {
  11252. if (isCaretContainerInline(container)) {
  11253. if (isText$9(container.nextSibling)) {
  11254. return CaretPosition(container.nextSibling, 0);
  11255. } else {
  11256. return CaretPosition.after(container);
  11257. }
  11258. } else {
  11259. return isBeforeInline(pos) ? CaretPosition(container, offset + 1) : pos;
  11260. }
  11261. } else {
  11262. if (isCaretContainerInline(container)) {
  11263. if (isText$9(container.previousSibling)) {
  11264. return CaretPosition(container.previousSibling, container.previousSibling.data.length);
  11265. } else {
  11266. return CaretPosition.before(container);
  11267. }
  11268. } else {
  11269. return isAfterInline(pos) ? CaretPosition(container, offset - 1) : pos;
  11270. }
  11271. }
  11272. };
  11273. const normalizeForwards = curry(normalizePosition, true);
  11274. const normalizeBackwards = curry(normalizePosition, false);
  11275. const execCommandIgnoreInputEvents = (editor, command) => {
  11276. const inputBlocker = e => e.stopImmediatePropagation();
  11277. editor.on('beforeinput input', inputBlocker, true);
  11278. editor.getDoc().execCommand(command);
  11279. editor.off('beforeinput input', inputBlocker);
  11280. };
  11281. const execDeleteCommand = editor => execCommandIgnoreInputEvents(editor, 'Delete');
  11282. const execForwardDeleteCommand = editor => execCommandIgnoreInputEvents(editor, 'ForwardDelete');
  11283. const isBeforeRoot = rootNode => elm => eq(rootNode, SugarElement.fromDom(elm.dom.parentNode));
  11284. const isTextBlockOrListItem = element => isTextBlock$2(element) || isListItem(element);
  11285. const getParentBlock$2 = (rootNode, elm) => {
  11286. if (contains(rootNode, elm)) {
  11287. return closest$4(elm, isTextBlockOrListItem, isBeforeRoot(rootNode));
  11288. } else {
  11289. return Optional.none();
  11290. }
  11291. };
  11292. const placeCaretInEmptyBody = editor => {
  11293. const body = editor.getBody();
  11294. const node = body.firstChild && editor.dom.isBlock(body.firstChild) ? body.firstChild : body;
  11295. editor.selection.setCursorLocation(node, 0);
  11296. };
  11297. const paddEmptyBody = editor => {
  11298. if (editor.dom.isEmpty(editor.getBody())) {
  11299. editor.setContent('');
  11300. placeCaretInEmptyBody(editor);
  11301. }
  11302. };
  11303. const willDeleteLastPositionInElement = (forward, fromPos, elm) => lift2(firstPositionIn(elm), lastPositionIn(elm), (firstPos, lastPos) => {
  11304. const normalizedFirstPos = normalizePosition(true, firstPos);
  11305. const normalizedLastPos = normalizePosition(false, lastPos);
  11306. const normalizedFromPos = normalizePosition(false, fromPos);
  11307. if (forward) {
  11308. return nextPosition(elm, normalizedFromPos).exists(nextPos => nextPos.isEqual(normalizedLastPos) && fromPos.isEqual(normalizedFirstPos));
  11309. } else {
  11310. return prevPosition(elm, normalizedFromPos).exists(prevPos => prevPos.isEqual(normalizedFirstPos) && fromPos.isEqual(normalizedLastPos));
  11311. }
  11312. }).getOr(true);
  11313. const freefallRtl = root => {
  11314. const child = isComment$1(root) ? prevSibling(root) : lastChild(root);
  11315. return child.bind(freefallRtl).orThunk(() => Optional.some(root));
  11316. };
  11317. const deleteRangeContents = (editor, rng, root, moveSelection = true) => {
  11318. rng.deleteContents();
  11319. const lastNode = freefallRtl(root).getOr(root);
  11320. const lastBlock = SugarElement.fromDom(editor.dom.getParent(lastNode.dom, editor.dom.isBlock));
  11321. if (isEmpty$2(lastBlock)) {
  11322. fillWithPaddingBr(lastBlock);
  11323. if (moveSelection) {
  11324. editor.selection.setCursorLocation(lastBlock.dom, 0);
  11325. }
  11326. }
  11327. if (!eq(root, lastBlock)) {
  11328. const additionalCleanupNodes = is$2(parent(lastBlock), root) ? [] : siblings(lastBlock);
  11329. each$f(additionalCleanupNodes.concat(children(root)), node => {
  11330. if (!eq(node, lastBlock) && !contains(node, lastBlock) && isEmpty$2(node)) {
  11331. remove$6(node);
  11332. }
  11333. });
  11334. }
  11335. };
  11336. const isRootFromElement = root => cur => eq(root, cur);
  11337. const getTableCells = table => descendants(table, 'td,th');
  11338. const getTableDetailsFromRange = (rng, isRoot) => {
  11339. const getTable = node => getClosestTable(SugarElement.fromDom(node), isRoot);
  11340. const startTable = getTable(rng.startContainer);
  11341. const endTable = getTable(rng.endContainer);
  11342. const isStartInTable = startTable.isSome();
  11343. const isEndInTable = endTable.isSome();
  11344. const isSameTable = lift2(startTable, endTable, eq).getOr(false);
  11345. const isMultiTable = !isSameTable && isStartInTable && isEndInTable;
  11346. return {
  11347. startTable,
  11348. endTable,
  11349. isStartInTable,
  11350. isEndInTable,
  11351. isSameTable,
  11352. isMultiTable
  11353. };
  11354. };
  11355. const tableCellRng = (start, end) => ({
  11356. start,
  11357. end
  11358. });
  11359. const tableSelection = (rng, table, cells) => ({
  11360. rng,
  11361. table,
  11362. cells
  11363. });
  11364. const deleteAction = Adt.generate([
  11365. {
  11366. singleCellTable: [
  11367. 'rng',
  11368. 'cell'
  11369. ]
  11370. },
  11371. { fullTable: ['table'] },
  11372. {
  11373. partialTable: [
  11374. 'cells',
  11375. 'outsideDetails'
  11376. ]
  11377. },
  11378. {
  11379. multiTable: [
  11380. 'startTableCells',
  11381. 'endTableCells',
  11382. 'betweenRng'
  11383. ]
  11384. }
  11385. ]);
  11386. const getClosestCell$1 = (container, isRoot) => closest$3(SugarElement.fromDom(container), 'td,th', isRoot);
  11387. const isExpandedCellRng = cellRng => !eq(cellRng.start, cellRng.end);
  11388. const getTableFromCellRng = (cellRng, isRoot) => getClosestTable(cellRng.start, isRoot).bind(startParentTable => getClosestTable(cellRng.end, isRoot).bind(endParentTable => someIf(eq(startParentTable, endParentTable), startParentTable)));
  11389. const isSingleCellTable = (cellRng, isRoot) => !isExpandedCellRng(cellRng) && getTableFromCellRng(cellRng, isRoot).exists(table => {
  11390. const rows = table.dom.rows;
  11391. return rows.length === 1 && rows[0].cells.length === 1;
  11392. });
  11393. const getCellRng = (rng, isRoot) => {
  11394. const startCell = getClosestCell$1(rng.startContainer, isRoot);
  11395. const endCell = getClosestCell$1(rng.endContainer, isRoot);
  11396. return lift2(startCell, endCell, tableCellRng);
  11397. };
  11398. const getCellRangeFromStartTable = isRoot => startCell => getClosestTable(startCell, isRoot).bind(table => last$3(getTableCells(table)).map(endCell => tableCellRng(startCell, endCell)));
  11399. const getCellRangeFromEndTable = isRoot => endCell => getClosestTable(endCell, isRoot).bind(table => head(getTableCells(table)).map(startCell => tableCellRng(startCell, endCell)));
  11400. const getTableSelectionFromCellRng = isRoot => cellRng => getTableFromCellRng(cellRng, isRoot).map(table => tableSelection(cellRng, table, getTableCells(table)));
  11401. const getTableSelections = (cellRng, selectionDetails, rng, isRoot) => {
  11402. if (rng.collapsed || !cellRng.forall(isExpandedCellRng)) {
  11403. return Optional.none();
  11404. } else if (selectionDetails.isSameTable) {
  11405. const sameTableSelection = cellRng.bind(getTableSelectionFromCellRng(isRoot));
  11406. return Optional.some({
  11407. start: sameTableSelection,
  11408. end: sameTableSelection
  11409. });
  11410. } else {
  11411. const startCell = getClosestCell$1(rng.startContainer, isRoot);
  11412. const endCell = getClosestCell$1(rng.endContainer, isRoot);
  11413. const startTableSelection = startCell.bind(getCellRangeFromStartTable(isRoot)).bind(getTableSelectionFromCellRng(isRoot));
  11414. const endTableSelection = endCell.bind(getCellRangeFromEndTable(isRoot)).bind(getTableSelectionFromCellRng(isRoot));
  11415. return Optional.some({
  11416. start: startTableSelection,
  11417. end: endTableSelection
  11418. });
  11419. }
  11420. };
  11421. const getCellIndex = (cells, cell) => findIndex$2(cells, x => eq(x, cell));
  11422. const getSelectedCells = tableSelection => lift2(getCellIndex(tableSelection.cells, tableSelection.rng.start), getCellIndex(tableSelection.cells, tableSelection.rng.end), (startIndex, endIndex) => tableSelection.cells.slice(startIndex, endIndex + 1));
  11423. const isSingleCellTableContentSelected = (optCellRng, rng, isRoot) => optCellRng.exists(cellRng => isSingleCellTable(cellRng, isRoot) && hasAllContentsSelected(cellRng.start, rng));
  11424. const unselectCells = (rng, selectionDetails) => {
  11425. const {startTable, endTable} = selectionDetails;
  11426. const otherContentRng = rng.cloneRange();
  11427. startTable.each(table => otherContentRng.setStartAfter(table.dom));
  11428. endTable.each(table => otherContentRng.setEndBefore(table.dom));
  11429. return otherContentRng;
  11430. };
  11431. const handleSingleTable = (cellRng, selectionDetails, rng, isRoot) => getTableSelections(cellRng, selectionDetails, rng, isRoot).bind(({start, end}) => start.or(end)).bind(tableSelection => {
  11432. const {isSameTable} = selectionDetails;
  11433. const selectedCells = getSelectedCells(tableSelection).getOr([]);
  11434. if (isSameTable && tableSelection.cells.length === selectedCells.length) {
  11435. return Optional.some(deleteAction.fullTable(tableSelection.table));
  11436. } else if (selectedCells.length > 0) {
  11437. if (isSameTable) {
  11438. return Optional.some(deleteAction.partialTable(selectedCells, Optional.none()));
  11439. } else {
  11440. const otherContentRng = unselectCells(rng, selectionDetails);
  11441. return Optional.some(deleteAction.partialTable(selectedCells, Optional.some({
  11442. ...selectionDetails,
  11443. rng: otherContentRng
  11444. })));
  11445. }
  11446. } else {
  11447. return Optional.none();
  11448. }
  11449. });
  11450. const handleMultiTable = (cellRng, selectionDetails, rng, isRoot) => getTableSelections(cellRng, selectionDetails, rng, isRoot).bind(({start, end}) => {
  11451. const startTableSelectedCells = start.bind(getSelectedCells).getOr([]);
  11452. const endTableSelectedCells = end.bind(getSelectedCells).getOr([]);
  11453. if (startTableSelectedCells.length > 0 && endTableSelectedCells.length > 0) {
  11454. const otherContentRng = unselectCells(rng, selectionDetails);
  11455. return Optional.some(deleteAction.multiTable(startTableSelectedCells, endTableSelectedCells, otherContentRng));
  11456. } else {
  11457. return Optional.none();
  11458. }
  11459. });
  11460. const getActionFromRange = (root, rng) => {
  11461. const isRoot = isRootFromElement(root);
  11462. const optCellRng = getCellRng(rng, isRoot);
  11463. const selectionDetails = getTableDetailsFromRange(rng, isRoot);
  11464. if (isSingleCellTableContentSelected(optCellRng, rng, isRoot)) {
  11465. return optCellRng.map(cellRng => deleteAction.singleCellTable(rng, cellRng.start));
  11466. } else if (selectionDetails.isMultiTable) {
  11467. return handleMultiTable(optCellRng, selectionDetails, rng, isRoot);
  11468. } else {
  11469. return handleSingleTable(optCellRng, selectionDetails, rng, isRoot);
  11470. }
  11471. };
  11472. const cleanCells = cells => each$f(cells, cell => {
  11473. remove$b(cell, 'contenteditable');
  11474. fillWithPaddingBr(cell);
  11475. });
  11476. const getOutsideBlock = (editor, container) => Optional.from(editor.dom.getParent(container, editor.dom.isBlock)).map(SugarElement.fromDom);
  11477. const handleEmptyBlock = (editor, startInTable, emptyBlock) => {
  11478. emptyBlock.each(block => {
  11479. if (startInTable) {
  11480. remove$6(block);
  11481. } else {
  11482. fillWithPaddingBr(block);
  11483. editor.selection.setCursorLocation(block.dom, 0);
  11484. }
  11485. });
  11486. };
  11487. const deleteContentInsideCell = (editor, cell, rng, isFirstCellInSelection) => {
  11488. const insideTableRng = rng.cloneRange();
  11489. if (isFirstCellInSelection) {
  11490. insideTableRng.setStart(rng.startContainer, rng.startOffset);
  11491. insideTableRng.setEndAfter(cell.dom.lastChild);
  11492. } else {
  11493. insideTableRng.setStartBefore(cell.dom.firstChild);
  11494. insideTableRng.setEnd(rng.endContainer, rng.endOffset);
  11495. }
  11496. deleteCellContents(editor, insideTableRng, cell, false).each(action => action());
  11497. };
  11498. const collapseAndRestoreCellSelection = editor => {
  11499. const selectedCells = getCellsFromEditor(editor);
  11500. const selectedNode = SugarElement.fromDom(editor.selection.getNode());
  11501. if (isTableCell$5(selectedNode.dom) && isEmpty$2(selectedNode)) {
  11502. editor.selection.setCursorLocation(selectedNode.dom, 0);
  11503. } else {
  11504. editor.selection.collapse(true);
  11505. }
  11506. if (selectedCells.length > 1 && exists(selectedCells, cell => eq(cell, selectedNode))) {
  11507. set$2(selectedNode, 'data-mce-selected', '1');
  11508. }
  11509. };
  11510. const emptySingleTableCells = (editor, cells, outsideDetails) => Optional.some(() => {
  11511. const editorRng = editor.selection.getRng();
  11512. const cellsToClean = outsideDetails.bind(({rng, isStartInTable}) => {
  11513. const outsideBlock = getOutsideBlock(editor, isStartInTable ? rng.endContainer : rng.startContainer);
  11514. rng.deleteContents();
  11515. handleEmptyBlock(editor, isStartInTable, outsideBlock.filter(isEmpty$2));
  11516. const endPointCell = isStartInTable ? cells[0] : cells[cells.length - 1];
  11517. deleteContentInsideCell(editor, endPointCell, editorRng, isStartInTable);
  11518. if (!isEmpty$2(endPointCell)) {
  11519. return Optional.some(isStartInTable ? cells.slice(1) : cells.slice(0, -1));
  11520. } else {
  11521. return Optional.none();
  11522. }
  11523. }).getOr(cells);
  11524. cleanCells(cellsToClean);
  11525. collapseAndRestoreCellSelection(editor);
  11526. });
  11527. const emptyMultiTableCells = (editor, startTableCells, endTableCells, betweenRng) => Optional.some(() => {
  11528. const rng = editor.selection.getRng();
  11529. const startCell = startTableCells[0];
  11530. const endCell = endTableCells[endTableCells.length - 1];
  11531. deleteContentInsideCell(editor, startCell, rng, true);
  11532. deleteContentInsideCell(editor, endCell, rng, false);
  11533. const startTableCellsToClean = isEmpty$2(startCell) ? startTableCells : startTableCells.slice(1);
  11534. const endTableCellsToClean = isEmpty$2(endCell) ? endTableCells : endTableCells.slice(0, -1);
  11535. cleanCells(startTableCellsToClean.concat(endTableCellsToClean));
  11536. betweenRng.deleteContents();
  11537. collapseAndRestoreCellSelection(editor);
  11538. });
  11539. const deleteCellContents = (editor, rng, cell, moveSelection = true) => Optional.some(() => {
  11540. deleteRangeContents(editor, rng, cell, moveSelection);
  11541. });
  11542. const deleteTableElement = (editor, table) => Optional.some(() => deleteElement$2(editor, false, table));
  11543. const deleteCellRange = (editor, rootElm, rng) => getActionFromRange(rootElm, rng).bind(action => action.fold(curry(deleteCellContents, editor), curry(deleteTableElement, editor), curry(emptySingleTableCells, editor), curry(emptyMultiTableCells, editor)));
  11544. const deleteCaptionRange = (editor, caption) => emptyElement(editor, caption);
  11545. const deleteTableRange = (editor, rootElm, rng, startElm) => getParentCaption(rootElm, startElm).fold(() => deleteCellRange(editor, rootElm, rng), caption => deleteCaptionRange(editor, caption));
  11546. const deleteRange$2 = (editor, startElm, selectedCells) => {
  11547. const rootNode = SugarElement.fromDom(editor.getBody());
  11548. const rng = editor.selection.getRng();
  11549. return selectedCells.length !== 0 ? emptySingleTableCells(editor, selectedCells, Optional.none()) : deleteTableRange(editor, rootNode, rng, startElm);
  11550. };
  11551. const getParentCell = (rootElm, elm) => find$2(parentsAndSelf(elm, rootElm), isTableCell$4);
  11552. const getParentCaption = (rootElm, elm) => find$2(parentsAndSelf(elm, rootElm), isTag('caption'));
  11553. 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)));
  11554. const emptyElement = (editor, elm) => Optional.some(() => {
  11555. fillWithPaddingBr(elm);
  11556. editor.selection.setCursorLocation(elm.dom, 0);
  11557. });
  11558. 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);
  11559. const emptyCaretCaption = (editor, elm) => emptyElement(editor, elm);
  11560. const validateCaretCaption = (rootElm, fromCaption, to) => getParentCaption(rootElm, SugarElement.fromDom(to.getNode())).fold(() => Optional.some(noop), toCaption => someIf(!eq(toCaption, fromCaption), noop));
  11561. 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));
  11562. const deleteCaretCells = (editor, forward, rootElm, startElm) => {
  11563. const from = CaretPosition.fromRangeStart(editor.selection.getRng());
  11564. return getParentCell(rootElm, startElm).bind(fromCell => isEmpty$2(fromCell) ? emptyElement(editor, fromCell) : deleteBetweenCells(editor, rootElm, forward, fromCell, from));
  11565. };
  11566. const deleteCaretCaption = (editor, forward, rootElm, fromCaption) => {
  11567. const from = CaretPosition.fromRangeStart(editor.selection.getRng());
  11568. return isEmpty$2(fromCaption) ? emptyElement(editor, fromCaption) : deleteCaretInsideCaption(editor, rootElm, forward, fromCaption, from);
  11569. };
  11570. const isNearTable = (forward, pos) => forward ? isBeforeTable(pos) : isAfterTable(pos);
  11571. const isBeforeOrAfterTable = (editor, forward) => {
  11572. const fromPos = CaretPosition.fromRangeStart(editor.selection.getRng());
  11573. return isNearTable(forward, fromPos) || fromPosition(forward, editor.getBody(), fromPos).exists(pos => isNearTable(forward, pos));
  11574. };
  11575. const deleteCaret$3 = (editor, forward, startElm) => {
  11576. const rootElm = SugarElement.fromDom(editor.getBody());
  11577. return getParentCaption(rootElm, startElm).fold(() => deleteCaretCells(editor, forward, rootElm, startElm).orThunk(() => someIf(isBeforeOrAfterTable(editor, forward), noop)), fromCaption => deleteCaretCaption(editor, forward, rootElm, fromCaption));
  11578. };
  11579. const backspaceDelete$9 = (editor, forward) => {
  11580. const startElm = SugarElement.fromDom(editor.selection.getStart(true));
  11581. const cells = getCellsFromEditor(editor);
  11582. return editor.selection.isCollapsed() && cells.length === 0 ? deleteCaret$3(editor, forward, startElm) : deleteRange$2(editor, startElm, cells);
  11583. };
  11584. const getContentEditableRoot$1 = (root, node) => {
  11585. while (node && node !== root) {
  11586. if (isContentEditableTrue$5(node) || isContentEditableFalse$b(node)) {
  11587. return node;
  11588. }
  11589. node = node.parentNode;
  11590. }
  11591. return null;
  11592. };
  11593. const traverse = (node, fn) => {
  11594. fn(node);
  11595. if (node.firstChild) {
  11596. traverse(node.firstChild, fn);
  11597. }
  11598. if (node.next) {
  11599. traverse(node.next, fn);
  11600. }
  11601. };
  11602. const matchNode$1 = (nodeFilters, attributeFilters, node, matches) => {
  11603. const name = node.name;
  11604. for (let ni = 0, nl = nodeFilters.length; ni < nl; ni++) {
  11605. const filter = nodeFilters[ni];
  11606. if (filter.name === name) {
  11607. const match = matches.nodes[name];
  11608. if (match) {
  11609. match.nodes.push(node);
  11610. } else {
  11611. matches.nodes[name] = {
  11612. filter,
  11613. nodes: [node]
  11614. };
  11615. }
  11616. }
  11617. }
  11618. if (node.attributes) {
  11619. for (let ai = 0, al = attributeFilters.length; ai < al; ai++) {
  11620. const filter = attributeFilters[ai];
  11621. const attrName = filter.name;
  11622. if (attrName in node.attributes.map) {
  11623. const match = matches.attributes[attrName];
  11624. if (match) {
  11625. match.nodes.push(node);
  11626. } else {
  11627. matches.attributes[attrName] = {
  11628. filter,
  11629. nodes: [node]
  11630. };
  11631. }
  11632. }
  11633. }
  11634. }
  11635. };
  11636. const findMatchingNodes = (nodeFilters, attributeFilters, node) => {
  11637. const matches = {
  11638. nodes: {},
  11639. attributes: {}
  11640. };
  11641. if (node.firstChild) {
  11642. traverse(node.firstChild, node => {
  11643. matchNode$1(nodeFilters, attributeFilters, node, matches);
  11644. });
  11645. }
  11646. return matches;
  11647. };
  11648. const runFilters = (matches, args) => {
  11649. const run = matchRecord => {
  11650. each$e(matchRecord, match => {
  11651. const nodes = filter$6(match.nodes, node => isNonNullable(node.parent));
  11652. each$f(match.filter.callbacks, callback => {
  11653. callback(nodes, match.filter.name, args);
  11654. });
  11655. });
  11656. };
  11657. run(matches.nodes);
  11658. run(matches.attributes);
  11659. };
  11660. const filter$3 = (nodeFilters, attributeFilters, node, args = {}) => {
  11661. const matches = findMatchingNodes(nodeFilters, attributeFilters, node);
  11662. runFilters(matches, args);
  11663. };
  11664. const paddEmptyNode = (settings, args, blockElements, node) => {
  11665. if (args.insert && blockElements[node.name]) {
  11666. node.empty().append(new AstNode('br', 1));
  11667. } else {
  11668. node.empty().append(new AstNode('#text', 3)).value = nbsp;
  11669. }
  11670. };
  11671. const isPaddedWithNbsp = node => hasOnlyChild(node, '#text') && node.firstChild.value === nbsp;
  11672. const hasOnlyChild = (node, name) => node && node.firstChild && node.firstChild === node.lastChild && node.firstChild.name === name;
  11673. const isPadded = (schema, node) => {
  11674. const rule = schema.getElementRule(node.name);
  11675. return rule && rule.paddEmpty;
  11676. };
  11677. const isEmpty = (schema, nonEmptyElements, whitespaceElements, node) => node.isEmpty(nonEmptyElements, whitespaceElements, node => isPadded(schema, node));
  11678. const isLineBreakNode = (node, blockElements) => node && (node.name in blockElements || node.name === 'br');
  11679. const removeOrUnwrapInvalidNode = (node, schema, originalNodeParent = node.parent) => {
  11680. if (schema.getSpecialElements()[node.name]) {
  11681. node.empty().remove();
  11682. } else {
  11683. const children = node.children();
  11684. for (const childNode of children) {
  11685. if (!schema.isValidChild(originalNodeParent.name, childNode.name)) {
  11686. removeOrUnwrapInvalidNode(childNode, schema, originalNodeParent);
  11687. }
  11688. }
  11689. node.unwrap();
  11690. }
  11691. };
  11692. const cleanInvalidNodes = (nodes, schema, onCreate = noop) => {
  11693. const textBlockElements = schema.getTextBlockElements();
  11694. const nonEmptyElements = schema.getNonEmptyElements();
  11695. const whitespaceElements = schema.getWhitespaceElements();
  11696. const nonSplittableElements = Tools.makeMap('tr,td,th,tbody,thead,tfoot,table');
  11697. const fixed = new Set();
  11698. for (let ni = 0; ni < nodes.length; ni++) {
  11699. const node = nodes[ni];
  11700. let parent;
  11701. let newParent;
  11702. let tempNode;
  11703. if (!node.parent || fixed.has(node)) {
  11704. continue;
  11705. }
  11706. if (textBlockElements[node.name] && node.parent.name === 'li') {
  11707. let sibling = node.next;
  11708. while (sibling) {
  11709. if (textBlockElements[sibling.name]) {
  11710. sibling.name = 'li';
  11711. fixed.add(sibling);
  11712. node.parent.insert(sibling, node.parent);
  11713. } else {
  11714. break;
  11715. }
  11716. sibling = sibling.next;
  11717. }
  11718. node.unwrap();
  11719. continue;
  11720. }
  11721. const parents = [node];
  11722. for (parent = node.parent; parent && !schema.isValidChild(parent.name, node.name) && !nonSplittableElements[parent.name]; parent = parent.parent) {
  11723. parents.push(parent);
  11724. }
  11725. if (parent && parents.length > 1) {
  11726. if (schema.isValidChild(parent.name, node.name)) {
  11727. parents.reverse();
  11728. newParent = parents[0].clone();
  11729. onCreate(newParent);
  11730. let currentNode = newParent;
  11731. for (let i = 0; i < parents.length - 1; i++) {
  11732. if (schema.isValidChild(currentNode.name, parents[i].name)) {
  11733. tempNode = parents[i].clone();
  11734. onCreate(tempNode);
  11735. currentNode.append(tempNode);
  11736. } else {
  11737. tempNode = currentNode;
  11738. }
  11739. for (let childNode = parents[i].firstChild; childNode && childNode !== parents[i + 1];) {
  11740. const nextNode = childNode.next;
  11741. tempNode.append(childNode);
  11742. childNode = nextNode;
  11743. }
  11744. currentNode = tempNode;
  11745. }
  11746. if (!isEmpty(schema, nonEmptyElements, whitespaceElements, newParent)) {
  11747. parent.insert(newParent, parents[0], true);
  11748. parent.insert(node, newParent);
  11749. } else {
  11750. parent.insert(node, parents[0], true);
  11751. }
  11752. parent = parents[0];
  11753. if (isEmpty(schema, nonEmptyElements, whitespaceElements, parent) || hasOnlyChild(parent, 'br')) {
  11754. parent.empty().remove();
  11755. }
  11756. } else {
  11757. removeOrUnwrapInvalidNode(node, schema);
  11758. }
  11759. } else if (node.parent) {
  11760. if (node.name === 'li') {
  11761. let sibling = node.prev;
  11762. if (sibling && (sibling.name === 'ul' || sibling.name === 'ol')) {
  11763. sibling.append(node);
  11764. continue;
  11765. }
  11766. sibling = node.next;
  11767. if (sibling && (sibling.name === 'ul' || sibling.name === 'ol')) {
  11768. sibling.insert(node, sibling.firstChild, true);
  11769. continue;
  11770. }
  11771. const wrapper = new AstNode('ul', 1);
  11772. onCreate(wrapper);
  11773. node.wrap(wrapper);
  11774. continue;
  11775. }
  11776. if (schema.isValidChild(node.parent.name, 'div') && schema.isValidChild('div', node.name)) {
  11777. const wrapper = new AstNode('div', 1);
  11778. onCreate(wrapper);
  11779. node.wrap(wrapper);
  11780. } else {
  11781. removeOrUnwrapInvalidNode(node, schema);
  11782. }
  11783. }
  11784. }
  11785. };
  11786. const createRange = (sc, so, ec, eo) => {
  11787. const rng = document.createRange();
  11788. rng.setStart(sc, so);
  11789. rng.setEnd(ec, eo);
  11790. return rng;
  11791. };
  11792. const normalizeBlockSelectionRange = rng => {
  11793. const startPos = CaretPosition.fromRangeStart(rng);
  11794. const endPos = CaretPosition.fromRangeEnd(rng);
  11795. const rootNode = rng.commonAncestorContainer;
  11796. return fromPosition(false, rootNode, endPos).map(newEndPos => {
  11797. if (!isInSameBlock(startPos, endPos, rootNode) && isInSameBlock(startPos, newEndPos, rootNode)) {
  11798. return createRange(startPos.container(), startPos.offset(), newEndPos.container(), newEndPos.offset());
  11799. } else {
  11800. return rng;
  11801. }
  11802. }).getOr(rng);
  11803. };
  11804. const normalize = rng => rng.collapsed ? rng : normalizeBlockSelectionRange(rng);
  11805. const hasOnlyOneChild$1 = node => {
  11806. return node.firstChild && node.firstChild === node.lastChild;
  11807. };
  11808. const isPaddingNode = node => {
  11809. return node.name === 'br' || node.value === nbsp;
  11810. };
  11811. const isPaddedEmptyBlock = (schema, node) => {
  11812. const blockElements = schema.getBlockElements();
  11813. return blockElements[node.name] && hasOnlyOneChild$1(node) && isPaddingNode(node.firstChild);
  11814. };
  11815. const isEmptyFragmentElement = (schema, node) => {
  11816. const nonEmptyElements = schema.getNonEmptyElements();
  11817. return node && (node.isEmpty(nonEmptyElements) || isPaddedEmptyBlock(schema, node));
  11818. };
  11819. const isListFragment = (schema, fragment) => {
  11820. let firstChild = fragment.firstChild;
  11821. let lastChild = fragment.lastChild;
  11822. if (firstChild && firstChild.name === 'meta') {
  11823. firstChild = firstChild.next;
  11824. }
  11825. if (lastChild && lastChild.attr('id') === 'mce_marker') {
  11826. lastChild = lastChild.prev;
  11827. }
  11828. if (isEmptyFragmentElement(schema, lastChild)) {
  11829. lastChild = lastChild.prev;
  11830. }
  11831. if (!firstChild || firstChild !== lastChild) {
  11832. return false;
  11833. }
  11834. return firstChild.name === 'ul' || firstChild.name === 'ol';
  11835. };
  11836. const cleanupDomFragment = domFragment => {
  11837. const firstChild = domFragment.firstChild;
  11838. const lastChild = domFragment.lastChild;
  11839. if (firstChild && firstChild.nodeName === 'META') {
  11840. firstChild.parentNode.removeChild(firstChild);
  11841. }
  11842. if (lastChild && lastChild.id === 'mce_marker') {
  11843. lastChild.parentNode.removeChild(lastChild);
  11844. }
  11845. return domFragment;
  11846. };
  11847. const toDomFragment = (dom, serializer, fragment) => {
  11848. const html = serializer.serialize(fragment);
  11849. const domFragment = dom.createFragment(html);
  11850. return cleanupDomFragment(domFragment);
  11851. };
  11852. const listItems = elm => {
  11853. return filter$6(elm.childNodes, child => {
  11854. return child.nodeName === 'LI';
  11855. });
  11856. };
  11857. const isPadding = node => {
  11858. return node.data === nbsp || isBr$6(node);
  11859. };
  11860. const isListItemPadded = node => {
  11861. return node && node.firstChild && node.firstChild === node.lastChild && isPadding(node.firstChild);
  11862. };
  11863. const isEmptyOrPadded = elm => {
  11864. return !elm.firstChild || isListItemPadded(elm);
  11865. };
  11866. const trimListItems = elms => {
  11867. return elms.length > 0 && isEmptyOrPadded(elms[elms.length - 1]) ? elms.slice(0, -1) : elms;
  11868. };
  11869. const getParentLi = (dom, node) => {
  11870. const parentBlock = dom.getParent(node, dom.isBlock);
  11871. return parentBlock && parentBlock.nodeName === 'LI' ? parentBlock : null;
  11872. };
  11873. const isParentBlockLi = (dom, node) => {
  11874. return !!getParentLi(dom, node);
  11875. };
  11876. const getSplit = (parentNode, rng) => {
  11877. const beforeRng = rng.cloneRange();
  11878. const afterRng = rng.cloneRange();
  11879. beforeRng.setStartBefore(parentNode);
  11880. afterRng.setEndAfter(parentNode);
  11881. return [
  11882. beforeRng.cloneContents(),
  11883. afterRng.cloneContents()
  11884. ];
  11885. };
  11886. const findFirstIn = (node, rootNode) => {
  11887. const caretPos = CaretPosition.before(node);
  11888. const caretWalker = CaretWalker(rootNode);
  11889. const newCaretPos = caretWalker.next(caretPos);
  11890. return newCaretPos ? newCaretPos.toRange() : null;
  11891. };
  11892. const findLastOf = (node, rootNode) => {
  11893. const caretPos = CaretPosition.after(node);
  11894. const caretWalker = CaretWalker(rootNode);
  11895. const newCaretPos = caretWalker.prev(caretPos);
  11896. return newCaretPos ? newCaretPos.toRange() : null;
  11897. };
  11898. const insertMiddle = (target, elms, rootNode, rng) => {
  11899. const parts = getSplit(target, rng);
  11900. const parentElm = target.parentNode;
  11901. parentElm.insertBefore(parts[0], target);
  11902. Tools.each(elms, li => {
  11903. parentElm.insertBefore(li, target);
  11904. });
  11905. parentElm.insertBefore(parts[1], target);
  11906. parentElm.removeChild(target);
  11907. return findLastOf(elms[elms.length - 1], rootNode);
  11908. };
  11909. const insertBefore$1 = (target, elms, rootNode) => {
  11910. const parentElm = target.parentNode;
  11911. Tools.each(elms, elm => {
  11912. parentElm.insertBefore(elm, target);
  11913. });
  11914. return findFirstIn(target, rootNode);
  11915. };
  11916. const insertAfter$1 = (target, elms, rootNode, dom) => {
  11917. dom.insertAfter(elms.reverse(), target);
  11918. return findLastOf(elms[0], rootNode);
  11919. };
  11920. const insertAtCaret$1 = (serializer, dom, rng, fragment) => {
  11921. const domFragment = toDomFragment(dom, serializer, fragment);
  11922. const liTarget = getParentLi(dom, rng.startContainer);
  11923. const liElms = trimListItems(listItems(domFragment.firstChild));
  11924. const BEGINNING = 1, END = 2;
  11925. const rootNode = dom.getRoot();
  11926. const isAt = location => {
  11927. const caretPos = CaretPosition.fromRangeStart(rng);
  11928. const caretWalker = CaretWalker(dom.getRoot());
  11929. const newPos = location === BEGINNING ? caretWalker.prev(caretPos) : caretWalker.next(caretPos);
  11930. return newPos ? getParentLi(dom, newPos.getNode()) !== liTarget : true;
  11931. };
  11932. if (isAt(BEGINNING)) {
  11933. return insertBefore$1(liTarget, liElms, rootNode);
  11934. } else if (isAt(END)) {
  11935. return insertAfter$1(liTarget, liElms, rootNode, dom);
  11936. }
  11937. return insertMiddle(liTarget, liElms, rootNode, rng);
  11938. };
  11939. const wrappedElements = ['pre'];
  11940. const shouldPasteContentOnly = (fragment, parentNode) => {
  11941. const firstNode = fragment.firstChild;
  11942. const isAFlattenableTag = contains$2(wrappedElements, firstNode.name);
  11943. const isPastingInTheSameTag = firstNode.name === parentNode.tagName.toLowerCase();
  11944. const lastNode = fragment.lastChild.attr('data-mce-type') === 'bookmark' ? fragment.lastChild.prev : fragment.lastChild;
  11945. const isCopingOnlyOneTag = firstNode === lastNode;
  11946. return isCopingOnlyOneTag && isAFlattenableTag && isPastingInTheSameTag;
  11947. };
  11948. const isTableCell$1 = isTableCell$5;
  11949. const isTableCellContentSelected = (dom, rng, cell) => {
  11950. if (cell !== null) {
  11951. const endCell = dom.getParent(rng.endContainer, isTableCell$1);
  11952. return cell === endCell && hasAllContentsSelected(SugarElement.fromDom(cell), rng);
  11953. } else {
  11954. return false;
  11955. }
  11956. };
  11957. const validInsertion = (editor, value, parentNode) => {
  11958. if (parentNode.getAttribute('data-mce-bogus') === 'all') {
  11959. parentNode.parentNode.insertBefore(editor.dom.createFragment(value), parentNode);
  11960. } else {
  11961. const node = parentNode.firstChild;
  11962. const node2 = parentNode.lastChild;
  11963. if (!node || node === node2 && node.nodeName === 'BR') {
  11964. editor.dom.setHTML(parentNode, value);
  11965. } else {
  11966. editor.selection.setContent(value, { no_events: true });
  11967. }
  11968. }
  11969. };
  11970. const trimBrsFromTableCell = (dom, elm) => {
  11971. Optional.from(dom.getParent(elm, 'td,th')).map(SugarElement.fromDom).each(trimBlockTrailingBr);
  11972. };
  11973. const reduceInlineTextElements = (editor, merge) => {
  11974. const textInlineElements = editor.schema.getTextInlineElements();
  11975. const dom = editor.dom;
  11976. if (merge) {
  11977. const root = editor.getBody();
  11978. const elementUtils = ElementUtils(dom);
  11979. Tools.each(dom.select('*[data-mce-fragment]'), node => {
  11980. const isInline = isNonNullable(textInlineElements[node.nodeName.toLowerCase()]);
  11981. if (isInline && hasInheritableStyles(dom, node)) {
  11982. for (let parentNode = node.parentNode; isNonNullable(parentNode) && parentNode !== root; parentNode = parentNode.parentNode) {
  11983. const styleConflict = hasStyleConflict(dom, node, parentNode);
  11984. if (styleConflict) {
  11985. break;
  11986. }
  11987. if (elementUtils.compare(parentNode, node)) {
  11988. dom.remove(node, true);
  11989. break;
  11990. }
  11991. }
  11992. }
  11993. });
  11994. }
  11995. };
  11996. const markFragmentElements = fragment => {
  11997. let node = fragment;
  11998. while (node = node.walk()) {
  11999. if (node.type === 1) {
  12000. node.attr('data-mce-fragment', '1');
  12001. }
  12002. }
  12003. };
  12004. const unmarkFragmentElements = elm => {
  12005. Tools.each(elm.getElementsByTagName('*'), elm => {
  12006. elm.removeAttribute('data-mce-fragment');
  12007. });
  12008. };
  12009. const isPartOfFragment = node => {
  12010. return !!node.getAttribute('data-mce-fragment');
  12011. };
  12012. const canHaveChildren = (editor, node) => {
  12013. return node && !editor.schema.getVoidElements()[node.nodeName];
  12014. };
  12015. const moveSelectionToMarker = (editor, marker) => {
  12016. let nextRng;
  12017. const dom = editor.dom;
  12018. const selection = editor.selection;
  12019. if (!marker) {
  12020. return;
  12021. }
  12022. selection.scrollIntoView(marker);
  12023. const parentEditableElm = getContentEditableRoot$1(editor.getBody(), marker);
  12024. if (dom.getContentEditable(parentEditableElm) === 'false') {
  12025. dom.remove(marker);
  12026. selection.select(parentEditableElm);
  12027. return;
  12028. }
  12029. let rng = dom.createRng();
  12030. const node = marker.previousSibling;
  12031. if (isText$9(node)) {
  12032. rng.setStart(node, node.nodeValue.length);
  12033. const node2 = marker.nextSibling;
  12034. if (isText$9(node2)) {
  12035. node.appendData(node2.data);
  12036. node2.parentNode.removeChild(node2);
  12037. }
  12038. } else {
  12039. rng.setStartBefore(marker);
  12040. rng.setEndBefore(marker);
  12041. }
  12042. const findNextCaretRng = rng => {
  12043. let caretPos = CaretPosition.fromRangeStart(rng);
  12044. const caretWalker = CaretWalker(editor.getBody());
  12045. caretPos = caretWalker.next(caretPos);
  12046. if (caretPos) {
  12047. return caretPos.toRange();
  12048. }
  12049. };
  12050. const parentBlock = dom.getParent(marker, dom.isBlock);
  12051. dom.remove(marker);
  12052. if (parentBlock && dom.isEmpty(parentBlock)) {
  12053. empty(SugarElement.fromDom(parentBlock));
  12054. rng.setStart(parentBlock, 0);
  12055. rng.setEnd(parentBlock, 0);
  12056. if (!isTableCell$1(parentBlock) && !isPartOfFragment(parentBlock) && (nextRng = findNextCaretRng(rng))) {
  12057. rng = nextRng;
  12058. dom.remove(parentBlock);
  12059. } else {
  12060. dom.add(parentBlock, dom.create('br', { 'data-mce-bogus': '1' }));
  12061. }
  12062. }
  12063. selection.setRng(rng);
  12064. };
  12065. const deleteSelectedContent = editor => {
  12066. const dom = editor.dom;
  12067. const rng = normalize(editor.selection.getRng());
  12068. editor.selection.setRng(rng);
  12069. const startCell = dom.getParent(rng.startContainer, isTableCell$1);
  12070. if (isTableCellContentSelected(dom, rng, startCell)) {
  12071. deleteCellContents(editor, rng, SugarElement.fromDom(startCell));
  12072. } else {
  12073. editor.getDoc().execCommand('Delete', false, null);
  12074. }
  12075. };
  12076. const insertHtmlAtCaret = (editor, value, details) => {
  12077. let parentNode;
  12078. let rng, node;
  12079. const selection = editor.selection;
  12080. const dom = editor.dom;
  12081. const parser = editor.parser;
  12082. const merge = details.merge;
  12083. const serializer = HtmlSerializer({ validate: true }, editor.schema);
  12084. const bookmarkHtml = '<span id="mce_marker" data-mce-type="bookmark">&#xFEFF;</span>';
  12085. if (value.indexOf('{$caret}') === -1) {
  12086. value += '{$caret}';
  12087. }
  12088. value = value.replace(/\{\$caret\}/, bookmarkHtml);
  12089. rng = selection.getRng();
  12090. const caretElement = rng.startContainer || (rng.parentElement ? rng.parentElement() : null);
  12091. const body = editor.getBody();
  12092. if (caretElement === body && selection.isCollapsed()) {
  12093. if (dom.isBlock(body.firstChild) && canHaveChildren(editor, body.firstChild) && dom.isEmpty(body.firstChild)) {
  12094. rng = dom.createRng();
  12095. rng.setStart(body.firstChild, 0);
  12096. rng.setEnd(body.firstChild, 0);
  12097. selection.setRng(rng);
  12098. }
  12099. }
  12100. if (!selection.isCollapsed()) {
  12101. deleteSelectedContent(editor);
  12102. }
  12103. parentNode = selection.getNode();
  12104. const parserArgs = {
  12105. context: parentNode.nodeName.toLowerCase(),
  12106. data: details.data,
  12107. insert: true
  12108. };
  12109. const fragment = parser.parse(value, parserArgs);
  12110. if (details.paste === true && isListFragment(editor.schema, fragment) && isParentBlockLi(dom, parentNode)) {
  12111. rng = insertAtCaret$1(serializer, dom, selection.getRng(), fragment);
  12112. selection.setRng(rng);
  12113. return value;
  12114. }
  12115. if (details.paste === true && shouldPasteContentOnly(fragment, parentNode)) {
  12116. fragment.firstChild.unwrap();
  12117. }
  12118. markFragmentElements(fragment);
  12119. node = fragment.lastChild;
  12120. if (node.attr('id') === 'mce_marker') {
  12121. const marker = node;
  12122. for (node = node.prev; node; node = node.walk(true)) {
  12123. if (node.type === 3 || !dom.isBlock(node.name)) {
  12124. if (editor.schema.isValidChild(node.parent.name, 'span')) {
  12125. node.parent.insert(marker, node, node.name === 'br');
  12126. }
  12127. break;
  12128. }
  12129. }
  12130. }
  12131. editor._selectionOverrides.showBlockCaretContainer(parentNode);
  12132. if (!parserArgs.invalid) {
  12133. value = serializer.serialize(fragment);
  12134. validInsertion(editor, value, parentNode);
  12135. } else {
  12136. editor.selection.setContent(bookmarkHtml);
  12137. parentNode = selection.getNode();
  12138. const rootNode = editor.getBody();
  12139. if (parentNode.nodeType === 9) {
  12140. parentNode = node = rootNode;
  12141. } else {
  12142. node = parentNode;
  12143. }
  12144. while (node !== rootNode) {
  12145. parentNode = node;
  12146. node = node.parentNode;
  12147. }
  12148. value = parentNode === rootNode ? rootNode.innerHTML : dom.getOuterHTML(parentNode);
  12149. const root = parser.parse(value);
  12150. for (let markerNode = root; markerNode; markerNode = markerNode.walk()) {
  12151. if (markerNode.attr('id') === 'mce_marker') {
  12152. markerNode.replace(fragment);
  12153. break;
  12154. }
  12155. }
  12156. const toExtract = fragment.children();
  12157. const parent = fragment.parent.name;
  12158. fragment.unwrap();
  12159. const invalidChildren = filter$6(toExtract, node => !editor.schema.isValidChild(parent, node.name));
  12160. cleanInvalidNodes(invalidChildren, editor.schema);
  12161. filter$3(parser.getNodeFilters(), parser.getAttributeFilters(), root);
  12162. value = serializer.serialize(root);
  12163. if (parentNode === rootNode) {
  12164. dom.setHTML(rootNode, value);
  12165. } else {
  12166. dom.setOuterHTML(parentNode, value);
  12167. }
  12168. }
  12169. reduceInlineTextElements(editor, merge);
  12170. moveSelectionToMarker(editor, dom.get('mce_marker'));
  12171. unmarkFragmentElements(editor.getBody());
  12172. trimBrsFromTableCell(dom, selection.getStart());
  12173. return value;
  12174. };
  12175. const isTreeNode = content => content instanceof AstNode;
  12176. const moveSelection = editor => {
  12177. if (hasFocus(editor)) {
  12178. firstPositionIn(editor.getBody()).each(pos => {
  12179. const node = pos.getNode();
  12180. const caretPos = isTable$3(node) ? firstPositionIn(node).getOr(pos) : pos;
  12181. editor.selection.setRng(caretPos.toRange());
  12182. });
  12183. }
  12184. };
  12185. const setEditorHtml = (editor, html, noSelection) => {
  12186. editor.dom.setHTML(editor.getBody(), html);
  12187. if (noSelection !== true) {
  12188. moveSelection(editor);
  12189. }
  12190. };
  12191. const setContentString = (editor, body, content, args) => {
  12192. if (content.length === 0 || /^\s+$/.test(content)) {
  12193. const padd = '<br data-mce-bogus="1">';
  12194. if (body.nodeName === 'TABLE') {
  12195. content = '<tr><td>' + padd + '</td></tr>';
  12196. } else if (/^(UL|OL)$/.test(body.nodeName)) {
  12197. content = '<li>' + padd + '</li>';
  12198. }
  12199. const forcedRootBlockName = getForcedRootBlock(editor);
  12200. if (editor.schema.isValidChild(body.nodeName.toLowerCase(), forcedRootBlockName.toLowerCase())) {
  12201. content = padd;
  12202. content = editor.dom.createHTML(forcedRootBlockName, getForcedRootBlockAttrs(editor), content);
  12203. } else if (!content) {
  12204. content = padd;
  12205. }
  12206. setEditorHtml(editor, content, args.no_selection);
  12207. return {
  12208. content,
  12209. html: content
  12210. };
  12211. } else {
  12212. if (args.format !== 'raw') {
  12213. content = HtmlSerializer({ validate: false }, editor.schema).serialize(editor.parser.parse(content, {
  12214. isRootContent: true,
  12215. insert: true
  12216. }));
  12217. }
  12218. const trimmedHtml = isWsPreserveElement(SugarElement.fromDom(body)) ? content : Tools.trim(content);
  12219. setEditorHtml(editor, trimmedHtml, args.no_selection);
  12220. return {
  12221. content: trimmedHtml,
  12222. html: trimmedHtml
  12223. };
  12224. }
  12225. };
  12226. const setContentTree = (editor, body, content, args) => {
  12227. filter$3(editor.parser.getNodeFilters(), editor.parser.getAttributeFilters(), content);
  12228. const html = HtmlSerializer({ validate: false }, editor.schema).serialize(content);
  12229. const trimmedHtml = isWsPreserveElement(SugarElement.fromDom(body)) ? html : Tools.trim(html);
  12230. setEditorHtml(editor, trimmedHtml, args.no_selection);
  12231. return {
  12232. content,
  12233. html: trimmedHtml
  12234. };
  12235. };
  12236. const setContentInternal = (editor, content, args) => {
  12237. return Optional.from(editor.getBody()).map(body => {
  12238. if (isTreeNode(content)) {
  12239. return setContentTree(editor, body, content, args);
  12240. } else {
  12241. return setContentString(editor, body, content, args);
  12242. }
  12243. }).getOr({
  12244. content,
  12245. html: isTreeNode(args.content) ? '' : args.content
  12246. });
  12247. };
  12248. const sibling = (scope, predicate) => sibling$1(scope, predicate).isSome();
  12249. const ensureIsRoot = isRoot => isFunction(isRoot) ? isRoot : never;
  12250. const ancestor = (scope, transform, isRoot) => {
  12251. let element = scope.dom;
  12252. const stop = ensureIsRoot(isRoot);
  12253. while (element.parentNode) {
  12254. element = element.parentNode;
  12255. const el = SugarElement.fromDom(element);
  12256. const transformed = transform(el);
  12257. if (transformed.isSome()) {
  12258. return transformed;
  12259. } else if (stop(el)) {
  12260. break;
  12261. }
  12262. }
  12263. return Optional.none();
  12264. };
  12265. const closest$2 = (scope, transform, isRoot) => {
  12266. const current = transform(scope);
  12267. const stop = ensureIsRoot(isRoot);
  12268. return current.orThunk(() => stop(scope) ? Optional.none() : ancestor(scope, transform, stop));
  12269. };
  12270. const isEq$3 = isEq$5;
  12271. const matchesUnInheritedFormatSelector = (ed, node, name) => {
  12272. const formatList = ed.formatter.get(name);
  12273. if (formatList) {
  12274. for (let i = 0; i < formatList.length; i++) {
  12275. const format = formatList[i];
  12276. if (isSelectorFormat(format) && format.inherit === false && ed.dom.is(node, format.selector)) {
  12277. return true;
  12278. }
  12279. }
  12280. }
  12281. return false;
  12282. };
  12283. const matchParents = (editor, node, name, vars, similar) => {
  12284. const root = editor.dom.getRoot();
  12285. if (node === root) {
  12286. return false;
  12287. }
  12288. node = editor.dom.getParent(node, node => {
  12289. if (matchesUnInheritedFormatSelector(editor, node, name)) {
  12290. return true;
  12291. }
  12292. return node.parentNode === root || !!matchNode(editor, node, name, vars, true);
  12293. });
  12294. return !!matchNode(editor, node, name, vars, similar);
  12295. };
  12296. const matchName = (dom, node, format) => {
  12297. if (isInlineFormat(format) && isEq$3(node, format.inline)) {
  12298. return true;
  12299. }
  12300. if (isBlockFormat(format) && isEq$3(node, format.block)) {
  12301. return true;
  12302. }
  12303. if (isSelectorFormat(format)) {
  12304. return isElement$6(node) && dom.is(node, format.selector);
  12305. }
  12306. return false;
  12307. };
  12308. const matchItems = (dom, node, format, itemName, similar, vars) => {
  12309. const items = format[itemName];
  12310. if (isFunction(format.onmatch)) {
  12311. return format.onmatch(node, format, itemName);
  12312. }
  12313. if (items) {
  12314. if (isUndefined(items.length)) {
  12315. for (const key in items) {
  12316. if (has$2(items, key)) {
  12317. const value = itemName === 'attributes' ? dom.getAttrib(node, key) : getStyle(dom, node, key);
  12318. const expectedValue = replaceVars(items[key], vars);
  12319. const isEmptyValue = isNullable(value) || isEmpty$3(value);
  12320. if (isEmptyValue && isNullable(expectedValue)) {
  12321. continue;
  12322. }
  12323. if (similar && isEmptyValue && !format.exact) {
  12324. return false;
  12325. }
  12326. if ((!similar || format.exact) && !isEq$3(value, normalizeStyleValue(expectedValue, key))) {
  12327. return false;
  12328. }
  12329. }
  12330. }
  12331. } else {
  12332. for (let i = 0; i < items.length; i++) {
  12333. if (itemName === 'attributes' ? dom.getAttrib(node, items[i]) : getStyle(dom, node, items[i])) {
  12334. return true;
  12335. }
  12336. }
  12337. }
  12338. }
  12339. return true;
  12340. };
  12341. const matchNode = (ed, node, name, vars, similar) => {
  12342. const formatList = ed.formatter.get(name);
  12343. const dom = ed.dom;
  12344. if (formatList && node) {
  12345. for (let i = 0; i < formatList.length; i++) {
  12346. const format = formatList[i];
  12347. if (matchName(ed.dom, node, format) && matchItems(dom, node, format, 'attributes', similar, vars) && matchItems(dom, node, format, 'styles', similar, vars)) {
  12348. const classes = format.classes;
  12349. if (classes) {
  12350. for (let x = 0; x < classes.length; x++) {
  12351. if (!ed.dom.hasClass(node, replaceVars(classes[x], vars))) {
  12352. return;
  12353. }
  12354. }
  12355. }
  12356. return format;
  12357. }
  12358. }
  12359. }
  12360. };
  12361. const match$2 = (editor, name, vars, node, similar) => {
  12362. if (node) {
  12363. return matchParents(editor, node, name, vars, similar);
  12364. }
  12365. node = editor.selection.getNode();
  12366. if (matchParents(editor, node, name, vars, similar)) {
  12367. return true;
  12368. }
  12369. const startNode = editor.selection.getStart();
  12370. if (startNode !== node) {
  12371. if (matchParents(editor, startNode, name, vars, similar)) {
  12372. return true;
  12373. }
  12374. }
  12375. return false;
  12376. };
  12377. const matchAll = (editor, names, vars) => {
  12378. const matchedFormatNames = [];
  12379. const checkedMap = {};
  12380. const startElement = editor.selection.getStart();
  12381. editor.dom.getParent(startElement, node => {
  12382. for (let i = 0; i < names.length; i++) {
  12383. const name = names[i];
  12384. if (!checkedMap[name] && matchNode(editor, node, name, vars)) {
  12385. checkedMap[name] = true;
  12386. matchedFormatNames.push(name);
  12387. }
  12388. }
  12389. }, editor.dom.getRoot());
  12390. return matchedFormatNames;
  12391. };
  12392. const closest$1 = (editor, names) => {
  12393. const isRoot = elm => eq(elm, SugarElement.fromDom(editor.getBody()));
  12394. const match = (elm, name) => matchNode(editor, elm.dom, name) ? Optional.some(name) : Optional.none();
  12395. return Optional.from(editor.selection.getStart(true)).bind(rawElm => closest$2(SugarElement.fromDom(rawElm), elm => findMap(names, name => match(elm, name)), isRoot)).getOrNull();
  12396. };
  12397. const canApply = (editor, name) => {
  12398. const formatList = editor.formatter.get(name);
  12399. const dom = editor.dom;
  12400. if (formatList) {
  12401. const startNode = editor.selection.getStart();
  12402. const parents = getParents$2(dom, startNode);
  12403. for (let x = formatList.length - 1; x >= 0; x--) {
  12404. const format = formatList[x];
  12405. if (!isSelectorFormat(format)) {
  12406. return true;
  12407. }
  12408. for (let i = parents.length - 1; i >= 0; i--) {
  12409. if (dom.is(parents[i], format.selector)) {
  12410. return true;
  12411. }
  12412. }
  12413. }
  12414. }
  12415. return false;
  12416. };
  12417. const matchAllOnNode = (editor, node, formatNames) => foldl(formatNames, (acc, name) => {
  12418. const matchSimilar = isVariableFormatName(editor, name);
  12419. if (editor.formatter.matchNode(node, name, {}, matchSimilar)) {
  12420. return acc.concat([name]);
  12421. } else {
  12422. return acc;
  12423. }
  12424. }, []);
  12425. const ZWSP = ZWSP$1, CARET_ID = '_mce_caret';
  12426. const importNode = (ownerDocument, node) => {
  12427. return ownerDocument.importNode(node, true);
  12428. };
  12429. const getEmptyCaretContainers = node => {
  12430. const nodes = [];
  12431. while (node) {
  12432. if (node.nodeType === 3 && node.nodeValue !== ZWSP || node.childNodes.length > 1) {
  12433. return [];
  12434. }
  12435. if (node.nodeType === 1) {
  12436. nodes.push(node);
  12437. }
  12438. node = node.firstChild;
  12439. }
  12440. return nodes;
  12441. };
  12442. const isCaretContainerEmpty = node => {
  12443. return getEmptyCaretContainers(node).length > 0;
  12444. };
  12445. const findFirstTextNode = node => {
  12446. if (node) {
  12447. const walker = new DomTreeWalker(node, node);
  12448. for (node = walker.current(); node; node = walker.next()) {
  12449. if (isText$9(node)) {
  12450. return node;
  12451. }
  12452. }
  12453. }
  12454. return null;
  12455. };
  12456. const createCaretContainer = fill => {
  12457. const caretContainer = SugarElement.fromTag('span');
  12458. setAll$1(caretContainer, {
  12459. 'id': CARET_ID,
  12460. 'data-mce-bogus': '1',
  12461. 'data-mce-type': 'format-caret'
  12462. });
  12463. if (fill) {
  12464. append$1(caretContainer, SugarElement.fromText(ZWSP));
  12465. }
  12466. return caretContainer;
  12467. };
  12468. const trimZwspFromCaretContainer = caretContainerNode => {
  12469. const textNode = findFirstTextNode(caretContainerNode);
  12470. if (textNode && textNode.nodeValue.charAt(0) === ZWSP) {
  12471. textNode.deleteData(0, 1);
  12472. }
  12473. return textNode;
  12474. };
  12475. const removeCaretContainerNode = (editor, node, moveCaret = true) => {
  12476. const dom = editor.dom, selection = editor.selection;
  12477. if (isCaretContainerEmpty(node)) {
  12478. deleteElement$2(editor, false, SugarElement.fromDom(node), moveCaret);
  12479. } else {
  12480. const rng = selection.getRng();
  12481. const block = dom.getParent(node, dom.isBlock);
  12482. const startContainer = rng.startContainer;
  12483. const startOffset = rng.startOffset;
  12484. const endContainer = rng.endContainer;
  12485. const endOffset = rng.endOffset;
  12486. const textNode = trimZwspFromCaretContainer(node);
  12487. dom.remove(node, true);
  12488. if (startContainer === textNode && startOffset > 0) {
  12489. rng.setStart(textNode, startOffset - 1);
  12490. }
  12491. if (endContainer === textNode && endOffset > 0) {
  12492. rng.setEnd(textNode, endOffset - 1);
  12493. }
  12494. if (block && dom.isEmpty(block)) {
  12495. fillWithPaddingBr(SugarElement.fromDom(block));
  12496. }
  12497. selection.setRng(rng);
  12498. }
  12499. };
  12500. const removeCaretContainer = (editor, node, moveCaret = true) => {
  12501. const dom = editor.dom, selection = editor.selection;
  12502. if (!node) {
  12503. node = getParentCaretContainer(editor.getBody(), selection.getStart());
  12504. if (!node) {
  12505. while (node = dom.get(CARET_ID)) {
  12506. removeCaretContainerNode(editor, node, false);
  12507. }
  12508. }
  12509. } else {
  12510. removeCaretContainerNode(editor, node, moveCaret);
  12511. }
  12512. };
  12513. const insertCaretContainerNode = (editor, caretContainer, formatNode) => {
  12514. const dom = editor.dom, block = dom.getParent(formatNode, curry(isTextBlock$1, editor));
  12515. if (block && dom.isEmpty(block)) {
  12516. formatNode.parentNode.replaceChild(caretContainer, formatNode);
  12517. } else {
  12518. removeTrailingBr(SugarElement.fromDom(formatNode));
  12519. if (dom.isEmpty(formatNode)) {
  12520. formatNode.parentNode.replaceChild(caretContainer, formatNode);
  12521. } else {
  12522. dom.insertAfter(caretContainer, formatNode);
  12523. }
  12524. }
  12525. };
  12526. const appendNode = (parentNode, node) => {
  12527. parentNode.appendChild(node);
  12528. return node;
  12529. };
  12530. const insertFormatNodesIntoCaretContainer = (formatNodes, caretContainer) => {
  12531. const innerMostFormatNode = foldr(formatNodes, (parentNode, formatNode) => {
  12532. return appendNode(parentNode, formatNode.cloneNode(false));
  12533. }, caretContainer);
  12534. return appendNode(innerMostFormatNode, innerMostFormatNode.ownerDocument.createTextNode(ZWSP));
  12535. };
  12536. const cleanFormatNode = (editor, caretContainer, formatNode, name, vars, similar) => {
  12537. const formatter = editor.formatter;
  12538. const dom = editor.dom;
  12539. const validFormats = filter$6(keys(formatter.get()), formatName => formatName !== name && !contains$1(formatName, 'removeformat'));
  12540. const matchedFormats = matchAllOnNode(editor, formatNode, validFormats);
  12541. const uniqueFormats = filter$6(matchedFormats, fmtName => !areSimilarFormats(editor, fmtName, name));
  12542. if (uniqueFormats.length > 0) {
  12543. const clonedFormatNode = formatNode.cloneNode(false);
  12544. dom.add(caretContainer, clonedFormatNode);
  12545. formatter.remove(name, vars, clonedFormatNode, similar);
  12546. dom.remove(clonedFormatNode);
  12547. return Optional.some(clonedFormatNode);
  12548. } else {
  12549. return Optional.none();
  12550. }
  12551. };
  12552. const applyCaretFormat = (editor, name, vars) => {
  12553. let caretContainer, textNode;
  12554. const selection = editor.selection;
  12555. const selectionRng = selection.getRng();
  12556. let offset = selectionRng.startOffset;
  12557. const container = selectionRng.startContainer;
  12558. const text = container.nodeValue;
  12559. caretContainer = getParentCaretContainer(editor.getBody(), selection.getStart());
  12560. if (caretContainer) {
  12561. textNode = findFirstTextNode(caretContainer);
  12562. }
  12563. const wordcharRegex = /[^\s\u00a0\u00ad\u200b\ufeff]/;
  12564. if (text && offset > 0 && offset < text.length && wordcharRegex.test(text.charAt(offset)) && wordcharRegex.test(text.charAt(offset - 1))) {
  12565. const bookmark = selection.getBookmark();
  12566. selectionRng.collapse(true);
  12567. let rng = expandRng(editor, selectionRng, editor.formatter.get(name));
  12568. rng = split(rng);
  12569. editor.formatter.apply(name, vars, rng);
  12570. selection.moveToBookmark(bookmark);
  12571. } else {
  12572. if (!caretContainer || textNode.nodeValue !== ZWSP) {
  12573. caretContainer = importNode(editor.getDoc(), createCaretContainer(true).dom);
  12574. textNode = caretContainer.firstChild;
  12575. selectionRng.insertNode(caretContainer);
  12576. offset = 1;
  12577. editor.formatter.apply(name, vars, caretContainer);
  12578. } else {
  12579. editor.formatter.apply(name, vars, caretContainer);
  12580. }
  12581. selection.setCursorLocation(textNode, offset);
  12582. }
  12583. };
  12584. const removeCaretFormat = (editor, name, vars, similar) => {
  12585. const dom = editor.dom;
  12586. const selection = editor.selection;
  12587. let hasContentAfter, node, formatNode;
  12588. const parents = [];
  12589. const rng = selection.getRng();
  12590. const container = rng.startContainer;
  12591. const offset = rng.startOffset;
  12592. node = container;
  12593. if (container.nodeType === 3) {
  12594. if (offset !== container.nodeValue.length) {
  12595. hasContentAfter = true;
  12596. }
  12597. node = node.parentNode;
  12598. }
  12599. while (node) {
  12600. if (matchNode(editor, node, name, vars, similar)) {
  12601. formatNode = node;
  12602. break;
  12603. }
  12604. if (node.nextSibling) {
  12605. hasContentAfter = true;
  12606. }
  12607. parents.push(node);
  12608. node = node.parentNode;
  12609. }
  12610. if (!formatNode) {
  12611. return;
  12612. }
  12613. if (hasContentAfter) {
  12614. const bookmark = selection.getBookmark();
  12615. rng.collapse(true);
  12616. let expandedRng = expandRng(editor, rng, editor.formatter.get(name), true);
  12617. expandedRng = split(expandedRng);
  12618. editor.formatter.remove(name, vars, expandedRng, similar);
  12619. selection.moveToBookmark(bookmark);
  12620. } else {
  12621. const caretContainer = getParentCaretContainer(editor.getBody(), formatNode);
  12622. const newCaretContainer = createCaretContainer(false).dom;
  12623. insertCaretContainerNode(editor, newCaretContainer, caretContainer !== null ? caretContainer : formatNode);
  12624. const cleanedFormatNode = cleanFormatNode(editor, newCaretContainer, formatNode, name, vars, similar);
  12625. const caretTextNode = insertFormatNodesIntoCaretContainer(parents.concat(cleanedFormatNode.toArray()), newCaretContainer);
  12626. removeCaretContainerNode(editor, caretContainer, false);
  12627. selection.setCursorLocation(caretTextNode, 1);
  12628. if (dom.isEmpty(formatNode)) {
  12629. dom.remove(formatNode);
  12630. }
  12631. }
  12632. };
  12633. const disableCaretContainer = (editor, keyCode) => {
  12634. const selection = editor.selection, body = editor.getBody();
  12635. removeCaretContainer(editor, null, false);
  12636. if ((keyCode === 8 || keyCode === 46) && selection.isCollapsed() && selection.getStart().innerHTML === ZWSP) {
  12637. removeCaretContainer(editor, getParentCaretContainer(body, selection.getStart()));
  12638. }
  12639. if (keyCode === 37 || keyCode === 39) {
  12640. removeCaretContainer(editor, getParentCaretContainer(body, selection.getStart()));
  12641. }
  12642. };
  12643. const setup$u = editor => {
  12644. editor.on('mouseup keydown', e => {
  12645. disableCaretContainer(editor, e.keyCode);
  12646. });
  12647. };
  12648. const replaceWithCaretFormat = (targetNode, formatNodes) => {
  12649. const caretContainer = createCaretContainer(false);
  12650. const innerMost = insertFormatNodesIntoCaretContainer(formatNodes, caretContainer.dom);
  12651. before$3(SugarElement.fromDom(targetNode), caretContainer);
  12652. remove$6(SugarElement.fromDom(targetNode));
  12653. return CaretPosition(innerMost, 0);
  12654. };
  12655. const isFormatElement = (editor, element) => {
  12656. const inlineElements = editor.schema.getTextInlineElements();
  12657. return has$2(inlineElements, name(element)) && !isCaretNode(element.dom) && !isBogus$2(element.dom);
  12658. };
  12659. const isEmptyCaretFormatElement = element => {
  12660. return isCaretNode(element.dom) && isCaretContainerEmpty(element.dom);
  12661. };
  12662. const postProcessHooks = {};
  12663. const filter$2 = filter$4;
  12664. const each$9 = each$d;
  12665. const addPostProcessHook = (name, hook) => {
  12666. const hooks = postProcessHooks[name];
  12667. if (!hooks) {
  12668. postProcessHooks[name] = [];
  12669. }
  12670. postProcessHooks[name].push(hook);
  12671. };
  12672. const postProcess$1 = (name, editor) => {
  12673. each$9(postProcessHooks[name], hook => {
  12674. hook(editor);
  12675. });
  12676. };
  12677. addPostProcessHook('pre', editor => {
  12678. const rng = editor.selection.getRng();
  12679. let blocks;
  12680. const hasPreSibling = pre => {
  12681. return isPre(pre.previousSibling) && indexOf(blocks, pre.previousSibling) !== -1;
  12682. };
  12683. const joinPre = (pre1, pre2) => {
  12684. const sPre2 = SugarElement.fromDom(pre2);
  12685. const doc = documentOrOwner(sPre2).dom;
  12686. remove$6(sPre2);
  12687. append(SugarElement.fromDom(pre1), [
  12688. SugarElement.fromTag('br', doc),
  12689. SugarElement.fromTag('br', doc),
  12690. ...children(sPre2)
  12691. ]);
  12692. };
  12693. const isPre = matchNodeNames(['pre']);
  12694. if (!rng.collapsed) {
  12695. blocks = editor.selection.getSelectedBlocks();
  12696. each$9(filter$2(filter$2(blocks, isPre), hasPreSibling), pre => {
  12697. joinPre(pre.previousSibling, pre);
  12698. });
  12699. }
  12700. });
  12701. const each$8 = Tools.each;
  12702. const isElementNode$1 = node => isElement$6(node) && !isBookmarkNode$1(node) && !isCaretNode(node) && !isBogus$2(node);
  12703. const findElementSibling = (node, siblingName) => {
  12704. for (let sibling = node; sibling; sibling = sibling[siblingName]) {
  12705. if (isText$9(sibling) && isNotEmpty(sibling.data)) {
  12706. return node;
  12707. }
  12708. if (isElement$6(sibling) && !isBookmarkNode$1(sibling)) {
  12709. return sibling;
  12710. }
  12711. }
  12712. return node;
  12713. };
  12714. const mergeSiblingsNodes = (dom, prev, next) => {
  12715. const elementUtils = ElementUtils(dom);
  12716. if (prev && next) {
  12717. prev = findElementSibling(prev, 'previousSibling');
  12718. next = findElementSibling(next, 'nextSibling');
  12719. if (elementUtils.compare(prev, next)) {
  12720. for (let sibling = prev.nextSibling; sibling && sibling !== next;) {
  12721. const tmpSibling = sibling;
  12722. sibling = sibling.nextSibling;
  12723. prev.appendChild(tmpSibling);
  12724. }
  12725. dom.remove(next);
  12726. Tools.each(Tools.grep(next.childNodes), node => {
  12727. prev.appendChild(node);
  12728. });
  12729. return prev;
  12730. }
  12731. }
  12732. return next;
  12733. };
  12734. const mergeSiblings = (dom, format, vars, node) => {
  12735. if (node && format.merge_siblings !== false) {
  12736. const newNode = mergeSiblingsNodes(dom, getNonWhiteSpaceSibling(node), node);
  12737. mergeSiblingsNodes(dom, newNode, getNonWhiteSpaceSibling(newNode, true));
  12738. }
  12739. };
  12740. const clearChildStyles = (dom, format, node) => {
  12741. if (format.clear_child_styles) {
  12742. const selector = format.links ? '*:not(a)' : '*';
  12743. each$8(dom.select(selector, node), node => {
  12744. if (isElementNode$1(node)) {
  12745. each$8(format.styles, (value, name) => {
  12746. dom.setStyle(node, name, '');
  12747. });
  12748. }
  12749. });
  12750. }
  12751. };
  12752. const processChildElements = (node, filter, process) => {
  12753. each$8(node.childNodes, node => {
  12754. if (isElementNode$1(node)) {
  12755. if (filter(node)) {
  12756. process(node);
  12757. }
  12758. if (node.hasChildNodes()) {
  12759. processChildElements(node, filter, process);
  12760. }
  12761. }
  12762. });
  12763. };
  12764. const unwrapEmptySpan = (dom, node) => {
  12765. if (node.nodeName === 'SPAN' && dom.getAttribs(node).length === 0) {
  12766. dom.remove(node, true);
  12767. }
  12768. };
  12769. const hasStyle = (dom, name) => node => !!(node && getStyle(dom, node, name));
  12770. const applyStyle = (dom, name, value) => node => {
  12771. dom.setStyle(node, name, value);
  12772. if (node.getAttribute('style') === '') {
  12773. node.removeAttribute('style');
  12774. }
  12775. unwrapEmptySpan(dom, node);
  12776. };
  12777. const removeResult = Adt.generate([
  12778. { keep: [] },
  12779. { rename: ['name'] },
  12780. { removed: [] }
  12781. ]);
  12782. const MCE_ATTR_RE = /^(src|href|style)$/;
  12783. const each$7 = Tools.each;
  12784. const isEq$2 = isEq$5;
  12785. const isTableCellOrRow = node => /^(TR|TH|TD)$/.test(node.nodeName);
  12786. const isChildOfInlineParent = (dom, node, parent) => dom.isChildOf(node, parent) && node !== parent && !dom.isBlock(parent);
  12787. const getContainer = (ed, rng, start) => {
  12788. let container = rng[start ? 'startContainer' : 'endContainer'];
  12789. let offset = rng[start ? 'startOffset' : 'endOffset'];
  12790. if (isElement$6(container)) {
  12791. const lastIdx = container.childNodes.length - 1;
  12792. if (!start && offset) {
  12793. offset--;
  12794. }
  12795. container = container.childNodes[offset > lastIdx ? lastIdx : offset];
  12796. }
  12797. if (isText$9(container) && start && offset >= container.nodeValue.length) {
  12798. container = new DomTreeWalker(container, ed.getBody()).next() || container;
  12799. }
  12800. if (isText$9(container) && !start && offset === 0) {
  12801. container = new DomTreeWalker(container, ed.getBody()).prev() || container;
  12802. }
  12803. return container;
  12804. };
  12805. const normalizeTableSelection = (node, start) => {
  12806. const prop = start ? 'firstChild' : 'lastChild';
  12807. if (isTableCellOrRow(node) && node[prop]) {
  12808. const childNode = node[prop];
  12809. if (node.nodeName === 'TR') {
  12810. return childNode[prop] || childNode;
  12811. } else {
  12812. return childNode;
  12813. }
  12814. }
  12815. return node;
  12816. };
  12817. const wrap$1 = (dom, node, name, attrs) => {
  12818. const wrapper = dom.create(name, attrs);
  12819. node.parentNode.insertBefore(wrapper, node);
  12820. wrapper.appendChild(node);
  12821. return wrapper;
  12822. };
  12823. const wrapWithSiblings = (dom, node, next, name, attrs) => {
  12824. const start = SugarElement.fromDom(node);
  12825. const wrapper = SugarElement.fromDom(dom.create(name, attrs));
  12826. const siblings = next ? nextSiblings(start) : prevSiblings(start);
  12827. append(wrapper, siblings);
  12828. if (next) {
  12829. before$3(start, wrapper);
  12830. prepend(wrapper, start);
  12831. } else {
  12832. after$4(start, wrapper);
  12833. append$1(wrapper, start);
  12834. }
  12835. return wrapper.dom;
  12836. };
  12837. const isColorFormatAndAnchor = (node, format) => format.links && node.nodeName === 'A';
  12838. const removeNode = (ed, node, format) => {
  12839. const parentNode = node.parentNode;
  12840. let rootBlockElm;
  12841. const dom = ed.dom;
  12842. const forcedRootBlock = getForcedRootBlock(ed);
  12843. if (isBlockFormat(format)) {
  12844. if (parentNode === dom.getRoot()) {
  12845. if (!format.list_block || !isEq$2(node, format.list_block)) {
  12846. each$f(from(node.childNodes), node => {
  12847. if (isValid(ed, forcedRootBlock, node.nodeName.toLowerCase())) {
  12848. if (!rootBlockElm) {
  12849. rootBlockElm = wrap$1(dom, node, forcedRootBlock);
  12850. dom.setAttribs(rootBlockElm, getForcedRootBlockAttrs(ed));
  12851. } else {
  12852. rootBlockElm.appendChild(node);
  12853. }
  12854. } else {
  12855. rootBlockElm = null;
  12856. }
  12857. });
  12858. }
  12859. }
  12860. }
  12861. if (isMixedFormat(format) && !isEq$2(format.inline, node)) {
  12862. return;
  12863. }
  12864. dom.remove(node, true);
  12865. };
  12866. const removeFormatInternal = (ed, format, vars, node, compareNode) => {
  12867. let stylesModified;
  12868. const dom = ed.dom;
  12869. if (!matchName(dom, node, format) && !isColorFormatAndAnchor(node, format)) {
  12870. return removeResult.keep();
  12871. }
  12872. const elm = node;
  12873. if (isInlineFormat(format) && format.remove === 'all' && isArray$1(format.preserve_attributes)) {
  12874. const attrsToPreserve = filter$6(dom.getAttribs(elm), attr => contains$2(format.preserve_attributes, attr.name.toLowerCase()));
  12875. dom.removeAllAttribs(elm);
  12876. each$f(attrsToPreserve, attr => dom.setAttrib(elm, attr.name, attr.value));
  12877. if (attrsToPreserve.length > 0) {
  12878. return removeResult.rename('span');
  12879. }
  12880. }
  12881. if (format.remove !== 'all') {
  12882. each$7(format.styles, (value, name) => {
  12883. value = normalizeStyleValue(replaceVars(value, vars), name + '');
  12884. if (isNumber(name)) {
  12885. name = value;
  12886. compareNode = null;
  12887. }
  12888. if (format.remove_similar || (!compareNode || isEq$2(getStyle(dom, compareNode, name), value))) {
  12889. dom.setStyle(elm, name, '');
  12890. }
  12891. stylesModified = true;
  12892. });
  12893. if (stylesModified && dom.getAttrib(elm, 'style') === '') {
  12894. elm.removeAttribute('style');
  12895. elm.removeAttribute('data-mce-style');
  12896. }
  12897. each$7(format.attributes, (value, name) => {
  12898. let valueOut;
  12899. value = replaceVars(value, vars);
  12900. if (isNumber(name)) {
  12901. name = value;
  12902. compareNode = null;
  12903. }
  12904. if (format.remove_similar || (!compareNode || isEq$2(dom.getAttrib(compareNode, name), value))) {
  12905. if (name === 'class') {
  12906. value = dom.getAttrib(elm, name);
  12907. if (value) {
  12908. valueOut = '';
  12909. each$f(value.split(/\s+/), cls => {
  12910. if (/mce\-\w+/.test(cls)) {
  12911. valueOut += (valueOut ? ' ' : '') + cls;
  12912. }
  12913. });
  12914. if (valueOut) {
  12915. dom.setAttrib(elm, name, valueOut);
  12916. return;
  12917. }
  12918. }
  12919. }
  12920. if (MCE_ATTR_RE.test(name)) {
  12921. elm.removeAttribute('data-mce-' + name);
  12922. }
  12923. if (name === 'style' && matchNodeNames(['li'])(elm) && dom.getStyle(elm, 'list-style-type') === 'none') {
  12924. elm.removeAttribute(name);
  12925. dom.setStyle(elm, 'list-style-type', 'none');
  12926. return;
  12927. }
  12928. if (name === 'class') {
  12929. elm.removeAttribute('className');
  12930. }
  12931. elm.removeAttribute(name);
  12932. }
  12933. });
  12934. each$7(format.classes, value => {
  12935. value = replaceVars(value, vars);
  12936. if (!compareNode || dom.hasClass(compareNode, value)) {
  12937. dom.removeClass(elm, value);
  12938. }
  12939. });
  12940. const attrs = dom.getAttribs(elm);
  12941. for (let i = 0; i < attrs.length; i++) {
  12942. const attrName = attrs[i].nodeName;
  12943. if (attrName.indexOf('_') !== 0 && attrName.indexOf('data-') !== 0) {
  12944. return removeResult.keep();
  12945. }
  12946. }
  12947. }
  12948. if (format.remove !== 'none') {
  12949. removeNode(ed, elm, format);
  12950. return removeResult.removed();
  12951. }
  12952. return removeResult.keep();
  12953. };
  12954. const removeFormat$1 = (ed, format, vars, node, compareNode) => removeFormatInternal(ed, format, vars, node, compareNode).fold(never, newName => {
  12955. ed.dom.rename(node, newName);
  12956. return true;
  12957. }, always);
  12958. const findFormatRoot = (editor, container, name, vars, similar) => {
  12959. let formatRoot;
  12960. each$f(getParents$2(editor.dom, container.parentNode).reverse(), parent => {
  12961. if (!formatRoot && parent.id !== '_start' && parent.id !== '_end') {
  12962. const format = matchNode(editor, parent, name, vars, similar);
  12963. if (format && format.split !== false) {
  12964. formatRoot = parent;
  12965. }
  12966. }
  12967. });
  12968. return formatRoot;
  12969. };
  12970. const removeFormatFromClone = (editor, format, vars, clone) => removeFormatInternal(editor, format, vars, clone, clone).fold(constant(clone), newName => {
  12971. const fragment = editor.dom.createFragment();
  12972. fragment.appendChild(clone);
  12973. return editor.dom.rename(clone, newName);
  12974. }, constant(null));
  12975. const wrapAndSplit = (editor, formatList, formatRoot, container, target, split, format, vars) => {
  12976. let clone, lastClone, firstClone;
  12977. const dom = editor.dom;
  12978. if (formatRoot) {
  12979. const formatRootParent = formatRoot.parentNode;
  12980. for (let parent = container.parentNode; parent && parent !== formatRootParent; parent = parent.parentNode) {
  12981. clone = dom.clone(parent, false);
  12982. for (let i = 0; i < formatList.length; i++) {
  12983. clone = removeFormatFromClone(editor, formatList[i], vars, clone);
  12984. if (clone === null) {
  12985. break;
  12986. }
  12987. }
  12988. if (clone) {
  12989. if (lastClone) {
  12990. clone.appendChild(lastClone);
  12991. }
  12992. if (!firstClone) {
  12993. firstClone = clone;
  12994. }
  12995. lastClone = clone;
  12996. }
  12997. }
  12998. if (split && (!format.mixed || !dom.isBlock(formatRoot))) {
  12999. container = dom.split(formatRoot, container);
  13000. }
  13001. if (lastClone) {
  13002. target.parentNode.insertBefore(lastClone, target);
  13003. firstClone.appendChild(target);
  13004. if (isInlineFormat(format)) {
  13005. mergeSiblings(dom, format, vars, lastClone);
  13006. }
  13007. }
  13008. }
  13009. return container;
  13010. };
  13011. const remove$2 = (ed, name, vars, node, similar) => {
  13012. const formatList = ed.formatter.get(name);
  13013. const format = formatList[0];
  13014. let contentEditable = true;
  13015. const dom = ed.dom;
  13016. const selection = ed.selection;
  13017. const splitToFormatRoot = container => {
  13018. const formatRoot = findFormatRoot(ed, container, name, vars, similar);
  13019. return wrapAndSplit(ed, formatList, formatRoot, container, container, true, format, vars);
  13020. };
  13021. const isRemoveBookmarkNode = node => isBookmarkNode$1(node) && isElement$6(node) && (node.id === '_start' || node.id === '_end');
  13022. const removeNodeFormat = node => exists(formatList, fmt => removeFormat$1(ed, fmt, vars, node, node));
  13023. const process = node => {
  13024. let lastContentEditable = true;
  13025. let hasContentEditableState = false;
  13026. if (isElement$6(node) && dom.getContentEditable(node)) {
  13027. lastContentEditable = contentEditable;
  13028. contentEditable = dom.getContentEditable(node) === 'true';
  13029. hasContentEditableState = true;
  13030. }
  13031. const children = from(node.childNodes);
  13032. if (contentEditable && !hasContentEditableState) {
  13033. const removed = removeNodeFormat(node);
  13034. const currentNodeMatches = removed || exists(formatList, f => matchName(dom, node, f));
  13035. const parentNode = node.parentNode;
  13036. if (!currentNodeMatches && isNonNullable(parentNode) && shouldExpandToSelector(format)) {
  13037. removeNodeFormat(parentNode);
  13038. }
  13039. }
  13040. if (format.deep) {
  13041. if (children.length) {
  13042. for (let i = 0; i < children.length; i++) {
  13043. process(children[i]);
  13044. }
  13045. if (hasContentEditableState) {
  13046. contentEditable = lastContentEditable;
  13047. }
  13048. }
  13049. }
  13050. const textDecorations = [
  13051. 'underline',
  13052. 'line-through',
  13053. 'overline'
  13054. ];
  13055. each$f(textDecorations, decoration => {
  13056. if (isElement$6(node) && ed.dom.getStyle(node, 'text-decoration') === decoration && node.parentNode && getTextDecoration(dom, node.parentNode) === decoration) {
  13057. removeFormat$1(ed, {
  13058. deep: false,
  13059. exact: true,
  13060. inline: 'span',
  13061. styles: { textDecoration: decoration }
  13062. }, null, node);
  13063. }
  13064. });
  13065. };
  13066. const unwrap = start => {
  13067. const node = dom.get(start ? '_start' : '_end');
  13068. let out = node[start ? 'firstChild' : 'lastChild'];
  13069. if (isRemoveBookmarkNode(out)) {
  13070. out = out[start ? 'firstChild' : 'lastChild'];
  13071. }
  13072. if (isText$9(out) && out.data.length === 0) {
  13073. out = start ? node.previousSibling || node.nextSibling : node.nextSibling || node.previousSibling;
  13074. }
  13075. dom.remove(node, true);
  13076. return out;
  13077. };
  13078. const removeRngStyle = rng => {
  13079. let startContainer, endContainer;
  13080. let expandedRng = expandRng(ed, rng, formatList, rng.collapsed);
  13081. if (format.split) {
  13082. expandedRng = split(expandedRng);
  13083. startContainer = getContainer(ed, expandedRng, true);
  13084. endContainer = getContainer(ed, expandedRng);
  13085. if (startContainer !== endContainer) {
  13086. startContainer = normalizeTableSelection(startContainer, true);
  13087. endContainer = normalizeTableSelection(endContainer, false);
  13088. if (isChildOfInlineParent(dom, startContainer, endContainer)) {
  13089. const marker = Optional.from(startContainer.firstChild).getOr(startContainer);
  13090. splitToFormatRoot(wrapWithSiblings(dom, marker, true, 'span', {
  13091. 'id': '_start',
  13092. 'data-mce-type': 'bookmark'
  13093. }));
  13094. unwrap(true);
  13095. return;
  13096. }
  13097. if (isChildOfInlineParent(dom, endContainer, startContainer)) {
  13098. const marker = Optional.from(endContainer.lastChild).getOr(endContainer);
  13099. splitToFormatRoot(wrapWithSiblings(dom, marker, false, 'span', {
  13100. 'id': '_end',
  13101. 'data-mce-type': 'bookmark'
  13102. }));
  13103. unwrap(false);
  13104. return;
  13105. }
  13106. startContainer = wrap$1(dom, startContainer, 'span', {
  13107. 'id': '_start',
  13108. 'data-mce-type': 'bookmark'
  13109. });
  13110. endContainer = wrap$1(dom, endContainer, 'span', {
  13111. 'id': '_end',
  13112. 'data-mce-type': 'bookmark'
  13113. });
  13114. const newRng = dom.createRng();
  13115. newRng.setStartAfter(startContainer);
  13116. newRng.setEndBefore(endContainer);
  13117. walk$3(dom, newRng, nodes => {
  13118. each$f(nodes, n => {
  13119. if (!isBookmarkNode$1(n) && !isBookmarkNode$1(n.parentNode)) {
  13120. splitToFormatRoot(n);
  13121. }
  13122. });
  13123. });
  13124. splitToFormatRoot(startContainer);
  13125. splitToFormatRoot(endContainer);
  13126. startContainer = unwrap(true);
  13127. endContainer = unwrap();
  13128. } else {
  13129. startContainer = endContainer = splitToFormatRoot(startContainer);
  13130. }
  13131. expandedRng.startContainer = startContainer.parentNode ? startContainer.parentNode : startContainer;
  13132. expandedRng.startOffset = dom.nodeIndex(startContainer);
  13133. expandedRng.endContainer = endContainer.parentNode ? endContainer.parentNode : endContainer;
  13134. expandedRng.endOffset = dom.nodeIndex(endContainer) + 1;
  13135. }
  13136. walk$3(dom, expandedRng, nodes => {
  13137. each$f(nodes, process);
  13138. });
  13139. };
  13140. if (node) {
  13141. if (isNode(node)) {
  13142. const rng = dom.createRng();
  13143. rng.setStartBefore(node);
  13144. rng.setEndAfter(node);
  13145. removeRngStyle(rng);
  13146. } else {
  13147. removeRngStyle(node);
  13148. }
  13149. fireFormatRemove(ed, name, node, vars);
  13150. return;
  13151. }
  13152. if (dom.getContentEditable(selection.getNode()) === 'false') {
  13153. node = selection.getNode();
  13154. for (let i = 0; i < formatList.length; i++) {
  13155. if (formatList[i].ceFalseOverride) {
  13156. if (removeFormat$1(ed, formatList[i], vars, node, node)) {
  13157. break;
  13158. }
  13159. }
  13160. }
  13161. fireFormatRemove(ed, name, node, vars);
  13162. return;
  13163. }
  13164. if (!selection.isCollapsed() || !isInlineFormat(format) || getCellsFromEditor(ed).length) {
  13165. preserve(selection, true, () => {
  13166. runOnRanges(ed, removeRngStyle);
  13167. });
  13168. if (isInlineFormat(format) && match$2(ed, name, vars, selection.getStart())) {
  13169. moveStart(dom, selection, selection.getRng());
  13170. }
  13171. ed.nodeChanged();
  13172. } else {
  13173. removeCaretFormat(ed, name, vars, similar);
  13174. }
  13175. fireFormatRemove(ed, name, node, vars);
  13176. };
  13177. const each$6 = Tools.each;
  13178. const mergeTextDecorationsAndColor = (dom, format, vars, node) => {
  13179. const processTextDecorationsAndColor = n => {
  13180. if (n.nodeType === 1 && n.parentNode && n.parentNode.nodeType === 1) {
  13181. const textDecoration = getTextDecoration(dom, n.parentNode);
  13182. if (dom.getStyle(n, 'color') && textDecoration) {
  13183. dom.setStyle(n, 'text-decoration', textDecoration);
  13184. } else if (dom.getStyle(n, 'text-decoration') === textDecoration) {
  13185. dom.setStyle(n, 'text-decoration', null);
  13186. }
  13187. }
  13188. };
  13189. if (format.styles && (format.styles.color || format.styles.textDecoration)) {
  13190. Tools.walk(node, processTextDecorationsAndColor, 'childNodes');
  13191. processTextDecorationsAndColor(node);
  13192. }
  13193. };
  13194. const mergeBackgroundColorAndFontSize = (dom, format, vars, node) => {
  13195. if (format.styles && format.styles.backgroundColor) {
  13196. processChildElements(node, hasStyle(dom, 'fontSize'), applyStyle(dom, 'backgroundColor', replaceVars(format.styles.backgroundColor, vars)));
  13197. }
  13198. };
  13199. const mergeSubSup = (dom, format, vars, node) => {
  13200. if (isInlineFormat(format) && (format.inline === 'sub' || format.inline === 'sup')) {
  13201. processChildElements(node, hasStyle(dom, 'fontSize'), applyStyle(dom, 'fontSize', ''));
  13202. dom.remove(dom.select(format.inline === 'sup' ? 'sub' : 'sup', node), true);
  13203. }
  13204. };
  13205. const mergeWithChildren = (editor, formatList, vars, node) => {
  13206. each$6(formatList, format => {
  13207. if (isInlineFormat(format)) {
  13208. each$6(editor.dom.select(format.inline, node), child => {
  13209. if (!isElementNode$1(child)) {
  13210. return;
  13211. }
  13212. removeFormat$1(editor, format, vars, child, format.exact ? child : null);
  13213. });
  13214. }
  13215. clearChildStyles(editor.dom, format, node);
  13216. });
  13217. };
  13218. const mergeWithParents = (editor, format, name, vars, node) => {
  13219. if (matchNode(editor, node.parentNode, name, vars)) {
  13220. if (removeFormat$1(editor, format, vars, node)) {
  13221. return;
  13222. }
  13223. }
  13224. if (format.merge_with_parents) {
  13225. editor.dom.getParent(node.parentNode, parent => {
  13226. if (matchNode(editor, parent, name, vars)) {
  13227. removeFormat$1(editor, format, vars, node);
  13228. return true;
  13229. }
  13230. });
  13231. }
  13232. };
  13233. const each$5 = Tools.each;
  13234. const isElementNode = node => {
  13235. return isElement$6(node) && !isBookmarkNode$1(node) && !isCaretNode(node) && !isBogus$2(node);
  13236. };
  13237. const canFormatBR = (editor, format, node, parentName) => {
  13238. if (canFormatEmptyLines(editor) && isInlineFormat(format)) {
  13239. const validBRParentElements = getTextRootBlockElements(editor.schema);
  13240. const hasCaretNodeSibling = sibling(SugarElement.fromDom(node), sibling => isCaretNode(sibling.dom));
  13241. return hasNonNullableKey(validBRParentElements, parentName) && isEmpty$2(SugarElement.fromDom(node.parentNode), false) && !hasCaretNodeSibling;
  13242. } else {
  13243. return false;
  13244. }
  13245. };
  13246. const applyFormat$1 = (ed, name, vars, node) => {
  13247. const formatList = ed.formatter.get(name);
  13248. const format = formatList[0];
  13249. const isCollapsed = !node && ed.selection.isCollapsed();
  13250. const dom = ed.dom;
  13251. const selection = ed.selection;
  13252. const setElementFormat = (elm, fmt = format) => {
  13253. if (isFunction(fmt.onformat)) {
  13254. fmt.onformat(elm, fmt, vars, node);
  13255. }
  13256. each$5(fmt.styles, (value, name) => {
  13257. dom.setStyle(elm, name, replaceVars(value, vars));
  13258. });
  13259. if (fmt.styles) {
  13260. const styleVal = dom.getAttrib(elm, 'style');
  13261. if (styleVal) {
  13262. dom.setAttrib(elm, 'data-mce-style', styleVal);
  13263. }
  13264. }
  13265. each$5(fmt.attributes, (value, name) => {
  13266. dom.setAttrib(elm, name, replaceVars(value, vars));
  13267. });
  13268. each$5(fmt.classes, value => {
  13269. value = replaceVars(value, vars);
  13270. if (!dom.hasClass(elm, value)) {
  13271. dom.addClass(elm, value);
  13272. }
  13273. });
  13274. };
  13275. const applyNodeStyle = (formatList, node) => {
  13276. let found = false;
  13277. each$5(formatList, format => {
  13278. if (!isSelectorFormat(format)) {
  13279. return false;
  13280. }
  13281. if (isNonNullable(format.collapsed) && format.collapsed !== isCollapsed) {
  13282. return;
  13283. }
  13284. if (dom.is(node, format.selector) && !isCaretNode(node)) {
  13285. setElementFormat(node, format);
  13286. found = true;
  13287. return false;
  13288. }
  13289. });
  13290. return found;
  13291. };
  13292. const createWrapElement = wrapName => {
  13293. if (isString(wrapName)) {
  13294. const wrapElm = dom.create(wrapName);
  13295. setElementFormat(wrapElm);
  13296. return wrapElm;
  13297. } else {
  13298. return null;
  13299. }
  13300. };
  13301. const applyRngStyle = (dom, rng, nodeSpecific) => {
  13302. const newWrappers = [];
  13303. let contentEditable = true;
  13304. const wrapName = format.inline || format.block;
  13305. const wrapElm = createWrapElement(wrapName);
  13306. walk$3(dom, rng, nodes => {
  13307. let currentWrapElm;
  13308. const process = node => {
  13309. let hasContentEditableState = false;
  13310. let lastContentEditable = contentEditable;
  13311. const nodeName = node.nodeName.toLowerCase();
  13312. const parentNode = node.parentNode;
  13313. const parentName = parentNode.nodeName.toLowerCase();
  13314. if (isElement$6(node) && dom.getContentEditable(node)) {
  13315. lastContentEditable = contentEditable;
  13316. contentEditable = dom.getContentEditable(node) === 'true';
  13317. hasContentEditableState = true;
  13318. }
  13319. if (isBr$6(node) && !canFormatBR(ed, format, node, parentName)) {
  13320. currentWrapElm = null;
  13321. if (isBlockFormat(format)) {
  13322. dom.remove(node);
  13323. }
  13324. return;
  13325. }
  13326. if (isBlockFormat(format) && format.wrapper && matchNode(ed, node, name, vars)) {
  13327. currentWrapElm = null;
  13328. return;
  13329. }
  13330. if (contentEditable && !hasContentEditableState && isBlockFormat(format) && !format.wrapper && isTextBlock$1(ed, nodeName) && isValid(ed, parentName, wrapName)) {
  13331. const elm = dom.rename(node, wrapName);
  13332. setElementFormat(elm);
  13333. newWrappers.push(elm);
  13334. currentWrapElm = null;
  13335. return;
  13336. }
  13337. if (isSelectorFormat(format)) {
  13338. let found = applyNodeStyle(formatList, node);
  13339. if (!found && isNonNullable(parentNode) && shouldExpandToSelector(format)) {
  13340. found = applyNodeStyle(formatList, parentNode);
  13341. }
  13342. if (!isInlineFormat(format) || found) {
  13343. currentWrapElm = null;
  13344. return;
  13345. }
  13346. }
  13347. if (contentEditable && !hasContentEditableState && isValid(ed, wrapName, nodeName) && isValid(ed, parentName, wrapName) && !(!nodeSpecific && isText$9(node) && isZwsp(node.data)) && !isCaretNode(node) && (!isInlineFormat(format) || !dom.isBlock(node))) {
  13348. if (!currentWrapElm) {
  13349. currentWrapElm = dom.clone(wrapElm, false);
  13350. node.parentNode.insertBefore(currentWrapElm, node);
  13351. newWrappers.push(currentWrapElm);
  13352. }
  13353. currentWrapElm.appendChild(node);
  13354. } else {
  13355. currentWrapElm = null;
  13356. each$f(from(node.childNodes), process);
  13357. if (hasContentEditableState) {
  13358. contentEditable = lastContentEditable;
  13359. }
  13360. currentWrapElm = null;
  13361. }
  13362. };
  13363. each$f(nodes, process);
  13364. });
  13365. if (format.links === true) {
  13366. each$f(newWrappers, node => {
  13367. const process = node => {
  13368. if (node.nodeName === 'A') {
  13369. setElementFormat(node, format);
  13370. }
  13371. each$f(from(node.childNodes), process);
  13372. };
  13373. process(node);
  13374. });
  13375. }
  13376. each$f(newWrappers, node => {
  13377. const getChildCount = node => {
  13378. let count = 0;
  13379. each$f(node.childNodes, node => {
  13380. if (!isEmptyTextNode$1(node) && !isBookmarkNode$1(node)) {
  13381. count++;
  13382. }
  13383. });
  13384. return count;
  13385. };
  13386. const mergeStyles = node => {
  13387. const childElement = find$2(node.childNodes, isElementNode).filter(child => matchName(dom, child, format));
  13388. return childElement.map(child => {
  13389. const clone = dom.clone(child, false);
  13390. setElementFormat(clone);
  13391. dom.replace(clone, node, true);
  13392. dom.remove(child, true);
  13393. return clone;
  13394. }).getOr(node);
  13395. };
  13396. const childCount = getChildCount(node);
  13397. if ((newWrappers.length > 1 || !dom.isBlock(node)) && childCount === 0) {
  13398. dom.remove(node, true);
  13399. return;
  13400. }
  13401. if (isInlineFormat(format) || isBlockFormat(format) && format.wrapper) {
  13402. if (!format.exact && childCount === 1) {
  13403. node = mergeStyles(node);
  13404. }
  13405. mergeWithChildren(ed, formatList, vars, node);
  13406. mergeWithParents(ed, format, name, vars, node);
  13407. mergeBackgroundColorAndFontSize(dom, format, vars, node);
  13408. mergeTextDecorationsAndColor(dom, format, vars, node);
  13409. mergeSubSup(dom, format, vars, node);
  13410. mergeSiblings(dom, format, vars, node);
  13411. }
  13412. });
  13413. };
  13414. if (dom.getContentEditable(selection.getNode()) === 'false') {
  13415. node = selection.getNode();
  13416. for (let i = 0, l = formatList.length; i < l; i++) {
  13417. const formatItem = formatList[i];
  13418. if (formatItem.ceFalseOverride && isSelectorFormat(formatItem) && dom.is(node, formatItem.selector)) {
  13419. setElementFormat(node, formatItem);
  13420. break;
  13421. }
  13422. }
  13423. fireFormatApply(ed, name, node, vars);
  13424. return;
  13425. }
  13426. if (format) {
  13427. if (node) {
  13428. if (isNode(node)) {
  13429. if (!applyNodeStyle(formatList, node)) {
  13430. const rng = dom.createRng();
  13431. rng.setStartBefore(node);
  13432. rng.setEndAfter(node);
  13433. applyRngStyle(dom, expandRng(ed, rng, formatList), true);
  13434. }
  13435. } else {
  13436. applyRngStyle(dom, node, true);
  13437. }
  13438. } else {
  13439. if (!isCollapsed || !isInlineFormat(format) || getCellsFromEditor(ed).length) {
  13440. selection.setRng(normalize(selection.getRng()));
  13441. preserve(selection, true, () => {
  13442. runOnRanges(ed, (selectionRng, fake) => {
  13443. const expandedRng = fake ? selectionRng : expandRng(ed, selectionRng, formatList);
  13444. applyRngStyle(dom, expandedRng, false);
  13445. });
  13446. });
  13447. moveStart(dom, selection, selection.getRng());
  13448. ed.nodeChanged();
  13449. } else {
  13450. applyCaretFormat(ed, name, vars);
  13451. }
  13452. }
  13453. postProcess$1(name, ed);
  13454. }
  13455. fireFormatApply(ed, name, node, vars);
  13456. };
  13457. const hasVars = value => has$2(value, 'vars');
  13458. const setup$t = (registeredFormatListeners, editor) => {
  13459. registeredFormatListeners.set({});
  13460. editor.on('NodeChange', e => {
  13461. updateAndFireChangeCallbacks(editor, e.element, registeredFormatListeners.get());
  13462. });
  13463. editor.on('FormatApply FormatRemove', e => {
  13464. 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));
  13465. updateAndFireChangeCallbacks(editor, element, registeredFormatListeners.get());
  13466. });
  13467. };
  13468. const fallbackElement = editor => editor.selection.getStart();
  13469. const matchingNode = (editor, parents, format, similar, vars) => {
  13470. const isMatchingNode = node => {
  13471. const matchingFormat = editor.formatter.matchNode(node, format, vars !== null && vars !== void 0 ? vars : {}, similar);
  13472. return !isUndefined(matchingFormat);
  13473. };
  13474. const isUnableToMatch = node => {
  13475. if (matchesUnInheritedFormatSelector(editor, node, format)) {
  13476. return true;
  13477. } else {
  13478. if (!similar) {
  13479. return isNonNullable(editor.formatter.matchNode(node, format, vars, true));
  13480. } else {
  13481. return false;
  13482. }
  13483. }
  13484. };
  13485. return findUntil$1(parents, isMatchingNode, isUnableToMatch);
  13486. };
  13487. const getParents = (editor, elm) => {
  13488. const element = elm !== null && elm !== void 0 ? elm : fallbackElement(editor);
  13489. return filter$6(getParents$2(editor.dom, element), node => isElement$6(node) && !isBogus$2(node));
  13490. };
  13491. const updateAndFireChangeCallbacks = (editor, elm, registeredCallbacks) => {
  13492. const parents = getParents(editor, elm);
  13493. each$e(registeredCallbacks, (data, format) => {
  13494. const runIfChanged = spec => {
  13495. const match = matchingNode(editor, parents, format, spec.similar, hasVars(spec) ? spec.vars : undefined);
  13496. const isSet = match.isSome();
  13497. if (spec.state.get() !== isSet) {
  13498. spec.state.set(isSet);
  13499. const node = match.getOr(elm);
  13500. if (hasVars(spec)) {
  13501. spec.callback(isSet, {
  13502. node,
  13503. format,
  13504. parents
  13505. });
  13506. } else {
  13507. each$f(spec.callbacks, callback => callback(isSet, {
  13508. node,
  13509. format,
  13510. parents
  13511. }));
  13512. }
  13513. }
  13514. };
  13515. each$f([
  13516. data.withSimilar,
  13517. data.withoutSimilar
  13518. ], runIfChanged);
  13519. each$f(data.withVars, runIfChanged);
  13520. });
  13521. };
  13522. const addListeners = (editor, registeredFormatListeners, formats, callback, similar, vars) => {
  13523. const formatChangeItems = registeredFormatListeners.get();
  13524. each$f(formats.split(','), format => {
  13525. const group = get$a(formatChangeItems, format).getOrThunk(() => {
  13526. const base = {
  13527. withSimilar: {
  13528. state: Cell(false),
  13529. similar: true,
  13530. callbacks: []
  13531. },
  13532. withoutSimilar: {
  13533. state: Cell(false),
  13534. similar: false,
  13535. callbacks: []
  13536. },
  13537. withVars: []
  13538. };
  13539. formatChangeItems[format] = base;
  13540. return base;
  13541. });
  13542. const getCurrent = () => {
  13543. const parents = getParents(editor);
  13544. return matchingNode(editor, parents, format, similar, vars).isSome();
  13545. };
  13546. if (isUndefined(vars)) {
  13547. const toAppendTo = similar ? group.withSimilar : group.withoutSimilar;
  13548. toAppendTo.callbacks.push(callback);
  13549. if (toAppendTo.callbacks.length === 1) {
  13550. toAppendTo.state.set(getCurrent());
  13551. }
  13552. } else {
  13553. group.withVars.push({
  13554. state: Cell(getCurrent()),
  13555. similar,
  13556. vars,
  13557. callback
  13558. });
  13559. }
  13560. });
  13561. registeredFormatListeners.set(formatChangeItems);
  13562. };
  13563. const removeListeners = (registeredFormatListeners, formats, callback) => {
  13564. const formatChangeItems = registeredFormatListeners.get();
  13565. each$f(formats.split(','), format => get$a(formatChangeItems, format).each(group => {
  13566. formatChangeItems[format] = {
  13567. withSimilar: {
  13568. ...group.withSimilar,
  13569. callbacks: filter$6(group.withSimilar.callbacks, cb => cb !== callback)
  13570. },
  13571. withoutSimilar: {
  13572. ...group.withoutSimilar,
  13573. callbacks: filter$6(group.withoutSimilar.callbacks, cb => cb !== callback)
  13574. },
  13575. withVars: filter$6(group.withVars, item => item.callback !== callback)
  13576. };
  13577. }));
  13578. registeredFormatListeners.set(formatChangeItems);
  13579. };
  13580. const formatChangedInternal = (editor, registeredFormatListeners, formats, callback, similar, vars) => {
  13581. if (registeredFormatListeners.get() === null) {
  13582. setup$t(registeredFormatListeners, editor);
  13583. }
  13584. addListeners(editor, registeredFormatListeners, formats, callback, similar, vars);
  13585. return { unbind: () => removeListeners(registeredFormatListeners, formats, callback) };
  13586. };
  13587. const toggle = (editor, name, vars, node) => {
  13588. const fmt = editor.formatter.get(name);
  13589. if (match$2(editor, name, vars, node) && (!('toggle' in fmt[0]) || fmt[0].toggle)) {
  13590. remove$2(editor, name, vars, node);
  13591. } else {
  13592. applyFormat$1(editor, name, vars, node);
  13593. }
  13594. };
  13595. function _typeof(obj) {
  13596. '@babel/helpers - typeof';
  13597. return _typeof = 'function' == typeof Symbol && 'symbol' == typeof Symbol.iterator ? function (obj) {
  13598. return typeof obj;
  13599. } : function (obj) {
  13600. return obj && 'function' == typeof Symbol && obj.constructor === Symbol && obj !== Symbol.prototype ? 'symbol' : typeof obj;
  13601. }, _typeof(obj);
  13602. }
  13603. function _setPrototypeOf(o, p) {
  13604. _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) {
  13605. o.__proto__ = p;
  13606. return o;
  13607. };
  13608. return _setPrototypeOf(o, p);
  13609. }
  13610. function _isNativeReflectConstruct() {
  13611. if (typeof Reflect === 'undefined' || !Reflect.construct)
  13612. return false;
  13613. if (Reflect.construct.sham)
  13614. return false;
  13615. if (typeof Proxy === 'function')
  13616. return true;
  13617. try {
  13618. Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {
  13619. }));
  13620. return true;
  13621. } catch (e) {
  13622. return false;
  13623. }
  13624. }
  13625. function _construct(Parent, args, Class) {
  13626. if (_isNativeReflectConstruct()) {
  13627. _construct = Reflect.construct;
  13628. } else {
  13629. _construct = function _construct(Parent, args, Class) {
  13630. var a = [null];
  13631. a.push.apply(a, args);
  13632. var Constructor = Function.bind.apply(Parent, a);
  13633. var instance = new Constructor();
  13634. if (Class)
  13635. _setPrototypeOf(instance, Class.prototype);
  13636. return instance;
  13637. };
  13638. }
  13639. return _construct.apply(null, arguments);
  13640. }
  13641. function _toConsumableArray(arr) {
  13642. return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _unsupportedIterableToArray(arr) || _nonIterableSpread();
  13643. }
  13644. function _arrayWithoutHoles(arr) {
  13645. if (Array.isArray(arr))
  13646. return _arrayLikeToArray(arr);
  13647. }
  13648. function _iterableToArray(iter) {
  13649. if (typeof Symbol !== 'undefined' && iter[Symbol.iterator] != null || iter['@@iterator'] != null)
  13650. return Array.from(iter);
  13651. }
  13652. function _unsupportedIterableToArray(o, minLen) {
  13653. if (!o)
  13654. return;
  13655. if (typeof o === 'string')
  13656. return _arrayLikeToArray(o, minLen);
  13657. var n = Object.prototype.toString.call(o).slice(8, -1);
  13658. if (n === 'Object' && o.constructor)
  13659. n = o.constructor.name;
  13660. if (n === 'Map' || n === 'Set')
  13661. return Array.from(o);
  13662. if (n === 'Arguments' || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n))
  13663. return _arrayLikeToArray(o, minLen);
  13664. }
  13665. function _arrayLikeToArray(arr, len) {
  13666. if (len == null || len > arr.length)
  13667. len = arr.length;
  13668. for (var i = 0, arr2 = new Array(len); i < len; i++)
  13669. arr2[i] = arr[i];
  13670. return arr2;
  13671. }
  13672. function _nonIterableSpread() {
  13673. throw new TypeError('Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.');
  13674. }
  13675. var hasOwnProperty = Object.hasOwnProperty, setPrototypeOf = Object.setPrototypeOf, isFrozen = Object.isFrozen, getPrototypeOf = Object.getPrototypeOf, getOwnPropertyDescriptor = Object.getOwnPropertyDescriptor;
  13676. var freeze = Object.freeze, seal = Object.seal, create$8 = Object.create;
  13677. var _ref = typeof Reflect !== 'undefined' && Reflect, apply = _ref.apply, construct = _ref.construct;
  13678. if (!apply) {
  13679. apply = function apply(fun, thisValue, args) {
  13680. return fun.apply(thisValue, args);
  13681. };
  13682. }
  13683. if (!freeze) {
  13684. freeze = function freeze(x) {
  13685. return x;
  13686. };
  13687. }
  13688. if (!seal) {
  13689. seal = function seal(x) {
  13690. return x;
  13691. };
  13692. }
  13693. if (!construct) {
  13694. construct = function construct(Func, args) {
  13695. return _construct(Func, _toConsumableArray(args));
  13696. };
  13697. }
  13698. var arrayForEach = unapply(Array.prototype.forEach);
  13699. var arrayPop = unapply(Array.prototype.pop);
  13700. var arrayPush = unapply(Array.prototype.push);
  13701. var stringToLowerCase = unapply(String.prototype.toLowerCase);
  13702. var stringMatch = unapply(String.prototype.match);
  13703. var stringReplace = unapply(String.prototype.replace);
  13704. var stringIndexOf = unapply(String.prototype.indexOf);
  13705. var stringTrim = unapply(String.prototype.trim);
  13706. var regExpTest = unapply(RegExp.prototype.test);
  13707. var typeErrorCreate = unconstruct(TypeError);
  13708. function unapply(func) {
  13709. return function (thisArg) {
  13710. for (var _len = arguments.length, args = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
  13711. args[_key - 1] = arguments[_key];
  13712. }
  13713. return apply(func, thisArg, args);
  13714. };
  13715. }
  13716. function unconstruct(func) {
  13717. return function () {
  13718. for (var _len2 = arguments.length, args = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) {
  13719. args[_key2] = arguments[_key2];
  13720. }
  13721. return construct(func, args);
  13722. };
  13723. }
  13724. function addToSet(set, array) {
  13725. if (setPrototypeOf) {
  13726. setPrototypeOf(set, null);
  13727. }
  13728. var l = array.length;
  13729. while (l--) {
  13730. var element = array[l];
  13731. if (typeof element === 'string') {
  13732. var lcElement = stringToLowerCase(element);
  13733. if (lcElement !== element) {
  13734. if (!isFrozen(array)) {
  13735. array[l] = lcElement;
  13736. }
  13737. element = lcElement;
  13738. }
  13739. }
  13740. set[element] = true;
  13741. }
  13742. return set;
  13743. }
  13744. function clone(object) {
  13745. var newObject = create$8(null);
  13746. var property;
  13747. for (property in object) {
  13748. if (apply(hasOwnProperty, object, [property])) {
  13749. newObject[property] = object[property];
  13750. }
  13751. }
  13752. return newObject;
  13753. }
  13754. function lookupGetter(object, prop) {
  13755. while (object !== null) {
  13756. var desc = getOwnPropertyDescriptor(object, prop);
  13757. if (desc) {
  13758. if (desc.get) {
  13759. return unapply(desc.get);
  13760. }
  13761. if (typeof desc.value === 'function') {
  13762. return unapply(desc.value);
  13763. }
  13764. }
  13765. object = getPrototypeOf(object);
  13766. }
  13767. function fallbackValue(element) {
  13768. console.warn('fallback value for', element);
  13769. return null;
  13770. }
  13771. return fallbackValue;
  13772. }
  13773. var html$1 = freeze([
  13774. 'a',
  13775. 'abbr',
  13776. 'acronym',
  13777. 'address',
  13778. 'area',
  13779. 'article',
  13780. 'aside',
  13781. 'audio',
  13782. 'b',
  13783. 'bdi',
  13784. 'bdo',
  13785. 'big',
  13786. 'blink',
  13787. 'blockquote',
  13788. 'body',
  13789. 'br',
  13790. 'button',
  13791. 'canvas',
  13792. 'caption',
  13793. 'center',
  13794. 'cite',
  13795. 'code',
  13796. 'col',
  13797. 'colgroup',
  13798. 'content',
  13799. 'data',
  13800. 'datalist',
  13801. 'dd',
  13802. 'decorator',
  13803. 'del',
  13804. 'details',
  13805. 'dfn',
  13806. 'dialog',
  13807. 'dir',
  13808. 'div',
  13809. 'dl',
  13810. 'dt',
  13811. 'element',
  13812. 'em',
  13813. 'fieldset',
  13814. 'figcaption',
  13815. 'figure',
  13816. 'font',
  13817. 'footer',
  13818. 'form',
  13819. 'h1',
  13820. 'h2',
  13821. 'h3',
  13822. 'h4',
  13823. 'h5',
  13824. 'h6',
  13825. 'head',
  13826. 'header',
  13827. 'hgroup',
  13828. 'hr',
  13829. 'html',
  13830. 'i',
  13831. 'img',
  13832. 'input',
  13833. 'ins',
  13834. 'kbd',
  13835. 'label',
  13836. 'legend',
  13837. 'li',
  13838. 'main',
  13839. 'map',
  13840. 'mark',
  13841. 'marquee',
  13842. 'menu',
  13843. 'menuitem',
  13844. 'meter',
  13845. 'nav',
  13846. 'nobr',
  13847. 'ol',
  13848. 'optgroup',
  13849. 'option',
  13850. 'output',
  13851. 'p',
  13852. 'picture',
  13853. 'pre',
  13854. 'progress',
  13855. 'q',
  13856. 'rp',
  13857. 'rt',
  13858. 'ruby',
  13859. 's',
  13860. 'samp',
  13861. 'section',
  13862. 'select',
  13863. 'shadow',
  13864. 'small',
  13865. 'source',
  13866. 'spacer',
  13867. 'span',
  13868. 'strike',
  13869. 'strong',
  13870. 'style',
  13871. 'sub',
  13872. 'summary',
  13873. 'sup',
  13874. 'table',
  13875. 'tbody',
  13876. 'td',
  13877. 'template',
  13878. 'textarea',
  13879. 'tfoot',
  13880. 'th',
  13881. 'thead',
  13882. 'time',
  13883. 'tr',
  13884. 'track',
  13885. 'tt',
  13886. 'u',
  13887. 'ul',
  13888. 'var',
  13889. 'video',
  13890. 'wbr'
  13891. ]);
  13892. var svg$1 = freeze([
  13893. 'svg',
  13894. 'a',
  13895. 'altglyph',
  13896. 'altglyphdef',
  13897. 'altglyphitem',
  13898. 'animatecolor',
  13899. 'animatemotion',
  13900. 'animatetransform',
  13901. 'circle',
  13902. 'clippath',
  13903. 'defs',
  13904. 'desc',
  13905. 'ellipse',
  13906. 'filter',
  13907. 'font',
  13908. 'g',
  13909. 'glyph',
  13910. 'glyphref',
  13911. 'hkern',
  13912. 'image',
  13913. 'line',
  13914. 'lineargradient',
  13915. 'marker',
  13916. 'mask',
  13917. 'metadata',
  13918. 'mpath',
  13919. 'path',
  13920. 'pattern',
  13921. 'polygon',
  13922. 'polyline',
  13923. 'radialgradient',
  13924. 'rect',
  13925. 'stop',
  13926. 'style',
  13927. 'switch',
  13928. 'symbol',
  13929. 'text',
  13930. 'textpath',
  13931. 'title',
  13932. 'tref',
  13933. 'tspan',
  13934. 'view',
  13935. 'vkern'
  13936. ]);
  13937. var svgFilters = freeze([
  13938. 'feBlend',
  13939. 'feColorMatrix',
  13940. 'feComponentTransfer',
  13941. 'feComposite',
  13942. 'feConvolveMatrix',
  13943. 'feDiffuseLighting',
  13944. 'feDisplacementMap',
  13945. 'feDistantLight',
  13946. 'feFlood',
  13947. 'feFuncA',
  13948. 'feFuncB',
  13949. 'feFuncG',
  13950. 'feFuncR',
  13951. 'feGaussianBlur',
  13952. 'feImage',
  13953. 'feMerge',
  13954. 'feMergeNode',
  13955. 'feMorphology',
  13956. 'feOffset',
  13957. 'fePointLight',
  13958. 'feSpecularLighting',
  13959. 'feSpotLight',
  13960. 'feTile',
  13961. 'feTurbulence'
  13962. ]);
  13963. var svgDisallowed = freeze([
  13964. 'animate',
  13965. 'color-profile',
  13966. 'cursor',
  13967. 'discard',
  13968. 'fedropshadow',
  13969. 'font-face',
  13970. 'font-face-format',
  13971. 'font-face-name',
  13972. 'font-face-src',
  13973. 'font-face-uri',
  13974. 'foreignobject',
  13975. 'hatch',
  13976. 'hatchpath',
  13977. 'mesh',
  13978. 'meshgradient',
  13979. 'meshpatch',
  13980. 'meshrow',
  13981. 'missing-glyph',
  13982. 'script',
  13983. 'set',
  13984. 'solidcolor',
  13985. 'unknown',
  13986. 'use'
  13987. ]);
  13988. var mathMl$1 = freeze([
  13989. 'math',
  13990. 'menclose',
  13991. 'merror',
  13992. 'mfenced',
  13993. 'mfrac',
  13994. 'mglyph',
  13995. 'mi',
  13996. 'mlabeledtr',
  13997. 'mmultiscripts',
  13998. 'mn',
  13999. 'mo',
  14000. 'mover',
  14001. 'mpadded',
  14002. 'mphantom',
  14003. 'mroot',
  14004. 'mrow',
  14005. 'ms',
  14006. 'mspace',
  14007. 'msqrt',
  14008. 'mstyle',
  14009. 'msub',
  14010. 'msup',
  14011. 'msubsup',
  14012. 'mtable',
  14013. 'mtd',
  14014. 'mtext',
  14015. 'mtr',
  14016. 'munder',
  14017. 'munderover'
  14018. ]);
  14019. var mathMlDisallowed = freeze([
  14020. 'maction',
  14021. 'maligngroup',
  14022. 'malignmark',
  14023. 'mlongdiv',
  14024. 'mscarries',
  14025. 'mscarry',
  14026. 'msgroup',
  14027. 'mstack',
  14028. 'msline',
  14029. 'msrow',
  14030. 'semantics',
  14031. 'annotation',
  14032. 'annotation-xml',
  14033. 'mprescripts',
  14034. 'none'
  14035. ]);
  14036. var text = freeze(['#text']);
  14037. var html = freeze([
  14038. 'accept',
  14039. 'action',
  14040. 'align',
  14041. 'alt',
  14042. 'autocapitalize',
  14043. 'autocomplete',
  14044. 'autopictureinpicture',
  14045. 'autoplay',
  14046. 'background',
  14047. 'bgcolor',
  14048. 'border',
  14049. 'capture',
  14050. 'cellpadding',
  14051. 'cellspacing',
  14052. 'checked',
  14053. 'cite',
  14054. 'class',
  14055. 'clear',
  14056. 'color',
  14057. 'cols',
  14058. 'colspan',
  14059. 'controls',
  14060. 'controlslist',
  14061. 'coords',
  14062. 'crossorigin',
  14063. 'datetime',
  14064. 'decoding',
  14065. 'default',
  14066. 'dir',
  14067. 'disabled',
  14068. 'disablepictureinpicture',
  14069. 'disableremoteplayback',
  14070. 'download',
  14071. 'draggable',
  14072. 'enctype',
  14073. 'enterkeyhint',
  14074. 'face',
  14075. 'for',
  14076. 'headers',
  14077. 'height',
  14078. 'hidden',
  14079. 'high',
  14080. 'href',
  14081. 'hreflang',
  14082. 'id',
  14083. 'inputmode',
  14084. 'integrity',
  14085. 'ismap',
  14086. 'kind',
  14087. 'label',
  14088. 'lang',
  14089. 'list',
  14090. 'loading',
  14091. 'loop',
  14092. 'low',
  14093. 'max',
  14094. 'maxlength',
  14095. 'media',
  14096. 'method',
  14097. 'min',
  14098. 'minlength',
  14099. 'multiple',
  14100. 'muted',
  14101. 'name',
  14102. 'nonce',
  14103. 'noshade',
  14104. 'novalidate',
  14105. 'nowrap',
  14106. 'open',
  14107. 'optimum',
  14108. 'pattern',
  14109. 'placeholder',
  14110. 'playsinline',
  14111. 'poster',
  14112. 'preload',
  14113. 'pubdate',
  14114. 'radiogroup',
  14115. 'readonly',
  14116. 'rel',
  14117. 'required',
  14118. 'rev',
  14119. 'reversed',
  14120. 'role',
  14121. 'rows',
  14122. 'rowspan',
  14123. 'spellcheck',
  14124. 'scope',
  14125. 'selected',
  14126. 'shape',
  14127. 'size',
  14128. 'sizes',
  14129. 'span',
  14130. 'srclang',
  14131. 'start',
  14132. 'src',
  14133. 'srcset',
  14134. 'step',
  14135. 'style',
  14136. 'summary',
  14137. 'tabindex',
  14138. 'title',
  14139. 'translate',
  14140. 'type',
  14141. 'usemap',
  14142. 'valign',
  14143. 'value',
  14144. 'width',
  14145. 'xmlns',
  14146. 'slot'
  14147. ]);
  14148. var svg = freeze([
  14149. 'accent-height',
  14150. 'accumulate',
  14151. 'additive',
  14152. 'alignment-baseline',
  14153. 'ascent',
  14154. 'attributename',
  14155. 'attributetype',
  14156. 'azimuth',
  14157. 'basefrequency',
  14158. 'baseline-shift',
  14159. 'begin',
  14160. 'bias',
  14161. 'by',
  14162. 'class',
  14163. 'clip',
  14164. 'clippathunits',
  14165. 'clip-path',
  14166. 'clip-rule',
  14167. 'color',
  14168. 'color-interpolation',
  14169. 'color-interpolation-filters',
  14170. 'color-profile',
  14171. 'color-rendering',
  14172. 'cx',
  14173. 'cy',
  14174. 'd',
  14175. 'dx',
  14176. 'dy',
  14177. 'diffuseconstant',
  14178. 'direction',
  14179. 'display',
  14180. 'divisor',
  14181. 'dur',
  14182. 'edgemode',
  14183. 'elevation',
  14184. 'end',
  14185. 'fill',
  14186. 'fill-opacity',
  14187. 'fill-rule',
  14188. 'filter',
  14189. 'filterunits',
  14190. 'flood-color',
  14191. 'flood-opacity',
  14192. 'font-family',
  14193. 'font-size',
  14194. 'font-size-adjust',
  14195. 'font-stretch',
  14196. 'font-style',
  14197. 'font-variant',
  14198. 'font-weight',
  14199. 'fx',
  14200. 'fy',
  14201. 'g1',
  14202. 'g2',
  14203. 'glyph-name',
  14204. 'glyphref',
  14205. 'gradientunits',
  14206. 'gradienttransform',
  14207. 'height',
  14208. 'href',
  14209. 'id',
  14210. 'image-rendering',
  14211. 'in',
  14212. 'in2',
  14213. 'k',
  14214. 'k1',
  14215. 'k2',
  14216. 'k3',
  14217. 'k4',
  14218. 'kerning',
  14219. 'keypoints',
  14220. 'keysplines',
  14221. 'keytimes',
  14222. 'lang',
  14223. 'lengthadjust',
  14224. 'letter-spacing',
  14225. 'kernelmatrix',
  14226. 'kernelunitlength',
  14227. 'lighting-color',
  14228. 'local',
  14229. 'marker-end',
  14230. 'marker-mid',
  14231. 'marker-start',
  14232. 'markerheight',
  14233. 'markerunits',
  14234. 'markerwidth',
  14235. 'maskcontentunits',
  14236. 'maskunits',
  14237. 'max',
  14238. 'mask',
  14239. 'media',
  14240. 'method',
  14241. 'mode',
  14242. 'min',
  14243. 'name',
  14244. 'numoctaves',
  14245. 'offset',
  14246. 'operator',
  14247. 'opacity',
  14248. 'order',
  14249. 'orient',
  14250. 'orientation',
  14251. 'origin',
  14252. 'overflow',
  14253. 'paint-order',
  14254. 'path',
  14255. 'pathlength',
  14256. 'patterncontentunits',
  14257. 'patterntransform',
  14258. 'patternunits',
  14259. 'points',
  14260. 'preservealpha',
  14261. 'preserveaspectratio',
  14262. 'primitiveunits',
  14263. 'r',
  14264. 'rx',
  14265. 'ry',
  14266. 'radius',
  14267. 'refx',
  14268. 'refy',
  14269. 'repeatcount',
  14270. 'repeatdur',
  14271. 'restart',
  14272. 'result',
  14273. 'rotate',
  14274. 'scale',
  14275. 'seed',
  14276. 'shape-rendering',
  14277. 'specularconstant',
  14278. 'specularexponent',
  14279. 'spreadmethod',
  14280. 'startoffset',
  14281. 'stddeviation',
  14282. 'stitchtiles',
  14283. 'stop-color',
  14284. 'stop-opacity',
  14285. 'stroke-dasharray',
  14286. 'stroke-dashoffset',
  14287. 'stroke-linecap',
  14288. 'stroke-linejoin',
  14289. 'stroke-miterlimit',
  14290. 'stroke-opacity',
  14291. 'stroke',
  14292. 'stroke-width',
  14293. 'style',
  14294. 'surfacescale',
  14295. 'systemlanguage',
  14296. 'tabindex',
  14297. 'targetx',
  14298. 'targety',
  14299. 'transform',
  14300. 'transform-origin',
  14301. 'text-anchor',
  14302. 'text-decoration',
  14303. 'text-rendering',
  14304. 'textlength',
  14305. 'type',
  14306. 'u1',
  14307. 'u2',
  14308. 'unicode',
  14309. 'values',
  14310. 'viewbox',
  14311. 'visibility',
  14312. 'version',
  14313. 'vert-adv-y',
  14314. 'vert-origin-x',
  14315. 'vert-origin-y',
  14316. 'width',
  14317. 'word-spacing',
  14318. 'wrap',
  14319. 'writing-mode',
  14320. 'xchannelselector',
  14321. 'ychannelselector',
  14322. 'x',
  14323. 'x1',
  14324. 'x2',
  14325. 'xmlns',
  14326. 'y',
  14327. 'y1',
  14328. 'y2',
  14329. 'z',
  14330. 'zoomandpan'
  14331. ]);
  14332. var mathMl = freeze([
  14333. 'accent',
  14334. 'accentunder',
  14335. 'align',
  14336. 'bevelled',
  14337. 'close',
  14338. 'columnsalign',
  14339. 'columnlines',
  14340. 'columnspan',
  14341. 'denomalign',
  14342. 'depth',
  14343. 'dir',
  14344. 'display',
  14345. 'displaystyle',
  14346. 'encoding',
  14347. 'fence',
  14348. 'frame',
  14349. 'height',
  14350. 'href',
  14351. 'id',
  14352. 'largeop',
  14353. 'length',
  14354. 'linethickness',
  14355. 'lspace',
  14356. 'lquote',
  14357. 'mathbackground',
  14358. 'mathcolor',
  14359. 'mathsize',
  14360. 'mathvariant',
  14361. 'maxsize',
  14362. 'minsize',
  14363. 'movablelimits',
  14364. 'notation',
  14365. 'numalign',
  14366. 'open',
  14367. 'rowalign',
  14368. 'rowlines',
  14369. 'rowspacing',
  14370. 'rowspan',
  14371. 'rspace',
  14372. 'rquote',
  14373. 'scriptlevel',
  14374. 'scriptminsize',
  14375. 'scriptsizemultiplier',
  14376. 'selection',
  14377. 'separator',
  14378. 'separators',
  14379. 'stretchy',
  14380. 'subscriptshift',
  14381. 'supscriptshift',
  14382. 'symmetric',
  14383. 'voffset',
  14384. 'width',
  14385. 'xmlns'
  14386. ]);
  14387. var xml = freeze([
  14388. 'xlink:href',
  14389. 'xml:id',
  14390. 'xlink:title',
  14391. 'xml:space',
  14392. 'xmlns:xlink'
  14393. ]);
  14394. var MUSTACHE_EXPR = seal(/\{\{[\w\W]*|[\w\W]*\}\}/gm);
  14395. var ERB_EXPR = seal(/<%[\w\W]*|[\w\W]*%>/gm);
  14396. var DATA_ATTR = seal(/^data-[\-\w.\u00B7-\uFFFF]/);
  14397. var ARIA_ATTR = seal(/^aria-[\-\w]+$/);
  14398. var IS_ALLOWED_URI = seal(/^(?:(?:(?:f|ht)tps?|mailto|tel|callto|cid|xmpp):|[^a-z]|[a-z+.\-]+(?:[^a-z+.\-:]|$))/i);
  14399. var IS_SCRIPT_OR_DATA = seal(/^(?:\w+script|data):/i);
  14400. var ATTR_WHITESPACE = seal(/[\u0000-\u0020\u00A0\u1680\u180E\u2000-\u2029\u205F\u3000]/g);
  14401. var DOCTYPE_NAME = seal(/^html$/i);
  14402. var getGlobal = function getGlobal() {
  14403. return typeof window === 'undefined' ? null : window;
  14404. };
  14405. var _createTrustedTypesPolicy = function _createTrustedTypesPolicy(trustedTypes, document) {
  14406. if (_typeof(trustedTypes) !== 'object' || typeof trustedTypes.createPolicy !== 'function') {
  14407. return null;
  14408. }
  14409. var suffix = null;
  14410. var ATTR_NAME = 'data-tt-policy-suffix';
  14411. if (document.currentScript && document.currentScript.hasAttribute(ATTR_NAME)) {
  14412. suffix = document.currentScript.getAttribute(ATTR_NAME);
  14413. }
  14414. var policyName = 'dompurify' + (suffix ? '#' + suffix : '');
  14415. try {
  14416. return trustedTypes.createPolicy(policyName, {
  14417. createHTML: function createHTML(html) {
  14418. return html;
  14419. }
  14420. });
  14421. } catch (_) {
  14422. console.warn('TrustedTypes policy ' + policyName + ' could not be created.');
  14423. return null;
  14424. }
  14425. };
  14426. function createDOMPurify() {
  14427. var window = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : getGlobal();
  14428. var DOMPurify = function DOMPurify(root) {
  14429. return createDOMPurify(root);
  14430. };
  14431. DOMPurify.version = '2.3.8';
  14432. DOMPurify.removed = [];
  14433. if (!window || !window.document || window.document.nodeType !== 9) {
  14434. DOMPurify.isSupported = false;
  14435. return DOMPurify;
  14436. }
  14437. var originalDocument = window.document;
  14438. var document = window.document;
  14439. var DocumentFragment = window.DocumentFragment, HTMLTemplateElement = window.HTMLTemplateElement, Node = window.Node, Element = window.Element, NodeFilter = window.NodeFilter, _window$NamedNodeMap = window.NamedNodeMap, NamedNodeMap = _window$NamedNodeMap === void 0 ? window.NamedNodeMap || window.MozNamedAttrMap : _window$NamedNodeMap, HTMLFormElement = window.HTMLFormElement, DOMParser = window.DOMParser, trustedTypes = window.trustedTypes;
  14440. var ElementPrototype = Element.prototype;
  14441. var cloneNode = lookupGetter(ElementPrototype, 'cloneNode');
  14442. var getNextSibling = lookupGetter(ElementPrototype, 'nextSibling');
  14443. var getChildNodes = lookupGetter(ElementPrototype, 'childNodes');
  14444. var getParentNode = lookupGetter(ElementPrototype, 'parentNode');
  14445. if (typeof HTMLTemplateElement === 'function') {
  14446. var template = document.createElement('template');
  14447. if (template.content && template.content.ownerDocument) {
  14448. document = template.content.ownerDocument;
  14449. }
  14450. }
  14451. var trustedTypesPolicy = _createTrustedTypesPolicy(trustedTypes, originalDocument);
  14452. var emptyHTML = trustedTypesPolicy ? trustedTypesPolicy.createHTML('') : '';
  14453. var _document = document, implementation = _document.implementation, createNodeIterator = _document.createNodeIterator, createDocumentFragment = _document.createDocumentFragment, getElementsByTagName = _document.getElementsByTagName;
  14454. var importNode = originalDocument.importNode;
  14455. var documentMode = {};
  14456. try {
  14457. documentMode = clone(document).documentMode ? document.documentMode : {};
  14458. } catch (_) {
  14459. }
  14460. var hooks = {};
  14461. DOMPurify.isSupported = typeof getParentNode === 'function' && implementation && typeof implementation.createHTMLDocument !== 'undefined' && documentMode !== 9;
  14462. 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;
  14463. var IS_ALLOWED_URI$1 = IS_ALLOWED_URI;
  14464. var ALLOWED_TAGS = null;
  14465. var DEFAULT_ALLOWED_TAGS = addToSet({}, [].concat(_toConsumableArray(html$1), _toConsumableArray(svg$1), _toConsumableArray(svgFilters), _toConsumableArray(mathMl$1), _toConsumableArray(text)));
  14466. var ALLOWED_ATTR = null;
  14467. var DEFAULT_ALLOWED_ATTR = addToSet({}, [].concat(_toConsumableArray(html), _toConsumableArray(svg), _toConsumableArray(mathMl), _toConsumableArray(xml)));
  14468. var CUSTOM_ELEMENT_HANDLING = Object.seal(Object.create(null, {
  14469. tagNameCheck: {
  14470. writable: true,
  14471. configurable: false,
  14472. enumerable: true,
  14473. value: null
  14474. },
  14475. attributeNameCheck: {
  14476. writable: true,
  14477. configurable: false,
  14478. enumerable: true,
  14479. value: null
  14480. },
  14481. allowCustomizedBuiltInElements: {
  14482. writable: true,
  14483. configurable: false,
  14484. enumerable: true,
  14485. value: false
  14486. }
  14487. }));
  14488. var FORBID_TAGS = null;
  14489. var FORBID_ATTR = null;
  14490. var ALLOW_ARIA_ATTR = true;
  14491. var ALLOW_DATA_ATTR = true;
  14492. var ALLOW_UNKNOWN_PROTOCOLS = false;
  14493. var SAFE_FOR_TEMPLATES = false;
  14494. var WHOLE_DOCUMENT = false;
  14495. var SET_CONFIG = false;
  14496. var FORCE_BODY = false;
  14497. var RETURN_DOM = false;
  14498. var RETURN_DOM_FRAGMENT = false;
  14499. var RETURN_TRUSTED_TYPE = false;
  14500. var SANITIZE_DOM = true;
  14501. var KEEP_CONTENT = true;
  14502. var IN_PLACE = false;
  14503. var USE_PROFILES = {};
  14504. var FORBID_CONTENTS = null;
  14505. var DEFAULT_FORBID_CONTENTS = addToSet({}, [
  14506. 'annotation-xml',
  14507. 'audio',
  14508. 'colgroup',
  14509. 'desc',
  14510. 'foreignobject',
  14511. 'head',
  14512. 'iframe',
  14513. 'math',
  14514. 'mi',
  14515. 'mn',
  14516. 'mo',
  14517. 'ms',
  14518. 'mtext',
  14519. 'noembed',
  14520. 'noframes',
  14521. 'noscript',
  14522. 'plaintext',
  14523. 'script',
  14524. 'style',
  14525. 'svg',
  14526. 'template',
  14527. 'thead',
  14528. 'title',
  14529. 'video',
  14530. 'xmp'
  14531. ]);
  14532. var DATA_URI_TAGS = null;
  14533. var DEFAULT_DATA_URI_TAGS = addToSet({}, [
  14534. 'audio',
  14535. 'video',
  14536. 'img',
  14537. 'source',
  14538. 'image',
  14539. 'track'
  14540. ]);
  14541. var URI_SAFE_ATTRIBUTES = null;
  14542. var DEFAULT_URI_SAFE_ATTRIBUTES = addToSet({}, [
  14543. 'alt',
  14544. 'class',
  14545. 'for',
  14546. 'id',
  14547. 'label',
  14548. 'name',
  14549. 'pattern',
  14550. 'placeholder',
  14551. 'role',
  14552. 'summary',
  14553. 'title',
  14554. 'value',
  14555. 'style',
  14556. 'xmlns'
  14557. ]);
  14558. var MATHML_NAMESPACE = 'http://www.w3.org/1998/Math/MathML';
  14559. var SVG_NAMESPACE = 'http://www.w3.org/2000/svg';
  14560. var HTML_NAMESPACE = 'http://www.w3.org/1999/xhtml';
  14561. var NAMESPACE = HTML_NAMESPACE;
  14562. var IS_EMPTY_INPUT = false;
  14563. var PARSER_MEDIA_TYPE;
  14564. var SUPPORTED_PARSER_MEDIA_TYPES = [
  14565. 'application/xhtml+xml',
  14566. 'text/html'
  14567. ];
  14568. var DEFAULT_PARSER_MEDIA_TYPE = 'text/html';
  14569. var transformCaseFunc;
  14570. var CONFIG = null;
  14571. var formElement = document.createElement('form');
  14572. var isRegexOrFunction = function isRegexOrFunction(testValue) {
  14573. return testValue instanceof RegExp || testValue instanceof Function;
  14574. };
  14575. var _parseConfig = function _parseConfig(cfg) {
  14576. if (CONFIG && CONFIG === cfg) {
  14577. return;
  14578. }
  14579. if (!cfg || _typeof(cfg) !== 'object') {
  14580. cfg = {};
  14581. }
  14582. cfg = clone(cfg);
  14583. ALLOWED_TAGS = 'ALLOWED_TAGS' in cfg ? addToSet({}, cfg.ALLOWED_TAGS) : DEFAULT_ALLOWED_TAGS;
  14584. ALLOWED_ATTR = 'ALLOWED_ATTR' in cfg ? addToSet({}, cfg.ALLOWED_ATTR) : DEFAULT_ALLOWED_ATTR;
  14585. URI_SAFE_ATTRIBUTES = 'ADD_URI_SAFE_ATTR' in cfg ? addToSet(clone(DEFAULT_URI_SAFE_ATTRIBUTES), cfg.ADD_URI_SAFE_ATTR) : DEFAULT_URI_SAFE_ATTRIBUTES;
  14586. DATA_URI_TAGS = 'ADD_DATA_URI_TAGS' in cfg ? addToSet(clone(DEFAULT_DATA_URI_TAGS), cfg.ADD_DATA_URI_TAGS) : DEFAULT_DATA_URI_TAGS;
  14587. FORBID_CONTENTS = 'FORBID_CONTENTS' in cfg ? addToSet({}, cfg.FORBID_CONTENTS) : DEFAULT_FORBID_CONTENTS;
  14588. FORBID_TAGS = 'FORBID_TAGS' in cfg ? addToSet({}, cfg.FORBID_TAGS) : {};
  14589. FORBID_ATTR = 'FORBID_ATTR' in cfg ? addToSet({}, cfg.FORBID_ATTR) : {};
  14590. USE_PROFILES = 'USE_PROFILES' in cfg ? cfg.USE_PROFILES : false;
  14591. ALLOW_ARIA_ATTR = cfg.ALLOW_ARIA_ATTR !== false;
  14592. ALLOW_DATA_ATTR = cfg.ALLOW_DATA_ATTR !== false;
  14593. ALLOW_UNKNOWN_PROTOCOLS = cfg.ALLOW_UNKNOWN_PROTOCOLS || false;
  14594. SAFE_FOR_TEMPLATES = cfg.SAFE_FOR_TEMPLATES || false;
  14595. WHOLE_DOCUMENT = cfg.WHOLE_DOCUMENT || false;
  14596. RETURN_DOM = cfg.RETURN_DOM || false;
  14597. RETURN_DOM_FRAGMENT = cfg.RETURN_DOM_FRAGMENT || false;
  14598. RETURN_TRUSTED_TYPE = cfg.RETURN_TRUSTED_TYPE || false;
  14599. FORCE_BODY = cfg.FORCE_BODY || false;
  14600. SANITIZE_DOM = cfg.SANITIZE_DOM !== false;
  14601. KEEP_CONTENT = cfg.KEEP_CONTENT !== false;
  14602. IN_PLACE = cfg.IN_PLACE || false;
  14603. IS_ALLOWED_URI$1 = cfg.ALLOWED_URI_REGEXP || IS_ALLOWED_URI$1;
  14604. NAMESPACE = cfg.NAMESPACE || HTML_NAMESPACE;
  14605. if (cfg.CUSTOM_ELEMENT_HANDLING && isRegexOrFunction(cfg.CUSTOM_ELEMENT_HANDLING.tagNameCheck)) {
  14606. CUSTOM_ELEMENT_HANDLING.tagNameCheck = cfg.CUSTOM_ELEMENT_HANDLING.tagNameCheck;
  14607. }
  14608. if (cfg.CUSTOM_ELEMENT_HANDLING && isRegexOrFunction(cfg.CUSTOM_ELEMENT_HANDLING.attributeNameCheck)) {
  14609. CUSTOM_ELEMENT_HANDLING.attributeNameCheck = cfg.CUSTOM_ELEMENT_HANDLING.attributeNameCheck;
  14610. }
  14611. if (cfg.CUSTOM_ELEMENT_HANDLING && typeof cfg.CUSTOM_ELEMENT_HANDLING.allowCustomizedBuiltInElements === 'boolean') {
  14612. CUSTOM_ELEMENT_HANDLING.allowCustomizedBuiltInElements = cfg.CUSTOM_ELEMENT_HANDLING.allowCustomizedBuiltInElements;
  14613. }
  14614. 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;
  14615. transformCaseFunc = PARSER_MEDIA_TYPE === 'application/xhtml+xml' ? function (x) {
  14616. return x;
  14617. } : stringToLowerCase;
  14618. if (SAFE_FOR_TEMPLATES) {
  14619. ALLOW_DATA_ATTR = false;
  14620. }
  14621. if (RETURN_DOM_FRAGMENT) {
  14622. RETURN_DOM = true;
  14623. }
  14624. if (USE_PROFILES) {
  14625. ALLOWED_TAGS = addToSet({}, _toConsumableArray(text));
  14626. ALLOWED_ATTR = [];
  14627. if (USE_PROFILES.html === true) {
  14628. addToSet(ALLOWED_TAGS, html$1);
  14629. addToSet(ALLOWED_ATTR, html);
  14630. }
  14631. if (USE_PROFILES.svg === true) {
  14632. addToSet(ALLOWED_TAGS, svg$1);
  14633. addToSet(ALLOWED_ATTR, svg);
  14634. addToSet(ALLOWED_ATTR, xml);
  14635. }
  14636. if (USE_PROFILES.svgFilters === true) {
  14637. addToSet(ALLOWED_TAGS, svgFilters);
  14638. addToSet(ALLOWED_ATTR, svg);
  14639. addToSet(ALLOWED_ATTR, xml);
  14640. }
  14641. if (USE_PROFILES.mathMl === true) {
  14642. addToSet(ALLOWED_TAGS, mathMl$1);
  14643. addToSet(ALLOWED_ATTR, mathMl);
  14644. addToSet(ALLOWED_ATTR, xml);
  14645. }
  14646. }
  14647. if (cfg.ADD_TAGS) {
  14648. if (ALLOWED_TAGS === DEFAULT_ALLOWED_TAGS) {
  14649. ALLOWED_TAGS = clone(ALLOWED_TAGS);
  14650. }
  14651. addToSet(ALLOWED_TAGS, cfg.ADD_TAGS);
  14652. }
  14653. if (cfg.ADD_ATTR) {
  14654. if (ALLOWED_ATTR === DEFAULT_ALLOWED_ATTR) {
  14655. ALLOWED_ATTR = clone(ALLOWED_ATTR);
  14656. }
  14657. addToSet(ALLOWED_ATTR, cfg.ADD_ATTR);
  14658. }
  14659. if (cfg.ADD_URI_SAFE_ATTR) {
  14660. addToSet(URI_SAFE_ATTRIBUTES, cfg.ADD_URI_SAFE_ATTR);
  14661. }
  14662. if (cfg.FORBID_CONTENTS) {
  14663. if (FORBID_CONTENTS === DEFAULT_FORBID_CONTENTS) {
  14664. FORBID_CONTENTS = clone(FORBID_CONTENTS);
  14665. }
  14666. addToSet(FORBID_CONTENTS, cfg.FORBID_CONTENTS);
  14667. }
  14668. if (KEEP_CONTENT) {
  14669. ALLOWED_TAGS['#text'] = true;
  14670. }
  14671. if (WHOLE_DOCUMENT) {
  14672. addToSet(ALLOWED_TAGS, [
  14673. 'html',
  14674. 'head',
  14675. 'body'
  14676. ]);
  14677. }
  14678. if (ALLOWED_TAGS.table) {
  14679. addToSet(ALLOWED_TAGS, ['tbody']);
  14680. delete FORBID_TAGS.tbody;
  14681. }
  14682. if (freeze) {
  14683. freeze(cfg);
  14684. }
  14685. CONFIG = cfg;
  14686. };
  14687. var MATHML_TEXT_INTEGRATION_POINTS = addToSet({}, [
  14688. 'mi',
  14689. 'mo',
  14690. 'mn',
  14691. 'ms',
  14692. 'mtext'
  14693. ]);
  14694. var HTML_INTEGRATION_POINTS = addToSet({}, [
  14695. 'foreignobject',
  14696. 'desc',
  14697. 'title',
  14698. 'annotation-xml'
  14699. ]);
  14700. var COMMON_SVG_AND_HTML_ELEMENTS = addToSet({}, [
  14701. 'title',
  14702. 'style',
  14703. 'font',
  14704. 'a',
  14705. 'script'
  14706. ]);
  14707. var ALL_SVG_TAGS = addToSet({}, svg$1);
  14708. addToSet(ALL_SVG_TAGS, svgFilters);
  14709. addToSet(ALL_SVG_TAGS, svgDisallowed);
  14710. var ALL_MATHML_TAGS = addToSet({}, mathMl$1);
  14711. addToSet(ALL_MATHML_TAGS, mathMlDisallowed);
  14712. var _checkValidNamespace = function _checkValidNamespace(element) {
  14713. var parent = getParentNode(element);
  14714. if (!parent || !parent.tagName) {
  14715. parent = {
  14716. namespaceURI: HTML_NAMESPACE,
  14717. tagName: 'template'
  14718. };
  14719. }
  14720. var tagName = stringToLowerCase(element.tagName);
  14721. var parentTagName = stringToLowerCase(parent.tagName);
  14722. if (element.namespaceURI === SVG_NAMESPACE) {
  14723. if (parent.namespaceURI === HTML_NAMESPACE) {
  14724. return tagName === 'svg';
  14725. }
  14726. if (parent.namespaceURI === MATHML_NAMESPACE) {
  14727. return tagName === 'svg' && (parentTagName === 'annotation-xml' || MATHML_TEXT_INTEGRATION_POINTS[parentTagName]);
  14728. }
  14729. return Boolean(ALL_SVG_TAGS[tagName]);
  14730. }
  14731. if (element.namespaceURI === MATHML_NAMESPACE) {
  14732. if (parent.namespaceURI === HTML_NAMESPACE) {
  14733. return tagName === 'math';
  14734. }
  14735. if (parent.namespaceURI === SVG_NAMESPACE) {
  14736. return tagName === 'math' && HTML_INTEGRATION_POINTS[parentTagName];
  14737. }
  14738. return Boolean(ALL_MATHML_TAGS[tagName]);
  14739. }
  14740. if (element.namespaceURI === HTML_NAMESPACE) {
  14741. if (parent.namespaceURI === SVG_NAMESPACE && !HTML_INTEGRATION_POINTS[parentTagName]) {
  14742. return false;
  14743. }
  14744. if (parent.namespaceURI === MATHML_NAMESPACE && !MATHML_TEXT_INTEGRATION_POINTS[parentTagName]) {
  14745. return false;
  14746. }
  14747. return !ALL_MATHML_TAGS[tagName] && (COMMON_SVG_AND_HTML_ELEMENTS[tagName] || !ALL_SVG_TAGS[tagName]);
  14748. }
  14749. return false;
  14750. };
  14751. var _forceRemove = function _forceRemove(node) {
  14752. arrayPush(DOMPurify.removed, { element: node });
  14753. try {
  14754. node.parentNode.removeChild(node);
  14755. } catch (_) {
  14756. try {
  14757. node.outerHTML = emptyHTML;
  14758. } catch (_) {
  14759. node.remove();
  14760. }
  14761. }
  14762. };
  14763. var _removeAttribute = function _removeAttribute(name, node) {
  14764. try {
  14765. arrayPush(DOMPurify.removed, {
  14766. attribute: node.getAttributeNode(name),
  14767. from: node
  14768. });
  14769. } catch (_) {
  14770. arrayPush(DOMPurify.removed, {
  14771. attribute: null,
  14772. from: node
  14773. });
  14774. }
  14775. node.removeAttribute(name);
  14776. if (name === 'is' && !ALLOWED_ATTR[name]) {
  14777. if (RETURN_DOM || RETURN_DOM_FRAGMENT) {
  14778. try {
  14779. _forceRemove(node);
  14780. } catch (_) {
  14781. }
  14782. } else {
  14783. try {
  14784. node.setAttribute(name, '');
  14785. } catch (_) {
  14786. }
  14787. }
  14788. }
  14789. };
  14790. var _initDocument = function _initDocument(dirty) {
  14791. var doc;
  14792. var leadingWhitespace;
  14793. if (FORCE_BODY) {
  14794. dirty = '<remove></remove>' + dirty;
  14795. } else {
  14796. var matches = stringMatch(dirty, /^[\r\n\t ]+/);
  14797. leadingWhitespace = matches && matches[0];
  14798. }
  14799. if (PARSER_MEDIA_TYPE === 'application/xhtml+xml') {
  14800. dirty = '<html xmlns="http://www.w3.org/1999/xhtml"><head></head><body>' + dirty + '</body></html>';
  14801. }
  14802. var dirtyPayload = trustedTypesPolicy ? trustedTypesPolicy.createHTML(dirty) : dirty;
  14803. if (NAMESPACE === HTML_NAMESPACE) {
  14804. try {
  14805. doc = new DOMParser().parseFromString(dirtyPayload, PARSER_MEDIA_TYPE);
  14806. } catch (_) {
  14807. }
  14808. }
  14809. if (!doc || !doc.documentElement) {
  14810. doc = implementation.createDocument(NAMESPACE, 'template', null);
  14811. try {
  14812. doc.documentElement.innerHTML = IS_EMPTY_INPUT ? '' : dirtyPayload;
  14813. } catch (_) {
  14814. }
  14815. }
  14816. var body = doc.body || doc.documentElement;
  14817. if (dirty && leadingWhitespace) {
  14818. body.insertBefore(document.createTextNode(leadingWhitespace), body.childNodes[0] || null);
  14819. }
  14820. if (NAMESPACE === HTML_NAMESPACE) {
  14821. return getElementsByTagName.call(doc, WHOLE_DOCUMENT ? 'html' : 'body')[0];
  14822. }
  14823. return WHOLE_DOCUMENT ? doc.documentElement : body;
  14824. };
  14825. var _createIterator = function _createIterator(root) {
  14826. return createNodeIterator.call(root.ownerDocument || root, root, NodeFilter.SHOW_ELEMENT | NodeFilter.SHOW_COMMENT | NodeFilter.SHOW_TEXT, null, false);
  14827. };
  14828. var _isClobbered = function _isClobbered(elm) {
  14829. 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');
  14830. };
  14831. var _isNode = function _isNode(object) {
  14832. return _typeof(Node) === 'object' ? object instanceof Node : object && _typeof(object) === 'object' && typeof object.nodeType === 'number' && typeof object.nodeName === 'string';
  14833. };
  14834. var _executeHook = function _executeHook(entryPoint, currentNode, data) {
  14835. if (!hooks[entryPoint]) {
  14836. return;
  14837. }
  14838. arrayForEach(hooks[entryPoint], function (hook) {
  14839. hook.call(DOMPurify, currentNode, data, CONFIG);
  14840. });
  14841. };
  14842. var _sanitizeElements = function _sanitizeElements(currentNode) {
  14843. var content;
  14844. _executeHook('beforeSanitizeElements', currentNode, null);
  14845. if (_isClobbered(currentNode)) {
  14846. _forceRemove(currentNode);
  14847. return true;
  14848. }
  14849. if (regExpTest(/[\u0080-\uFFFF]/, currentNode.nodeName)) {
  14850. _forceRemove(currentNode);
  14851. return true;
  14852. }
  14853. var tagName = transformCaseFunc(currentNode.nodeName);
  14854. _executeHook('uponSanitizeElement', currentNode, {
  14855. tagName: tagName,
  14856. allowedTags: ALLOWED_TAGS
  14857. });
  14858. if (currentNode.hasChildNodes() && !_isNode(currentNode.firstElementChild) && (!_isNode(currentNode.content) || !_isNode(currentNode.content.firstElementChild)) && regExpTest(/<[/\w]/g, currentNode.innerHTML) && regExpTest(/<[/\w]/g, currentNode.textContent)) {
  14859. _forceRemove(currentNode);
  14860. return true;
  14861. }
  14862. if (tagName === 'select' && regExpTest(/<template/i, currentNode.innerHTML)) {
  14863. _forceRemove(currentNode);
  14864. return true;
  14865. }
  14866. if (!ALLOWED_TAGS[tagName] || FORBID_TAGS[tagName]) {
  14867. if (!FORBID_TAGS[tagName] && _basicCustomElementTest(tagName)) {
  14868. if (CUSTOM_ELEMENT_HANDLING.tagNameCheck instanceof RegExp && regExpTest(CUSTOM_ELEMENT_HANDLING.tagNameCheck, tagName))
  14869. return false;
  14870. if (CUSTOM_ELEMENT_HANDLING.tagNameCheck instanceof Function && CUSTOM_ELEMENT_HANDLING.tagNameCheck(tagName))
  14871. return false;
  14872. }
  14873. if (KEEP_CONTENT && !FORBID_CONTENTS[tagName]) {
  14874. var parentNode = getParentNode(currentNode) || currentNode.parentNode;
  14875. var childNodes = getChildNodes(currentNode) || currentNode.childNodes;
  14876. if (childNodes && parentNode) {
  14877. var childCount = childNodes.length;
  14878. for (var i = childCount - 1; i >= 0; --i) {
  14879. parentNode.insertBefore(cloneNode(childNodes[i], true), getNextSibling(currentNode));
  14880. }
  14881. }
  14882. }
  14883. _forceRemove(currentNode);
  14884. return true;
  14885. }
  14886. if (currentNode instanceof Element && !_checkValidNamespace(currentNode)) {
  14887. _forceRemove(currentNode);
  14888. return true;
  14889. }
  14890. if ((tagName === 'noscript' || tagName === 'noembed') && regExpTest(/<\/no(script|embed)/i, currentNode.innerHTML)) {
  14891. _forceRemove(currentNode);
  14892. return true;
  14893. }
  14894. if (SAFE_FOR_TEMPLATES && currentNode.nodeType === 3) {
  14895. content = currentNode.textContent;
  14896. content = stringReplace(content, MUSTACHE_EXPR$1, ' ');
  14897. content = stringReplace(content, ERB_EXPR$1, ' ');
  14898. if (currentNode.textContent !== content) {
  14899. arrayPush(DOMPurify.removed, { element: currentNode.cloneNode() });
  14900. currentNode.textContent = content;
  14901. }
  14902. }
  14903. _executeHook('afterSanitizeElements', currentNode, null);
  14904. return false;
  14905. };
  14906. var _isValidAttribute = function _isValidAttribute(lcTag, lcName, value) {
  14907. if (SANITIZE_DOM && (lcName === 'id' || lcName === 'name') && (value in document || value in formElement)) {
  14908. return false;
  14909. }
  14910. if (ALLOW_DATA_ATTR && !FORBID_ATTR[lcName] && regExpTest(DATA_ATTR$1, lcName));
  14911. else if (ALLOW_ARIA_ATTR && regExpTest(ARIA_ATTR$1, lcName));
  14912. else if (!ALLOWED_ATTR[lcName] || FORBID_ATTR[lcName]) {
  14913. 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)));
  14914. else {
  14915. return false;
  14916. }
  14917. } else if (URI_SAFE_ATTRIBUTES[lcName]);
  14918. else if (regExpTest(IS_ALLOWED_URI$1, stringReplace(value, ATTR_WHITESPACE$1, '')));
  14919. else if ((lcName === 'src' || lcName === 'xlink:href' || lcName === 'href') && lcTag !== 'script' && stringIndexOf(value, 'data:') === 0 && DATA_URI_TAGS[lcTag]);
  14920. else if (ALLOW_UNKNOWN_PROTOCOLS && !regExpTest(IS_SCRIPT_OR_DATA$1, stringReplace(value, ATTR_WHITESPACE$1, '')));
  14921. else if (!value);
  14922. else {
  14923. return false;
  14924. }
  14925. return true;
  14926. };
  14927. var _basicCustomElementTest = function _basicCustomElementTest(tagName) {
  14928. return tagName.indexOf('-') > 0;
  14929. };
  14930. var _sanitizeAttributes = function _sanitizeAttributes(currentNode) {
  14931. var attr;
  14932. var value;
  14933. var lcName;
  14934. var l;
  14935. _executeHook('beforeSanitizeAttributes', currentNode, null);
  14936. var attributes = currentNode.attributes;
  14937. if (!attributes) {
  14938. return;
  14939. }
  14940. var hookEvent = {
  14941. attrName: '',
  14942. attrValue: '',
  14943. keepAttr: true,
  14944. allowedAttributes: ALLOWED_ATTR
  14945. };
  14946. l = attributes.length;
  14947. while (l--) {
  14948. attr = attributes[l];
  14949. var _attr = attr, name = _attr.name, namespaceURI = _attr.namespaceURI;
  14950. value = name === 'value' ? attr.value : stringTrim(attr.value);
  14951. lcName = transformCaseFunc(name);
  14952. var initValue = value;
  14953. hookEvent.attrName = lcName;
  14954. hookEvent.attrValue = value;
  14955. hookEvent.keepAttr = true;
  14956. hookEvent.forceKeepAttr = undefined;
  14957. _executeHook('uponSanitizeAttribute', currentNode, hookEvent);
  14958. value = hookEvent.attrValue;
  14959. if (hookEvent.forceKeepAttr) {
  14960. continue;
  14961. }
  14962. if (!hookEvent.keepAttr) {
  14963. _removeAttribute(name, currentNode);
  14964. continue;
  14965. }
  14966. if (regExpTest(/\/>/i, value)) {
  14967. _removeAttribute(name, currentNode);
  14968. continue;
  14969. }
  14970. if (SAFE_FOR_TEMPLATES) {
  14971. value = stringReplace(value, MUSTACHE_EXPR$1, ' ');
  14972. value = stringReplace(value, ERB_EXPR$1, ' ');
  14973. }
  14974. var lcTag = transformCaseFunc(currentNode.nodeName);
  14975. if (!_isValidAttribute(lcTag, lcName, value)) {
  14976. _removeAttribute(name, currentNode);
  14977. continue;
  14978. }
  14979. if (value !== initValue) {
  14980. try {
  14981. if (namespaceURI) {
  14982. currentNode.setAttributeNS(namespaceURI, name, value);
  14983. } else {
  14984. currentNode.setAttribute(name, value);
  14985. }
  14986. } catch (_) {
  14987. _removeAttribute(name, currentNode);
  14988. }
  14989. }
  14990. }
  14991. _executeHook('afterSanitizeAttributes', currentNode, null);
  14992. };
  14993. var _sanitizeShadowDOM = function _sanitizeShadowDOM(fragment) {
  14994. var shadowNode;
  14995. var shadowIterator = _createIterator(fragment);
  14996. _executeHook('beforeSanitizeShadowDOM', fragment, null);
  14997. while (shadowNode = shadowIterator.nextNode()) {
  14998. _executeHook('uponSanitizeShadowNode', shadowNode, null);
  14999. if (_sanitizeElements(shadowNode)) {
  15000. continue;
  15001. }
  15002. if (shadowNode.content instanceof DocumentFragment) {
  15003. _sanitizeShadowDOM(shadowNode.content);
  15004. }
  15005. _sanitizeAttributes(shadowNode);
  15006. }
  15007. _executeHook('afterSanitizeShadowDOM', fragment, null);
  15008. };
  15009. DOMPurify.sanitize = function (dirty, cfg) {
  15010. var body;
  15011. var importedNode;
  15012. var currentNode;
  15013. var oldNode;
  15014. var returnNode;
  15015. IS_EMPTY_INPUT = !dirty;
  15016. if (IS_EMPTY_INPUT) {
  15017. dirty = '<!-->';
  15018. }
  15019. if (typeof dirty !== 'string' && !_isNode(dirty)) {
  15020. if (typeof dirty.toString !== 'function') {
  15021. throw typeErrorCreate('toString is not a function');
  15022. } else {
  15023. dirty = dirty.toString();
  15024. if (typeof dirty !== 'string') {
  15025. throw typeErrorCreate('dirty is not a string, aborting');
  15026. }
  15027. }
  15028. }
  15029. if (!DOMPurify.isSupported) {
  15030. if (_typeof(window.toStaticHTML) === 'object' || typeof window.toStaticHTML === 'function') {
  15031. if (typeof dirty === 'string') {
  15032. return window.toStaticHTML(dirty);
  15033. }
  15034. if (_isNode(dirty)) {
  15035. return window.toStaticHTML(dirty.outerHTML);
  15036. }
  15037. }
  15038. return dirty;
  15039. }
  15040. if (!SET_CONFIG) {
  15041. _parseConfig(cfg);
  15042. }
  15043. DOMPurify.removed = [];
  15044. if (typeof dirty === 'string') {
  15045. IN_PLACE = false;
  15046. }
  15047. if (IN_PLACE) {
  15048. if (dirty.nodeName) {
  15049. var tagName = transformCaseFunc(dirty.nodeName);
  15050. if (!ALLOWED_TAGS[tagName] || FORBID_TAGS[tagName]) {
  15051. throw typeErrorCreate('root node is forbidden and cannot be sanitized in-place');
  15052. }
  15053. }
  15054. } else if (dirty instanceof Node) {
  15055. body = _initDocument('<!---->');
  15056. importedNode = body.ownerDocument.importNode(dirty, true);
  15057. if (importedNode.nodeType === 1 && importedNode.nodeName === 'BODY') {
  15058. body = importedNode;
  15059. } else if (importedNode.nodeName === 'HTML') {
  15060. body = importedNode;
  15061. } else {
  15062. body.appendChild(importedNode);
  15063. }
  15064. } else {
  15065. if (!RETURN_DOM && !SAFE_FOR_TEMPLATES && !WHOLE_DOCUMENT && dirty.indexOf('<') === -1) {
  15066. return trustedTypesPolicy && RETURN_TRUSTED_TYPE ? trustedTypesPolicy.createHTML(dirty) : dirty;
  15067. }
  15068. body = _initDocument(dirty);
  15069. if (!body) {
  15070. return RETURN_DOM ? null : RETURN_TRUSTED_TYPE ? emptyHTML : '';
  15071. }
  15072. }
  15073. if (body && FORCE_BODY) {
  15074. _forceRemove(body.firstChild);
  15075. }
  15076. var nodeIterator = _createIterator(IN_PLACE ? dirty : body);
  15077. while (currentNode = nodeIterator.nextNode()) {
  15078. if (currentNode.nodeType === 3 && currentNode === oldNode) {
  15079. continue;
  15080. }
  15081. if (_sanitizeElements(currentNode)) {
  15082. continue;
  15083. }
  15084. if (currentNode.content instanceof DocumentFragment) {
  15085. _sanitizeShadowDOM(currentNode.content);
  15086. }
  15087. _sanitizeAttributes(currentNode);
  15088. oldNode = currentNode;
  15089. }
  15090. oldNode = null;
  15091. if (IN_PLACE) {
  15092. return dirty;
  15093. }
  15094. if (RETURN_DOM) {
  15095. if (RETURN_DOM_FRAGMENT) {
  15096. returnNode = createDocumentFragment.call(body.ownerDocument);
  15097. while (body.firstChild) {
  15098. returnNode.appendChild(body.firstChild);
  15099. }
  15100. } else {
  15101. returnNode = body;
  15102. }
  15103. if (ALLOWED_ATTR.shadowroot) {
  15104. returnNode = importNode.call(originalDocument, returnNode, true);
  15105. }
  15106. return returnNode;
  15107. }
  15108. var serializedHTML = WHOLE_DOCUMENT ? body.outerHTML : body.innerHTML;
  15109. if (WHOLE_DOCUMENT && ALLOWED_TAGS['!doctype'] && body.ownerDocument && body.ownerDocument.doctype && body.ownerDocument.doctype.name && regExpTest(DOCTYPE_NAME, body.ownerDocument.doctype.name)) {
  15110. serializedHTML = '<!DOCTYPE ' + body.ownerDocument.doctype.name + '>\n' + serializedHTML;
  15111. }
  15112. if (SAFE_FOR_TEMPLATES) {
  15113. serializedHTML = stringReplace(serializedHTML, MUSTACHE_EXPR$1, ' ');
  15114. serializedHTML = stringReplace(serializedHTML, ERB_EXPR$1, ' ');
  15115. }
  15116. return trustedTypesPolicy && RETURN_TRUSTED_TYPE ? trustedTypesPolicy.createHTML(serializedHTML) : serializedHTML;
  15117. };
  15118. DOMPurify.setConfig = function (cfg) {
  15119. _parseConfig(cfg);
  15120. SET_CONFIG = true;
  15121. };
  15122. DOMPurify.clearConfig = function () {
  15123. CONFIG = null;
  15124. SET_CONFIG = false;
  15125. };
  15126. DOMPurify.isValidAttribute = function (tag, attr, value) {
  15127. if (!CONFIG) {
  15128. _parseConfig({});
  15129. }
  15130. var lcTag = transformCaseFunc(tag);
  15131. var lcName = transformCaseFunc(attr);
  15132. return _isValidAttribute(lcTag, lcName, value);
  15133. };
  15134. DOMPurify.addHook = function (entryPoint, hookFunction) {
  15135. if (typeof hookFunction !== 'function') {
  15136. return;
  15137. }
  15138. hooks[entryPoint] = hooks[entryPoint] || [];
  15139. arrayPush(hooks[entryPoint], hookFunction);
  15140. };
  15141. DOMPurify.removeHook = function (entryPoint) {
  15142. if (hooks[entryPoint]) {
  15143. return arrayPop(hooks[entryPoint]);
  15144. }
  15145. };
  15146. DOMPurify.removeHooks = function (entryPoint) {
  15147. if (hooks[entryPoint]) {
  15148. hooks[entryPoint] = [];
  15149. }
  15150. };
  15151. DOMPurify.removeAllHooks = function () {
  15152. hooks = {};
  15153. };
  15154. return DOMPurify;
  15155. }
  15156. var purify = createDOMPurify();
  15157. const explode$1 = Tools.explode;
  15158. const create$7 = () => {
  15159. const filters = {};
  15160. const addFilter = (name, callback) => {
  15161. each$f(explode$1(name), name => {
  15162. if (!has$2(filters, name)) {
  15163. filters[name] = {
  15164. name,
  15165. callbacks: []
  15166. };
  15167. }
  15168. filters[name].callbacks.push(callback);
  15169. });
  15170. };
  15171. const getFilters = () => values(filters);
  15172. const removeFilter = (name, callback) => {
  15173. each$f(explode$1(name), name => {
  15174. if (has$2(filters, name)) {
  15175. if (isNonNullable(callback)) {
  15176. const filter = filters[name];
  15177. const newCallbacks = filter$6(filter.callbacks, c => c !== callback);
  15178. if (newCallbacks.length > 0) {
  15179. filter.callbacks = newCallbacks;
  15180. } else {
  15181. delete filters[name];
  15182. }
  15183. } else {
  15184. delete filters[name];
  15185. }
  15186. }
  15187. });
  15188. };
  15189. return {
  15190. addFilter,
  15191. getFilters,
  15192. removeFilter
  15193. };
  15194. };
  15195. const removeAttrs = (node, names) => {
  15196. each$f(names, name => {
  15197. node.attr(name, null);
  15198. });
  15199. };
  15200. const addFontToSpansFilter = (domParser, styles, fontSizes) => {
  15201. domParser.addNodeFilter('font', nodes => {
  15202. each$f(nodes, node => {
  15203. const props = styles.parse(node.attr('style'));
  15204. const color = node.attr('color');
  15205. const face = node.attr('face');
  15206. const size = node.attr('size');
  15207. if (color) {
  15208. props.color = color;
  15209. }
  15210. if (face) {
  15211. props['font-family'] = face;
  15212. }
  15213. if (size) {
  15214. props['font-size'] = fontSizes[parseInt(node.attr('size'), 10) - 1];
  15215. }
  15216. node.name = 'span';
  15217. node.attr('style', styles.serialize(props));
  15218. removeAttrs(node, [
  15219. 'color',
  15220. 'face',
  15221. 'size'
  15222. ]);
  15223. });
  15224. });
  15225. };
  15226. const addStrikeFilter = (domParser, schema, styles) => {
  15227. domParser.addNodeFilter('strike', nodes => {
  15228. const convertToSTag = schema.type !== 'html4';
  15229. each$f(nodes, node => {
  15230. if (convertToSTag) {
  15231. node.name = 's';
  15232. } else {
  15233. const props = styles.parse(node.attr('style'));
  15234. props['text-decoration'] = 'line-through';
  15235. node.name = 'span';
  15236. node.attr('style', styles.serialize(props));
  15237. }
  15238. });
  15239. });
  15240. };
  15241. const addFilters = (domParser, settings, schema) => {
  15242. const styles = Styles();
  15243. if (settings.convert_fonts_to_spans) {
  15244. addFontToSpansFilter(domParser, styles, Tools.explode(settings.font_size_legacy_values));
  15245. }
  15246. addStrikeFilter(domParser, schema, styles);
  15247. };
  15248. const register$5 = (domParser, settings, schema) => {
  15249. if (settings.inline_styles) {
  15250. addFilters(domParser, settings, schema);
  15251. }
  15252. };
  15253. const blobUriToBlob = url => fetch(url).then(res => res.ok ? res.blob() : Promise.reject()).catch(() => Promise.reject(`Cannot convert ${ url } to Blob. Resource might not exist or is inaccessible.`));
  15254. const extractBase64Data = data => {
  15255. const matches = /([a-z0-9+\/=\s]+)/i.exec(data);
  15256. return matches ? matches[1] : '';
  15257. };
  15258. const parseDataUri = uri => {
  15259. const [type, ...rest] = uri.split(',');
  15260. const data = rest.join(',');
  15261. const matches = /data:([^/]+\/[^;]+)(;.+)?/.exec(type);
  15262. if (matches) {
  15263. const base64Encoded = matches[2] === ';base64';
  15264. const extractedData = base64Encoded ? extractBase64Data(data) : decodeURIComponent(data);
  15265. return Optional.some({
  15266. type: matches[1],
  15267. data: extractedData,
  15268. base64Encoded
  15269. });
  15270. } else {
  15271. return Optional.none();
  15272. }
  15273. };
  15274. const buildBlob = (type, data, base64Encoded = true) => {
  15275. let str = data;
  15276. if (base64Encoded) {
  15277. try {
  15278. str = atob(data);
  15279. } catch (e) {
  15280. return Optional.none();
  15281. }
  15282. }
  15283. const arr = new Uint8Array(str.length);
  15284. for (let i = 0; i < arr.length; i++) {
  15285. arr[i] = str.charCodeAt(i);
  15286. }
  15287. return Optional.some(new Blob([arr], { type }));
  15288. };
  15289. const dataUriToBlob = uri => {
  15290. return new Promise((resolve, reject) => {
  15291. parseDataUri(uri).bind(({type, data, base64Encoded}) => buildBlob(type, data, base64Encoded)).fold(() => reject('Invalid data URI'), resolve);
  15292. });
  15293. };
  15294. const uriToBlob = url => {
  15295. if (startsWith(url, 'blob:')) {
  15296. return blobUriToBlob(url);
  15297. } else if (startsWith(url, 'data:')) {
  15298. return dataUriToBlob(url);
  15299. } else {
  15300. return Promise.reject('Unknown URI format');
  15301. }
  15302. };
  15303. const blobToDataUri = blob => {
  15304. return new Promise((resolve, reject) => {
  15305. const reader = new FileReader();
  15306. reader.onloadend = () => {
  15307. resolve(reader.result);
  15308. };
  15309. reader.onerror = () => {
  15310. reject(reader.error.message);
  15311. };
  15312. reader.readAsDataURL(blob);
  15313. });
  15314. };
  15315. let count$1 = 0;
  15316. const uniqueId$1 = prefix => {
  15317. return (prefix || 'blobid') + count$1++;
  15318. };
  15319. const processDataUri = (dataUri, base64Only, generateBlobInfo) => {
  15320. return parseDataUri(dataUri).bind(({data, type, base64Encoded}) => {
  15321. if (base64Only && !base64Encoded) {
  15322. return Optional.none();
  15323. } else {
  15324. const base64 = base64Encoded ? data : btoa(data);
  15325. return generateBlobInfo(base64, type);
  15326. }
  15327. });
  15328. };
  15329. const createBlobInfo$1 = (blobCache, blob, base64) => {
  15330. const blobInfo = blobCache.create(uniqueId$1(), blob, base64);
  15331. blobCache.add(blobInfo);
  15332. return blobInfo;
  15333. };
  15334. const dataUriToBlobInfo = (blobCache, dataUri, base64Only = false) => {
  15335. return processDataUri(dataUri, base64Only, (base64, type) => Optional.from(blobCache.getByData(base64, type)).orThunk(() => buildBlob(type, base64).map(blob => createBlobInfo$1(blobCache, blob, base64))));
  15336. };
  15337. const imageToBlobInfo = (blobCache, imageSrc) => {
  15338. const invalidDataUri = () => Promise.reject('Invalid data URI');
  15339. if (startsWith(imageSrc, 'blob:')) {
  15340. const blobInfo = blobCache.getByUri(imageSrc);
  15341. if (isNonNullable(blobInfo)) {
  15342. return Promise.resolve(blobInfo);
  15343. } else {
  15344. return uriToBlob(imageSrc).then(blob => {
  15345. return blobToDataUri(blob).then(dataUri => {
  15346. return processDataUri(dataUri, false, base64 => {
  15347. return Optional.some(createBlobInfo$1(blobCache, blob, base64));
  15348. }).getOrThunk(invalidDataUri);
  15349. });
  15350. });
  15351. }
  15352. } else if (startsWith(imageSrc, 'data:')) {
  15353. return dataUriToBlobInfo(blobCache, imageSrc).fold(invalidDataUri, blobInfo => Promise.resolve(blobInfo));
  15354. } else {
  15355. return Promise.reject('Unknown image data format');
  15356. }
  15357. };
  15358. const isBogusImage = img => isNonNullable(img.attr('data-mce-bogus'));
  15359. const isInternalImageSource = img => img.attr('src') === Env.transparentSrc || isNonNullable(img.attr('data-mce-placeholder'));
  15360. const registerBase64ImageFilter = (parser, settings) => {
  15361. const {blob_cache: blobCache} = settings;
  15362. const processImage = img => {
  15363. const inputSrc = img.attr('src');
  15364. if (isInternalImageSource(img) || isBogusImage(img)) {
  15365. return;
  15366. }
  15367. dataUriToBlobInfo(blobCache, inputSrc, true).each(blobInfo => {
  15368. img.attr('src', blobInfo.blobUri());
  15369. });
  15370. };
  15371. if (blobCache) {
  15372. parser.addAttributeFilter('src', nodes => each$f(nodes, processImage));
  15373. }
  15374. };
  15375. const register$4 = (parser, settings) => {
  15376. const schema = parser.schema;
  15377. if (settings.remove_trailing_brs) {
  15378. parser.addNodeFilter('br', (nodes, _, args) => {
  15379. const blockElements = Tools.extend({}, schema.getBlockElements());
  15380. const nonEmptyElements = schema.getNonEmptyElements();
  15381. const whitespaceElements = schema.getWhitespaceElements();
  15382. blockElements.body = 1;
  15383. for (let i = 0, l = nodes.length; i < l; i++) {
  15384. let node = nodes[i];
  15385. let parent = node.parent;
  15386. if (blockElements[node.parent.name] && node === parent.lastChild) {
  15387. let prev = node.prev;
  15388. while (prev) {
  15389. const prevName = prev.name;
  15390. if (prevName !== 'span' || prev.attr('data-mce-type') !== 'bookmark') {
  15391. if (prevName === 'br') {
  15392. node = null;
  15393. }
  15394. break;
  15395. }
  15396. prev = prev.prev;
  15397. }
  15398. if (node) {
  15399. node.remove();
  15400. if (isEmpty(schema, nonEmptyElements, whitespaceElements, parent)) {
  15401. const elementRule = schema.getElementRule(parent.name);
  15402. if (elementRule) {
  15403. if (elementRule.removeEmpty) {
  15404. parent.remove();
  15405. } else if (elementRule.paddEmpty) {
  15406. paddEmptyNode(settings, args, blockElements, parent);
  15407. }
  15408. }
  15409. }
  15410. }
  15411. } else {
  15412. let lastParent = node;
  15413. while (parent && parent.firstChild === lastParent && parent.lastChild === lastParent) {
  15414. lastParent = parent;
  15415. if (blockElements[parent.name]) {
  15416. break;
  15417. }
  15418. parent = parent.parent;
  15419. }
  15420. if (lastParent === parent) {
  15421. const textNode = new AstNode('#text', 3);
  15422. textNode.value = nbsp;
  15423. node.replace(textNode);
  15424. }
  15425. }
  15426. }
  15427. });
  15428. }
  15429. parser.addAttributeFilter('href', nodes => {
  15430. let i = nodes.length;
  15431. const appendRel = rel => {
  15432. const parts = rel.split(' ').filter(p => p.length > 0);
  15433. return parts.concat(['noopener']).sort().join(' ');
  15434. };
  15435. const addNoOpener = rel => {
  15436. const newRel = rel ? Tools.trim(rel) : '';
  15437. if (!/\b(noopener)\b/g.test(newRel)) {
  15438. return appendRel(newRel);
  15439. } else {
  15440. return newRel;
  15441. }
  15442. };
  15443. if (!settings.allow_unsafe_link_target) {
  15444. while (i--) {
  15445. const node = nodes[i];
  15446. if (node.name === 'a' && node.attr('target') === '_blank') {
  15447. node.attr('rel', addNoOpener(node.attr('rel')));
  15448. }
  15449. }
  15450. }
  15451. });
  15452. if (!settings.allow_html_in_named_anchor) {
  15453. parser.addAttributeFilter('id,name', nodes => {
  15454. let i = nodes.length, sibling, prevSibling, parent, node;
  15455. while (i--) {
  15456. node = nodes[i];
  15457. if (node.name === 'a' && node.firstChild && !node.attr('href')) {
  15458. parent = node.parent;
  15459. sibling = node.lastChild;
  15460. do {
  15461. prevSibling = sibling.prev;
  15462. parent.insert(sibling, node);
  15463. sibling = prevSibling;
  15464. } while (sibling);
  15465. }
  15466. }
  15467. });
  15468. }
  15469. if (settings.fix_list_elements) {
  15470. parser.addNodeFilter('ul,ol', nodes => {
  15471. let i = nodes.length, node, parentNode;
  15472. while (i--) {
  15473. node = nodes[i];
  15474. parentNode = node.parent;
  15475. if (parentNode.name === 'ul' || parentNode.name === 'ol') {
  15476. if (node.prev && node.prev.name === 'li') {
  15477. node.prev.append(node);
  15478. } else {
  15479. const li = new AstNode('li', 1);
  15480. li.attr('style', 'list-style-type: none');
  15481. node.wrap(li);
  15482. }
  15483. }
  15484. }
  15485. });
  15486. }
  15487. if (settings.validate && schema.getValidClasses()) {
  15488. parser.addAttributeFilter('class', nodes => {
  15489. const validClasses = schema.getValidClasses();
  15490. let i = nodes.length;
  15491. while (i--) {
  15492. const node = nodes[i];
  15493. const classList = node.attr('class').split(' ');
  15494. let classValue = '';
  15495. for (let ci = 0; ci < classList.length; ci++) {
  15496. const className = classList[ci];
  15497. let valid = false;
  15498. let validClassesMap = validClasses['*'];
  15499. if (validClassesMap && validClassesMap[className]) {
  15500. valid = true;
  15501. }
  15502. validClassesMap = validClasses[node.name];
  15503. if (!valid && validClassesMap && validClassesMap[className]) {
  15504. valid = true;
  15505. }
  15506. if (valid) {
  15507. if (classValue) {
  15508. classValue += ' ';
  15509. }
  15510. classValue += className;
  15511. }
  15512. }
  15513. if (!classValue.length) {
  15514. classValue = null;
  15515. }
  15516. node.attr('class', classValue);
  15517. }
  15518. });
  15519. }
  15520. registerBase64ImageFilter(parser, settings);
  15521. };
  15522. const each$4 = Tools.each, trim = Tools.trim;
  15523. const queryParts = 'source protocol authority userInfo user password host port relative path directory file query anchor'.split(' ');
  15524. const DEFAULT_PORTS = {
  15525. ftp: 21,
  15526. http: 80,
  15527. https: 443,
  15528. mailto: 25
  15529. };
  15530. const safeSvgDataUrlElements = [
  15531. 'img',
  15532. 'video'
  15533. ];
  15534. const blockSvgDataUris = (allowSvgDataUrls, tagName) => {
  15535. if (isNonNullable(allowSvgDataUrls)) {
  15536. return !allowSvgDataUrls;
  15537. } else {
  15538. return isNonNullable(tagName) ? !contains$2(safeSvgDataUrlElements, tagName) : true;
  15539. }
  15540. };
  15541. const decodeUri = encodedUri => {
  15542. try {
  15543. return decodeURIComponent(encodedUri);
  15544. } catch (ex) {
  15545. return unescape(encodedUri);
  15546. }
  15547. };
  15548. const isInvalidUri = (settings, uri, tagName) => {
  15549. const decodedUri = decodeUri(uri);
  15550. if (settings.allow_script_urls) {
  15551. return false;
  15552. } else if (/((java|vb)script|mhtml):/i.test(decodedUri)) {
  15553. return true;
  15554. } else if (settings.allow_html_data_urls) {
  15555. return false;
  15556. } else if (/^data:image\//i.test(decodedUri)) {
  15557. return blockSvgDataUris(settings.allow_svg_data_urls, tagName) && /^data:image\/svg\+xml/i.test(decodedUri);
  15558. } else {
  15559. return /^data:/i.test(decodedUri);
  15560. }
  15561. };
  15562. class URI {
  15563. constructor(url, settings) {
  15564. url = trim(url);
  15565. this.settings = settings || {};
  15566. const baseUri = this.settings.base_uri;
  15567. const self = this;
  15568. if (/^([\w\-]+):([^\/]{2})/i.test(url) || /^\s*#/.test(url)) {
  15569. self.source = url;
  15570. return;
  15571. }
  15572. const isProtocolRelative = url.indexOf('//') === 0;
  15573. if (url.indexOf('/') === 0 && !isProtocolRelative) {
  15574. url = (baseUri ? baseUri.protocol || 'http' : 'http') + '://mce_host' + url;
  15575. }
  15576. if (!/^[\w\-]*:?\/\//.test(url)) {
  15577. const baseUrl = this.settings.base_uri ? this.settings.base_uri.path : new URI(document.location.href).directory;
  15578. if (this.settings.base_uri && this.settings.base_uri.protocol == '') {
  15579. url = '//mce_host' + self.toAbsPath(baseUrl, url);
  15580. } else {
  15581. const match = /([^#?]*)([#?]?.*)/.exec(url);
  15582. url = (baseUri && baseUri.protocol || 'http') + '://mce_host' + self.toAbsPath(baseUrl, match[1]) + match[2];
  15583. }
  15584. }
  15585. url = url.replace(/@@/g, '(mce_at)');
  15586. const urlMatch = /^(?:(?![^:@]+:[^:@\/]*@)([^:\/?#.]+):)?(?:\/\/)?((?:(([^:@\/]*):?([^:@\/]*))?@)?(\[[a-zA-Z0-9:.%]+\]|[^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/.exec(url);
  15587. each$4(queryParts, (v, i) => {
  15588. let part = urlMatch[i];
  15589. if (part) {
  15590. part = part.replace(/\(mce_at\)/g, '@@');
  15591. }
  15592. self[v] = part;
  15593. });
  15594. if (baseUri) {
  15595. if (!self.protocol) {
  15596. self.protocol = baseUri.protocol;
  15597. }
  15598. if (!self.userInfo) {
  15599. self.userInfo = baseUri.userInfo;
  15600. }
  15601. if (!self.port && self.host === 'mce_host') {
  15602. self.port = baseUri.port;
  15603. }
  15604. if (!self.host || self.host === 'mce_host') {
  15605. self.host = baseUri.host;
  15606. }
  15607. self.source = '';
  15608. }
  15609. if (isProtocolRelative) {
  15610. self.protocol = '';
  15611. }
  15612. }
  15613. static parseDataUri(uri) {
  15614. let type;
  15615. const uriComponents = decodeURIComponent(uri).split(',');
  15616. const matches = /data:([^;]+)/.exec(uriComponents[0]);
  15617. if (matches) {
  15618. type = matches[1];
  15619. }
  15620. return {
  15621. type,
  15622. data: uriComponents[1]
  15623. };
  15624. }
  15625. static isDomSafe(uri, context, options = {}) {
  15626. if (options.allow_script_urls) {
  15627. return true;
  15628. } else {
  15629. const decodedUri = Entities.decode(uri).replace(/[\s\u0000-\u001F]+/g, '');
  15630. return !isInvalidUri(options, decodedUri, context);
  15631. }
  15632. }
  15633. static getDocumentBaseUrl(loc) {
  15634. let baseUrl;
  15635. if (loc.protocol.indexOf('http') !== 0 && loc.protocol !== 'file:') {
  15636. baseUrl = loc.href;
  15637. } else {
  15638. baseUrl = loc.protocol + '//' + loc.host + loc.pathname;
  15639. }
  15640. if (/^[^:]+:\/\/\/?[^\/]+\//.test(baseUrl)) {
  15641. baseUrl = baseUrl.replace(/[\?#].*$/, '').replace(/[\/\\][^\/]+$/, '');
  15642. if (!/[\/\\]$/.test(baseUrl)) {
  15643. baseUrl += '/';
  15644. }
  15645. }
  15646. return baseUrl;
  15647. }
  15648. setPath(path) {
  15649. const pathMatch = /^(.*?)\/?(\w+)?$/.exec(path);
  15650. this.path = pathMatch[0];
  15651. this.directory = pathMatch[1];
  15652. this.file = pathMatch[2];
  15653. this.source = '';
  15654. this.getURI();
  15655. }
  15656. toRelative(uri) {
  15657. let output;
  15658. if (uri === './') {
  15659. return uri;
  15660. }
  15661. const relativeUri = new URI(uri, { base_uri: this });
  15662. if (relativeUri.host !== 'mce_host' && this.host !== relativeUri.host && relativeUri.host || this.port !== relativeUri.port || this.protocol !== relativeUri.protocol && relativeUri.protocol !== '') {
  15663. return relativeUri.getURI();
  15664. }
  15665. const tu = this.getURI(), uu = relativeUri.getURI();
  15666. if (tu === uu || tu.charAt(tu.length - 1) === '/' && tu.substr(0, tu.length - 1) === uu) {
  15667. return tu;
  15668. }
  15669. output = this.toRelPath(this.path, relativeUri.path);
  15670. if (relativeUri.query) {
  15671. output += '?' + relativeUri.query;
  15672. }
  15673. if (relativeUri.anchor) {
  15674. output += '#' + relativeUri.anchor;
  15675. }
  15676. return output;
  15677. }
  15678. toAbsolute(uri, noHost) {
  15679. const absoluteUri = new URI(uri, { base_uri: this });
  15680. return absoluteUri.getURI(noHost && this.isSameOrigin(absoluteUri));
  15681. }
  15682. isSameOrigin(uri) {
  15683. if (this.host == uri.host && this.protocol == uri.protocol) {
  15684. if (this.port == uri.port) {
  15685. return true;
  15686. }
  15687. const defaultPort = DEFAULT_PORTS[this.protocol];
  15688. if (defaultPort && (this.port || defaultPort) == (uri.port || defaultPort)) {
  15689. return true;
  15690. }
  15691. }
  15692. return false;
  15693. }
  15694. toRelPath(base, path) {
  15695. let breakPoint = 0, out = '', i, l;
  15696. const normalizedBase = base.substring(0, base.lastIndexOf('/')).split('/');
  15697. const items = path.split('/');
  15698. if (normalizedBase.length >= items.length) {
  15699. for (i = 0, l = normalizedBase.length; i < l; i++) {
  15700. if (i >= items.length || normalizedBase[i] !== items[i]) {
  15701. breakPoint = i + 1;
  15702. break;
  15703. }
  15704. }
  15705. }
  15706. if (normalizedBase.length < items.length) {
  15707. for (i = 0, l = items.length; i < l; i++) {
  15708. if (i >= normalizedBase.length || normalizedBase[i] !== items[i]) {
  15709. breakPoint = i + 1;
  15710. break;
  15711. }
  15712. }
  15713. }
  15714. if (breakPoint === 1) {
  15715. return path;
  15716. }
  15717. for (i = 0, l = normalizedBase.length - (breakPoint - 1); i < l; i++) {
  15718. out += '../';
  15719. }
  15720. for (i = breakPoint - 1, l = items.length; i < l; i++) {
  15721. if (i !== breakPoint - 1) {
  15722. out += '/' + items[i];
  15723. } else {
  15724. out += items[i];
  15725. }
  15726. }
  15727. return out;
  15728. }
  15729. toAbsPath(base, path) {
  15730. let i, nb = 0, o = [], outPath;
  15731. const tr = /\/$/.test(path) ? '/' : '';
  15732. let normalizedBase = base.split('/');
  15733. const normalizedPath = path.split('/');
  15734. each$4(normalizedBase, k => {
  15735. if (k) {
  15736. o.push(k);
  15737. }
  15738. });
  15739. normalizedBase = o;
  15740. for (i = normalizedPath.length - 1, o = []; i >= 0; i--) {
  15741. if (normalizedPath[i].length === 0 || normalizedPath[i] === '.') {
  15742. continue;
  15743. }
  15744. if (normalizedPath[i] === '..') {
  15745. nb++;
  15746. continue;
  15747. }
  15748. if (nb > 0) {
  15749. nb--;
  15750. continue;
  15751. }
  15752. o.push(normalizedPath[i]);
  15753. }
  15754. i = normalizedBase.length - nb;
  15755. if (i <= 0) {
  15756. outPath = reverse(o).join('/');
  15757. } else {
  15758. outPath = normalizedBase.slice(0, i).join('/') + '/' + reverse(o).join('/');
  15759. }
  15760. if (outPath.indexOf('/') !== 0) {
  15761. outPath = '/' + outPath;
  15762. }
  15763. if (tr && outPath.lastIndexOf('/') !== outPath.length - 1) {
  15764. outPath += tr;
  15765. }
  15766. return outPath;
  15767. }
  15768. getURI(noProtoHost = false) {
  15769. let s;
  15770. if (!this.source || noProtoHost) {
  15771. s = '';
  15772. if (!noProtoHost) {
  15773. if (this.protocol) {
  15774. s += this.protocol + '://';
  15775. } else {
  15776. s += '//';
  15777. }
  15778. if (this.userInfo) {
  15779. s += this.userInfo + '@';
  15780. }
  15781. if (this.host) {
  15782. s += this.host;
  15783. }
  15784. if (this.port) {
  15785. s += ':' + this.port;
  15786. }
  15787. }
  15788. if (this.path) {
  15789. s += this.path;
  15790. }
  15791. if (this.query) {
  15792. s += '?' + this.query;
  15793. }
  15794. if (this.anchor) {
  15795. s += '#' + this.anchor;
  15796. }
  15797. this.source = s;
  15798. }
  15799. return this.source;
  15800. }
  15801. }
  15802. const makeMap = Tools.makeMap, extend$1 = Tools.extend;
  15803. const basePurifyConfig = {
  15804. IN_PLACE: true,
  15805. ALLOW_UNKNOWN_PROTOCOLS: true,
  15806. ALLOWED_TAGS: [
  15807. '#comment',
  15808. '#cdata-section',
  15809. 'body'
  15810. ],
  15811. ALLOWED_ATTR: []
  15812. };
  15813. const filteredUrlAttrs = Tools.makeMap('src,href,data,background,action,formaction,poster,xlink:href');
  15814. const internalElementAttr = 'data-mce-type';
  15815. const getPurifyConfig = (settings, mimeType) => {
  15816. const config = { ...basePurifyConfig };
  15817. config.PARSER_MEDIA_TYPE = mimeType;
  15818. if (settings.allow_script_urls) {
  15819. config.ALLOWED_URI_REGEXP = /.*/;
  15820. } else if (settings.allow_html_data_urls) {
  15821. config.ALLOWED_URI_REGEXP = /^(?!(\w+script|mhtml):)/i;
  15822. }
  15823. return config;
  15824. };
  15825. const setupPurify = (settings, schema) => {
  15826. const purify$1 = purify();
  15827. const validate = settings.validate;
  15828. let uid = 0;
  15829. purify$1.addHook('uponSanitizeElement', (ele, evt) => {
  15830. var _a, _b;
  15831. if (ele.nodeType === COMMENT && !settings.allow_conditional_comments && /^\[if/i.test(ele.nodeValue)) {
  15832. ele.nodeValue = ' ' + ele.nodeValue;
  15833. }
  15834. const tagName = evt.tagName;
  15835. if (ele.nodeType !== ELEMENT || tagName === 'body') {
  15836. return;
  15837. }
  15838. const element = SugarElement.fromDom(ele);
  15839. const isInternalElement = has$1(element, internalElementAttr);
  15840. const bogus = get$9(element, 'data-mce-bogus');
  15841. if (!isInternalElement && isString(bogus)) {
  15842. if (bogus === 'all') {
  15843. remove$6(element);
  15844. } else {
  15845. unwrap(element);
  15846. }
  15847. return;
  15848. }
  15849. const rule = schema.getElementRule(tagName.toLowerCase());
  15850. if (validate && !rule) {
  15851. unwrap(element);
  15852. return;
  15853. } else {
  15854. evt.allowedTags[tagName] = true;
  15855. }
  15856. if (validate && !isInternalElement) {
  15857. each$f((_a = rule.attributesForced) !== null && _a !== void 0 ? _a : [], attr => {
  15858. set$2(element, attr.name, attr.value === '{$uid}' ? `mce_${ uid++ }` : attr.value);
  15859. });
  15860. each$f((_b = rule.attributesDefault) !== null && _b !== void 0 ? _b : [], attr => {
  15861. if (!has$1(element, attr.name)) {
  15862. set$2(element, attr.name, attr.value === '{$uid}' ? `mce_${ uid++ }` : attr.value);
  15863. }
  15864. });
  15865. if (rule.attributesRequired && !exists(rule.attributesRequired, attr => has$1(element, attr))) {
  15866. unwrap(element);
  15867. return;
  15868. }
  15869. if (rule.removeEmptyAttrs && hasNone(element)) {
  15870. unwrap(element);
  15871. return;
  15872. }
  15873. if (rule.outputName && rule.outputName !== tagName.toLowerCase()) {
  15874. mutate(element, rule.outputName);
  15875. }
  15876. }
  15877. });
  15878. purify$1.addHook('uponSanitizeAttribute', (ele, evt) => {
  15879. const tagName = ele.tagName.toLowerCase();
  15880. const {attrName, attrValue} = evt;
  15881. evt.keepAttr = !validate || schema.isValid(tagName, attrName) || startsWith(attrName, 'data-') || startsWith(attrName, 'aria-');
  15882. if (attrName in filteredUrlAttrs && isInvalidUri(settings, attrValue, tagName)) {
  15883. evt.keepAttr = false;
  15884. }
  15885. if (evt.keepAttr) {
  15886. evt.allowedAttributes[attrName] = true;
  15887. if (attrName in schema.getBoolAttrs()) {
  15888. evt.attrValue = attrName;
  15889. }
  15890. if (settings.allow_svg_data_urls && startsWith(attrValue, 'data:image/svg+xml')) {
  15891. evt.forceKeepAttr = true;
  15892. }
  15893. } else if (ele.hasAttribute(internalElementAttr) && (attrName === 'id' || attrName === 'class' || attrName === 'style')) {
  15894. evt.forceKeepAttr = true;
  15895. }
  15896. });
  15897. return purify$1;
  15898. };
  15899. const transferChildren = (parent, nativeParent, specialElements) => {
  15900. const parentName = parent.name;
  15901. const isSpecial = parentName in specialElements && parentName !== 'title' && parentName !== 'textarea';
  15902. const childNodes = nativeParent.childNodes;
  15903. for (let ni = 0, nl = childNodes.length; ni < nl; ni++) {
  15904. const nativeChild = childNodes[ni];
  15905. const child = new AstNode(nativeChild.nodeName.toLowerCase(), nativeChild.nodeType);
  15906. if (isElement$6(nativeChild)) {
  15907. const attributes = nativeChild.attributes;
  15908. for (let ai = 0, al = attributes.length; ai < al; ai++) {
  15909. const attr = attributes[ai];
  15910. child.attr(attr.name, attr.value);
  15911. }
  15912. } else if (isText$9(nativeChild)) {
  15913. child.value = nativeChild.data;
  15914. if (isSpecial) {
  15915. child.raw = true;
  15916. }
  15917. } else if (isComment(nativeChild) || isCData(nativeChild) || isPi(nativeChild)) {
  15918. child.value = nativeChild.data;
  15919. }
  15920. transferChildren(child, nativeChild, specialElements);
  15921. parent.append(child);
  15922. }
  15923. };
  15924. const walkTree = (root, preprocessors, postprocessors) => {
  15925. const traverseOrder = [];
  15926. for (let node = root, lastNode = node; isNonNullable(node); lastNode = node, node = node.walk()) {
  15927. each$f(preprocessors, preprocess => preprocess(node));
  15928. if (isNullable(node.parent) && node !== root) {
  15929. node = lastNode;
  15930. } else {
  15931. traverseOrder.push(node);
  15932. }
  15933. }
  15934. for (let i = traverseOrder.length - 1; i >= 0; i--) {
  15935. const node = traverseOrder[i];
  15936. each$f(postprocessors, postprocess => postprocess(node));
  15937. }
  15938. };
  15939. const whitespaceCleaner = (root, schema, settings, args) => {
  15940. const validate = settings.validate;
  15941. const nonEmptyElements = schema.getNonEmptyElements();
  15942. const whitespaceElements = schema.getWhitespaceElements();
  15943. const blockElements = extend$1(makeMap('script,style,head,html,body,title,meta,param'), schema.getBlockElements());
  15944. const textRootBlockElements = getTextRootBlockElements(schema);
  15945. const allWhiteSpaceRegExp = /[ \t\r\n]+/g;
  15946. const startWhiteSpaceRegExp = /^[ \t\r\n]+/;
  15947. const endWhiteSpaceRegExp = /[ \t\r\n]+$/;
  15948. const hasWhitespaceParent = node => {
  15949. node = node.parent;
  15950. while (isNonNullable(node)) {
  15951. if (node.name in whitespaceElements) {
  15952. return true;
  15953. } else {
  15954. node = node.parent;
  15955. }
  15956. }
  15957. return false;
  15958. };
  15959. const isTextRootBlockEmpty = node => {
  15960. let tempNode = node;
  15961. while (isNonNullable(tempNode)) {
  15962. if (tempNode.name in textRootBlockElements) {
  15963. return isEmpty(schema, nonEmptyElements, whitespaceElements, tempNode);
  15964. } else {
  15965. tempNode = tempNode.parent;
  15966. }
  15967. }
  15968. return false;
  15969. };
  15970. const isAtEdgeOfBlock = (node, start) => {
  15971. const neighbour = start ? node.prev : node.next;
  15972. if (isNonNullable(neighbour)) {
  15973. return false;
  15974. }
  15975. return node.parent.name in blockElements && (node.parent !== root || args.isRootContent);
  15976. };
  15977. const preprocess = node => {
  15978. if (node.type === 3) {
  15979. if (!hasWhitespaceParent(node)) {
  15980. let text = node.value;
  15981. text = text.replace(allWhiteSpaceRegExp, ' ');
  15982. if (isLineBreakNode(node.prev, blockElements) || isAtEdgeOfBlock(node, true)) {
  15983. text = text.replace(startWhiteSpaceRegExp, '');
  15984. }
  15985. if (text.length === 0) {
  15986. node.remove();
  15987. } else {
  15988. node.value = text;
  15989. }
  15990. }
  15991. }
  15992. };
  15993. const postprocess = node => {
  15994. var _a;
  15995. if (node.type === 1) {
  15996. const elementRule = schema.getElementRule(node.name);
  15997. if (validate && elementRule) {
  15998. const isNodeEmpty = isEmpty(schema, nonEmptyElements, whitespaceElements, node);
  15999. if (elementRule.paddInEmptyBlock && isNodeEmpty && isTextRootBlockEmpty(node)) {
  16000. paddEmptyNode(settings, args, blockElements, node);
  16001. } else if (elementRule.removeEmpty && isNodeEmpty) {
  16002. if (blockElements[node.name]) {
  16003. node.remove();
  16004. } else {
  16005. node.unwrap();
  16006. }
  16007. } else if (elementRule.paddEmpty && (isNodeEmpty || isPaddedWithNbsp(node))) {
  16008. paddEmptyNode(settings, args, blockElements, node);
  16009. }
  16010. }
  16011. } else if (node.type === 3) {
  16012. if (!hasWhitespaceParent(node)) {
  16013. let text = node.value;
  16014. if (blockElements[(_a = node.next) === null || _a === void 0 ? void 0 : _a.name] || isAtEdgeOfBlock(node, false)) {
  16015. text = text.replace(endWhiteSpaceRegExp, '');
  16016. }
  16017. if (text.length === 0) {
  16018. node.remove();
  16019. } else {
  16020. node.value = text;
  16021. }
  16022. }
  16023. }
  16024. };
  16025. return [
  16026. preprocess,
  16027. postprocess
  16028. ];
  16029. };
  16030. const getRootBlockName = (settings, args) => {
  16031. var _a;
  16032. const name = (_a = args.forced_root_block) !== null && _a !== void 0 ? _a : settings.forced_root_block;
  16033. if (name === false) {
  16034. return '';
  16035. } else if (name === true) {
  16036. return 'p';
  16037. } else {
  16038. return name;
  16039. }
  16040. };
  16041. const DomParser = (settings = {}, schema = Schema()) => {
  16042. const nodeFilterRegistry = create$7();
  16043. const attributeFilterRegistry = create$7();
  16044. const defaultedSettings = {
  16045. validate: true,
  16046. root_name: 'body',
  16047. ...settings
  16048. };
  16049. const parser = new DOMParser();
  16050. const purify = setupPurify(defaultedSettings, schema);
  16051. const parseAndSanitizeWithContext = (html, rootName, format = 'html') => {
  16052. const mimeType = format === 'xhtml' ? 'application/xhtml+xml' : 'text/html';
  16053. const isSpecialRoot = has$2(schema.getSpecialElements(), rootName.toLowerCase());
  16054. const content = isSpecialRoot ? `<${ rootName }>${ html }</${ rootName }>` : html;
  16055. const wrappedHtml = format === 'xhtml' ? `<html xmlns="http://www.w3.org/1999/xhtml"><head></head><body>${ content }</body></html>` : `<body>${ content }</body>`;
  16056. const body = parser.parseFromString(wrappedHtml, mimeType).body;
  16057. purify.sanitize(body, getPurifyConfig(defaultedSettings, mimeType));
  16058. purify.removed = [];
  16059. return isSpecialRoot ? body.firstChild : body;
  16060. };
  16061. const addNodeFilter = nodeFilterRegistry.addFilter;
  16062. const getNodeFilters = nodeFilterRegistry.getFilters;
  16063. const removeNodeFilter = nodeFilterRegistry.removeFilter;
  16064. const addAttributeFilter = attributeFilterRegistry.addFilter;
  16065. const getAttributeFilters = attributeFilterRegistry.getFilters;
  16066. const removeAttributeFilter = attributeFilterRegistry.removeFilter;
  16067. const findInvalidChildren = (node, invalidChildren) => {
  16068. const parent = node.parent;
  16069. if (parent && schema.children[node.name] && !schema.isValidChild(parent.name, node.name)) {
  16070. invalidChildren.push(node);
  16071. }
  16072. };
  16073. const addRootBlocks = (rootNode, rootBlockName) => {
  16074. const blockElements = extend$1(makeMap('script,style,head,html,body,title,meta,param'), schema.getBlockElements());
  16075. const startWhiteSpaceRegExp = /^[ \t\r\n]+/;
  16076. const endWhiteSpaceRegExp = /[ \t\r\n]+$/;
  16077. let node = rootNode.firstChild, rootBlockNode = null;
  16078. const trim = rootBlock => {
  16079. if (rootBlock) {
  16080. node = rootBlock.firstChild;
  16081. if (node && node.type === 3) {
  16082. node.value = node.value.replace(startWhiteSpaceRegExp, '');
  16083. }
  16084. node = rootBlock.lastChild;
  16085. if (node && node.type === 3) {
  16086. node.value = node.value.replace(endWhiteSpaceRegExp, '');
  16087. }
  16088. }
  16089. };
  16090. if (!schema.isValidChild(rootNode.name, rootBlockName.toLowerCase())) {
  16091. return;
  16092. }
  16093. while (node) {
  16094. const next = node.next;
  16095. if (node.type === 3 || node.type === 1 && node.name !== 'p' && !blockElements[node.name] && !node.attr(internalElementAttr)) {
  16096. if (!rootBlockNode) {
  16097. rootBlockNode = new AstNode(rootBlockName, 1);
  16098. rootBlockNode.attr(defaultedSettings.forced_root_block_attrs);
  16099. rootNode.insert(rootBlockNode, node);
  16100. rootBlockNode.append(node);
  16101. } else {
  16102. rootBlockNode.append(node);
  16103. }
  16104. } else {
  16105. trim(rootBlockNode);
  16106. rootBlockNode = null;
  16107. }
  16108. node = next;
  16109. }
  16110. trim(rootBlockNode);
  16111. };
  16112. const parse = (html, args = {}) => {
  16113. var _a;
  16114. const validate = defaultedSettings.validate;
  16115. const rootName = (_a = args.context) !== null && _a !== void 0 ? _a : defaultedSettings.root_name;
  16116. const element = parseAndSanitizeWithContext(html, rootName, args.format);
  16117. const rootNode = new AstNode(rootName, 11);
  16118. transferChildren(rootNode, element, schema.getSpecialElements());
  16119. const [whitespacePre, whitespacePost] = whitespaceCleaner(rootNode, schema, defaultedSettings, args);
  16120. const invalidChildren = [];
  16121. const invalidFinder = validate ? node => findInvalidChildren(node, invalidChildren) : noop;
  16122. const matches = {
  16123. nodes: {},
  16124. attributes: {}
  16125. };
  16126. const matchFinder = node => matchNode$1(getNodeFilters(), getAttributeFilters(), node, matches);
  16127. walkTree(rootNode, [
  16128. whitespacePre,
  16129. matchFinder
  16130. ], [
  16131. whitespacePost,
  16132. invalidFinder
  16133. ]);
  16134. invalidChildren.reverse();
  16135. if (validate && invalidChildren.length > 0) {
  16136. if (args.context) {
  16137. const {
  16138. pass: topLevelChildren,
  16139. fail: otherChildren
  16140. } = partition$2(invalidChildren, child => child.parent === rootNode);
  16141. cleanInvalidNodes(otherChildren, schema, matchFinder);
  16142. args.invalid = topLevelChildren.length > 0;
  16143. } else {
  16144. cleanInvalidNodes(invalidChildren, schema, matchFinder);
  16145. }
  16146. }
  16147. const rootBlockName = getRootBlockName(defaultedSettings, args);
  16148. if (rootBlockName && (rootNode.name === 'body' || args.isRootContent)) {
  16149. addRootBlocks(rootNode, rootBlockName);
  16150. }
  16151. if (!args.invalid) {
  16152. runFilters(matches, args);
  16153. }
  16154. return rootNode;
  16155. };
  16156. const exports = {
  16157. schema,
  16158. addAttributeFilter,
  16159. getAttributeFilters,
  16160. removeAttributeFilter,
  16161. addNodeFilter,
  16162. getNodeFilters,
  16163. removeNodeFilter,
  16164. parse
  16165. };
  16166. register$4(exports, defaultedSettings);
  16167. register$5(exports, defaultedSettings, schema);
  16168. return exports;
  16169. };
  16170. const serializeContent = content => isTreeNode(content) ? HtmlSerializer({ validate: false }).serialize(content) : content;
  16171. const withSerializedContent = (content, fireEvent) => {
  16172. const serializedContent = serializeContent(content);
  16173. const eventArgs = fireEvent(serializedContent);
  16174. if (eventArgs.isDefaultPrevented()) {
  16175. return eventArgs;
  16176. } else if (isTreeNode(content)) {
  16177. if (eventArgs.content !== serializedContent) {
  16178. const rootNode = DomParser({
  16179. validate: false,
  16180. forced_root_block: false
  16181. }).parse(eventArgs.content, { context: content.name });
  16182. return {
  16183. ...eventArgs,
  16184. content: rootNode
  16185. };
  16186. } else {
  16187. return {
  16188. ...eventArgs,
  16189. content
  16190. };
  16191. }
  16192. } else {
  16193. return eventArgs;
  16194. }
  16195. };
  16196. const preProcessGetContent = (editor, args) => {
  16197. if (args.no_events) {
  16198. return Result.value(args);
  16199. } else {
  16200. const eventArgs = fireBeforeGetContent(editor, args);
  16201. if (eventArgs.isDefaultPrevented()) {
  16202. return Result.error(fireGetContent(editor, {
  16203. content: '',
  16204. ...eventArgs
  16205. }).content);
  16206. } else {
  16207. return Result.value(eventArgs);
  16208. }
  16209. }
  16210. };
  16211. const postProcessGetContent = (editor, content, args) => {
  16212. if (args.no_events) {
  16213. return content;
  16214. } else {
  16215. const processedEventArgs = withSerializedContent(content, c => fireGetContent(editor, {
  16216. ...args,
  16217. content: c
  16218. }));
  16219. return processedEventArgs.content;
  16220. }
  16221. };
  16222. const preProcessSetContent = (editor, args) => {
  16223. if (args.no_events) {
  16224. return Result.value(args);
  16225. } else {
  16226. const processedEventArgs = withSerializedContent(args.content, content => fireBeforeSetContent(editor, {
  16227. ...args,
  16228. content
  16229. }));
  16230. if (processedEventArgs.isDefaultPrevented()) {
  16231. fireSetContent(editor, processedEventArgs);
  16232. return Result.error(undefined);
  16233. } else {
  16234. return Result.value(processedEventArgs);
  16235. }
  16236. }
  16237. };
  16238. const postProcessSetContent = (editor, content, args) => {
  16239. if (!args.no_events) {
  16240. fireSetContent(editor, {
  16241. ...args,
  16242. content
  16243. });
  16244. }
  16245. };
  16246. const tableModel = (element, width, rows) => ({
  16247. element,
  16248. width,
  16249. rows
  16250. });
  16251. const tableRow = (element, cells) => ({
  16252. element,
  16253. cells
  16254. });
  16255. const cellPosition = (x, y) => ({
  16256. x,
  16257. y
  16258. });
  16259. const getSpan = (td, key) => {
  16260. const value = parseInt(get$9(td, key), 10);
  16261. return isNaN(value) ? 1 : value;
  16262. };
  16263. const fillout = (table, x, y, tr, td) => {
  16264. const rowspan = getSpan(td, 'rowspan');
  16265. const colspan = getSpan(td, 'colspan');
  16266. const rows = table.rows;
  16267. for (let y2 = y; y2 < y + rowspan; y2++) {
  16268. if (!rows[y2]) {
  16269. rows[y2] = tableRow(deep$1(tr), []);
  16270. }
  16271. for (let x2 = x; x2 < x + colspan; x2++) {
  16272. const cells = rows[y2].cells;
  16273. cells[x2] = y2 === y && x2 === x ? td : shallow$1(td);
  16274. }
  16275. }
  16276. };
  16277. const cellExists = (table, x, y) => {
  16278. const rows = table.rows;
  16279. const cells = rows[y] ? rows[y].cells : [];
  16280. return !!cells[x];
  16281. };
  16282. const skipCellsX = (table, x, y) => {
  16283. while (cellExists(table, x, y)) {
  16284. x++;
  16285. }
  16286. return x;
  16287. };
  16288. const getWidth = rows => {
  16289. return foldl(rows, (acc, row) => {
  16290. return row.cells.length > acc ? row.cells.length : acc;
  16291. }, 0);
  16292. };
  16293. const findElementPos = (table, element) => {
  16294. const rows = table.rows;
  16295. for (let y = 0; y < rows.length; y++) {
  16296. const cells = rows[y].cells;
  16297. for (let x = 0; x < cells.length; x++) {
  16298. if (eq(cells[x], element)) {
  16299. return Optional.some(cellPosition(x, y));
  16300. }
  16301. }
  16302. }
  16303. return Optional.none();
  16304. };
  16305. const extractRows = (table, sx, sy, ex, ey) => {
  16306. const newRows = [];
  16307. const rows = table.rows;
  16308. for (let y = sy; y <= ey; y++) {
  16309. const cells = rows[y].cells;
  16310. const slice = sx < ex ? cells.slice(sx, ex + 1) : cells.slice(ex, sx + 1);
  16311. newRows.push(tableRow(rows[y].element, slice));
  16312. }
  16313. return newRows;
  16314. };
  16315. const subTable = (table, startPos, endPos) => {
  16316. const sx = startPos.x, sy = startPos.y;
  16317. const ex = endPos.x, ey = endPos.y;
  16318. const newRows = sy < ey ? extractRows(table, sx, sy, ex, ey) : extractRows(table, sx, ey, ex, sy);
  16319. return tableModel(table.element, getWidth(newRows), newRows);
  16320. };
  16321. const createDomTable = (table, rows) => {
  16322. const tableElement = shallow$1(table.element);
  16323. const tableBody = SugarElement.fromTag('tbody');
  16324. append(tableBody, rows);
  16325. append$1(tableElement, tableBody);
  16326. return tableElement;
  16327. };
  16328. const modelRowsToDomRows = table => {
  16329. return map$3(table.rows, row => {
  16330. const cells = map$3(row.cells, cell => {
  16331. const td = deep$1(cell);
  16332. remove$b(td, 'colspan');
  16333. remove$b(td, 'rowspan');
  16334. return td;
  16335. });
  16336. const tr = shallow$1(row.element);
  16337. append(tr, cells);
  16338. return tr;
  16339. });
  16340. };
  16341. const fromDom = tableElm => {
  16342. const table = tableModel(shallow$1(tableElm), 0, []);
  16343. each$f(descendants(tableElm, 'tr'), (tr, y) => {
  16344. each$f(descendants(tr, 'td,th'), (td, x) => {
  16345. fillout(table, skipCellsX(table, x, y), y, tr, td);
  16346. });
  16347. });
  16348. return tableModel(table.element, getWidth(table.rows), table.rows);
  16349. };
  16350. const toDom = table => {
  16351. return createDomTable(table, modelRowsToDomRows(table));
  16352. };
  16353. const subsection = (table, startElement, endElement) => {
  16354. return findElementPos(table, startElement).bind(startPos => {
  16355. return findElementPos(table, endElement).map(endPos => {
  16356. return subTable(table, startPos, endPos);
  16357. });
  16358. });
  16359. };
  16360. const findParentListContainer = parents => find$2(parents, elm => name(elm) === 'ul' || name(elm) === 'ol');
  16361. const getFullySelectedListWrappers = (parents, rng) => find$2(parents, elm => name(elm) === 'li' && hasAllContentsSelected(elm, rng)).fold(constant([]), _li => findParentListContainer(parents).map(listCont => {
  16362. const listElm = SugarElement.fromTag(name(listCont));
  16363. const listStyles = filter$5(getAllRaw(listCont), (_style, name) => startsWith(name, 'list-style'));
  16364. setAll(listElm, listStyles);
  16365. return [
  16366. SugarElement.fromTag('li'),
  16367. listElm
  16368. ];
  16369. }).getOr([]));
  16370. const wrap = (innerElm, elms) => {
  16371. const wrapped = foldl(elms, (acc, elm) => {
  16372. append$1(elm, acc);
  16373. return elm;
  16374. }, innerElm);
  16375. return elms.length > 0 ? fromElements([wrapped]) : wrapped;
  16376. };
  16377. const directListWrappers = commonAnchorContainer => {
  16378. if (isListItem(commonAnchorContainer)) {
  16379. return parent(commonAnchorContainer).filter(isList).fold(constant([]), listElm => [
  16380. commonAnchorContainer,
  16381. listElm
  16382. ]);
  16383. } else {
  16384. return isList(commonAnchorContainer) ? [commonAnchorContainer] : [];
  16385. }
  16386. };
  16387. const getWrapElements = (rootNode, rng) => {
  16388. const commonAnchorContainer = SugarElement.fromDom(rng.commonAncestorContainer);
  16389. const parents = parentsAndSelf(commonAnchorContainer, rootNode);
  16390. const wrapElements = filter$6(parents, isWrapElement);
  16391. const listWrappers = getFullySelectedListWrappers(parents, rng);
  16392. const allWrappers = wrapElements.concat(listWrappers.length ? listWrappers : directListWrappers(commonAnchorContainer));
  16393. return map$3(allWrappers, shallow$1);
  16394. };
  16395. const emptyFragment = () => fromElements([]);
  16396. const getFragmentFromRange = (rootNode, rng) => wrap(SugarElement.fromDom(rng.cloneContents()), getWrapElements(rootNode, rng));
  16397. const getParentTable = (rootElm, cell) => ancestor$2(cell, 'table', curry(eq, rootElm));
  16398. const getTableFragment = (rootNode, selectedTableCells) => getParentTable(rootNode, selectedTableCells[0]).bind(tableElm => {
  16399. const firstCell = selectedTableCells[0];
  16400. const lastCell = selectedTableCells[selectedTableCells.length - 1];
  16401. const fullTableModel = fromDom(tableElm);
  16402. return subsection(fullTableModel, firstCell, lastCell).map(sectionedTableModel => fromElements([toDom(sectionedTableModel)]));
  16403. }).getOrThunk(emptyFragment);
  16404. const getSelectionFragment = (rootNode, ranges) => ranges.length > 0 && ranges[0].collapsed ? emptyFragment() : getFragmentFromRange(rootNode, ranges[0]);
  16405. const read$3 = (rootNode, ranges) => {
  16406. const selectedCells = getCellsFromElementOrRanges(ranges, rootNode);
  16407. return selectedCells.length > 0 ? getTableFragment(rootNode, selectedCells) : getSelectionFragment(rootNode, ranges);
  16408. };
  16409. const isCollapsibleWhitespace = (text, index) => index >= 0 && index < text.length && isWhiteSpace(text.charAt(index));
  16410. const getInnerText = bin => {
  16411. return trim$1(bin.innerText);
  16412. };
  16413. const getContextNodeName = parentBlockOpt => parentBlockOpt.map(block => block.nodeName).getOr('div').toLowerCase();
  16414. const getTextContent = editor => Optional.from(editor.selection.getRng()).map(rng => {
  16415. const parentBlockOpt = Optional.from(editor.dom.getParent(rng.commonAncestorContainer, editor.dom.isBlock));
  16416. const body = editor.getBody();
  16417. const contextNodeName = getContextNodeName(parentBlockOpt);
  16418. const bin = editor.dom.add(body, contextNodeName, {
  16419. 'data-mce-bogus': 'all',
  16420. 'style': 'overflow: hidden; opacity: 0;'
  16421. }, rng.cloneContents());
  16422. const text = getInnerText(bin);
  16423. const nonRenderedText = trim$1(bin.textContent);
  16424. editor.dom.remove(bin);
  16425. if (isCollapsibleWhitespace(nonRenderedText, 0) || isCollapsibleWhitespace(nonRenderedText, nonRenderedText.length - 1)) {
  16426. const parentBlock = parentBlockOpt.getOr(body);
  16427. const parentBlockText = getInnerText(parentBlock);
  16428. const textIndex = parentBlockText.indexOf(text);
  16429. if (textIndex === -1) {
  16430. return text;
  16431. } else {
  16432. const hasProceedingSpace = isCollapsibleWhitespace(parentBlockText, textIndex - 1);
  16433. const hasTrailingSpace = isCollapsibleWhitespace(parentBlockText, textIndex + text.length);
  16434. return (hasProceedingSpace ? ' ' : '') + text + (hasTrailingSpace ? ' ' : '');
  16435. }
  16436. } else {
  16437. return text;
  16438. }
  16439. }).getOr('');
  16440. const getSerializedContent = (editor, args) => {
  16441. const rng = editor.selection.getRng(), tmpElm = editor.dom.create('body');
  16442. const sel = editor.selection.getSel();
  16443. const ranges = processRanges(editor, getRanges$1(sel));
  16444. const fragment = args.contextual ? read$3(SugarElement.fromDom(editor.getBody()), ranges).dom : rng.cloneContents();
  16445. if (fragment) {
  16446. tmpElm.appendChild(fragment);
  16447. }
  16448. return editor.selection.serializer.serialize(tmpElm, args);
  16449. };
  16450. const extractSelectedContent = (editor, args) => {
  16451. if (args.format === 'text') {
  16452. return getTextContent(editor);
  16453. } else {
  16454. const content = getSerializedContent(editor, args);
  16455. if (args.format === 'tree') {
  16456. return content;
  16457. } else {
  16458. return editor.selection.isCollapsed() ? '' : content;
  16459. }
  16460. }
  16461. };
  16462. const setupArgs$3 = (args, format) => ({
  16463. ...args,
  16464. format,
  16465. get: true,
  16466. selection: true,
  16467. getInner: true
  16468. });
  16469. const getSelectedContentInternal = (editor, format, args = {}) => {
  16470. const defaultedArgs = setupArgs$3(args, format);
  16471. return preProcessGetContent(editor, defaultedArgs).fold(identity, updatedArgs => {
  16472. const content = extractSelectedContent(editor, updatedArgs);
  16473. return postProcessGetContent(editor, content, updatedArgs);
  16474. });
  16475. };
  16476. const KEEP = 0, INSERT = 1, DELETE = 2;
  16477. const diff = (left, right) => {
  16478. const size = left.length + right.length + 2;
  16479. const vDown = new Array(size);
  16480. const vUp = new Array(size);
  16481. const snake = (start, end, diag) => {
  16482. return {
  16483. start,
  16484. end,
  16485. diag
  16486. };
  16487. };
  16488. const buildScript = (start1, end1, start2, end2, script) => {
  16489. const middle = getMiddleSnake(start1, end1, start2, end2);
  16490. if (middle === null || middle.start === end1 && middle.diag === end1 - end2 || middle.end === start1 && middle.diag === start1 - start2) {
  16491. let i = start1;
  16492. let j = start2;
  16493. while (i < end1 || j < end2) {
  16494. if (i < end1 && j < end2 && left[i] === right[j]) {
  16495. script.push([
  16496. KEEP,
  16497. left[i]
  16498. ]);
  16499. ++i;
  16500. ++j;
  16501. } else {
  16502. if (end1 - start1 > end2 - start2) {
  16503. script.push([
  16504. DELETE,
  16505. left[i]
  16506. ]);
  16507. ++i;
  16508. } else {
  16509. script.push([
  16510. INSERT,
  16511. right[j]
  16512. ]);
  16513. ++j;
  16514. }
  16515. }
  16516. }
  16517. } else {
  16518. buildScript(start1, middle.start, start2, middle.start - middle.diag, script);
  16519. for (let i2 = middle.start; i2 < middle.end; ++i2) {
  16520. script.push([
  16521. KEEP,
  16522. left[i2]
  16523. ]);
  16524. }
  16525. buildScript(middle.end, end1, middle.end - middle.diag, end2, script);
  16526. }
  16527. };
  16528. const buildSnake = (start, diag, end1, end2) => {
  16529. let end = start;
  16530. while (end - diag < end2 && end < end1 && left[end] === right[end - diag]) {
  16531. ++end;
  16532. }
  16533. return snake(start, end, diag);
  16534. };
  16535. const getMiddleSnake = (start1, end1, start2, end2) => {
  16536. const m = end1 - start1;
  16537. const n = end2 - start2;
  16538. if (m === 0 || n === 0) {
  16539. return null;
  16540. }
  16541. const delta = m - n;
  16542. const sum = n + m;
  16543. const offset = (sum % 2 === 0 ? sum : sum + 1) / 2;
  16544. vDown[1 + offset] = start1;
  16545. vUp[1 + offset] = end1 + 1;
  16546. let d, k, i, x, y;
  16547. for (d = 0; d <= offset; ++d) {
  16548. for (k = -d; k <= d; k += 2) {
  16549. i = k + offset;
  16550. if (k === -d || k !== d && vDown[i - 1] < vDown[i + 1]) {
  16551. vDown[i] = vDown[i + 1];
  16552. } else {
  16553. vDown[i] = vDown[i - 1] + 1;
  16554. }
  16555. x = vDown[i];
  16556. y = x - start1 + start2 - k;
  16557. while (x < end1 && y < end2 && left[x] === right[y]) {
  16558. vDown[i] = ++x;
  16559. ++y;
  16560. }
  16561. if (delta % 2 !== 0 && delta - d <= k && k <= delta + d) {
  16562. if (vUp[i - delta] <= vDown[i]) {
  16563. return buildSnake(vUp[i - delta], k + start1 - start2, end1, end2);
  16564. }
  16565. }
  16566. }
  16567. for (k = delta - d; k <= delta + d; k += 2) {
  16568. i = k + offset - delta;
  16569. if (k === delta - d || k !== delta + d && vUp[i + 1] <= vUp[i - 1]) {
  16570. vUp[i] = vUp[i + 1] - 1;
  16571. } else {
  16572. vUp[i] = vUp[i - 1];
  16573. }
  16574. x = vUp[i] - 1;
  16575. y = x - start1 + start2 - k;
  16576. while (x >= start1 && y >= start2 && left[x] === right[y]) {
  16577. vUp[i] = x--;
  16578. y--;
  16579. }
  16580. if (delta % 2 === 0 && -d <= k && k <= d) {
  16581. if (vUp[i] <= vDown[i + delta]) {
  16582. return buildSnake(vUp[i], k + start1 - start2, end1, end2);
  16583. }
  16584. }
  16585. }
  16586. }
  16587. };
  16588. const script = [];
  16589. buildScript(0, left.length, 0, right.length, script);
  16590. return script;
  16591. };
  16592. const getOuterHtml = elm => {
  16593. if (isElement$6(elm)) {
  16594. return elm.outerHTML;
  16595. } else if (isText$9(elm)) {
  16596. return Entities.encodeRaw(elm.data, false);
  16597. } else if (isComment(elm)) {
  16598. return '<!--' + elm.data + '-->';
  16599. }
  16600. return '';
  16601. };
  16602. const createFragment = html => {
  16603. let node;
  16604. const container = document.createElement('div');
  16605. const frag = document.createDocumentFragment();
  16606. if (html) {
  16607. container.innerHTML = html;
  16608. }
  16609. while (node = container.firstChild) {
  16610. frag.appendChild(node);
  16611. }
  16612. return frag;
  16613. };
  16614. const insertAt = (elm, html, index) => {
  16615. const fragment = createFragment(html);
  16616. if (elm.hasChildNodes() && index < elm.childNodes.length) {
  16617. const target = elm.childNodes[index];
  16618. target.parentNode.insertBefore(fragment, target);
  16619. } else {
  16620. elm.appendChild(fragment);
  16621. }
  16622. };
  16623. const removeAt = (elm, index) => {
  16624. if (elm.hasChildNodes() && index < elm.childNodes.length) {
  16625. const target = elm.childNodes[index];
  16626. target.parentNode.removeChild(target);
  16627. }
  16628. };
  16629. const applyDiff = (diff, elm) => {
  16630. let index = 0;
  16631. each$f(diff, action => {
  16632. if (action[0] === KEEP) {
  16633. index++;
  16634. } else if (action[0] === INSERT) {
  16635. insertAt(elm, action[1], index);
  16636. index++;
  16637. } else if (action[0] === DELETE) {
  16638. removeAt(elm, index);
  16639. }
  16640. });
  16641. };
  16642. const read$2 = elm => {
  16643. return filter$6(map$3(from(elm.childNodes), getOuterHtml), item => {
  16644. return item.length > 0;
  16645. });
  16646. };
  16647. const write = (fragments, elm) => {
  16648. const currentFragments = map$3(from(elm.childNodes), getOuterHtml);
  16649. applyDiff(diff(currentFragments, fragments), elm);
  16650. return elm;
  16651. };
  16652. const lazyTempDocument = cached(() => document.implementation.createHTMLDocument('undo'));
  16653. const hasIframes = html => {
  16654. return html.indexOf('</iframe>') !== -1;
  16655. };
  16656. const createFragmentedLevel = fragments => {
  16657. return {
  16658. type: 'fragmented',
  16659. fragments,
  16660. content: '',
  16661. bookmark: null,
  16662. beforeBookmark: null
  16663. };
  16664. };
  16665. const createCompleteLevel = content => {
  16666. return {
  16667. type: 'complete',
  16668. fragments: null,
  16669. content,
  16670. bookmark: null,
  16671. beforeBookmark: null
  16672. };
  16673. };
  16674. const createFromEditor = editor => {
  16675. const fragments = read$2(editor.getBody());
  16676. const trimmedFragments = bind$3(fragments, html => {
  16677. const trimmed = trimInternal(editor.serializer, html);
  16678. return trimmed.length > 0 ? [trimmed] : [];
  16679. });
  16680. const content = trimmedFragments.join('');
  16681. return hasIframes(content) ? createFragmentedLevel(trimmedFragments) : createCompleteLevel(content);
  16682. };
  16683. const applyToEditor = (editor, level, before) => {
  16684. const bookmark = before ? level.beforeBookmark : level.bookmark;
  16685. if (level.type === 'fragmented') {
  16686. write(level.fragments, editor.getBody());
  16687. } else {
  16688. editor.setContent(level.content, {
  16689. format: 'raw',
  16690. no_selection: isNonNullable(bookmark) && isPathBookmark(bookmark) ? !bookmark.isFakeCaret : true
  16691. });
  16692. }
  16693. editor.selection.moveToBookmark(bookmark);
  16694. };
  16695. const getLevelContent = level => {
  16696. return level.type === 'fragmented' ? level.fragments.join('') : level.content;
  16697. };
  16698. const getCleanLevelContent = level => {
  16699. const elm = SugarElement.fromTag('body', lazyTempDocument());
  16700. set(elm, getLevelContent(level));
  16701. each$f(descendants(elm, '*[data-mce-bogus]'), unwrap);
  16702. return get$6(elm);
  16703. };
  16704. const hasEqualContent = (level1, level2) => getLevelContent(level1) === getLevelContent(level2);
  16705. const hasEqualCleanedContent = (level1, level2) => getCleanLevelContent(level1) === getCleanLevelContent(level2);
  16706. const isEq$1 = (level1, level2) => {
  16707. if (!level1 || !level2) {
  16708. return false;
  16709. } else if (hasEqualContent(level1, level2)) {
  16710. return true;
  16711. } else {
  16712. return hasEqualCleanedContent(level1, level2);
  16713. }
  16714. };
  16715. const isUnlocked = locks => locks.get() === 0;
  16716. const setTyping = (undoManager, typing, locks) => {
  16717. if (isUnlocked(locks)) {
  16718. undoManager.typing = typing;
  16719. }
  16720. };
  16721. const endTyping = (undoManager, locks) => {
  16722. if (undoManager.typing) {
  16723. setTyping(undoManager, false, locks);
  16724. undoManager.add();
  16725. }
  16726. };
  16727. const endTypingLevelIgnoreLocks = undoManager => {
  16728. if (undoManager.typing) {
  16729. undoManager.typing = false;
  16730. undoManager.add();
  16731. }
  16732. };
  16733. const beforeChange$1 = (editor, locks, beforeBookmark) => {
  16734. if (isUnlocked(locks)) {
  16735. beforeBookmark.set(getUndoBookmark(editor.selection));
  16736. }
  16737. };
  16738. const addUndoLevel$1 = (editor, undoManager, index, locks, beforeBookmark, level, event) => {
  16739. const currentLevel = createFromEditor(editor);
  16740. level = level || {};
  16741. level = Tools.extend(level, currentLevel);
  16742. if (isUnlocked(locks) === false || editor.removed) {
  16743. return null;
  16744. }
  16745. const lastLevel = undoManager.data[index.get()];
  16746. if (editor.dispatch('BeforeAddUndo', {
  16747. level,
  16748. lastLevel,
  16749. originalEvent: event
  16750. }).isDefaultPrevented()) {
  16751. return null;
  16752. }
  16753. if (lastLevel && isEq$1(lastLevel, level)) {
  16754. return null;
  16755. }
  16756. if (undoManager.data[index.get()]) {
  16757. beforeBookmark.get().each(bm => {
  16758. undoManager.data[index.get()].beforeBookmark = bm;
  16759. });
  16760. }
  16761. const customUndoRedoLevels = getCustomUndoRedoLevels(editor);
  16762. if (customUndoRedoLevels) {
  16763. if (undoManager.data.length > customUndoRedoLevels) {
  16764. for (let i = 0; i < undoManager.data.length - 1; i++) {
  16765. undoManager.data[i] = undoManager.data[i + 1];
  16766. }
  16767. undoManager.data.length--;
  16768. index.set(undoManager.data.length);
  16769. }
  16770. }
  16771. level.bookmark = getUndoBookmark(editor.selection);
  16772. if (index.get() < undoManager.data.length - 1) {
  16773. undoManager.data.length = index.get() + 1;
  16774. }
  16775. undoManager.data.push(level);
  16776. index.set(undoManager.data.length - 1);
  16777. const args = {
  16778. level,
  16779. lastLevel,
  16780. originalEvent: event
  16781. };
  16782. if (index.get() > 0) {
  16783. editor.setDirty(true);
  16784. editor.dispatch('AddUndo', args);
  16785. editor.dispatch('change', args);
  16786. } else {
  16787. editor.dispatch('AddUndo', args);
  16788. }
  16789. return level;
  16790. };
  16791. const clear$1 = (editor, undoManager, index) => {
  16792. undoManager.data = [];
  16793. index.set(0);
  16794. undoManager.typing = false;
  16795. editor.dispatch('ClearUndos');
  16796. };
  16797. const extra$1 = (editor, undoManager, index, callback1, callback2) => {
  16798. if (undoManager.transact(callback1)) {
  16799. const bookmark = undoManager.data[index.get()].bookmark;
  16800. const lastLevel = undoManager.data[index.get() - 1];
  16801. applyToEditor(editor, lastLevel, true);
  16802. if (undoManager.transact(callback2)) {
  16803. undoManager.data[index.get() - 1].beforeBookmark = bookmark;
  16804. }
  16805. }
  16806. };
  16807. const redo$1 = (editor, index, data) => {
  16808. let level;
  16809. if (index.get() < data.length - 1) {
  16810. index.set(index.get() + 1);
  16811. level = data[index.get()];
  16812. applyToEditor(editor, level, false);
  16813. editor.setDirty(true);
  16814. editor.dispatch('Redo', { level });
  16815. }
  16816. return level;
  16817. };
  16818. const undo$1 = (editor, undoManager, locks, index) => {
  16819. let level;
  16820. if (undoManager.typing) {
  16821. undoManager.add();
  16822. undoManager.typing = false;
  16823. setTyping(undoManager, false, locks);
  16824. }
  16825. if (index.get() > 0) {
  16826. index.set(index.get() - 1);
  16827. level = undoManager.data[index.get()];
  16828. applyToEditor(editor, level, true);
  16829. editor.setDirty(true);
  16830. editor.dispatch('Undo', { level });
  16831. }
  16832. return level;
  16833. };
  16834. const reset$1 = undoManager => {
  16835. undoManager.clear();
  16836. undoManager.add();
  16837. };
  16838. const hasUndo$1 = (editor, undoManager, index) => index.get() > 0 || undoManager.typing && undoManager.data[0] && !isEq$1(createFromEditor(editor), undoManager.data[0]);
  16839. const hasRedo$1 = (undoManager, index) => index.get() < undoManager.data.length - 1 && !undoManager.typing;
  16840. const transact$1 = (undoManager, locks, callback) => {
  16841. endTyping(undoManager, locks);
  16842. undoManager.beforeChange();
  16843. undoManager.ignore(callback);
  16844. return undoManager.add();
  16845. };
  16846. const ignore$1 = (locks, callback) => {
  16847. try {
  16848. locks.set(locks.get() + 1);
  16849. callback();
  16850. } finally {
  16851. locks.set(locks.get() - 1);
  16852. }
  16853. };
  16854. const addVisualInternal = (editor, elm) => {
  16855. const dom = editor.dom;
  16856. const scope = isNonNullable(elm) ? elm : editor.getBody();
  16857. if (isUndefined(editor.hasVisual)) {
  16858. editor.hasVisual = isVisualAidsEnabled(editor);
  16859. }
  16860. each$f(dom.select('table,a', scope), matchedElm => {
  16861. switch (matchedElm.nodeName) {
  16862. case 'TABLE':
  16863. const cls = getVisualAidsTableClass(editor);
  16864. const value = dom.getAttrib(matchedElm, 'border');
  16865. if ((!value || value === '0') && editor.hasVisual) {
  16866. dom.addClass(matchedElm, cls);
  16867. } else {
  16868. dom.removeClass(matchedElm, cls);
  16869. }
  16870. break;
  16871. case 'A':
  16872. if (!dom.getAttrib(matchedElm, 'href')) {
  16873. const value = dom.getAttrib(matchedElm, 'name') || matchedElm.id;
  16874. const cls = getVisualAidsAnchorClass(editor);
  16875. if (value && editor.hasVisual) {
  16876. dom.addClass(matchedElm, cls);
  16877. } else {
  16878. dom.removeClass(matchedElm, cls);
  16879. }
  16880. }
  16881. break;
  16882. }
  16883. });
  16884. editor.dispatch('VisualAid', {
  16885. element: elm,
  16886. hasVisual: editor.hasVisual
  16887. });
  16888. };
  16889. const makePlainAdaptor = editor => ({
  16890. init: { bindEvents: noop },
  16891. undoManager: {
  16892. beforeChange: (locks, beforeBookmark) => beforeChange$1(editor, locks, beforeBookmark),
  16893. add: (undoManager, index, locks, beforeBookmark, level, event) => addUndoLevel$1(editor, undoManager, index, locks, beforeBookmark, level, event),
  16894. undo: (undoManager, locks, index) => undo$1(editor, undoManager, locks, index),
  16895. redo: (index, data) => redo$1(editor, index, data),
  16896. clear: (undoManager, index) => clear$1(editor, undoManager, index),
  16897. reset: undoManager => reset$1(undoManager),
  16898. hasUndo: (undoManager, index) => hasUndo$1(editor, undoManager, index),
  16899. hasRedo: (undoManager, index) => hasRedo$1(undoManager, index),
  16900. transact: (undoManager, locks, callback) => transact$1(undoManager, locks, callback),
  16901. ignore: (locks, callback) => ignore$1(locks, callback),
  16902. extra: (undoManager, index, callback1, callback2) => extra$1(editor, undoManager, index, callback1, callback2)
  16903. },
  16904. formatter: {
  16905. match: (name, vars, node, similar) => match$2(editor, name, vars, node, similar),
  16906. matchAll: (names, vars) => matchAll(editor, names, vars),
  16907. matchNode: (node, name, vars, similar) => matchNode(editor, node, name, vars, similar),
  16908. canApply: name => canApply(editor, name),
  16909. closest: names => closest$1(editor, names),
  16910. apply: (name, vars, node) => applyFormat$1(editor, name, vars, node),
  16911. remove: (name, vars, node, similar) => remove$2(editor, name, vars, node, similar),
  16912. toggle: (name, vars, node) => toggle(editor, name, vars, node),
  16913. formatChanged: (registeredFormatListeners, formats, callback, similar, vars) => formatChangedInternal(editor, registeredFormatListeners, formats, callback, similar, vars)
  16914. },
  16915. editor: {
  16916. getContent: args => getContentInternal(editor, args),
  16917. setContent: (content, args) => setContentInternal(editor, content, args),
  16918. insertContent: (value, details) => insertHtmlAtCaret(editor, value, details),
  16919. addVisual: elm => addVisualInternal(editor, elm)
  16920. },
  16921. selection: { getContent: (format, args) => getSelectedContentInternal(editor, format, args) },
  16922. autocompleter: {
  16923. addDecoration: range => create$9(editor, range),
  16924. removeDecoration: () => remove$3(editor, SugarElement.fromDom(editor.getBody()))
  16925. },
  16926. raw: { getModel: () => Optional.none() }
  16927. });
  16928. const makeRtcAdaptor = rtcEditor => {
  16929. const defaultVars = vars => isObject(vars) ? vars : {};
  16930. const {init, undoManager, formatter, editor, selection, autocompleter, raw} = rtcEditor;
  16931. return {
  16932. init: { bindEvents: init.bindEvents },
  16933. undoManager: {
  16934. beforeChange: undoManager.beforeChange,
  16935. add: undoManager.add,
  16936. undo: undoManager.undo,
  16937. redo: undoManager.redo,
  16938. clear: undoManager.clear,
  16939. reset: undoManager.reset,
  16940. hasUndo: undoManager.hasUndo,
  16941. hasRedo: undoManager.hasRedo,
  16942. transact: (_undoManager, _locks, fn) => undoManager.transact(fn),
  16943. ignore: (_locks, callback) => undoManager.ignore(callback),
  16944. extra: (_undoManager, _index, callback1, callback2) => undoManager.extra(callback1, callback2)
  16945. },
  16946. formatter: {
  16947. match: (name, vars, _node, similar) => formatter.match(name, defaultVars(vars), similar),
  16948. matchAll: formatter.matchAll,
  16949. matchNode: formatter.matchNode,
  16950. canApply: name => formatter.canApply(name),
  16951. closest: names => formatter.closest(names),
  16952. apply: (name, vars, _node) => formatter.apply(name, defaultVars(vars)),
  16953. remove: (name, vars, _node, _similar) => formatter.remove(name, defaultVars(vars)),
  16954. toggle: (name, vars, _node) => formatter.toggle(name, defaultVars(vars)),
  16955. formatChanged: (_rfl, formats, callback, similar, vars) => formatter.formatChanged(formats, callback, similar, vars)
  16956. },
  16957. editor: {
  16958. getContent: args => editor.getContent(args),
  16959. setContent: (content, args) => {
  16960. return {
  16961. content: editor.setContent(content, args),
  16962. html: ''
  16963. };
  16964. },
  16965. insertContent: (content, _details) => {
  16966. editor.insertContent(content);
  16967. return '';
  16968. },
  16969. addVisual: editor.addVisual
  16970. },
  16971. selection: { getContent: (_format, args) => selection.getContent(args) },
  16972. autocompleter: {
  16973. addDecoration: autocompleter.addDecoration,
  16974. removeDecoration: autocompleter.removeDecoration
  16975. },
  16976. raw: { getModel: () => Optional.some(raw.getRawModel()) }
  16977. };
  16978. };
  16979. const makeNoopAdaptor = () => {
  16980. const nul = constant(null);
  16981. const empty = constant('');
  16982. return {
  16983. init: { bindEvents: noop },
  16984. undoManager: {
  16985. beforeChange: noop,
  16986. add: nul,
  16987. undo: nul,
  16988. redo: nul,
  16989. clear: noop,
  16990. reset: noop,
  16991. hasUndo: never,
  16992. hasRedo: never,
  16993. transact: nul,
  16994. ignore: noop,
  16995. extra: noop
  16996. },
  16997. formatter: {
  16998. match: never,
  16999. matchAll: constant([]),
  17000. matchNode: constant(undefined),
  17001. canApply: never,
  17002. closest: empty,
  17003. apply: noop,
  17004. remove: noop,
  17005. toggle: noop,
  17006. formatChanged: constant({ unbind: noop })
  17007. },
  17008. editor: {
  17009. getContent: empty,
  17010. setContent: constant({
  17011. content: '',
  17012. html: ''
  17013. }),
  17014. insertContent: constant(''),
  17015. addVisual: noop
  17016. },
  17017. selection: { getContent: empty },
  17018. autocompleter: {
  17019. addDecoration: noop,
  17020. removeDecoration: noop
  17021. },
  17022. raw: { getModel: constant(Optional.none()) }
  17023. };
  17024. };
  17025. const isRtc = editor => has$2(editor.plugins, 'rtc');
  17026. const getRtcSetup = editor => get$a(editor.plugins, 'rtc').bind(rtcPlugin => Optional.from(rtcPlugin.setup));
  17027. const setup$s = editor => {
  17028. const editorCast = editor;
  17029. return getRtcSetup(editor).fold(() => {
  17030. editorCast.rtcInstance = makePlainAdaptor(editor);
  17031. return Optional.none();
  17032. }, setup => {
  17033. editorCast.rtcInstance = makeNoopAdaptor();
  17034. return Optional.some(() => setup().then(rtcEditor => {
  17035. editorCast.rtcInstance = makeRtcAdaptor(rtcEditor);
  17036. return rtcEditor.rtc.isRemote;
  17037. }));
  17038. });
  17039. };
  17040. const getRtcInstanceWithFallback = editor => editor.rtcInstance ? editor.rtcInstance : makePlainAdaptor(editor);
  17041. const getRtcInstanceWithError = editor => {
  17042. const rtcInstance = editor.rtcInstance;
  17043. if (!rtcInstance) {
  17044. throw new Error('Failed to get RTC instance not yet initialized.');
  17045. } else {
  17046. return rtcInstance;
  17047. }
  17048. };
  17049. const beforeChange = (editor, locks, beforeBookmark) => {
  17050. getRtcInstanceWithError(editor).undoManager.beforeChange(locks, beforeBookmark);
  17051. };
  17052. const addUndoLevel = (editor, undoManager, index, locks, beforeBookmark, level, event) => getRtcInstanceWithError(editor).undoManager.add(undoManager, index, locks, beforeBookmark, level, event);
  17053. const undo = (editor, undoManager, locks, index) => getRtcInstanceWithError(editor).undoManager.undo(undoManager, locks, index);
  17054. const redo = (editor, index, data) => getRtcInstanceWithError(editor).undoManager.redo(index, data);
  17055. const clear = (editor, undoManager, index) => {
  17056. getRtcInstanceWithError(editor).undoManager.clear(undoManager, index);
  17057. };
  17058. const reset = (editor, undoManager) => {
  17059. getRtcInstanceWithError(editor).undoManager.reset(undoManager);
  17060. };
  17061. const hasUndo = (editor, undoManager, index) => getRtcInstanceWithError(editor).undoManager.hasUndo(undoManager, index);
  17062. const hasRedo = (editor, undoManager, index) => getRtcInstanceWithError(editor).undoManager.hasRedo(undoManager, index);
  17063. const transact = (editor, undoManager, locks, callback) => getRtcInstanceWithError(editor).undoManager.transact(undoManager, locks, callback);
  17064. const ignore = (editor, locks, callback) => {
  17065. getRtcInstanceWithError(editor).undoManager.ignore(locks, callback);
  17066. };
  17067. const extra = (editor, undoManager, index, callback1, callback2) => {
  17068. getRtcInstanceWithError(editor).undoManager.extra(undoManager, index, callback1, callback2);
  17069. };
  17070. const matchFormat = (editor, name, vars, node, similar) => getRtcInstanceWithError(editor).formatter.match(name, vars, node, similar);
  17071. const matchAllFormats = (editor, names, vars) => getRtcInstanceWithError(editor).formatter.matchAll(names, vars);
  17072. const matchNodeFormat = (editor, node, name, vars, similar) => getRtcInstanceWithError(editor).formatter.matchNode(node, name, vars, similar);
  17073. const canApplyFormat = (editor, name) => getRtcInstanceWithError(editor).formatter.canApply(name);
  17074. const closestFormat = (editor, names) => getRtcInstanceWithError(editor).formatter.closest(names);
  17075. const applyFormat = (editor, name, vars, node) => {
  17076. getRtcInstanceWithError(editor).formatter.apply(name, vars, node);
  17077. };
  17078. const removeFormat = (editor, name, vars, node, similar) => {
  17079. getRtcInstanceWithError(editor).formatter.remove(name, vars, node, similar);
  17080. };
  17081. const toggleFormat = (editor, name, vars, node) => {
  17082. getRtcInstanceWithError(editor).formatter.toggle(name, vars, node);
  17083. };
  17084. const formatChanged = (editor, registeredFormatListeners, formats, callback, similar, vars) => getRtcInstanceWithError(editor).formatter.formatChanged(registeredFormatListeners, formats, callback, similar, vars);
  17085. const getContent$2 = (editor, args) => getRtcInstanceWithFallback(editor).editor.getContent(args);
  17086. const setContent$2 = (editor, content, args) => getRtcInstanceWithFallback(editor).editor.setContent(content, args);
  17087. const insertContent$1 = (editor, value, details) => getRtcInstanceWithFallback(editor).editor.insertContent(value, details);
  17088. const getSelectedContent = (editor, format, args) => getRtcInstanceWithError(editor).selection.getContent(format, args);
  17089. const addVisual$1 = (editor, elm) => getRtcInstanceWithError(editor).editor.addVisual(elm);
  17090. const bindEvents = editor => getRtcInstanceWithError(editor).init.bindEvents();
  17091. const addAutocompleterDecoration = (editor, range) => getRtcInstanceWithError(editor).autocompleter.addDecoration(range);
  17092. const removeAutocompleterDecoration = editor => getRtcInstanceWithError(editor).autocompleter.removeDecoration();
  17093. const getContent$1 = (editor, args = {}) => {
  17094. const format = args.format ? args.format : 'html';
  17095. return getSelectedContent(editor, format, args);
  17096. };
  17097. const removeEmpty = text => {
  17098. if (text.dom.length === 0) {
  17099. remove$6(text);
  17100. return Optional.none();
  17101. } else {
  17102. return Optional.some(text);
  17103. }
  17104. };
  17105. const walkPastBookmark = (node, start) => node.filter(elm => BookmarkManager.isBookmarkNode(elm.dom)).bind(start ? nextSibling : prevSibling);
  17106. const merge$1 = (outer, inner, rng, start) => {
  17107. const outerElm = outer.dom;
  17108. const innerElm = inner.dom;
  17109. const oldLength = start ? outerElm.length : innerElm.length;
  17110. if (start) {
  17111. mergeTextNodes(outerElm, innerElm, false, !start);
  17112. rng.setStart(innerElm, oldLength);
  17113. } else {
  17114. mergeTextNodes(innerElm, outerElm, false, !start);
  17115. rng.setEnd(innerElm, oldLength);
  17116. }
  17117. };
  17118. const normalizeTextIfRequired = (inner, start) => {
  17119. parent(inner).each(root => {
  17120. const text = inner.dom;
  17121. if (start && needsToBeNbspLeft(root, CaretPosition(text, 0))) {
  17122. normalizeWhitespaceAfter(text, 0);
  17123. } else if (!start && needsToBeNbspRight(root, CaretPosition(text, text.length))) {
  17124. normalizeWhitespaceBefore(text, text.length);
  17125. }
  17126. });
  17127. };
  17128. const mergeAndNormalizeText = (outerNode, innerNode, rng, start) => {
  17129. outerNode.bind(outer => {
  17130. const normalizer = start ? normalizeWhitespaceBefore : normalizeWhitespaceAfter;
  17131. normalizer(outer.dom, start ? outer.dom.length : 0);
  17132. return innerNode.filter(isText$a).map(inner => merge$1(outer, inner, rng, start));
  17133. }).orThunk(() => {
  17134. const innerTextNode = walkPastBookmark(innerNode, start).or(innerNode).filter(isText$a);
  17135. return innerTextNode.map(inner => normalizeTextIfRequired(inner, start));
  17136. });
  17137. };
  17138. const rngSetContent = (rng, fragment) => {
  17139. const firstChild = Optional.from(fragment.firstChild).map(SugarElement.fromDom);
  17140. const lastChild = Optional.from(fragment.lastChild).map(SugarElement.fromDom);
  17141. rng.deleteContents();
  17142. rng.insertNode(fragment);
  17143. const prevText = firstChild.bind(prevSibling).filter(isText$a).bind(removeEmpty);
  17144. const nextText = lastChild.bind(nextSibling).filter(isText$a).bind(removeEmpty);
  17145. mergeAndNormalizeText(prevText, firstChild, rng, true);
  17146. mergeAndNormalizeText(nextText, lastChild, rng, false);
  17147. rng.collapse(false);
  17148. };
  17149. const setupArgs$2 = (args, content) => ({
  17150. format: 'html',
  17151. ...args,
  17152. set: true,
  17153. selection: true,
  17154. content
  17155. });
  17156. const cleanContent = (editor, args) => {
  17157. if (args.format !== 'raw') {
  17158. const rng = editor.selection.getRng();
  17159. const contextBlock = editor.dom.getParent(rng.commonAncestorContainer, editor.dom.isBlock);
  17160. const contextArgs = contextBlock ? { context: contextBlock.nodeName.toLowerCase() } : {};
  17161. const node = editor.parser.parse(args.content, {
  17162. forced_root_block: false,
  17163. ...contextArgs,
  17164. ...args
  17165. });
  17166. return HtmlSerializer({ validate: false }, editor.schema).serialize(node);
  17167. } else {
  17168. return args.content;
  17169. }
  17170. };
  17171. const setContent$1 = (editor, content, args = {}) => {
  17172. const defaultedArgs = setupArgs$2(args, content);
  17173. preProcessSetContent(editor, defaultedArgs).each(updatedArgs => {
  17174. const cleanedContent = cleanContent(editor, updatedArgs);
  17175. const rng = editor.selection.getRng();
  17176. rngSetContent(rng, rng.createContextualFragment(cleanedContent));
  17177. editor.selection.setRng(rng);
  17178. scrollRangeIntoView(editor, rng);
  17179. postProcessSetContent(editor, cleanedContent, updatedArgs);
  17180. });
  17181. };
  17182. const deleteFromCallbackMap = (callbackMap, selector, callback) => {
  17183. if (callbackMap && has$2(callbackMap, selector)) {
  17184. const newCallbacks = filter$6(callbackMap[selector], cb => cb !== callback);
  17185. if (newCallbacks.length === 0) {
  17186. delete callbackMap[selector];
  17187. } else {
  17188. callbackMap[selector] = newCallbacks;
  17189. }
  17190. }
  17191. };
  17192. var SelectorChanged = (dom, editor) => {
  17193. let selectorChangedData;
  17194. let currentSelectors;
  17195. const findMatchingNode = (selector, nodes) => find$2(nodes, node => dom.is(node, selector));
  17196. const getParents = elem => dom.getParents(elem, null, dom.getRoot());
  17197. return {
  17198. selectorChangedWithUnbind: (selector, callback) => {
  17199. if (!selectorChangedData) {
  17200. selectorChangedData = {};
  17201. currentSelectors = {};
  17202. editor.on('NodeChange', e => {
  17203. const node = e.element;
  17204. const parents = getParents(node);
  17205. const matchedSelectors = {};
  17206. Tools.each(selectorChangedData, (callbacks, selector) => {
  17207. findMatchingNode(selector, parents).each(node => {
  17208. if (!currentSelectors[selector]) {
  17209. each$f(callbacks, callback => {
  17210. callback(true, {
  17211. node,
  17212. selector,
  17213. parents
  17214. });
  17215. });
  17216. currentSelectors[selector] = callbacks;
  17217. }
  17218. matchedSelectors[selector] = callbacks;
  17219. });
  17220. });
  17221. Tools.each(currentSelectors, (callbacks, selector) => {
  17222. if (!matchedSelectors[selector]) {
  17223. delete currentSelectors[selector];
  17224. Tools.each(callbacks, callback => {
  17225. callback(false, {
  17226. node,
  17227. selector,
  17228. parents
  17229. });
  17230. });
  17231. }
  17232. });
  17233. });
  17234. }
  17235. if (!selectorChangedData[selector]) {
  17236. selectorChangedData[selector] = [];
  17237. }
  17238. selectorChangedData[selector].push(callback);
  17239. findMatchingNode(selector, getParents(editor.selection.getStart())).each(() => {
  17240. currentSelectors[selector] = selectorChangedData[selector];
  17241. });
  17242. return {
  17243. unbind: () => {
  17244. deleteFromCallbackMap(selectorChangedData, selector, callback);
  17245. deleteFromCallbackMap(currentSelectors, selector, callback);
  17246. }
  17247. };
  17248. }
  17249. };
  17250. };
  17251. const isAttachedToDom = node => {
  17252. return !!(node && node.ownerDocument) && contains(SugarElement.fromDom(node.ownerDocument), SugarElement.fromDom(node));
  17253. };
  17254. const isValidRange = rng => {
  17255. if (!rng) {
  17256. return false;
  17257. } else {
  17258. return isAttachedToDom(rng.startContainer) && isAttachedToDom(rng.endContainer);
  17259. }
  17260. };
  17261. const EditorSelection = (dom, win, serializer, editor) => {
  17262. let selectedRange;
  17263. let explicitRange;
  17264. const {selectorChangedWithUnbind} = SelectorChanged(dom, editor);
  17265. const setCursorLocation = (node, offset) => {
  17266. const rng = dom.createRng();
  17267. if (isNonNullable(node) && isNonNullable(offset)) {
  17268. rng.setStart(node, offset);
  17269. rng.setEnd(node, offset);
  17270. setRng(rng);
  17271. collapse(false);
  17272. } else {
  17273. moveEndPoint(dom, rng, editor.getBody(), true);
  17274. setRng(rng);
  17275. }
  17276. };
  17277. const getContent = args => getContent$1(editor, args);
  17278. const setContent = (content, args) => setContent$1(editor, content, args);
  17279. const getStart$1 = real => getStart(editor.getBody(), getRng$1(), real);
  17280. const getEnd = real => getEnd$1(editor.getBody(), getRng$1(), real);
  17281. const getBookmark = (type, normalized) => bookmarkManager.getBookmark(type, normalized);
  17282. const moveToBookmark = bookmark => bookmarkManager.moveToBookmark(bookmark);
  17283. const select$1 = (node, content) => {
  17284. select(dom, node, content).each(setRng);
  17285. return node;
  17286. };
  17287. const isCollapsed = () => {
  17288. const rng = getRng$1(), sel = getSel();
  17289. if (!rng || rng.item) {
  17290. return false;
  17291. }
  17292. if (rng.compareEndPoints) {
  17293. return rng.compareEndPoints('StartToEnd', rng) === 0;
  17294. }
  17295. return !sel || rng.collapsed;
  17296. };
  17297. const collapse = toStart => {
  17298. const rng = getRng$1();
  17299. rng.collapse(!!toStart);
  17300. setRng(rng);
  17301. };
  17302. const getSel = () => win.getSelection ? win.getSelection() : win.document.selection;
  17303. const getRng$1 = () => {
  17304. let selection, rng, elm;
  17305. const tryCompareBoundaryPoints = (how, sourceRange, destinationRange) => {
  17306. try {
  17307. return sourceRange.compareBoundaryPoints(how, destinationRange);
  17308. } catch (ex) {
  17309. return -1;
  17310. }
  17311. };
  17312. const doc = win.document;
  17313. if (editor.bookmark !== undefined && hasFocus(editor) === false) {
  17314. const bookmark = getRng(editor);
  17315. if (bookmark.isSome()) {
  17316. return bookmark.map(r => processRanges(editor, [r])[0]).getOr(doc.createRange());
  17317. }
  17318. }
  17319. try {
  17320. if ((selection = getSel()) && !isRestrictedNode(selection.anchorNode)) {
  17321. if (selection.rangeCount > 0) {
  17322. rng = selection.getRangeAt(0);
  17323. } else {
  17324. rng = selection.createRange ? selection.createRange() : doc.createRange();
  17325. }
  17326. rng = processRanges(editor, [rng])[0];
  17327. }
  17328. } catch (ex) {
  17329. }
  17330. if (!rng) {
  17331. rng = doc.createRange();
  17332. }
  17333. if (rng.setStart && rng.startContainer.nodeType === 9 && rng.collapsed) {
  17334. elm = dom.getRoot();
  17335. rng.setStart(elm, 0);
  17336. rng.setEnd(elm, 0);
  17337. }
  17338. if (selectedRange && explicitRange) {
  17339. if (tryCompareBoundaryPoints(rng.START_TO_START, rng, selectedRange) === 0 && tryCompareBoundaryPoints(rng.END_TO_END, rng, selectedRange) === 0) {
  17340. rng = explicitRange;
  17341. } else {
  17342. selectedRange = null;
  17343. explicitRange = null;
  17344. }
  17345. }
  17346. return rng;
  17347. };
  17348. const setRng = (rng, forward) => {
  17349. let node;
  17350. if (!isValidRange(rng)) {
  17351. return;
  17352. }
  17353. const sel = getSel();
  17354. const evt = editor.dispatch('SetSelectionRange', {
  17355. range: rng,
  17356. forward
  17357. });
  17358. rng = evt.range;
  17359. if (sel) {
  17360. explicitRange = rng;
  17361. try {
  17362. sel.removeAllRanges();
  17363. sel.addRange(rng);
  17364. } catch (ex) {
  17365. }
  17366. if (forward === false && sel.extend) {
  17367. sel.collapse(rng.endContainer, rng.endOffset);
  17368. sel.extend(rng.startContainer, rng.startOffset);
  17369. }
  17370. selectedRange = sel.rangeCount > 0 ? sel.getRangeAt(0) : null;
  17371. }
  17372. if (!rng.collapsed && rng.startContainer === rng.endContainer && sel.setBaseAndExtent) {
  17373. if (rng.endOffset - rng.startOffset < 2) {
  17374. if (rng.startContainer.hasChildNodes()) {
  17375. node = rng.startContainer.childNodes[rng.startOffset];
  17376. if (node && node.tagName === 'IMG') {
  17377. sel.setBaseAndExtent(rng.startContainer, rng.startOffset, rng.endContainer, rng.endOffset);
  17378. if (sel.anchorNode !== rng.startContainer || sel.focusNode !== rng.endContainer) {
  17379. sel.setBaseAndExtent(node, 0, node, 1);
  17380. }
  17381. }
  17382. }
  17383. }
  17384. }
  17385. editor.dispatch('AfterSetSelectionRange', {
  17386. range: rng,
  17387. forward
  17388. });
  17389. };
  17390. const setNode = elm => {
  17391. setContent(dom.getOuterHTML(elm));
  17392. return elm;
  17393. };
  17394. const getNode$1 = () => getNode(editor.getBody(), getRng$1());
  17395. const getSelectedBlocks$1 = (startElm, endElm) => getSelectedBlocks(dom, getRng$1(), startElm, endElm);
  17396. const isForward = () => {
  17397. const sel = getSel();
  17398. const anchorNode = sel === null || sel === void 0 ? void 0 : sel.anchorNode;
  17399. const focusNode = sel === null || sel === void 0 ? void 0 : sel.focusNode;
  17400. if (!sel || !anchorNode || !focusNode || isRestrictedNode(anchorNode) || isRestrictedNode(focusNode)) {
  17401. return true;
  17402. }
  17403. const anchorRange = dom.createRng();
  17404. const focusRange = dom.createRng();
  17405. try {
  17406. anchorRange.setStart(anchorNode, sel.anchorOffset);
  17407. anchorRange.collapse(true);
  17408. focusRange.setStart(focusNode, sel.focusOffset);
  17409. focusRange.collapse(true);
  17410. } catch (e) {
  17411. return true;
  17412. }
  17413. return anchorRange.compareBoundaryPoints(anchorRange.START_TO_START, focusRange) <= 0;
  17414. };
  17415. const normalize = () => {
  17416. const rng = getRng$1();
  17417. const sel = getSel();
  17418. if (!hasMultipleRanges(sel) && hasAnyRanges(editor)) {
  17419. const normRng = normalize$2(dom, rng);
  17420. normRng.each(normRng => {
  17421. setRng(normRng, isForward());
  17422. });
  17423. return normRng.getOr(rng);
  17424. }
  17425. return rng;
  17426. };
  17427. const selectorChanged = (selector, callback) => {
  17428. selectorChangedWithUnbind(selector, callback);
  17429. return exports;
  17430. };
  17431. const getScrollContainer = () => {
  17432. let scrollContainer;
  17433. let node = dom.getRoot();
  17434. while (node && node.nodeName !== 'BODY') {
  17435. if (node.scrollHeight > node.clientHeight) {
  17436. scrollContainer = node;
  17437. break;
  17438. }
  17439. node = node.parentNode;
  17440. }
  17441. return scrollContainer;
  17442. };
  17443. const scrollIntoView = (elm, alignToTop) => {
  17444. if (isNonNullable(elm)) {
  17445. scrollElementIntoView(editor, elm, alignToTop);
  17446. } else {
  17447. scrollRangeIntoView(editor, getRng$1(), alignToTop);
  17448. }
  17449. };
  17450. const placeCaretAt = (clientX, clientY) => setRng(fromPoint(clientX, clientY, editor.getDoc()));
  17451. const getBoundingClientRect = () => {
  17452. const rng = getRng$1();
  17453. return rng.collapsed ? CaretPosition.fromRangeStart(rng).getClientRects()[0] : rng.getBoundingClientRect();
  17454. };
  17455. const destroy = () => {
  17456. win = selectedRange = explicitRange = null;
  17457. controlSelection.destroy();
  17458. };
  17459. const exports = {
  17460. bookmarkManager: null,
  17461. controlSelection: null,
  17462. dom,
  17463. win,
  17464. serializer,
  17465. editor,
  17466. collapse,
  17467. setCursorLocation,
  17468. getContent,
  17469. setContent,
  17470. getBookmark,
  17471. moveToBookmark,
  17472. select: select$1,
  17473. isCollapsed,
  17474. isForward,
  17475. setNode,
  17476. getNode: getNode$1,
  17477. getSel,
  17478. setRng,
  17479. getRng: getRng$1,
  17480. getStart: getStart$1,
  17481. getEnd,
  17482. getSelectedBlocks: getSelectedBlocks$1,
  17483. normalize,
  17484. selectorChanged,
  17485. selectorChangedWithUnbind,
  17486. getScrollContainer,
  17487. scrollIntoView,
  17488. placeCaretAt,
  17489. getBoundingClientRect,
  17490. destroy
  17491. };
  17492. const bookmarkManager = BookmarkManager(exports);
  17493. const controlSelection = ControlSelection(exports, editor);
  17494. exports.bookmarkManager = bookmarkManager;
  17495. exports.controlSelection = controlSelection;
  17496. return exports;
  17497. };
  17498. const register$3 = (htmlParser, settings, dom) => {
  17499. htmlParser.addAttributeFilter('data-mce-tabindex', (nodes, name) => {
  17500. let i = nodes.length;
  17501. while (i--) {
  17502. const node = nodes[i];
  17503. node.attr('tabindex', node.attr('data-mce-tabindex'));
  17504. node.attr(name, null);
  17505. }
  17506. });
  17507. htmlParser.addAttributeFilter('src,href,style', (nodes, name) => {
  17508. const internalName = 'data-mce-' + name;
  17509. const urlConverter = settings.url_converter;
  17510. const urlConverterScope = settings.url_converter_scope;
  17511. let i = nodes.length;
  17512. while (i--) {
  17513. const node = nodes[i];
  17514. let value = node.attr(internalName);
  17515. if (value !== undefined) {
  17516. node.attr(name, value.length > 0 ? value : null);
  17517. node.attr(internalName, null);
  17518. } else {
  17519. value = node.attr(name);
  17520. if (name === 'style') {
  17521. value = dom.serializeStyle(dom.parseStyle(value), node.name);
  17522. } else if (urlConverter) {
  17523. value = urlConverter.call(urlConverterScope, value, name, node.name);
  17524. }
  17525. node.attr(name, value.length > 0 ? value : null);
  17526. }
  17527. }
  17528. });
  17529. htmlParser.addAttributeFilter('class', nodes => {
  17530. let i = nodes.length;
  17531. while (i--) {
  17532. const node = nodes[i];
  17533. let value = node.attr('class');
  17534. if (value) {
  17535. value = node.attr('class').replace(/(?:^|\s)mce-item-\w+(?!\S)/g, '');
  17536. node.attr('class', value.length > 0 ? value : null);
  17537. }
  17538. }
  17539. });
  17540. htmlParser.addAttributeFilter('data-mce-type', (nodes, name, args) => {
  17541. let i = nodes.length;
  17542. while (i--) {
  17543. const node = nodes[i];
  17544. if (node.attr('data-mce-type') === 'bookmark' && !args.cleanup) {
  17545. const hasChildren = Optional.from(node.firstChild).exists(firstChild => !isZwsp(firstChild.value));
  17546. if (hasChildren) {
  17547. node.unwrap();
  17548. } else {
  17549. node.remove();
  17550. }
  17551. }
  17552. }
  17553. });
  17554. htmlParser.addNodeFilter('noscript', nodes => {
  17555. let i = nodes.length;
  17556. while (i--) {
  17557. const node = nodes[i].firstChild;
  17558. if (node) {
  17559. node.value = Entities.decode(node.value);
  17560. }
  17561. }
  17562. });
  17563. htmlParser.addNodeFilter('script,style', (nodes, name) => {
  17564. const trim = value => {
  17565. 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, '');
  17566. };
  17567. let i = nodes.length;
  17568. while (i--) {
  17569. const node = nodes[i];
  17570. const value = node.firstChild ? node.firstChild.value : '';
  17571. if (name === 'script') {
  17572. const type = node.attr('type');
  17573. if (type) {
  17574. node.attr('type', type === 'mce-no/type' ? null : type.replace(/^mce\-/, ''));
  17575. }
  17576. if (settings.element_format === 'xhtml' && value.length > 0) {
  17577. node.firstChild.value = '// <![CDATA[\n' + trim(value) + '\n// ]]>';
  17578. }
  17579. } else {
  17580. if (settings.element_format === 'xhtml' && value.length > 0) {
  17581. node.firstChild.value = '<!--\n' + trim(value) + '\n-->';
  17582. }
  17583. }
  17584. }
  17585. });
  17586. htmlParser.addNodeFilter('#comment', nodes => {
  17587. let i = nodes.length;
  17588. while (i--) {
  17589. const node = nodes[i];
  17590. if (settings.preserve_cdata && node.value.indexOf('[CDATA[') === 0) {
  17591. node.name = '#cdata';
  17592. node.type = 4;
  17593. node.value = dom.decode(node.value.replace(/^\[CDATA\[|\]\]$/g, ''));
  17594. } else if (node.value.indexOf('mce:protected ') === 0) {
  17595. node.name = '#text';
  17596. node.type = 3;
  17597. node.raw = true;
  17598. node.value = unescape(node.value).substr(14);
  17599. }
  17600. }
  17601. });
  17602. htmlParser.addNodeFilter('xml:namespace,input', (nodes, name) => {
  17603. let i = nodes.length;
  17604. while (i--) {
  17605. const node = nodes[i];
  17606. if (node.type === 7) {
  17607. node.remove();
  17608. } else if (node.type === 1) {
  17609. if (name === 'input' && !node.attr('type')) {
  17610. node.attr('type', 'text');
  17611. }
  17612. }
  17613. }
  17614. });
  17615. htmlParser.addAttributeFilter('data-mce-type', nodes => {
  17616. each$f(nodes, node => {
  17617. if (node.attr('data-mce-type') === 'format-caret') {
  17618. if (node.isEmpty(htmlParser.schema.getNonEmptyElements())) {
  17619. node.remove();
  17620. } else {
  17621. node.unwrap();
  17622. }
  17623. }
  17624. });
  17625. });
  17626. 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) => {
  17627. let i = nodes.length;
  17628. while (i--) {
  17629. nodes[i].attr(name, null);
  17630. }
  17631. });
  17632. };
  17633. const trimTrailingBr = rootNode => {
  17634. const isBr = node => {
  17635. return node && node.name === 'br';
  17636. };
  17637. const brNode1 = rootNode.lastChild;
  17638. if (isBr(brNode1)) {
  17639. const brNode2 = brNode1.prev;
  17640. if (isBr(brNode2)) {
  17641. brNode1.remove();
  17642. brNode2.remove();
  17643. }
  17644. }
  17645. };
  17646. const preProcess$1 = (editor, node, args) => {
  17647. let oldDoc;
  17648. const dom = editor.dom;
  17649. let clonedNode = node.cloneNode(true);
  17650. const impl = document.implementation;
  17651. if (impl.createHTMLDocument) {
  17652. const doc = impl.createHTMLDocument('');
  17653. Tools.each(clonedNode.nodeName === 'BODY' ? clonedNode.childNodes : [clonedNode], node => {
  17654. doc.body.appendChild(doc.importNode(node, true));
  17655. });
  17656. if (clonedNode.nodeName !== 'BODY') {
  17657. clonedNode = doc.body.firstChild;
  17658. } else {
  17659. clonedNode = doc.body;
  17660. }
  17661. oldDoc = dom.doc;
  17662. dom.doc = doc;
  17663. }
  17664. firePreProcess(editor, {
  17665. ...args,
  17666. node: clonedNode
  17667. });
  17668. if (oldDoc) {
  17669. dom.doc = oldDoc;
  17670. }
  17671. return clonedNode;
  17672. };
  17673. const shouldFireEvent = (editor, args) => {
  17674. return editor && editor.hasEventListeners('PreProcess') && !args.no_events;
  17675. };
  17676. const process$1 = (editor, node, args) => {
  17677. return shouldFireEvent(editor, args) ? preProcess$1(editor, node, args) : node;
  17678. };
  17679. const addTempAttr = (htmlParser, tempAttrs, name) => {
  17680. if (Tools.inArray(tempAttrs, name) === -1) {
  17681. htmlParser.addAttributeFilter(name, (nodes, name) => {
  17682. let i = nodes.length;
  17683. while (i--) {
  17684. nodes[i].attr(name, null);
  17685. }
  17686. });
  17687. tempAttrs.push(name);
  17688. }
  17689. };
  17690. const postProcess = (editor, args, content) => {
  17691. if (!args.no_events && editor) {
  17692. const outArgs = firePostProcess(editor, {
  17693. ...args,
  17694. content
  17695. });
  17696. return outArgs.content;
  17697. } else {
  17698. return content;
  17699. }
  17700. };
  17701. const getHtmlFromNode = (dom, node, args) => {
  17702. const html = trim$1(args.getInner ? node.innerHTML : dom.getOuterHTML(node));
  17703. return args.selection || isWsPreserveElement(SugarElement.fromDom(node)) ? html : Tools.trim(html);
  17704. };
  17705. const parseHtml = (htmlParser, html, args) => {
  17706. const parserArgs = args.selection ? {
  17707. forced_root_block: false,
  17708. ...args
  17709. } : args;
  17710. const rootNode = htmlParser.parse(html, parserArgs);
  17711. trimTrailingBr(rootNode);
  17712. return rootNode;
  17713. };
  17714. const serializeNode = (settings, schema, node) => {
  17715. const htmlSerializer = HtmlSerializer(settings, schema);
  17716. return htmlSerializer.serialize(node);
  17717. };
  17718. const toHtml = (editor, settings, schema, rootNode, args) => {
  17719. const content = serializeNode(settings, schema, rootNode);
  17720. return postProcess(editor, args, content);
  17721. };
  17722. const DomSerializerImpl = (settings, editor) => {
  17723. const tempAttrs = ['data-mce-selected'];
  17724. const dom = editor && editor.dom ? editor.dom : DOMUtils.DOM;
  17725. const schema = editor && editor.schema ? editor.schema : Schema(settings);
  17726. settings.entity_encoding = settings.entity_encoding || 'named';
  17727. settings.remove_trailing_brs = 'remove_trailing_brs' in settings ? settings.remove_trailing_brs : true;
  17728. const htmlParser = DomParser(settings, schema);
  17729. register$3(htmlParser, settings, dom);
  17730. const serialize = (node, parserArgs = {}) => {
  17731. const args = {
  17732. format: 'html',
  17733. ...parserArgs
  17734. };
  17735. const targetNode = process$1(editor, node, args);
  17736. const html = getHtmlFromNode(dom, targetNode, args);
  17737. const rootNode = parseHtml(htmlParser, html, args);
  17738. return args.format === 'tree' ? rootNode : toHtml(editor, settings, schema, rootNode, args);
  17739. };
  17740. return {
  17741. schema,
  17742. addNodeFilter: htmlParser.addNodeFilter,
  17743. addAttributeFilter: htmlParser.addAttributeFilter,
  17744. serialize: serialize,
  17745. addRules: schema.addValidElements,
  17746. setRules: schema.setValidElements,
  17747. addTempAttr: curry(addTempAttr, htmlParser, tempAttrs),
  17748. getTempAttrs: constant(tempAttrs),
  17749. getNodeFilters: htmlParser.getNodeFilters,
  17750. getAttributeFilters: htmlParser.getAttributeFilters,
  17751. removeNodeFilter: htmlParser.removeNodeFilter,
  17752. removeAttributeFilter: htmlParser.removeAttributeFilter
  17753. };
  17754. };
  17755. const DomSerializer = (settings, editor) => {
  17756. const domSerializer = DomSerializerImpl(settings, editor);
  17757. return {
  17758. schema: domSerializer.schema,
  17759. addNodeFilter: domSerializer.addNodeFilter,
  17760. addAttributeFilter: domSerializer.addAttributeFilter,
  17761. serialize: domSerializer.serialize,
  17762. addRules: domSerializer.addRules,
  17763. setRules: domSerializer.setRules,
  17764. addTempAttr: domSerializer.addTempAttr,
  17765. getTempAttrs: domSerializer.getTempAttrs,
  17766. getNodeFilters: domSerializer.getNodeFilters,
  17767. getAttributeFilters: domSerializer.getAttributeFilters,
  17768. removeNodeFilter: domSerializer.removeNodeFilter,
  17769. removeAttributeFilter: domSerializer.removeAttributeFilter
  17770. };
  17771. };
  17772. const defaultFormat$1 = 'html';
  17773. const setupArgs$1 = (args, format) => ({
  17774. ...args,
  17775. format,
  17776. get: true,
  17777. getInner: true
  17778. });
  17779. const getContent = (editor, args = {}) => {
  17780. const format = args.format ? args.format : defaultFormat$1;
  17781. const defaultedArgs = setupArgs$1(args, format);
  17782. return preProcessGetContent(editor, defaultedArgs).fold(identity, updatedArgs => {
  17783. const content = getContent$2(editor, updatedArgs);
  17784. return postProcessGetContent(editor, content, updatedArgs);
  17785. });
  17786. };
  17787. const defaultFormat = 'html';
  17788. const setupArgs = (args, content) => ({
  17789. format: defaultFormat,
  17790. ...args,
  17791. set: true,
  17792. content
  17793. });
  17794. const setContent = (editor, content, args = {}) => {
  17795. const defaultedArgs = setupArgs(args, content);
  17796. return preProcessSetContent(editor, defaultedArgs).map(updatedArgs => {
  17797. const result = setContent$2(editor, updatedArgs.content, updatedArgs);
  17798. postProcessSetContent(editor, result.html, updatedArgs);
  17799. return result.content;
  17800. }).getOr(content);
  17801. };
  17802. 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(',');
  17803. const removedPlugins = 'bbcode,colorpicker,contextmenu,fullpage,legacyoutput,spellchecker,textcolor'.split(',');
  17804. const getRemovedOptions = options => {
  17805. const settingNames = filter$6(removedOptions, setting => has$2(options, setting));
  17806. const forcedRootBlock = options.forced_root_block;
  17807. if (forcedRootBlock === false || forcedRootBlock === '') {
  17808. settingNames.push('forced_root_block (false only)');
  17809. }
  17810. return sort(settingNames);
  17811. };
  17812. const getRemovedPlugins = options => {
  17813. const plugins = Tools.makeMap(options.plugins, ' ');
  17814. const hasPlugin = plugin => has$2(plugins, plugin);
  17815. const pluginNames = filter$6(removedPlugins, hasPlugin);
  17816. return sort(pluginNames);
  17817. };
  17818. const logRemovedWarnings = (rawOptions, normalizedOptions) => {
  17819. const removedOptions = getRemovedOptions(rawOptions);
  17820. const removedPlugins = getRemovedPlugins(normalizedOptions);
  17821. const hasRemovedPlugins = removedPlugins.length > 0;
  17822. const hasRemovedOptions = removedOptions.length > 0;
  17823. const isLegacyMobileTheme = normalizedOptions.theme === 'mobile';
  17824. if (hasRemovedPlugins || hasRemovedOptions || isLegacyMobileTheme) {
  17825. const listJoiner = '\n- ';
  17826. const themesMessage = isLegacyMobileTheme ? `\n\nThemes:${ listJoiner }mobile` : '';
  17827. const pluginsMessage = hasRemovedPlugins ? `\n\nPlugins:${ listJoiner }${ removedPlugins.join(listJoiner) }` : '';
  17828. const optionsMessage = hasRemovedOptions ? `\n\nOptions:${ listJoiner }${ removedOptions.join(listJoiner) }` : '';
  17829. 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);
  17830. }
  17831. };
  17832. const logWarnings = (rawOptions, normalizedOptions) => {
  17833. logRemovedWarnings(rawOptions, normalizedOptions);
  17834. };
  17835. const DOM$8 = DOMUtils.DOM;
  17836. const restoreOriginalStyles = editor => {
  17837. DOM$8.setStyle(editor.id, 'display', editor.orgDisplay);
  17838. };
  17839. const safeDestroy = x => Optional.from(x).each(x => x.destroy());
  17840. const clearDomReferences = editor => {
  17841. editor.contentAreaContainer = editor.formElement = editor.container = editor.editorContainer = null;
  17842. editor.bodyElement = editor.contentDocument = editor.contentWindow = null;
  17843. editor.iframeElement = editor.targetElm = null;
  17844. if (editor.selection) {
  17845. editor.selection = editor.selection.win = editor.selection.dom = editor.selection.dom.doc = null;
  17846. }
  17847. };
  17848. const restoreForm = editor => {
  17849. const form = editor.formElement;
  17850. if (form) {
  17851. if (form._mceOldSubmit) {
  17852. form.submit = form._mceOldSubmit;
  17853. form._mceOldSubmit = null;
  17854. }
  17855. DOM$8.unbind(form, 'submit reset', editor.formEventDelegate);
  17856. }
  17857. };
  17858. const remove$1 = editor => {
  17859. if (!editor.removed) {
  17860. const {_selectionOverrides, editorUpload} = editor;
  17861. const body = editor.getBody();
  17862. const element = editor.getElement();
  17863. if (body) {
  17864. editor.save({ is_removing: true });
  17865. }
  17866. editor.removed = true;
  17867. editor.unbindAllNativeEvents();
  17868. if (editor.hasHiddenInput && element) {
  17869. DOM$8.remove(element.nextSibling);
  17870. }
  17871. fireRemove(editor);
  17872. editor.editorManager.remove(editor);
  17873. if (!editor.inline && body) {
  17874. restoreOriginalStyles(editor);
  17875. }
  17876. fireDetach(editor);
  17877. DOM$8.remove(editor.getContainer());
  17878. safeDestroy(_selectionOverrides);
  17879. safeDestroy(editorUpload);
  17880. editor.destroy();
  17881. }
  17882. };
  17883. const destroy = (editor, automatic) => {
  17884. const {selection, dom} = editor;
  17885. if (editor.destroyed) {
  17886. return;
  17887. }
  17888. if (!automatic && !editor.removed) {
  17889. editor.remove();
  17890. return;
  17891. }
  17892. if (!automatic) {
  17893. editor.editorManager.off('beforeunload', editor._beforeUnload);
  17894. if (editor.theme && editor.theme.destroy) {
  17895. editor.theme.destroy();
  17896. }
  17897. safeDestroy(selection);
  17898. safeDestroy(dom);
  17899. }
  17900. restoreForm(editor);
  17901. clearDomReferences(editor);
  17902. editor.destroyed = true;
  17903. };
  17904. const CreateIconManager = () => {
  17905. const lookup = {};
  17906. const add = (id, iconPack) => {
  17907. lookup[id] = iconPack;
  17908. };
  17909. const get = id => {
  17910. if (lookup[id]) {
  17911. return lookup[id];
  17912. }
  17913. return { icons: {} };
  17914. };
  17915. const has = id => has$2(lookup, id);
  17916. return {
  17917. add,
  17918. get,
  17919. has
  17920. };
  17921. };
  17922. const IconManager = CreateIconManager();
  17923. const ModelManager = AddOnManager.ModelManager;
  17924. const getProp = (propName, elm) => {
  17925. const rawElm = elm.dom;
  17926. return rawElm[propName];
  17927. };
  17928. const getComputedSizeProp = (propName, elm) => parseInt(get$7(elm, propName), 10);
  17929. const getClientWidth = curry(getProp, 'clientWidth');
  17930. const getClientHeight = curry(getProp, 'clientHeight');
  17931. const getMarginTop = curry(getComputedSizeProp, 'margin-top');
  17932. const getMarginLeft = curry(getComputedSizeProp, 'margin-left');
  17933. const getBoundingClientRect = elm => elm.dom.getBoundingClientRect();
  17934. const isInsideElementContentArea = (bodyElm, clientX, clientY) => {
  17935. const clientWidth = getClientWidth(bodyElm);
  17936. const clientHeight = getClientHeight(bodyElm);
  17937. return clientX >= 0 && clientY >= 0 && clientX <= clientWidth && clientY <= clientHeight;
  17938. };
  17939. const transpose = (inline, elm, clientX, clientY) => {
  17940. const clientRect = getBoundingClientRect(elm);
  17941. const deltaX = inline ? clientRect.left + elm.dom.clientLeft + getMarginLeft(elm) : 0;
  17942. const deltaY = inline ? clientRect.top + elm.dom.clientTop + getMarginTop(elm) : 0;
  17943. const x = clientX - deltaX;
  17944. const y = clientY - deltaY;
  17945. return {
  17946. x,
  17947. y
  17948. };
  17949. };
  17950. const isXYInContentArea = (editor, clientX, clientY) => {
  17951. const bodyElm = SugarElement.fromDom(editor.getBody());
  17952. const targetElm = editor.inline ? bodyElm : documentElement(bodyElm);
  17953. const transposedPoint = transpose(editor.inline, targetElm, clientX, clientY);
  17954. return isInsideElementContentArea(targetElm, transposedPoint.x, transposedPoint.y);
  17955. };
  17956. const fromDomSafe = node => Optional.from(node).map(SugarElement.fromDom);
  17957. const isEditorAttachedToDom = editor => {
  17958. const rawContainer = editor.inline ? editor.getBody() : editor.getContentAreaContainer();
  17959. return fromDomSafe(rawContainer).map(inBody).getOr(false);
  17960. };
  17961. const NotificationManagerImpl = () => {
  17962. const unimplemented = () => {
  17963. throw new Error('Theme did not provide a NotificationManager implementation.');
  17964. };
  17965. return {
  17966. open: unimplemented,
  17967. close: unimplemented,
  17968. getArgs: unimplemented
  17969. };
  17970. };
  17971. const NotificationManager = editor => {
  17972. const notifications = [];
  17973. const getImplementation = () => {
  17974. const theme = editor.theme;
  17975. return theme && theme.getNotificationManagerImpl ? theme.getNotificationManagerImpl() : NotificationManagerImpl();
  17976. };
  17977. const getTopNotification = () => {
  17978. return Optional.from(notifications[0]);
  17979. };
  17980. const isEqual = (a, b) => {
  17981. return a.type === b.type && a.text === b.text && !a.progressBar && !a.timeout && !b.progressBar && !b.timeout;
  17982. };
  17983. const reposition = () => {
  17984. each$f(notifications, notification => {
  17985. notification.reposition();
  17986. });
  17987. };
  17988. const addNotification = notification => {
  17989. notifications.push(notification);
  17990. };
  17991. const closeNotification = notification => {
  17992. findIndex$2(notifications, otherNotification => {
  17993. return otherNotification === notification;
  17994. }).each(index => {
  17995. notifications.splice(index, 1);
  17996. });
  17997. };
  17998. const open = (spec, fireEvent = true) => {
  17999. if (editor.removed || !isEditorAttachedToDom(editor)) {
  18000. return;
  18001. }
  18002. if (fireEvent) {
  18003. editor.dispatch('BeforeOpenNotification', { notification: spec });
  18004. }
  18005. return find$2(notifications, notification => {
  18006. return isEqual(getImplementation().getArgs(notification), spec);
  18007. }).getOrThunk(() => {
  18008. editor.editorManager.setActive(editor);
  18009. const notification = getImplementation().open(spec, () => {
  18010. closeNotification(notification);
  18011. reposition();
  18012. getTopNotification().fold(() => editor.focus(), top => focus$1(SugarElement.fromDom(top.getEl())));
  18013. });
  18014. addNotification(notification);
  18015. reposition();
  18016. editor.dispatch('OpenNotification', { notification: { ...notification } });
  18017. return notification;
  18018. });
  18019. };
  18020. const close = () => {
  18021. getTopNotification().each(notification => {
  18022. getImplementation().close(notification);
  18023. closeNotification(notification);
  18024. reposition();
  18025. });
  18026. };
  18027. const getNotifications = constant(notifications);
  18028. const registerEvents = editor => {
  18029. editor.on('SkinLoaded', () => {
  18030. const serviceMessage = getServiceMessage(editor);
  18031. if (serviceMessage) {
  18032. open({
  18033. text: serviceMessage,
  18034. type: 'warning',
  18035. timeout: 0
  18036. }, false);
  18037. }
  18038. reposition();
  18039. });
  18040. editor.on('show ResizeEditor ResizeWindow NodeChange', () => {
  18041. requestAnimationFrame(reposition);
  18042. });
  18043. editor.on('remove', () => {
  18044. each$f(notifications.slice(), notification => {
  18045. getImplementation().close(notification);
  18046. });
  18047. });
  18048. };
  18049. registerEvents(editor);
  18050. return {
  18051. open,
  18052. close,
  18053. getNotifications
  18054. };
  18055. };
  18056. const PluginManager = AddOnManager.PluginManager;
  18057. const ThemeManager = AddOnManager.ThemeManager;
  18058. var WindowManagerImpl = () => {
  18059. const unimplemented = () => {
  18060. throw new Error('Theme did not provide a WindowManager implementation.');
  18061. };
  18062. return {
  18063. open: unimplemented,
  18064. openUrl: unimplemented,
  18065. alert: unimplemented,
  18066. confirm: unimplemented,
  18067. close: unimplemented,
  18068. getParams: unimplemented,
  18069. setParams: unimplemented
  18070. };
  18071. };
  18072. const WindowManager = editor => {
  18073. let dialogs = [];
  18074. const getImplementation = () => {
  18075. const theme = editor.theme;
  18076. return theme && theme.getWindowManagerImpl ? theme.getWindowManagerImpl() : WindowManagerImpl();
  18077. };
  18078. const funcBind = (scope, f) => {
  18079. return (...args) => {
  18080. return f ? f.apply(scope, args) : undefined;
  18081. };
  18082. };
  18083. const fireOpenEvent = dialog => {
  18084. editor.dispatch('OpenWindow', { dialog });
  18085. };
  18086. const fireCloseEvent = dialog => {
  18087. editor.dispatch('CloseWindow', { dialog });
  18088. };
  18089. const addDialog = dialog => {
  18090. dialogs.push(dialog);
  18091. fireOpenEvent(dialog);
  18092. };
  18093. const closeDialog = dialog => {
  18094. fireCloseEvent(dialog);
  18095. dialogs = filter$6(dialogs, otherDialog => {
  18096. return otherDialog !== dialog;
  18097. });
  18098. if (dialogs.length === 0) {
  18099. editor.focus();
  18100. }
  18101. };
  18102. const getTopDialog = () => {
  18103. return Optional.from(dialogs[dialogs.length - 1]);
  18104. };
  18105. const storeSelectionAndOpenDialog = openDialog => {
  18106. editor.editorManager.setActive(editor);
  18107. store(editor);
  18108. editor.ui.show();
  18109. const dialog = openDialog();
  18110. addDialog(dialog);
  18111. return dialog;
  18112. };
  18113. const open = (args, params) => {
  18114. return storeSelectionAndOpenDialog(() => getImplementation().open(args, params, closeDialog));
  18115. };
  18116. const openUrl = args => {
  18117. return storeSelectionAndOpenDialog(() => getImplementation().openUrl(args, closeDialog));
  18118. };
  18119. const alert = (message, callback, scope) => {
  18120. const windowManagerImpl = getImplementation();
  18121. windowManagerImpl.alert(message, funcBind(scope ? scope : windowManagerImpl, callback));
  18122. };
  18123. const confirm = (message, callback, scope) => {
  18124. const windowManagerImpl = getImplementation();
  18125. windowManagerImpl.confirm(message, funcBind(scope ? scope : windowManagerImpl, callback));
  18126. };
  18127. const close = () => {
  18128. getTopDialog().each(dialog => {
  18129. getImplementation().close(dialog);
  18130. closeDialog(dialog);
  18131. });
  18132. };
  18133. editor.on('remove', () => {
  18134. each$f(dialogs, dialog => {
  18135. getImplementation().close(dialog);
  18136. });
  18137. });
  18138. return {
  18139. open,
  18140. openUrl,
  18141. alert,
  18142. confirm,
  18143. close
  18144. };
  18145. };
  18146. const displayNotification = (editor, message) => {
  18147. editor.notificationManager.open({
  18148. type: 'error',
  18149. text: message
  18150. });
  18151. };
  18152. const displayError = (editor, message) => {
  18153. if (editor._skinLoaded) {
  18154. displayNotification(editor, message);
  18155. } else {
  18156. editor.on('SkinLoaded', () => {
  18157. displayNotification(editor, message);
  18158. });
  18159. }
  18160. };
  18161. const uploadError = (editor, message) => {
  18162. displayError(editor, I18n.translate([
  18163. 'Failed to upload image: {0}',
  18164. message
  18165. ]));
  18166. };
  18167. const logError = (editor, errorType, msg) => {
  18168. fireError(editor, errorType, { message: msg });
  18169. console.error(msg);
  18170. };
  18171. const createLoadError = (type, url, name) => name ? `Failed to load ${ type }: ${ name } from url ${ url }` : `Failed to load ${ type } url: ${ url }`;
  18172. const pluginLoadError = (editor, url, name) => {
  18173. logError(editor, 'PluginLoadError', createLoadError('plugin', url, name));
  18174. };
  18175. const iconsLoadError = (editor, url, name) => {
  18176. logError(editor, 'IconsLoadError', createLoadError('icons', url, name));
  18177. };
  18178. const languageLoadError = (editor, url, name) => {
  18179. logError(editor, 'LanguageLoadError', createLoadError('language', url, name));
  18180. };
  18181. const themeLoadError = (editor, url, name) => {
  18182. logError(editor, 'ThemeLoadError', createLoadError('theme', url, name));
  18183. };
  18184. const modelLoadError = (editor, url, name) => {
  18185. logError(editor, 'ModelLoadError', createLoadError('model', url, name));
  18186. };
  18187. const pluginInitError = (editor, name, err) => {
  18188. const message = I18n.translate([
  18189. 'Failed to initialize plugin: {0}',
  18190. name
  18191. ]);
  18192. fireError(editor, 'PluginLoadError', { message });
  18193. initError(message, err);
  18194. displayError(editor, message);
  18195. };
  18196. const initError = (message, ...x) => {
  18197. const console = window.console;
  18198. if (console) {
  18199. if (console.error) {
  18200. console.error(message, ...x);
  18201. } else {
  18202. console.log(message, ...x);
  18203. }
  18204. }
  18205. };
  18206. const isContentCssSkinName = url => /^[a-z0-9\-]+$/i.test(url);
  18207. const getContentCssUrls = editor => {
  18208. return transformToUrls(editor, getContentCss(editor));
  18209. };
  18210. const getFontCssUrls = editor => {
  18211. return transformToUrls(editor, getFontCss(editor));
  18212. };
  18213. const transformToUrls = (editor, cssLinks) => {
  18214. const skinUrl = editor.editorManager.baseURL + '/skins/content';
  18215. const suffix = editor.editorManager.suffix;
  18216. const contentCssFile = `content${ suffix }.css`;
  18217. const inline = editor.inline === true;
  18218. return map$3(cssLinks, url => {
  18219. if (isContentCssSkinName(url) && !inline) {
  18220. return `${ skinUrl }/${ url }/${ contentCssFile }`;
  18221. } else {
  18222. return editor.documentBaseURI.toAbsolute(url);
  18223. }
  18224. });
  18225. };
  18226. const appendContentCssFromSettings = editor => {
  18227. editor.contentCSS = editor.contentCSS.concat(getContentCssUrls(editor), getFontCssUrls(editor));
  18228. };
  18229. const filter$1 = always;
  18230. const bind$1 = (element, event, handler) => bind$2(element, event, filter$1, handler);
  18231. const getAllImages = elm => {
  18232. return elm ? from(elm.getElementsByTagName('img')) : [];
  18233. };
  18234. const ImageScanner = (uploadStatus, blobCache) => {
  18235. const cachedPromises = {};
  18236. const findAll = (elm, predicate = always) => {
  18237. const images = filter$6(getAllImages(elm), img => {
  18238. const src = img.src;
  18239. if (img.hasAttribute('data-mce-bogus')) {
  18240. return false;
  18241. }
  18242. if (img.hasAttribute('data-mce-placeholder')) {
  18243. return false;
  18244. }
  18245. if (!src || src === Env.transparentSrc) {
  18246. return false;
  18247. }
  18248. if (startsWith(src, 'blob:')) {
  18249. return !uploadStatus.isUploaded(src) && predicate(img);
  18250. }
  18251. if (startsWith(src, 'data:')) {
  18252. return predicate(img);
  18253. }
  18254. return false;
  18255. });
  18256. const promises = map$3(images, img => {
  18257. const imageSrc = img.src;
  18258. if (has$2(cachedPromises, imageSrc)) {
  18259. return cachedPromises[imageSrc].then(imageInfo => {
  18260. if (isString(imageInfo)) {
  18261. return imageInfo;
  18262. } else {
  18263. return {
  18264. image: img,
  18265. blobInfo: imageInfo.blobInfo
  18266. };
  18267. }
  18268. });
  18269. } else {
  18270. const newPromise = imageToBlobInfo(blobCache, imageSrc).then(blobInfo => {
  18271. delete cachedPromises[imageSrc];
  18272. return {
  18273. image: img,
  18274. blobInfo
  18275. };
  18276. }).catch(error => {
  18277. delete cachedPromises[imageSrc];
  18278. return error;
  18279. });
  18280. cachedPromises[imageSrc] = newPromise;
  18281. return newPromise;
  18282. }
  18283. });
  18284. return Promise.all(promises);
  18285. };
  18286. return { findAll };
  18287. };
  18288. const UploadStatus = () => {
  18289. const PENDING = 1, UPLOADED = 2;
  18290. let blobUriStatuses = {};
  18291. const createStatus = (status, resultUri) => {
  18292. return {
  18293. status,
  18294. resultUri
  18295. };
  18296. };
  18297. const hasBlobUri = blobUri => {
  18298. return blobUri in blobUriStatuses;
  18299. };
  18300. const getResultUri = blobUri => {
  18301. const result = blobUriStatuses[blobUri];
  18302. return result ? result.resultUri : null;
  18303. };
  18304. const isPending = blobUri => {
  18305. return hasBlobUri(blobUri) ? blobUriStatuses[blobUri].status === PENDING : false;
  18306. };
  18307. const isUploaded = blobUri => {
  18308. return hasBlobUri(blobUri) ? blobUriStatuses[blobUri].status === UPLOADED : false;
  18309. };
  18310. const markPending = blobUri => {
  18311. blobUriStatuses[blobUri] = createStatus(PENDING, null);
  18312. };
  18313. const markUploaded = (blobUri, resultUri) => {
  18314. blobUriStatuses[blobUri] = createStatus(UPLOADED, resultUri);
  18315. };
  18316. const removeFailed = blobUri => {
  18317. delete blobUriStatuses[blobUri];
  18318. };
  18319. const destroy = () => {
  18320. blobUriStatuses = {};
  18321. };
  18322. return {
  18323. hasBlobUri,
  18324. getResultUri,
  18325. isPending,
  18326. isUploaded,
  18327. markPending,
  18328. markUploaded,
  18329. removeFailed,
  18330. destroy
  18331. };
  18332. };
  18333. let count = 0;
  18334. const seed = () => {
  18335. const rnd = () => {
  18336. return Math.round(Math.random() * 4294967295).toString(36);
  18337. };
  18338. const now = new Date().getTime();
  18339. return 's' + now.toString(36) + rnd() + rnd() + rnd();
  18340. };
  18341. const uuid = prefix => {
  18342. return prefix + count++ + seed();
  18343. };
  18344. const BlobCache = () => {
  18345. let cache = [];
  18346. const mimeToExt = mime => {
  18347. const mimes = {
  18348. 'image/jpeg': 'jpg',
  18349. 'image/jpg': 'jpg',
  18350. 'image/gif': 'gif',
  18351. 'image/png': 'png',
  18352. 'image/apng': 'apng',
  18353. 'image/avif': 'avif',
  18354. 'image/svg+xml': 'svg',
  18355. 'image/webp': 'webp',
  18356. 'image/bmp': 'bmp',
  18357. 'image/tiff': 'tiff'
  18358. };
  18359. return mimes[mime.toLowerCase()] || 'dat';
  18360. };
  18361. const create = (o, blob, base64, name, filename) => {
  18362. if (isString(o)) {
  18363. const id = o;
  18364. return toBlobInfo({
  18365. id,
  18366. name,
  18367. filename,
  18368. blob,
  18369. base64
  18370. });
  18371. } else if (isObject(o)) {
  18372. return toBlobInfo(o);
  18373. } else {
  18374. throw new Error('Unknown input type');
  18375. }
  18376. };
  18377. const toBlobInfo = o => {
  18378. if (!o.blob || !o.base64) {
  18379. throw new Error('blob and base64 representations of the image are required for BlobInfo to be created');
  18380. }
  18381. const id = o.id || uuid('blobid');
  18382. const name = o.name || id;
  18383. const blob = o.blob;
  18384. return {
  18385. id: constant(id),
  18386. name: constant(name),
  18387. filename: constant(o.filename || name + '.' + mimeToExt(blob.type)),
  18388. blob: constant(blob),
  18389. base64: constant(o.base64),
  18390. blobUri: constant(o.blobUri || URL.createObjectURL(blob)),
  18391. uri: constant(o.uri)
  18392. };
  18393. };
  18394. const add = blobInfo => {
  18395. if (!get(blobInfo.id())) {
  18396. cache.push(blobInfo);
  18397. }
  18398. };
  18399. const findFirst = predicate => find$2(cache, predicate).getOrUndefined();
  18400. const get = id => findFirst(cachedBlobInfo => cachedBlobInfo.id() === id);
  18401. const getByUri = blobUri => findFirst(blobInfo => blobInfo.blobUri() === blobUri);
  18402. const getByData = (base64, type) => findFirst(blobInfo => blobInfo.base64() === base64 && blobInfo.blob().type === type);
  18403. const removeByUri = blobUri => {
  18404. cache = filter$6(cache, blobInfo => {
  18405. if (blobInfo.blobUri() === blobUri) {
  18406. URL.revokeObjectURL(blobInfo.blobUri());
  18407. return false;
  18408. }
  18409. return true;
  18410. });
  18411. };
  18412. const destroy = () => {
  18413. each$f(cache, cachedBlobInfo => {
  18414. URL.revokeObjectURL(cachedBlobInfo.blobUri());
  18415. });
  18416. cache = [];
  18417. };
  18418. return {
  18419. create,
  18420. add,
  18421. get,
  18422. getByUri,
  18423. getByData,
  18424. findFirst,
  18425. removeByUri,
  18426. destroy
  18427. };
  18428. };
  18429. const Uploader = (uploadStatus, settings) => {
  18430. const pendingPromises = {};
  18431. const pathJoin = (path1, path2) => {
  18432. if (path1) {
  18433. return path1.replace(/\/$/, '') + '/' + path2.replace(/^\//, '');
  18434. }
  18435. return path2;
  18436. };
  18437. const defaultHandler = (blobInfo, progress) => new Promise((success, failure) => {
  18438. const xhr = new XMLHttpRequest();
  18439. xhr.open('POST', settings.url);
  18440. xhr.withCredentials = settings.credentials;
  18441. xhr.upload.onprogress = e => {
  18442. progress(e.loaded / e.total * 100);
  18443. };
  18444. xhr.onerror = () => {
  18445. failure('Image upload failed due to a XHR Transport error. Code: ' + xhr.status);
  18446. };
  18447. xhr.onload = () => {
  18448. if (xhr.status < 200 || xhr.status >= 300) {
  18449. failure('HTTP Error: ' + xhr.status);
  18450. return;
  18451. }
  18452. const json = JSON.parse(xhr.responseText);
  18453. if (!json || !isString(json.location)) {
  18454. failure('Invalid JSON: ' + xhr.responseText);
  18455. return;
  18456. }
  18457. success(pathJoin(settings.basePath, json.location));
  18458. };
  18459. const formData = new FormData();
  18460. formData.append('file', blobInfo.blob(), blobInfo.filename());
  18461. xhr.send(formData);
  18462. });
  18463. const noUpload = () => new Promise(resolve => {
  18464. resolve([]);
  18465. });
  18466. const handlerSuccess = (blobInfo, url) => ({
  18467. url,
  18468. blobInfo,
  18469. status: true
  18470. });
  18471. const handlerFailure = (blobInfo, error) => ({
  18472. url: '',
  18473. blobInfo,
  18474. status: false,
  18475. error
  18476. });
  18477. const resolvePending = (blobUri, result) => {
  18478. Tools.each(pendingPromises[blobUri], resolve => {
  18479. resolve(result);
  18480. });
  18481. delete pendingPromises[blobUri];
  18482. };
  18483. const uploadBlobInfo = (blobInfo, handler, openNotification) => {
  18484. uploadStatus.markPending(blobInfo.blobUri());
  18485. return new Promise(resolve => {
  18486. let notification;
  18487. let progress;
  18488. try {
  18489. const closeNotification = () => {
  18490. if (notification) {
  18491. notification.close();
  18492. progress = noop;
  18493. }
  18494. };
  18495. const success = url => {
  18496. closeNotification();
  18497. uploadStatus.markUploaded(blobInfo.blobUri(), url);
  18498. resolvePending(blobInfo.blobUri(), handlerSuccess(blobInfo, url));
  18499. resolve(handlerSuccess(blobInfo, url));
  18500. };
  18501. const failure = error => {
  18502. closeNotification();
  18503. uploadStatus.removeFailed(blobInfo.blobUri());
  18504. resolvePending(blobInfo.blobUri(), handlerFailure(blobInfo, error));
  18505. resolve(handlerFailure(blobInfo, error));
  18506. };
  18507. progress = percent => {
  18508. if (percent < 0 || percent > 100) {
  18509. return;
  18510. }
  18511. Optional.from(notification).orThunk(() => Optional.from(openNotification).map(apply$1)).each(n => {
  18512. notification = n;
  18513. n.progressBar.value(percent);
  18514. });
  18515. };
  18516. handler(blobInfo, progress).then(success, err => {
  18517. failure(isString(err) ? { message: err } : err);
  18518. });
  18519. } catch (ex) {
  18520. resolve(handlerFailure(blobInfo, ex));
  18521. }
  18522. });
  18523. };
  18524. const isDefaultHandler = handler => handler === defaultHandler;
  18525. const pendingUploadBlobInfo = blobInfo => {
  18526. const blobUri = blobInfo.blobUri();
  18527. return new Promise(resolve => {
  18528. pendingPromises[blobUri] = pendingPromises[blobUri] || [];
  18529. pendingPromises[blobUri].push(resolve);
  18530. });
  18531. };
  18532. const uploadBlobs = (blobInfos, openNotification) => {
  18533. blobInfos = Tools.grep(blobInfos, blobInfo => !uploadStatus.isUploaded(blobInfo.blobUri()));
  18534. return Promise.all(Tools.map(blobInfos, blobInfo => uploadStatus.isPending(blobInfo.blobUri()) ? pendingUploadBlobInfo(blobInfo) : uploadBlobInfo(blobInfo, settings.handler, openNotification)));
  18535. };
  18536. const upload = (blobInfos, openNotification) => !settings.url && isDefaultHandler(settings.handler) ? noUpload() : uploadBlobs(blobInfos, openNotification);
  18537. if (isFunction(settings.handler) === false) {
  18538. settings.handler = defaultHandler;
  18539. }
  18540. return { upload };
  18541. };
  18542. const openNotification = editor => () => editor.notificationManager.open({
  18543. text: editor.translate('Image uploading...'),
  18544. type: 'info',
  18545. timeout: -1,
  18546. progressBar: true
  18547. });
  18548. const createUploader = (editor, uploadStatus) => Uploader(uploadStatus, {
  18549. url: getImageUploadUrl(editor),
  18550. basePath: getImageUploadBasePath(editor),
  18551. credentials: getImagesUploadCredentials(editor),
  18552. handler: getImagesUploadHandler(editor)
  18553. });
  18554. const ImageUploader = editor => {
  18555. const uploadStatus = UploadStatus();
  18556. const uploader = createUploader(editor, uploadStatus);
  18557. return { upload: (blobInfos, showNotification = true) => uploader.upload(blobInfos, showNotification ? openNotification(editor) : undefined) };
  18558. };
  18559. const EditorUpload = editor => {
  18560. const blobCache = BlobCache();
  18561. let uploader, imageScanner;
  18562. const uploadStatus = UploadStatus();
  18563. const urlFilters = [];
  18564. const aliveGuard = callback => {
  18565. return result => {
  18566. if (editor.selection) {
  18567. return callback(result);
  18568. }
  18569. return [];
  18570. };
  18571. };
  18572. const cacheInvalidator = url => url + (url.indexOf('?') === -1 ? '?' : '&') + new Date().getTime();
  18573. const replaceString = (content, search, replace) => {
  18574. let index = 0;
  18575. do {
  18576. index = content.indexOf(search, index);
  18577. if (index !== -1) {
  18578. content = content.substring(0, index) + replace + content.substr(index + search.length);
  18579. index += replace.length - search.length + 1;
  18580. }
  18581. } while (index !== -1);
  18582. return content;
  18583. };
  18584. const replaceImageUrl = (content, targetUrl, replacementUrl) => {
  18585. const replacementString = `src="${ replacementUrl }"${ replacementUrl === Env.transparentSrc ? ' data-mce-placeholder="1"' : '' }`;
  18586. content = replaceString(content, `src="${ targetUrl }"`, replacementString);
  18587. content = replaceString(content, 'data-mce-src="' + targetUrl + '"', 'data-mce-src="' + replacementUrl + '"');
  18588. return content;
  18589. };
  18590. const replaceUrlInUndoStack = (targetUrl, replacementUrl) => {
  18591. each$f(editor.undoManager.data, level => {
  18592. if (level.type === 'fragmented') {
  18593. level.fragments = map$3(level.fragments, fragment => replaceImageUrl(fragment, targetUrl, replacementUrl));
  18594. } else {
  18595. level.content = replaceImageUrl(level.content, targetUrl, replacementUrl);
  18596. }
  18597. });
  18598. };
  18599. const replaceImageUriInView = (image, resultUri) => {
  18600. const src = editor.convertURL(resultUri, 'src');
  18601. replaceUrlInUndoStack(image.src, resultUri);
  18602. setAll$1(SugarElement.fromDom(image), {
  18603. 'src': shouldReuseFileName(editor) ? cacheInvalidator(resultUri) : resultUri,
  18604. 'data-mce-src': src
  18605. });
  18606. };
  18607. const uploadImages = () => {
  18608. if (!uploader) {
  18609. uploader = createUploader(editor, uploadStatus);
  18610. }
  18611. return scanForImages().then(aliveGuard(imageInfos => {
  18612. const blobInfos = map$3(imageInfos, imageInfo => imageInfo.blobInfo);
  18613. return uploader.upload(blobInfos, openNotification(editor)).then(aliveGuard(result => {
  18614. const imagesToRemove = [];
  18615. let shouldDispatchChange = false;
  18616. const filteredResult = map$3(result, (uploadInfo, index) => {
  18617. const blobInfo = imageInfos[index].blobInfo;
  18618. const image = imageInfos[index].image;
  18619. let removed = false;
  18620. if (uploadInfo.status && shouldReplaceBlobUris(editor)) {
  18621. if (uploadInfo.url && !contains$1(image.src, uploadInfo.url)) {
  18622. shouldDispatchChange = true;
  18623. }
  18624. blobCache.removeByUri(image.src);
  18625. if (isRtc(editor)) ; else {
  18626. replaceImageUriInView(image, uploadInfo.url);
  18627. }
  18628. } else if (uploadInfo.error) {
  18629. if (uploadInfo.error.remove) {
  18630. replaceUrlInUndoStack(image.getAttribute('src'), Env.transparentSrc);
  18631. imagesToRemove.push(image);
  18632. removed = true;
  18633. }
  18634. uploadError(editor, uploadInfo.error.message);
  18635. }
  18636. return {
  18637. element: image,
  18638. status: uploadInfo.status,
  18639. uploadUri: uploadInfo.url,
  18640. blobInfo,
  18641. removed
  18642. };
  18643. });
  18644. if (imagesToRemove.length > 0 && !isRtc(editor)) {
  18645. editor.undoManager.transact(() => {
  18646. each$f(imagesToRemove, element => {
  18647. editor.dom.remove(element);
  18648. blobCache.removeByUri(element.src);
  18649. });
  18650. });
  18651. } else if (shouldDispatchChange) {
  18652. editor.undoManager.dispatchChange();
  18653. }
  18654. return filteredResult;
  18655. }));
  18656. }));
  18657. };
  18658. const uploadImagesAuto = () => isAutomaticUploadsEnabled(editor) ? uploadImages() : Promise.resolve([]);
  18659. const isValidDataUriImage = imgElm => forall(urlFilters, filter => filter(imgElm));
  18660. const addFilter = filter => {
  18661. urlFilters.push(filter);
  18662. };
  18663. const scanForImages = () => {
  18664. if (!imageScanner) {
  18665. imageScanner = ImageScanner(uploadStatus, blobCache);
  18666. }
  18667. return imageScanner.findAll(editor.getBody(), isValidDataUriImage).then(aliveGuard(result => {
  18668. const filteredResult = filter$6(result, resultItem => {
  18669. if (isString(resultItem)) {
  18670. displayError(editor, resultItem);
  18671. return false;
  18672. } else {
  18673. return true;
  18674. }
  18675. });
  18676. if (isRtc(editor)) ; else {
  18677. each$f(filteredResult, resultItem => {
  18678. replaceUrlInUndoStack(resultItem.image.src, resultItem.blobInfo.blobUri());
  18679. resultItem.image.src = resultItem.blobInfo.blobUri();
  18680. resultItem.image.removeAttribute('data-mce-src');
  18681. });
  18682. }
  18683. return filteredResult;
  18684. }));
  18685. };
  18686. const destroy = () => {
  18687. blobCache.destroy();
  18688. uploadStatus.destroy();
  18689. imageScanner = uploader = null;
  18690. };
  18691. const replaceBlobUris = content => {
  18692. return content.replace(/src="(blob:[^"]+)"/g, (match, blobUri) => {
  18693. const resultUri = uploadStatus.getResultUri(blobUri);
  18694. if (resultUri) {
  18695. return 'src="' + resultUri + '"';
  18696. }
  18697. let blobInfo = blobCache.getByUri(blobUri);
  18698. if (!blobInfo) {
  18699. blobInfo = foldl(editor.editorManager.get(), (result, editor) => {
  18700. return result || editor.editorUpload && editor.editorUpload.blobCache.getByUri(blobUri);
  18701. }, null);
  18702. }
  18703. if (blobInfo) {
  18704. const blob = blobInfo.blob();
  18705. return 'src="data:' + blob.type + ';base64,' + blobInfo.base64() + '"';
  18706. }
  18707. return match;
  18708. });
  18709. };
  18710. editor.on('SetContent', () => {
  18711. if (isAutomaticUploadsEnabled(editor)) {
  18712. uploadImagesAuto();
  18713. } else {
  18714. scanForImages();
  18715. }
  18716. });
  18717. editor.on('RawSaveContent', e => {
  18718. e.content = replaceBlobUris(e.content);
  18719. });
  18720. editor.on('GetContent', e => {
  18721. if (e.source_view || e.format === 'raw' || e.format === 'tree') {
  18722. return;
  18723. }
  18724. e.content = replaceBlobUris(e.content);
  18725. });
  18726. editor.on('PostRender', () => {
  18727. editor.parser.addNodeFilter('img', images => {
  18728. each$f(images, img => {
  18729. const src = img.attr('src');
  18730. if (blobCache.getByUri(src)) {
  18731. return;
  18732. }
  18733. const resultUri = uploadStatus.getResultUri(src);
  18734. if (resultUri) {
  18735. img.attr('src', resultUri);
  18736. }
  18737. });
  18738. });
  18739. });
  18740. return {
  18741. blobCache,
  18742. addFilter,
  18743. uploadImages,
  18744. uploadImagesAuto,
  18745. scanForImages,
  18746. destroy
  18747. };
  18748. };
  18749. const get$1 = editor => {
  18750. const dom = editor.dom;
  18751. const schemaType = editor.schema.type;
  18752. const formats = {
  18753. valigntop: [{
  18754. selector: 'td,th',
  18755. styles: { verticalAlign: 'top' }
  18756. }],
  18757. valignmiddle: [{
  18758. selector: 'td,th',
  18759. styles: { verticalAlign: 'middle' }
  18760. }],
  18761. valignbottom: [{
  18762. selector: 'td,th',
  18763. styles: { verticalAlign: 'bottom' }
  18764. }],
  18765. alignleft: [
  18766. {
  18767. selector: 'figure.image',
  18768. collapsed: false,
  18769. classes: 'align-left',
  18770. ceFalseOverride: true,
  18771. preview: 'font-family font-size'
  18772. },
  18773. {
  18774. selector: 'figure,p,h1,h2,h3,h4,h5,h6,td,th,tr,div,ul,ol,li,pre',
  18775. styles: { textAlign: 'left' },
  18776. inherit: false,
  18777. preview: false
  18778. },
  18779. {
  18780. selector: 'img,audio,video',
  18781. collapsed: false,
  18782. styles: { float: 'left' },
  18783. preview: 'font-family font-size'
  18784. },
  18785. {
  18786. selector: 'table',
  18787. collapsed: false,
  18788. styles: {
  18789. marginLeft: '0px',
  18790. marginRight: 'auto'
  18791. },
  18792. onformat: table => {
  18793. dom.setStyle(table, 'float', null);
  18794. },
  18795. preview: 'font-family font-size'
  18796. }
  18797. ],
  18798. aligncenter: [
  18799. {
  18800. selector: 'figure,p,h1,h2,h3,h4,h5,h6,td,th,tr,div,ul,ol,li,pre',
  18801. styles: { textAlign: 'center' },
  18802. inherit: false,
  18803. preview: 'font-family font-size'
  18804. },
  18805. {
  18806. selector: 'figure.image',
  18807. collapsed: false,
  18808. classes: 'align-center',
  18809. ceFalseOverride: true,
  18810. preview: 'font-family font-size'
  18811. },
  18812. {
  18813. selector: 'img,audio,video',
  18814. collapsed: false,
  18815. styles: {
  18816. display: 'block',
  18817. marginLeft: 'auto',
  18818. marginRight: 'auto'
  18819. },
  18820. preview: false
  18821. },
  18822. {
  18823. selector: 'table',
  18824. collapsed: false,
  18825. styles: {
  18826. marginLeft: 'auto',
  18827. marginRight: 'auto'
  18828. },
  18829. preview: 'font-family font-size'
  18830. }
  18831. ],
  18832. alignright: [
  18833. {
  18834. selector: 'figure.image',
  18835. collapsed: false,
  18836. classes: 'align-right',
  18837. ceFalseOverride: true,
  18838. preview: 'font-family font-size'
  18839. },
  18840. {
  18841. selector: 'figure,p,h1,h2,h3,h4,h5,h6,td,th,tr,div,ul,ol,li,pre',
  18842. styles: { textAlign: 'right' },
  18843. inherit: false,
  18844. preview: 'font-family font-size'
  18845. },
  18846. {
  18847. selector: 'img,audio,video',
  18848. collapsed: false,
  18849. styles: { float: 'right' },
  18850. preview: 'font-family font-size'
  18851. },
  18852. {
  18853. selector: 'table',
  18854. collapsed: false,
  18855. styles: {
  18856. marginRight: '0px',
  18857. marginLeft: 'auto'
  18858. },
  18859. onformat: table => {
  18860. dom.setStyle(table, 'float', null);
  18861. },
  18862. preview: 'font-family font-size'
  18863. }
  18864. ],
  18865. alignjustify: [{
  18866. selector: 'figure,p,h1,h2,h3,h4,h5,h6,td,th,tr,div,ul,ol,li,pre',
  18867. styles: { textAlign: 'justify' },
  18868. inherit: false,
  18869. preview: 'font-family font-size'
  18870. }],
  18871. bold: [
  18872. {
  18873. inline: 'strong',
  18874. remove: 'all',
  18875. preserve_attributes: [
  18876. 'class',
  18877. 'style'
  18878. ]
  18879. },
  18880. {
  18881. inline: 'span',
  18882. styles: { fontWeight: 'bold' }
  18883. },
  18884. {
  18885. inline: 'b',
  18886. remove: 'all',
  18887. preserve_attributes: [
  18888. 'class',
  18889. 'style'
  18890. ]
  18891. }
  18892. ],
  18893. italic: [
  18894. {
  18895. inline: 'em',
  18896. remove: 'all',
  18897. preserve_attributes: [
  18898. 'class',
  18899. 'style'
  18900. ]
  18901. },
  18902. {
  18903. inline: 'span',
  18904. styles: { fontStyle: 'italic' }
  18905. },
  18906. {
  18907. inline: 'i',
  18908. remove: 'all',
  18909. preserve_attributes: [
  18910. 'class',
  18911. 'style'
  18912. ]
  18913. }
  18914. ],
  18915. underline: [
  18916. {
  18917. inline: 'span',
  18918. styles: { textDecoration: 'underline' },
  18919. exact: true
  18920. },
  18921. {
  18922. inline: 'u',
  18923. remove: 'all',
  18924. preserve_attributes: [
  18925. 'class',
  18926. 'style'
  18927. ]
  18928. }
  18929. ],
  18930. strikethrough: (() => {
  18931. const span = {
  18932. inline: 'span',
  18933. styles: { textDecoration: 'line-through' },
  18934. exact: true
  18935. };
  18936. const strike = {
  18937. inline: 'strike',
  18938. remove: 'all',
  18939. preserve_attributes: [
  18940. 'class',
  18941. 'style'
  18942. ]
  18943. };
  18944. const s = {
  18945. inline: 's',
  18946. remove: 'all',
  18947. preserve_attributes: [
  18948. 'class',
  18949. 'style'
  18950. ]
  18951. };
  18952. return schemaType !== 'html4' ? [
  18953. s,
  18954. span,
  18955. strike
  18956. ] : [
  18957. span,
  18958. s,
  18959. strike
  18960. ];
  18961. })(),
  18962. forecolor: {
  18963. inline: 'span',
  18964. styles: { color: '%value' },
  18965. links: true,
  18966. remove_similar: true,
  18967. clear_child_styles: true
  18968. },
  18969. hilitecolor: {
  18970. inline: 'span',
  18971. styles: { backgroundColor: '%value' },
  18972. links: true,
  18973. remove_similar: true,
  18974. clear_child_styles: true
  18975. },
  18976. fontname: {
  18977. inline: 'span',
  18978. toggle: false,
  18979. styles: { fontFamily: '%value' },
  18980. clear_child_styles: true
  18981. },
  18982. fontsize: {
  18983. inline: 'span',
  18984. toggle: false,
  18985. styles: { fontSize: '%value' },
  18986. clear_child_styles: true
  18987. },
  18988. lineheight: {
  18989. selector: 'h1,h2,h3,h4,h5,h6,p,li,td,th,div',
  18990. styles: { lineHeight: '%value' }
  18991. },
  18992. fontsize_class: {
  18993. inline: 'span',
  18994. attributes: { class: '%value' }
  18995. },
  18996. blockquote: {
  18997. block: 'blockquote',
  18998. wrapper: true,
  18999. remove: 'all'
  19000. },
  19001. subscript: { inline: 'sub' },
  19002. superscript: { inline: 'sup' },
  19003. code: { inline: 'code' },
  19004. link: {
  19005. inline: 'a',
  19006. selector: 'a',
  19007. remove: 'all',
  19008. split: true,
  19009. deep: true,
  19010. onmatch: (node, _fmt, _itemName) => {
  19011. return isElement$6(node) && node.hasAttribute('href');
  19012. },
  19013. onformat: (elm, _fmt, vars) => {
  19014. Tools.each(vars, (value, key) => {
  19015. dom.setAttrib(elm, key, value);
  19016. });
  19017. }
  19018. },
  19019. lang: {
  19020. inline: 'span',
  19021. clear_child_styles: true,
  19022. remove_similar: true,
  19023. attributes: {
  19024. 'lang': '%value',
  19025. 'data-mce-lang': vars => {
  19026. var _a;
  19027. return (_a = vars === null || vars === void 0 ? void 0 : vars.customValue) !== null && _a !== void 0 ? _a : null;
  19028. }
  19029. }
  19030. },
  19031. removeformat: [
  19032. {
  19033. selector: 'b,strong,em,i,font,u,strike,s,sub,sup,dfn,code,samp,kbd,var,cite,mark,q,del,ins,small',
  19034. remove: 'all',
  19035. split: true,
  19036. expand: false,
  19037. block_expand: true,
  19038. deep: true
  19039. },
  19040. {
  19041. selector: 'span',
  19042. attributes: [
  19043. 'style',
  19044. 'class'
  19045. ],
  19046. remove: 'empty',
  19047. split: true,
  19048. expand: false,
  19049. deep: true
  19050. },
  19051. {
  19052. selector: '*',
  19053. attributes: [
  19054. 'style',
  19055. 'class'
  19056. ],
  19057. split: false,
  19058. expand: false,
  19059. deep: true
  19060. }
  19061. ]
  19062. };
  19063. Tools.each('p h1 h2 h3 h4 h5 h6 div address pre dt dd samp'.split(/\s/), name => {
  19064. formats[name] = {
  19065. block: name,
  19066. remove: 'all'
  19067. };
  19068. });
  19069. return formats;
  19070. };
  19071. const genericBase = {
  19072. remove_similar: true,
  19073. inherit: false
  19074. };
  19075. const cellBase = {
  19076. selector: 'td,th',
  19077. ...genericBase
  19078. };
  19079. const cellFormats = {
  19080. tablecellbackgroundcolor: {
  19081. styles: { backgroundColor: '%value' },
  19082. ...cellBase
  19083. },
  19084. tablecellverticalalign: {
  19085. styles: { 'vertical-align': '%value' },
  19086. ...cellBase
  19087. },
  19088. tablecellbordercolor: {
  19089. styles: { borderColor: '%value' },
  19090. ...cellBase
  19091. },
  19092. tablecellclass: {
  19093. classes: ['%value'],
  19094. ...cellBase
  19095. },
  19096. tableclass: {
  19097. selector: 'table',
  19098. classes: ['%value'],
  19099. ...genericBase
  19100. },
  19101. tablecellborderstyle: {
  19102. styles: { borderStyle: '%value' },
  19103. ...cellBase
  19104. },
  19105. tablecellborderwidth: {
  19106. styles: { borderWidth: '%value' },
  19107. ...cellBase
  19108. }
  19109. };
  19110. const get = constant(cellFormats);
  19111. const FormatRegistry = editor => {
  19112. const formats = {};
  19113. const get$2 = name => isNonNullable(name) ? formats[name] : formats;
  19114. const has = name => has$2(formats, name);
  19115. const register = (name, format) => {
  19116. if (name) {
  19117. if (!isString(name)) {
  19118. each$e(name, (format, name) => {
  19119. register(name, format);
  19120. });
  19121. } else {
  19122. if (!isArray$1(format)) {
  19123. format = [format];
  19124. }
  19125. each$f(format, format => {
  19126. if (isUndefined(format.deep)) {
  19127. format.deep = !isSelectorFormat(format);
  19128. }
  19129. if (isUndefined(format.split)) {
  19130. format.split = !isSelectorFormat(format) || isInlineFormat(format);
  19131. }
  19132. if (isUndefined(format.remove) && isSelectorFormat(format) && !isInlineFormat(format)) {
  19133. format.remove = 'none';
  19134. }
  19135. if (isSelectorFormat(format) && isInlineFormat(format)) {
  19136. format.mixed = true;
  19137. format.block_expand = true;
  19138. }
  19139. if (isString(format.classes)) {
  19140. format.classes = format.classes.split(/\s+/);
  19141. }
  19142. });
  19143. formats[name] = format;
  19144. }
  19145. }
  19146. };
  19147. const unregister = name => {
  19148. if (name && formats[name]) {
  19149. delete formats[name];
  19150. }
  19151. return formats;
  19152. };
  19153. register(get$1(editor));
  19154. register(get());
  19155. register(getFormats(editor));
  19156. return {
  19157. get: get$2,
  19158. has,
  19159. register,
  19160. unregister
  19161. };
  19162. };
  19163. const each$3 = Tools.each;
  19164. const dom = DOMUtils.DOM;
  19165. const parsedSelectorToHtml = (ancestry, editor) => {
  19166. let elm, item, fragment;
  19167. const schema = editor && editor.schema || Schema({});
  19168. const decorate = (elm, item) => {
  19169. if (item.classes.length) {
  19170. dom.addClass(elm, item.classes.join(' '));
  19171. }
  19172. dom.setAttribs(elm, item.attrs);
  19173. };
  19174. const createElement = sItem => {
  19175. item = typeof sItem === 'string' ? {
  19176. name: sItem,
  19177. classes: [],
  19178. attrs: {}
  19179. } : sItem;
  19180. const elm = dom.create(item.name);
  19181. decorate(elm, item);
  19182. return elm;
  19183. };
  19184. const getRequiredParent = (elm, candidate) => {
  19185. const name = typeof elm !== 'string' ? elm.nodeName.toLowerCase() : elm;
  19186. const elmRule = schema.getElementRule(name);
  19187. const parentsRequired = elmRule && elmRule.parentsRequired;
  19188. if (parentsRequired && parentsRequired.length) {
  19189. return candidate && Tools.inArray(parentsRequired, candidate) !== -1 ? candidate : parentsRequired[0];
  19190. } else {
  19191. return false;
  19192. }
  19193. };
  19194. const wrapInHtml = (elm, ancestry, siblings) => {
  19195. let parent, parentCandidate;
  19196. const ancestor = ancestry.length > 0 && ancestry[0];
  19197. const ancestorName = ancestor && ancestor.name;
  19198. const parentRequired = getRequiredParent(elm, ancestorName);
  19199. if (parentRequired) {
  19200. if (ancestorName === parentRequired) {
  19201. parentCandidate = ancestry[0];
  19202. ancestry = ancestry.slice(1);
  19203. } else {
  19204. parentCandidate = parentRequired;
  19205. }
  19206. } else if (ancestor) {
  19207. parentCandidate = ancestry[0];
  19208. ancestry = ancestry.slice(1);
  19209. } else if (!siblings) {
  19210. return elm;
  19211. }
  19212. if (parentCandidate) {
  19213. parent = createElement(parentCandidate);
  19214. parent.appendChild(elm);
  19215. }
  19216. if (siblings) {
  19217. if (!parent) {
  19218. parent = dom.create('div');
  19219. parent.appendChild(elm);
  19220. }
  19221. Tools.each(siblings, sibling => {
  19222. const siblingElm = createElement(sibling);
  19223. parent.insertBefore(siblingElm, elm);
  19224. });
  19225. }
  19226. return wrapInHtml(parent, ancestry, parentCandidate && parentCandidate.siblings);
  19227. };
  19228. if (ancestry && ancestry.length) {
  19229. item = ancestry[0];
  19230. elm = createElement(item);
  19231. fragment = dom.create('div');
  19232. fragment.appendChild(wrapInHtml(elm, ancestry.slice(1), item.siblings));
  19233. return fragment;
  19234. } else {
  19235. return '';
  19236. }
  19237. };
  19238. const parseSelectorItem = item => {
  19239. let tagName;
  19240. const obj = {
  19241. classes: [],
  19242. attrs: {}
  19243. };
  19244. item = obj.selector = Tools.trim(item);
  19245. if (item !== '*') {
  19246. tagName = item.replace(/(?:([#\.]|::?)([\w\-]+)|(\[)([^\]]+)\]?)/g, ($0, $1, $2, $3, $4) => {
  19247. switch ($1) {
  19248. case '#':
  19249. obj.attrs.id = $2;
  19250. break;
  19251. case '.':
  19252. obj.classes.push($2);
  19253. break;
  19254. case ':':
  19255. if (Tools.inArray('checked disabled enabled read-only required'.split(' '), $2) !== -1) {
  19256. obj.attrs[$2] = $2;
  19257. }
  19258. break;
  19259. }
  19260. if ($3 === '[') {
  19261. const m = $4.match(/([\w\-]+)(?:\=\"([^\"]+))?/);
  19262. if (m) {
  19263. obj.attrs[m[1]] = m[2];
  19264. }
  19265. }
  19266. return '';
  19267. });
  19268. }
  19269. obj.name = tagName || 'div';
  19270. return obj;
  19271. };
  19272. const parseSelector = selector => {
  19273. if (!selector || typeof selector !== 'string') {
  19274. return [];
  19275. }
  19276. selector = selector.split(/\s*,\s*/)[0];
  19277. selector = selector.replace(/\s*(~\+|~|\+|>)\s*/g, '$1');
  19278. return Tools.map(selector.split(/(?:>|\s+(?![^\[\]]+\]))/), item => {
  19279. const siblings = Tools.map(item.split(/(?:~\+|~|\+)/), parseSelectorItem);
  19280. const obj = siblings.pop();
  19281. if (siblings.length) {
  19282. obj.siblings = siblings;
  19283. }
  19284. return obj;
  19285. }).reverse();
  19286. };
  19287. const getCssText = (editor, format) => {
  19288. let name, previewFrag;
  19289. let previewCss = '', parentFontSize;
  19290. let previewStyles = getPreviewStyles(editor);
  19291. if (previewStyles === '') {
  19292. return '';
  19293. }
  19294. const removeVars = val => {
  19295. return val.replace(/%(\w+)/g, '');
  19296. };
  19297. if (typeof format === 'string') {
  19298. format = editor.formatter.get(format);
  19299. if (!format) {
  19300. return;
  19301. }
  19302. format = format[0];
  19303. }
  19304. if ('preview' in format) {
  19305. const previewOpt = get$a(format, 'preview');
  19306. if (is$2(previewOpt, false)) {
  19307. return '';
  19308. } else {
  19309. previewStyles = previewOpt.getOr(previewStyles);
  19310. }
  19311. }
  19312. name = format.block || format.inline || 'span';
  19313. const items = parseSelector(format.selector);
  19314. if (items.length) {
  19315. if (!items[0].name) {
  19316. items[0].name = name;
  19317. }
  19318. name = format.selector;
  19319. previewFrag = parsedSelectorToHtml(items, editor);
  19320. } else {
  19321. previewFrag = parsedSelectorToHtml([name], editor);
  19322. }
  19323. const previewElm = dom.select(name, previewFrag)[0] || previewFrag.firstChild;
  19324. each$3(format.styles, (value, name) => {
  19325. const newValue = removeVars(value);
  19326. if (newValue) {
  19327. dom.setStyle(previewElm, name, newValue);
  19328. }
  19329. });
  19330. each$3(format.attributes, (value, name) => {
  19331. const newValue = removeVars(value);
  19332. if (newValue) {
  19333. dom.setAttrib(previewElm, name, newValue);
  19334. }
  19335. });
  19336. each$3(format.classes, value => {
  19337. const newValue = removeVars(value);
  19338. if (!dom.hasClass(previewElm, newValue)) {
  19339. dom.addClass(previewElm, newValue);
  19340. }
  19341. });
  19342. editor.dispatch('PreviewFormats');
  19343. dom.setStyles(previewFrag, {
  19344. position: 'absolute',
  19345. left: -65535
  19346. });
  19347. editor.getBody().appendChild(previewFrag);
  19348. parentFontSize = dom.getStyle(editor.getBody(), 'fontSize', true);
  19349. parentFontSize = /px$/.test(parentFontSize) ? parseInt(parentFontSize, 10) : 0;
  19350. each$3(previewStyles.split(' '), name => {
  19351. let value = dom.getStyle(previewElm, name, true);
  19352. if (name === 'background-color' && /transparent|rgba\s*\([^)]+,\s*0\)/.test(value)) {
  19353. value = dom.getStyle(editor.getBody(), name, true);
  19354. if (rgbaToHexString(value).toLowerCase() === '#ffffff') {
  19355. return;
  19356. }
  19357. }
  19358. if (name === 'color') {
  19359. if (rgbaToHexString(value).toLowerCase() === '#000000') {
  19360. return;
  19361. }
  19362. }
  19363. if (name === 'font-size') {
  19364. if (/em|%$/.test(value)) {
  19365. if (parentFontSize === 0) {
  19366. return;
  19367. }
  19368. const numValue = parseFloat(value) / (/%$/.test(value) ? 100 : 1);
  19369. value = numValue * parentFontSize + 'px';
  19370. }
  19371. }
  19372. if (name === 'border' && value) {
  19373. previewCss += 'padding:0 2px;';
  19374. }
  19375. previewCss += name + ':' + value + ';';
  19376. });
  19377. editor.dispatch('AfterPreviewFormats');
  19378. dom.remove(previewFrag);
  19379. return previewCss;
  19380. };
  19381. const setup$r = editor => {
  19382. editor.addShortcut('meta+b', '', 'Bold');
  19383. editor.addShortcut('meta+i', '', 'Italic');
  19384. editor.addShortcut('meta+u', '', 'Underline');
  19385. for (let i = 1; i <= 6; i++) {
  19386. editor.addShortcut('access+' + i, '', [
  19387. 'FormatBlock',
  19388. false,
  19389. 'h' + i
  19390. ]);
  19391. }
  19392. editor.addShortcut('access+7', '', [
  19393. 'FormatBlock',
  19394. false,
  19395. 'p'
  19396. ]);
  19397. editor.addShortcut('access+8', '', [
  19398. 'FormatBlock',
  19399. false,
  19400. 'div'
  19401. ]);
  19402. editor.addShortcut('access+9', '', [
  19403. 'FormatBlock',
  19404. false,
  19405. 'address'
  19406. ]);
  19407. };
  19408. const Formatter = editor => {
  19409. const formats = FormatRegistry(editor);
  19410. const formatChangeState = Cell(null);
  19411. setup$r(editor);
  19412. setup$u(editor);
  19413. return {
  19414. get: formats.get,
  19415. has: formats.has,
  19416. register: formats.register,
  19417. unregister: formats.unregister,
  19418. apply: (name, vars, node) => {
  19419. applyFormat(editor, name, vars, node);
  19420. },
  19421. remove: (name, vars, node, similar) => {
  19422. removeFormat(editor, name, vars, node, similar);
  19423. },
  19424. toggle: (name, vars, node) => {
  19425. toggleFormat(editor, name, vars, node);
  19426. },
  19427. match: (name, vars, node, similar) => matchFormat(editor, name, vars, node, similar),
  19428. closest: names => closestFormat(editor, names),
  19429. matchAll: (names, vars) => matchAllFormats(editor, names, vars),
  19430. matchNode: (node, name, vars, similar) => matchNodeFormat(editor, node, name, vars, similar),
  19431. canApply: name => canApplyFormat(editor, name),
  19432. formatChanged: (formats, callback, similar, vars) => formatChanged(editor, formatChangeState, formats, callback, similar, vars),
  19433. getCssText: curry(getCssText, editor)
  19434. };
  19435. };
  19436. const shouldIgnoreCommand = cmd => {
  19437. switch (cmd.toLowerCase()) {
  19438. case 'undo':
  19439. case 'redo':
  19440. case 'mcefocus':
  19441. return true;
  19442. default:
  19443. return false;
  19444. }
  19445. };
  19446. const registerEvents = (editor, undoManager, locks) => {
  19447. const isFirstTypedCharacter = Cell(false);
  19448. const addNonTypingUndoLevel = e => {
  19449. setTyping(undoManager, false, locks);
  19450. undoManager.add({}, e);
  19451. };
  19452. editor.on('init', () => {
  19453. undoManager.add();
  19454. });
  19455. editor.on('BeforeExecCommand', e => {
  19456. const cmd = e.command;
  19457. if (!shouldIgnoreCommand(cmd)) {
  19458. endTyping(undoManager, locks);
  19459. undoManager.beforeChange();
  19460. }
  19461. });
  19462. editor.on('ExecCommand', e => {
  19463. const cmd = e.command;
  19464. if (!shouldIgnoreCommand(cmd)) {
  19465. addNonTypingUndoLevel(e);
  19466. }
  19467. });
  19468. editor.on('ObjectResizeStart cut', () => {
  19469. undoManager.beforeChange();
  19470. });
  19471. editor.on('SaveContent ObjectResized blur', addNonTypingUndoLevel);
  19472. editor.on('dragend', addNonTypingUndoLevel);
  19473. editor.on('keyup', e => {
  19474. const keyCode = e.keyCode;
  19475. if (e.isDefaultPrevented()) {
  19476. return;
  19477. }
  19478. if (keyCode >= 33 && keyCode <= 36 || keyCode >= 37 && keyCode <= 40 || keyCode === 45 || e.ctrlKey) {
  19479. addNonTypingUndoLevel();
  19480. editor.nodeChanged();
  19481. }
  19482. if (keyCode === 46 || keyCode === 8) {
  19483. editor.nodeChanged();
  19484. }
  19485. if (isFirstTypedCharacter.get() && undoManager.typing && isEq$1(createFromEditor(editor), undoManager.data[0]) === false) {
  19486. if (editor.isDirty() === false) {
  19487. editor.setDirty(true);
  19488. }
  19489. editor.dispatch('TypingUndo');
  19490. isFirstTypedCharacter.set(false);
  19491. editor.nodeChanged();
  19492. }
  19493. });
  19494. editor.on('keydown', e => {
  19495. const keyCode = e.keyCode;
  19496. if (e.isDefaultPrevented()) {
  19497. return;
  19498. }
  19499. if (keyCode >= 33 && keyCode <= 36 || keyCode >= 37 && keyCode <= 40 || keyCode === 45) {
  19500. if (undoManager.typing) {
  19501. addNonTypingUndoLevel(e);
  19502. }
  19503. return;
  19504. }
  19505. const modKey = e.ctrlKey && !e.altKey || e.metaKey;
  19506. if ((keyCode < 16 || keyCode > 20) && keyCode !== 224 && keyCode !== 91 && !undoManager.typing && !modKey) {
  19507. undoManager.beforeChange();
  19508. setTyping(undoManager, true, locks);
  19509. undoManager.add({}, e);
  19510. isFirstTypedCharacter.set(true);
  19511. }
  19512. });
  19513. editor.on('mousedown', e => {
  19514. if (undoManager.typing) {
  19515. addNonTypingUndoLevel(e);
  19516. }
  19517. });
  19518. const isInsertReplacementText = event => event.inputType === 'insertReplacementText';
  19519. const isInsertTextDataNull = event => event.inputType === 'insertText' && event.data === null;
  19520. const isInsertFromPasteOrDrop = event => event.inputType === 'insertFromPaste' || event.inputType === 'insertFromDrop';
  19521. editor.on('input', e => {
  19522. if (e.inputType && (isInsertReplacementText(e) || isInsertTextDataNull(e) || isInsertFromPasteOrDrop(e))) {
  19523. addNonTypingUndoLevel(e);
  19524. }
  19525. });
  19526. editor.on('AddUndo Undo Redo ClearUndos', e => {
  19527. if (!e.isDefaultPrevented()) {
  19528. editor.nodeChanged();
  19529. }
  19530. });
  19531. };
  19532. const addKeyboardShortcuts = editor => {
  19533. editor.addShortcut('meta+z', '', 'Undo');
  19534. editor.addShortcut('meta+y,meta+shift+z', '', 'Redo');
  19535. };
  19536. const UndoManager = editor => {
  19537. const beforeBookmark = value$2();
  19538. const locks = Cell(0);
  19539. const index = Cell(0);
  19540. const undoManager = {
  19541. data: [],
  19542. typing: false,
  19543. beforeChange: () => {
  19544. beforeChange(editor, locks, beforeBookmark);
  19545. },
  19546. add: (level, event) => {
  19547. return addUndoLevel(editor, undoManager, index, locks, beforeBookmark, level, event);
  19548. },
  19549. dispatchChange: () => {
  19550. editor.setDirty(true);
  19551. editor.dispatch('change', {
  19552. level: createFromEditor(editor),
  19553. lastLevel: get$b(undoManager.data, index.get()).getOrUndefined()
  19554. });
  19555. },
  19556. undo: () => {
  19557. return undo(editor, undoManager, locks, index);
  19558. },
  19559. redo: () => {
  19560. return redo(editor, index, undoManager.data);
  19561. },
  19562. clear: () => {
  19563. clear(editor, undoManager, index);
  19564. },
  19565. reset: () => {
  19566. reset(editor, undoManager);
  19567. },
  19568. hasUndo: () => {
  19569. return hasUndo(editor, undoManager, index);
  19570. },
  19571. hasRedo: () => {
  19572. return hasRedo(editor, undoManager, index);
  19573. },
  19574. transact: callback => {
  19575. return transact(editor, undoManager, locks, callback);
  19576. },
  19577. ignore: callback => {
  19578. ignore(editor, locks, callback);
  19579. },
  19580. extra: (callback1, callback2) => {
  19581. extra(editor, undoManager, index, callback1, callback2);
  19582. }
  19583. };
  19584. if (!isRtc(editor)) {
  19585. registerEvents(editor, undoManager, locks);
  19586. }
  19587. addKeyboardShortcuts(editor);
  19588. return undoManager;
  19589. };
  19590. const nonTypingKeycodes = [
  19591. 9,
  19592. 27,
  19593. VK.HOME,
  19594. VK.END,
  19595. 19,
  19596. 20,
  19597. 44,
  19598. 144,
  19599. 145,
  19600. 33,
  19601. 34,
  19602. 45,
  19603. 16,
  19604. 17,
  19605. 18,
  19606. 91,
  19607. 92,
  19608. 93,
  19609. VK.DOWN,
  19610. VK.UP,
  19611. VK.LEFT,
  19612. VK.RIGHT
  19613. ].concat(Env.browser.isFirefox() ? [224] : []);
  19614. const placeholderAttr = 'data-mce-placeholder';
  19615. const isKeyboardEvent = e => e.type === 'keydown' || e.type === 'keyup';
  19616. const isDeleteEvent = e => {
  19617. const keyCode = e.keyCode;
  19618. return keyCode === VK.BACKSPACE || keyCode === VK.DELETE;
  19619. };
  19620. const isNonTypingKeyboardEvent = e => {
  19621. if (isKeyboardEvent(e)) {
  19622. const keyCode = e.keyCode;
  19623. return !isDeleteEvent(e) && (VK.metaKeyPressed(e) || e.altKey || keyCode >= 112 && keyCode <= 123 || contains$2(nonTypingKeycodes, keyCode));
  19624. } else {
  19625. return false;
  19626. }
  19627. };
  19628. const isTypingKeyboardEvent = e => isKeyboardEvent(e) && !(isDeleteEvent(e) || e.type === 'keyup' && e.keyCode === 229);
  19629. const isVisuallyEmpty = (dom, rootElm, forcedRootBlock) => {
  19630. if (isEmpty$2(SugarElement.fromDom(rootElm), false)) {
  19631. const firstElement = rootElm.firstElementChild;
  19632. if (!firstElement) {
  19633. return true;
  19634. } else if (dom.getStyle(rootElm.firstElementChild, 'padding-left') || dom.getStyle(rootElm.firstElementChild, 'padding-right')) {
  19635. return false;
  19636. } else {
  19637. return forcedRootBlock === firstElement.nodeName.toLowerCase();
  19638. }
  19639. } else {
  19640. return false;
  19641. }
  19642. };
  19643. const setup$q = editor => {
  19644. const dom = editor.dom;
  19645. const rootBlock = getForcedRootBlock(editor);
  19646. const placeholder = getPlaceholder(editor);
  19647. const updatePlaceholder = (e, initial) => {
  19648. if (isNonTypingKeyboardEvent(e)) {
  19649. return;
  19650. }
  19651. const body = editor.getBody();
  19652. const showPlaceholder = isTypingKeyboardEvent(e) ? false : isVisuallyEmpty(dom, body, rootBlock);
  19653. const isPlaceholderShown = dom.getAttrib(body, placeholderAttr) !== '';
  19654. if (isPlaceholderShown !== showPlaceholder || initial) {
  19655. dom.setAttrib(body, placeholderAttr, showPlaceholder ? placeholder : null);
  19656. dom.setAttrib(body, 'aria-placeholder', showPlaceholder ? placeholder : null);
  19657. firePlaceholderToggle(editor, showPlaceholder);
  19658. editor.on(showPlaceholder ? 'keydown' : 'keyup', updatePlaceholder);
  19659. editor.off(showPlaceholder ? 'keyup' : 'keydown', updatePlaceholder);
  19660. }
  19661. };
  19662. if (placeholder) {
  19663. editor.on('init', e => {
  19664. updatePlaceholder(e, true);
  19665. editor.on('change SetContent ExecCommand', updatePlaceholder);
  19666. editor.on('paste', e => Delay.setEditorTimeout(editor, () => updatePlaceholder(e)));
  19667. });
  19668. }
  19669. };
  19670. const blockPosition = (block, position) => ({
  19671. block,
  19672. position
  19673. });
  19674. const blockBoundary = (from, to) => ({
  19675. from,
  19676. to
  19677. });
  19678. const getBlockPosition = (rootNode, pos) => {
  19679. const rootElm = SugarElement.fromDom(rootNode);
  19680. const containerElm = SugarElement.fromDom(pos.container());
  19681. return getParentBlock$2(rootElm, containerElm).map(block => blockPosition(block, pos));
  19682. };
  19683. const isDifferentBlocks = blockBoundary => eq(blockBoundary.from.block, blockBoundary.to.block) === false;
  19684. const hasSameParent = blockBoundary => parent(blockBoundary.from.block).bind(parent1 => parent(blockBoundary.to.block).filter(parent2 => eq(parent1, parent2))).isSome();
  19685. const isEditable$2 = blockBoundary => isContentEditableFalse$b(blockBoundary.from.block.dom) === false && isContentEditableFalse$b(blockBoundary.to.block.dom) === false;
  19686. const skipLastBr = (rootNode, forward, blockPosition) => {
  19687. if (isBr$6(blockPosition.position.getNode()) && isEmpty$2(blockPosition.block) === false) {
  19688. return positionIn(false, blockPosition.block.dom).bind(lastPositionInBlock => {
  19689. if (lastPositionInBlock.isEqual(blockPosition.position)) {
  19690. return fromPosition(forward, rootNode, lastPositionInBlock).bind(to => getBlockPosition(rootNode, to));
  19691. } else {
  19692. return Optional.some(blockPosition);
  19693. }
  19694. }).getOr(blockPosition);
  19695. } else {
  19696. return blockPosition;
  19697. }
  19698. };
  19699. const readFromRange = (rootNode, forward, rng) => {
  19700. const fromBlockPos = getBlockPosition(rootNode, CaretPosition.fromRangeStart(rng));
  19701. const toBlockPos = fromBlockPos.bind(blockPos => fromPosition(forward, rootNode, blockPos.position).bind(to => getBlockPosition(rootNode, to).map(blockPos => skipLastBr(rootNode, forward, blockPos))));
  19702. return lift2(fromBlockPos, toBlockPos, blockBoundary).filter(blockBoundary => isDifferentBlocks(blockBoundary) && hasSameParent(blockBoundary) && isEditable$2(blockBoundary));
  19703. };
  19704. const read$1 = (rootNode, forward, rng) => rng.collapsed ? readFromRange(rootNode, forward, rng) : Optional.none();
  19705. const getChildrenUntilBlockBoundary = block => {
  19706. const children$1 = children(block);
  19707. return findIndex$2(children$1, isBlock$2).fold(constant(children$1), index => children$1.slice(0, index));
  19708. };
  19709. const extractChildren = block => {
  19710. const children = getChildrenUntilBlockBoundary(block);
  19711. each$f(children, remove$6);
  19712. return children;
  19713. };
  19714. const removeEmptyRoot = (rootNode, block) => {
  19715. const parents = parentsAndSelf(block, rootNode);
  19716. return find$2(parents.reverse(), element => isEmpty$2(element)).each(remove$6);
  19717. };
  19718. const isEmptyBefore = el => filter$6(prevSiblings(el), el => !isEmpty$2(el)).length === 0;
  19719. const nestedBlockMerge = (rootNode, fromBlock, toBlock, insertionPoint) => {
  19720. if (isEmpty$2(toBlock)) {
  19721. fillWithPaddingBr(toBlock);
  19722. return firstPositionIn(toBlock.dom);
  19723. }
  19724. if (isEmptyBefore(insertionPoint) && isEmpty$2(fromBlock)) {
  19725. before$3(insertionPoint, SugarElement.fromTag('br'));
  19726. }
  19727. const position = prevPosition(toBlock.dom, CaretPosition.before(insertionPoint.dom));
  19728. each$f(extractChildren(fromBlock), child => {
  19729. before$3(insertionPoint, child);
  19730. });
  19731. removeEmptyRoot(rootNode, fromBlock);
  19732. return position;
  19733. };
  19734. const sidelongBlockMerge = (rootNode, fromBlock, toBlock) => {
  19735. if (isEmpty$2(toBlock)) {
  19736. remove$6(toBlock);
  19737. if (isEmpty$2(fromBlock)) {
  19738. fillWithPaddingBr(fromBlock);
  19739. }
  19740. return firstPositionIn(fromBlock.dom);
  19741. }
  19742. const position = lastPositionIn(toBlock.dom);
  19743. each$f(extractChildren(fromBlock), child => {
  19744. append$1(toBlock, child);
  19745. });
  19746. removeEmptyRoot(rootNode, fromBlock);
  19747. return position;
  19748. };
  19749. const findInsertionPoint = (toBlock, block) => {
  19750. const parentsAndSelf$1 = parentsAndSelf(block, toBlock);
  19751. return Optional.from(parentsAndSelf$1[parentsAndSelf$1.length - 1]);
  19752. };
  19753. const getInsertionPoint = (fromBlock, toBlock) => contains(toBlock, fromBlock) ? findInsertionPoint(toBlock, fromBlock) : Optional.none();
  19754. const trimBr = (first, block) => {
  19755. positionIn(first, block.dom).map(position => position.getNode()).map(SugarElement.fromDom).filter(isBr$5).each(remove$6);
  19756. };
  19757. const mergeBlockInto = (rootNode, fromBlock, toBlock) => {
  19758. trimBr(true, fromBlock);
  19759. trimBr(false, toBlock);
  19760. return getInsertionPoint(fromBlock, toBlock).fold(curry(sidelongBlockMerge, rootNode, fromBlock, toBlock), curry(nestedBlockMerge, rootNode, fromBlock, toBlock));
  19761. };
  19762. const mergeBlocks = (rootNode, forward, block1, block2) => forward ? mergeBlockInto(rootNode, block2, block1) : mergeBlockInto(rootNode, block1, block2);
  19763. const backspaceDelete$8 = (editor, forward) => {
  19764. const rootNode = SugarElement.fromDom(editor.getBody());
  19765. const position = read$1(rootNode.dom, forward, editor.selection.getRng()).map(blockBoundary => () => {
  19766. mergeBlocks(rootNode, forward, blockBoundary.from.block, blockBoundary.to.block).each(pos => {
  19767. editor.selection.setRng(pos.toRange());
  19768. });
  19769. });
  19770. return position;
  19771. };
  19772. const deleteRangeMergeBlocks = (rootNode, selection) => {
  19773. const rng = selection.getRng();
  19774. return lift2(getParentBlock$2(rootNode, SugarElement.fromDom(rng.startContainer)), getParentBlock$2(rootNode, SugarElement.fromDom(rng.endContainer)), (block1, block2) => {
  19775. if (eq(block1, block2) === false) {
  19776. return Optional.some(() => {
  19777. rng.deleteContents();
  19778. mergeBlocks(rootNode, true, block1, block2).each(pos => {
  19779. selection.setRng(pos.toRange());
  19780. });
  19781. });
  19782. } else {
  19783. return Optional.none();
  19784. }
  19785. }).getOr(Optional.none());
  19786. };
  19787. const isRawNodeInTable = (root, rawNode) => {
  19788. const node = SugarElement.fromDom(rawNode);
  19789. const isRoot = curry(eq, root);
  19790. return ancestor$3(node, isTableCell$4, isRoot).isSome();
  19791. };
  19792. const isSelectionInTable = (root, rng) => isRawNodeInTable(root, rng.startContainer) || isRawNodeInTable(root, rng.endContainer);
  19793. const isEverythingSelected = (root, rng) => {
  19794. const noPrevious = prevPosition(root.dom, CaretPosition.fromRangeStart(rng)).isNone();
  19795. const noNext = nextPosition(root.dom, CaretPosition.fromRangeEnd(rng)).isNone();
  19796. return !isSelectionInTable(root, rng) && noPrevious && noNext;
  19797. };
  19798. const emptyEditor = editor => {
  19799. return Optional.some(() => {
  19800. editor.setContent('');
  19801. editor.selection.setCursorLocation();
  19802. });
  19803. };
  19804. const deleteRange$1 = editor => {
  19805. const rootNode = SugarElement.fromDom(editor.getBody());
  19806. const rng = editor.selection.getRng();
  19807. return isEverythingSelected(rootNode, rng) ? emptyEditor(editor) : deleteRangeMergeBlocks(rootNode, editor.selection);
  19808. };
  19809. const backspaceDelete$7 = (editor, _forward) => editor.selection.isCollapsed() ? Optional.none() : deleteRange$1(editor);
  19810. const isContentEditableTrue$2 = isContentEditableTrue$5;
  19811. const isContentEditableFalse$5 = isContentEditableFalse$b;
  19812. const showCaret = (direction, editor, node, before, scrollIntoView) => Optional.from(editor._selectionOverrides.showCaret(direction, node, before, scrollIntoView));
  19813. const getNodeRange = node => {
  19814. const rng = node.ownerDocument.createRange();
  19815. rng.selectNode(node);
  19816. return rng;
  19817. };
  19818. const selectNode = (editor, node) => {
  19819. const e = editor.dispatch('BeforeObjectSelected', { target: node });
  19820. if (e.isDefaultPrevented()) {
  19821. return Optional.none();
  19822. }
  19823. return Optional.some(getNodeRange(node));
  19824. };
  19825. const renderCaretAtRange = (editor, range, scrollIntoView) => {
  19826. const normalizedRange = normalizeRange(1, editor.getBody(), range);
  19827. const caretPosition = CaretPosition.fromRangeStart(normalizedRange);
  19828. const caretPositionNode = caretPosition.getNode();
  19829. if (isInlineFakeCaretTarget(caretPositionNode)) {
  19830. return showCaret(1, editor, caretPositionNode, !caretPosition.isAtEnd(), false);
  19831. }
  19832. const caretPositionBeforeNode = caretPosition.getNode(true);
  19833. if (isInlineFakeCaretTarget(caretPositionBeforeNode)) {
  19834. return showCaret(1, editor, caretPositionBeforeNode, false, false);
  19835. }
  19836. const ceRoot = editor.dom.getParent(caretPosition.getNode(), node => isContentEditableFalse$5(node) || isContentEditableTrue$2(node));
  19837. if (isInlineFakeCaretTarget(ceRoot)) {
  19838. return showCaret(1, editor, ceRoot, false, scrollIntoView);
  19839. }
  19840. return Optional.none();
  19841. };
  19842. const renderRangeCaret = (editor, range, scrollIntoView) => range.collapsed ? renderCaretAtRange(editor, range, scrollIntoView).getOr(range) : range;
  19843. const isBeforeBoundary = pos => isBeforeContentEditableFalse(pos) || isBeforeMedia(pos);
  19844. const isAfterBoundary = pos => isAfterContentEditableFalse(pos) || isAfterMedia(pos);
  19845. const trimEmptyTextNode = (dom, node) => {
  19846. if (isText$9(node) && node.data.length === 0) {
  19847. dom.remove(node);
  19848. }
  19849. };
  19850. const deleteContentAndShowCaret = (editor, range, node, direction, forward, peekCaretPosition) => {
  19851. showCaret(direction, editor, peekCaretPosition.getNode(!forward), forward, true).each(caretRange => {
  19852. if (range.collapsed) {
  19853. const deleteRange = range.cloneRange();
  19854. if (forward) {
  19855. deleteRange.setEnd(caretRange.startContainer, caretRange.startOffset);
  19856. } else {
  19857. deleteRange.setStart(caretRange.endContainer, caretRange.endOffset);
  19858. }
  19859. deleteRange.deleteContents();
  19860. } else {
  19861. range.deleteContents();
  19862. }
  19863. editor.selection.setRng(caretRange);
  19864. });
  19865. trimEmptyTextNode(editor.dom, node);
  19866. };
  19867. const deleteBoundaryText = (editor, forward) => {
  19868. const range = editor.selection.getRng();
  19869. if (!isText$9(range.commonAncestorContainer)) {
  19870. return Optional.none();
  19871. }
  19872. const direction = forward ? HDirection.Forwards : HDirection.Backwards;
  19873. const caretWalker = CaretWalker(editor.getBody());
  19874. const getNextPosFn = curry(getVisualCaretPosition, forward ? caretWalker.next : caretWalker.prev);
  19875. const isBeforeFn = forward ? isBeforeBoundary : isAfterBoundary;
  19876. const caretPosition = getNormalizedRangeEndPoint(direction, editor.getBody(), range);
  19877. const nextCaretPosition = normalizePosition(forward, getNextPosFn(caretPosition));
  19878. if (!nextCaretPosition || !isMoveInsideSameBlock(caretPosition, nextCaretPosition)) {
  19879. return Optional.none();
  19880. } else if (isBeforeFn(nextCaretPosition)) {
  19881. return Optional.some(() => deleteContentAndShowCaret(editor, range, caretPosition.getNode(), direction, forward, nextCaretPosition));
  19882. }
  19883. const peekCaretPosition = getNextPosFn(nextCaretPosition);
  19884. if (peekCaretPosition && isBeforeFn(peekCaretPosition)) {
  19885. if (isMoveInsideSameBlock(nextCaretPosition, peekCaretPosition)) {
  19886. return Optional.some(() => deleteContentAndShowCaret(editor, range, caretPosition.getNode(), direction, forward, peekCaretPosition));
  19887. }
  19888. }
  19889. return Optional.none();
  19890. };
  19891. const backspaceDelete$6 = (editor, forward) => deleteBoundaryText(editor, forward);
  19892. const getEdgeCefPosition = (editor, atStart) => {
  19893. const root = editor.getBody();
  19894. return atStart ? firstPositionIn(root).filter(isBeforeContentEditableFalse) : lastPositionIn(root).filter(isAfterContentEditableFalse);
  19895. };
  19896. const isCefAtEdgeSelected = editor => {
  19897. const rng = editor.selection.getRng();
  19898. return !rng.collapsed && (getEdgeCefPosition(editor, true).exists(pos => pos.isEqual(CaretPosition.fromRangeStart(rng))) || getEdgeCefPosition(editor, false).exists(pos => pos.isEqual(CaretPosition.fromRangeEnd(rng))));
  19899. };
  19900. const isCompoundElement = node => isTableCell$4(SugarElement.fromDom(node)) || isListItem(SugarElement.fromDom(node));
  19901. const DeleteAction = Adt.generate([
  19902. { remove: ['element'] },
  19903. { moveToElement: ['element'] },
  19904. { moveToPosition: ['position'] }
  19905. ]);
  19906. const isAtContentEditableBlockCaret = (forward, from) => {
  19907. const elm = from.getNode(forward === false);
  19908. const caretLocation = forward ? 'after' : 'before';
  19909. return isElement$6(elm) && elm.getAttribute('data-mce-caret') === caretLocation;
  19910. };
  19911. const isDeleteFromCefDifferentBlocks = (root, forward, from, to) => {
  19912. const inSameBlock = elm => isInline$1(SugarElement.fromDom(elm)) && !isInSameBlock(from, to, root);
  19913. return getRelativeCefElm(!forward, from).fold(() => getRelativeCefElm(forward, to).fold(never, inSameBlock), inSameBlock);
  19914. };
  19915. const deleteEmptyBlockOrMoveToCef = (root, forward, from, to) => {
  19916. const toCefElm = to.getNode(forward === false);
  19917. 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)));
  19918. };
  19919. const findCefPosition = (root, forward, from) => fromPosition(forward, root, from).bind(to => {
  19920. if (isCompoundElement(to.getNode())) {
  19921. return Optional.none();
  19922. } else if (isDeleteFromCefDifferentBlocks(root, forward, from, to)) {
  19923. return Optional.none();
  19924. } else if (forward && isContentEditableFalse$b(to.getNode())) {
  19925. return deleteEmptyBlockOrMoveToCef(root, forward, from, to);
  19926. } else if (forward === false && isContentEditableFalse$b(to.getNode(true))) {
  19927. return deleteEmptyBlockOrMoveToCef(root, forward, from, to);
  19928. } else if (forward && isAfterContentEditableFalse(from)) {
  19929. return Optional.some(DeleteAction.moveToPosition(to));
  19930. } else if (forward === false && isBeforeContentEditableFalse(from)) {
  19931. return Optional.some(DeleteAction.moveToPosition(to));
  19932. } else {
  19933. return Optional.none();
  19934. }
  19935. });
  19936. const getContentEditableBlockAction = (forward, elm) => {
  19937. if (forward && isContentEditableFalse$b(elm.nextSibling)) {
  19938. return Optional.some(DeleteAction.moveToElement(elm.nextSibling));
  19939. } else if (forward === false && isContentEditableFalse$b(elm.previousSibling)) {
  19940. return Optional.some(DeleteAction.moveToElement(elm.previousSibling));
  19941. } else {
  19942. return Optional.none();
  19943. }
  19944. };
  19945. const skipMoveToActionFromInlineCefToContent = (root, from, deleteAction) => deleteAction.fold(elm => Optional.some(DeleteAction.remove(elm)), elm => Optional.some(DeleteAction.moveToElement(elm)), to => {
  19946. if (isInSameBlock(from, to, root)) {
  19947. return Optional.none();
  19948. } else {
  19949. return Optional.some(DeleteAction.moveToPosition(to));
  19950. }
  19951. });
  19952. const getContentEditableAction = (root, forward, from) => {
  19953. if (isAtContentEditableBlockCaret(forward, from)) {
  19954. return getContentEditableBlockAction(forward, from.getNode(forward === false)).fold(() => findCefPosition(root, forward, from), Optional.some);
  19955. } else {
  19956. return findCefPosition(root, forward, from).bind(deleteAction => skipMoveToActionFromInlineCefToContent(root, from, deleteAction));
  19957. }
  19958. };
  19959. const read = (root, forward, rng) => {
  19960. const normalizedRange = normalizeRange(forward ? 1 : -1, root, rng);
  19961. const from = CaretPosition.fromRangeStart(normalizedRange);
  19962. const rootElement = SugarElement.fromDom(root);
  19963. if (forward === false && isAfterContentEditableFalse(from)) {
  19964. return Optional.some(DeleteAction.remove(from.getNode(true)));
  19965. } else if (forward && isBeforeContentEditableFalse(from)) {
  19966. return Optional.some(DeleteAction.remove(from.getNode()));
  19967. } else if (forward === false && isBeforeContentEditableFalse(from) && isAfterBr(rootElement, from)) {
  19968. return findPreviousBr(rootElement, from).map(br => DeleteAction.remove(br.getNode()));
  19969. } else if (forward && isAfterContentEditableFalse(from) && isBeforeBr$1(rootElement, from)) {
  19970. return findNextBr(rootElement, from).map(br => DeleteAction.remove(br.getNode()));
  19971. } else {
  19972. return getContentEditableAction(root, forward, from);
  19973. }
  19974. };
  19975. const deleteElement$1 = (editor, forward) => element => {
  19976. editor._selectionOverrides.hideFakeCaret();
  19977. deleteElement$2(editor, forward, SugarElement.fromDom(element));
  19978. return true;
  19979. };
  19980. const moveToElement = (editor, forward) => element => {
  19981. const pos = forward ? CaretPosition.before(element) : CaretPosition.after(element);
  19982. editor.selection.setRng(pos.toRange());
  19983. return true;
  19984. };
  19985. const moveToPosition = editor => pos => {
  19986. editor.selection.setRng(pos.toRange());
  19987. return true;
  19988. };
  19989. const getAncestorCe = (editor, node) => Optional.from(getContentEditableRoot$1(editor.getBody(), node));
  19990. const backspaceDeleteCaret = (editor, forward) => {
  19991. const selectedNode = editor.selection.getNode();
  19992. return getAncestorCe(editor, selectedNode).filter(isContentEditableFalse$b).fold(() => read(editor.getBody(), forward, editor.selection.getRng()).map(deleteAction => () => deleteAction.fold(deleteElement$1(editor, forward), moveToElement(editor, forward), moveToPosition(editor))), () => Optional.some(noop));
  19993. };
  19994. const deleteOffscreenSelection = rootElement => {
  19995. each$f(descendants(rootElement, '.mce-offscreen-selection'), remove$6);
  19996. };
  19997. const backspaceDeleteRange = (editor, forward) => {
  19998. const selectedNode = editor.selection.getNode();
  19999. if (isContentEditableFalse$b(selectedNode) && !isTableCell$5(selectedNode)) {
  20000. const hasCefAncestor = getAncestorCe(editor, selectedNode.parentNode).filter(isContentEditableFalse$b);
  20001. return hasCefAncestor.fold(() => Optional.some(() => {
  20002. deleteOffscreenSelection(SugarElement.fromDom(editor.getBody()));
  20003. deleteElement$2(editor, forward, SugarElement.fromDom(editor.selection.getNode()));
  20004. paddEmptyBody(editor);
  20005. }), () => Optional.some(noop));
  20006. }
  20007. if (isCefAtEdgeSelected(editor)) {
  20008. return Optional.some(() => {
  20009. deleteRangeContents(editor, editor.selection.getRng(), SugarElement.fromDom(editor.getBody()));
  20010. });
  20011. }
  20012. return Optional.none();
  20013. };
  20014. const paddEmptyElement = editor => {
  20015. const dom = editor.dom, selection = editor.selection;
  20016. const ceRoot = getContentEditableRoot$1(editor.getBody(), selection.getNode());
  20017. if (isContentEditableTrue$5(ceRoot) && dom.isBlock(ceRoot) && dom.isEmpty(ceRoot)) {
  20018. const br = dom.create('br', { 'data-mce-bogus': '1' });
  20019. dom.setHTML(ceRoot, '');
  20020. ceRoot.appendChild(br);
  20021. selection.setRng(CaretPosition.before(br).toRange());
  20022. }
  20023. return true;
  20024. };
  20025. const backspaceDelete$5 = (editor, forward) => {
  20026. if (editor.selection.isCollapsed()) {
  20027. return backspaceDeleteCaret(editor, forward);
  20028. } else {
  20029. return backspaceDeleteRange(editor, forward);
  20030. }
  20031. };
  20032. const deleteCaret$2 = (editor, forward) => {
  20033. const fromPos = CaretPosition.fromRangeStart(editor.selection.getRng());
  20034. 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));
  20035. };
  20036. const backspaceDelete$4 = (editor, forward) => editor.selection.isCollapsed() ? deleteCaret$2(editor, forward) : Optional.none();
  20037. const isText$2 = isText$9;
  20038. const startsWithCaretContainer = node => isText$2(node) && node.data[0] === ZWSP$1;
  20039. const endsWithCaretContainer = node => isText$2(node) && node.data[node.data.length - 1] === ZWSP$1;
  20040. const createZwsp = node => node.ownerDocument.createTextNode(ZWSP$1);
  20041. const insertBefore = node => {
  20042. if (isText$2(node.previousSibling)) {
  20043. if (endsWithCaretContainer(node.previousSibling)) {
  20044. return node.previousSibling;
  20045. } else {
  20046. node.previousSibling.appendData(ZWSP$1);
  20047. return node.previousSibling;
  20048. }
  20049. } else if (isText$2(node)) {
  20050. if (startsWithCaretContainer(node)) {
  20051. return node;
  20052. } else {
  20053. node.insertData(0, ZWSP$1);
  20054. return node;
  20055. }
  20056. } else {
  20057. const newNode = createZwsp(node);
  20058. node.parentNode.insertBefore(newNode, node);
  20059. return newNode;
  20060. }
  20061. };
  20062. const insertAfter = node => {
  20063. if (isText$2(node.nextSibling)) {
  20064. if (startsWithCaretContainer(node.nextSibling)) {
  20065. return node.nextSibling;
  20066. } else {
  20067. node.nextSibling.insertData(0, ZWSP$1);
  20068. return node.nextSibling;
  20069. }
  20070. } else if (isText$2(node)) {
  20071. if (endsWithCaretContainer(node)) {
  20072. return node;
  20073. } else {
  20074. node.appendData(ZWSP$1);
  20075. return node;
  20076. }
  20077. } else {
  20078. const newNode = createZwsp(node);
  20079. if (node.nextSibling) {
  20080. node.parentNode.insertBefore(newNode, node.nextSibling);
  20081. } else {
  20082. node.parentNode.appendChild(newNode);
  20083. }
  20084. return newNode;
  20085. }
  20086. };
  20087. const insertInline = (before, node) => before ? insertBefore(node) : insertAfter(node);
  20088. const insertInlineBefore = curry(insertInline, true);
  20089. const insertInlineAfter = curry(insertInline, false);
  20090. const insertInlinePos = (pos, before) => {
  20091. if (isText$9(pos.container())) {
  20092. return insertInline(before, pos.container());
  20093. } else {
  20094. return insertInline(before, pos.getNode());
  20095. }
  20096. };
  20097. const isPosCaretContainer = (pos, caret) => {
  20098. const caretNode = caret.get();
  20099. return caretNode && pos.container() === caretNode && isCaretContainerInline(caretNode);
  20100. };
  20101. const renderCaret = (caret, location) => location.fold(element => {
  20102. remove$4(caret.get());
  20103. const text = insertInlineBefore(element);
  20104. caret.set(text);
  20105. return Optional.some(CaretPosition(text, text.length - 1));
  20106. }, element => firstPositionIn(element).map(pos => {
  20107. if (!isPosCaretContainer(pos, caret)) {
  20108. remove$4(caret.get());
  20109. const text = insertInlinePos(pos, true);
  20110. caret.set(text);
  20111. return CaretPosition(text, 1);
  20112. } else {
  20113. return CaretPosition(caret.get(), 1);
  20114. }
  20115. }), element => lastPositionIn(element).map(pos => {
  20116. if (!isPosCaretContainer(pos, caret)) {
  20117. remove$4(caret.get());
  20118. const text = insertInlinePos(pos, false);
  20119. caret.set(text);
  20120. return CaretPosition(text, text.length - 1);
  20121. } else {
  20122. return CaretPosition(caret.get(), caret.get().length - 1);
  20123. }
  20124. }), element => {
  20125. remove$4(caret.get());
  20126. const text = insertInlineAfter(element);
  20127. caret.set(text);
  20128. return Optional.some(CaretPosition(text, 1));
  20129. });
  20130. const evaluateUntil = (fns, args) => {
  20131. for (let i = 0; i < fns.length; i++) {
  20132. const result = fns[i].apply(null, args);
  20133. if (result.isSome()) {
  20134. return result;
  20135. }
  20136. }
  20137. return Optional.none();
  20138. };
  20139. const Location = Adt.generate([
  20140. { before: ['element'] },
  20141. { start: ['element'] },
  20142. { end: ['element'] },
  20143. { after: ['element'] }
  20144. ]);
  20145. const rescope$1 = (rootNode, node) => {
  20146. const parentBlock = getParentBlock$3(node, rootNode);
  20147. return parentBlock ? parentBlock : rootNode;
  20148. };
  20149. const before = (isInlineTarget, rootNode, pos) => {
  20150. const nPos = normalizeForwards(pos);
  20151. const scope = rescope$1(rootNode, nPos.container());
  20152. return findRootInline(isInlineTarget, scope, nPos).fold(() => nextPosition(scope, nPos).bind(curry(findRootInline, isInlineTarget, scope)).map(inline => Location.before(inline)), Optional.none);
  20153. };
  20154. const isNotInsideFormatCaretContainer = (rootNode, elm) => getParentCaretContainer(rootNode, elm) === null;
  20155. const findInsideRootInline = (isInlineTarget, rootNode, pos) => findRootInline(isInlineTarget, rootNode, pos).filter(curry(isNotInsideFormatCaretContainer, rootNode));
  20156. const start$1 = (isInlineTarget, rootNode, pos) => {
  20157. const nPos = normalizeBackwards(pos);
  20158. return findInsideRootInline(isInlineTarget, rootNode, nPos).bind(inline => {
  20159. const prevPos = prevPosition(inline, nPos);
  20160. return prevPos.isNone() ? Optional.some(Location.start(inline)) : Optional.none();
  20161. });
  20162. };
  20163. const end = (isInlineTarget, rootNode, pos) => {
  20164. const nPos = normalizeForwards(pos);
  20165. return findInsideRootInline(isInlineTarget, rootNode, nPos).bind(inline => {
  20166. const nextPos = nextPosition(inline, nPos);
  20167. return nextPos.isNone() ? Optional.some(Location.end(inline)) : Optional.none();
  20168. });
  20169. };
  20170. const after = (isInlineTarget, rootNode, pos) => {
  20171. const nPos = normalizeBackwards(pos);
  20172. const scope = rescope$1(rootNode, nPos.container());
  20173. return findRootInline(isInlineTarget, scope, nPos).fold(() => prevPosition(scope, nPos).bind(curry(findRootInline, isInlineTarget, scope)).map(inline => Location.after(inline)), Optional.none);
  20174. };
  20175. const isValidLocation = location => isRtl(getElement(location)) === false;
  20176. const readLocation = (isInlineTarget, rootNode, pos) => {
  20177. const location = evaluateUntil([
  20178. before,
  20179. start$1,
  20180. end,
  20181. after
  20182. ], [
  20183. isInlineTarget,
  20184. rootNode,
  20185. pos
  20186. ]);
  20187. return location.filter(isValidLocation);
  20188. };
  20189. const getElement = location => location.fold(identity, identity, identity, identity);
  20190. const getName = location => location.fold(constant('before'), constant('start'), constant('end'), constant('after'));
  20191. const outside = location => location.fold(Location.before, Location.before, Location.after, Location.after);
  20192. const inside = location => location.fold(Location.start, Location.start, Location.end, Location.end);
  20193. const isEq = (location1, location2) => getName(location1) === getName(location2) && getElement(location1) === getElement(location2);
  20194. const betweenInlines = (forward, isInlineTarget, rootNode, from, to, location) => lift2(findRootInline(isInlineTarget, rootNode, from), findRootInline(isInlineTarget, rootNode, to), (fromInline, toInline) => {
  20195. if (fromInline !== toInline && hasSameParentBlock(rootNode, fromInline, toInline)) {
  20196. return Location.after(forward ? fromInline : toInline);
  20197. } else {
  20198. return location;
  20199. }
  20200. }).getOr(location);
  20201. const skipNoMovement = (fromLocation, toLocation) => fromLocation.fold(always, fromLocation => !isEq(fromLocation, toLocation));
  20202. const findLocationTraverse = (forward, isInlineTarget, rootNode, fromLocation, pos) => {
  20203. const from = normalizePosition(forward, pos);
  20204. const to = fromPosition(forward, rootNode, from).map(curry(normalizePosition, forward));
  20205. const location = to.fold(() => fromLocation.map(outside), to => readLocation(isInlineTarget, rootNode, to).map(curry(betweenInlines, forward, isInlineTarget, rootNode, from, to)).filter(curry(skipNoMovement, fromLocation)));
  20206. return location.filter(isValidLocation);
  20207. };
  20208. const findLocationSimple = (forward, location) => {
  20209. if (forward) {
  20210. return location.fold(compose(Optional.some, Location.start), Optional.none, compose(Optional.some, Location.after), Optional.none);
  20211. } else {
  20212. return location.fold(Optional.none, compose(Optional.some, Location.before), Optional.none, compose(Optional.some, Location.end));
  20213. }
  20214. };
  20215. const findLocation$1 = (forward, isInlineTarget, rootNode, pos) => {
  20216. const from = normalizePosition(forward, pos);
  20217. const fromLocation = readLocation(isInlineTarget, rootNode, from);
  20218. return readLocation(isInlineTarget, rootNode, from).bind(curry(findLocationSimple, forward)).orThunk(() => findLocationTraverse(forward, isInlineTarget, rootNode, fromLocation, pos));
  20219. };
  20220. const hasSelectionModifyApi = editor => {
  20221. return isFunction(editor.selection.getSel().modify);
  20222. };
  20223. const moveRel = (forward, selection, pos) => {
  20224. const delta = forward ? 1 : -1;
  20225. selection.setRng(CaretPosition(pos.container(), pos.offset() + delta).toRange());
  20226. selection.getSel().modify('move', forward ? 'forward' : 'backward', 'word');
  20227. return true;
  20228. };
  20229. const moveByWord = (forward, editor) => {
  20230. const rng = editor.selection.getRng();
  20231. const pos = forward ? CaretPosition.fromRangeEnd(rng) : CaretPosition.fromRangeStart(rng);
  20232. if (!hasSelectionModifyApi(editor)) {
  20233. return false;
  20234. } else if (forward && isBeforeInline(pos)) {
  20235. return moveRel(true, editor.selection, pos);
  20236. } else if (!forward && isAfterInline(pos)) {
  20237. return moveRel(false, editor.selection, pos);
  20238. } else {
  20239. return false;
  20240. }
  20241. };
  20242. var BreakType;
  20243. (function (BreakType) {
  20244. BreakType[BreakType['Br'] = 0] = 'Br';
  20245. BreakType[BreakType['Block'] = 1] = 'Block';
  20246. BreakType[BreakType['Wrap'] = 2] = 'Wrap';
  20247. BreakType[BreakType['Eol'] = 3] = 'Eol';
  20248. }(BreakType || (BreakType = {})));
  20249. const flip = (direction, positions) => direction === HDirection.Backwards ? reverse(positions) : positions;
  20250. const walk$1 = (direction, caretWalker, pos) => direction === HDirection.Forwards ? caretWalker.next(pos) : caretWalker.prev(pos);
  20251. const getBreakType = (scope, direction, currentPos, nextPos) => {
  20252. if (isBr$6(nextPos.getNode(direction === HDirection.Forwards))) {
  20253. return BreakType.Br;
  20254. } else if (isInSameBlock(currentPos, nextPos) === false) {
  20255. return BreakType.Block;
  20256. } else {
  20257. return BreakType.Wrap;
  20258. }
  20259. };
  20260. const getPositionsUntil = (predicate, direction, scope, start) => {
  20261. const caretWalker = CaretWalker(scope);
  20262. let currentPos = start;
  20263. const positions = [];
  20264. while (currentPos) {
  20265. const nextPos = walk$1(direction, caretWalker, currentPos);
  20266. if (!nextPos) {
  20267. break;
  20268. }
  20269. if (isBr$6(nextPos.getNode(false))) {
  20270. if (direction === HDirection.Forwards) {
  20271. return {
  20272. positions: flip(direction, positions).concat([nextPos]),
  20273. breakType: BreakType.Br,
  20274. breakAt: Optional.some(nextPos)
  20275. };
  20276. } else {
  20277. return {
  20278. positions: flip(direction, positions),
  20279. breakType: BreakType.Br,
  20280. breakAt: Optional.some(nextPos)
  20281. };
  20282. }
  20283. }
  20284. if (!nextPos.isVisible()) {
  20285. currentPos = nextPos;
  20286. continue;
  20287. }
  20288. if (predicate(currentPos, nextPos)) {
  20289. const breakType = getBreakType(scope, direction, currentPos, nextPos);
  20290. return {
  20291. positions: flip(direction, positions),
  20292. breakType,
  20293. breakAt: Optional.some(nextPos)
  20294. };
  20295. }
  20296. positions.push(nextPos);
  20297. currentPos = nextPos;
  20298. }
  20299. return {
  20300. positions: flip(direction, positions),
  20301. breakType: BreakType.Eol,
  20302. breakAt: Optional.none()
  20303. };
  20304. };
  20305. const getAdjacentLinePositions = (direction, getPositionsUntilBreak, scope, start) => getPositionsUntilBreak(scope, start).breakAt.map(pos => {
  20306. const positions = getPositionsUntilBreak(scope, pos).positions;
  20307. return direction === HDirection.Backwards ? positions.concat(pos) : [pos].concat(positions);
  20308. }).getOr([]);
  20309. const findClosestHorizontalPositionFromPoint = (positions, x) => foldl(positions, (acc, newPos) => acc.fold(() => Optional.some(newPos), lastPos => lift2(head(lastPos.getClientRects()), head(newPos.getClientRects()), (lastRect, newRect) => {
  20310. const lastDist = Math.abs(x - lastRect.left);
  20311. const newDist = Math.abs(x - newRect.left);
  20312. return newDist <= lastDist ? newPos : lastPos;
  20313. }).or(acc)), Optional.none());
  20314. const findClosestHorizontalPosition = (positions, pos) => head(pos.getClientRects()).bind(targetRect => findClosestHorizontalPositionFromPoint(positions, targetRect.left));
  20315. const getPositionsUntilPreviousLine = curry(getPositionsUntil, CaretPosition.isAbove, -1);
  20316. const getPositionsUntilNextLine = curry(getPositionsUntil, CaretPosition.isBelow, 1);
  20317. const getPositionsAbove = curry(getAdjacentLinePositions, -1, getPositionsUntilPreviousLine);
  20318. const getPositionsBelow = curry(getAdjacentLinePositions, 1, getPositionsUntilNextLine);
  20319. const isAtFirstLine = (scope, pos) => getPositionsUntilPreviousLine(scope, pos).breakAt.isNone();
  20320. const isAtLastLine = (scope, pos) => getPositionsUntilNextLine(scope, pos).breakAt.isNone();
  20321. const getFirstLinePositions = scope => firstPositionIn(scope).map(pos => [pos].concat(getPositionsUntilNextLine(scope, pos).positions)).getOr([]);
  20322. const getLastLinePositions = scope => lastPositionIn(scope).map(pos => getPositionsUntilPreviousLine(scope, pos).positions.concat(pos)).getOr([]);
  20323. const getClosestPositionAbove = (scope, pos) => findClosestHorizontalPosition(getPositionsAbove(scope, pos), pos);
  20324. const getClosestPositionBelow = (scope, pos) => findClosestHorizontalPosition(getPositionsBelow(scope, pos), pos);
  20325. const isContentEditableFalse$4 = isContentEditableFalse$b;
  20326. const distanceToRectLeft$1 = (clientRect, clientX) => Math.abs(clientRect.left - clientX);
  20327. const distanceToRectRight$1 = (clientRect, clientX) => Math.abs(clientRect.right - clientX);
  20328. const isNodeClientRect = rect => hasNonNullableKey(rect, 'node');
  20329. const findClosestClientRect = (clientRects, clientX) => reduce(clientRects, (oldClientRect, clientRect) => {
  20330. const oldDistance = Math.min(distanceToRectLeft$1(oldClientRect, clientX), distanceToRectRight$1(oldClientRect, clientX));
  20331. const newDistance = Math.min(distanceToRectLeft$1(clientRect, clientX), distanceToRectRight$1(clientRect, clientX));
  20332. if (newDistance === oldDistance && isNodeClientRect(clientRect) && isContentEditableFalse$4(clientRect.node)) {
  20333. return clientRect;
  20334. }
  20335. if (newDistance < oldDistance) {
  20336. return clientRect;
  20337. }
  20338. return oldClientRect;
  20339. });
  20340. const getNodeClientRects = node => {
  20341. const toArrayWithNode = clientRects => {
  20342. return map$3(clientRects, rect => {
  20343. const clientRect = clone$1(rect);
  20344. clientRect.node = node;
  20345. return clientRect;
  20346. });
  20347. };
  20348. if (isElement$6(node)) {
  20349. return toArrayWithNode(node.getClientRects());
  20350. } else if (isText$9(node)) {
  20351. const rng = node.ownerDocument.createRange();
  20352. rng.setStart(node, 0);
  20353. rng.setEnd(node, node.data.length);
  20354. return toArrayWithNode(rng.getClientRects());
  20355. } else {
  20356. return [];
  20357. }
  20358. };
  20359. const getClientRects = nodes => bind$3(nodes, getNodeClientRects);
  20360. var VDirection;
  20361. (function (VDirection) {
  20362. VDirection[VDirection['Up'] = -1] = 'Up';
  20363. VDirection[VDirection['Down'] = 1] = 'Down';
  20364. }(VDirection || (VDirection = {})));
  20365. const findUntil = (direction, root, predicateFn, node) => {
  20366. while (node = findNode(node, direction, isEditableCaretCandidate$1, root)) {
  20367. if (predicateFn(node)) {
  20368. return;
  20369. }
  20370. }
  20371. };
  20372. const walkUntil = (direction, isAboveFn, isBeflowFn, root, predicateFn, caretPosition) => {
  20373. let line = 0;
  20374. const result = [];
  20375. const add = node => {
  20376. let clientRects = getClientRects([node]);
  20377. if (direction === -1) {
  20378. clientRects = clientRects.reverse();
  20379. }
  20380. for (let i = 0; i < clientRects.length; i++) {
  20381. const clientRect = clientRects[i];
  20382. if (isBeflowFn(clientRect, targetClientRect)) {
  20383. continue;
  20384. }
  20385. if (result.length > 0 && isAboveFn(clientRect, last$2(result))) {
  20386. line++;
  20387. }
  20388. clientRect.line = line;
  20389. if (predicateFn(clientRect)) {
  20390. return true;
  20391. }
  20392. result.push(clientRect);
  20393. }
  20394. };
  20395. const targetClientRect = last$2(caretPosition.getClientRects());
  20396. if (!targetClientRect) {
  20397. return result;
  20398. }
  20399. const node = caretPosition.getNode();
  20400. add(node);
  20401. findUntil(direction, root, add, node);
  20402. return result;
  20403. };
  20404. const aboveLineNumber = (lineNumber, clientRect) => clientRect.line > lineNumber;
  20405. const isLineNumber = (lineNumber, clientRect) => clientRect.line === lineNumber;
  20406. const upUntil = curry(walkUntil, VDirection.Up, isAbove$1, isBelow$1);
  20407. const downUntil = curry(walkUntil, VDirection.Down, isBelow$1, isAbove$1);
  20408. const positionsUntil = (direction, root, predicateFn, node) => {
  20409. const caretWalker = CaretWalker(root);
  20410. let walkFn;
  20411. let isBelowFn;
  20412. let isAboveFn;
  20413. let caretPosition;
  20414. const result = [];
  20415. let line = 0;
  20416. const getClientRect = caretPosition => {
  20417. if (direction === 1) {
  20418. return last$2(caretPosition.getClientRects());
  20419. }
  20420. return last$2(caretPosition.getClientRects());
  20421. };
  20422. if (direction === 1) {
  20423. walkFn = caretWalker.next;
  20424. isBelowFn = isBelow$1;
  20425. isAboveFn = isAbove$1;
  20426. caretPosition = CaretPosition.after(node);
  20427. } else {
  20428. walkFn = caretWalker.prev;
  20429. isBelowFn = isAbove$1;
  20430. isAboveFn = isBelow$1;
  20431. caretPosition = CaretPosition.before(node);
  20432. }
  20433. const targetClientRect = getClientRect(caretPosition);
  20434. do {
  20435. if (!caretPosition.isVisible()) {
  20436. continue;
  20437. }
  20438. const rect = getClientRect(caretPosition);
  20439. if (isAboveFn(rect, targetClientRect)) {
  20440. continue;
  20441. }
  20442. if (result.length > 0 && isBelowFn(rect, last$2(result))) {
  20443. line++;
  20444. }
  20445. const clientRect = clone$1(rect);
  20446. clientRect.position = caretPosition;
  20447. clientRect.line = line;
  20448. if (predicateFn(clientRect)) {
  20449. return result;
  20450. }
  20451. result.push(clientRect);
  20452. } while (caretPosition = walkFn(caretPosition));
  20453. return result;
  20454. };
  20455. const isAboveLine = lineNumber => clientRect => aboveLineNumber(lineNumber, clientRect);
  20456. const isLine = lineNumber => clientRect => isLineNumber(lineNumber, clientRect);
  20457. const moveToRange = (editor, rng) => {
  20458. editor.selection.setRng(rng);
  20459. scrollRangeIntoView(editor, editor.selection.getRng());
  20460. };
  20461. const renderRangeCaretOpt = (editor, range, scrollIntoView) => Optional.some(renderRangeCaret(editor, range, scrollIntoView));
  20462. const moveHorizontally = (editor, direction, range, isBefore, isAfter, isElement) => {
  20463. const forwards = direction === HDirection.Forwards;
  20464. const caretWalker = CaretWalker(editor.getBody());
  20465. const getNextPosFn = curry(getVisualCaretPosition, forwards ? caretWalker.next : caretWalker.prev);
  20466. const isBeforeFn = forwards ? isBefore : isAfter;
  20467. if (!range.collapsed) {
  20468. const node = getSelectedNode(range);
  20469. if (isElement(node)) {
  20470. return showCaret(direction, editor, node, direction === HDirection.Backwards, false);
  20471. } else if (isCefAtEdgeSelected(editor)) {
  20472. const newRange = range.cloneRange();
  20473. newRange.collapse(direction === HDirection.Backwards);
  20474. return Optional.from(newRange);
  20475. }
  20476. }
  20477. const caretPosition = getNormalizedRangeEndPoint(direction, editor.getBody(), range);
  20478. if (isBeforeFn(caretPosition)) {
  20479. return selectNode(editor, caretPosition.getNode(!forwards));
  20480. }
  20481. const nextCaretPosition = normalizePosition(forwards, getNextPosFn(caretPosition));
  20482. const rangeIsInContainerBlock = isRangeInCaretContainerBlock(range);
  20483. if (!nextCaretPosition) {
  20484. return rangeIsInContainerBlock ? Optional.some(range) : Optional.none();
  20485. }
  20486. if (isBeforeFn(nextCaretPosition)) {
  20487. return showCaret(direction, editor, nextCaretPosition.getNode(!forwards), forwards, false);
  20488. }
  20489. const peekCaretPosition = getNextPosFn(nextCaretPosition);
  20490. if (peekCaretPosition && isBeforeFn(peekCaretPosition)) {
  20491. if (isMoveInsideSameBlock(nextCaretPosition, peekCaretPosition)) {
  20492. return showCaret(direction, editor, peekCaretPosition.getNode(!forwards), forwards, false);
  20493. }
  20494. }
  20495. if (rangeIsInContainerBlock) {
  20496. return renderRangeCaretOpt(editor, nextCaretPosition.toRange(), false);
  20497. }
  20498. return Optional.none();
  20499. };
  20500. const moveVertically = (editor, direction, range, isBefore, isAfter, isElement) => {
  20501. const caretPosition = getNormalizedRangeEndPoint(direction, editor.getBody(), range);
  20502. const caretClientRect = last$2(caretPosition.getClientRects());
  20503. const forwards = direction === VDirection.Down;
  20504. const root = editor.getBody();
  20505. if (!caretClientRect) {
  20506. return Optional.none();
  20507. }
  20508. if (isCefAtEdgeSelected(editor)) {
  20509. const caretPosition = forwards ? CaretPosition.fromRangeEnd(range) : CaretPosition.fromRangeStart(range);
  20510. const getClosestFn = !forwards ? getClosestPositionAbove : getClosestPositionBelow;
  20511. return getClosestFn(root, caretPosition).orThunk(() => Optional.from(caretPosition)).map(pos => pos.toRange());
  20512. }
  20513. const walkerFn = forwards ? downUntil : upUntil;
  20514. const linePositions = walkerFn(root, isAboveLine(1), caretPosition);
  20515. const nextLinePositions = filter$6(linePositions, isLine(1));
  20516. const clientX = caretClientRect.left;
  20517. const nextLineRect = findClosestClientRect(nextLinePositions, clientX);
  20518. if (nextLineRect && isElement(nextLineRect.node)) {
  20519. const dist1 = Math.abs(clientX - nextLineRect.left);
  20520. const dist2 = Math.abs(clientX - nextLineRect.right);
  20521. return showCaret(direction, editor, nextLineRect.node, dist1 < dist2, false);
  20522. }
  20523. let currentNode;
  20524. if (isBefore(caretPosition)) {
  20525. currentNode = caretPosition.getNode();
  20526. } else if (isAfter(caretPosition)) {
  20527. currentNode = caretPosition.getNode(true);
  20528. } else {
  20529. currentNode = getSelectedNode(range);
  20530. }
  20531. if (currentNode) {
  20532. const caretPositions = positionsUntil(direction, root, isAboveLine(1), currentNode);
  20533. let closestNextLineRect = findClosestClientRect(filter$6(caretPositions, isLine(1)), clientX);
  20534. if (closestNextLineRect) {
  20535. return renderRangeCaretOpt(editor, closestNextLineRect.position.toRange(), false);
  20536. }
  20537. closestNextLineRect = last$2(filter$6(caretPositions, isLine(0)));
  20538. if (closestNextLineRect) {
  20539. return renderRangeCaretOpt(editor, closestNextLineRect.position.toRange(), false);
  20540. }
  20541. }
  20542. if (nextLinePositions.length === 0) {
  20543. return getLineEndPoint(editor, forwards).filter(forwards ? isAfter : isBefore).map(pos => renderRangeCaret(editor, pos.toRange(), false));
  20544. }
  20545. return Optional.none();
  20546. };
  20547. const getLineEndPoint = (editor, forward) => {
  20548. const rng = editor.selection.getRng();
  20549. const from = forward ? CaretPosition.fromRangeEnd(rng) : CaretPosition.fromRangeStart(rng);
  20550. const host = getEditingHost(from.container(), editor.getBody());
  20551. if (forward) {
  20552. const lineInfo = getPositionsUntilNextLine(host, from);
  20553. return last$3(lineInfo.positions);
  20554. } else {
  20555. const lineInfo = getPositionsUntilPreviousLine(host, from);
  20556. return head(lineInfo.positions);
  20557. }
  20558. };
  20559. const moveToLineEndPoint$3 = (editor, forward, isElementPosition) => getLineEndPoint(editor, forward).filter(isElementPosition).exists(pos => {
  20560. editor.selection.setRng(pos.toRange());
  20561. return true;
  20562. });
  20563. const setCaretPosition = (editor, pos) => {
  20564. const rng = editor.dom.createRng();
  20565. rng.setStart(pos.container(), pos.offset());
  20566. rng.setEnd(pos.container(), pos.offset());
  20567. editor.selection.setRng(rng);
  20568. };
  20569. const setSelected = (state, elm) => {
  20570. if (state) {
  20571. elm.setAttribute('data-mce-selected', 'inline-boundary');
  20572. } else {
  20573. elm.removeAttribute('data-mce-selected');
  20574. }
  20575. };
  20576. const renderCaretLocation = (editor, caret, location) => renderCaret(caret, location).map(pos => {
  20577. setCaretPosition(editor, pos);
  20578. return location;
  20579. });
  20580. const getPositionFromRange = (range, root, forward) => {
  20581. const start = CaretPosition.fromRangeStart(range);
  20582. if (range.collapsed) {
  20583. return start;
  20584. } else {
  20585. const end = CaretPosition.fromRangeEnd(range);
  20586. return forward ? prevPosition(root, end).getOr(end) : nextPosition(root, start).getOr(start);
  20587. }
  20588. };
  20589. const findLocation = (editor, caret, forward) => {
  20590. const rootNode = editor.getBody();
  20591. const from = getPositionFromRange(editor.selection.getRng(), rootNode, forward);
  20592. const isInlineTarget$1 = curry(isInlineTarget, editor);
  20593. const location = findLocation$1(forward, isInlineTarget$1, rootNode, from);
  20594. return location.bind(location => renderCaretLocation(editor, caret, location));
  20595. };
  20596. const toggleInlines = (isInlineTarget, dom, elms) => {
  20597. const inlineBoundaries = map$3(descendants(SugarElement.fromDom(dom.getRoot()), '*[data-mce-selected="inline-boundary"]'), e => e.dom);
  20598. const selectedInlines = filter$6(inlineBoundaries, isInlineTarget);
  20599. const targetInlines = filter$6(elms, isInlineTarget);
  20600. each$f(difference(selectedInlines, targetInlines), curry(setSelected, false));
  20601. each$f(difference(targetInlines, selectedInlines), curry(setSelected, true));
  20602. };
  20603. const safeRemoveCaretContainer = (editor, caret) => {
  20604. if (editor.selection.isCollapsed() && editor.composing !== true && caret.get()) {
  20605. const pos = CaretPosition.fromRangeStart(editor.selection.getRng());
  20606. if (CaretPosition.isTextPosition(pos) && isAtZwsp(pos) === false) {
  20607. setCaretPosition(editor, removeAndReposition(caret.get(), pos));
  20608. caret.set(null);
  20609. }
  20610. }
  20611. };
  20612. const renderInsideInlineCaret = (isInlineTarget, editor, caret, elms) => {
  20613. if (editor.selection.isCollapsed()) {
  20614. const inlines = filter$6(elms, isInlineTarget);
  20615. each$f(inlines, _inline => {
  20616. const pos = CaretPosition.fromRangeStart(editor.selection.getRng());
  20617. readLocation(isInlineTarget, editor.getBody(), pos).bind(location => renderCaretLocation(editor, caret, location));
  20618. });
  20619. }
  20620. };
  20621. const move$2 = (editor, caret, forward) => isInlineBoundariesEnabled(editor) ? findLocation(editor, caret, forward).isSome() : false;
  20622. const moveWord = (forward, editor, _caret) => isInlineBoundariesEnabled(editor) ? moveByWord(forward, editor) : false;
  20623. const setupSelectedState = editor => {
  20624. const caret = Cell(null);
  20625. const isInlineTarget$1 = curry(isInlineTarget, editor);
  20626. editor.on('NodeChange', e => {
  20627. if (isInlineBoundariesEnabled(editor)) {
  20628. toggleInlines(isInlineTarget$1, editor.dom, e.parents);
  20629. safeRemoveCaretContainer(editor, caret);
  20630. renderInsideInlineCaret(isInlineTarget$1, editor, caret, e.parents);
  20631. }
  20632. });
  20633. return caret;
  20634. };
  20635. const moveNextWord = curry(moveWord, true);
  20636. const movePrevWord = curry(moveWord, false);
  20637. const moveToLineEndPoint$2 = (editor, forward, caret) => {
  20638. if (isInlineBoundariesEnabled(editor)) {
  20639. const linePoint = getLineEndPoint(editor, forward).getOrThunk(() => {
  20640. const rng = editor.selection.getRng();
  20641. return forward ? CaretPosition.fromRangeEnd(rng) : CaretPosition.fromRangeStart(rng);
  20642. });
  20643. return readLocation(curry(isInlineTarget, editor), editor.getBody(), linePoint).exists(loc => {
  20644. const outsideLoc = outside(loc);
  20645. return renderCaret(caret, outsideLoc).exists(pos => {
  20646. setCaretPosition(editor, pos);
  20647. return true;
  20648. });
  20649. });
  20650. } else {
  20651. return false;
  20652. }
  20653. };
  20654. const rangeFromPositions = (from, to) => {
  20655. const range = document.createRange();
  20656. range.setStart(from.container(), from.offset());
  20657. range.setEnd(to.container(), to.offset());
  20658. return range;
  20659. };
  20660. const hasOnlyTwoOrLessPositionsLeft = elm => lift2(firstPositionIn(elm), lastPositionIn(elm), (firstPos, lastPos) => {
  20661. const normalizedFirstPos = normalizePosition(true, firstPos);
  20662. const normalizedLastPos = normalizePosition(false, lastPos);
  20663. return nextPosition(elm, normalizedFirstPos).forall(pos => pos.isEqual(normalizedLastPos));
  20664. }).getOr(true);
  20665. const setCaretLocation = (editor, caret) => location => renderCaret(caret, location).map(pos => () => setCaretPosition(editor, pos));
  20666. const deleteFromTo = (editor, caret, from, to) => {
  20667. const rootNode = editor.getBody();
  20668. const isInlineTarget$1 = curry(isInlineTarget, editor);
  20669. editor.undoManager.ignore(() => {
  20670. editor.selection.setRng(rangeFromPositions(from, to));
  20671. execDeleteCommand(editor);
  20672. readLocation(isInlineTarget$1, rootNode, CaretPosition.fromRangeStart(editor.selection.getRng())).map(inside).bind(setCaretLocation(editor, caret)).each(call);
  20673. });
  20674. editor.nodeChanged();
  20675. };
  20676. const rescope = (rootNode, node) => {
  20677. const parentBlock = getParentBlock$3(node, rootNode);
  20678. return parentBlock ? parentBlock : rootNode;
  20679. };
  20680. const backspaceDeleteCollapsed = (editor, caret, forward, from) => {
  20681. const rootNode = rescope(editor.getBody(), from.container());
  20682. const isInlineTarget$1 = curry(isInlineTarget, editor);
  20683. const fromLocation = readLocation(isInlineTarget$1, rootNode, from);
  20684. const location = fromLocation.bind(location => {
  20685. if (forward) {
  20686. return location.fold(constant(Optional.some(inside(location))), Optional.none, constant(Optional.some(outside(location))), Optional.none);
  20687. } else {
  20688. return location.fold(Optional.none, constant(Optional.some(outside(location))), Optional.none, constant(Optional.some(inside(location))));
  20689. }
  20690. });
  20691. return location.map(setCaretLocation(editor, caret)).getOrThunk(() => {
  20692. const toPosition = navigate(forward, rootNode, from);
  20693. const toLocation = toPosition.bind(pos => readLocation(isInlineTarget$1, rootNode, pos));
  20694. return lift2(fromLocation, toLocation, () => findRootInline(isInlineTarget$1, rootNode, from).bind(elm => {
  20695. if (hasOnlyTwoOrLessPositionsLeft(elm)) {
  20696. return Optional.some(() => {
  20697. deleteElement$2(editor, forward, SugarElement.fromDom(elm));
  20698. });
  20699. } else {
  20700. return Optional.none();
  20701. }
  20702. })).getOrThunk(() => toLocation.bind(() => toPosition.map(to => {
  20703. return () => {
  20704. if (forward) {
  20705. deleteFromTo(editor, caret, from, to);
  20706. } else {
  20707. deleteFromTo(editor, caret, to, from);
  20708. }
  20709. };
  20710. })));
  20711. });
  20712. };
  20713. const backspaceDelete$3 = (editor, caret, forward) => {
  20714. if (editor.selection.isCollapsed() && isInlineBoundariesEnabled(editor)) {
  20715. const from = CaretPosition.fromRangeStart(editor.selection.getRng());
  20716. return backspaceDeleteCollapsed(editor, caret, forward, from);
  20717. }
  20718. return Optional.none();
  20719. };
  20720. const getParentInlines = (rootElm, startElm) => {
  20721. const parents = parentsAndSelf(startElm, rootElm);
  20722. return findIndex$2(parents, isBlock$2).fold(constant(parents), index => parents.slice(0, index));
  20723. };
  20724. const hasOnlyOneChild = elm => childNodesCount(elm) === 1;
  20725. const deleteLastPosition = (forward, editor, target, parentInlines) => {
  20726. const isFormatElement$1 = curry(isFormatElement, editor);
  20727. const formatNodes = map$3(filter$6(parentInlines, isFormatElement$1), elm => elm.dom);
  20728. if (formatNodes.length === 0) {
  20729. deleteElement$2(editor, forward, target);
  20730. } else {
  20731. const pos = replaceWithCaretFormat(target.dom, formatNodes);
  20732. editor.selection.setRng(pos.toRange());
  20733. }
  20734. };
  20735. const deleteCaret$1 = (editor, forward) => {
  20736. const rootElm = SugarElement.fromDom(editor.getBody());
  20737. const startElm = SugarElement.fromDom(editor.selection.getStart());
  20738. const parentInlines = filter$6(getParentInlines(rootElm, startElm), hasOnlyOneChild);
  20739. return last$3(parentInlines).bind(target => {
  20740. const fromPos = CaretPosition.fromRangeStart(editor.selection.getRng());
  20741. if (willDeleteLastPositionInElement(forward, fromPos, target.dom) && !isEmptyCaretFormatElement(target)) {
  20742. return Optional.some(() => deleteLastPosition(forward, editor, target, parentInlines));
  20743. } else {
  20744. return Optional.none();
  20745. }
  20746. });
  20747. };
  20748. const backspaceDelete$2 = (editor, forward) => editor.selection.isCollapsed() ? deleteCaret$1(editor, forward) : Optional.none();
  20749. const deleteElement = (editor, forward, element) => {
  20750. return Optional.some(() => {
  20751. editor._selectionOverrides.hideFakeCaret();
  20752. deleteElement$2(editor, forward, SugarElement.fromDom(element));
  20753. });
  20754. };
  20755. const deleteCaret = (editor, forward) => {
  20756. const isNearMedia = forward ? isBeforeMedia : isAfterMedia;
  20757. const direction = forward ? HDirection.Forwards : HDirection.Backwards;
  20758. const fromPos = getNormalizedRangeEndPoint(direction, editor.getBody(), editor.selection.getRng());
  20759. if (isNearMedia(fromPos)) {
  20760. return deleteElement(editor, forward, fromPos.getNode(!forward));
  20761. } else {
  20762. return Optional.from(normalizePosition(forward, fromPos)).filter(pos => isNearMedia(pos) && isMoveInsideSameBlock(fromPos, pos)).map(pos => () => deleteElement(editor, forward, pos.getNode(!forward)));
  20763. }
  20764. };
  20765. const deleteRange = (editor, forward) => {
  20766. const selectedNode = editor.selection.getNode();
  20767. return isMedia$2(selectedNode) ? deleteElement(editor, forward, selectedNode) : Optional.none();
  20768. };
  20769. const backspaceDelete$1 = (editor, forward) => editor.selection.isCollapsed() ? deleteCaret(editor, forward) : deleteRange(editor, forward);
  20770. const isEditable$1 = target => closest$4(target, elm => isContentEditableTrue$5(elm.dom) || isContentEditableFalse$b(elm.dom)).exists(elm => isContentEditableTrue$5(elm.dom));
  20771. const parseIndentValue = value => {
  20772. const number = parseInt(value, 10);
  20773. return isNaN(number) ? 0 : number;
  20774. };
  20775. const getIndentStyleName = (useMargin, element) => {
  20776. const indentStyleName = useMargin || isTable$2(element) ? 'margin' : 'padding';
  20777. const suffix = get$7(element, 'direction') === 'rtl' ? '-right' : '-left';
  20778. return indentStyleName + suffix;
  20779. };
  20780. const indentElement = (dom, command, useMargin, value, unit, element) => {
  20781. const indentStyleName = getIndentStyleName(useMargin, SugarElement.fromDom(element));
  20782. if (command === 'outdent') {
  20783. const styleValue = Math.max(0, parseIndentValue(element.style[indentStyleName]) - value);
  20784. dom.setStyle(element, indentStyleName, styleValue ? styleValue + unit : '');
  20785. } else {
  20786. const styleValue = parseIndentValue(element.style[indentStyleName]) + value + unit;
  20787. dom.setStyle(element, indentStyleName, styleValue);
  20788. }
  20789. };
  20790. const validateBlocks = (editor, blocks) => forall(blocks, block => {
  20791. const indentStyleName = getIndentStyleName(shouldIndentUseMargin(editor), block);
  20792. const intentValue = getRaw$1(block, indentStyleName).map(parseIndentValue).getOr(0);
  20793. const contentEditable = editor.dom.getContentEditable(block.dom);
  20794. return contentEditable !== 'false' && intentValue > 0;
  20795. });
  20796. const canOutdent = editor => {
  20797. const blocks = getBlocksToIndent(editor);
  20798. return !editor.mode.isReadOnly() && (blocks.length > 1 || validateBlocks(editor, blocks));
  20799. };
  20800. const isListComponent = el => isList(el) || isListItem(el);
  20801. const parentIsListComponent = el => parent(el).exists(isListComponent);
  20802. const getBlocksToIndent = editor => filter$6(fromDom$1(editor.selection.getSelectedBlocks()), el => !isListComponent(el) && !parentIsListComponent(el) && isEditable$1(el));
  20803. const handle = (editor, command) => {
  20804. const {dom} = editor;
  20805. const indentation = getIndentation(editor);
  20806. const indentUnit = /[a-z%]+$/i.exec(indentation)[0];
  20807. const indentValue = parseInt(indentation, 10);
  20808. const useMargin = shouldIndentUseMargin(editor);
  20809. each$f(getBlocksToIndent(editor), block => {
  20810. indentElement(dom, command, useMargin, indentValue, indentUnit, block.dom);
  20811. });
  20812. };
  20813. const indent = editor => handle(editor, 'indent');
  20814. const outdent = editor => handle(editor, 'outdent');
  20815. const backspaceDelete = editor => {
  20816. if (editor.selection.isCollapsed() && canOutdent(editor)) {
  20817. const dom = editor.dom;
  20818. const rng = editor.selection.getRng();
  20819. const pos = CaretPosition.fromRangeStart(rng);
  20820. const block = dom.getParent(rng.startContainer, dom.isBlock);
  20821. if (block !== null && isAtStartOfBlock(SugarElement.fromDom(block), pos)) {
  20822. return Optional.some(() => outdent(editor));
  20823. }
  20824. }
  20825. return Optional.none();
  20826. };
  20827. const findAction = (editor, caret, forward) => findMap([
  20828. backspaceDelete,
  20829. backspaceDelete$5,
  20830. backspaceDelete$6,
  20831. (editor, forward) => backspaceDelete$3(editor, caret, forward),
  20832. backspaceDelete$8,
  20833. backspaceDelete$9,
  20834. backspaceDelete$4,
  20835. backspaceDelete$1,
  20836. backspaceDelete$7,
  20837. backspaceDelete$2
  20838. ], item => item(editor, forward));
  20839. const deleteCommand = (editor, caret) => {
  20840. const result = findAction(editor, caret, false);
  20841. result.fold(() => {
  20842. execDeleteCommand(editor);
  20843. paddEmptyBody(editor);
  20844. }, call);
  20845. };
  20846. const forwardDeleteCommand = (editor, caret) => {
  20847. const result = findAction(editor, caret, true);
  20848. result.fold(() => execForwardDeleteCommand(editor), call);
  20849. };
  20850. const setup$p = (editor, caret) => {
  20851. editor.addCommand('delete', () => {
  20852. deleteCommand(editor, caret);
  20853. });
  20854. editor.addCommand('forwardDelete', () => {
  20855. forwardDeleteCommand(editor, caret);
  20856. });
  20857. };
  20858. const SIGNIFICANT_MOVE = 5;
  20859. const LONGPRESS_DELAY = 400;
  20860. const getTouch = event => {
  20861. if (event.touches === undefined || event.touches.length !== 1) {
  20862. return Optional.none();
  20863. }
  20864. return Optional.some(event.touches[0]);
  20865. };
  20866. const isFarEnough = (touch, data) => {
  20867. const distX = Math.abs(touch.clientX - data.x);
  20868. const distY = Math.abs(touch.clientY - data.y);
  20869. return distX > SIGNIFICANT_MOVE || distY > SIGNIFICANT_MOVE;
  20870. };
  20871. const setup$o = editor => {
  20872. const startData = value$2();
  20873. const longpressFired = Cell(false);
  20874. const debounceLongpress = last$1(e => {
  20875. editor.dispatch('longpress', {
  20876. ...e,
  20877. type: 'longpress'
  20878. });
  20879. longpressFired.set(true);
  20880. }, LONGPRESS_DELAY);
  20881. editor.on('touchstart', e => {
  20882. getTouch(e).each(touch => {
  20883. debounceLongpress.cancel();
  20884. const data = {
  20885. x: touch.clientX,
  20886. y: touch.clientY,
  20887. target: e.target
  20888. };
  20889. debounceLongpress.throttle(e);
  20890. longpressFired.set(false);
  20891. startData.set(data);
  20892. });
  20893. }, true);
  20894. editor.on('touchmove', e => {
  20895. debounceLongpress.cancel();
  20896. getTouch(e).each(touch => {
  20897. startData.on(data => {
  20898. if (isFarEnough(touch, data)) {
  20899. startData.clear();
  20900. longpressFired.set(false);
  20901. editor.dispatch('longpresscancel');
  20902. }
  20903. });
  20904. });
  20905. }, true);
  20906. editor.on('touchend touchcancel', e => {
  20907. debounceLongpress.cancel();
  20908. if (e.type === 'touchcancel') {
  20909. return;
  20910. }
  20911. startData.get().filter(data => data.target.isEqualNode(e.target)).each(() => {
  20912. if (longpressFired.get()) {
  20913. e.preventDefault();
  20914. } else {
  20915. editor.dispatch('tap', {
  20916. ...e,
  20917. type: 'tap'
  20918. });
  20919. }
  20920. });
  20921. }, true);
  20922. };
  20923. const isBlockElement = (blockElements, node) => has$2(blockElements, node.nodeName);
  20924. const isValidTarget = (blockElements, node) => {
  20925. if (isText$9(node)) {
  20926. return true;
  20927. } else if (isElement$6(node)) {
  20928. return !isBlockElement(blockElements, node) && !isBookmarkNode$1(node);
  20929. } else {
  20930. return false;
  20931. }
  20932. };
  20933. const hasBlockParent = (blockElements, root, node) => {
  20934. return exists(parents(SugarElement.fromDom(node), SugarElement.fromDom(root)), elm => {
  20935. return isBlockElement(blockElements, elm.dom);
  20936. });
  20937. };
  20938. const shouldRemoveTextNode = (blockElements, node) => {
  20939. if (isText$9(node)) {
  20940. if (node.nodeValue.length === 0) {
  20941. return true;
  20942. } else if (/^\s+$/.test(node.nodeValue) && (!node.nextSibling || isBlockElement(blockElements, node.nextSibling))) {
  20943. return true;
  20944. }
  20945. }
  20946. return false;
  20947. };
  20948. const addRootBlocks = editor => {
  20949. const dom = editor.dom, selection = editor.selection;
  20950. const schema = editor.schema, blockElements = schema.getBlockElements();
  20951. let node = selection.getStart();
  20952. const rootNode = editor.getBody();
  20953. let rootBlockNode, tempNode, wrapped;
  20954. const forcedRootBlock = getForcedRootBlock(editor);
  20955. if (!node || !isElement$6(node)) {
  20956. return;
  20957. }
  20958. const rootNodeName = rootNode.nodeName.toLowerCase();
  20959. if (!schema.isValidChild(rootNodeName, forcedRootBlock.toLowerCase()) || hasBlockParent(blockElements, rootNode, node)) {
  20960. return;
  20961. }
  20962. const rng = selection.getRng();
  20963. const startContainer = rng.startContainer;
  20964. const startOffset = rng.startOffset;
  20965. const endContainer = rng.endContainer;
  20966. const endOffset = rng.endOffset;
  20967. const restoreSelection = hasFocus(editor);
  20968. node = rootNode.firstChild;
  20969. while (node) {
  20970. if (isValidTarget(blockElements, node)) {
  20971. if (shouldRemoveTextNode(blockElements, node)) {
  20972. tempNode = node;
  20973. node = node.nextSibling;
  20974. dom.remove(tempNode);
  20975. continue;
  20976. }
  20977. if (!rootBlockNode) {
  20978. rootBlockNode = dom.create(forcedRootBlock, getForcedRootBlockAttrs(editor));
  20979. node.parentNode.insertBefore(rootBlockNode, node);
  20980. wrapped = true;
  20981. }
  20982. tempNode = node;
  20983. node = node.nextSibling;
  20984. rootBlockNode.appendChild(tempNode);
  20985. } else {
  20986. rootBlockNode = null;
  20987. node = node.nextSibling;
  20988. }
  20989. }
  20990. if (wrapped && restoreSelection) {
  20991. rng.setStart(startContainer, startOffset);
  20992. rng.setEnd(endContainer, endOffset);
  20993. selection.setRng(rng);
  20994. editor.nodeChanged();
  20995. }
  20996. };
  20997. const setup$n = editor => {
  20998. editor.on('NodeChange', curry(addRootBlocks, editor));
  20999. };
  21000. const hasClass = checkClassName => node => (' ' + node.attr('class') + ' ').indexOf(checkClassName) !== -1;
  21001. const replaceMatchWithSpan = (editor, content, cls) => {
  21002. return function (match) {
  21003. const args = arguments, index = args[args.length - 2];
  21004. const prevChar = index > 0 ? content.charAt(index - 1) : '';
  21005. if (prevChar === '"') {
  21006. return match;
  21007. }
  21008. if (prevChar === '>') {
  21009. const findStartTagIndex = content.lastIndexOf('<', index);
  21010. if (findStartTagIndex !== -1) {
  21011. const tagHtml = content.substring(findStartTagIndex, index);
  21012. if (tagHtml.indexOf('contenteditable="false"') !== -1) {
  21013. return match;
  21014. }
  21015. }
  21016. }
  21017. return '<span class="' + cls + '" data-mce-content="' + editor.dom.encode(args[0]) + '">' + editor.dom.encode(typeof args[1] === 'string' ? args[1] : args[0]) + '</span>';
  21018. };
  21019. };
  21020. const convertRegExpsToNonEditable = (editor, nonEditableRegExps, e) => {
  21021. let i = nonEditableRegExps.length, content = e.content;
  21022. if (e.format === 'raw') {
  21023. return;
  21024. }
  21025. while (i--) {
  21026. content = content.replace(nonEditableRegExps[i], replaceMatchWithSpan(editor, content, getNonEditableClass(editor)));
  21027. }
  21028. e.content = content;
  21029. };
  21030. const setup$m = editor => {
  21031. const contentEditableAttrName = 'contenteditable';
  21032. const editClass = ' ' + Tools.trim(getEditableClass(editor)) + ' ';
  21033. const nonEditClass = ' ' + Tools.trim(getNonEditableClass(editor)) + ' ';
  21034. const hasEditClass = hasClass(editClass);
  21035. const hasNonEditClass = hasClass(nonEditClass);
  21036. const nonEditableRegExps = getNonEditableRegExps(editor);
  21037. if (nonEditableRegExps.length > 0) {
  21038. editor.on('BeforeSetContent', e => {
  21039. convertRegExpsToNonEditable(editor, nonEditableRegExps, e);
  21040. });
  21041. }
  21042. editor.parser.addAttributeFilter('class', nodes => {
  21043. let i = nodes.length;
  21044. while (i--) {
  21045. const node = nodes[i];
  21046. if (hasEditClass(node)) {
  21047. node.attr(contentEditableAttrName, 'true');
  21048. } else if (hasNonEditClass(node)) {
  21049. node.attr(contentEditableAttrName, 'false');
  21050. }
  21051. }
  21052. });
  21053. editor.serializer.addAttributeFilter(contentEditableAttrName, nodes => {
  21054. let i = nodes.length;
  21055. while (i--) {
  21056. const node = nodes[i];
  21057. if (!hasEditClass(node) && !hasNonEditClass(node)) {
  21058. continue;
  21059. }
  21060. if (nonEditableRegExps.length > 0 && node.attr('data-mce-content')) {
  21061. node.name = '#text';
  21062. node.type = 3;
  21063. node.raw = true;
  21064. node.value = node.attr('data-mce-content');
  21065. } else {
  21066. node.attr(contentEditableAttrName, null);
  21067. }
  21068. }
  21069. });
  21070. };
  21071. const findBlockCaretContainer = editor => descendant(SugarElement.fromDom(editor.getBody()), '*[data-mce-caret]').map(elm => elm.dom).getOrNull();
  21072. const showBlockCaretContainer = (editor, blockCaretContainer) => {
  21073. if (blockCaretContainer.hasAttribute('data-mce-caret')) {
  21074. showCaretContainerBlock(blockCaretContainer);
  21075. editor.selection.setRng(editor.selection.getRng());
  21076. editor.selection.scrollIntoView(blockCaretContainer);
  21077. }
  21078. };
  21079. const handleBlockContainer = (editor, e) => {
  21080. const blockCaretContainer = findBlockCaretContainer(editor);
  21081. if (!blockCaretContainer) {
  21082. return;
  21083. }
  21084. if (e.type === 'compositionstart') {
  21085. e.preventDefault();
  21086. e.stopPropagation();
  21087. showBlockCaretContainer(editor, blockCaretContainer);
  21088. return;
  21089. }
  21090. if (hasContent(blockCaretContainer)) {
  21091. showBlockCaretContainer(editor, blockCaretContainer);
  21092. editor.undoManager.add();
  21093. }
  21094. };
  21095. const setup$l = editor => {
  21096. editor.on('keyup compositionstart', curry(handleBlockContainer, editor));
  21097. };
  21098. const isContentEditableFalse$3 = isContentEditableFalse$b;
  21099. const moveToCeFalseHorizontally = (direction, editor, range) => moveHorizontally(editor, direction, range, isBeforeContentEditableFalse, isAfterContentEditableFalse, isContentEditableFalse$3);
  21100. const moveToCeFalseVertically = (direction, editor, range) => {
  21101. const isBefore = caretPosition => isBeforeContentEditableFalse(caretPosition) || isBeforeTable(caretPosition);
  21102. const isAfter = caretPosition => isAfterContentEditableFalse(caretPosition) || isAfterTable(caretPosition);
  21103. return moveVertically(editor, direction, range, isBefore, isAfter, isContentEditableFalse$3);
  21104. };
  21105. const createTextBlock = editor => {
  21106. const textBlock = editor.dom.create(getForcedRootBlock(editor));
  21107. textBlock.innerHTML = '<br data-mce-bogus="1">';
  21108. return textBlock;
  21109. };
  21110. const exitPreBlock = (editor, direction, range) => {
  21111. const caretWalker = CaretWalker(editor.getBody());
  21112. const getVisualCaretPosition$1 = curry(getVisualCaretPosition, direction === 1 ? caretWalker.next : caretWalker.prev);
  21113. if (range.collapsed) {
  21114. const pre = editor.dom.getParent(range.startContainer, 'PRE');
  21115. if (!pre) {
  21116. return;
  21117. }
  21118. const caretPos = getVisualCaretPosition$1(CaretPosition.fromRangeStart(range));
  21119. if (!caretPos) {
  21120. const newBlock = SugarElement.fromDom(createTextBlock(editor));
  21121. if (direction === 1) {
  21122. after$4(SugarElement.fromDom(pre), newBlock);
  21123. } else {
  21124. before$3(SugarElement.fromDom(pre), newBlock);
  21125. }
  21126. editor.selection.select(newBlock.dom, true);
  21127. editor.selection.collapse();
  21128. }
  21129. }
  21130. };
  21131. const getHorizontalRange = (editor, forward) => {
  21132. const direction = forward ? HDirection.Forwards : HDirection.Backwards;
  21133. const range = editor.selection.getRng();
  21134. return moveToCeFalseHorizontally(direction, editor, range).orThunk(() => {
  21135. exitPreBlock(editor, direction, range);
  21136. return Optional.none();
  21137. });
  21138. };
  21139. const getVerticalRange = (editor, down) => {
  21140. const direction = down ? 1 : -1;
  21141. const range = editor.selection.getRng();
  21142. return moveToCeFalseVertically(direction, editor, range).orThunk(() => {
  21143. exitPreBlock(editor, direction, range);
  21144. return Optional.none();
  21145. });
  21146. };
  21147. const moveH$2 = (editor, forward) => getHorizontalRange(editor, forward).exists(newRange => {
  21148. moveToRange(editor, newRange);
  21149. return true;
  21150. });
  21151. const moveV$3 = (editor, down) => getVerticalRange(editor, down).exists(newRange => {
  21152. moveToRange(editor, newRange);
  21153. return true;
  21154. });
  21155. const moveToLineEndPoint$1 = (editor, forward) => {
  21156. const isCefPosition = forward ? isAfterContentEditableFalse : isBeforeContentEditableFalse;
  21157. return moveToLineEndPoint$3(editor, forward, isCefPosition);
  21158. };
  21159. const selectToEndPoint = (editor, forward) => getEdgeCefPosition(editor, !forward).map(pos => {
  21160. const rng = pos.toRange();
  21161. const curRng = editor.selection.getRng();
  21162. if (forward) {
  21163. rng.setStart(curRng.startContainer, curRng.startOffset);
  21164. } else {
  21165. rng.setEnd(curRng.endContainer, curRng.endOffset);
  21166. }
  21167. return rng;
  21168. }).exists(rng => {
  21169. moveToRange(editor, rng);
  21170. return true;
  21171. });
  21172. const isTarget = node => contains$2(['figcaption'], name(node));
  21173. const rangeBefore = target => {
  21174. const rng = document.createRange();
  21175. rng.setStartBefore(target.dom);
  21176. rng.setEndBefore(target.dom);
  21177. return rng;
  21178. };
  21179. const insertElement = (root, elm, forward) => {
  21180. if (forward) {
  21181. append$1(root, elm);
  21182. } else {
  21183. prepend(root, elm);
  21184. }
  21185. };
  21186. const insertEmptyLine = (root, forward, blockName, attrs) => {
  21187. const block = SugarElement.fromTag(blockName);
  21188. const br = SugarElement.fromTag('br');
  21189. setAll$1(block, attrs);
  21190. append$1(block, br);
  21191. insertElement(root, block, forward);
  21192. return rangeBefore(br);
  21193. };
  21194. const getClosestTargetBlock = (pos, root) => {
  21195. const isRoot = curry(eq, root);
  21196. return closest$4(SugarElement.fromDom(pos.container()), isBlock$2, isRoot).filter(isTarget);
  21197. };
  21198. const isAtFirstOrLastLine = (root, forward, pos) => forward ? isAtLastLine(root.dom, pos) : isAtFirstLine(root.dom, pos);
  21199. const moveCaretToNewEmptyLine = (editor, forward) => {
  21200. const root = SugarElement.fromDom(editor.getBody());
  21201. const pos = CaretPosition.fromRangeStart(editor.selection.getRng());
  21202. const rootBlock = getForcedRootBlock(editor);
  21203. const rootBlockAttrs = getForcedRootBlockAttrs(editor);
  21204. return getClosestTargetBlock(pos, root).exists(() => {
  21205. if (isAtFirstOrLastLine(root, forward, pos)) {
  21206. const rng = insertEmptyLine(root, forward, rootBlock, rootBlockAttrs);
  21207. editor.selection.setRng(rng);
  21208. return true;
  21209. } else {
  21210. return false;
  21211. }
  21212. });
  21213. };
  21214. const moveV$2 = (editor, forward) => {
  21215. if (editor.selection.isCollapsed()) {
  21216. return moveCaretToNewEmptyLine(editor, forward);
  21217. } else {
  21218. return false;
  21219. }
  21220. };
  21221. const baseKeyPattern = {
  21222. shiftKey: false,
  21223. altKey: false,
  21224. ctrlKey: false,
  21225. metaKey: false,
  21226. keyCode: 0
  21227. };
  21228. const defaultPatterns = patterns => map$3(patterns, pattern => ({
  21229. ...baseKeyPattern,
  21230. action: noop,
  21231. ...pattern
  21232. }));
  21233. const defaultDelayedPatterns = patterns => map$3(patterns, pattern => ({
  21234. ...baseKeyPattern,
  21235. action: () => Optional.none(),
  21236. ...pattern
  21237. }));
  21238. const matchesEvent = (pattern, evt) => evt.keyCode === pattern.keyCode && evt.shiftKey === pattern.shiftKey && evt.altKey === pattern.altKey && evt.ctrlKey === pattern.ctrlKey && evt.metaKey === pattern.metaKey;
  21239. const match$1 = (patterns, evt) => bind$3(defaultPatterns(patterns), pattern => matchesEvent(pattern, evt) ? [pattern] : []);
  21240. const matchDelayed = (patterns, evt) => bind$3(defaultDelayedPatterns(patterns), pattern => matchesEvent(pattern, evt) ? [pattern] : []);
  21241. const action = (f, ...x) => () => f.apply(null, x);
  21242. const execute = (patterns, evt) => find$2(match$1(patterns, evt), pattern => pattern.action());
  21243. const executeWithDelayedAction = (patterns, evt) => findMap(matchDelayed(patterns, evt), pattern => pattern.action());
  21244. const moveH$1 = (editor, forward) => {
  21245. const direction = forward ? HDirection.Forwards : HDirection.Backwards;
  21246. const range = editor.selection.getRng();
  21247. return moveHorizontally(editor, direction, range, isBeforeMedia, isAfterMedia, isMedia$2).exists(newRange => {
  21248. moveToRange(editor, newRange);
  21249. return true;
  21250. });
  21251. };
  21252. const moveV$1 = (editor, down) => {
  21253. const direction = down ? 1 : -1;
  21254. const range = editor.selection.getRng();
  21255. return moveVertically(editor, direction, range, isBeforeMedia, isAfterMedia, isMedia$2).exists(newRange => {
  21256. moveToRange(editor, newRange);
  21257. return true;
  21258. });
  21259. };
  21260. const moveToLineEndPoint = (editor, forward) => {
  21261. const isNearMedia = forward ? isAfterMedia : isBeforeMedia;
  21262. return moveToLineEndPoint$3(editor, forward, isNearMedia);
  21263. };
  21264. const adt = Adt.generate([
  21265. { none: ['current'] },
  21266. { first: ['current'] },
  21267. {
  21268. middle: [
  21269. 'current',
  21270. 'target'
  21271. ]
  21272. },
  21273. { last: ['current'] }
  21274. ]);
  21275. const none = current => adt.none(current);
  21276. const CellLocation = {
  21277. ...adt,
  21278. none
  21279. };
  21280. const firstLayer = (scope, selector) => {
  21281. return filterFirstLayer(scope, selector, always);
  21282. };
  21283. const filterFirstLayer = (scope, selector, predicate) => {
  21284. return bind$3(children(scope), x => {
  21285. if (is$1(x, selector)) {
  21286. return predicate(x) ? [x] : [];
  21287. } else {
  21288. return filterFirstLayer(x, selector, predicate);
  21289. }
  21290. });
  21291. };
  21292. const lookup$1 = (tags, element, isRoot = never) => {
  21293. if (isRoot(element)) {
  21294. return Optional.none();
  21295. }
  21296. if (contains$2(tags, name(element))) {
  21297. return Optional.some(element);
  21298. }
  21299. const isRootOrUpperTable = elm => is$1(elm, 'table') || isRoot(elm);
  21300. return ancestor$2(element, tags.join(','), isRootOrUpperTable);
  21301. };
  21302. const cell = (element, isRoot) => lookup$1([
  21303. 'td',
  21304. 'th'
  21305. ], element, isRoot);
  21306. const cells = ancestor => firstLayer(ancestor, 'th,td');
  21307. const table = (element, isRoot) => closest$3(element, 'table', isRoot);
  21308. const walk = (all, current, index, direction, isEligible = always) => {
  21309. const forwards = direction === 1;
  21310. if (!forwards && index <= 0) {
  21311. return CellLocation.first(all[0]);
  21312. } else if (forwards && index >= all.length - 1) {
  21313. return CellLocation.last(all[all.length - 1]);
  21314. } else {
  21315. const newIndex = index + direction;
  21316. const elem = all[newIndex];
  21317. return isEligible(elem) ? CellLocation.middle(current, elem) : walk(all, current, newIndex, direction, isEligible);
  21318. }
  21319. };
  21320. const detect = (current, isRoot) => {
  21321. return table(current, isRoot).bind(table => {
  21322. const all = cells(table);
  21323. const index = findIndex$2(all, x => eq(current, x));
  21324. return index.map(index => ({
  21325. index,
  21326. all
  21327. }));
  21328. });
  21329. };
  21330. const next = (current, isEligible, isRoot) => {
  21331. const detection = detect(current, isRoot);
  21332. return detection.fold(() => {
  21333. return CellLocation.none(current);
  21334. }, info => {
  21335. return walk(info.all, current, info.index, 1, isEligible);
  21336. });
  21337. };
  21338. const prev = (current, isEligible, isRoot) => {
  21339. const detection = detect(current, isRoot);
  21340. return detection.fold(() => {
  21341. return CellLocation.none();
  21342. }, info => {
  21343. return walk(info.all, current, info.index, -1, isEligible);
  21344. });
  21345. };
  21346. const closest = target => closest$3(target, '[contenteditable]');
  21347. const isEditable = (element, assumeEditable = false) => {
  21348. if (inBody(element)) {
  21349. return element.dom.isContentEditable;
  21350. } else {
  21351. return closest(element).fold(constant(assumeEditable), editable => getRaw(editable) === 'true');
  21352. }
  21353. };
  21354. const getRaw = element => element.dom.contentEditable;
  21355. const deflate = (rect, delta) => ({
  21356. left: rect.left - delta,
  21357. top: rect.top - delta,
  21358. right: rect.right + delta * 2,
  21359. bottom: rect.bottom + delta * 2,
  21360. width: rect.width + delta,
  21361. height: rect.height + delta
  21362. });
  21363. const getCorners = (getYAxisValue, tds) => bind$3(tds, td => {
  21364. const rect = deflate(clone$1(td.getBoundingClientRect()), -1);
  21365. return [
  21366. {
  21367. x: rect.left,
  21368. y: getYAxisValue(rect),
  21369. cell: td
  21370. },
  21371. {
  21372. x: rect.right,
  21373. y: getYAxisValue(rect),
  21374. cell: td
  21375. }
  21376. ];
  21377. });
  21378. const findClosestCorner = (corners, x, y) => foldl(corners, (acc, newCorner) => acc.fold(() => Optional.some(newCorner), oldCorner => {
  21379. const oldDist = Math.sqrt(Math.abs(oldCorner.x - x) + Math.abs(oldCorner.y - y));
  21380. const newDist = Math.sqrt(Math.abs(newCorner.x - x) + Math.abs(newCorner.y - y));
  21381. return Optional.some(newDist < oldDist ? newCorner : oldCorner);
  21382. }), Optional.none());
  21383. const getClosestCell = (getYAxisValue, isTargetCorner, table, x, y) => {
  21384. const cells = descendants(SugarElement.fromDom(table), 'td,th,caption').map(e => e.dom);
  21385. const corners = filter$6(getCorners(getYAxisValue, cells), corner => isTargetCorner(corner, y));
  21386. return findClosestCorner(corners, x, y).map(corner => corner.cell);
  21387. };
  21388. const getBottomValue = rect => rect.bottom;
  21389. const getTopValue = rect => rect.top;
  21390. const isAbove = (corner, y) => corner.y < y;
  21391. const isBelow = (corner, y) => corner.y > y;
  21392. const getClosestCellAbove = curry(getClosestCell, getBottomValue, isAbove);
  21393. const getClosestCellBelow = curry(getClosestCell, getTopValue, isBelow);
  21394. const findClosestPositionInAboveCell = (table, pos) => head(pos.getClientRects()).bind(rect => getClosestCellAbove(table, rect.left, rect.top)).bind(cell => findClosestHorizontalPosition(getLastLinePositions(cell), pos));
  21395. const findClosestPositionInBelowCell = (table, pos) => last$3(pos.getClientRects()).bind(rect => getClosestCellBelow(table, rect.left, rect.top)).bind(cell => findClosestHorizontalPosition(getFirstLinePositions(cell), pos));
  21396. const hasNextBreak = (getPositionsUntil, scope, lineInfo) => lineInfo.breakAt.exists(breakPos => getPositionsUntil(scope, breakPos).breakAt.isSome());
  21397. const startsWithWrapBreak = lineInfo => lineInfo.breakType === BreakType.Wrap && lineInfo.positions.length === 0;
  21398. const startsWithBrBreak = lineInfo => lineInfo.breakType === BreakType.Br && lineInfo.positions.length === 1;
  21399. const isAtTableCellLine = (getPositionsUntil, scope, pos) => {
  21400. const lineInfo = getPositionsUntil(scope, pos);
  21401. if (startsWithWrapBreak(lineInfo) || !isBr$6(pos.getNode()) && startsWithBrBreak(lineInfo)) {
  21402. return !hasNextBreak(getPositionsUntil, scope, lineInfo);
  21403. } else {
  21404. return lineInfo.breakAt.isNone();
  21405. }
  21406. };
  21407. const isAtFirstTableCellLine = curry(isAtTableCellLine, getPositionsUntilPreviousLine);
  21408. const isAtLastTableCellLine = curry(isAtTableCellLine, getPositionsUntilNextLine);
  21409. const isCaretAtStartOrEndOfTable = (forward, rng, table) => {
  21410. const caretPos = CaretPosition.fromRangeStart(rng);
  21411. return positionIn(!forward, table).exists(pos => pos.isEqual(caretPos));
  21412. };
  21413. const navigateHorizontally = (editor, forward, table, _td) => {
  21414. const rng = editor.selection.getRng();
  21415. const direction = forward ? 1 : -1;
  21416. if (isFakeCaretTableBrowser() && isCaretAtStartOrEndOfTable(forward, rng, table)) {
  21417. showCaret(direction, editor, table, !forward, false).each(newRng => {
  21418. moveToRange(editor, newRng);
  21419. });
  21420. return true;
  21421. }
  21422. return false;
  21423. };
  21424. 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));
  21425. 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));
  21426. const getTable = (previous, pos) => {
  21427. const node = pos.getNode(previous);
  21428. return isElement$6(node) && node.nodeName === 'TABLE' ? Optional.some(node) : Optional.none();
  21429. };
  21430. const renderBlock = (down, editor, table) => {
  21431. const forcedRootBlock = getForcedRootBlock(editor);
  21432. editor.undoManager.transact(() => {
  21433. const element = SugarElement.fromTag(forcedRootBlock);
  21434. setAll$1(element, getForcedRootBlockAttrs(editor));
  21435. append$1(element, SugarElement.fromTag('br'));
  21436. if (down) {
  21437. after$4(SugarElement.fromDom(table), element);
  21438. } else {
  21439. before$3(SugarElement.fromDom(table), element);
  21440. }
  21441. const rng = editor.dom.createRng();
  21442. rng.setStart(element.dom, 0);
  21443. rng.setEnd(element.dom, 0);
  21444. moveToRange(editor, rng);
  21445. });
  21446. };
  21447. const moveCaret = (editor, down, pos) => {
  21448. const table = down ? getTable(true, pos) : getTable(false, pos);
  21449. const last = down === false;
  21450. 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)));
  21451. };
  21452. const navigateVertically = (editor, down, table, td) => {
  21453. const rng = editor.selection.getRng();
  21454. const pos = CaretPosition.fromRangeStart(rng);
  21455. const root = editor.getBody();
  21456. if (!down && isAtFirstTableCellLine(td, pos)) {
  21457. const newPos = getClosestAbovePosition(root, table, pos);
  21458. moveCaret(editor, down, newPos);
  21459. return true;
  21460. } else if (down && isAtLastTableCellLine(td, pos)) {
  21461. const newPos = getClosestBelowPosition(root, table, pos);
  21462. moveCaret(editor, down, newPos);
  21463. return true;
  21464. } else {
  21465. return false;
  21466. }
  21467. };
  21468. 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);
  21469. const moveH = (editor, forward) => move$1(editor, forward, navigateHorizontally);
  21470. const moveV = (editor, forward) => move$1(editor, forward, navigateVertically);
  21471. const getCellFirstCursorPosition = cell => {
  21472. const selection = SimSelection.exact(cell, 0, cell, 0);
  21473. return toNative(selection);
  21474. };
  21475. const tabGo = (editor, isRoot, cell) => {
  21476. return cell.fold(Optional.none, Optional.none, (_current, next) => {
  21477. return first(next).map(cell => {
  21478. return getCellFirstCursorPosition(cell);
  21479. });
  21480. }, current => {
  21481. editor.execCommand('mceTableInsertRowAfter');
  21482. return tabForward(editor, isRoot, current);
  21483. });
  21484. };
  21485. const tabForward = (editor, isRoot, cell) => tabGo(editor, isRoot, next(cell, isEditable));
  21486. const tabBackward = (editor, isRoot, cell) => tabGo(editor, isRoot, prev(cell, isEditable));
  21487. const handleTab = (editor, forward) => {
  21488. const rootElements = [
  21489. 'table',
  21490. 'li',
  21491. 'dl'
  21492. ];
  21493. const body = SugarElement.fromDom(editor.getBody());
  21494. const isRoot = element => {
  21495. const name$1 = name(element);
  21496. return eq(element, body) || contains$2(rootElements, name$1);
  21497. };
  21498. const rng = editor.selection.getRng();
  21499. const container = SugarElement.fromDom(!forward ? rng.startContainer : rng.endContainer);
  21500. return cell(container, isRoot).map(cell => {
  21501. table(cell, isRoot).each(table => {
  21502. editor.model.table.clearSelectedCells(table.dom);
  21503. });
  21504. editor.selection.collapse(!forward);
  21505. const navigation = !forward ? tabBackward : tabForward;
  21506. const rng = navigation(editor, isRoot, cell);
  21507. rng.each(range => {
  21508. editor.selection.setRng(range);
  21509. });
  21510. return true;
  21511. }).getOr(false);
  21512. };
  21513. const executeKeydownOverride$4 = (editor, caret, evt) => {
  21514. const isMac = Env.os.isMacOS() || Env.os.isiOS();
  21515. execute([
  21516. {
  21517. keyCode: VK.RIGHT,
  21518. action: action(moveH$2, editor, true)
  21519. },
  21520. {
  21521. keyCode: VK.LEFT,
  21522. action: action(moveH$2, editor, false)
  21523. },
  21524. {
  21525. keyCode: VK.UP,
  21526. action: action(moveV$3, editor, false)
  21527. },
  21528. {
  21529. keyCode: VK.DOWN,
  21530. action: action(moveV$3, editor, true)
  21531. },
  21532. ...isMac ? [
  21533. {
  21534. keyCode: VK.UP,
  21535. action: action(selectToEndPoint, editor, false),
  21536. metaKey: true,
  21537. shiftKey: true
  21538. },
  21539. {
  21540. keyCode: VK.DOWN,
  21541. action: action(selectToEndPoint, editor, true),
  21542. metaKey: true,
  21543. shiftKey: true
  21544. }
  21545. ] : [],
  21546. {
  21547. keyCode: VK.RIGHT,
  21548. action: action(moveH, editor, true)
  21549. },
  21550. {
  21551. keyCode: VK.LEFT,
  21552. action: action(moveH, editor, false)
  21553. },
  21554. {
  21555. keyCode: VK.UP,
  21556. action: action(moveV, editor, false)
  21557. },
  21558. {
  21559. keyCode: VK.DOWN,
  21560. action: action(moveV, editor, true)
  21561. },
  21562. {
  21563. keyCode: VK.RIGHT,
  21564. action: action(moveH$1, editor, true)
  21565. },
  21566. {
  21567. keyCode: VK.LEFT,
  21568. action: action(moveH$1, editor, false)
  21569. },
  21570. {
  21571. keyCode: VK.UP,
  21572. action: action(moveV$1, editor, false)
  21573. },
  21574. {
  21575. keyCode: VK.DOWN,
  21576. action: action(moveV$1, editor, true)
  21577. },
  21578. {
  21579. keyCode: VK.RIGHT,
  21580. action: action(move$2, editor, caret, true)
  21581. },
  21582. {
  21583. keyCode: VK.LEFT,
  21584. action: action(move$2, editor, caret, false)
  21585. },
  21586. {
  21587. keyCode: VK.RIGHT,
  21588. ctrlKey: !isMac,
  21589. altKey: isMac,
  21590. action: action(moveNextWord, editor, caret)
  21591. },
  21592. {
  21593. keyCode: VK.LEFT,
  21594. ctrlKey: !isMac,
  21595. altKey: isMac,
  21596. action: action(movePrevWord, editor, caret)
  21597. },
  21598. {
  21599. keyCode: VK.UP,
  21600. action: action(moveV$2, editor, false)
  21601. },
  21602. {
  21603. keyCode: VK.DOWN,
  21604. action: action(moveV$2, editor, true)
  21605. }
  21606. ], evt).each(_ => {
  21607. evt.preventDefault();
  21608. });
  21609. };
  21610. const setup$k = (editor, caret) => {
  21611. editor.on('keydown', evt => {
  21612. if (evt.isDefaultPrevented() === false) {
  21613. executeKeydownOverride$4(editor, caret, evt);
  21614. }
  21615. });
  21616. };
  21617. const point = (container, offset) => ({
  21618. container,
  21619. offset
  21620. });
  21621. const DOM$7 = DOMUtils.DOM;
  21622. const alwaysNext = startNode => node => startNode === node ? -1 : 0;
  21623. const isBoundary = dom => node => dom.isBlock(node) || contains$2([
  21624. 'BR',
  21625. 'IMG',
  21626. 'HR',
  21627. 'INPUT'
  21628. ], node.nodeName) || dom.getContentEditable(node) === 'false';
  21629. const textBefore = (node, offset, rootNode) => {
  21630. if (isText$9(node) && offset >= 0) {
  21631. return Optional.some(point(node, offset));
  21632. } else {
  21633. const textSeeker = TextSeeker(DOM$7);
  21634. return Optional.from(textSeeker.backwards(node, offset, alwaysNext(node), rootNode)).map(prev => point(prev.container, prev.container.data.length));
  21635. }
  21636. };
  21637. const textAfter = (node, offset, rootNode) => {
  21638. if (isText$9(node) && offset >= node.length) {
  21639. return Optional.some(point(node, offset));
  21640. } else {
  21641. const textSeeker = TextSeeker(DOM$7);
  21642. return Optional.from(textSeeker.forwards(node, offset, alwaysNext(node), rootNode)).map(prev => point(prev.container, 0));
  21643. }
  21644. };
  21645. const scanLeft = (node, offset, rootNode) => {
  21646. if (!isText$9(node)) {
  21647. return Optional.none();
  21648. }
  21649. const text = node.textContent;
  21650. if (offset >= 0 && offset <= text.length) {
  21651. return Optional.some(point(node, offset));
  21652. } else {
  21653. const textSeeker = TextSeeker(DOM$7);
  21654. return Optional.from(textSeeker.backwards(node, offset, alwaysNext(node), rootNode)).bind(prev => {
  21655. const prevText = prev.container.data;
  21656. return scanLeft(prev.container, offset + prevText.length, rootNode);
  21657. });
  21658. }
  21659. };
  21660. const scanRight = (node, offset, rootNode) => {
  21661. if (!isText$9(node)) {
  21662. return Optional.none();
  21663. }
  21664. const text = node.textContent;
  21665. if (offset <= text.length) {
  21666. return Optional.some(point(node, offset));
  21667. } else {
  21668. const textSeeker = TextSeeker(DOM$7);
  21669. return Optional.from(textSeeker.forwards(node, offset, alwaysNext(node), rootNode)).bind(next => scanRight(next.container, offset - text.length, rootNode));
  21670. }
  21671. };
  21672. const repeatLeft = (dom, node, offset, process, rootNode) => {
  21673. const search = TextSeeker(dom, isBoundary(dom));
  21674. return Optional.from(search.backwards(node, offset, process, rootNode));
  21675. };
  21676. const isValidTextRange = rng => rng.collapsed && rng.startContainer.nodeType === 3;
  21677. const getText = rng => rng.toString().replace(/\u00A0/g, ' ').replace(/\uFEFF/g, '');
  21678. const isWhitespace = chr => chr !== '' && ' \xA0\f\n\r\t\x0B'.indexOf(chr) !== -1;
  21679. const stripTriggerChar = (text, triggerCh) => text.substring(triggerCh.length);
  21680. const findChar = (text, index, ch) => {
  21681. let i;
  21682. for (i = index - 1; i >= 0; i--) {
  21683. const char = text.charAt(i);
  21684. if (isWhitespace(char)) {
  21685. return Optional.none();
  21686. }
  21687. if (char === ch) {
  21688. break;
  21689. }
  21690. }
  21691. return Optional.some(i);
  21692. };
  21693. const findStart = (dom, initRange, ch, minChars = 0) => {
  21694. if (!isValidTextRange(initRange)) {
  21695. return Optional.none();
  21696. }
  21697. const findTriggerChIndex = (element, offset, text) => findChar(text, offset, ch).getOr(offset);
  21698. const root = dom.getParent(initRange.startContainer, dom.isBlock) || dom.getRoot();
  21699. return repeatLeft(dom, initRange.startContainer, initRange.startOffset, findTriggerChIndex, root).bind(spot => {
  21700. const range = initRange.cloneRange();
  21701. range.setStart(spot.container, spot.offset);
  21702. range.setEnd(initRange.endContainer, initRange.endOffset);
  21703. if (range.collapsed) {
  21704. return Optional.none();
  21705. }
  21706. const text = getText(range);
  21707. const triggerCharIndex = text.lastIndexOf(ch);
  21708. if (triggerCharIndex !== 0 || stripTriggerChar(text, ch).length < minChars) {
  21709. return Optional.none();
  21710. } else {
  21711. return Optional.some({
  21712. text: stripTriggerChar(text, ch),
  21713. range,
  21714. triggerChar: ch
  21715. });
  21716. }
  21717. });
  21718. };
  21719. const getContext = (dom, initRange, ch, minChars = 0) => detect$1(SugarElement.fromDom(initRange.startContainer)).fold(() => findStart(dom, initRange, ch, minChars), elm => {
  21720. const range = dom.createRng();
  21721. range.selectNode(elm.dom);
  21722. const text = getText(range);
  21723. return Optional.some({
  21724. range,
  21725. text: stripTriggerChar(text, ch),
  21726. triggerChar: ch
  21727. });
  21728. });
  21729. const isText$1 = node => node.nodeType === TEXT;
  21730. const isElement = node => node.nodeType === ELEMENT;
  21731. const toLast = node => {
  21732. if (isText$1(node)) {
  21733. return point(node, node.data.length);
  21734. } else {
  21735. const children = node.childNodes;
  21736. return children.length > 0 ? toLast(children[children.length - 1]) : point(node, children.length);
  21737. }
  21738. };
  21739. const toLeaf = (node, offset) => {
  21740. const children = node.childNodes;
  21741. if (children.length > 0 && offset < children.length) {
  21742. return toLeaf(children[offset], 0);
  21743. } else if (children.length > 0 && isElement(node) && children.length === offset) {
  21744. return toLast(children[children.length - 1]);
  21745. } else {
  21746. return point(node, offset);
  21747. }
  21748. };
  21749. const isPreviousCharContent = (dom, leaf) => {
  21750. const root = dom.getParent(leaf.container, dom.isBlock);
  21751. return repeatLeft(dom, leaf.container, leaf.offset, (_element, offset) => offset === 0 ? -1 : offset, root).filter(spot => {
  21752. const char = spot.container.data.charAt(spot.offset - 1);
  21753. return !isWhitespace(char);
  21754. }).isSome();
  21755. };
  21756. const isStartOfWord = dom => rng => {
  21757. const leaf = toLeaf(rng.startContainer, rng.startOffset);
  21758. return !isPreviousCharContent(dom, leaf);
  21759. };
  21760. const getTriggerContext = (dom, initRange, database) => findMap(database.triggerChars, ch => getContext(dom, initRange, ch));
  21761. const lookup = (editor, getDatabase) => {
  21762. const database = getDatabase();
  21763. const rng = editor.selection.getRng();
  21764. return getTriggerContext(editor.dom, rng, database).bind(context => lookupWithContext(editor, getDatabase, context));
  21765. };
  21766. const lookupWithContext = (editor, getDatabase, context, fetchOptions = {}) => {
  21767. const database = getDatabase();
  21768. const rng = editor.selection.getRng();
  21769. const startText = rng.startContainer.nodeValue;
  21770. 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));
  21771. if (autocompleters.length === 0) {
  21772. return Optional.none();
  21773. }
  21774. const lookupData = Promise.all(map$3(autocompleters, ac => {
  21775. const fetchResult = ac.fetch(context.text, ac.maxResults, fetchOptions);
  21776. return fetchResult.then(results => ({
  21777. matchText: context.text,
  21778. items: results,
  21779. columns: ac.columns,
  21780. onAction: ac.onAction,
  21781. highlightOn: ac.highlightOn
  21782. }));
  21783. }));
  21784. return Optional.some({
  21785. lookupData,
  21786. context
  21787. });
  21788. };
  21789. var SimpleResultType;
  21790. (function (SimpleResultType) {
  21791. SimpleResultType[SimpleResultType['Error'] = 0] = 'Error';
  21792. SimpleResultType[SimpleResultType['Value'] = 1] = 'Value';
  21793. }(SimpleResultType || (SimpleResultType = {})));
  21794. const fold$1 = (res, onError, onValue) => res.stype === SimpleResultType.Error ? onError(res.serror) : onValue(res.svalue);
  21795. const partition = results => {
  21796. const values = [];
  21797. const errors = [];
  21798. each$f(results, obj => {
  21799. fold$1(obj, err => errors.push(err), val => values.push(val));
  21800. });
  21801. return {
  21802. values,
  21803. errors
  21804. };
  21805. };
  21806. const mapError = (res, f) => {
  21807. if (res.stype === SimpleResultType.Error) {
  21808. return {
  21809. stype: SimpleResultType.Error,
  21810. serror: f(res.serror)
  21811. };
  21812. } else {
  21813. return res;
  21814. }
  21815. };
  21816. const map = (res, f) => {
  21817. if (res.stype === SimpleResultType.Value) {
  21818. return {
  21819. stype: SimpleResultType.Value,
  21820. svalue: f(res.svalue)
  21821. };
  21822. } else {
  21823. return res;
  21824. }
  21825. };
  21826. const bind = (res, f) => {
  21827. if (res.stype === SimpleResultType.Value) {
  21828. return f(res.svalue);
  21829. } else {
  21830. return res;
  21831. }
  21832. };
  21833. const bindError = (res, f) => {
  21834. if (res.stype === SimpleResultType.Error) {
  21835. return f(res.serror);
  21836. } else {
  21837. return res;
  21838. }
  21839. };
  21840. const svalue = v => ({
  21841. stype: SimpleResultType.Value,
  21842. svalue: v
  21843. });
  21844. const serror = e => ({
  21845. stype: SimpleResultType.Error,
  21846. serror: e
  21847. });
  21848. const toResult = res => fold$1(res, Result.error, Result.value);
  21849. const fromResult = res => res.fold(serror, svalue);
  21850. const SimpleResult = {
  21851. fromResult,
  21852. toResult,
  21853. svalue,
  21854. partition,
  21855. serror,
  21856. bind,
  21857. bindError,
  21858. map,
  21859. mapError,
  21860. fold: fold$1
  21861. };
  21862. const formatObj = input => {
  21863. return isObject(input) && keys(input).length > 100 ? ' removed due to size' : JSON.stringify(input, null, 2);
  21864. };
  21865. const formatErrors = errors => {
  21866. const es = errors.length > 10 ? errors.slice(0, 10).concat([{
  21867. path: [],
  21868. getErrorInfo: constant('... (only showing first ten failures)')
  21869. }]) : errors;
  21870. return map$3(es, e => {
  21871. return 'Failed path: (' + e.path.join(' > ') + ')\n' + e.getErrorInfo();
  21872. });
  21873. };
  21874. const nu = (path, getErrorInfo) => {
  21875. return SimpleResult.serror([{
  21876. path,
  21877. getErrorInfo
  21878. }]);
  21879. };
  21880. const missingRequired = (path, key, obj) => nu(path, () => 'Could not find valid *required* value for "' + key + '" in ' + formatObj(obj));
  21881. const missingKey = (path, key) => nu(path, () => 'Choice schema did not contain choice key: "' + key + '"');
  21882. const missingBranch = (path, branches, branch) => nu(path, () => 'The chosen schema: "' + branch + '" did not exist in branches: ' + formatObj(branches));
  21883. const custom = (path, err) => nu(path, constant(err));
  21884. const chooseFrom = (path, input, branches, ch) => {
  21885. const fields = get$a(branches, ch);
  21886. return fields.fold(() => missingBranch(path, branches, ch), vp => vp.extract(path.concat(['branch: ' + ch]), input));
  21887. };
  21888. const choose$1 = (key, branches) => {
  21889. const extract = (path, input) => {
  21890. const choice = get$a(input, key);
  21891. return choice.fold(() => missingKey(path, key), chosen => chooseFrom(path, input, branches, chosen));
  21892. };
  21893. const toString = () => 'chooseOn(' + key + '). Possible values: ' + keys(branches);
  21894. return {
  21895. extract,
  21896. toString
  21897. };
  21898. };
  21899. const shallow = (old, nu) => {
  21900. return nu;
  21901. };
  21902. const deep = (old, nu) => {
  21903. const bothObjects = isPlainObject(old) && isPlainObject(nu);
  21904. return bothObjects ? deepMerge(old, nu) : nu;
  21905. };
  21906. const baseMerge = merger => {
  21907. return (...objects) => {
  21908. if (objects.length === 0) {
  21909. throw new Error(`Can't merge zero objects`);
  21910. }
  21911. const ret = {};
  21912. for (let j = 0; j < objects.length; j++) {
  21913. const curObject = objects[j];
  21914. for (const key in curObject) {
  21915. if (has$2(curObject, key)) {
  21916. ret[key] = merger(ret[key], curObject[key]);
  21917. }
  21918. }
  21919. }
  21920. return ret;
  21921. };
  21922. };
  21923. const deepMerge = baseMerge(deep);
  21924. const merge = baseMerge(shallow);
  21925. const required = () => ({
  21926. tag: 'required',
  21927. process: {}
  21928. });
  21929. const defaultedThunk = fallbackThunk => ({
  21930. tag: 'defaultedThunk',
  21931. process: fallbackThunk
  21932. });
  21933. const defaulted$1 = fallback => defaultedThunk(constant(fallback));
  21934. const asOption = () => ({
  21935. tag: 'option',
  21936. process: {}
  21937. });
  21938. const mergeValues = (values, base) => values.length > 0 ? SimpleResult.svalue(deepMerge(base, merge.apply(undefined, values))) : SimpleResult.svalue(base);
  21939. const mergeErrors = errors => compose(SimpleResult.serror, flatten)(errors);
  21940. const consolidateObj = (objects, base) => {
  21941. const partition = SimpleResult.partition(objects);
  21942. return partition.errors.length > 0 ? mergeErrors(partition.errors) : mergeValues(partition.values, base);
  21943. };
  21944. const consolidateArr = objects => {
  21945. const partitions = SimpleResult.partition(objects);
  21946. return partitions.errors.length > 0 ? mergeErrors(partitions.errors) : SimpleResult.svalue(partitions.values);
  21947. };
  21948. const ResultCombine = {
  21949. consolidateObj,
  21950. consolidateArr
  21951. };
  21952. const field$1 = (key, newKey, presence, prop) => ({
  21953. tag: 'field',
  21954. key,
  21955. newKey,
  21956. presence,
  21957. prop
  21958. });
  21959. const customField$1 = (newKey, instantiator) => ({
  21960. tag: 'custom',
  21961. newKey,
  21962. instantiator
  21963. });
  21964. const fold = (value, ifField, ifCustom) => {
  21965. switch (value.tag) {
  21966. case 'field':
  21967. return ifField(value.key, value.newKey, value.presence, value.prop);
  21968. case 'custom':
  21969. return ifCustom(value.newKey, value.instantiator);
  21970. }
  21971. };
  21972. const value = validator => {
  21973. const extract = (path, val) => {
  21974. return SimpleResult.bindError(validator(val), err => custom(path, err));
  21975. };
  21976. const toString = constant('val');
  21977. return {
  21978. extract,
  21979. toString
  21980. };
  21981. };
  21982. const anyValue$1 = value(SimpleResult.svalue);
  21983. const requiredAccess = (path, obj, key, bundle) => get$a(obj, key).fold(() => missingRequired(path, key, obj), bundle);
  21984. const fallbackAccess = (obj, key, fallback, bundle) => {
  21985. const v = get$a(obj, key).getOrThunk(() => fallback(obj));
  21986. return bundle(v);
  21987. };
  21988. const optionAccess = (obj, key, bundle) => bundle(get$a(obj, key));
  21989. const optionDefaultedAccess = (obj, key, fallback, bundle) => {
  21990. const opt = get$a(obj, key).map(val => val === true ? fallback(obj) : val);
  21991. return bundle(opt);
  21992. };
  21993. const extractField = (field, path, obj, key, prop) => {
  21994. const bundle = av => prop.extract(path.concat([key]), av);
  21995. const bundleAsOption = optValue => optValue.fold(() => SimpleResult.svalue(Optional.none()), ov => {
  21996. const result = prop.extract(path.concat([key]), ov);
  21997. return SimpleResult.map(result, Optional.some);
  21998. });
  21999. switch (field.tag) {
  22000. case 'required':
  22001. return requiredAccess(path, obj, key, bundle);
  22002. case 'defaultedThunk':
  22003. return fallbackAccess(obj, key, field.process, bundle);
  22004. case 'option':
  22005. return optionAccess(obj, key, bundleAsOption);
  22006. case 'defaultedOptionThunk':
  22007. return optionDefaultedAccess(obj, key, field.process, bundleAsOption);
  22008. case 'mergeWithThunk': {
  22009. return fallbackAccess(obj, key, constant({}), v => {
  22010. const result = deepMerge(field.process(obj), v);
  22011. return bundle(result);
  22012. });
  22013. }
  22014. }
  22015. };
  22016. const extractFields = (path, obj, fields) => {
  22017. const success = {};
  22018. const errors = [];
  22019. for (const field of fields) {
  22020. fold(field, (key, newKey, presence, prop) => {
  22021. const result = extractField(presence, path, obj, key, prop);
  22022. SimpleResult.fold(result, err => {
  22023. errors.push(...err);
  22024. }, res => {
  22025. success[newKey] = res;
  22026. });
  22027. }, (newKey, instantiator) => {
  22028. success[newKey] = instantiator(obj);
  22029. });
  22030. }
  22031. return errors.length > 0 ? SimpleResult.serror(errors) : SimpleResult.svalue(success);
  22032. };
  22033. const objOf = values => {
  22034. const extract = (path, o) => extractFields(path, o, values);
  22035. const toString = () => {
  22036. const fieldStrings = map$3(values, value => fold(value, (key, _okey, _presence, prop) => key + ' -> ' + prop.toString(), (newKey, _instantiator) => 'state(' + newKey + ')'));
  22037. return 'obj{\n' + fieldStrings.join('\n') + '}';
  22038. };
  22039. return {
  22040. extract,
  22041. toString
  22042. };
  22043. };
  22044. const arrOf = prop => {
  22045. const extract = (path, array) => {
  22046. const results = map$3(array, (a, i) => prop.extract(path.concat(['[' + i + ']']), a));
  22047. return ResultCombine.consolidateArr(results);
  22048. };
  22049. const toString = () => 'array(' + prop.toString() + ')';
  22050. return {
  22051. extract,
  22052. toString
  22053. };
  22054. };
  22055. const valueOf = validator => value(v => validator(v).fold(SimpleResult.serror, SimpleResult.svalue));
  22056. const extractValue = (label, prop, obj) => {
  22057. const res = prop.extract([label], obj);
  22058. return SimpleResult.mapError(res, errs => ({
  22059. input: obj,
  22060. errors: errs
  22061. }));
  22062. };
  22063. const asRaw = (label, prop, obj) => SimpleResult.toResult(extractValue(label, prop, obj));
  22064. const formatError = errInfo => {
  22065. return 'Errors: \n' + formatErrors(errInfo.errors).join('\n') + '\n\nInput object: ' + formatObj(errInfo.input);
  22066. };
  22067. const choose = (key, branches) => choose$1(key, map$2(branches, objOf));
  22068. const anyValue = constant(anyValue$1);
  22069. const typedValue = (validator, expectedType) => value(a => {
  22070. const actualType = typeof a;
  22071. return validator(a) ? SimpleResult.svalue(a) : SimpleResult.serror(`Expected type: ${ expectedType } but got: ${ actualType }`);
  22072. });
  22073. const number = typedValue(isNumber, 'number');
  22074. const string = typedValue(isString, 'string');
  22075. const boolean = typedValue(isBoolean, 'boolean');
  22076. const functionProcessor = typedValue(isFunction, 'function');
  22077. const field = field$1;
  22078. const customField = customField$1;
  22079. const validateEnum = values => valueOf(value => contains$2(values, value) ? Result.value(value) : Result.error(`Unsupported value: "${ value }", choose one of "${ values.join(', ') }".`));
  22080. const requiredOf = (key, schema) => field(key, key, required(), schema);
  22081. const requiredString = key => requiredOf(key, string);
  22082. const requiredFunction = key => requiredOf(key, functionProcessor);
  22083. const requiredArrayOf = (key, schema) => field(key, key, required(), arrOf(schema));
  22084. const optionOf = (key, schema) => field(key, key, asOption(), schema);
  22085. const optionString = key => optionOf(key, string);
  22086. const optionFunction = key => optionOf(key, functionProcessor);
  22087. const defaulted = (key, fallback) => field(key, key, defaulted$1(fallback), anyValue());
  22088. const defaultedOf = (key, fallback, schema) => field(key, key, defaulted$1(fallback), schema);
  22089. const defaultedNumber = (key, fallback) => defaultedOf(key, fallback, number);
  22090. const defaultedString = (key, fallback) => defaultedOf(key, fallback, string);
  22091. const defaultedStringEnum = (key, fallback, values) => defaultedOf(key, fallback, validateEnum(values));
  22092. const defaultedBoolean = (key, fallback) => defaultedOf(key, fallback, boolean);
  22093. const defaultedFunction = (key, fallback) => defaultedOf(key, fallback, functionProcessor);
  22094. const defaultedArrayOf = (key, fallback, schema) => defaultedOf(key, fallback, arrOf(schema));
  22095. const type = requiredString('type');
  22096. const fetch$1 = requiredFunction('fetch');
  22097. const onAction = requiredFunction('onAction');
  22098. const onSetup = defaultedFunction('onSetup', () => noop);
  22099. const optionalText = optionString('text');
  22100. const optionalIcon = optionString('icon');
  22101. const optionalTooltip = optionString('tooltip');
  22102. const optionalLabel = optionString('label');
  22103. const active = defaultedBoolean('active', false);
  22104. const enabled = defaultedBoolean('enabled', true);
  22105. const primary = defaultedBoolean('primary', false);
  22106. const defaultedColumns = num => defaulted('columns', num);
  22107. const defaultedType = type => defaultedString('type', type);
  22108. const autocompleterSchema = objOf([
  22109. type,
  22110. requiredString('ch'),
  22111. defaultedNumber('minChars', 1),
  22112. defaultedColumns(1),
  22113. defaultedNumber('maxResults', 10),
  22114. optionFunction('matches'),
  22115. fetch$1,
  22116. onAction,
  22117. defaultedArrayOf('highlightOn', [], string)
  22118. ]);
  22119. const createAutocompleter = spec => asRaw('Autocompleter', autocompleterSchema, spec);
  22120. const baseToolbarButtonFields = [
  22121. enabled,
  22122. optionalTooltip,
  22123. optionalIcon,
  22124. optionalText,
  22125. onSetup
  22126. ];
  22127. const baseToolbarToggleButtonFields = [active].concat(baseToolbarButtonFields);
  22128. const contextBarFields = [
  22129. defaultedFunction('predicate', never),
  22130. defaultedStringEnum('scope', 'node', [
  22131. 'node',
  22132. 'editor'
  22133. ]),
  22134. defaultedStringEnum('position', 'selection', [
  22135. 'node',
  22136. 'selection',
  22137. 'line'
  22138. ])
  22139. ];
  22140. const contextButtonFields = baseToolbarButtonFields.concat([
  22141. defaultedType('contextformbutton'),
  22142. primary,
  22143. onAction,
  22144. customField('original', identity)
  22145. ]);
  22146. const contextToggleButtonFields = baseToolbarToggleButtonFields.concat([
  22147. defaultedType('contextformbutton'),
  22148. primary,
  22149. onAction,
  22150. customField('original', identity)
  22151. ]);
  22152. const launchButtonFields = baseToolbarButtonFields.concat([defaultedType('contextformbutton')]);
  22153. const launchToggleButtonFields = baseToolbarToggleButtonFields.concat([defaultedType('contextformtogglebutton')]);
  22154. const toggleOrNormal = choose('type', {
  22155. contextformbutton: contextButtonFields,
  22156. contextformtogglebutton: contextToggleButtonFields
  22157. });
  22158. objOf([
  22159. defaultedType('contextform'),
  22160. defaultedFunction('initValue', constant('')),
  22161. optionalLabel,
  22162. requiredArrayOf('commands', toggleOrNormal),
  22163. optionOf('launch', choose('type', {
  22164. contextformbutton: launchButtonFields,
  22165. contextformtogglebutton: launchToggleButtonFields
  22166. }))
  22167. ].concat(contextBarFields));
  22168. const register$2 = editor => {
  22169. const popups = editor.ui.registry.getAll().popups;
  22170. const dataset = map$2(popups, popup => createAutocompleter(popup).fold(err => {
  22171. throw new Error(formatError(err));
  22172. }, identity));
  22173. const triggerChars = stringArray(mapToArray(dataset, v => v.ch));
  22174. const datasetValues = values(dataset);
  22175. const lookupByChar = ch => filter$6(datasetValues, dv => dv.ch === ch);
  22176. return {
  22177. dataset,
  22178. triggerChars,
  22179. lookupByChar
  22180. };
  22181. };
  22182. const setupEditorInput = (editor, api) => {
  22183. const update = last$1(api.load, 50);
  22184. editor.on('keypress compositionend', e => {
  22185. if (e.which === 27) {
  22186. return;
  22187. }
  22188. update.throttle();
  22189. });
  22190. editor.on('keydown', e => {
  22191. const keyCode = e.which;
  22192. if (keyCode === 8) {
  22193. update.throttle();
  22194. } else if (keyCode === 27) {
  22195. api.cancelIfNecessary();
  22196. }
  22197. });
  22198. editor.on('remove', update.cancel);
  22199. };
  22200. const setup$j = editor => {
  22201. const activeAutocompleter = value$2();
  22202. const uiActive = Cell(false);
  22203. const isActive = activeAutocompleter.isSet;
  22204. const cancelIfNecessary = () => {
  22205. if (isActive()) {
  22206. removeAutocompleterDecoration(editor);
  22207. fireAutocompleterEnd(editor);
  22208. uiActive.set(false);
  22209. activeAutocompleter.clear();
  22210. }
  22211. };
  22212. const commenceIfNecessary = context => {
  22213. if (!isActive()) {
  22214. addAutocompleterDecoration(editor, context.range);
  22215. activeAutocompleter.set({
  22216. triggerChar: context.triggerChar,
  22217. matchLength: context.text.length
  22218. });
  22219. }
  22220. };
  22221. const getAutocompleters = cached(() => register$2(editor));
  22222. 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));
  22223. const load = fetchOptions => {
  22224. doLookup(fetchOptions).fold(cancelIfNecessary, lookupInfo => {
  22225. commenceIfNecessary(lookupInfo.context);
  22226. lookupInfo.lookupData.then(lookupData => {
  22227. activeAutocompleter.get().map(ac => {
  22228. const context = lookupInfo.context;
  22229. if (ac.triggerChar === context.triggerChar) {
  22230. if (context.text.length - ac.matchLength >= 10) {
  22231. cancelIfNecessary();
  22232. } else {
  22233. activeAutocompleter.set({
  22234. ...ac,
  22235. matchLength: context.text.length
  22236. });
  22237. if (uiActive.get()) {
  22238. fireAutocompleterUpdate(editor, { lookupData });
  22239. } else {
  22240. uiActive.set(true);
  22241. fireAutocompleterStart(editor, { lookupData });
  22242. }
  22243. }
  22244. }
  22245. });
  22246. });
  22247. });
  22248. };
  22249. editor.addCommand('mceAutocompleterReload', (_ui, value) => {
  22250. const fetchOptions = isObject(value) ? value.fetchOptions : {};
  22251. load(fetchOptions);
  22252. });
  22253. editor.addCommand('mceAutocompleterClose', cancelIfNecessary);
  22254. setupEditorInput(editor, {
  22255. cancelIfNecessary,
  22256. load
  22257. });
  22258. };
  22259. const createAndFireInputEvent = eventType => (editor, inputType, specifics = {}) => {
  22260. const target = editor.getBody();
  22261. const overrides = {
  22262. bubbles: true,
  22263. composed: true,
  22264. data: null,
  22265. isComposing: false,
  22266. detail: 0,
  22267. view: null,
  22268. target,
  22269. currentTarget: target,
  22270. eventPhase: Event.AT_TARGET,
  22271. originalTarget: target,
  22272. explicitOriginalTarget: target,
  22273. isTrusted: false,
  22274. srcElement: target,
  22275. cancelable: false,
  22276. preventDefault: noop,
  22277. inputType
  22278. };
  22279. const input = clone$3(new InputEvent(eventType));
  22280. return editor.dispatch(eventType, {
  22281. ...input,
  22282. ...overrides,
  22283. ...specifics
  22284. });
  22285. };
  22286. const fireFakeInputEvent = createAndFireInputEvent('input');
  22287. const fireFakeBeforeInputEvent = createAndFireInputEvent('beforeinput');
  22288. const executeKeydownOverride$3 = (editor, caret, evt) => {
  22289. const inputType = evt.keyCode === VK.BACKSPACE ? 'deleteContentBackward' : 'deleteContentForward';
  22290. executeWithDelayedAction([
  22291. {
  22292. keyCode: VK.BACKSPACE,
  22293. action: action(backspaceDelete, editor)
  22294. },
  22295. {
  22296. keyCode: VK.BACKSPACE,
  22297. action: action(backspaceDelete$5, editor, false)
  22298. },
  22299. {
  22300. keyCode: VK.DELETE,
  22301. action: action(backspaceDelete$5, editor, true)
  22302. },
  22303. {
  22304. keyCode: VK.BACKSPACE,
  22305. action: action(backspaceDelete$6, editor, false)
  22306. },
  22307. {
  22308. keyCode: VK.DELETE,
  22309. action: action(backspaceDelete$6, editor, true)
  22310. },
  22311. {
  22312. keyCode: VK.BACKSPACE,
  22313. action: action(backspaceDelete$3, editor, caret, false)
  22314. },
  22315. {
  22316. keyCode: VK.DELETE,
  22317. action: action(backspaceDelete$3, editor, caret, true)
  22318. },
  22319. {
  22320. keyCode: VK.BACKSPACE,
  22321. action: action(backspaceDelete$9, editor, false)
  22322. },
  22323. {
  22324. keyCode: VK.DELETE,
  22325. action: action(backspaceDelete$9, editor, true)
  22326. },
  22327. {
  22328. keyCode: VK.BACKSPACE,
  22329. action: action(backspaceDelete$4, editor, false)
  22330. },
  22331. {
  22332. keyCode: VK.DELETE,
  22333. action: action(backspaceDelete$4, editor, true)
  22334. },
  22335. {
  22336. keyCode: VK.BACKSPACE,
  22337. action: action(backspaceDelete$1, editor, false)
  22338. },
  22339. {
  22340. keyCode: VK.DELETE,
  22341. action: action(backspaceDelete$1, editor, true)
  22342. },
  22343. {
  22344. keyCode: VK.BACKSPACE,
  22345. action: action(backspaceDelete$7, editor, false)
  22346. },
  22347. {
  22348. keyCode: VK.DELETE,
  22349. action: action(backspaceDelete$7, editor, true)
  22350. },
  22351. {
  22352. keyCode: VK.BACKSPACE,
  22353. action: action(backspaceDelete$8, editor, false)
  22354. },
  22355. {
  22356. keyCode: VK.DELETE,
  22357. action: action(backspaceDelete$8, editor, true)
  22358. },
  22359. {
  22360. keyCode: VK.BACKSPACE,
  22361. action: action(backspaceDelete$2, editor, false)
  22362. },
  22363. {
  22364. keyCode: VK.DELETE,
  22365. action: action(backspaceDelete$2, editor, true)
  22366. }
  22367. ], evt).each(applyAction => {
  22368. evt.preventDefault();
  22369. const beforeInput = fireFakeBeforeInputEvent(editor, inputType);
  22370. if (!beforeInput.isDefaultPrevented()) {
  22371. applyAction();
  22372. fireFakeInputEvent(editor, inputType);
  22373. }
  22374. });
  22375. };
  22376. const executeKeyupOverride = (editor, evt) => {
  22377. execute([
  22378. {
  22379. keyCode: VK.BACKSPACE,
  22380. action: action(paddEmptyElement, editor)
  22381. },
  22382. {
  22383. keyCode: VK.DELETE,
  22384. action: action(paddEmptyElement, editor)
  22385. }
  22386. ], evt);
  22387. };
  22388. const setup$i = (editor, caret) => {
  22389. editor.on('keydown', evt => {
  22390. if (evt.isDefaultPrevented() === false) {
  22391. executeKeydownOverride$3(editor, caret, evt);
  22392. }
  22393. });
  22394. editor.on('keyup', evt => {
  22395. if (evt.isDefaultPrevented() === false) {
  22396. executeKeyupOverride(editor, evt);
  22397. }
  22398. });
  22399. };
  22400. const firstNonWhiteSpaceNodeSibling = node => {
  22401. while (node) {
  22402. if (node.nodeType === 1 || node.nodeType === 3 && node.data && /[\r\n\s]/.test(node.data)) {
  22403. return node;
  22404. }
  22405. node = node.nextSibling;
  22406. }
  22407. };
  22408. const moveToCaretPosition = (editor, root) => {
  22409. let node, lastNode = root;
  22410. const dom = editor.dom;
  22411. const moveCaretBeforeOnEnterElementsMap = editor.schema.getMoveCaretBeforeOnEnterElements();
  22412. if (!root) {
  22413. return;
  22414. }
  22415. if (/^(LI|DT|DD)$/.test(root.nodeName)) {
  22416. const firstChild = firstNonWhiteSpaceNodeSibling(root.firstChild);
  22417. if (firstChild && /^(UL|OL|DL)$/.test(firstChild.nodeName)) {
  22418. root.insertBefore(dom.doc.createTextNode(nbsp), root.firstChild);
  22419. }
  22420. }
  22421. const rng = dom.createRng();
  22422. root.normalize();
  22423. if (root.hasChildNodes()) {
  22424. const walker = new DomTreeWalker(root, root);
  22425. while (node = walker.current()) {
  22426. if (isText$9(node)) {
  22427. rng.setStart(node, 0);
  22428. rng.setEnd(node, 0);
  22429. break;
  22430. }
  22431. if (moveCaretBeforeOnEnterElementsMap[node.nodeName.toLowerCase()]) {
  22432. rng.setStartBefore(node);
  22433. rng.setEndBefore(node);
  22434. break;
  22435. }
  22436. lastNode = node;
  22437. node = walker.next();
  22438. }
  22439. if (!node) {
  22440. rng.setStart(lastNode, 0);
  22441. rng.setEnd(lastNode, 0);
  22442. }
  22443. } else {
  22444. if (isBr$6(root)) {
  22445. if (root.nextSibling && dom.isBlock(root.nextSibling)) {
  22446. rng.setStartBefore(root);
  22447. rng.setEndBefore(root);
  22448. } else {
  22449. rng.setStartAfter(root);
  22450. rng.setEndAfter(root);
  22451. }
  22452. } else {
  22453. rng.setStart(root, 0);
  22454. rng.setEnd(root, 0);
  22455. }
  22456. }
  22457. editor.selection.setRng(rng);
  22458. scrollRangeIntoView(editor, rng);
  22459. };
  22460. const getEditableRoot$1 = (dom, node) => {
  22461. const root = dom.getRoot();
  22462. let parent, editableRoot;
  22463. parent = node;
  22464. while (parent !== root && dom.getContentEditable(parent) !== 'false') {
  22465. if (dom.getContentEditable(parent) === 'true') {
  22466. editableRoot = parent;
  22467. }
  22468. parent = parent.parentNode;
  22469. }
  22470. return parent !== root ? editableRoot : root;
  22471. };
  22472. const getParentBlock$1 = editor => {
  22473. return Optional.from(editor.dom.getParent(editor.selection.getStart(true), editor.dom.isBlock));
  22474. };
  22475. const getParentBlockName = editor => {
  22476. return getParentBlock$1(editor).fold(constant(''), parentBlock => {
  22477. return parentBlock.nodeName.toUpperCase();
  22478. });
  22479. };
  22480. const isListItemParentBlock = editor => {
  22481. return getParentBlock$1(editor).filter(elm => {
  22482. return isListItem(SugarElement.fromDom(elm));
  22483. }).isSome();
  22484. };
  22485. const hasFirstChild = (elm, name) => {
  22486. return elm.firstChild && elm.firstChild.nodeName === name;
  22487. };
  22488. const isFirstChild = elm => {
  22489. var _a;
  22490. return ((_a = elm.parentNode) === null || _a === void 0 ? void 0 : _a.firstChild) === elm;
  22491. };
  22492. const hasParent = (elm, parentName) => {
  22493. return elm && elm.parentNode && elm.parentNode.nodeName === parentName;
  22494. };
  22495. const isListBlock = elm => {
  22496. return elm && /^(OL|UL|LI)$/.test(elm.nodeName);
  22497. };
  22498. const isNestedList = elm => {
  22499. return isListBlock(elm) && isListBlock(elm.parentNode);
  22500. };
  22501. const getContainerBlock = containerBlock => {
  22502. const containerBlockParent = containerBlock.parentNode;
  22503. if (/^(LI|DT|DD)$/.test(containerBlockParent.nodeName)) {
  22504. return containerBlockParent;
  22505. }
  22506. return containerBlock;
  22507. };
  22508. const isFirstOrLastLi = (containerBlock, parentBlock, first) => {
  22509. let node = containerBlock[first ? 'firstChild' : 'lastChild'];
  22510. while (node) {
  22511. if (isElement$6(node)) {
  22512. break;
  22513. }
  22514. node = node[first ? 'nextSibling' : 'previousSibling'];
  22515. }
  22516. return node === parentBlock;
  22517. };
  22518. const insert$3 = (editor, createNewBlock, containerBlock, parentBlock, newBlockName) => {
  22519. const dom = editor.dom;
  22520. const rng = editor.selection.getRng();
  22521. if (containerBlock === editor.getBody()) {
  22522. return;
  22523. }
  22524. if (isNestedList(containerBlock)) {
  22525. newBlockName = 'LI';
  22526. }
  22527. let newBlock = createNewBlock(newBlockName);
  22528. if (isFirstOrLastLi(containerBlock, parentBlock, true) && isFirstOrLastLi(containerBlock, parentBlock, false)) {
  22529. if (hasParent(containerBlock, 'LI')) {
  22530. const containerBlockParent = getContainerBlock(containerBlock);
  22531. dom.insertAfter(newBlock, containerBlockParent);
  22532. if (isFirstChild(containerBlock)) {
  22533. dom.remove(containerBlockParent);
  22534. } else {
  22535. dom.remove(containerBlock);
  22536. }
  22537. } else {
  22538. dom.replace(newBlock, containerBlock);
  22539. }
  22540. } else if (isFirstOrLastLi(containerBlock, parentBlock, true)) {
  22541. if (hasParent(containerBlock, 'LI')) {
  22542. dom.insertAfter(newBlock, getContainerBlock(containerBlock));
  22543. newBlock.appendChild(dom.doc.createTextNode(' '));
  22544. newBlock.appendChild(containerBlock);
  22545. } else {
  22546. containerBlock.parentNode.insertBefore(newBlock, containerBlock);
  22547. }
  22548. dom.remove(parentBlock);
  22549. } else if (isFirstOrLastLi(containerBlock, parentBlock, false)) {
  22550. dom.insertAfter(newBlock, getContainerBlock(containerBlock));
  22551. dom.remove(parentBlock);
  22552. } else {
  22553. containerBlock = getContainerBlock(containerBlock);
  22554. const tmpRng = rng.cloneRange();
  22555. tmpRng.setStartAfter(parentBlock);
  22556. tmpRng.setEndAfter(containerBlock);
  22557. const fragment = tmpRng.extractContents();
  22558. if (newBlockName === 'LI' && hasFirstChild(fragment, 'LI')) {
  22559. newBlock = fragment.firstChild;
  22560. dom.insertAfter(fragment, containerBlock);
  22561. } else {
  22562. dom.insertAfter(fragment, containerBlock);
  22563. dom.insertAfter(newBlock, containerBlock);
  22564. }
  22565. dom.remove(parentBlock);
  22566. }
  22567. moveToCaretPosition(editor, newBlock);
  22568. };
  22569. const trimZwsp = fragment => {
  22570. each$f(descendants$1(SugarElement.fromDom(fragment), isText$a), text => {
  22571. const rawNode = text.dom;
  22572. rawNode.nodeValue = trim$1(rawNode.nodeValue);
  22573. });
  22574. };
  22575. const isEmptyAnchor = (dom, elm) => {
  22576. return elm && elm.nodeName === 'A' && dom.isEmpty(elm);
  22577. };
  22578. const isTableCell = node => {
  22579. return node && /^(TD|TH|CAPTION)$/.test(node.nodeName);
  22580. };
  22581. const emptyBlock = elm => {
  22582. elm.innerHTML = '<br data-mce-bogus="1">';
  22583. };
  22584. const containerAndSiblingName = (container, nodeName) => {
  22585. return container.nodeName === nodeName || container.previousSibling && container.previousSibling.nodeName === nodeName;
  22586. };
  22587. const canSplitBlock = (dom, node) => {
  22588. return node && dom.isBlock(node) && !/^(TD|TH|CAPTION|FORM)$/.test(node.nodeName) && !/^(fixed|absolute)/i.test(node.style.position) && dom.getContentEditable(node) !== 'true';
  22589. };
  22590. const trimInlineElementsOnLeftSideOfBlock = (dom, nonEmptyElementsMap, block) => {
  22591. let node = block;
  22592. const firstChilds = [];
  22593. let i;
  22594. if (!node) {
  22595. return;
  22596. }
  22597. while (node = node.firstChild) {
  22598. if (dom.isBlock(node)) {
  22599. return;
  22600. }
  22601. if (isElement$6(node) && !nonEmptyElementsMap[node.nodeName.toLowerCase()]) {
  22602. firstChilds.push(node);
  22603. }
  22604. }
  22605. i = firstChilds.length;
  22606. while (i--) {
  22607. node = firstChilds[i];
  22608. if (!node.hasChildNodes() || node.firstChild === node.lastChild && node.firstChild.nodeValue === '') {
  22609. dom.remove(node);
  22610. } else {
  22611. if (isEmptyAnchor(dom, node)) {
  22612. dom.remove(node);
  22613. }
  22614. }
  22615. }
  22616. };
  22617. const normalizeZwspOffset = (start, container, offset) => {
  22618. if (isText$9(container) === false) {
  22619. return offset;
  22620. } else if (start) {
  22621. return offset === 1 && container.data.charAt(offset - 1) === ZWSP$1 ? 0 : offset;
  22622. } else {
  22623. return offset === container.data.length - 1 && container.data.charAt(offset) === ZWSP$1 ? container.data.length : offset;
  22624. }
  22625. };
  22626. const includeZwspInRange = rng => {
  22627. const newRng = rng.cloneRange();
  22628. newRng.setStart(rng.startContainer, normalizeZwspOffset(true, rng.startContainer, rng.startOffset));
  22629. newRng.setEnd(rng.endContainer, normalizeZwspOffset(false, rng.endContainer, rng.endOffset));
  22630. return newRng;
  22631. };
  22632. const trimLeadingLineBreaks = node => {
  22633. do {
  22634. if (isText$9(node)) {
  22635. node.nodeValue = node.nodeValue.replace(/^[\r\n]+/, '');
  22636. }
  22637. node = node.firstChild;
  22638. } while (node);
  22639. };
  22640. const getEditableRoot = (dom, node) => {
  22641. const root = dom.getRoot();
  22642. let parent, editableRoot;
  22643. parent = node;
  22644. while (parent !== root && dom.getContentEditable(parent) !== 'false') {
  22645. if (dom.getContentEditable(parent) === 'true') {
  22646. editableRoot = parent;
  22647. }
  22648. parent = parent.parentNode;
  22649. }
  22650. return parent !== root ? editableRoot : root;
  22651. };
  22652. const applyAttributes = (editor, node, forcedRootBlockAttrs) => {
  22653. const dom = editor.dom;
  22654. Optional.from(forcedRootBlockAttrs.style).map(dom.parseStyle).each(attrStyles => {
  22655. const currentStyles = getAllRaw(SugarElement.fromDom(node));
  22656. const newStyles = {
  22657. ...currentStyles,
  22658. ...attrStyles
  22659. };
  22660. dom.setStyles(node, newStyles);
  22661. });
  22662. const attrClassesOpt = Optional.from(forcedRootBlockAttrs.class).map(attrClasses => attrClasses.split(/\s+/));
  22663. const currentClassesOpt = Optional.from(node.className).map(currentClasses => filter$6(currentClasses.split(/\s+/), clazz => clazz !== ''));
  22664. lift2(attrClassesOpt, currentClassesOpt, (attrClasses, currentClasses) => {
  22665. const filteredClasses = filter$6(currentClasses, clazz => !contains$2(attrClasses, clazz));
  22666. const newClasses = [
  22667. ...attrClasses,
  22668. ...filteredClasses
  22669. ];
  22670. dom.setAttrib(node, 'class', newClasses.join(' '));
  22671. });
  22672. const appliedAttrs = [
  22673. 'style',
  22674. 'class'
  22675. ];
  22676. const remainingAttrs = filter$5(forcedRootBlockAttrs, (_, attrs) => !contains$2(appliedAttrs, attrs));
  22677. dom.setAttribs(node, remainingAttrs);
  22678. };
  22679. const setForcedBlockAttrs = (editor, node) => {
  22680. const forcedRootBlockName = getForcedRootBlock(editor);
  22681. if (forcedRootBlockName.toLowerCase() === node.tagName.toLowerCase()) {
  22682. const forcedRootBlockAttrs = getForcedRootBlockAttrs(editor);
  22683. applyAttributes(editor, node, forcedRootBlockAttrs);
  22684. }
  22685. };
  22686. const wrapSelfAndSiblingsInDefaultBlock = (editor, newBlockName, rng, container, offset) => {
  22687. let newBlock, parentBlock, startNode, node, next, rootBlockName;
  22688. const dom = editor.dom, editableRoot = getEditableRoot(dom, container);
  22689. parentBlock = dom.getParent(container, dom.isBlock);
  22690. if (!parentBlock || !canSplitBlock(dom, parentBlock)) {
  22691. parentBlock = parentBlock || editableRoot;
  22692. if (parentBlock === editor.getBody() || isTableCell(parentBlock)) {
  22693. rootBlockName = parentBlock.nodeName.toLowerCase();
  22694. } else {
  22695. rootBlockName = parentBlock.parentNode.nodeName.toLowerCase();
  22696. }
  22697. if (!parentBlock.hasChildNodes()) {
  22698. newBlock = dom.create(newBlockName);
  22699. setForcedBlockAttrs(editor, newBlock);
  22700. parentBlock.appendChild(newBlock);
  22701. rng.setStart(newBlock, 0);
  22702. rng.setEnd(newBlock, 0);
  22703. return newBlock;
  22704. }
  22705. node = container;
  22706. while (node.parentNode !== parentBlock) {
  22707. node = node.parentNode;
  22708. }
  22709. while (node && !dom.isBlock(node)) {
  22710. startNode = node;
  22711. node = node.previousSibling;
  22712. }
  22713. if (startNode && editor.schema.isValidChild(rootBlockName, newBlockName.toLowerCase())) {
  22714. newBlock = dom.create(newBlockName);
  22715. setForcedBlockAttrs(editor, newBlock);
  22716. startNode.parentNode.insertBefore(newBlock, startNode);
  22717. node = startNode;
  22718. while (node && !dom.isBlock(node)) {
  22719. next = node.nextSibling;
  22720. newBlock.appendChild(node);
  22721. node = next;
  22722. }
  22723. rng.setStart(container, offset);
  22724. rng.setEnd(container, offset);
  22725. }
  22726. }
  22727. return container;
  22728. };
  22729. const addBrToBlockIfNeeded = (dom, block) => {
  22730. block.normalize();
  22731. const lastChild = block.lastChild;
  22732. if (!lastChild || /^(left|right)$/gi.test(dom.getStyle(lastChild, 'float', true))) {
  22733. dom.add(block, 'br');
  22734. }
  22735. };
  22736. const shouldEndContainer = (editor, container) => {
  22737. const optionValue = shouldEndContainerOnEmptyBlock(editor);
  22738. if (isNullable(container)) {
  22739. return false;
  22740. } else if (isString(optionValue)) {
  22741. return contains$2(Tools.explode(optionValue), container.nodeName.toLowerCase());
  22742. } else {
  22743. return optionValue;
  22744. }
  22745. };
  22746. const insert$2 = (editor, evt) => {
  22747. let tmpRng, container, offset, parentBlock;
  22748. let newBlock, fragment, containerBlock, parentBlockName, isAfterLastNodeInContainer;
  22749. const dom = editor.dom;
  22750. const schema = editor.schema, nonEmptyElementsMap = schema.getNonEmptyElements();
  22751. const rng = editor.selection.getRng();
  22752. const newBlockName = getForcedRootBlock(editor);
  22753. const createNewBlock = name => {
  22754. let node = container, block, clonedNode, caretNode;
  22755. const textInlineElements = schema.getTextInlineElements();
  22756. if (name || parentBlockName === 'TABLE' || parentBlockName === 'HR') {
  22757. block = dom.create(name || newBlockName);
  22758. } else {
  22759. block = parentBlock.cloneNode(false);
  22760. }
  22761. caretNode = block;
  22762. if (shouldKeepStyles(editor) === false) {
  22763. dom.setAttrib(block, 'style', null);
  22764. dom.setAttrib(block, 'class', null);
  22765. } else {
  22766. do {
  22767. if (textInlineElements[node.nodeName]) {
  22768. if (isCaretNode(node) || isBookmarkNode$1(node)) {
  22769. continue;
  22770. }
  22771. clonedNode = node.cloneNode(false);
  22772. dom.setAttrib(clonedNode, 'id', '');
  22773. if (block.hasChildNodes()) {
  22774. clonedNode.appendChild(block.firstChild);
  22775. block.appendChild(clonedNode);
  22776. } else {
  22777. caretNode = clonedNode;
  22778. block.appendChild(clonedNode);
  22779. }
  22780. }
  22781. } while ((node = node.parentNode) && node !== editableRoot);
  22782. }
  22783. setForcedBlockAttrs(editor, block);
  22784. emptyBlock(caretNode);
  22785. return block;
  22786. };
  22787. const isCaretAtStartOrEndOfBlock = start => {
  22788. let node, name;
  22789. const normalizedOffset = normalizeZwspOffset(start, container, offset);
  22790. if (isText$9(container) && (start ? normalizedOffset > 0 : normalizedOffset < container.nodeValue.length)) {
  22791. return false;
  22792. }
  22793. if (container.parentNode === parentBlock && isAfterLastNodeInContainer && !start) {
  22794. return true;
  22795. }
  22796. if (start && isElement$6(container) && container === parentBlock.firstChild) {
  22797. return true;
  22798. }
  22799. if (containerAndSiblingName(container, 'TABLE') || containerAndSiblingName(container, 'HR')) {
  22800. return isAfterLastNodeInContainer && !start || !isAfterLastNodeInContainer && start;
  22801. }
  22802. const walker = new DomTreeWalker(container, parentBlock);
  22803. if (isText$9(container)) {
  22804. if (start && normalizedOffset === 0) {
  22805. walker.prev();
  22806. } else if (!start && normalizedOffset === container.nodeValue.length) {
  22807. walker.next();
  22808. }
  22809. }
  22810. while (node = walker.current()) {
  22811. if (isElement$6(node)) {
  22812. if (!node.getAttribute('data-mce-bogus')) {
  22813. name = node.nodeName.toLowerCase();
  22814. if (nonEmptyElementsMap[name] && name !== 'br') {
  22815. return false;
  22816. }
  22817. }
  22818. } else if (isText$9(node) && !isWhitespaceText(node.nodeValue)) {
  22819. return false;
  22820. }
  22821. if (start) {
  22822. walker.prev();
  22823. } else {
  22824. walker.next();
  22825. }
  22826. }
  22827. return true;
  22828. };
  22829. const insertNewBlockAfter = () => {
  22830. if (/^(H[1-6]|PRE|FIGURE)$/.test(parentBlockName) && containerBlockName !== 'HGROUP') {
  22831. newBlock = createNewBlock(newBlockName);
  22832. } else {
  22833. newBlock = createNewBlock();
  22834. }
  22835. if (shouldEndContainer(editor, containerBlock) && canSplitBlock(dom, containerBlock) && dom.isEmpty(parentBlock)) {
  22836. newBlock = dom.split(containerBlock, parentBlock);
  22837. } else {
  22838. dom.insertAfter(newBlock, parentBlock);
  22839. }
  22840. moveToCaretPosition(editor, newBlock);
  22841. };
  22842. normalize$2(dom, rng).each(normRng => {
  22843. rng.setStart(normRng.startContainer, normRng.startOffset);
  22844. rng.setEnd(normRng.endContainer, normRng.endOffset);
  22845. });
  22846. container = rng.startContainer;
  22847. offset = rng.startOffset;
  22848. const shiftKey = !!(evt && evt.shiftKey);
  22849. const ctrlKey = !!(evt && evt.ctrlKey);
  22850. if (isElement$6(container) && container.hasChildNodes()) {
  22851. isAfterLastNodeInContainer = offset > container.childNodes.length - 1;
  22852. container = container.childNodes[Math.min(offset, container.childNodes.length - 1)] || container;
  22853. if (isAfterLastNodeInContainer && isText$9(container)) {
  22854. offset = container.nodeValue.length;
  22855. } else {
  22856. offset = 0;
  22857. }
  22858. }
  22859. const editableRoot = getEditableRoot(dom, container);
  22860. if (!editableRoot) {
  22861. return;
  22862. }
  22863. if (!shiftKey) {
  22864. container = wrapSelfAndSiblingsInDefaultBlock(editor, newBlockName, rng, container, offset);
  22865. }
  22866. parentBlock = dom.getParent(container, dom.isBlock);
  22867. containerBlock = parentBlock ? dom.getParent(parentBlock.parentNode, dom.isBlock) : null;
  22868. parentBlockName = parentBlock ? parentBlock.nodeName.toUpperCase() : '';
  22869. const containerBlockName = containerBlock ? containerBlock.nodeName.toUpperCase() : '';
  22870. if (containerBlockName === 'LI' && !ctrlKey) {
  22871. parentBlock = containerBlock;
  22872. containerBlock = containerBlock.parentNode;
  22873. parentBlockName = containerBlockName;
  22874. }
  22875. if (/^(LI|DT|DD)$/.test(parentBlockName)) {
  22876. if (dom.isEmpty(parentBlock)) {
  22877. insert$3(editor, createNewBlock, containerBlock, parentBlock, newBlockName);
  22878. return;
  22879. }
  22880. }
  22881. if (parentBlock === editor.getBody()) {
  22882. return;
  22883. }
  22884. if (isCaretContainerBlock$1(parentBlock)) {
  22885. newBlock = showCaretContainerBlock(parentBlock);
  22886. if (dom.isEmpty(parentBlock)) {
  22887. emptyBlock(parentBlock);
  22888. }
  22889. setForcedBlockAttrs(editor, newBlock);
  22890. moveToCaretPosition(editor, newBlock);
  22891. } else if (isCaretAtStartOrEndOfBlock()) {
  22892. insertNewBlockAfter();
  22893. } else if (isCaretAtStartOrEndOfBlock(true)) {
  22894. newBlock = parentBlock.parentNode.insertBefore(createNewBlock(), parentBlock);
  22895. moveToCaretPosition(editor, containerAndSiblingName(parentBlock, 'HR') ? newBlock : parentBlock);
  22896. } else {
  22897. tmpRng = includeZwspInRange(rng).cloneRange();
  22898. tmpRng.setEndAfter(parentBlock);
  22899. fragment = tmpRng.extractContents();
  22900. trimZwsp(fragment);
  22901. trimLeadingLineBreaks(fragment);
  22902. newBlock = fragment.firstChild;
  22903. dom.insertAfter(fragment, parentBlock);
  22904. trimInlineElementsOnLeftSideOfBlock(dom, nonEmptyElementsMap, newBlock);
  22905. addBrToBlockIfNeeded(dom, parentBlock);
  22906. if (dom.isEmpty(parentBlock)) {
  22907. emptyBlock(parentBlock);
  22908. }
  22909. newBlock.normalize();
  22910. if (dom.isEmpty(newBlock)) {
  22911. dom.remove(newBlock);
  22912. insertNewBlockAfter();
  22913. } else {
  22914. setForcedBlockAttrs(editor, newBlock);
  22915. moveToCaretPosition(editor, newBlock);
  22916. }
  22917. }
  22918. dom.setAttrib(newBlock, 'id', '');
  22919. editor.dispatch('NewBlock', { newBlock });
  22920. };
  22921. const fakeEventName$1 = 'insertParagraph';
  22922. const blockbreak = {
  22923. insert: insert$2,
  22924. fakeEventName: fakeEventName$1
  22925. };
  22926. const hasRightSideContent = (schema, container, parentBlock) => {
  22927. const walker = new DomTreeWalker(container, parentBlock);
  22928. let node;
  22929. const nonEmptyElementsMap = schema.getNonEmptyElements();
  22930. while (node = walker.next()) {
  22931. if (nonEmptyElementsMap[node.nodeName.toLowerCase()] || node.length > 0) {
  22932. return true;
  22933. }
  22934. }
  22935. };
  22936. const moveSelectionToBr = (editor, brElm, extraBr) => {
  22937. const rng = editor.dom.createRng();
  22938. if (!extraBr) {
  22939. rng.setStartAfter(brElm);
  22940. rng.setEndAfter(brElm);
  22941. } else {
  22942. rng.setStartBefore(brElm);
  22943. rng.setEndBefore(brElm);
  22944. }
  22945. editor.selection.setRng(rng);
  22946. scrollRangeIntoView(editor, rng);
  22947. };
  22948. const insertBrAtCaret = (editor, evt) => {
  22949. const selection = editor.selection;
  22950. const dom = editor.dom;
  22951. const rng = selection.getRng();
  22952. let brElm;
  22953. let extraBr;
  22954. normalize$2(dom, rng).each(normRng => {
  22955. rng.setStart(normRng.startContainer, normRng.startOffset);
  22956. rng.setEnd(normRng.endContainer, normRng.endOffset);
  22957. });
  22958. let offset = rng.startOffset;
  22959. let container = rng.startContainer;
  22960. if (container.nodeType === 1 && container.hasChildNodes()) {
  22961. const isAfterLastNodeInContainer = offset > container.childNodes.length - 1;
  22962. container = container.childNodes[Math.min(offset, container.childNodes.length - 1)] || container;
  22963. if (isAfterLastNodeInContainer && container.nodeType === 3) {
  22964. offset = container.nodeValue.length;
  22965. } else {
  22966. offset = 0;
  22967. }
  22968. }
  22969. let parentBlock = dom.getParent(container, dom.isBlock);
  22970. const containerBlock = parentBlock ? dom.getParent(parentBlock.parentNode, dom.isBlock) : null;
  22971. const containerBlockName = containerBlock ? containerBlock.nodeName.toUpperCase() : '';
  22972. const isControlKey = !!(evt && evt.ctrlKey);
  22973. if (containerBlockName === 'LI' && !isControlKey) {
  22974. parentBlock = containerBlock;
  22975. }
  22976. if (container && container.nodeType === 3 && offset >= container.nodeValue.length) {
  22977. if (!hasRightSideContent(editor.schema, container, parentBlock)) {
  22978. brElm = dom.create('br');
  22979. rng.insertNode(brElm);
  22980. rng.setStartAfter(brElm);
  22981. rng.setEndAfter(brElm);
  22982. extraBr = true;
  22983. }
  22984. }
  22985. brElm = dom.create('br');
  22986. rangeInsertNode(dom, rng, brElm);
  22987. moveSelectionToBr(editor, brElm, extraBr);
  22988. editor.undoManager.add();
  22989. };
  22990. const insertBrBefore = (editor, inline) => {
  22991. const br = SugarElement.fromTag('br');
  22992. before$3(SugarElement.fromDom(inline), br);
  22993. editor.undoManager.add();
  22994. };
  22995. const insertBrAfter = (editor, inline) => {
  22996. if (!hasBrAfter(editor.getBody(), inline)) {
  22997. after$4(SugarElement.fromDom(inline), SugarElement.fromTag('br'));
  22998. }
  22999. const br = SugarElement.fromTag('br');
  23000. after$4(SugarElement.fromDom(inline), br);
  23001. moveSelectionToBr(editor, br.dom, false);
  23002. editor.undoManager.add();
  23003. };
  23004. const isBeforeBr = pos => {
  23005. return isBr$6(pos.getNode());
  23006. };
  23007. const hasBrAfter = (rootNode, startNode) => {
  23008. if (isBeforeBr(CaretPosition.after(startNode))) {
  23009. return true;
  23010. } else {
  23011. return nextPosition(rootNode, CaretPosition.after(startNode)).map(pos => {
  23012. return isBr$6(pos.getNode());
  23013. }).getOr(false);
  23014. }
  23015. };
  23016. const isAnchorLink = elm => {
  23017. return elm && elm.nodeName === 'A' && 'href' in elm;
  23018. };
  23019. const isInsideAnchor = location => {
  23020. return location.fold(never, isAnchorLink, isAnchorLink, never);
  23021. };
  23022. const readInlineAnchorLocation = editor => {
  23023. const isInlineTarget$1 = curry(isInlineTarget, editor);
  23024. const position = CaretPosition.fromRangeStart(editor.selection.getRng());
  23025. return readLocation(isInlineTarget$1, editor.getBody(), position).filter(isInsideAnchor);
  23026. };
  23027. const insertBrOutsideAnchor = (editor, location) => {
  23028. location.fold(noop, curry(insertBrBefore, editor), curry(insertBrAfter, editor), noop);
  23029. };
  23030. const insert$1 = (editor, evt) => {
  23031. const anchorLocation = readInlineAnchorLocation(editor);
  23032. if (anchorLocation.isSome()) {
  23033. anchorLocation.each(curry(insertBrOutsideAnchor, editor));
  23034. } else {
  23035. insertBrAtCaret(editor, evt);
  23036. }
  23037. };
  23038. const fakeEventName = 'insertLineBreak';
  23039. const linebreak = {
  23040. insert: insert$1,
  23041. fakeEventName
  23042. };
  23043. const matchesSelector = (editor, selector) => {
  23044. return getParentBlock$1(editor).filter(parentBlock => {
  23045. return selector.length > 0 && is$1(SugarElement.fromDom(parentBlock), selector);
  23046. }).isSome();
  23047. };
  23048. const shouldInsertBr = editor => {
  23049. return matchesSelector(editor, getBrNewLineSelector(editor));
  23050. };
  23051. const shouldBlockNewLine$1 = editor => {
  23052. return matchesSelector(editor, getNoNewLineSelector(editor));
  23053. };
  23054. const newLineAction = Adt.generate([
  23055. { br: [] },
  23056. { block: [] },
  23057. { none: [] }
  23058. ]);
  23059. const shouldBlockNewLine = (editor, _shiftKey) => {
  23060. return shouldBlockNewLine$1(editor);
  23061. };
  23062. const inListBlock = requiredState => {
  23063. return (editor, _shiftKey) => {
  23064. return isListItemParentBlock(editor) === requiredState;
  23065. };
  23066. };
  23067. const inBlock = (blockName, requiredState) => (editor, _shiftKey) => {
  23068. const state = getParentBlockName(editor) === blockName.toUpperCase();
  23069. return state === requiredState;
  23070. };
  23071. const inPreBlock = requiredState => inBlock('pre', requiredState);
  23072. const inSummaryBlock = () => inBlock('summary', true);
  23073. const shouldPutBrInPre = requiredState => {
  23074. return (editor, _shiftKey) => {
  23075. return shouldPutBrInPre$1(editor) === requiredState;
  23076. };
  23077. };
  23078. const inBrContext = (editor, _shiftKey) => {
  23079. return shouldInsertBr(editor);
  23080. };
  23081. const hasShiftKey = (_editor, shiftKey) => {
  23082. return shiftKey;
  23083. };
  23084. const canInsertIntoEditableRoot = editor => {
  23085. const forcedRootBlock = getForcedRootBlock(editor);
  23086. const rootEditable = getEditableRoot$1(editor.dom, editor.selection.getStart());
  23087. return rootEditable && editor.schema.isValidChild(rootEditable.nodeName, forcedRootBlock);
  23088. };
  23089. const match = (predicates, action) => {
  23090. return (editor, shiftKey) => {
  23091. const isMatch = foldl(predicates, (res, p) => {
  23092. return res && p(editor, shiftKey);
  23093. }, true);
  23094. return isMatch ? Optional.some(action) : Optional.none();
  23095. };
  23096. };
  23097. const getAction = (editor, evt) => {
  23098. return evaluateUntil([
  23099. match([shouldBlockNewLine], newLineAction.none()),
  23100. match([inSummaryBlock()], newLineAction.br()),
  23101. match([
  23102. inPreBlock(true),
  23103. shouldPutBrInPre(false),
  23104. hasShiftKey
  23105. ], newLineAction.br()),
  23106. match([
  23107. inPreBlock(true),
  23108. shouldPutBrInPre(false)
  23109. ], newLineAction.block()),
  23110. match([
  23111. inPreBlock(true),
  23112. shouldPutBrInPre(true),
  23113. hasShiftKey
  23114. ], newLineAction.block()),
  23115. match([
  23116. inPreBlock(true),
  23117. shouldPutBrInPre(true)
  23118. ], newLineAction.br()),
  23119. match([
  23120. inListBlock(true),
  23121. hasShiftKey
  23122. ], newLineAction.br()),
  23123. match([inListBlock(true)], newLineAction.block()),
  23124. match([inBrContext], newLineAction.br()),
  23125. match([hasShiftKey], newLineAction.br()),
  23126. match([canInsertIntoEditableRoot], newLineAction.block())
  23127. ], [
  23128. editor,
  23129. !!(evt && evt.shiftKey)
  23130. ]).getOr(newLineAction.none());
  23131. };
  23132. const insertBreak = (breakType, editor, evt) => {
  23133. if (!editor.selection.isCollapsed()) {
  23134. execDeleteCommand(editor);
  23135. }
  23136. if (isNonNullable(evt)) {
  23137. const event = fireFakeBeforeInputEvent(editor, breakType.fakeEventName);
  23138. if (event.isDefaultPrevented()) {
  23139. return;
  23140. }
  23141. }
  23142. breakType.insert(editor, evt);
  23143. if (isNonNullable(evt)) {
  23144. fireFakeInputEvent(editor, breakType.fakeEventName);
  23145. }
  23146. };
  23147. const insert = (editor, evt) => {
  23148. const br = () => insertBreak(linebreak, editor, evt);
  23149. const block = () => insertBreak(blockbreak, editor, evt);
  23150. const logicalAction = getAction(editor, evt);
  23151. switch (getNewlineBehavior(editor)) {
  23152. case 'linebreak':
  23153. logicalAction.fold(br, br, noop);
  23154. break;
  23155. case 'block':
  23156. logicalAction.fold(block, block, noop);
  23157. break;
  23158. case 'invert':
  23159. logicalAction.fold(block, br, noop);
  23160. break;
  23161. default:
  23162. logicalAction.fold(br, block, noop);
  23163. break;
  23164. }
  23165. };
  23166. const handleEnterKeyEvent = (editor, event) => {
  23167. if (event.isDefaultPrevented()) {
  23168. return;
  23169. }
  23170. event.preventDefault();
  23171. endTypingLevelIgnoreLocks(editor.undoManager);
  23172. editor.undoManager.transact(() => {
  23173. insert(editor, event);
  23174. });
  23175. };
  23176. const setup$h = editor => {
  23177. editor.on('keydown', event => {
  23178. if (event.keyCode === VK.ENTER) {
  23179. handleEnterKeyEvent(editor, event);
  23180. }
  23181. });
  23182. };
  23183. const executeKeydownOverride$2 = (editor, caret, evt) => {
  23184. const isMac = Env.os.isMacOS() || Env.os.isiOS();
  23185. execute([
  23186. {
  23187. keyCode: VK.END,
  23188. action: action(moveToLineEndPoint$1, editor, true)
  23189. },
  23190. {
  23191. keyCode: VK.HOME,
  23192. action: action(moveToLineEndPoint$1, editor, false)
  23193. },
  23194. ...!isMac ? [
  23195. {
  23196. keyCode: VK.HOME,
  23197. action: action(selectToEndPoint, editor, false),
  23198. ctrlKey: true,
  23199. shiftKey: true
  23200. },
  23201. {
  23202. keyCode: VK.END,
  23203. action: action(selectToEndPoint, editor, true),
  23204. ctrlKey: true,
  23205. shiftKey: true
  23206. }
  23207. ] : [],
  23208. {
  23209. keyCode: VK.END,
  23210. action: action(moveToLineEndPoint, editor, true)
  23211. },
  23212. {
  23213. keyCode: VK.HOME,
  23214. action: action(moveToLineEndPoint, editor, false)
  23215. },
  23216. {
  23217. keyCode: VK.END,
  23218. action: action(moveToLineEndPoint$2, editor, true, caret)
  23219. },
  23220. {
  23221. keyCode: VK.HOME,
  23222. action: action(moveToLineEndPoint$2, editor, false, caret)
  23223. }
  23224. ], evt).each(_ => {
  23225. evt.preventDefault();
  23226. });
  23227. };
  23228. const setup$g = (editor, caret) => {
  23229. editor.on('keydown', evt => {
  23230. if (evt.isDefaultPrevented() === false) {
  23231. executeKeydownOverride$2(editor, caret, evt);
  23232. }
  23233. });
  23234. };
  23235. const setup$f = editor => {
  23236. editor.on('input', e => {
  23237. if (e.isComposing === false) {
  23238. normalizeNbspsInEditor(editor);
  23239. }
  23240. });
  23241. };
  23242. const platform = detect$2();
  23243. const executeKeyupAction = (editor, caret, evt) => {
  23244. execute([
  23245. {
  23246. keyCode: VK.PAGE_UP,
  23247. action: action(moveToLineEndPoint$2, editor, false, caret)
  23248. },
  23249. {
  23250. keyCode: VK.PAGE_DOWN,
  23251. action: action(moveToLineEndPoint$2, editor, true, caret)
  23252. }
  23253. ], evt);
  23254. };
  23255. const stopImmediatePropagation = e => e.stopImmediatePropagation();
  23256. const isPageUpDown = evt => evt.keyCode === VK.PAGE_UP || evt.keyCode === VK.PAGE_DOWN;
  23257. const setNodeChangeBlocker = (blocked, editor, block) => {
  23258. if (block && !blocked.get()) {
  23259. editor.on('NodeChange', stopImmediatePropagation, true);
  23260. } else if (!block && blocked.get()) {
  23261. editor.off('NodeChange', stopImmediatePropagation);
  23262. }
  23263. blocked.set(block);
  23264. };
  23265. const setup$e = (editor, caret) => {
  23266. if (platform.os.isMacOS()) {
  23267. return;
  23268. }
  23269. const blocked = Cell(false);
  23270. editor.on('keydown', evt => {
  23271. if (isPageUpDown(evt)) {
  23272. setNodeChangeBlocker(blocked, editor, true);
  23273. }
  23274. });
  23275. editor.on('keyup', evt => {
  23276. if (evt.isDefaultPrevented() === false) {
  23277. executeKeyupAction(editor, caret, evt);
  23278. }
  23279. if (isPageUpDown(evt) && blocked.get()) {
  23280. setNodeChangeBlocker(blocked, editor, false);
  23281. editor.nodeChanged();
  23282. }
  23283. });
  23284. };
  23285. const insertTextAtPosition = (text, pos) => {
  23286. const container = pos.container();
  23287. const offset = pos.offset();
  23288. if (isText$9(container)) {
  23289. container.insertData(offset, text);
  23290. return Optional.some(CaretPosition(container, offset + text.length));
  23291. } else {
  23292. return getElementFromPosition(pos).map(elm => {
  23293. const textNode = SugarElement.fromText(text);
  23294. if (pos.isAtEnd()) {
  23295. after$4(elm, textNode);
  23296. } else {
  23297. before$3(elm, textNode);
  23298. }
  23299. return CaretPosition(textNode.dom, text.length);
  23300. });
  23301. }
  23302. };
  23303. const insertNbspAtPosition = curry(insertTextAtPosition, nbsp);
  23304. const insertSpaceAtPosition = curry(insertTextAtPosition, ' ');
  23305. 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)));
  23306. const insertInlineBoundarySpaceOrNbsp = (root, pos) => checkPos => needsToHaveNbsp(root, checkPos) ? insertNbspAtPosition(pos) : insertSpaceAtPosition(pos);
  23307. const setSelection = editor => pos => {
  23308. editor.selection.setRng(pos.toRange());
  23309. editor.nodeChanged();
  23310. return true;
  23311. };
  23312. const insertSpaceOrNbspAtSelection = editor => {
  23313. const pos = CaretPosition.fromRangeStart(editor.selection.getRng());
  23314. const root = SugarElement.fromDom(editor.getBody());
  23315. if (editor.selection.isCollapsed()) {
  23316. const isInlineTarget$1 = curry(isInlineTarget, editor);
  23317. const caretPosition = CaretPosition.fromRangeStart(editor.selection.getRng());
  23318. return readLocation(isInlineTarget$1, editor.getBody(), caretPosition).bind(locationToCaretPosition(root)).map(checkPos => () => insertInlineBoundarySpaceOrNbsp(root, pos)(checkPos).each(setSelection(editor)));
  23319. } else {
  23320. return Optional.none();
  23321. }
  23322. };
  23323. const executeKeydownOverride$1 = (editor, evt) => {
  23324. executeWithDelayedAction([{
  23325. keyCode: VK.SPACEBAR,
  23326. action: action(insertSpaceOrNbspAtSelection, editor)
  23327. }], evt).each(applyAction => {
  23328. evt.preventDefault();
  23329. const event = fireFakeBeforeInputEvent(editor, 'insertText', { data: ' ' });
  23330. if (!event.isDefaultPrevented()) {
  23331. applyAction();
  23332. fireFakeInputEvent(editor, 'insertText', { data: ' ' });
  23333. }
  23334. });
  23335. };
  23336. const setup$d = editor => {
  23337. editor.on('keydown', evt => {
  23338. if (evt.isDefaultPrevented() === false) {
  23339. executeKeydownOverride$1(editor, evt);
  23340. }
  23341. });
  23342. };
  23343. const tableTabNavigation = editor => {
  23344. if (hasTableTabNavigation(editor)) {
  23345. return [
  23346. {
  23347. keyCode: VK.TAB,
  23348. action: action(handleTab, editor, true)
  23349. },
  23350. {
  23351. keyCode: VK.TAB,
  23352. shiftKey: true,
  23353. action: action(handleTab, editor, false)
  23354. }
  23355. ];
  23356. } else {
  23357. return [];
  23358. }
  23359. };
  23360. const executeKeydownOverride = (editor, evt) => {
  23361. execute([...tableTabNavigation(editor)], evt).each(_ => {
  23362. evt.preventDefault();
  23363. });
  23364. };
  23365. const setup$c = editor => {
  23366. editor.on('keydown', evt => {
  23367. if (evt.isDefaultPrevented() === false) {
  23368. executeKeydownOverride(editor, evt);
  23369. }
  23370. });
  23371. };
  23372. const setup$b = editor => {
  23373. editor.addShortcut('Meta+P', '', 'mcePrint');
  23374. setup$j(editor);
  23375. if (isRtc(editor)) {
  23376. return Cell(null);
  23377. } else {
  23378. const caret = setupSelectedState(editor);
  23379. setup$l(editor);
  23380. setup$k(editor, caret);
  23381. setup$i(editor, caret);
  23382. setup$h(editor);
  23383. setup$d(editor);
  23384. setup$f(editor);
  23385. setup$c(editor);
  23386. setup$g(editor, caret);
  23387. setup$e(editor, caret);
  23388. return caret;
  23389. }
  23390. };
  23391. class NodeChange {
  23392. constructor(editor) {
  23393. this.lastPath = [];
  23394. this.editor = editor;
  23395. let lastRng;
  23396. const self = this;
  23397. if (!('onselectionchange' in editor.getDoc())) {
  23398. editor.on('NodeChange click mouseup keyup focus', e => {
  23399. const nativeRng = editor.selection.getRng();
  23400. const fakeRng = {
  23401. startContainer: nativeRng.startContainer,
  23402. startOffset: nativeRng.startOffset,
  23403. endContainer: nativeRng.endContainer,
  23404. endOffset: nativeRng.endOffset
  23405. };
  23406. if (e.type === 'nodechange' || !isEq$4(fakeRng, lastRng)) {
  23407. editor.dispatch('SelectionChange');
  23408. }
  23409. lastRng = fakeRng;
  23410. });
  23411. }
  23412. editor.on('contextmenu', () => {
  23413. editor.dispatch('SelectionChange');
  23414. });
  23415. editor.on('SelectionChange', () => {
  23416. const startElm = editor.selection.getStart(true);
  23417. if (!startElm) {
  23418. return;
  23419. }
  23420. if (hasAnyRanges(editor) && !self.isSameElementPath(startElm) && editor.dom.isChildOf(startElm, editor.getBody())) {
  23421. editor.nodeChanged({ selectionChange: true });
  23422. }
  23423. });
  23424. editor.on('mouseup', e => {
  23425. if (!e.isDefaultPrevented() && hasAnyRanges(editor)) {
  23426. if (editor.selection.getNode().nodeName === 'IMG') {
  23427. Delay.setEditorTimeout(editor, () => {
  23428. editor.nodeChanged();
  23429. });
  23430. } else {
  23431. editor.nodeChanged();
  23432. }
  23433. }
  23434. });
  23435. }
  23436. nodeChanged(args) {
  23437. const selection = this.editor.selection;
  23438. let node, parents, root;
  23439. if (this.editor.initialized && selection && !shouldDisableNodeChange(this.editor) && !this.editor.mode.isReadOnly()) {
  23440. root = this.editor.getBody();
  23441. node = selection.getStart(true) || root;
  23442. if (node.ownerDocument !== this.editor.getDoc() || !this.editor.dom.isChildOf(node, root)) {
  23443. node = root;
  23444. }
  23445. parents = [];
  23446. this.editor.dom.getParent(node, node => {
  23447. if (node === root) {
  23448. return true;
  23449. }
  23450. parents.push(node);
  23451. });
  23452. args = args || {};
  23453. args.element = node;
  23454. args.parents = parents;
  23455. this.editor.dispatch('NodeChange', args);
  23456. }
  23457. }
  23458. isSameElementPath(startElm) {
  23459. let i;
  23460. const editor = this.editor;
  23461. const currentPath = reverse(editor.dom.getParents(startElm, always, editor.getBody()));
  23462. if (currentPath.length === this.lastPath.length) {
  23463. for (i = currentPath.length; i >= 0; i--) {
  23464. if (currentPath[i] !== this.lastPath[i]) {
  23465. break;
  23466. }
  23467. }
  23468. if (i === -1) {
  23469. this.lastPath = currentPath;
  23470. return true;
  23471. }
  23472. }
  23473. this.lastPath = currentPath;
  23474. return false;
  23475. }
  23476. }
  23477. const internalMimeType = 'x-tinymce/html';
  23478. const internalHtmlMime = constant(internalMimeType);
  23479. const internalMark = '<!-- ' + internalMimeType + ' -->';
  23480. const mark = html => internalMark + html;
  23481. const unmark = html => html.replace(internalMark, '');
  23482. const isMarked = html => html.indexOf(internalMark) !== -1;
  23483. const isPlainText = text => {
  23484. return !/<(?:\/?(?!(?:div|p|br|span)>)\w+|(?:(?!(?:span style="white-space:\s?pre;?">)|br\s?\/>))\w+\s[^>]+)>/i.test(text);
  23485. };
  23486. const openContainer = (rootTag, rootAttrs) => {
  23487. let tag = '<' + rootTag;
  23488. const attrs = mapToArray(rootAttrs, (value, key) => key + '="' + Entities.encodeAllRaw(value) + '"');
  23489. if (attrs.length) {
  23490. tag += ' ' + attrs.join(' ');
  23491. }
  23492. return tag + '>';
  23493. };
  23494. const toBlockElements = (text, rootTag, rootAttrs) => {
  23495. const blocks = text.split(/\n\n/);
  23496. const tagOpen = openContainer(rootTag, rootAttrs);
  23497. const tagClose = '</' + rootTag + '>';
  23498. const paragraphs = map$3(blocks, p => {
  23499. return p.split(/\n/).join('<br />');
  23500. });
  23501. const stitch = p => {
  23502. return tagOpen + p + tagClose;
  23503. };
  23504. return paragraphs.length === 1 ? paragraphs[0] : map$3(paragraphs, stitch).join('');
  23505. };
  23506. const pasteBinDefaultContent = '%MCEPASTEBIN%';
  23507. const create$6 = (editor, lastRngCell) => {
  23508. const {dom, selection} = editor;
  23509. const body = editor.getBody();
  23510. lastRngCell.set(selection.getRng());
  23511. const pasteBinElm = dom.add(editor.getBody(), 'div', {
  23512. 'id': 'mcepastebin',
  23513. 'class': 'mce-pastebin',
  23514. 'contentEditable': true,
  23515. 'data-mce-bogus': 'all',
  23516. 'style': 'position: fixed; top: 50%; width: 10px; height: 10px; overflow: hidden; opacity: 0'
  23517. }, pasteBinDefaultContent);
  23518. if (Env.browser.isFirefox()) {
  23519. dom.setStyle(pasteBinElm, 'left', dom.getStyle(body, 'direction', true) === 'rtl' ? 65535 : -65535);
  23520. }
  23521. dom.bind(pasteBinElm, 'beforedeactivate focusin focusout', e => {
  23522. e.stopPropagation();
  23523. });
  23524. pasteBinElm.focus();
  23525. selection.select(pasteBinElm, true);
  23526. };
  23527. const remove = (editor, lastRngCell) => {
  23528. const dom = editor.dom;
  23529. if (getEl(editor)) {
  23530. let pasteBinClone;
  23531. const lastRng = lastRngCell.get();
  23532. while (pasteBinClone = getEl(editor)) {
  23533. dom.remove(pasteBinClone);
  23534. dom.unbind(pasteBinClone);
  23535. }
  23536. if (lastRng) {
  23537. editor.selection.setRng(lastRng);
  23538. }
  23539. }
  23540. lastRngCell.set(null);
  23541. };
  23542. const getEl = editor => editor.dom.get('mcepastebin');
  23543. const isPasteBin = elm => elm && elm.id === 'mcepastebin';
  23544. const getHtml = editor => {
  23545. const dom = editor.dom;
  23546. const copyAndRemove = (toElm, fromElm) => {
  23547. toElm.appendChild(fromElm);
  23548. dom.remove(fromElm, true);
  23549. };
  23550. const [pasteBinElm, ...pasteBinClones] = filter$6(editor.getBody().childNodes, isPasteBin);
  23551. each$f(pasteBinClones, pasteBinClone => {
  23552. copyAndRemove(pasteBinElm, pasteBinClone);
  23553. });
  23554. const dirtyWrappers = dom.select('div[id=mcepastebin]', pasteBinElm);
  23555. for (let i = dirtyWrappers.length - 1; i >= 0; i--) {
  23556. const cleanWrapper = dom.create('div');
  23557. pasteBinElm.insertBefore(cleanWrapper, dirtyWrappers[i]);
  23558. copyAndRemove(cleanWrapper, dirtyWrappers[i]);
  23559. }
  23560. return pasteBinElm ? pasteBinElm.innerHTML : '';
  23561. };
  23562. const isDefaultPasteBinContent = content => content === pasteBinDefaultContent;
  23563. const PasteBin = editor => {
  23564. const lastRng = Cell(null);
  23565. return {
  23566. create: () => create$6(editor, lastRng),
  23567. remove: () => remove(editor, lastRng),
  23568. getEl: () => getEl(editor),
  23569. getHtml: () => getHtml(editor),
  23570. getLastRng: lastRng.get
  23571. };
  23572. };
  23573. const filter = (content, items) => {
  23574. Tools.each(items, v => {
  23575. if (is$4(v, RegExp)) {
  23576. content = content.replace(v, '');
  23577. } else {
  23578. content = content.replace(v[0], v[1]);
  23579. }
  23580. });
  23581. return content;
  23582. };
  23583. const innerText = html => {
  23584. const schema = Schema();
  23585. const domParser = DomParser({}, schema);
  23586. let text = '';
  23587. const voidElements = schema.getVoidElements();
  23588. const ignoreElements = Tools.makeMap('script noscript style textarea video audio iframe object', ' ');
  23589. const blockElements = schema.getBlockElements();
  23590. const walk = node => {
  23591. const name = node.name, currentNode = node;
  23592. if (name === 'br') {
  23593. text += '\n';
  23594. return;
  23595. }
  23596. if (name === 'wbr') {
  23597. return;
  23598. }
  23599. if (voidElements[name]) {
  23600. text += ' ';
  23601. }
  23602. if (ignoreElements[name]) {
  23603. text += ' ';
  23604. return;
  23605. }
  23606. if (node.type === 3) {
  23607. text += node.value;
  23608. }
  23609. if (!(node.name in schema.getVoidElements())) {
  23610. if (node = node.firstChild) {
  23611. do {
  23612. walk(node);
  23613. } while (node = node.next);
  23614. }
  23615. }
  23616. if (blockElements[name] && currentNode.next) {
  23617. text += '\n';
  23618. if (name === 'p') {
  23619. text += '\n';
  23620. }
  23621. }
  23622. };
  23623. html = filter(html, [/<!\[[^\]]+\]>/g]);
  23624. walk(domParser.parse(html));
  23625. return text;
  23626. };
  23627. const trimHtml = html => {
  23628. const trimSpaces = (all, s1, s2) => {
  23629. if (!s1 && !s2) {
  23630. return ' ';
  23631. }
  23632. return nbsp;
  23633. };
  23634. html = filter(html, [
  23635. /^[\s\S]*<body[^>]*>\s*|\s*<\/body[^>]*>[\s\S]*$/ig,
  23636. /<!--StartFragment-->|<!--EndFragment-->/g,
  23637. [
  23638. /( ?)<span class="Apple-converted-space">\u00a0<\/span>( ?)/g,
  23639. trimSpaces
  23640. ],
  23641. /<br class="Apple-interchange-newline">/g,
  23642. /<br>$/i
  23643. ]);
  23644. return html;
  23645. };
  23646. const createIdGenerator = prefix => {
  23647. let count = 0;
  23648. return () => {
  23649. return prefix + count++;
  23650. };
  23651. };
  23652. const getImageMimeType = ext => {
  23653. const lowerExt = ext.toLowerCase();
  23654. const mimeOverrides = {
  23655. jpg: 'jpeg',
  23656. jpe: 'jpeg',
  23657. jfi: 'jpeg',
  23658. jif: 'jpeg',
  23659. jfif: 'jpeg',
  23660. pjpeg: 'jpeg',
  23661. pjp: 'jpeg',
  23662. svg: 'svg+xml'
  23663. };
  23664. return Tools.hasOwn(mimeOverrides, lowerExt) ? 'image/' + mimeOverrides[lowerExt] : 'image/' + lowerExt;
  23665. };
  23666. const preProcess = (editor, html) => {
  23667. const parser = DomParser({}, editor.schema);
  23668. parser.addNodeFilter('meta', nodes => {
  23669. Tools.each(nodes, node => {
  23670. node.remove();
  23671. });
  23672. });
  23673. const fragment = parser.parse(html, {
  23674. forced_root_block: false,
  23675. isRootContent: true
  23676. });
  23677. return HtmlSerializer({ validate: true }, editor.schema).serialize(fragment);
  23678. };
  23679. const processResult = (content, cancelled) => ({
  23680. content,
  23681. cancelled
  23682. });
  23683. const postProcessFilter = (editor, html, internal) => {
  23684. const tempBody = editor.dom.create('div', { style: 'display:none' }, html);
  23685. const postProcessArgs = firePastePostProcess(editor, tempBody, internal);
  23686. return processResult(postProcessArgs.node.innerHTML, postProcessArgs.isDefaultPrevented());
  23687. };
  23688. const filterContent = (editor, content, internal) => {
  23689. const preProcessArgs = firePastePreProcess(editor, content, internal);
  23690. const filteredContent = preProcess(editor, preProcessArgs.content);
  23691. if (editor.hasEventListeners('PastePostProcess') && !preProcessArgs.isDefaultPrevented()) {
  23692. return postProcessFilter(editor, filteredContent, internal);
  23693. } else {
  23694. return processResult(filteredContent, preProcessArgs.isDefaultPrevented());
  23695. }
  23696. };
  23697. const process = (editor, html, internal) => {
  23698. return filterContent(editor, html, internal);
  23699. };
  23700. const pasteHtml$1 = (editor, html) => {
  23701. editor.insertContent(html, {
  23702. merge: shouldPasteMergeFormats(editor),
  23703. paste: true
  23704. });
  23705. return true;
  23706. };
  23707. const isAbsoluteUrl = url => /^https?:\/\/[\w\-\/+=.,!;:&%@^~(){}?#]+$/i.test(url);
  23708. const isImageUrl = (editor, url) => {
  23709. return isAbsoluteUrl(url) && exists(getAllowedImageFileTypes(editor), type => endsWith(url.toLowerCase(), `.${ type.toLowerCase() }`));
  23710. };
  23711. const createImage = (editor, url, pasteHtmlFn) => {
  23712. editor.undoManager.extra(() => {
  23713. pasteHtmlFn(editor, url);
  23714. }, () => {
  23715. editor.insertContent('<img src="' + url + '">');
  23716. });
  23717. return true;
  23718. };
  23719. const createLink = (editor, url, pasteHtmlFn) => {
  23720. editor.undoManager.extra(() => {
  23721. pasteHtmlFn(editor, url);
  23722. }, () => {
  23723. editor.execCommand('mceInsertLink', false, url);
  23724. });
  23725. return true;
  23726. };
  23727. const linkSelection = (editor, html, pasteHtmlFn) => !editor.selection.isCollapsed() && isAbsoluteUrl(html) ? createLink(editor, html, pasteHtmlFn) : false;
  23728. const insertImage = (editor, html, pasteHtmlFn) => isImageUrl(editor, html) ? createImage(editor, html, pasteHtmlFn) : false;
  23729. const smartInsertContent = (editor, html) => {
  23730. Tools.each([
  23731. linkSelection,
  23732. insertImage,
  23733. pasteHtml$1
  23734. ], action => {
  23735. return action(editor, html, pasteHtml$1) !== true;
  23736. });
  23737. };
  23738. const insertContent = (editor, html, pasteAsText) => {
  23739. if (pasteAsText || !isSmartPasteEnabled(editor)) {
  23740. pasteHtml$1(editor, html);
  23741. } else {
  23742. smartInsertContent(editor, html);
  23743. }
  23744. };
  23745. const uniqueId = createIdGenerator('mceclip');
  23746. const doPaste = (editor, content, internal, pasteAsText) => {
  23747. const args = process(editor, content, internal);
  23748. if (args.cancelled === false) {
  23749. insertContent(editor, args.content, pasteAsText);
  23750. }
  23751. };
  23752. const pasteHtml = (editor, html, internalFlag) => {
  23753. const internal = internalFlag ? internalFlag : isMarked(html);
  23754. doPaste(editor, unmark(html), internal, false);
  23755. };
  23756. const pasteText = (editor, text) => {
  23757. const encodedText = editor.dom.encode(text).replace(/\r\n/g, '\n');
  23758. const normalizedText = normalize$4(encodedText, getPasteTabSpaces(editor));
  23759. const html = toBlockElements(normalizedText, getForcedRootBlock(editor), getForcedRootBlockAttrs(editor));
  23760. doPaste(editor, html, false, true);
  23761. };
  23762. const getDataTransferItems = dataTransfer => {
  23763. const items = {};
  23764. if (dataTransfer && dataTransfer.types) {
  23765. for (let i = 0; i < dataTransfer.types.length; i++) {
  23766. const contentType = dataTransfer.types[i];
  23767. try {
  23768. items[contentType] = dataTransfer.getData(contentType);
  23769. } catch (ex) {
  23770. items[contentType] = '';
  23771. }
  23772. }
  23773. }
  23774. return items;
  23775. };
  23776. const hasContentType = (clipboardContent, mimeType) => mimeType in clipboardContent && clipboardContent[mimeType].length > 0;
  23777. const hasHtmlOrText = content => hasContentType(content, 'text/html') || hasContentType(content, 'text/plain');
  23778. const extractFilename = (editor, str) => {
  23779. const m = str.match(/([\s\S]+?)(?:\.[a-z0-9.]+)$/i);
  23780. return isNonNullable(m) ? editor.dom.encode(m[1]) : null;
  23781. };
  23782. const createBlobInfo = (editor, blobCache, file, base64) => {
  23783. const id = uniqueId();
  23784. const useFileName = shouldReuseFileName(editor) && isNonNullable(file.name);
  23785. const name = useFileName ? extractFilename(editor, file.name) : id;
  23786. const filename = useFileName ? file.name : undefined;
  23787. const blobInfo = blobCache.create(id, file, base64, name, filename);
  23788. blobCache.add(blobInfo);
  23789. return blobInfo;
  23790. };
  23791. const pasteImage = (editor, imageItem) => {
  23792. parseDataUri(imageItem.uri).each(({data, type, base64Encoded}) => {
  23793. const base64 = base64Encoded ? data : btoa(data);
  23794. const file = imageItem.file;
  23795. const blobCache = editor.editorUpload.blobCache;
  23796. const existingBlobInfo = blobCache.getByData(base64, type);
  23797. const blobInfo = existingBlobInfo !== null && existingBlobInfo !== void 0 ? existingBlobInfo : createBlobInfo(editor, blobCache, file, base64);
  23798. pasteHtml(editor, `<img src="${ blobInfo.blobUri() }">`, false);
  23799. });
  23800. };
  23801. const isClipboardEvent = event => event.type === 'paste';
  23802. const readFilesAsDataUris = items => Promise.all(map$3(items, file => {
  23803. return blobToDataUri(file).then(uri => ({
  23804. file,
  23805. uri
  23806. }));
  23807. }));
  23808. const isImage = editor => {
  23809. const allowedExtensions = getAllowedImageFileTypes(editor);
  23810. return file => startsWith(file.type, 'image/') && exists(allowedExtensions, extension => {
  23811. return getImageMimeType(extension) === file.type;
  23812. });
  23813. };
  23814. const getImagesFromDataTransfer = (editor, dataTransfer) => {
  23815. const items = dataTransfer.items ? bind$3(from(dataTransfer.items), item => {
  23816. return item.kind === 'file' ? [item.getAsFile()] : [];
  23817. }) : [];
  23818. const files = dataTransfer.files ? from(dataTransfer.files) : [];
  23819. return filter$6(items.length > 0 ? items : files, isImage(editor));
  23820. };
  23821. const pasteImageData = (editor, e, rng) => {
  23822. const dataTransfer = isClipboardEvent(e) ? e.clipboardData : e.dataTransfer;
  23823. if (shouldPasteDataImages(editor) && dataTransfer) {
  23824. const images = getImagesFromDataTransfer(editor, dataTransfer);
  23825. if (images.length > 0) {
  23826. e.preventDefault();
  23827. readFilesAsDataUris(images).then(fileResults => {
  23828. if (rng) {
  23829. editor.selection.setRng(rng);
  23830. }
  23831. each$f(fileResults, result => {
  23832. pasteImage(editor, result);
  23833. });
  23834. });
  23835. return true;
  23836. }
  23837. }
  23838. return false;
  23839. };
  23840. const isBrokenAndroidClipboardEvent = e => {
  23841. var _a, _b;
  23842. 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;
  23843. };
  23844. const isKeyboardPasteEvent = e => VK.metaKeyPressed(e) && e.keyCode === 86 || e.shiftKey && e.keyCode === 45;
  23845. const insertClipboardContent = (editor, clipboardContent, html, plainTextMode) => {
  23846. let content = trimHtml(html);
  23847. const isInternal = hasContentType(clipboardContent, internalHtmlMime()) || isMarked(html);
  23848. const isPlainTextHtml = !isInternal && isPlainText(content);
  23849. const isAbsoluteUrl$1 = isAbsoluteUrl(content);
  23850. if (isDefaultPasteBinContent(content) || !content.length || isPlainTextHtml && !isAbsoluteUrl$1) {
  23851. plainTextMode = true;
  23852. }
  23853. if (plainTextMode || isAbsoluteUrl$1) {
  23854. if (hasContentType(clipboardContent, 'text/plain') && isPlainTextHtml) {
  23855. content = clipboardContent['text/plain'];
  23856. } else {
  23857. content = innerText(content);
  23858. }
  23859. }
  23860. if (isDefaultPasteBinContent(content)) {
  23861. return;
  23862. }
  23863. if (plainTextMode) {
  23864. pasteText(editor, content);
  23865. } else {
  23866. pasteHtml(editor, content, isInternal);
  23867. }
  23868. };
  23869. const registerEventHandlers = (editor, pasteBin, pasteFormat) => {
  23870. let keyboardPastePlainTextState;
  23871. const getLastRng = () => pasteBin.getLastRng() || editor.selection.getRng();
  23872. editor.on('keydown', e => {
  23873. if (isKeyboardPasteEvent(e) && !e.isDefaultPrevented()) {
  23874. keyboardPastePlainTextState = e.shiftKey && e.keyCode === 86;
  23875. }
  23876. });
  23877. editor.on('paste', e => {
  23878. if (e.isDefaultPrevented() || isBrokenAndroidClipboardEvent(e)) {
  23879. return;
  23880. }
  23881. const plainTextMode = pasteFormat.get() === 'text' || keyboardPastePlainTextState;
  23882. keyboardPastePlainTextState = false;
  23883. const clipboardContent = getDataTransferItems(e.clipboardData);
  23884. if (!hasHtmlOrText(clipboardContent) && pasteImageData(editor, e, getLastRng())) {
  23885. return;
  23886. }
  23887. if (hasContentType(clipboardContent, 'text/html')) {
  23888. e.preventDefault();
  23889. insertClipboardContent(editor, clipboardContent, clipboardContent['text/html'], plainTextMode);
  23890. } else {
  23891. pasteBin.create();
  23892. Delay.setEditorTimeout(editor, () => {
  23893. const html = pasteBin.getHtml();
  23894. pasteBin.remove();
  23895. insertClipboardContent(editor, clipboardContent, html, plainTextMode);
  23896. }, 0);
  23897. }
  23898. });
  23899. };
  23900. const registerDataImageFilter = editor => {
  23901. const isWebKitFakeUrl = src => startsWith(src, 'webkit-fake-url');
  23902. const isDataUri = src => startsWith(src, 'data:');
  23903. const isPasteInsert = args => {
  23904. var _a;
  23905. return ((_a = args.data) === null || _a === void 0 ? void 0 : _a.paste) === true;
  23906. };
  23907. editor.parser.addNodeFilter('img', (nodes, name, args) => {
  23908. if (!shouldPasteDataImages(editor) && isPasteInsert(args)) {
  23909. for (const node of nodes) {
  23910. const src = node.attr('src');
  23911. if (isString(src) && !node.attr('data-mce-object') && src !== Env.transparentSrc) {
  23912. if (isWebKitFakeUrl(src)) {
  23913. node.remove();
  23914. } else if (!shouldAllowHtmlDataUrls(editor) && isDataUri(src)) {
  23915. node.remove();
  23916. }
  23917. }
  23918. }
  23919. }
  23920. });
  23921. };
  23922. const registerEventsAndFilters = (editor, pasteBin, pasteFormat) => {
  23923. registerEventHandlers(editor, pasteBin, pasteFormat);
  23924. registerDataImageFilter(editor);
  23925. };
  23926. const togglePlainTextPaste = (editor, pasteFormat) => {
  23927. if (pasteFormat.get() === 'text') {
  23928. pasteFormat.set('html');
  23929. firePastePlainTextToggle(editor, false);
  23930. } else {
  23931. pasteFormat.set('text');
  23932. firePastePlainTextToggle(editor, true);
  23933. }
  23934. editor.focus();
  23935. };
  23936. const register$1 = (editor, pasteFormat) => {
  23937. editor.addCommand('mceTogglePlainTextPaste', () => {
  23938. togglePlainTextPaste(editor, pasteFormat);
  23939. });
  23940. editor.addCommand('mceInsertClipboardContent', (ui, value) => {
  23941. if (value.html) {
  23942. pasteHtml(editor, value.html, value.internal);
  23943. }
  23944. if (value.text) {
  23945. pasteText(editor, value.text);
  23946. }
  23947. });
  23948. };
  23949. const setHtml5Clipboard = (clipboardData, html, text) => {
  23950. try {
  23951. clipboardData.clearData();
  23952. clipboardData.setData('text/html', html);
  23953. clipboardData.setData('text/plain', text);
  23954. clipboardData.setData(internalHtmlMime(), html);
  23955. return true;
  23956. } catch (e) {
  23957. return false;
  23958. }
  23959. };
  23960. const setClipboardData = (evt, data, fallback, done) => {
  23961. if (setHtml5Clipboard(evt.clipboardData, data.html, data.text)) {
  23962. evt.preventDefault();
  23963. done();
  23964. } else {
  23965. fallback(data.html, done);
  23966. }
  23967. };
  23968. const fallback = editor => (html, done) => {
  23969. const {dom, selection} = editor;
  23970. const outer = dom.create('div', {
  23971. 'contenteditable': 'false',
  23972. 'data-mce-bogus': 'all'
  23973. });
  23974. const inner = dom.create('div', { contenteditable: 'true' }, html);
  23975. dom.setStyles(outer, {
  23976. position: 'fixed',
  23977. top: '0',
  23978. left: '-3000px',
  23979. width: '1000px',
  23980. overflow: 'hidden'
  23981. });
  23982. outer.appendChild(inner);
  23983. dom.add(editor.getBody(), outer);
  23984. const range = selection.getRng();
  23985. inner.focus();
  23986. const offscreenRange = dom.createRng();
  23987. offscreenRange.selectNodeContents(inner);
  23988. selection.setRng(offscreenRange);
  23989. Delay.setEditorTimeout(editor, () => {
  23990. selection.setRng(range);
  23991. dom.remove(outer);
  23992. done();
  23993. }, 0);
  23994. };
  23995. const getData = editor => ({
  23996. html: mark(editor.selection.getContent({ contextual: true })),
  23997. text: editor.selection.getContent({ format: 'text' })
  23998. });
  23999. const isTableSelection = editor => !!editor.dom.getParent(editor.selection.getStart(), 'td[data-mce-selected],th[data-mce-selected]', editor.getBody());
  24000. const hasSelectedContent = editor => !editor.selection.isCollapsed() || isTableSelection(editor);
  24001. const cut = editor => evt => {
  24002. if (!evt.isDefaultPrevented() && hasSelectedContent(editor)) {
  24003. setClipboardData(evt, getData(editor), fallback(editor), () => {
  24004. if (Env.browser.isChromium() || Env.browser.isFirefox()) {
  24005. const rng = editor.selection.getRng();
  24006. Delay.setEditorTimeout(editor, () => {
  24007. editor.selection.setRng(rng);
  24008. editor.execCommand('Delete');
  24009. }, 0);
  24010. } else {
  24011. editor.execCommand('Delete');
  24012. }
  24013. });
  24014. }
  24015. };
  24016. const copy = editor => evt => {
  24017. if (!evt.isDefaultPrevented() && hasSelectedContent(editor)) {
  24018. setClipboardData(evt, getData(editor), fallback(editor), noop);
  24019. }
  24020. };
  24021. const register = editor => {
  24022. editor.on('cut', cut(editor));
  24023. editor.on('copy', copy(editor));
  24024. };
  24025. const getCaretRangeFromEvent = (editor, e) => {
  24026. var _a, _b;
  24027. return RangeUtils.getCaretRangeFromPoint((_a = e.clientX) !== null && _a !== void 0 ? _a : 0, (_b = e.clientY) !== null && _b !== void 0 ? _b : 0, editor.getDoc());
  24028. };
  24029. const isPlainTextFileUrl = content => {
  24030. const plainTextContent = content['text/plain'];
  24031. return plainTextContent ? plainTextContent.indexOf('file://') === 0 : false;
  24032. };
  24033. const setFocusedRange = (editor, rng) => {
  24034. editor.focus();
  24035. if (rng) {
  24036. editor.selection.setRng(rng);
  24037. }
  24038. };
  24039. const hasImage = dataTransfer => exists(dataTransfer.files, file => /^image\//.test(file.type));
  24040. const setup$a = (editor, draggingInternallyState) => {
  24041. if (shouldPasteBlockDrop(editor)) {
  24042. editor.on('dragend dragover draggesture dragdrop drop drag', e => {
  24043. e.preventDefault();
  24044. e.stopPropagation();
  24045. });
  24046. }
  24047. if (!shouldPasteDataImages(editor)) {
  24048. editor.on('drop', e => {
  24049. const dataTransfer = e.dataTransfer;
  24050. if (dataTransfer && hasImage(dataTransfer)) {
  24051. e.preventDefault();
  24052. }
  24053. });
  24054. }
  24055. editor.on('drop', e => {
  24056. if (e.isDefaultPrevented() || draggingInternallyState.get()) {
  24057. return;
  24058. }
  24059. const rng = getCaretRangeFromEvent(editor, e);
  24060. if (isNullable(rng)) {
  24061. return;
  24062. }
  24063. const dropContent = getDataTransferItems(e.dataTransfer);
  24064. const internal = hasContentType(dropContent, internalHtmlMime());
  24065. if ((!hasHtmlOrText(dropContent) || isPlainTextFileUrl(dropContent)) && pasteImageData(editor, e, rng)) {
  24066. return;
  24067. }
  24068. const internalContent = dropContent[internalHtmlMime()];
  24069. const content = internalContent || dropContent['text/html'] || dropContent['text/plain'];
  24070. if (content) {
  24071. e.preventDefault();
  24072. Delay.setEditorTimeout(editor, () => {
  24073. editor.undoManager.transact(() => {
  24074. if (internalContent) {
  24075. editor.execCommand('Delete');
  24076. }
  24077. setFocusedRange(editor, rng);
  24078. const trimmedContent = trimHtml(content);
  24079. if (dropContent['text/html']) {
  24080. pasteHtml(editor, trimmedContent, internal);
  24081. } else {
  24082. pasteText(editor, trimmedContent);
  24083. }
  24084. });
  24085. });
  24086. }
  24087. });
  24088. editor.on('dragstart', _e => {
  24089. draggingInternallyState.set(true);
  24090. });
  24091. editor.on('dragover dragend', e => {
  24092. if (shouldPasteDataImages(editor) && draggingInternallyState.get() === false) {
  24093. e.preventDefault();
  24094. setFocusedRange(editor, getCaretRangeFromEvent(editor, e));
  24095. }
  24096. if (e.type === 'dragend') {
  24097. draggingInternallyState.set(false);
  24098. }
  24099. });
  24100. };
  24101. const setup$9 = editor => {
  24102. const processEvent = f => e => {
  24103. f(editor, e);
  24104. };
  24105. const preProcess = getPastePreProcess(editor);
  24106. if (isFunction(preProcess)) {
  24107. editor.on('PastePreProcess', processEvent(preProcess));
  24108. }
  24109. const postProcess = getPastePostProcess(editor);
  24110. if (isFunction(postProcess)) {
  24111. editor.on('PastePostProcess', processEvent(postProcess));
  24112. }
  24113. };
  24114. const addPreProcessFilter = (editor, filterFunc) => {
  24115. editor.on('PastePreProcess', e => {
  24116. e.content = filterFunc(editor, e.content, e.internal);
  24117. });
  24118. };
  24119. const rgbRegExp = /rgb\s*\(\s*([0-9]+)\s*,\s*([0-9]+)\s*,\s*([0-9]+)\s*\)/gi;
  24120. const rgbToHex = value => Tools.trim(value).replace(rgbRegExp, rgbaToHexString).toLowerCase();
  24121. const removeWebKitStyles = (editor, content, internal) => {
  24122. const webKitStylesOption = getPasteWebkitStyles(editor);
  24123. if (internal || webKitStylesOption === 'all' || !shouldPasteRemoveWebKitStyles(editor)) {
  24124. return content;
  24125. }
  24126. const webKitStyles = webKitStylesOption ? webKitStylesOption.split(/[, ]/) : [];
  24127. if (webKitStyles && webKitStylesOption !== 'none') {
  24128. const dom = editor.dom, node = editor.selection.getNode();
  24129. content = content.replace(/(<[^>]+) style="([^"]*)"([^>]*>)/gi, (all, before, value, after) => {
  24130. const inputStyles = dom.parseStyle(dom.decode(value));
  24131. const outputStyles = {};
  24132. for (let i = 0; i < webKitStyles.length; i++) {
  24133. const inputValue = inputStyles[webKitStyles[i]];
  24134. let compareInput = inputValue;
  24135. let currentValue = dom.getStyle(node, webKitStyles[i], true);
  24136. if (/color/.test(webKitStyles[i])) {
  24137. compareInput = rgbToHex(compareInput);
  24138. currentValue = rgbToHex(currentValue);
  24139. }
  24140. if (currentValue !== compareInput) {
  24141. outputStyles[webKitStyles[i]] = inputValue;
  24142. }
  24143. }
  24144. const outputStyle = dom.serializeStyle(outputStyles, 'span');
  24145. if (outputStyle) {
  24146. return before + ' style="' + outputStyle + '"' + after;
  24147. }
  24148. return before + after;
  24149. });
  24150. } else {
  24151. content = content.replace(/(<[^>]+) style="([^"]*)"([^>]*>)/gi, '$1$3');
  24152. }
  24153. content = content.replace(/(<[^>]+) data-mce-style="([^"]+)"([^>]*>)/gi, (all, before, value, after) => {
  24154. return before + ' style="' + value + '"' + after;
  24155. });
  24156. return content;
  24157. };
  24158. const setup$8 = editor => {
  24159. if (Env.browser.isChromium() || Env.browser.isSafari()) {
  24160. addPreProcessFilter(editor, removeWebKitStyles);
  24161. }
  24162. };
  24163. const setup$7 = editor => {
  24164. const draggingInternallyState = Cell(false);
  24165. const pasteFormat = Cell(isPasteAsTextEnabled(editor) ? 'text' : 'html');
  24166. const pasteBin = PasteBin(editor);
  24167. setup$8(editor);
  24168. register$1(editor, pasteFormat);
  24169. setup$9(editor);
  24170. editor.on('PreInit', () => {
  24171. register(editor);
  24172. setup$a(editor, draggingInternallyState);
  24173. registerEventsAndFilters(editor, pasteBin, pasteFormat);
  24174. });
  24175. };
  24176. const preventSummaryToggle = editor => {
  24177. editor.on('click', e => {
  24178. if (editor.dom.getParent(e.target, 'details')) {
  24179. e.preventDefault();
  24180. }
  24181. });
  24182. };
  24183. const filterDetails = editor => {
  24184. editor.parser.addNodeFilter('details', elms => {
  24185. each$f(elms, details => {
  24186. details.attr('data-mce-open', details.attr('open'));
  24187. details.attr('open', 'open');
  24188. });
  24189. });
  24190. editor.serializer.addNodeFilter('details', elms => {
  24191. each$f(elms, details => {
  24192. const open = details.attr('data-mce-open');
  24193. details.attr('open', isString(open) ? open : null);
  24194. details.attr('data-mce-open', null);
  24195. });
  24196. });
  24197. };
  24198. const setup$6 = editor => {
  24199. preventSummaryToggle(editor);
  24200. filterDetails(editor);
  24201. };
  24202. const isBr = isBr$6;
  24203. const isText = isText$9;
  24204. const isContentEditableFalse$2 = elm => isContentEditableFalse$b(elm.dom);
  24205. const isContentEditableTrue$1 = elm => isContentEditableTrue$5(elm.dom);
  24206. const isRoot = rootNode => elm => eq(SugarElement.fromDom(rootNode), elm);
  24207. const getClosestScope = (node, rootNode) => closest$4(SugarElement.fromDom(node), elm => isContentEditableTrue$1(elm) || isBlock$2(elm), isRoot(rootNode)).getOr(SugarElement.fromDom(rootNode)).dom;
  24208. const getClosestCef = (node, rootNode) => closest$4(SugarElement.fromDom(node), isContentEditableFalse$2, isRoot(rootNode));
  24209. const findEdgeCaretCandidate = (startNode, scope, forward) => {
  24210. const walker = new DomTreeWalker(startNode, scope);
  24211. const next = forward ? walker.next.bind(walker) : walker.prev.bind(walker);
  24212. let result = startNode;
  24213. for (let current = forward ? startNode : next(); current && !isBr(current); current = next()) {
  24214. if (isCaretCandidate$3(current)) {
  24215. result = current;
  24216. }
  24217. }
  24218. return result;
  24219. };
  24220. const findClosestBlockRange = (startRng, rootNode) => {
  24221. const startPos = CaretPosition.fromRangeStart(startRng);
  24222. const clickNode = startPos.getNode();
  24223. const scope = getClosestScope(clickNode, rootNode);
  24224. const startNode = findEdgeCaretCandidate(clickNode, scope, false);
  24225. const endNode = findEdgeCaretCandidate(clickNode, scope, true);
  24226. const rng = document.createRange();
  24227. getClosestCef(startNode, scope).fold(() => {
  24228. if (isText(startNode)) {
  24229. rng.setStart(startNode, 0);
  24230. } else {
  24231. rng.setStartBefore(startNode);
  24232. }
  24233. }, cef => rng.setStartBefore(cef.dom));
  24234. getClosestCef(endNode, scope).fold(() => {
  24235. if (isText(endNode)) {
  24236. rng.setEnd(endNode, endNode.data.length);
  24237. } else {
  24238. rng.setEndAfter(endNode);
  24239. }
  24240. }, cef => rng.setEndAfter(cef.dom));
  24241. return rng;
  24242. };
  24243. const onTripleClickSelect = editor => {
  24244. const rng = findClosestBlockRange(editor.selection.getRng(), editor.getBody());
  24245. editor.selection.setRng(normalize(rng));
  24246. };
  24247. const setup$5 = editor => {
  24248. editor.on('mousedown', e => {
  24249. if (e.detail >= 3) {
  24250. e.preventDefault();
  24251. onTripleClickSelect(editor);
  24252. }
  24253. });
  24254. };
  24255. var FakeCaretPosition;
  24256. (function (FakeCaretPosition) {
  24257. FakeCaretPosition['Before'] = 'before';
  24258. FakeCaretPosition['After'] = 'after';
  24259. }(FakeCaretPosition || (FakeCaretPosition = {})));
  24260. const distanceToRectLeft = (clientRect, clientX) => Math.abs(clientRect.left - clientX);
  24261. const distanceToRectRight = (clientRect, clientX) => Math.abs(clientRect.right - clientX);
  24262. const isInsideY = (clientY, clientRect) => clientY >= clientRect.top && clientY <= clientRect.bottom;
  24263. const collidesY = (r1, r2) => r1.top < r2.bottom && r1.bottom > r2.top;
  24264. const isOverlapping = (r1, r2) => {
  24265. const overlap = overlapY(r1, r2) / Math.min(r1.height, r2.height);
  24266. return collidesY(r1, r2) && overlap > 0.5;
  24267. };
  24268. const splitRectsPerAxis = (rects, y) => {
  24269. const intersectingRects = filter$6(rects, rect => isInsideY(y, rect));
  24270. return boundingClientRectFromRects(intersectingRects).fold(() => [
  24271. [],
  24272. rects
  24273. ], boundingRect => {
  24274. const {
  24275. pass: horizontal,
  24276. fail: vertical
  24277. } = partition$2(rects, rect => isOverlapping(rect, boundingRect));
  24278. return [
  24279. horizontal,
  24280. vertical
  24281. ];
  24282. });
  24283. };
  24284. const clientInfo = (rect, clientX) => {
  24285. return {
  24286. node: rect.node,
  24287. position: distanceToRectLeft(rect, clientX) < distanceToRectRight(rect, clientX) ? FakeCaretPosition.Before : FakeCaretPosition.After
  24288. };
  24289. };
  24290. const horizontalDistance = (rect, x, _y) => x > rect.left && x < rect.right ? 0 : Math.min(Math.abs(rect.left - x), Math.abs(rect.right - x));
  24291. const closestChildCaretCandidateNodeRect = (children, clientX, clientY) => {
  24292. const caretCandidateRect = rect => {
  24293. if (isCaretCandidate$3(rect.node)) {
  24294. return Optional.some(rect);
  24295. } else if (isElement$6(rect.node)) {
  24296. return closestChildCaretCandidateNodeRect(from(rect.node.childNodes), clientX, clientY);
  24297. } else {
  24298. return Optional.none();
  24299. }
  24300. };
  24301. const getClosestTextNode = (rects, distance) => {
  24302. if (rects.length >= 2) {
  24303. const r1 = caretCandidateRect(rects[0]).getOr(rects[0]);
  24304. const r2 = caretCandidateRect(rects[1]).getOr(rects[1]);
  24305. const deltaDistance = Math.abs(distance(r1, clientX, clientY) - distance(r2, clientX, clientY));
  24306. if (deltaDistance < 2) {
  24307. if (isText$9(r1.node)) {
  24308. return Optional.some(r1);
  24309. } else if (isText$9(r2.node)) {
  24310. return Optional.some(r2);
  24311. }
  24312. }
  24313. }
  24314. return Optional.none();
  24315. };
  24316. const findClosestCaretCandidateNodeRect = (rects, distance) => {
  24317. const sortedRects = sort(rects, (r1, r2) => distance(r1, clientX, clientY) - distance(r2, clientX, clientY));
  24318. return getClosestTextNode(sortedRects, distance).orThunk(() => findMap(sortedRects, caretCandidateRect));
  24319. };
  24320. const [horizontalRects, verticalRects] = splitRectsPerAxis(getClientRects(children), clientY);
  24321. const {
  24322. pass: above,
  24323. fail: below
  24324. } = partition$2(verticalRects, rect => rect.top < clientY);
  24325. return findClosestCaretCandidateNodeRect(horizontalRects, horizontalDistance).orThunk(() => findClosestCaretCandidateNodeRect(below, distanceToRectEdgeFromXY)).orThunk(() => findClosestCaretCandidateNodeRect(above, distanceToRectEdgeFromXY));
  24326. };
  24327. const traverseUp = (rootElm, scope, clientX, clientY) => {
  24328. const helper = (scope, prevScope) => {
  24329. return prevScope.fold(() => closestChildCaretCandidateNodeRect(from(scope.dom.childNodes), clientX, clientY), prevScope => {
  24330. const uncheckedChildren = filter$6(from(scope.dom.childNodes), node => node !== prevScope.dom);
  24331. return closestChildCaretCandidateNodeRect(uncheckedChildren, clientX, clientY);
  24332. }).orThunk(() => {
  24333. const parent = eq(scope, rootElm) ? Optional.none() : parentElement(scope);
  24334. return parent.bind(newScope => helper(newScope, Optional.some(scope)));
  24335. });
  24336. };
  24337. return helper(scope, Optional.none());
  24338. };
  24339. const closestCaretCandidateNodeRect = (root, clientX, clientY) => {
  24340. const rootElm = SugarElement.fromDom(root);
  24341. const ownerDoc = documentOrOwner(rootElm);
  24342. const elementAtPoint = SugarElement.fromPoint(ownerDoc, clientX, clientY).filter(elm => contains(rootElm, elm));
  24343. const element = elementAtPoint.getOr(rootElm);
  24344. return traverseUp(rootElm, element, clientX, clientY);
  24345. };
  24346. const closestFakeCaretCandidate = (root, clientX, clientY) => closestCaretCandidateNodeRect(root, clientX, clientY).filter(rect => isFakeCaretTarget(rect.node)).map(rect => clientInfo(rect, clientX));
  24347. const getAbsolutePosition = elm => {
  24348. const clientRect = elm.getBoundingClientRect();
  24349. const doc = elm.ownerDocument;
  24350. const docElem = doc.documentElement;
  24351. const win = doc.defaultView;
  24352. return {
  24353. top: clientRect.top + win.pageYOffset - docElem.clientTop,
  24354. left: clientRect.left + win.pageXOffset - docElem.clientLeft
  24355. };
  24356. };
  24357. const getBodyPosition = editor => editor.inline ? getAbsolutePosition(editor.getBody()) : {
  24358. left: 0,
  24359. top: 0
  24360. };
  24361. const getScrollPosition = editor => {
  24362. const body = editor.getBody();
  24363. return editor.inline ? {
  24364. left: body.scrollLeft,
  24365. top: body.scrollTop
  24366. } : {
  24367. left: 0,
  24368. top: 0
  24369. };
  24370. };
  24371. const getBodyScroll = editor => {
  24372. const body = editor.getBody(), docElm = editor.getDoc().documentElement;
  24373. const inlineScroll = {
  24374. left: body.scrollLeft,
  24375. top: body.scrollTop
  24376. };
  24377. const iframeScroll = {
  24378. left: body.scrollLeft || docElm.scrollLeft,
  24379. top: body.scrollTop || docElm.scrollTop
  24380. };
  24381. return editor.inline ? inlineScroll : iframeScroll;
  24382. };
  24383. const getMousePosition = (editor, event) => {
  24384. if (event.target.ownerDocument !== editor.getDoc()) {
  24385. const iframePosition = getAbsolutePosition(editor.getContentAreaContainer());
  24386. const scrollPosition = getBodyScroll(editor);
  24387. return {
  24388. left: event.pageX - iframePosition.left + scrollPosition.left,
  24389. top: event.pageY - iframePosition.top + scrollPosition.top
  24390. };
  24391. }
  24392. return {
  24393. left: event.pageX,
  24394. top: event.pageY
  24395. };
  24396. };
  24397. const calculatePosition = (bodyPosition, scrollPosition, mousePosition) => ({
  24398. pageX: mousePosition.left - bodyPosition.left + scrollPosition.left,
  24399. pageY: mousePosition.top - bodyPosition.top + scrollPosition.top
  24400. });
  24401. const calc = (editor, event) => calculatePosition(getBodyPosition(editor), getScrollPosition(editor), getMousePosition(editor, event));
  24402. const isContentEditableFalse$1 = isContentEditableFalse$b, isContentEditableTrue = isContentEditableTrue$5;
  24403. const isDraggable = (rootElm, elm) => isContentEditableFalse$1(elm) && elm !== rootElm;
  24404. const isValidDropTarget = (editor, targetElement, dragElement) => {
  24405. if (targetElement === dragElement || editor.dom.isChildOf(targetElement, dragElement)) {
  24406. return false;
  24407. }
  24408. return !isContentEditableFalse$1(targetElement);
  24409. };
  24410. const cloneElement = elm => {
  24411. const cloneElm = elm.cloneNode(true);
  24412. cloneElm.removeAttribute('data-mce-selected');
  24413. return cloneElm;
  24414. };
  24415. const createGhost = (editor, elm, width, height) => {
  24416. const dom = editor.dom;
  24417. const clonedElm = elm.cloneNode(true);
  24418. dom.setStyles(clonedElm, {
  24419. width,
  24420. height
  24421. });
  24422. dom.setAttrib(clonedElm, 'data-mce-selected', null);
  24423. const ghostElm = dom.create('div', {
  24424. 'class': 'mce-drag-container',
  24425. 'data-mce-bogus': 'all',
  24426. 'unselectable': 'on',
  24427. 'contenteditable': 'false'
  24428. });
  24429. dom.setStyles(ghostElm, {
  24430. position: 'absolute',
  24431. opacity: 0.5,
  24432. overflow: 'hidden',
  24433. border: 0,
  24434. padding: 0,
  24435. margin: 0,
  24436. width,
  24437. height
  24438. });
  24439. dom.setStyles(clonedElm, {
  24440. margin: 0,
  24441. boxSizing: 'border-box'
  24442. });
  24443. ghostElm.appendChild(clonedElm);
  24444. return ghostElm;
  24445. };
  24446. const appendGhostToBody = (ghostElm, bodyElm) => {
  24447. if (ghostElm.parentNode !== bodyElm) {
  24448. bodyElm.appendChild(ghostElm);
  24449. }
  24450. };
  24451. const moveGhost = (ghostElm, position, width, height, maxX, maxY) => {
  24452. let overflowX = 0, overflowY = 0;
  24453. ghostElm.style.left = position.pageX + 'px';
  24454. ghostElm.style.top = position.pageY + 'px';
  24455. if (position.pageX + width > maxX) {
  24456. overflowX = position.pageX + width - maxX;
  24457. }
  24458. if (position.pageY + height > maxY) {
  24459. overflowY = position.pageY + height - maxY;
  24460. }
  24461. ghostElm.style.width = width - overflowX + 'px';
  24462. ghostElm.style.height = height - overflowY + 'px';
  24463. };
  24464. const removeElement = elm => {
  24465. if (elm && elm.parentNode) {
  24466. elm.parentNode.removeChild(elm);
  24467. }
  24468. };
  24469. const isLeftMouseButtonPressed = e => e.button === 0;
  24470. const applyRelPos = (state, position) => ({
  24471. pageX: position.pageX - state.relX,
  24472. pageY: position.pageY + 5
  24473. });
  24474. const start = (state, editor) => e => {
  24475. if (isLeftMouseButtonPressed(e)) {
  24476. const ceElm = find$2(editor.dom.getParents(e.target), or(isContentEditableFalse$1, isContentEditableTrue)).getOr(null);
  24477. if (isDraggable(editor.getBody(), ceElm)) {
  24478. const elmPos = editor.dom.getPos(ceElm);
  24479. const bodyElm = editor.getBody();
  24480. const docElm = editor.getDoc().documentElement;
  24481. state.set({
  24482. element: ceElm,
  24483. dragging: false,
  24484. screenX: e.screenX,
  24485. screenY: e.screenY,
  24486. maxX: (editor.inline ? bodyElm.scrollWidth : docElm.offsetWidth) - 2,
  24487. maxY: (editor.inline ? bodyElm.scrollHeight : docElm.offsetHeight) - 2,
  24488. relX: e.pageX - elmPos.x,
  24489. relY: e.pageY - elmPos.y,
  24490. width: ceElm.offsetWidth,
  24491. height: ceElm.offsetHeight,
  24492. ghost: createGhost(editor, ceElm, ceElm.offsetWidth, ceElm.offsetHeight)
  24493. });
  24494. }
  24495. }
  24496. };
  24497. const move = (state, editor) => {
  24498. const throttledPlaceCaretAt = first$1((clientX, clientY) => {
  24499. editor._selectionOverrides.hideFakeCaret();
  24500. editor.selection.placeCaretAt(clientX, clientY);
  24501. }, 0);
  24502. editor.on('remove', throttledPlaceCaretAt.cancel);
  24503. return e => state.on(state => {
  24504. const movement = Math.max(Math.abs(e.screenX - state.screenX), Math.abs(e.screenY - state.screenY));
  24505. if (!state.dragging && movement > 10) {
  24506. const args = editor.dispatch('dragstart', { target: state.element });
  24507. if (args.isDefaultPrevented()) {
  24508. return;
  24509. }
  24510. state.dragging = true;
  24511. editor.focus();
  24512. }
  24513. if (state.dragging) {
  24514. const targetPos = applyRelPos(state, calc(editor, e));
  24515. appendGhostToBody(state.ghost, editor.getBody());
  24516. moveGhost(state.ghost, targetPos, state.width, state.height, state.maxX, state.maxY);
  24517. throttledPlaceCaretAt.throttle(e.clientX, e.clientY);
  24518. }
  24519. });
  24520. };
  24521. const getRawTarget = selection => {
  24522. const rng = selection.getSel().getRangeAt(0);
  24523. const startContainer = rng.startContainer;
  24524. return startContainer.nodeType === 3 ? startContainer.parentNode : startContainer;
  24525. };
  24526. const drop = (state, editor) => e => {
  24527. state.on(state => {
  24528. if (state.dragging) {
  24529. if (isValidDropTarget(editor, getRawTarget(editor.selection), state.element)) {
  24530. const targetClone = cloneElement(state.element);
  24531. const args = editor.dispatch('drop', {
  24532. clientX: e.clientX,
  24533. clientY: e.clientY
  24534. });
  24535. if (!args.isDefaultPrevented()) {
  24536. editor.undoManager.transact(() => {
  24537. removeElement(state.element);
  24538. editor.insertContent(editor.dom.getOuterHTML(targetClone));
  24539. editor._selectionOverrides.hideFakeCaret();
  24540. });
  24541. }
  24542. }
  24543. editor.dispatch('dragend');
  24544. }
  24545. });
  24546. removeDragState(state);
  24547. };
  24548. const stop = (state, editor) => () => {
  24549. state.on(state => {
  24550. if (state.dragging) {
  24551. editor.dispatch('dragend');
  24552. }
  24553. });
  24554. removeDragState(state);
  24555. };
  24556. const removeDragState = state => {
  24557. state.on(state => {
  24558. removeElement(state.ghost);
  24559. });
  24560. state.clear();
  24561. };
  24562. const bindFakeDragEvents = editor => {
  24563. const state = value$2();
  24564. const pageDom = DOMUtils.DOM;
  24565. const rootDocument = document;
  24566. const dragStartHandler = start(state, editor);
  24567. const dragHandler = move(state, editor);
  24568. const dropHandler = drop(state, editor);
  24569. const dragEndHandler = stop(state, editor);
  24570. editor.on('mousedown', dragStartHandler);
  24571. editor.on('mousemove', dragHandler);
  24572. editor.on('mouseup', dropHandler);
  24573. pageDom.bind(rootDocument, 'mousemove', dragHandler);
  24574. pageDom.bind(rootDocument, 'mouseup', dragEndHandler);
  24575. editor.on('remove', () => {
  24576. pageDom.unbind(rootDocument, 'mousemove', dragHandler);
  24577. pageDom.unbind(rootDocument, 'mouseup', dragEndHandler);
  24578. });
  24579. editor.on('keydown', e => {
  24580. if (e.keyCode === VK.ESC) {
  24581. dragEndHandler();
  24582. }
  24583. });
  24584. };
  24585. const blockUnsupportedFileDrop = editor => {
  24586. const preventFileDrop = e => {
  24587. if (!e.isDefaultPrevented()) {
  24588. const dataTransfer = e.dataTransfer;
  24589. if (dataTransfer && (contains$2(dataTransfer.types, 'Files') || dataTransfer.files.length > 0)) {
  24590. e.preventDefault();
  24591. if (e.type === 'drop') {
  24592. displayError(editor, 'Dropped file type is not supported');
  24593. }
  24594. }
  24595. }
  24596. };
  24597. const preventFileDropIfUIElement = e => {
  24598. if (isUIElement(editor, e.target)) {
  24599. preventFileDrop(e);
  24600. }
  24601. };
  24602. const setup = () => {
  24603. const pageDom = DOMUtils.DOM;
  24604. const dom = editor.dom;
  24605. const doc = document;
  24606. const editorRoot = editor.inline ? editor.getBody() : editor.getDoc();
  24607. const eventNames = [
  24608. 'drop',
  24609. 'dragover'
  24610. ];
  24611. each$f(eventNames, name => {
  24612. pageDom.bind(doc, name, preventFileDropIfUIElement);
  24613. dom.bind(editorRoot, name, preventFileDrop);
  24614. });
  24615. editor.on('remove', () => {
  24616. each$f(eventNames, name => {
  24617. pageDom.unbind(doc, name, preventFileDropIfUIElement);
  24618. dom.unbind(editorRoot, name, preventFileDrop);
  24619. });
  24620. });
  24621. };
  24622. editor.on('init', () => {
  24623. Delay.setEditorTimeout(editor, setup, 0);
  24624. });
  24625. };
  24626. const init$2 = editor => {
  24627. bindFakeDragEvents(editor);
  24628. if (shouldBlockUnsupportedDrop(editor)) {
  24629. blockUnsupportedFileDrop(editor);
  24630. }
  24631. };
  24632. const setup$4 = editor => {
  24633. const renderFocusCaret = first$1(() => {
  24634. if (!editor.removed && editor.getBody().contains(document.activeElement)) {
  24635. const rng = editor.selection.getRng();
  24636. if (rng.collapsed) {
  24637. const caretRange = renderRangeCaret(editor, rng, false);
  24638. editor.selection.setRng(caretRange);
  24639. }
  24640. }
  24641. }, 0);
  24642. editor.on('focus', () => {
  24643. renderFocusCaret.throttle();
  24644. });
  24645. editor.on('blur', () => {
  24646. renderFocusCaret.cancel();
  24647. });
  24648. };
  24649. const setup$3 = editor => {
  24650. editor.on('init', () => {
  24651. editor.on('focusin', e => {
  24652. const target = e.target;
  24653. if (isMedia$2(target)) {
  24654. const ceRoot = getContentEditableRoot$1(editor.getBody(), target);
  24655. const node = isContentEditableFalse$b(ceRoot) ? ceRoot : target;
  24656. if (editor.selection.getNode() !== node) {
  24657. selectNode(editor, node).each(rng => editor.selection.setRng(rng));
  24658. }
  24659. }
  24660. });
  24661. });
  24662. };
  24663. const isContentEditableFalse = isContentEditableFalse$b;
  24664. const getContentEditableRoot = (editor, node) => getContentEditableRoot$1(editor.getBody(), node);
  24665. const SelectionOverrides = editor => {
  24666. const selection = editor.selection, dom = editor.dom;
  24667. const isBlock = dom.isBlock;
  24668. const rootNode = editor.getBody();
  24669. const fakeCaret = FakeCaret(editor, rootNode, isBlock, () => hasFocus(editor));
  24670. const realSelectionId = 'sel-' + dom.uniqueId();
  24671. const elementSelectionAttr = 'data-mce-selected';
  24672. let selectedElement;
  24673. const isFakeSelectionElement = node => dom.hasClass(node, 'mce-offscreen-selection');
  24674. const isFakeSelectionTargetElement = node => node !== rootNode && (isContentEditableFalse(node) || isMedia$2(node)) && dom.isChildOf(node, rootNode);
  24675. const setRange = range => {
  24676. if (range) {
  24677. selection.setRng(range);
  24678. }
  24679. };
  24680. const showCaret = (direction, node, before, scrollIntoView = true) => {
  24681. const e = editor.dispatch('ShowCaret', {
  24682. target: node,
  24683. direction,
  24684. before
  24685. });
  24686. if (e.isDefaultPrevented()) {
  24687. return null;
  24688. }
  24689. if (scrollIntoView) {
  24690. selection.scrollIntoView(node, direction === -1);
  24691. }
  24692. return fakeCaret.show(before, node);
  24693. };
  24694. const showBlockCaretContainer = blockCaretContainer => {
  24695. if (blockCaretContainer.hasAttribute('data-mce-caret')) {
  24696. showCaretContainerBlock(blockCaretContainer);
  24697. selection.scrollIntoView(blockCaretContainer);
  24698. }
  24699. };
  24700. const registerEvents = () => {
  24701. editor.on('click', e => {
  24702. const contentEditableRoot = getContentEditableRoot(editor, e.target);
  24703. if (contentEditableRoot) {
  24704. if (isContentEditableFalse(contentEditableRoot)) {
  24705. e.preventDefault();
  24706. editor.focus();
  24707. }
  24708. }
  24709. });
  24710. editor.on('blur NewBlock', removeElementSelection);
  24711. editor.on('ResizeWindow FullscreenStateChanged', fakeCaret.reposition);
  24712. editor.on('tap', e => {
  24713. const targetElm = e.target;
  24714. const contentEditableRoot = getContentEditableRoot(editor, targetElm);
  24715. if (isContentEditableFalse(contentEditableRoot)) {
  24716. e.preventDefault();
  24717. selectNode(editor, contentEditableRoot).each(setElementSelection);
  24718. } else if (isFakeSelectionTargetElement(targetElm)) {
  24719. selectNode(editor, targetElm).each(setElementSelection);
  24720. }
  24721. }, true);
  24722. editor.on('mousedown', e => {
  24723. const targetElm = e.target;
  24724. if (targetElm !== rootNode && targetElm.nodeName !== 'HTML' && !dom.isChildOf(targetElm, rootNode)) {
  24725. return;
  24726. }
  24727. if (isXYInContentArea(editor, e.clientX, e.clientY) === false) {
  24728. return;
  24729. }
  24730. removeElementSelection();
  24731. hideFakeCaret();
  24732. const closestContentEditable = getContentEditableRoot(editor, targetElm);
  24733. if (isContentEditableFalse(closestContentEditable)) {
  24734. e.preventDefault();
  24735. selectNode(editor, closestContentEditable).each(setElementSelection);
  24736. } else {
  24737. closestFakeCaretCandidate(rootNode, e.clientX, e.clientY).each(caretInfo => {
  24738. e.preventDefault();
  24739. const range = showCaret(1, caretInfo.node, caretInfo.position === FakeCaretPosition.Before, false);
  24740. setRange(range);
  24741. if (isElement$6(closestContentEditable)) {
  24742. closestContentEditable.focus();
  24743. } else {
  24744. editor.getBody().focus();
  24745. }
  24746. });
  24747. }
  24748. });
  24749. editor.on('keypress', e => {
  24750. if (VK.modifierPressed(e)) {
  24751. return;
  24752. }
  24753. if (isContentEditableFalse(selection.getNode())) {
  24754. e.preventDefault();
  24755. }
  24756. });
  24757. editor.on('GetSelectionRange', e => {
  24758. let rng = e.range;
  24759. if (selectedElement) {
  24760. if (!selectedElement.parentNode) {
  24761. selectedElement = null;
  24762. return;
  24763. }
  24764. rng = rng.cloneRange();
  24765. rng.selectNode(selectedElement);
  24766. e.range = rng;
  24767. }
  24768. });
  24769. editor.on('SetSelectionRange', e => {
  24770. e.range = normalizeVoidElementSelection(e.range);
  24771. const rng = setElementSelection(e.range, e.forward);
  24772. if (rng) {
  24773. e.range = rng;
  24774. }
  24775. });
  24776. const isPasteBin = node => node.id === 'mcepastebin';
  24777. editor.on('AfterSetSelectionRange', e => {
  24778. const rng = e.range;
  24779. const parentNode = rng.startContainer.parentNode;
  24780. if (!isRangeInCaretContainer(rng) && !isPasteBin(parentNode)) {
  24781. hideFakeCaret();
  24782. }
  24783. if (!isFakeSelectionElement(parentNode)) {
  24784. removeElementSelection();
  24785. }
  24786. });
  24787. init$2(editor);
  24788. setup$4(editor);
  24789. setup$3(editor);
  24790. };
  24791. const isWithinCaretContainer = node => isCaretContainer$2(node) || startsWithCaretContainer$1(node) || endsWithCaretContainer$1(node);
  24792. const isRangeInCaretContainer = rng => isWithinCaretContainer(rng.startContainer) || isWithinCaretContainer(rng.endContainer);
  24793. const normalizeVoidElementSelection = rng => {
  24794. const voidElements = editor.schema.getVoidElements();
  24795. const newRng = dom.createRng();
  24796. const startContainer = rng.startContainer;
  24797. const startOffset = rng.startOffset;
  24798. const endContainer = rng.endContainer;
  24799. const endOffset = rng.endOffset;
  24800. if (has$2(voidElements, startContainer.nodeName.toLowerCase())) {
  24801. if (startOffset === 0) {
  24802. newRng.setStartBefore(startContainer);
  24803. } else {
  24804. newRng.setStartAfter(startContainer);
  24805. }
  24806. } else {
  24807. newRng.setStart(startContainer, startOffset);
  24808. }
  24809. if (has$2(voidElements, endContainer.nodeName.toLowerCase())) {
  24810. if (endOffset === 0) {
  24811. newRng.setEndBefore(endContainer);
  24812. } else {
  24813. newRng.setEndAfter(endContainer);
  24814. }
  24815. } else {
  24816. newRng.setEnd(endContainer, endOffset);
  24817. }
  24818. return newRng;
  24819. };
  24820. const setupOffscreenSelection = (node, targetClone) => {
  24821. const body = SugarElement.fromDom(editor.getBody());
  24822. const doc = editor.getDoc();
  24823. const realSelectionContainer = descendant(body, '#' + realSelectionId).getOrThunk(() => {
  24824. const newContainer = SugarElement.fromHtml('<div data-mce-bogus="all" class="mce-offscreen-selection"></div>', doc);
  24825. set$2(newContainer, 'id', realSelectionId);
  24826. append$1(body, newContainer);
  24827. return newContainer;
  24828. });
  24829. const newRange = dom.createRng();
  24830. empty(realSelectionContainer);
  24831. append(realSelectionContainer, [
  24832. SugarElement.fromText(nbsp, doc),
  24833. SugarElement.fromDom(targetClone),
  24834. SugarElement.fromText(nbsp, doc)
  24835. ]);
  24836. newRange.setStart(realSelectionContainer.dom.firstChild, 1);
  24837. newRange.setEnd(realSelectionContainer.dom.lastChild, 0);
  24838. setAll(realSelectionContainer, { top: dom.getPos(node, editor.getBody()).y + 'px' });
  24839. focus$1(realSelectionContainer);
  24840. const sel = selection.getSel();
  24841. sel.removeAllRanges();
  24842. sel.addRange(newRange);
  24843. return newRange;
  24844. };
  24845. const selectElement = elm => {
  24846. const targetClone = elm.cloneNode(true);
  24847. const e = editor.dispatch('ObjectSelected', {
  24848. target: elm,
  24849. targetClone
  24850. });
  24851. if (e.isDefaultPrevented()) {
  24852. return null;
  24853. }
  24854. const range = setupOffscreenSelection(elm, e.targetClone);
  24855. const nodeElm = SugarElement.fromDom(elm);
  24856. each$f(descendants(SugarElement.fromDom(editor.getBody()), `*[${ elementSelectionAttr }]`), elm => {
  24857. if (!eq(nodeElm, elm)) {
  24858. remove$b(elm, elementSelectionAttr);
  24859. }
  24860. });
  24861. if (!dom.getAttrib(elm, elementSelectionAttr)) {
  24862. elm.setAttribute(elementSelectionAttr, '1');
  24863. }
  24864. selectedElement = elm;
  24865. hideFakeCaret();
  24866. return range;
  24867. };
  24868. const setElementSelection = (range, forward) => {
  24869. if (!range) {
  24870. return null;
  24871. }
  24872. if (range.collapsed) {
  24873. if (!isRangeInCaretContainer(range)) {
  24874. const dir = forward ? 1 : -1;
  24875. const caretPosition = getNormalizedRangeEndPoint(dir, rootNode, range);
  24876. const beforeNode = caretPosition.getNode(!forward);
  24877. if (isFakeCaretTarget(beforeNode)) {
  24878. return showCaret(dir, beforeNode, forward ? !caretPosition.isAtEnd() : false, false);
  24879. }
  24880. const afterNode = caretPosition.getNode(forward);
  24881. if (isFakeCaretTarget(afterNode)) {
  24882. return showCaret(dir, afterNode, forward ? false : !caretPosition.isAtEnd(), false);
  24883. }
  24884. }
  24885. return null;
  24886. }
  24887. let startContainer = range.startContainer;
  24888. let startOffset = range.startOffset;
  24889. const endOffset = range.endOffset;
  24890. if (startContainer.nodeType === 3 && startOffset === 0 && isContentEditableFalse(startContainer.parentNode)) {
  24891. startContainer = startContainer.parentNode;
  24892. startOffset = dom.nodeIndex(startContainer);
  24893. startContainer = startContainer.parentNode;
  24894. }
  24895. if (startContainer.nodeType !== 1) {
  24896. return null;
  24897. }
  24898. if (endOffset === startOffset + 1 && startContainer === range.endContainer) {
  24899. const node = startContainer.childNodes[startOffset];
  24900. if (isFakeSelectionTargetElement(node)) {
  24901. return selectElement(node);
  24902. }
  24903. }
  24904. return null;
  24905. };
  24906. const removeElementSelection = () => {
  24907. if (selectedElement) {
  24908. selectedElement.removeAttribute(elementSelectionAttr);
  24909. }
  24910. descendant(SugarElement.fromDom(editor.getBody()), '#' + realSelectionId).each(remove$6);
  24911. selectedElement = null;
  24912. };
  24913. const destroy = () => {
  24914. fakeCaret.destroy();
  24915. selectedElement = null;
  24916. };
  24917. const hideFakeCaret = () => {
  24918. fakeCaret.hide();
  24919. };
  24920. if (!isRtc(editor)) {
  24921. registerEvents();
  24922. }
  24923. return {
  24924. showCaret,
  24925. showBlockCaretContainer,
  24926. hideFakeCaret,
  24927. destroy
  24928. };
  24929. };
  24930. const generatePath = (root, node, offset) => {
  24931. if (isText$9(node) && (offset < 0 || offset > node.data.length)) {
  24932. return [];
  24933. }
  24934. const p = [offset];
  24935. let current = node;
  24936. while (current !== root && current.parentNode) {
  24937. const parent = current.parentNode;
  24938. for (let i = 0; i < parent.childNodes.length; i++) {
  24939. if (parent.childNodes[i] === current) {
  24940. p.push(i);
  24941. break;
  24942. }
  24943. }
  24944. current = parent;
  24945. }
  24946. return current === root ? p.reverse() : [];
  24947. };
  24948. const generatePathRange = (root, startNode, startOffset, endNode, endOffset) => {
  24949. const start = generatePath(root, startNode, startOffset);
  24950. const end = generatePath(root, endNode, endOffset);
  24951. return {
  24952. start,
  24953. end
  24954. };
  24955. };
  24956. const resolvePath = (root, path) => {
  24957. const nodePath = path.slice();
  24958. const offset = nodePath.pop();
  24959. const resolvedNode = foldl(nodePath, (optNode, index) => optNode.bind(node => Optional.from(node.childNodes[index])), Optional.some(root));
  24960. return resolvedNode.bind(node => {
  24961. if (isText$9(node) && (offset < 0 || offset > node.data.length)) {
  24962. return Optional.none();
  24963. } else {
  24964. return Optional.some({
  24965. node,
  24966. offset
  24967. });
  24968. }
  24969. });
  24970. };
  24971. const resolvePathRange = (root, range) => resolvePath(root, range.start).bind(({
  24972. node: startNode,
  24973. offset: startOffset
  24974. }) => resolvePath(root, range.end).map(({
  24975. node: endNode,
  24976. offset: endOffset
  24977. }) => {
  24978. const rng = document.createRange();
  24979. rng.setStart(startNode, startOffset);
  24980. rng.setEnd(endNode, endOffset);
  24981. return rng;
  24982. }));
  24983. const generatePathRangeFromRange = (root, range) => generatePathRange(root, range.startContainer, range.startOffset, range.endContainer, range.endOffset);
  24984. const cleanEmptyNodes = (dom, node, isRoot) => {
  24985. if (node && dom.isEmpty(node) && !isRoot(node)) {
  24986. const parent = node.parentNode;
  24987. dom.remove(node);
  24988. cleanEmptyNodes(dom, parent, isRoot);
  24989. }
  24990. };
  24991. const deleteRng = (dom, rng, isRoot, clean = true) => {
  24992. const startParent = rng.startContainer.parentNode;
  24993. const endParent = rng.endContainer.parentNode;
  24994. rng.deleteContents();
  24995. if (clean && !isRoot(rng.startContainer)) {
  24996. if (isText$9(rng.startContainer) && rng.startContainer.data.length === 0) {
  24997. dom.remove(rng.startContainer);
  24998. }
  24999. if (isText$9(rng.endContainer) && rng.endContainer.data.length === 0) {
  25000. dom.remove(rng.endContainer);
  25001. }
  25002. cleanEmptyNodes(dom, startParent, isRoot);
  25003. if (startParent !== endParent) {
  25004. cleanEmptyNodes(dom, endParent, isRoot);
  25005. }
  25006. }
  25007. };
  25008. const getParentBlock = (editor, rng) => Optional.from(editor.dom.getParent(rng.startContainer, editor.dom.isBlock));
  25009. const stripPattern = (dom, block, pattern) => {
  25010. const firstTextNode = textAfter(block, 0, block);
  25011. firstTextNode.each(spot => {
  25012. const node = spot.container;
  25013. scanRight(node, pattern.start.length, block).each(end => {
  25014. const rng = dom.createRng();
  25015. rng.setStart(node, 0);
  25016. rng.setEnd(end.container, end.offset);
  25017. deleteRng(dom, rng, e => e === block);
  25018. });
  25019. });
  25020. };
  25021. const applyPattern$1 = (editor, match) => {
  25022. const dom = editor.dom;
  25023. const pattern = match.pattern;
  25024. const rng = resolvePathRange(dom.getRoot(), match.range).getOrDie('Unable to resolve path range');
  25025. const isBlockFormatName = (name, formatter) => {
  25026. const formatSet = formatter.get(name);
  25027. return isArray$1(formatSet) && head(formatSet).exists(format => has$2(format, 'block'));
  25028. };
  25029. getParentBlock(editor, rng).each(block => {
  25030. if (pattern.type === 'block-format') {
  25031. if (isBlockFormatName(pattern.format, editor.formatter)) {
  25032. editor.undoManager.transact(() => {
  25033. stripPattern(editor.dom, block, pattern);
  25034. editor.formatter.apply(pattern.format);
  25035. });
  25036. }
  25037. } else if (pattern.type === 'block-command') {
  25038. editor.undoManager.transact(() => {
  25039. stripPattern(editor.dom, block, pattern);
  25040. editor.execCommand(pattern.cmd, false, pattern.value);
  25041. });
  25042. }
  25043. });
  25044. return true;
  25045. };
  25046. const findPattern$1 = (patterns, text) => {
  25047. const nuText = text.replace(nbsp, ' ');
  25048. return find$2(patterns, pattern => text.indexOf(pattern.start) === 0 || nuText.indexOf(pattern.start) === 0);
  25049. };
  25050. const findPatterns$1 = (editor, patterns) => {
  25051. const dom = editor.dom;
  25052. const rng = editor.selection.getRng();
  25053. return getParentBlock(editor, rng).filter(block => {
  25054. const forcedRootBlock = getForcedRootBlock(editor);
  25055. const matchesForcedRootBlock = dom.is(block, forcedRootBlock);
  25056. return block !== null && matchesForcedRootBlock;
  25057. }).bind(block => {
  25058. const blockText = block.textContent;
  25059. const matchedPattern = findPattern$1(patterns, blockText);
  25060. return matchedPattern.map(pattern => {
  25061. if (Tools.trim(blockText).length === pattern.start.length) {
  25062. return [];
  25063. }
  25064. return [{
  25065. pattern,
  25066. range: generatePathRange(dom.getRoot(), block, 0, block, 0)
  25067. }];
  25068. });
  25069. }).getOr([]);
  25070. };
  25071. const applyMatches$1 = (editor, matches) => {
  25072. if (matches.length === 0) {
  25073. return;
  25074. }
  25075. const bookmark = editor.selection.getBookmark();
  25076. each$f(matches, match => applyPattern$1(editor, match));
  25077. editor.selection.moveToBookmark(bookmark);
  25078. };
  25079. const newMarker = (dom, id) => dom.create('span', {
  25080. 'data-mce-type': 'bookmark',
  25081. id
  25082. });
  25083. const rangeFromMarker = (dom, marker) => {
  25084. const rng = dom.createRng();
  25085. rng.setStartAfter(marker.start);
  25086. rng.setEndBefore(marker.end);
  25087. return rng;
  25088. };
  25089. const createMarker = (dom, markerPrefix, pathRange) => {
  25090. const rng = resolvePathRange(dom.getRoot(), pathRange).getOrDie('Unable to resolve path range');
  25091. const startNode = rng.startContainer;
  25092. const endNode = rng.endContainer;
  25093. const textEnd = rng.endOffset === 0 ? endNode : endNode.splitText(rng.endOffset);
  25094. const textStart = rng.startOffset === 0 ? startNode : startNode.splitText(rng.startOffset);
  25095. return {
  25096. prefix: markerPrefix,
  25097. end: textEnd.parentNode.insertBefore(newMarker(dom, markerPrefix + '-end'), textEnd),
  25098. start: textStart.parentNode.insertBefore(newMarker(dom, markerPrefix + '-start'), textStart)
  25099. };
  25100. };
  25101. const removeMarker = (dom, marker, isRoot) => {
  25102. cleanEmptyNodes(dom, dom.get(marker.prefix + '-end'), isRoot);
  25103. cleanEmptyNodes(dom, dom.get(marker.prefix + '-start'), isRoot);
  25104. };
  25105. const isReplacementPattern = pattern => pattern.start.length === 0;
  25106. const matchesPattern = patternContent => (element, offset) => {
  25107. const text = element.data;
  25108. const searchText = text.substring(0, offset);
  25109. const startEndIndex = searchText.lastIndexOf(patternContent.charAt(patternContent.length - 1));
  25110. const startIndex = searchText.lastIndexOf(patternContent);
  25111. if (startIndex !== -1) {
  25112. return startIndex + patternContent.length;
  25113. } else if (startEndIndex !== -1) {
  25114. return startEndIndex + 1;
  25115. } else {
  25116. return -1;
  25117. }
  25118. };
  25119. const findPatternStartFromSpot = (dom, pattern, block, spot) => {
  25120. const startPattern = pattern.start;
  25121. const startSpot = repeatLeft(dom, spot.container, spot.offset, matchesPattern(startPattern), block);
  25122. return startSpot.bind(spot => {
  25123. if (spot.offset >= startPattern.length) {
  25124. const rng = dom.createRng();
  25125. rng.setStart(spot.container, spot.offset - startPattern.length);
  25126. rng.setEnd(spot.container, spot.offset);
  25127. return Optional.some(rng);
  25128. } else {
  25129. const offset = spot.offset - startPattern.length;
  25130. return scanLeft(spot.container, offset, block).map(nextSpot => {
  25131. const rng = dom.createRng();
  25132. rng.setStart(nextSpot.container, nextSpot.offset);
  25133. rng.setEnd(spot.container, spot.offset);
  25134. return rng;
  25135. }).filter(rng => rng.toString() === startPattern).orThunk(() => findPatternStartFromSpot(dom, pattern, block, point(spot.container, 0)));
  25136. }
  25137. });
  25138. };
  25139. const findPatternStart = (dom, pattern, node, offset, block, requireGap = false) => {
  25140. if (pattern.start.length === 0 && !requireGap) {
  25141. const rng = dom.createRng();
  25142. rng.setStart(node, offset);
  25143. rng.setEnd(node, offset);
  25144. return Optional.some(rng);
  25145. }
  25146. return textBefore(node, offset, block).bind(spot => {
  25147. const start = findPatternStartFromSpot(dom, pattern, block, spot);
  25148. return start.bind(startRange => {
  25149. if (requireGap) {
  25150. if (startRange.endContainer === spot.container && startRange.endOffset === spot.offset) {
  25151. return Optional.none();
  25152. } else if (spot.offset === 0 && startRange.endContainer.textContent.length === startRange.endOffset) {
  25153. return Optional.none();
  25154. }
  25155. }
  25156. return Optional.some(startRange);
  25157. });
  25158. });
  25159. };
  25160. const findPattern = (editor, block, details) => {
  25161. const dom = editor.dom;
  25162. const root = dom.getRoot();
  25163. const pattern = details.pattern;
  25164. const endNode = details.position.container;
  25165. const endOffset = details.position.offset;
  25166. return scanLeft(endNode, endOffset - details.pattern.end.length, block).bind(spot => {
  25167. const endPathRng = generatePathRange(root, spot.container, spot.offset, endNode, endOffset);
  25168. if (isReplacementPattern(pattern)) {
  25169. return Optional.some({
  25170. matches: [{
  25171. pattern,
  25172. startRng: endPathRng,
  25173. endRng: endPathRng
  25174. }],
  25175. position: spot
  25176. });
  25177. } else {
  25178. const resultsOpt = findPatternsRec(editor, details.remainingPatterns, spot.container, spot.offset, block);
  25179. const results = resultsOpt.getOr({
  25180. matches: [],
  25181. position: spot
  25182. });
  25183. const pos = results.position;
  25184. const start = findPatternStart(dom, pattern, pos.container, pos.offset, block, resultsOpt.isNone());
  25185. return start.map(startRng => {
  25186. const startPathRng = generatePathRangeFromRange(root, startRng);
  25187. return {
  25188. matches: results.matches.concat([{
  25189. pattern,
  25190. startRng: startPathRng,
  25191. endRng: endPathRng
  25192. }]),
  25193. position: point(startRng.startContainer, startRng.startOffset)
  25194. };
  25195. });
  25196. }
  25197. });
  25198. };
  25199. const findPatternsRec = (editor, patterns, node, offset, block) => {
  25200. const dom = editor.dom;
  25201. return textBefore(node, offset, dom.getRoot()).bind(endSpot => {
  25202. const rng = dom.createRng();
  25203. rng.setStart(block, 0);
  25204. rng.setEnd(node, offset);
  25205. const text = rng.toString();
  25206. for (let i = 0; i < patterns.length; i++) {
  25207. const pattern = patterns[i];
  25208. if (!endsWith(text, pattern.end)) {
  25209. continue;
  25210. }
  25211. const patternsWithoutCurrent = patterns.slice();
  25212. patternsWithoutCurrent.splice(i, 1);
  25213. const result = findPattern(editor, block, {
  25214. pattern,
  25215. remainingPatterns: patternsWithoutCurrent,
  25216. position: endSpot
  25217. });
  25218. if (result.isSome()) {
  25219. return result;
  25220. }
  25221. }
  25222. return Optional.none();
  25223. });
  25224. };
  25225. const applyPattern = (editor, pattern, patternRange) => {
  25226. editor.selection.setRng(patternRange);
  25227. if (pattern.type === 'inline-format') {
  25228. each$f(pattern.format, format => {
  25229. editor.formatter.apply(format);
  25230. });
  25231. } else {
  25232. editor.execCommand(pattern.cmd, false, pattern.value);
  25233. }
  25234. };
  25235. const applyReplacementPattern = (editor, pattern, marker, isRoot) => {
  25236. const markerRange = rangeFromMarker(editor.dom, marker);
  25237. deleteRng(editor.dom, markerRange, isRoot);
  25238. applyPattern(editor, pattern, markerRange);
  25239. };
  25240. const applyPatternWithContent = (editor, pattern, startMarker, endMarker, isRoot) => {
  25241. const dom = editor.dom;
  25242. const markerEndRange = rangeFromMarker(dom, endMarker);
  25243. const markerStartRange = rangeFromMarker(dom, startMarker);
  25244. deleteRng(dom, markerStartRange, isRoot);
  25245. deleteRng(dom, markerEndRange, isRoot);
  25246. const patternMarker = {
  25247. prefix: startMarker.prefix,
  25248. start: startMarker.end,
  25249. end: endMarker.start
  25250. };
  25251. const patternRange = rangeFromMarker(dom, patternMarker);
  25252. applyPattern(editor, pattern, patternRange);
  25253. };
  25254. const addMarkers = (dom, matches) => {
  25255. const markerPrefix = generate$1('mce_textpattern');
  25256. const matchesWithEnds = foldr(matches, (acc, match) => {
  25257. const endMarker = createMarker(dom, markerPrefix + `_end${ acc.length }`, match.endRng);
  25258. return acc.concat([{
  25259. ...match,
  25260. endMarker
  25261. }]);
  25262. }, []);
  25263. return foldr(matchesWithEnds, (acc, match) => {
  25264. const idx = matchesWithEnds.length - acc.length - 1;
  25265. const startMarker = isReplacementPattern(match.pattern) ? match.endMarker : createMarker(dom, markerPrefix + `_start${ idx }`, match.startRng);
  25266. return acc.concat([{
  25267. ...match,
  25268. startMarker
  25269. }]);
  25270. }, []);
  25271. };
  25272. const findPatterns = (editor, patterns, space) => {
  25273. const rng = editor.selection.getRng();
  25274. if (rng.collapsed === false) {
  25275. return [];
  25276. }
  25277. return getParentBlock(editor, rng).bind(block => {
  25278. const offset = Math.max(0, rng.startOffset - (space ? 1 : 0));
  25279. return findPatternsRec(editor, patterns, rng.startContainer, offset, block);
  25280. }).fold(() => [], result => result.matches);
  25281. };
  25282. const applyMatches = (editor, matches) => {
  25283. if (matches.length === 0) {
  25284. return;
  25285. }
  25286. const dom = editor.dom;
  25287. const bookmark = editor.selection.getBookmark();
  25288. const matchesWithMarkers = addMarkers(dom, matches);
  25289. each$f(matchesWithMarkers, match => {
  25290. const block = dom.getParent(match.startMarker.start, dom.isBlock);
  25291. const isRoot = node => node === block;
  25292. if (isReplacementPattern(match.pattern)) {
  25293. applyReplacementPattern(editor, match.pattern, match.endMarker, isRoot);
  25294. } else {
  25295. applyPatternWithContent(editor, match.pattern, match.startMarker, match.endMarker, isRoot);
  25296. }
  25297. removeMarker(dom, match.endMarker, isRoot);
  25298. removeMarker(dom, match.startMarker, isRoot);
  25299. });
  25300. editor.selection.moveToBookmark(bookmark);
  25301. };
  25302. const hasPatterns = patternSet => patternSet.inlinePatterns.length > 0 || patternSet.blockPatterns.length > 0;
  25303. const handleEnter = (editor, patternSet) => {
  25304. if (!editor.selection.isCollapsed() || !hasPatterns(patternSet)) {
  25305. return false;
  25306. }
  25307. const inlineMatches = findPatterns(editor, patternSet.inlinePatterns, false);
  25308. const blockMatches = findPatterns$1(editor, patternSet.blockPatterns);
  25309. if (blockMatches.length > 0 || inlineMatches.length > 0) {
  25310. editor.undoManager.add();
  25311. editor.undoManager.extra(() => {
  25312. editor.execCommand('mceInsertNewLine');
  25313. }, () => {
  25314. editor.insertContent(zeroWidth);
  25315. applyMatches(editor, inlineMatches);
  25316. applyMatches$1(editor, blockMatches);
  25317. const range = editor.selection.getRng();
  25318. const spot = textBefore(range.startContainer, range.startOffset, editor.dom.getRoot());
  25319. editor.execCommand('mceInsertNewLine');
  25320. spot.each(s => {
  25321. const node = s.container;
  25322. if (node.data.charAt(s.offset - 1) === zeroWidth) {
  25323. node.deleteData(s.offset - 1, 1);
  25324. cleanEmptyNodes(editor.dom, node.parentNode, e => e === editor.dom.getRoot());
  25325. }
  25326. });
  25327. });
  25328. return true;
  25329. }
  25330. return false;
  25331. };
  25332. const handleInlineKey = (editor, inlinePatterns) => {
  25333. if (inlinePatterns.length > 0) {
  25334. const inlineMatches = findPatterns(editor, inlinePatterns, true);
  25335. if (inlineMatches.length > 0) {
  25336. editor.undoManager.transact(() => {
  25337. applyMatches(editor, inlineMatches);
  25338. });
  25339. }
  25340. }
  25341. };
  25342. const checkKeyEvent = (codes, event, predicate) => {
  25343. for (let i = 0; i < codes.length; i++) {
  25344. if (predicate(codes[i], event)) {
  25345. return true;
  25346. }
  25347. }
  25348. return false;
  25349. };
  25350. const checkKeyCode = (codes, event) => checkKeyEvent(codes, event, (code, event) => {
  25351. return code === event.keyCode && VK.modifierPressed(event) === false;
  25352. });
  25353. const checkCharCode = (chars, event) => checkKeyEvent(chars, event, (chr, event) => {
  25354. return chr.charCodeAt(0) === event.charCode;
  25355. });
  25356. const setup$2 = editor => {
  25357. const charCodes = [
  25358. ',',
  25359. '.',
  25360. ';',
  25361. ':',
  25362. '!',
  25363. '?'
  25364. ];
  25365. const keyCodes = [32];
  25366. const getPatternSet = () => createPatternSet(getTextPatterns(editor));
  25367. const getInlinePatterns$1 = () => getInlinePatterns(getTextPatterns(editor));
  25368. editor.on('keydown', e => {
  25369. if (e.keyCode === 13 && !VK.modifierPressed(e)) {
  25370. if (handleEnter(editor, getPatternSet())) {
  25371. e.preventDefault();
  25372. }
  25373. }
  25374. }, true);
  25375. editor.on('keyup', e => {
  25376. if (checkKeyCode(keyCodes, e)) {
  25377. handleInlineKey(editor, getInlinePatterns$1());
  25378. }
  25379. });
  25380. editor.on('keypress', e => {
  25381. if (checkCharCode(charCodes, e)) {
  25382. Delay.setEditorTimeout(editor, () => {
  25383. handleInlineKey(editor, getInlinePatterns$1());
  25384. });
  25385. }
  25386. });
  25387. };
  25388. const setup$1 = editor => {
  25389. setup$2(editor);
  25390. };
  25391. const Quirks = editor => {
  25392. const each = Tools.each;
  25393. const BACKSPACE = VK.BACKSPACE, DELETE = VK.DELETE, dom = editor.dom, selection = editor.selection, parser = editor.parser;
  25394. const browser = Env.browser;
  25395. const isGecko = browser.isFirefox();
  25396. const isWebKit = browser.isChromium() || browser.isSafari();
  25397. const isiOS = Env.deviceType.isiPhone() || Env.deviceType.isiPad();
  25398. const isMac = Env.os.isMacOS() || Env.os.isiOS();
  25399. const setEditorCommandState = (cmd, state) => {
  25400. try {
  25401. editor.getDoc().execCommand(cmd, false, state);
  25402. } catch (ex) {
  25403. }
  25404. };
  25405. const isDefaultPrevented = e => {
  25406. return e.isDefaultPrevented();
  25407. };
  25408. const emptyEditorWhenDeleting = () => {
  25409. const serializeRng = rng => {
  25410. const body = dom.create('body');
  25411. const contents = rng.cloneContents();
  25412. body.appendChild(contents);
  25413. return selection.serializer.serialize(body, { format: 'html' });
  25414. };
  25415. const allContentsSelected = rng => {
  25416. const selection = serializeRng(rng);
  25417. const allRng = dom.createRng();
  25418. allRng.selectNode(editor.getBody());
  25419. const allSelection = serializeRng(allRng);
  25420. return selection === allSelection;
  25421. };
  25422. editor.on('keydown', e => {
  25423. const keyCode = e.keyCode;
  25424. let isCollapsed, body;
  25425. if (!isDefaultPrevented(e) && (keyCode === DELETE || keyCode === BACKSPACE)) {
  25426. isCollapsed = editor.selection.isCollapsed();
  25427. body = editor.getBody();
  25428. if (isCollapsed && !dom.isEmpty(body)) {
  25429. return;
  25430. }
  25431. if (!isCollapsed && !allContentsSelected(editor.selection.getRng())) {
  25432. return;
  25433. }
  25434. e.preventDefault();
  25435. editor.setContent('');
  25436. if (body.firstChild && dom.isBlock(body.firstChild)) {
  25437. editor.selection.setCursorLocation(body.firstChild, 0);
  25438. } else {
  25439. editor.selection.setCursorLocation(body, 0);
  25440. }
  25441. editor.nodeChanged();
  25442. }
  25443. });
  25444. };
  25445. const selectAll = () => {
  25446. editor.shortcuts.add('meta+a', null, 'SelectAll');
  25447. };
  25448. const documentElementEditingFocus = () => {
  25449. if (!editor.inline) {
  25450. dom.bind(editor.getDoc(), 'mousedown mouseup', e => {
  25451. let rng;
  25452. if (e.target === editor.getDoc().documentElement) {
  25453. rng = selection.getRng();
  25454. editor.getBody().focus();
  25455. if (e.type === 'mousedown') {
  25456. if (isCaretContainer$2(rng.startContainer)) {
  25457. return;
  25458. }
  25459. selection.placeCaretAt(e.clientX, e.clientY);
  25460. } else {
  25461. selection.setRng(rng);
  25462. }
  25463. }
  25464. });
  25465. }
  25466. };
  25467. const removeHrOnBackspace = () => {
  25468. editor.on('keydown', e => {
  25469. if (!isDefaultPrevented(e) && e.keyCode === BACKSPACE) {
  25470. if (!editor.getBody().getElementsByTagName('hr').length) {
  25471. return;
  25472. }
  25473. if (selection.isCollapsed() && selection.getRng().startOffset === 0) {
  25474. const node = selection.getNode();
  25475. const previousSibling = node.previousSibling;
  25476. if (node.nodeName === 'HR') {
  25477. dom.remove(node);
  25478. e.preventDefault();
  25479. return;
  25480. }
  25481. if (previousSibling && previousSibling.nodeName && previousSibling.nodeName.toLowerCase() === 'hr') {
  25482. dom.remove(previousSibling);
  25483. e.preventDefault();
  25484. }
  25485. }
  25486. }
  25487. });
  25488. };
  25489. const focusBody = () => {
  25490. if (!Range.prototype.getClientRects) {
  25491. editor.on('mousedown', e => {
  25492. if (!isDefaultPrevented(e) && e.target.nodeName === 'HTML') {
  25493. const body = editor.getBody();
  25494. body.blur();
  25495. Delay.setEditorTimeout(editor, () => {
  25496. body.focus();
  25497. });
  25498. }
  25499. });
  25500. }
  25501. };
  25502. const selectControlElements = () => {
  25503. const visualAidsAnchorClass = getVisualAidsAnchorClass(editor);
  25504. editor.on('click', e => {
  25505. const target = e.target;
  25506. if (/^(IMG|HR)$/.test(target.nodeName) && dom.getContentEditableParent(target) !== 'false') {
  25507. e.preventDefault();
  25508. editor.selection.select(target);
  25509. editor.nodeChanged();
  25510. }
  25511. if (target.nodeName === 'A' && dom.hasClass(target, visualAidsAnchorClass) && target.childNodes.length === 0) {
  25512. e.preventDefault();
  25513. selection.select(target);
  25514. }
  25515. });
  25516. };
  25517. const removeStylesWhenDeletingAcrossBlockElements = () => {
  25518. const getAttributeApplyFunction = () => {
  25519. const template = dom.getAttribs(selection.getStart().cloneNode(false));
  25520. return () => {
  25521. const target = selection.getStart();
  25522. if (target !== editor.getBody()) {
  25523. dom.setAttrib(target, 'style', null);
  25524. each(template, attr => {
  25525. target.setAttributeNode(attr.cloneNode(true));
  25526. });
  25527. }
  25528. };
  25529. };
  25530. const isSelectionAcrossElements = () => {
  25531. return !selection.isCollapsed() && dom.getParent(selection.getStart(), dom.isBlock) !== dom.getParent(selection.getEnd(), dom.isBlock);
  25532. };
  25533. editor.on('keypress', e => {
  25534. let applyAttributes;
  25535. if (!isDefaultPrevented(e) && (e.keyCode === 8 || e.keyCode === 46) && isSelectionAcrossElements()) {
  25536. applyAttributes = getAttributeApplyFunction();
  25537. editor.getDoc().execCommand('delete', false, null);
  25538. applyAttributes();
  25539. e.preventDefault();
  25540. return false;
  25541. }
  25542. });
  25543. dom.bind(editor.getDoc(), 'cut', e => {
  25544. let applyAttributes;
  25545. if (!isDefaultPrevented(e) && isSelectionAcrossElements()) {
  25546. applyAttributes = getAttributeApplyFunction();
  25547. Delay.setEditorTimeout(editor, () => {
  25548. applyAttributes();
  25549. });
  25550. }
  25551. });
  25552. };
  25553. const disableBackspaceIntoATable = () => {
  25554. editor.on('keydown', e => {
  25555. if (!isDefaultPrevented(e) && e.keyCode === BACKSPACE) {
  25556. if (selection.isCollapsed() && selection.getRng().startOffset === 0) {
  25557. const previousSibling = selection.getNode().previousSibling;
  25558. if (previousSibling && previousSibling.nodeName && previousSibling.nodeName.toLowerCase() === 'table') {
  25559. e.preventDefault();
  25560. return false;
  25561. }
  25562. }
  25563. }
  25564. });
  25565. };
  25566. const removeBlockQuoteOnBackSpace = () => {
  25567. editor.on('keydown', e => {
  25568. let rng, parent;
  25569. if (isDefaultPrevented(e) || e.keyCode !== VK.BACKSPACE) {
  25570. return;
  25571. }
  25572. rng = selection.getRng();
  25573. const container = rng.startContainer;
  25574. const offset = rng.startOffset;
  25575. const root = dom.getRoot();
  25576. parent = container;
  25577. if (!rng.collapsed || offset !== 0) {
  25578. return;
  25579. }
  25580. while (parent && parent.parentNode && parent.parentNode.firstChild === parent && parent.parentNode !== root) {
  25581. parent = parent.parentNode;
  25582. }
  25583. if (parent.tagName === 'BLOCKQUOTE') {
  25584. editor.formatter.toggle('blockquote', null, parent);
  25585. rng = dom.createRng();
  25586. rng.setStart(container, 0);
  25587. rng.setEnd(container, 0);
  25588. selection.setRng(rng);
  25589. }
  25590. });
  25591. };
  25592. const setGeckoEditingOptions = () => {
  25593. const setOpts = () => {
  25594. setEditorCommandState('StyleWithCSS', false);
  25595. setEditorCommandState('enableInlineTableEditing', false);
  25596. if (!getObjectResizing(editor)) {
  25597. setEditorCommandState('enableObjectResizing', false);
  25598. }
  25599. };
  25600. if (!isReadOnly$1(editor)) {
  25601. editor.on('BeforeExecCommand mousedown', setOpts);
  25602. }
  25603. };
  25604. const addBrAfterLastLinks = () => {
  25605. const fixLinks = () => {
  25606. each(dom.select('a'), node => {
  25607. let parentNode = node.parentNode;
  25608. const root = dom.getRoot();
  25609. if (parentNode.lastChild === node) {
  25610. while (parentNode && !dom.isBlock(parentNode)) {
  25611. if (parentNode.parentNode.lastChild !== parentNode || parentNode === root) {
  25612. return;
  25613. }
  25614. parentNode = parentNode.parentNode;
  25615. }
  25616. dom.add(parentNode, 'br', { 'data-mce-bogus': 1 });
  25617. }
  25618. });
  25619. };
  25620. editor.on('SetContent ExecCommand', e => {
  25621. if (e.type === 'setcontent' || e.command === 'mceInsertLink') {
  25622. fixLinks();
  25623. }
  25624. });
  25625. };
  25626. const setDefaultBlockType = () => {
  25627. editor.on('init', () => {
  25628. setEditorCommandState('DefaultParagraphSeparator', getForcedRootBlock(editor));
  25629. });
  25630. };
  25631. const isAllContentSelected = editor => {
  25632. const body = editor.getBody();
  25633. const rng = editor.selection.getRng();
  25634. return rng.startContainer === rng.endContainer && rng.startContainer === body && rng.startOffset === 0 && rng.endOffset === body.childNodes.length;
  25635. };
  25636. const normalizeSelection = () => {
  25637. editor.on('keyup focusin mouseup', e => {
  25638. if (!VK.modifierPressed(e) && !isAllContentSelected(editor)) {
  25639. selection.normalize();
  25640. }
  25641. }, true);
  25642. };
  25643. const showBrokenImageIcon = () => {
  25644. editor.contentStyles.push('img:-moz-broken {' + '-moz-force-broken-image-icon:1;' + 'min-width:24px;' + 'min-height:24px' + '}');
  25645. };
  25646. const restoreFocusOnKeyDown = () => {
  25647. if (!editor.inline) {
  25648. editor.on('keydown', () => {
  25649. if (document.activeElement === document.body) {
  25650. editor.getWin().focus();
  25651. }
  25652. });
  25653. }
  25654. };
  25655. const bodyHeight = () => {
  25656. if (!editor.inline) {
  25657. editor.contentStyles.push('body {min-height: 150px}');
  25658. editor.on('click', e => {
  25659. let rng;
  25660. if (e.target.nodeName === 'HTML') {
  25661. rng = editor.selection.getRng();
  25662. editor.getBody().focus();
  25663. editor.selection.setRng(rng);
  25664. editor.selection.normalize();
  25665. editor.nodeChanged();
  25666. }
  25667. });
  25668. }
  25669. };
  25670. const blockCmdArrowNavigation = () => {
  25671. if (isMac) {
  25672. editor.on('keydown', e => {
  25673. if (VK.metaKeyPressed(e) && !e.shiftKey && (e.keyCode === 37 || e.keyCode === 39)) {
  25674. e.preventDefault();
  25675. const selection = editor.selection.getSel();
  25676. selection.modify('move', e.keyCode === 37 ? 'backward' : 'forward', 'lineboundary');
  25677. }
  25678. });
  25679. }
  25680. };
  25681. const tapLinksAndImages = () => {
  25682. editor.on('click', e => {
  25683. let elm = e.target;
  25684. do {
  25685. if (elm.tagName === 'A') {
  25686. e.preventDefault();
  25687. return;
  25688. }
  25689. } while (elm = elm.parentNode);
  25690. });
  25691. editor.contentStyles.push('.mce-content-body {-webkit-touch-callout: none}');
  25692. };
  25693. const blockFormSubmitInsideEditor = () => {
  25694. editor.on('init', () => {
  25695. editor.dom.bind(editor.getBody(), 'submit', e => {
  25696. e.preventDefault();
  25697. });
  25698. });
  25699. };
  25700. const removeAppleInterchangeBrs = () => {
  25701. parser.addNodeFilter('br', nodes => {
  25702. let i = nodes.length;
  25703. while (i--) {
  25704. if (nodes[i].attr('class') === 'Apple-interchange-newline') {
  25705. nodes[i].remove();
  25706. }
  25707. }
  25708. });
  25709. };
  25710. const refreshContentEditable = noop;
  25711. const isHidden = () => {
  25712. if (!isGecko || editor.removed) {
  25713. return false;
  25714. }
  25715. const sel = editor.selection.getSel();
  25716. return !sel || !sel.rangeCount || sel.rangeCount === 0;
  25717. };
  25718. const setupRtc = () => {
  25719. if (isWebKit) {
  25720. documentElementEditingFocus();
  25721. selectControlElements();
  25722. blockFormSubmitInsideEditor();
  25723. selectAll();
  25724. if (isiOS) {
  25725. restoreFocusOnKeyDown();
  25726. bodyHeight();
  25727. tapLinksAndImages();
  25728. }
  25729. }
  25730. if (isGecko) {
  25731. focusBody();
  25732. setGeckoEditingOptions();
  25733. showBrokenImageIcon();
  25734. blockCmdArrowNavigation();
  25735. }
  25736. };
  25737. const setup = () => {
  25738. removeBlockQuoteOnBackSpace();
  25739. emptyEditorWhenDeleting();
  25740. if (!Env.windowsPhone) {
  25741. normalizeSelection();
  25742. }
  25743. if (isWebKit) {
  25744. documentElementEditingFocus();
  25745. selectControlElements();
  25746. setDefaultBlockType();
  25747. blockFormSubmitInsideEditor();
  25748. disableBackspaceIntoATable();
  25749. removeAppleInterchangeBrs();
  25750. if (isiOS) {
  25751. restoreFocusOnKeyDown();
  25752. bodyHeight();
  25753. tapLinksAndImages();
  25754. } else {
  25755. selectAll();
  25756. }
  25757. }
  25758. if (isGecko) {
  25759. removeHrOnBackspace();
  25760. focusBody();
  25761. removeStylesWhenDeletingAcrossBlockElements();
  25762. setGeckoEditingOptions();
  25763. addBrAfterLastLinks();
  25764. showBrokenImageIcon();
  25765. blockCmdArrowNavigation();
  25766. disableBackspaceIntoATable();
  25767. }
  25768. };
  25769. if (isRtc(editor)) {
  25770. setupRtc();
  25771. } else {
  25772. setup();
  25773. }
  25774. return {
  25775. refreshContentEditable,
  25776. isHidden
  25777. };
  25778. };
  25779. const DOM$6 = DOMUtils.DOM;
  25780. const appendStyle = (editor, text) => {
  25781. const body = SugarElement.fromDom(editor.getBody());
  25782. const container = getStyleContainer(getRootNode(body));
  25783. const style = SugarElement.fromTag('style');
  25784. set$2(style, 'type', 'text/css');
  25785. append$1(style, SugarElement.fromText(text));
  25786. append$1(container, style);
  25787. editor.on('remove', () => {
  25788. remove$6(style);
  25789. });
  25790. };
  25791. const getRootName = editor => editor.inline ? editor.getElement().nodeName.toLowerCase() : undefined;
  25792. const removeUndefined = obj => filter$5(obj, v => isUndefined(v) === false);
  25793. const mkParserSettings = editor => {
  25794. const getOption = editor.options.get;
  25795. const blobCache = editor.editorUpload.blobCache;
  25796. return removeUndefined({
  25797. allow_conditional_comments: getOption('allow_conditional_comments'),
  25798. allow_html_data_urls: getOption('allow_html_data_urls'),
  25799. allow_svg_data_urls: getOption('allow_svg_data_urls'),
  25800. allow_html_in_named_anchor: getOption('allow_html_in_named_anchor'),
  25801. allow_script_urls: getOption('allow_script_urls'),
  25802. allow_unsafe_link_target: getOption('allow_unsafe_link_target'),
  25803. convert_fonts_to_spans: getOption('convert_fonts_to_spans'),
  25804. fix_list_elements: getOption('fix_list_elements'),
  25805. font_size_legacy_values: getOption('font_size_legacy_values'),
  25806. forced_root_block: getOption('forced_root_block'),
  25807. forced_root_block_attrs: getOption('forced_root_block_attrs'),
  25808. preserve_cdata: getOption('preserve_cdata'),
  25809. remove_trailing_brs: getOption('remove_trailing_brs'),
  25810. inline_styles: getOption('inline_styles'),
  25811. root_name: getRootName(editor),
  25812. validate: true,
  25813. blob_cache: blobCache,
  25814. document: editor.getDoc()
  25815. });
  25816. };
  25817. const mkSchemaSettings = editor => {
  25818. const getOption = editor.options.get;
  25819. return removeUndefined({
  25820. custom_elements: getOption('custom_elements'),
  25821. extended_valid_elements: getOption('extended_valid_elements'),
  25822. invalid_elements: getOption('invalid_elements'),
  25823. invalid_styles: getOption('invalid_styles'),
  25824. schema: getOption('schema'),
  25825. valid_children: getOption('valid_children'),
  25826. valid_classes: getOption('valid_classes'),
  25827. valid_elements: getOption('valid_elements'),
  25828. valid_styles: getOption('valid_styles'),
  25829. verify_html: getOption('verify_html'),
  25830. padd_empty_block_inline_children: getOption('format_empty_lines')
  25831. });
  25832. };
  25833. const mkSerializerSettings = editor => {
  25834. const getOption = editor.options.get;
  25835. return {
  25836. ...mkParserSettings(editor),
  25837. ...mkSchemaSettings(editor),
  25838. ...removeUndefined({
  25839. url_converter: getOption('url_converter'),
  25840. url_converter_scope: getOption('url_converter_scope'),
  25841. element_format: getOption('element_format'),
  25842. entities: getOption('entities'),
  25843. entity_encoding: getOption('entity_encoding'),
  25844. indent: getOption('indent'),
  25845. indent_after: getOption('indent_after'),
  25846. indent_before: getOption('indent_before')
  25847. })
  25848. };
  25849. };
  25850. const createParser = editor => {
  25851. const parser = DomParser(mkParserSettings(editor), editor.schema);
  25852. parser.addAttributeFilter('src,href,style,tabindex', (nodes, name) => {
  25853. let i = nodes.length, node, value;
  25854. const dom = editor.dom;
  25855. const internalName = 'data-mce-' + name;
  25856. while (i--) {
  25857. node = nodes[i];
  25858. value = node.attr(name);
  25859. if (value && !node.attr(internalName)) {
  25860. if (value.indexOf('data:') === 0 || value.indexOf('blob:') === 0) {
  25861. continue;
  25862. }
  25863. if (name === 'style') {
  25864. value = dom.serializeStyle(dom.parseStyle(value), node.name);
  25865. if (!value.length) {
  25866. value = null;
  25867. }
  25868. node.attr(internalName, value);
  25869. node.attr(name, value);
  25870. } else if (name === 'tabindex') {
  25871. node.attr(internalName, value);
  25872. node.attr(name, null);
  25873. } else {
  25874. node.attr(internalName, editor.convertURL(value, name, node.name));
  25875. }
  25876. }
  25877. }
  25878. });
  25879. parser.addNodeFilter('script', nodes => {
  25880. let i = nodes.length;
  25881. while (i--) {
  25882. const node = nodes[i];
  25883. const type = node.attr('type') || 'no/type';
  25884. if (type.indexOf('mce-') !== 0) {
  25885. node.attr('type', 'mce-' + type);
  25886. }
  25887. }
  25888. });
  25889. if (editor.options.get('preserve_cdata')) {
  25890. parser.addNodeFilter('#cdata', nodes => {
  25891. let i = nodes.length;
  25892. while (i--) {
  25893. const node = nodes[i];
  25894. node.type = 8;
  25895. node.name = '#comment';
  25896. node.value = '[CDATA[' + editor.dom.encode(node.value) + ']]';
  25897. }
  25898. });
  25899. }
  25900. parser.addNodeFilter('p,h1,h2,h3,h4,h5,h6,div', nodes => {
  25901. let i = nodes.length;
  25902. const nonEmptyElements = editor.schema.getNonEmptyElements();
  25903. while (i--) {
  25904. const node = nodes[i];
  25905. if (node.isEmpty(nonEmptyElements) && node.getAll('br').length === 0) {
  25906. node.append(new AstNode('br', 1));
  25907. }
  25908. }
  25909. });
  25910. return parser;
  25911. };
  25912. const autoFocus = editor => {
  25913. const autoFocus = getAutoFocus(editor);
  25914. if (autoFocus) {
  25915. Delay.setEditorTimeout(editor, () => {
  25916. let focusEditor;
  25917. if (autoFocus === true) {
  25918. focusEditor = editor;
  25919. } else {
  25920. focusEditor = editor.editorManager.get(autoFocus);
  25921. }
  25922. if (!focusEditor.destroyed) {
  25923. focusEditor.focus();
  25924. }
  25925. }, 100);
  25926. }
  25927. };
  25928. const moveSelectionToFirstCaretPosition = editor => {
  25929. const root = editor.dom.getRoot();
  25930. if (!editor.inline && (!hasAnyRanges(editor) || editor.selection.getStart(true) === root)) {
  25931. firstPositionIn(root).each(pos => {
  25932. const node = pos.getNode();
  25933. const caretPos = isTable$3(node) ? firstPositionIn(node).getOr(pos) : pos;
  25934. editor.selection.setRng(caretPos.toRange());
  25935. });
  25936. }
  25937. };
  25938. const initEditor = editor => {
  25939. editor.bindPendingEventDelegates();
  25940. editor.initialized = true;
  25941. fireInit(editor);
  25942. editor.focus(true);
  25943. moveSelectionToFirstCaretPosition(editor);
  25944. editor.nodeChanged({ initial: true });
  25945. const initInstanceCallback = getInitInstanceCallback(editor);
  25946. if (isFunction(initInstanceCallback)) {
  25947. initInstanceCallback.call(editor, editor);
  25948. }
  25949. autoFocus(editor);
  25950. };
  25951. const getStyleSheetLoader$1 = editor => editor.inline ? editor.ui.styleSheetLoader : editor.dom.styleSheetLoader;
  25952. const makeStylesheetLoadingPromises = (editor, css, framedFonts) => {
  25953. const promises = [getStyleSheetLoader$1(editor).loadAll(css)];
  25954. if (editor.inline) {
  25955. return promises;
  25956. } else {
  25957. return promises.concat([editor.ui.styleSheetLoader.loadAll(framedFonts)]);
  25958. }
  25959. };
  25960. const loadContentCss = editor => {
  25961. const styleSheetLoader = getStyleSheetLoader$1(editor);
  25962. const fontCss = getFontCss(editor);
  25963. const css = editor.contentCSS;
  25964. const removeCss = () => {
  25965. styleSheetLoader.unloadAll(css);
  25966. if (!editor.inline) {
  25967. editor.ui.styleSheetLoader.unloadAll(fontCss);
  25968. }
  25969. };
  25970. const loaded = () => {
  25971. if (editor.removed) {
  25972. removeCss();
  25973. } else {
  25974. editor.on('remove', removeCss);
  25975. }
  25976. };
  25977. if (editor.contentStyles.length > 0) {
  25978. let contentCssText = '';
  25979. Tools.each(editor.contentStyles, style => {
  25980. contentCssText += style + '\r\n';
  25981. });
  25982. editor.dom.addStyle(contentCssText);
  25983. }
  25984. const allStylesheets = Promise.all(makeStylesheetLoadingPromises(editor, css, fontCss)).then(loaded).catch(loaded);
  25985. const contentStyle = getContentStyle(editor);
  25986. if (contentStyle) {
  25987. appendStyle(editor, contentStyle);
  25988. }
  25989. return allStylesheets;
  25990. };
  25991. const preInit = editor => {
  25992. const doc = editor.getDoc(), body = editor.getBody();
  25993. firePreInit(editor);
  25994. if (!shouldBrowserSpellcheck(editor)) {
  25995. doc.body.spellcheck = false;
  25996. DOM$6.setAttrib(body, 'spellcheck', 'false');
  25997. }
  25998. editor.quirks = Quirks(editor);
  25999. firePostRender(editor);
  26000. const directionality = getDirectionality(editor);
  26001. if (directionality !== undefined) {
  26002. body.dir = directionality;
  26003. }
  26004. const protect = getProtect(editor);
  26005. if (protect) {
  26006. editor.on('BeforeSetContent', e => {
  26007. Tools.each(protect, pattern => {
  26008. e.content = e.content.replace(pattern, str => {
  26009. return '<!--mce:protected ' + escape(str) + '-->';
  26010. });
  26011. });
  26012. });
  26013. }
  26014. editor.on('SetContent', () => {
  26015. editor.addVisual(editor.getBody());
  26016. });
  26017. editor.on('compositionstart compositionend', e => {
  26018. editor.composing = e.type === 'compositionstart';
  26019. });
  26020. };
  26021. const loadInitialContent = editor => {
  26022. if (!isRtc(editor)) {
  26023. editor.load({
  26024. initial: true,
  26025. format: 'html'
  26026. });
  26027. }
  26028. editor.startContent = editor.getContent({ format: 'raw' });
  26029. };
  26030. const initEditorWithInitialContent = editor => {
  26031. if (editor.removed !== true) {
  26032. loadInitialContent(editor);
  26033. initEditor(editor);
  26034. }
  26035. };
  26036. const contentBodyLoaded = editor => {
  26037. const targetElm = editor.getElement();
  26038. let doc = editor.getDoc();
  26039. if (editor.inline) {
  26040. DOM$6.addClass(targetElm, 'mce-content-body');
  26041. editor.contentDocument = doc = document;
  26042. editor.contentWindow = window;
  26043. editor.bodyElement = targetElm;
  26044. editor.contentAreaContainer = targetElm;
  26045. }
  26046. const body = editor.getBody();
  26047. body.disabled = true;
  26048. editor.readonly = isReadOnly$1(editor);
  26049. if (!editor.readonly) {
  26050. if (editor.inline && DOM$6.getStyle(body, 'position', true) === 'static') {
  26051. body.style.position = 'relative';
  26052. }
  26053. body.contentEditable = 'true';
  26054. }
  26055. body.disabled = false;
  26056. editor.editorUpload = EditorUpload(editor);
  26057. editor.schema = Schema(mkSchemaSettings(editor));
  26058. editor.dom = DOMUtils(doc, {
  26059. keep_values: true,
  26060. url_converter: editor.convertURL,
  26061. url_converter_scope: editor,
  26062. update_styles: true,
  26063. root_element: editor.inline ? editor.getBody() : null,
  26064. collect: () => editor.inline,
  26065. schema: editor.schema,
  26066. contentCssCors: shouldUseContentCssCors(editor),
  26067. referrerPolicy: getReferrerPolicy(editor),
  26068. onSetAttrib: e => {
  26069. editor.dispatch('SetAttrib', e);
  26070. }
  26071. });
  26072. editor.parser = createParser(editor);
  26073. editor.serializer = DomSerializer(mkSerializerSettings(editor), editor);
  26074. editor.selection = EditorSelection(editor.dom, editor.getWin(), editor.serializer, editor);
  26075. editor.annotator = Annotator(editor);
  26076. editor.formatter = Formatter(editor);
  26077. editor.undoManager = UndoManager(editor);
  26078. editor._nodeChangeDispatcher = new NodeChange(editor);
  26079. editor._selectionOverrides = SelectionOverrides(editor);
  26080. setup$o(editor);
  26081. setup$6(editor);
  26082. setup$m(editor);
  26083. if (!isRtc(editor)) {
  26084. setup$5(editor);
  26085. setup$1(editor);
  26086. }
  26087. const caret = setup$b(editor);
  26088. setup$p(editor, caret);
  26089. setup$n(editor);
  26090. setup$q(editor);
  26091. setup$7(editor);
  26092. const setupRtcThunk = setup$s(editor);
  26093. preInit(editor);
  26094. setupRtcThunk.fold(() => {
  26095. loadContentCss(editor).then(() => initEditorWithInitialContent(editor));
  26096. }, setupRtc => {
  26097. editor.setProgressState(true);
  26098. loadContentCss(editor).then(() => {
  26099. setupRtc().then(_rtcMode => {
  26100. editor.setProgressState(false);
  26101. initEditorWithInitialContent(editor);
  26102. bindEvents(editor);
  26103. }, err => {
  26104. editor.notificationManager.open({
  26105. type: 'error',
  26106. text: String(err)
  26107. });
  26108. initEditorWithInitialContent(editor);
  26109. bindEvents(editor);
  26110. });
  26111. });
  26112. });
  26113. };
  26114. const initContentBody = (editor, skipWrite) => {
  26115. if (!editor.inline) {
  26116. editor.getElement().style.visibility = editor.orgVisibility;
  26117. }
  26118. if (!skipWrite && !editor.inline) {
  26119. const iframe = editor.iframeElement;
  26120. const binder = bind$1(SugarElement.fromDom(iframe), 'load', () => {
  26121. binder.unbind();
  26122. editor.contentDocument = iframe.contentDocument;
  26123. contentBodyLoaded(editor);
  26124. });
  26125. iframe.srcdoc = editor.iframeHTML;
  26126. } else {
  26127. contentBodyLoaded(editor);
  26128. }
  26129. };
  26130. const DOM$5 = DOMUtils.DOM;
  26131. const createIframeElement = (id, title, customAttrs, tabindex) => {
  26132. const iframe = SugarElement.fromTag('iframe');
  26133. tabindex.each(t => set$2(iframe, 'tabindex', t));
  26134. setAll$1(iframe, customAttrs);
  26135. setAll$1(iframe, {
  26136. id: id + '_ifr',
  26137. frameBorder: '0',
  26138. allowTransparency: 'true',
  26139. title
  26140. });
  26141. add$2(iframe, 'tox-edit-area__iframe');
  26142. return iframe;
  26143. };
  26144. const getIframeHtml = editor => {
  26145. let iframeHTML = getDocType(editor) + '<html><head>';
  26146. if (getDocumentBaseUrl(editor) !== editor.documentBaseUrl) {
  26147. iframeHTML += '<base href="' + editor.documentBaseURI.getURI() + '" />';
  26148. }
  26149. iframeHTML += '<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />';
  26150. const bodyId = getBodyId(editor);
  26151. const bodyClass = getBodyClass(editor);
  26152. const translatedAriaText = editor.translate(getIframeAriaText(editor));
  26153. if (getContentSecurityPolicy(editor)) {
  26154. iframeHTML += '<meta http-equiv="Content-Security-Policy" content="' + getContentSecurityPolicy(editor) + '" />';
  26155. }
  26156. iframeHTML += '</head>' + `<body id="${ bodyId }" class="mce-content-body ${ bodyClass }" data-id="${ editor.id }" aria-label="${ translatedAriaText }">` + '<br>' + '</body></html>';
  26157. return iframeHTML;
  26158. };
  26159. const createIframe = (editor, boxInfo) => {
  26160. const iframeTitle = editor.translate('Rich Text Area');
  26161. const tabindex = getOpt(SugarElement.fromDom(editor.getElement()), 'tabindex').bind(toInt);
  26162. const ifr = createIframeElement(editor.id, iframeTitle, getIframeAttrs(editor), tabindex).dom;
  26163. ifr.onload = () => {
  26164. ifr.onload = null;
  26165. editor.dispatch('load');
  26166. };
  26167. editor.contentAreaContainer = boxInfo.iframeContainer;
  26168. editor.iframeElement = ifr;
  26169. editor.iframeHTML = getIframeHtml(editor);
  26170. DOM$5.add(boxInfo.iframeContainer, ifr);
  26171. };
  26172. const init$1 = (editor, boxInfo) => {
  26173. createIframe(editor, boxInfo);
  26174. if (boxInfo.editorContainer) {
  26175. DOM$5.get(boxInfo.editorContainer).style.display = editor.orgDisplay;
  26176. editor.hidden = DOM$5.isHidden(boxInfo.editorContainer);
  26177. }
  26178. editor.getElement().style.display = 'none';
  26179. DOM$5.setAttrib(editor.id, 'aria-hidden', 'true');
  26180. initContentBody(editor);
  26181. };
  26182. const DOM$4 = DOMUtils.DOM;
  26183. const initPlugin = (editor, initializedPlugins, plugin) => {
  26184. const Plugin = PluginManager.get(plugin);
  26185. const pluginUrl = PluginManager.urls[plugin] || editor.documentBaseUrl.replace(/\/$/, '');
  26186. plugin = Tools.trim(plugin);
  26187. if (Plugin && Tools.inArray(initializedPlugins, plugin) === -1) {
  26188. if (editor.plugins[plugin]) {
  26189. return;
  26190. }
  26191. try {
  26192. const pluginInstance = Plugin(editor, pluginUrl) || {};
  26193. editor.plugins[plugin] = pluginInstance;
  26194. if (isFunction(pluginInstance.init)) {
  26195. pluginInstance.init(editor, pluginUrl);
  26196. initializedPlugins.push(plugin);
  26197. }
  26198. } catch (e) {
  26199. pluginInitError(editor, plugin, e);
  26200. }
  26201. }
  26202. };
  26203. const trimLegacyPrefix = name => {
  26204. return name.replace(/^\-/, '');
  26205. };
  26206. const initPlugins = editor => {
  26207. const initializedPlugins = [];
  26208. each$f(getPlugins(editor), name => {
  26209. initPlugin(editor, initializedPlugins, trimLegacyPrefix(name));
  26210. });
  26211. };
  26212. const initIcons = editor => {
  26213. const iconPackName = Tools.trim(getIconPackName(editor));
  26214. const currentIcons = editor.ui.registry.getAll().icons;
  26215. const loadIcons = {
  26216. ...IconManager.get('default').icons,
  26217. ...IconManager.get(iconPackName).icons
  26218. };
  26219. each$e(loadIcons, (svgData, icon) => {
  26220. if (!has$2(currentIcons, icon)) {
  26221. editor.ui.registry.addIcon(icon, svgData);
  26222. }
  26223. });
  26224. };
  26225. const initTheme = editor => {
  26226. const theme = getTheme(editor);
  26227. if (isString(theme)) {
  26228. const Theme = ThemeManager.get(theme);
  26229. editor.theme = Theme(editor, ThemeManager.urls[theme]) || {};
  26230. if (isFunction(editor.theme.init)) {
  26231. editor.theme.init(editor, ThemeManager.urls[theme] || editor.documentBaseUrl.replace(/\/$/, ''));
  26232. }
  26233. } else {
  26234. editor.theme = {};
  26235. }
  26236. };
  26237. const initModel = editor => {
  26238. const model = getModel(editor);
  26239. const Model = ModelManager.get(model);
  26240. editor.model = Model(editor, ModelManager.urls[model]);
  26241. };
  26242. const renderFromLoadedTheme = editor => {
  26243. return editor.theme.renderUI();
  26244. };
  26245. const renderFromThemeFunc = editor => {
  26246. const elm = editor.getElement();
  26247. const theme = getTheme(editor);
  26248. const info = theme(editor, elm);
  26249. if (info.editorContainer.nodeType) {
  26250. info.editorContainer.id = info.editorContainer.id || editor.id + '_parent';
  26251. }
  26252. if (info.iframeContainer && info.iframeContainer.nodeType) {
  26253. info.iframeContainer.id = info.iframeContainer.id || editor.id + '_iframecontainer';
  26254. }
  26255. info.height = info.iframeHeight ? info.iframeHeight : elm.offsetHeight;
  26256. return info;
  26257. };
  26258. const createThemeFalseResult = element => {
  26259. return {
  26260. editorContainer: element,
  26261. iframeContainer: element,
  26262. api: {}
  26263. };
  26264. };
  26265. const renderThemeFalseIframe = targetElement => {
  26266. const iframeContainer = DOM$4.create('div');
  26267. DOM$4.insertAfter(iframeContainer, targetElement);
  26268. return createThemeFalseResult(iframeContainer);
  26269. };
  26270. const renderThemeFalse = editor => {
  26271. const targetElement = editor.getElement();
  26272. return editor.inline ? createThemeFalseResult(null) : renderThemeFalseIframe(targetElement);
  26273. };
  26274. const renderThemeUi = editor => {
  26275. const elm = editor.getElement();
  26276. editor.orgDisplay = elm.style.display;
  26277. if (isString(getTheme(editor))) {
  26278. return renderFromLoadedTheme(editor);
  26279. } else if (isFunction(getTheme(editor))) {
  26280. return renderFromThemeFunc(editor);
  26281. } else {
  26282. return renderThemeFalse(editor);
  26283. }
  26284. };
  26285. const augmentEditorUiApi = (editor, api) => {
  26286. const uiApiFacade = {
  26287. show: Optional.from(api.show).getOr(noop),
  26288. hide: Optional.from(api.hide).getOr(noop),
  26289. isEnabled: Optional.from(api.isEnabled).getOr(always),
  26290. setEnabled: state => {
  26291. if (!editor.mode.isReadOnly()) {
  26292. Optional.from(api.setEnabled).each(f => f(state));
  26293. }
  26294. }
  26295. };
  26296. editor.ui = {
  26297. ...editor.ui,
  26298. ...uiApiFacade
  26299. };
  26300. };
  26301. const init = editor => {
  26302. editor.dispatch('ScriptsLoaded');
  26303. initIcons(editor);
  26304. initTheme(editor);
  26305. initModel(editor);
  26306. initPlugins(editor);
  26307. const renderInfo = renderThemeUi(editor);
  26308. augmentEditorUiApi(editor, Optional.from(renderInfo.api).getOr({}));
  26309. const boxInfo = {
  26310. editorContainer: renderInfo.editorContainer,
  26311. iframeContainer: renderInfo.iframeContainer
  26312. };
  26313. editor.editorContainer = boxInfo.editorContainer ? boxInfo.editorContainer : null;
  26314. appendContentCssFromSettings(editor);
  26315. if (editor.inline) {
  26316. return initContentBody(editor);
  26317. } else {
  26318. return init$1(editor, boxInfo);
  26319. }
  26320. };
  26321. const DOM$3 = DOMUtils.DOM;
  26322. const hasSkipLoadPrefix = name => name.charAt(0) === '-';
  26323. const loadLanguage = (scriptLoader, editor) => {
  26324. const languageCode = getLanguageCode(editor);
  26325. const languageUrl = getLanguageUrl(editor);
  26326. if (I18n.hasCode(languageCode) === false && languageCode !== 'en') {
  26327. const url = isNotEmpty(languageUrl) ? languageUrl : `${ editor.editorManager.baseURL }/langs/${ languageCode }.js`;
  26328. scriptLoader.add(url).catch(() => {
  26329. languageLoadError(editor, url, languageCode);
  26330. });
  26331. }
  26332. };
  26333. const loadTheme = (editor, suffix) => {
  26334. const theme = getTheme(editor);
  26335. if (isString(theme) && !hasSkipLoadPrefix(theme) && !has$2(ThemeManager.urls, theme)) {
  26336. const themeUrl = getThemeUrl(editor);
  26337. const url = themeUrl ? editor.documentBaseURI.toAbsolute(themeUrl) : `themes/${ theme }/theme${ suffix }.js`;
  26338. ThemeManager.load(theme, url).catch(() => {
  26339. themeLoadError(editor, url, theme);
  26340. });
  26341. }
  26342. };
  26343. const loadModel = (editor, suffix) => {
  26344. const model = getModel(editor);
  26345. if (model !== 'plugin' && !has$2(ModelManager.urls, model)) {
  26346. const modelUrl = getModelUrl(editor);
  26347. const url = isString(modelUrl) ? editor.documentBaseURI.toAbsolute(modelUrl) : `models/${ model }/model${ suffix }.js`;
  26348. ModelManager.load(model, url).catch(() => {
  26349. modelLoadError(editor, url, model);
  26350. });
  26351. }
  26352. };
  26353. const getIconsUrlMetaFromUrl = editor => Optional.from(getIconsUrl(editor)).filter(isNotEmpty).map(url => ({
  26354. url,
  26355. name: Optional.none()
  26356. }));
  26357. const getIconsUrlMetaFromName = (editor, name, suffix) => Optional.from(name).filter(name => isNotEmpty(name) && !IconManager.has(name)).map(name => ({
  26358. url: `${ editor.editorManager.baseURL }/icons/${ name }/icons${ suffix }.js`,
  26359. name: Optional.some(name)
  26360. }));
  26361. const loadIcons = (scriptLoader, editor, suffix) => {
  26362. const defaultIconsUrl = getIconsUrlMetaFromName(editor, 'default', suffix);
  26363. const customIconsUrl = getIconsUrlMetaFromUrl(editor).orThunk(() => getIconsUrlMetaFromName(editor, getIconPackName(editor), ''));
  26364. each$f(cat([
  26365. defaultIconsUrl,
  26366. customIconsUrl
  26367. ]), urlMeta => {
  26368. scriptLoader.add(urlMeta.url).catch(() => {
  26369. iconsLoadError(editor, urlMeta.url, urlMeta.name.getOrUndefined());
  26370. });
  26371. });
  26372. };
  26373. const loadPlugins = (editor, suffix) => {
  26374. const loadPlugin = (name, url) => {
  26375. PluginManager.load(name, url).catch(() => {
  26376. pluginLoadError(editor, url, name);
  26377. });
  26378. };
  26379. each$e(getExternalPlugins$1(editor), (url, name) => {
  26380. loadPlugin(name, url);
  26381. editor.options.set('plugins', getPlugins(editor).concat(name));
  26382. });
  26383. each$f(getPlugins(editor), plugin => {
  26384. plugin = Tools.trim(plugin);
  26385. if (plugin && !PluginManager.urls[plugin] && !hasSkipLoadPrefix(plugin)) {
  26386. loadPlugin(plugin, `plugins/${ plugin }/plugin${ suffix }.js`);
  26387. }
  26388. });
  26389. };
  26390. const isThemeLoaded = editor => {
  26391. const theme = getTheme(editor);
  26392. return !isString(theme) || isNonNullable(ThemeManager.get(theme));
  26393. };
  26394. const isModelLoaded = editor => {
  26395. const model = getModel(editor);
  26396. return isNonNullable(ModelManager.get(model));
  26397. };
  26398. const loadScripts = (editor, suffix) => {
  26399. const scriptLoader = ScriptLoader.ScriptLoader;
  26400. const initEditor = () => {
  26401. if (!editor.removed && isThemeLoaded(editor) && isModelLoaded(editor)) {
  26402. init(editor);
  26403. }
  26404. };
  26405. loadTheme(editor, suffix);
  26406. loadModel(editor, suffix);
  26407. loadLanguage(scriptLoader, editor);
  26408. loadIcons(scriptLoader, editor, suffix);
  26409. loadPlugins(editor, suffix);
  26410. scriptLoader.loadQueue().then(initEditor, initEditor);
  26411. };
  26412. const getStyleSheetLoader = (element, editor) => instance.forElement(element, {
  26413. contentCssCors: hasContentCssCors(editor),
  26414. referrerPolicy: getReferrerPolicy(editor)
  26415. });
  26416. const render = editor => {
  26417. const id = editor.id;
  26418. I18n.setCode(getLanguageCode(editor));
  26419. const readyHandler = () => {
  26420. DOM$3.unbind(window, 'ready', readyHandler);
  26421. editor.render();
  26422. };
  26423. if (!EventUtils.Event.domLoaded) {
  26424. DOM$3.bind(window, 'ready', readyHandler);
  26425. return;
  26426. }
  26427. if (!editor.getElement()) {
  26428. return;
  26429. }
  26430. const element = SugarElement.fromDom(editor.getElement());
  26431. const snapshot = clone$4(element);
  26432. editor.on('remove', () => {
  26433. eachr(element.dom.attributes, attr => remove$b(element, attr.name));
  26434. setAll$1(element, snapshot);
  26435. });
  26436. editor.ui.styleSheetLoader = getStyleSheetLoader(element, editor);
  26437. if (!isInline(editor)) {
  26438. editor.orgVisibility = editor.getElement().style.visibility;
  26439. editor.getElement().style.visibility = 'hidden';
  26440. } else {
  26441. editor.inline = true;
  26442. }
  26443. const form = editor.getElement().form || DOM$3.getParent(id, 'form');
  26444. if (form) {
  26445. editor.formElement = form;
  26446. if (hasHiddenInput(editor) && !isTextareaOrInput(editor.getElement())) {
  26447. DOM$3.insertAfter(DOM$3.create('input', {
  26448. type: 'hidden',
  26449. name: id
  26450. }), id);
  26451. editor.hasHiddenInput = true;
  26452. }
  26453. editor.formEventDelegate = e => {
  26454. editor.dispatch(e.type, e);
  26455. };
  26456. DOM$3.bind(form, 'submit reset', editor.formEventDelegate);
  26457. editor.on('reset', () => {
  26458. editor.resetContent();
  26459. });
  26460. if (shouldPatchSubmit(editor) && !form.submit.nodeType && !form.submit.length && !form._mceOldSubmit) {
  26461. form._mceOldSubmit = form.submit;
  26462. form.submit = () => {
  26463. editor.editorManager.triggerSave();
  26464. editor.setDirty(false);
  26465. return form._mceOldSubmit(form);
  26466. };
  26467. }
  26468. }
  26469. editor.windowManager = WindowManager(editor);
  26470. editor.notificationManager = NotificationManager(editor);
  26471. if (isEncodingXml(editor)) {
  26472. editor.on('GetContent', e => {
  26473. if (e.save) {
  26474. e.content = DOM$3.encode(e.content);
  26475. }
  26476. });
  26477. }
  26478. if (shouldAddFormSubmitTrigger(editor)) {
  26479. editor.on('submit', () => {
  26480. if (editor.initialized) {
  26481. editor.save();
  26482. }
  26483. });
  26484. }
  26485. if (shouldAddUnloadTrigger(editor)) {
  26486. editor._beforeUnload = () => {
  26487. if (editor.initialized && !editor.destroyed && !editor.isHidden()) {
  26488. editor.save({
  26489. format: 'raw',
  26490. no_events: true,
  26491. set_dirty: false
  26492. });
  26493. }
  26494. };
  26495. editor.editorManager.on('BeforeUnload', editor._beforeUnload);
  26496. }
  26497. editor.editorManager.add(editor);
  26498. loadScripts(editor, editor.suffix);
  26499. };
  26500. const sectionResult = (sections, settings) => ({
  26501. sections: constant(sections),
  26502. options: constant(settings)
  26503. });
  26504. const deviceDetection = detect$2().deviceType;
  26505. const isPhone = deviceDetection.isPhone();
  26506. const isTablet = deviceDetection.isTablet();
  26507. const normalizePlugins = plugins => {
  26508. if (isNullable(plugins)) {
  26509. return [];
  26510. } else {
  26511. const pluginNames = isArray$1(plugins) ? plugins : plugins.split(/[ ,]/);
  26512. const trimmedPlugins = map$3(pluginNames, trim$3);
  26513. return filter$6(trimmedPlugins, isNotEmpty);
  26514. }
  26515. };
  26516. const extractSections = (keys, options) => {
  26517. const result = bifilter(options, (value, key) => {
  26518. return contains$2(keys, key);
  26519. });
  26520. return sectionResult(result.t, result.f);
  26521. };
  26522. const getSection = (sectionResult, name, defaults = {}) => {
  26523. const sections = sectionResult.sections();
  26524. const sectionOptions = get$a(sections, name).getOr({});
  26525. return Tools.extend({}, defaults, sectionOptions);
  26526. };
  26527. const hasSection = (sectionResult, name) => {
  26528. return has$2(sectionResult.sections(), name);
  26529. };
  26530. const getSectionConfig = (sectionResult, name) => {
  26531. return hasSection(sectionResult, name) ? sectionResult.sections()[name] : {};
  26532. };
  26533. const getMobileOverrideOptions = (mobileOptions, isPhone) => {
  26534. const defaultMobileOptions = {
  26535. table_grid: false,
  26536. object_resizing: false,
  26537. resize: false,
  26538. toolbar_mode: get$a(mobileOptions, 'toolbar_mode').getOr('scrolling'),
  26539. toolbar_sticky: false
  26540. };
  26541. const defaultPhoneOptions = { menubar: false };
  26542. return {
  26543. ...defaultMobileOptions,
  26544. ...isPhone ? defaultPhoneOptions : {}
  26545. };
  26546. };
  26547. const getExternalPlugins = (overrideOptions, options) => {
  26548. var _a;
  26549. const userDefinedExternalPlugins = (_a = options.external_plugins) !== null && _a !== void 0 ? _a : {};
  26550. if (overrideOptions && overrideOptions.external_plugins) {
  26551. return Tools.extend({}, overrideOptions.external_plugins, userDefinedExternalPlugins);
  26552. } else {
  26553. return userDefinedExternalPlugins;
  26554. }
  26555. };
  26556. const combinePlugins = (forcedPlugins, plugins) => {
  26557. return [].concat(normalizePlugins(forcedPlugins)).concat(normalizePlugins(plugins));
  26558. };
  26559. const getPlatformPlugins = (isMobileDevice, sectionResult, desktopPlugins, mobilePlugins) => {
  26560. if (isMobileDevice && hasSection(sectionResult, 'mobile')) {
  26561. return mobilePlugins;
  26562. } else {
  26563. return desktopPlugins;
  26564. }
  26565. };
  26566. const processPlugins = (isMobileDevice, sectionResult, defaultOverrideOptions, options) => {
  26567. const forcedPlugins = normalizePlugins(defaultOverrideOptions.forced_plugins);
  26568. const desktopPlugins = normalizePlugins(options.plugins);
  26569. const mobileConfig = getSectionConfig(sectionResult, 'mobile');
  26570. const mobilePlugins = mobileConfig.plugins ? normalizePlugins(mobileConfig.plugins) : desktopPlugins;
  26571. const platformPlugins = getPlatformPlugins(isMobileDevice, sectionResult, desktopPlugins, mobilePlugins);
  26572. const combinedPlugins = combinePlugins(forcedPlugins, platformPlugins);
  26573. return Tools.extend(options, {
  26574. forced_plugins: forcedPlugins,
  26575. plugins: combinedPlugins
  26576. });
  26577. };
  26578. const isOnMobile = (isMobileDevice, sectionResult) => {
  26579. return isMobileDevice && hasSection(sectionResult, 'mobile');
  26580. };
  26581. const combineOptions = (isMobileDevice, isPhone, defaultOptions, defaultOverrideOptions, options) => {
  26582. var _a;
  26583. const deviceOverrideOptions = isMobileDevice ? { mobile: getMobileOverrideOptions((_a = options.mobile) !== null && _a !== void 0 ? _a : {}, isPhone) } : {};
  26584. const sectionResult = extractSections(['mobile'], deepMerge(deviceOverrideOptions, options));
  26585. const extendedOptions = Tools.extend(defaultOptions, defaultOverrideOptions, sectionResult.options(), isOnMobile(isMobileDevice, sectionResult) ? getSection(sectionResult, 'mobile') : {}, { external_plugins: getExternalPlugins(defaultOverrideOptions, sectionResult.options()) });
  26586. return processPlugins(isMobileDevice, sectionResult, defaultOverrideOptions, extendedOptions);
  26587. };
  26588. const normalizeOptions = (defaultOverrideOptions, options) => combineOptions(isPhone || isTablet, isPhone, options, defaultOverrideOptions, options);
  26589. const addVisual = (editor, elm) => addVisual$1(editor, elm);
  26590. const registerExecCommands$3 = editor => {
  26591. const toggleFormat = (name, value) => {
  26592. editor.formatter.toggle(name, value);
  26593. editor.nodeChanged();
  26594. };
  26595. const toggleAlign = align => () => {
  26596. each$f('left,center,right,justify'.split(','), name => {
  26597. if (align !== name) {
  26598. editor.formatter.remove('align' + name);
  26599. }
  26600. });
  26601. if (align !== 'none') {
  26602. toggleFormat('align' + align);
  26603. }
  26604. };
  26605. editor.editorCommands.addCommands({
  26606. JustifyLeft: toggleAlign('left'),
  26607. JustifyCenter: toggleAlign('center'),
  26608. JustifyRight: toggleAlign('right'),
  26609. JustifyFull: toggleAlign('justify'),
  26610. JustifyNone: toggleAlign('none')
  26611. });
  26612. };
  26613. const registerQueryStateCommands$1 = editor => {
  26614. const alignStates = name => () => {
  26615. const selection = editor.selection;
  26616. const nodes = selection.isCollapsed() ? [editor.dom.getParent(selection.getNode(), editor.dom.isBlock)] : selection.getSelectedBlocks();
  26617. return exists(nodes, node => isNonNullable(editor.formatter.matchNode(node, name)));
  26618. };
  26619. editor.editorCommands.addCommands({
  26620. JustifyLeft: alignStates('alignleft'),
  26621. JustifyCenter: alignStates('aligncenter'),
  26622. JustifyRight: alignStates('alignright'),
  26623. JustifyFull: alignStates('alignjustify')
  26624. }, 'state');
  26625. };
  26626. const registerCommands$a = editor => {
  26627. registerExecCommands$3(editor);
  26628. registerQueryStateCommands$1(editor);
  26629. };
  26630. const registerCommands$9 = editor => {
  26631. editor.editorCommands.addCommands({
  26632. 'Cut,Copy,Paste': command => {
  26633. const doc = editor.getDoc();
  26634. let failed;
  26635. try {
  26636. doc.execCommand(command);
  26637. } catch (ex) {
  26638. failed = true;
  26639. }
  26640. if (command === 'paste' && !doc.queryCommandEnabled(command)) {
  26641. failed = true;
  26642. }
  26643. if (failed || !doc.queryCommandSupported(command)) {
  26644. let msg = editor.translate(`Your browser doesn't support direct access to the clipboard. ` + 'Please use the Ctrl+X/C/V keyboard shortcuts instead.');
  26645. if (Env.os.isMacOS() || Env.os.isiOS()) {
  26646. msg = msg.replace(/Ctrl\+/g, '\u2318+');
  26647. }
  26648. editor.notificationManager.open({
  26649. text: msg,
  26650. type: 'error'
  26651. });
  26652. }
  26653. }
  26654. });
  26655. };
  26656. const trimOrPadLeftRight = (dom, rng, html) => {
  26657. const root = SugarElement.fromDom(dom.getRoot());
  26658. if (needsToBeNbspLeft(root, CaretPosition.fromRangeStart(rng))) {
  26659. html = html.replace(/^ /, '&nbsp;');
  26660. } else {
  26661. html = html.replace(/^&nbsp;/, ' ');
  26662. }
  26663. if (needsToBeNbspRight(root, CaretPosition.fromRangeEnd(rng))) {
  26664. html = html.replace(/(&nbsp;| )(<br( \/)>)?$/, '&nbsp;');
  26665. } else {
  26666. html = html.replace(/&nbsp;(<br( \/)?>)?$/, ' ');
  26667. }
  26668. return html;
  26669. };
  26670. const processValue$1 = value => {
  26671. if (typeof value !== 'string') {
  26672. const details = Tools.extend({
  26673. paste: value.paste,
  26674. data: { paste: value.paste }
  26675. }, value);
  26676. return {
  26677. content: value.content,
  26678. details
  26679. };
  26680. }
  26681. return {
  26682. content: value,
  26683. details: {}
  26684. };
  26685. };
  26686. const trimOrPad = (editor, value) => {
  26687. const selection = editor.selection;
  26688. const dom = editor.dom;
  26689. if (/^ | $/.test(value)) {
  26690. return trimOrPadLeftRight(dom, selection.getRng(), value);
  26691. } else {
  26692. return value;
  26693. }
  26694. };
  26695. const insertAtCaret = (editor, value) => {
  26696. const {content, details} = processValue$1(value);
  26697. preProcessSetContent(editor, {
  26698. content: trimOrPad(editor, content),
  26699. format: 'html',
  26700. set: false,
  26701. selection: true,
  26702. paste: details.paste
  26703. }).each(args => {
  26704. const insertedContent = insertContent$1(editor, args.content, details);
  26705. postProcessSetContent(editor, insertedContent, args);
  26706. editor.addVisual();
  26707. });
  26708. };
  26709. const registerCommands$8 = editor => {
  26710. editor.editorCommands.addCommands({
  26711. mceCleanup: () => {
  26712. const bm = editor.selection.getBookmark();
  26713. editor.setContent(editor.getContent());
  26714. editor.selection.moveToBookmark(bm);
  26715. },
  26716. insertImage: (_command, _ui, value) => {
  26717. insertAtCaret(editor, editor.dom.createHTML('img', { src: value }));
  26718. },
  26719. insertHorizontalRule: () => {
  26720. editor.execCommand('mceInsertContent', false, '<hr>');
  26721. },
  26722. insertText: (_command, _ui, value) => {
  26723. insertAtCaret(editor, editor.dom.encode(value));
  26724. },
  26725. insertHTML: (_command, _ui, value) => {
  26726. insertAtCaret(editor, value);
  26727. },
  26728. mceInsertContent: (_command, _ui, value) => {
  26729. insertAtCaret(editor, value);
  26730. },
  26731. mceSetContent: (_command, _ui, value) => {
  26732. editor.setContent(value);
  26733. },
  26734. mceReplaceContent: (_command, _ui, value) => {
  26735. editor.execCommand('mceInsertContent', false, value.replace(/\{\$selection\}/g, editor.selection.getContent({ format: 'text' })));
  26736. },
  26737. mceNewDocument: () => {
  26738. editor.setContent('');
  26739. }
  26740. });
  26741. };
  26742. const legacyPropNames = {
  26743. 'font-size': 'size',
  26744. 'font-family': 'face'
  26745. };
  26746. const getSpecifiedFontProp = (propName, rootElm, elm) => {
  26747. const getProperty = elm => getRaw$1(elm, propName).orThunk(() => {
  26748. if (name(elm) === 'font') {
  26749. return get$a(legacyPropNames, propName).bind(legacyPropName => getOpt(elm, legacyPropName));
  26750. } else {
  26751. return Optional.none();
  26752. }
  26753. });
  26754. const isRoot = elm => eq(SugarElement.fromDom(rootElm), elm);
  26755. return closest$2(SugarElement.fromDom(elm), elm => getProperty(elm), isRoot);
  26756. };
  26757. const normalizeFontFamily = fontFamily => fontFamily.replace(/[\'\"\\]/g, '').replace(/,\s+/g, ',');
  26758. const getComputedFontProp = (propName, elm) => Optional.from(DOMUtils.DOM.getStyle(elm, propName, true));
  26759. 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('');
  26760. const getFontSize = getFontProp('font-size');
  26761. const getFontFamily = compose(normalizeFontFamily, getFontProp('font-family'));
  26762. const findFirstCaretElement = editor => firstPositionIn(editor.getBody()).map(caret => {
  26763. const container = caret.container();
  26764. return isText$9(container) ? container.parentNode : container;
  26765. });
  26766. const getCaretElement = editor => Optional.from(editor.selection.getRng()).bind(rng => {
  26767. const root = editor.getBody();
  26768. const atStartOfNode = rng.startContainer === root && rng.startOffset === 0;
  26769. return atStartOfNode ? Optional.none() : Optional.from(editor.selection.getStart(true));
  26770. });
  26771. const bindRange = (editor, binder) => getCaretElement(editor).orThunk(curry(findFirstCaretElement, editor)).map(SugarElement.fromDom).filter(isElement$7).bind(binder);
  26772. const mapRange = (editor, mapper) => bindRange(editor, compose1(Optional.some, mapper));
  26773. const fromFontSizeNumber = (editor, value) => {
  26774. if (/^[0-9.]+$/.test(value)) {
  26775. const fontSizeNumber = parseInt(value, 10);
  26776. if (fontSizeNumber >= 1 && fontSizeNumber <= 7) {
  26777. const fontSizes = getFontStyleValues(editor);
  26778. const fontClasses = getFontSizeClasses(editor);
  26779. if (fontClasses) {
  26780. return fontClasses[fontSizeNumber - 1] || value;
  26781. } else {
  26782. return fontSizes[fontSizeNumber - 1] || value;
  26783. }
  26784. } else {
  26785. return value;
  26786. }
  26787. } else {
  26788. return value;
  26789. }
  26790. };
  26791. const normalizeFontNames = font => {
  26792. const fonts = font.split(/\s*,\s*/);
  26793. return map$3(fonts, font => {
  26794. if (font.indexOf(' ') !== -1 && !(startsWith(font, '"') || startsWith(font, `'`))) {
  26795. return `'${ font }'`;
  26796. } else {
  26797. return font;
  26798. }
  26799. }).join(',');
  26800. };
  26801. const fontNameAction = (editor, value) => {
  26802. const font = fromFontSizeNumber(editor, value);
  26803. editor.formatter.toggle('fontname', { value: normalizeFontNames(font) });
  26804. editor.nodeChanged();
  26805. };
  26806. const fontNameQuery = editor => mapRange(editor, elm => getFontFamily(editor.getBody(), elm.dom)).getOr('');
  26807. const fontSizeAction = (editor, value) => {
  26808. editor.formatter.toggle('fontsize', { value: fromFontSizeNumber(editor, value) });
  26809. editor.nodeChanged();
  26810. };
  26811. const fontSizeQuery = editor => mapRange(editor, elm => getFontSize(editor.getBody(), elm.dom)).getOr('');
  26812. const lineHeightQuery = editor => mapRange(editor, elm => {
  26813. const root = SugarElement.fromDom(editor.getBody());
  26814. const specifiedStyle = closest$2(elm, elm => getRaw$1(elm, 'line-height'), curry(eq, root));
  26815. const computedStyle = () => {
  26816. const lineHeight = parseFloat(get$7(elm, 'line-height'));
  26817. const fontSize = parseFloat(get$7(elm, 'font-size'));
  26818. return String(lineHeight / fontSize);
  26819. };
  26820. return specifiedStyle.getOrThunk(computedStyle);
  26821. }).getOr('');
  26822. const lineHeightAction = (editor, lineHeight) => {
  26823. editor.formatter.toggle('lineheight', { value: String(lineHeight) });
  26824. editor.nodeChanged();
  26825. };
  26826. const registerExecCommands$2 = editor => {
  26827. const toggleFormat = (name, value) => {
  26828. editor.formatter.toggle(name, value);
  26829. editor.nodeChanged();
  26830. };
  26831. editor.editorCommands.addCommands({
  26832. 'Bold,Italic,Underline,Strikethrough,Superscript,Subscript': command => {
  26833. toggleFormat(command);
  26834. },
  26835. 'ForeColor,HiliteColor': (command, _ui, value) => {
  26836. toggleFormat(command, { value });
  26837. },
  26838. 'BackColor': (_command, _ui, value) => {
  26839. toggleFormat('hilitecolor', { value });
  26840. },
  26841. 'FontName': (_command, _ui, value) => {
  26842. fontNameAction(editor, value);
  26843. },
  26844. 'FontSize': (_command, _ui, value) => {
  26845. fontSizeAction(editor, value);
  26846. },
  26847. 'LineHeight': (_command, _ui, value) => {
  26848. lineHeightAction(editor, value);
  26849. },
  26850. 'Lang': (command, _ui, lang) => {
  26851. toggleFormat(command, {
  26852. value: lang.code,
  26853. customValue: lang.customCode
  26854. });
  26855. },
  26856. 'RemoveFormat': command => {
  26857. editor.formatter.remove(command);
  26858. },
  26859. 'mceBlockQuote': () => {
  26860. toggleFormat('blockquote');
  26861. },
  26862. 'FormatBlock': (_command, _ui, value) => {
  26863. toggleFormat(isString(value) ? value : 'p');
  26864. },
  26865. 'mceToggleFormat': (_command, _ui, value) => {
  26866. toggleFormat(value);
  26867. }
  26868. });
  26869. };
  26870. const registerQueryValueCommands = editor => {
  26871. const isFormatMatch = name => editor.formatter.match(name);
  26872. editor.editorCommands.addCommands({
  26873. 'Bold,Italic,Underline,Strikethrough,Superscript,Subscript': command => isFormatMatch(command),
  26874. 'mceBlockQuote': () => isFormatMatch('blockquote')
  26875. }, 'state');
  26876. editor.editorCommands.addQueryValueHandler('FontName', () => fontNameQuery(editor));
  26877. editor.editorCommands.addQueryValueHandler('FontSize', () => fontSizeQuery(editor));
  26878. editor.editorCommands.addQueryValueHandler('LineHeight', () => lineHeightQuery(editor));
  26879. };
  26880. const registerCommands$7 = editor => {
  26881. registerExecCommands$2(editor);
  26882. registerQueryValueCommands(editor);
  26883. };
  26884. const registerCommands$6 = editor => {
  26885. editor.editorCommands.addCommands({
  26886. mceAddUndoLevel: () => {
  26887. editor.undoManager.add();
  26888. },
  26889. mceEndUndoLevel: () => {
  26890. editor.undoManager.add();
  26891. },
  26892. Undo: () => {
  26893. editor.undoManager.undo();
  26894. },
  26895. Redo: () => {
  26896. editor.undoManager.redo();
  26897. }
  26898. });
  26899. };
  26900. const registerCommands$5 = editor => {
  26901. editor.editorCommands.addCommands({
  26902. Indent: () => {
  26903. indent(editor);
  26904. },
  26905. Outdent: () => {
  26906. outdent(editor);
  26907. }
  26908. });
  26909. editor.editorCommands.addCommands({ Outdent: () => canOutdent(editor) }, 'state');
  26910. };
  26911. const registerCommands$4 = editor => {
  26912. const applyLinkToSelection = (_command, _ui, value) => {
  26913. const linkDetails = isString(value) ? { href: value } : value;
  26914. const anchor = editor.dom.getParent(editor.selection.getNode(), 'a');
  26915. if (isObject(linkDetails) && isString(linkDetails.href)) {
  26916. linkDetails.href = linkDetails.href.replace(/ /g, '%20');
  26917. if (!anchor || !linkDetails.href) {
  26918. editor.formatter.remove('link');
  26919. }
  26920. if (linkDetails.href) {
  26921. editor.formatter.apply('link', linkDetails, anchor);
  26922. }
  26923. }
  26924. };
  26925. editor.editorCommands.addCommands({
  26926. unlink: () => {
  26927. if (editor.selection.isCollapsed()) {
  26928. const elm = editor.dom.getParent(editor.selection.getStart(), 'a');
  26929. if (elm) {
  26930. editor.dom.remove(elm, true);
  26931. }
  26932. return;
  26933. }
  26934. editor.formatter.remove('link');
  26935. },
  26936. mceInsertLink: applyLinkToSelection,
  26937. createLink: applyLinkToSelection
  26938. });
  26939. };
  26940. const registerExecCommands$1 = editor => {
  26941. editor.editorCommands.addCommands({
  26942. 'InsertUnorderedList,InsertOrderedList': command => {
  26943. editor.getDoc().execCommand(command);
  26944. const listElm = editor.dom.getParent(editor.selection.getNode(), 'ol,ul');
  26945. if (listElm) {
  26946. const listParent = listElm.parentNode;
  26947. if (/^(H[1-6]|P|ADDRESS|PRE)$/.test(listParent.nodeName)) {
  26948. const bm = editor.selection.getBookmark();
  26949. editor.dom.split(listParent, listElm);
  26950. editor.selection.moveToBookmark(bm);
  26951. }
  26952. }
  26953. }
  26954. });
  26955. };
  26956. const registerQueryStateCommands = editor => {
  26957. editor.editorCommands.addCommands({
  26958. 'InsertUnorderedList,InsertOrderedList': command => {
  26959. const list = editor.dom.getParent(editor.selection.getNode(), 'ul,ol');
  26960. return list && (command === 'insertunorderedlist' && list.tagName === 'UL' || command === 'insertorderedlist' && list.tagName === 'OL');
  26961. }
  26962. }, 'state');
  26963. };
  26964. const registerCommands$3 = editor => {
  26965. registerExecCommands$1(editor);
  26966. registerQueryStateCommands(editor);
  26967. };
  26968. const registerCommands$2 = editor => {
  26969. editor.editorCommands.addCommands({
  26970. insertParagraph: () => {
  26971. insertBreak(blockbreak, editor);
  26972. },
  26973. mceInsertNewLine: (_command, _ui, value) => {
  26974. insert(editor, value);
  26975. },
  26976. InsertLineBreak: (_command, _ui, _value) => {
  26977. insertBreak(linebreak, editor);
  26978. }
  26979. });
  26980. };
  26981. const registerCommands$1 = editor => {
  26982. editor.editorCommands.addCommands({
  26983. mceSelectNodeDepth: (_command, _ui, value) => {
  26984. let counter = 0;
  26985. editor.dom.getParent(editor.selection.getNode(), node => {
  26986. if (node.nodeType === 1 && counter++ === value) {
  26987. editor.selection.select(node);
  26988. return false;
  26989. }
  26990. }, editor.getBody());
  26991. },
  26992. mceSelectNode: (_command, _ui, value) => {
  26993. editor.selection.select(value);
  26994. },
  26995. selectAll: () => {
  26996. const editingHost = editor.dom.getParent(editor.selection.getStart(), isContentEditableTrue$5);
  26997. if (editingHost) {
  26998. const rng = editor.dom.createRng();
  26999. rng.selectNodeContents(editingHost);
  27000. editor.selection.setRng(rng);
  27001. }
  27002. }
  27003. });
  27004. };
  27005. const registerExecCommands = editor => {
  27006. editor.editorCommands.addCommands({
  27007. mceRemoveNode: (_command, _ui, value) => {
  27008. const node = value !== null && value !== void 0 ? value : editor.selection.getNode();
  27009. if (node !== editor.getBody()) {
  27010. const bm = editor.selection.getBookmark();
  27011. editor.dom.remove(node, true);
  27012. editor.selection.moveToBookmark(bm);
  27013. }
  27014. },
  27015. mcePrint: () => {
  27016. editor.getWin().print();
  27017. },
  27018. mceFocus: (_command, _ui, value) => {
  27019. focus(editor, value);
  27020. },
  27021. mceToggleVisualAid: () => {
  27022. editor.hasVisual = !editor.hasVisual;
  27023. editor.addVisual();
  27024. }
  27025. });
  27026. };
  27027. const registerCommands = editor => {
  27028. registerCommands$a(editor);
  27029. registerCommands$9(editor);
  27030. registerCommands$6(editor);
  27031. registerCommands$1(editor);
  27032. registerCommands$8(editor);
  27033. registerCommands$4(editor);
  27034. registerCommands$5(editor);
  27035. registerCommands$2(editor);
  27036. registerCommands$3(editor);
  27037. registerCommands$7(editor);
  27038. registerExecCommands(editor);
  27039. };
  27040. class EditorCommands {
  27041. constructor(editor) {
  27042. this.commands = {
  27043. state: {},
  27044. exec: {},
  27045. value: {}
  27046. };
  27047. this.editor = editor;
  27048. }
  27049. execCommand(command, ui, value, args) {
  27050. const editor = this.editor;
  27051. const lowerCaseCommand = command.toLowerCase();
  27052. const skipFocus = args === null || args === void 0 ? void 0 : args.skip_focus;
  27053. if (editor.removed) {
  27054. return false;
  27055. }
  27056. if (lowerCaseCommand !== 'mcefocus') {
  27057. if (!/^(mceAddUndoLevel|mceEndUndoLevel)$/i.test(lowerCaseCommand) && !skipFocus) {
  27058. editor.focus();
  27059. } else {
  27060. restore(editor);
  27061. }
  27062. }
  27063. const eventArgs = editor.dispatch('BeforeExecCommand', {
  27064. command,
  27065. ui,
  27066. value
  27067. });
  27068. if (eventArgs.isDefaultPrevented()) {
  27069. return false;
  27070. }
  27071. const func = this.commands.exec[lowerCaseCommand];
  27072. if (isFunction(func)) {
  27073. func(lowerCaseCommand, ui, value);
  27074. editor.dispatch('ExecCommand', {
  27075. command,
  27076. ui,
  27077. value
  27078. });
  27079. return true;
  27080. }
  27081. return false;
  27082. }
  27083. queryCommandState(command) {
  27084. if (this.editor.quirks.isHidden() || this.editor.removed) {
  27085. return false;
  27086. }
  27087. const lowerCaseCommand = command.toLowerCase();
  27088. const func = this.commands.state[lowerCaseCommand];
  27089. if (isFunction(func)) {
  27090. return func(lowerCaseCommand);
  27091. }
  27092. return false;
  27093. }
  27094. queryCommandValue(command) {
  27095. if (this.editor.quirks.isHidden() || this.editor.removed) {
  27096. return '';
  27097. }
  27098. const lowerCaseCommand = command.toLowerCase();
  27099. const func = this.commands.value[lowerCaseCommand];
  27100. if (isFunction(func)) {
  27101. return func(lowerCaseCommand);
  27102. }
  27103. return '';
  27104. }
  27105. addCommands(commandList, type = 'exec') {
  27106. const commands = this.commands;
  27107. each$e(commandList, (callback, command) => {
  27108. each$f(command.toLowerCase().split(','), command => {
  27109. commands[type][command] = callback;
  27110. });
  27111. });
  27112. }
  27113. addCommand(command, callback, scope) {
  27114. const lowerCaseCommand = command.toLowerCase();
  27115. this.commands.exec[lowerCaseCommand] = (_command, ui, value) => callback.call(scope !== null && scope !== void 0 ? scope : this.editor, ui, value);
  27116. }
  27117. queryCommandSupported(command) {
  27118. const lowerCaseCommand = command.toLowerCase();
  27119. if (this.commands.exec[lowerCaseCommand]) {
  27120. return true;
  27121. }
  27122. return false;
  27123. }
  27124. addQueryStateHandler(command, callback, scope) {
  27125. this.commands.state[command.toLowerCase()] = () => callback.call(scope !== null && scope !== void 0 ? scope : this.editor);
  27126. }
  27127. addQueryValueHandler(command, callback, scope) {
  27128. this.commands.value[command.toLowerCase()] = () => callback.call(scope !== null && scope !== void 0 ? scope : this.editor);
  27129. }
  27130. }
  27131. const internalContentEditableAttr = 'data-mce-contenteditable';
  27132. const toggleClass = (elm, cls, state) => {
  27133. if (has(elm, cls) && state === false) {
  27134. remove$8(elm, cls);
  27135. } else if (state) {
  27136. add$2(elm, cls);
  27137. }
  27138. };
  27139. const setEditorCommandState = (editor, cmd, state) => {
  27140. try {
  27141. editor.getDoc().execCommand(cmd, false, String(state));
  27142. } catch (ex) {
  27143. }
  27144. };
  27145. const setContentEditable = (elm, state) => {
  27146. elm.dom.contentEditable = state ? 'true' : 'false';
  27147. };
  27148. const switchOffContentEditableTrue = elm => {
  27149. each$f(descendants(elm, '*[contenteditable="true"]'), elm => {
  27150. set$2(elm, internalContentEditableAttr, 'true');
  27151. setContentEditable(elm, false);
  27152. });
  27153. };
  27154. const switchOnContentEditableTrue = elm => {
  27155. each$f(descendants(elm, `*[${ internalContentEditableAttr }="true"]`), elm => {
  27156. remove$b(elm, internalContentEditableAttr);
  27157. setContentEditable(elm, true);
  27158. });
  27159. };
  27160. const removeFakeSelection = editor => {
  27161. Optional.from(editor.selection.getNode()).each(elm => {
  27162. elm.removeAttribute('data-mce-selected');
  27163. });
  27164. };
  27165. const restoreFakeSelection = editor => {
  27166. editor.selection.setRng(editor.selection.getRng());
  27167. };
  27168. const toggleReadOnly = (editor, state) => {
  27169. const body = SugarElement.fromDom(editor.getBody());
  27170. toggleClass(body, 'mce-content-readonly', state);
  27171. if (state) {
  27172. editor.selection.controlSelection.hideResizeRect();
  27173. editor._selectionOverrides.hideFakeCaret();
  27174. removeFakeSelection(editor);
  27175. editor.readonly = true;
  27176. setContentEditable(body, false);
  27177. switchOffContentEditableTrue(body);
  27178. } else {
  27179. editor.readonly = false;
  27180. setContentEditable(body, true);
  27181. switchOnContentEditableTrue(body);
  27182. setEditorCommandState(editor, 'StyleWithCSS', false);
  27183. setEditorCommandState(editor, 'enableInlineTableEditing', false);
  27184. setEditorCommandState(editor, 'enableObjectResizing', false);
  27185. if (hasEditorOrUiFocus(editor)) {
  27186. editor.focus();
  27187. }
  27188. restoreFakeSelection(editor);
  27189. editor.nodeChanged();
  27190. }
  27191. };
  27192. const isReadOnly = editor => editor.readonly;
  27193. const registerFilters = editor => {
  27194. editor.parser.addAttributeFilter('contenteditable', nodes => {
  27195. if (isReadOnly(editor)) {
  27196. each$f(nodes, node => {
  27197. node.attr(internalContentEditableAttr, node.attr('contenteditable'));
  27198. node.attr('contenteditable', 'false');
  27199. });
  27200. }
  27201. });
  27202. editor.serializer.addAttributeFilter(internalContentEditableAttr, nodes => {
  27203. if (isReadOnly(editor)) {
  27204. each$f(nodes, node => {
  27205. node.attr('contenteditable', node.attr(internalContentEditableAttr));
  27206. });
  27207. }
  27208. });
  27209. editor.serializer.addTempAttr(internalContentEditableAttr);
  27210. };
  27211. const registerReadOnlyContentFilters = editor => {
  27212. if (editor.serializer) {
  27213. registerFilters(editor);
  27214. } else {
  27215. editor.on('PreInit', () => {
  27216. registerFilters(editor);
  27217. });
  27218. }
  27219. };
  27220. const isClickEvent = e => e.type === 'click';
  27221. const allowedEvents = ['copy'];
  27222. const isReadOnlyAllowedEvent = e => contains$2(allowedEvents, e.type);
  27223. const getAnchorHrefOpt = (editor, elm) => {
  27224. const isRoot = elm => eq(elm, SugarElement.fromDom(editor.getBody()));
  27225. return closest$3(elm, 'a', isRoot).bind(a => getOpt(a, 'href'));
  27226. };
  27227. const processReadonlyEvents = (editor, e) => {
  27228. if (isClickEvent(e) && !VK.metaKeyPressed(e)) {
  27229. const elm = SugarElement.fromDom(e.target);
  27230. getAnchorHrefOpt(editor, elm).each(href => {
  27231. e.preventDefault();
  27232. if (/^#/.test(href)) {
  27233. const targetEl = editor.dom.select(`${ href },[name="${ removeLeading(href, '#') }"]`);
  27234. if (targetEl.length) {
  27235. editor.selection.scrollIntoView(targetEl[0], true);
  27236. }
  27237. } else {
  27238. window.open(href, '_blank', 'rel=noopener noreferrer,menubar=yes,toolbar=yes,location=yes,status=yes,resizable=yes,scrollbars=yes');
  27239. }
  27240. });
  27241. } else if (isReadOnlyAllowedEvent(e)) {
  27242. editor.dispatch(e.type, e);
  27243. }
  27244. };
  27245. const registerReadOnlySelectionBlockers = editor => {
  27246. editor.on('ShowCaret', e => {
  27247. if (isReadOnly(editor)) {
  27248. e.preventDefault();
  27249. }
  27250. });
  27251. editor.on('ObjectSelected', e => {
  27252. if (isReadOnly(editor)) {
  27253. e.preventDefault();
  27254. }
  27255. });
  27256. };
  27257. 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', ' ');
  27258. class EventDispatcher {
  27259. constructor(settings) {
  27260. this.bindings = {};
  27261. this.settings = settings || {};
  27262. this.scope = this.settings.scope || this;
  27263. this.toggleEvent = this.settings.toggleEvent || never;
  27264. }
  27265. static isNative(name) {
  27266. return !!nativeEvents[name.toLowerCase()];
  27267. }
  27268. fire(name, args) {
  27269. return this.dispatch(name, args);
  27270. }
  27271. dispatch(name, args) {
  27272. const lcName = name.toLowerCase();
  27273. const event = normalize$3(lcName, args !== null && args !== void 0 ? args : {}, this.scope);
  27274. if (this.settings.beforeFire) {
  27275. this.settings.beforeFire(event);
  27276. }
  27277. const handlers = this.bindings[lcName];
  27278. if (handlers) {
  27279. for (let i = 0, l = handlers.length; i < l; i++) {
  27280. const callback = handlers[i];
  27281. if (callback.removed) {
  27282. continue;
  27283. }
  27284. if (callback.once) {
  27285. this.off(lcName, callback.func);
  27286. }
  27287. if (event.isImmediatePropagationStopped()) {
  27288. return event;
  27289. }
  27290. if (callback.func.call(this.scope, event) === false) {
  27291. event.preventDefault();
  27292. return event;
  27293. }
  27294. }
  27295. }
  27296. return event;
  27297. }
  27298. on(name, callback, prepend, extra) {
  27299. if (callback === false) {
  27300. callback = never;
  27301. }
  27302. if (callback) {
  27303. const wrappedCallback = {
  27304. func: callback,
  27305. removed: false
  27306. };
  27307. if (extra) {
  27308. Tools.extend(wrappedCallback, extra);
  27309. }
  27310. const names = name.toLowerCase().split(' ');
  27311. let i = names.length;
  27312. while (i--) {
  27313. const currentName = names[i];
  27314. let handlers = this.bindings[currentName];
  27315. if (!handlers) {
  27316. handlers = [];
  27317. this.toggleEvent(currentName, true);
  27318. }
  27319. if (prepend) {
  27320. handlers = [
  27321. wrappedCallback,
  27322. ...handlers
  27323. ];
  27324. } else {
  27325. handlers = [
  27326. ...handlers,
  27327. wrappedCallback
  27328. ];
  27329. }
  27330. this.bindings[currentName] = handlers;
  27331. }
  27332. }
  27333. return this;
  27334. }
  27335. off(name, callback) {
  27336. if (name) {
  27337. const names = name.toLowerCase().split(' ');
  27338. let i = names.length;
  27339. while (i--) {
  27340. const currentName = names[i];
  27341. let handlers = this.bindings[currentName];
  27342. if (!currentName) {
  27343. each$e(this.bindings, (_value, bindingName) => {
  27344. this.toggleEvent(bindingName, false);
  27345. delete this.bindings[bindingName];
  27346. });
  27347. return this;
  27348. }
  27349. if (handlers) {
  27350. if (!callback) {
  27351. handlers.length = 0;
  27352. } else {
  27353. const filteredHandlers = partition$2(handlers, handler => handler.func === callback);
  27354. handlers = filteredHandlers.fail;
  27355. this.bindings[currentName] = handlers;
  27356. each$f(filteredHandlers.pass, handler => {
  27357. handler.removed = true;
  27358. });
  27359. }
  27360. if (!handlers.length) {
  27361. this.toggleEvent(name, false);
  27362. delete this.bindings[currentName];
  27363. }
  27364. }
  27365. }
  27366. } else {
  27367. each$e(this.bindings, (_value, name) => {
  27368. this.toggleEvent(name, false);
  27369. });
  27370. this.bindings = {};
  27371. }
  27372. return this;
  27373. }
  27374. once(name, callback, prepend) {
  27375. return this.on(name, callback, prepend, { once: true });
  27376. }
  27377. has(name) {
  27378. name = name.toLowerCase();
  27379. return !(!this.bindings[name] || this.bindings[name].length === 0);
  27380. }
  27381. }
  27382. const getEventDispatcher = obj => {
  27383. if (!obj._eventDispatcher) {
  27384. obj._eventDispatcher = new EventDispatcher({
  27385. scope: obj,
  27386. toggleEvent: (name, state) => {
  27387. if (EventDispatcher.isNative(name) && obj.toggleNativeEvent) {
  27388. obj.toggleNativeEvent(name, state);
  27389. }
  27390. }
  27391. });
  27392. }
  27393. return obj._eventDispatcher;
  27394. };
  27395. const Observable = {
  27396. fire(name, args, bubble) {
  27397. return this.dispatch(name, args, bubble);
  27398. },
  27399. dispatch(name, args, bubble) {
  27400. const self = this;
  27401. if (self.removed && name !== 'remove' && name !== 'detach') {
  27402. return normalize$3(name.toLowerCase(), args !== null && args !== void 0 ? args : {}, self);
  27403. }
  27404. const dispatcherArgs = getEventDispatcher(self).dispatch(name, args);
  27405. if (bubble !== false && self.parent) {
  27406. let parent = self.parent();
  27407. while (parent && !dispatcherArgs.isPropagationStopped()) {
  27408. parent.dispatch(name, dispatcherArgs, false);
  27409. parent = parent.parent();
  27410. }
  27411. }
  27412. return dispatcherArgs;
  27413. },
  27414. on(name, callback, prepend) {
  27415. return getEventDispatcher(this).on(name, callback, prepend);
  27416. },
  27417. off(name, callback) {
  27418. return getEventDispatcher(this).off(name, callback);
  27419. },
  27420. once(name, callback) {
  27421. return getEventDispatcher(this).once(name, callback);
  27422. },
  27423. hasEventListeners(name) {
  27424. return getEventDispatcher(this).has(name);
  27425. }
  27426. };
  27427. const DOM$2 = DOMUtils.DOM;
  27428. let customEventRootDelegates;
  27429. const getEventTarget = (editor, eventName) => {
  27430. if (eventName === 'selectionchange') {
  27431. return editor.getDoc();
  27432. }
  27433. if (!editor.inline && /^mouse|touch|click|contextmenu|drop|dragover|dragend/.test(eventName)) {
  27434. return editor.getDoc().documentElement;
  27435. }
  27436. const eventRoot = getEventRoot(editor);
  27437. if (eventRoot) {
  27438. if (!editor.eventRoot) {
  27439. editor.eventRoot = DOM$2.select(eventRoot)[0];
  27440. }
  27441. return editor.eventRoot;
  27442. }
  27443. return editor.getBody();
  27444. };
  27445. const isListening = editor => !editor.hidden && !isReadOnly(editor);
  27446. const fireEvent = (editor, eventName, e) => {
  27447. if (isListening(editor)) {
  27448. editor.dispatch(eventName, e);
  27449. } else if (isReadOnly(editor)) {
  27450. processReadonlyEvents(editor, e);
  27451. }
  27452. };
  27453. const bindEventDelegate = (editor, eventName) => {
  27454. let delegate;
  27455. if (!editor.delegates) {
  27456. editor.delegates = {};
  27457. }
  27458. if (editor.delegates[eventName] || editor.removed) {
  27459. return;
  27460. }
  27461. const eventRootElm = getEventTarget(editor, eventName);
  27462. if (getEventRoot(editor)) {
  27463. if (!customEventRootDelegates) {
  27464. customEventRootDelegates = {};
  27465. editor.editorManager.on('removeEditor', () => {
  27466. if (!editor.editorManager.activeEditor) {
  27467. if (customEventRootDelegates) {
  27468. each$e(customEventRootDelegates, (_value, name) => {
  27469. editor.dom.unbind(getEventTarget(editor, name));
  27470. });
  27471. customEventRootDelegates = null;
  27472. }
  27473. }
  27474. });
  27475. }
  27476. if (customEventRootDelegates[eventName]) {
  27477. return;
  27478. }
  27479. delegate = e => {
  27480. const target = e.target;
  27481. const editors = editor.editorManager.get();
  27482. let i = editors.length;
  27483. while (i--) {
  27484. const body = editors[i].getBody();
  27485. if (body === target || DOM$2.isChildOf(target, body)) {
  27486. fireEvent(editors[i], eventName, e);
  27487. }
  27488. }
  27489. };
  27490. customEventRootDelegates[eventName] = delegate;
  27491. DOM$2.bind(eventRootElm, eventName, delegate);
  27492. } else {
  27493. delegate = e => {
  27494. fireEvent(editor, eventName, e);
  27495. };
  27496. DOM$2.bind(eventRootElm, eventName, delegate);
  27497. editor.delegates[eventName] = delegate;
  27498. }
  27499. };
  27500. const EditorObservable = {
  27501. ...Observable,
  27502. bindPendingEventDelegates() {
  27503. const self = this;
  27504. Tools.each(self._pendingNativeEvents, name => {
  27505. bindEventDelegate(self, name);
  27506. });
  27507. },
  27508. toggleNativeEvent(name, state) {
  27509. const self = this;
  27510. if (name === 'focus' || name === 'blur') {
  27511. return;
  27512. }
  27513. if (self.removed) {
  27514. return;
  27515. }
  27516. if (state) {
  27517. if (self.initialized) {
  27518. bindEventDelegate(self, name);
  27519. } else {
  27520. if (!self._pendingNativeEvents) {
  27521. self._pendingNativeEvents = [name];
  27522. } else {
  27523. self._pendingNativeEvents.push(name);
  27524. }
  27525. }
  27526. } else if (self.initialized) {
  27527. self.dom.unbind(getEventTarget(self, name), name, self.delegates[name]);
  27528. delete self.delegates[name];
  27529. }
  27530. },
  27531. unbindAllNativeEvents() {
  27532. const self = this;
  27533. const body = self.getBody();
  27534. const dom = self.dom;
  27535. if (self.delegates) {
  27536. each$e(self.delegates, (value, name) => {
  27537. self.dom.unbind(getEventTarget(self, name), name, value);
  27538. });
  27539. delete self.delegates;
  27540. }
  27541. if (!self.inline && body && dom) {
  27542. body.onload = null;
  27543. dom.unbind(self.getWin());
  27544. dom.unbind(self.getDoc());
  27545. }
  27546. if (dom) {
  27547. dom.unbind(body);
  27548. dom.unbind(self.getContainer());
  27549. }
  27550. }
  27551. };
  27552. const stringListProcessor = value => {
  27553. if (isString(value)) {
  27554. return {
  27555. value: value.split(/[ ,]/),
  27556. valid: true
  27557. };
  27558. } else if (isArrayOf(value, isString)) {
  27559. return {
  27560. value,
  27561. valid: true
  27562. };
  27563. } else {
  27564. return {
  27565. valid: false,
  27566. message: `The value must be a string[] or a comma/space separated string.`
  27567. };
  27568. }
  27569. };
  27570. const getBuiltInProcessor = type => {
  27571. const validator = (() => {
  27572. switch (type) {
  27573. case 'array':
  27574. return isArray$1;
  27575. case 'boolean':
  27576. return isBoolean;
  27577. case 'function':
  27578. return isFunction;
  27579. case 'number':
  27580. return isNumber;
  27581. case 'object':
  27582. return isObject;
  27583. case 'string':
  27584. return isString;
  27585. case 'string[]':
  27586. return stringListProcessor;
  27587. case 'object[]':
  27588. return val => isArrayOf(val, isObject);
  27589. case 'regexp':
  27590. return val => is$4(val, RegExp);
  27591. }
  27592. })();
  27593. return value => processValue(value, validator, `The value must be a ${ type }.`);
  27594. };
  27595. const isBuiltInSpec = spec => isString(spec.processor);
  27596. const getErrorMessage = (message, result) => {
  27597. const additionalText = isEmpty$3(result.message) ? '' : `. ${ result.message }`;
  27598. return message + additionalText;
  27599. };
  27600. const isValidResult = result => result.valid;
  27601. const processValue = (value, processor, message = '') => {
  27602. const result = processor(value);
  27603. if (isBoolean(result)) {
  27604. return result ? {
  27605. value: value,
  27606. valid: true
  27607. } : {
  27608. valid: false,
  27609. message
  27610. };
  27611. } else {
  27612. return result;
  27613. }
  27614. };
  27615. const processDefaultValue = (name, defaultValue, processor) => {
  27616. if (!isUndefined(defaultValue)) {
  27617. const result = processValue(defaultValue, processor);
  27618. if (isValidResult(result)) {
  27619. return result.value;
  27620. } else {
  27621. console.error(getErrorMessage(`Invalid default value passed for the "${ name }" option`, result));
  27622. }
  27623. }
  27624. return undefined;
  27625. };
  27626. const create$5 = (editor, initialOptions) => {
  27627. const registry = {};
  27628. const values = {};
  27629. const setValue = (name, value, processor) => {
  27630. const result = processValue(value, processor);
  27631. if (isValidResult(result)) {
  27632. values[name] = result.value;
  27633. return true;
  27634. } else {
  27635. console.warn(getErrorMessage(`Invalid value passed for the ${ name } option`, result));
  27636. return false;
  27637. }
  27638. };
  27639. const register = (name, spec) => {
  27640. const processor = isBuiltInSpec(spec) ? getBuiltInProcessor(spec.processor) : spec.processor;
  27641. const defaultValue = processDefaultValue(name, spec.default, processor);
  27642. registry[name] = {
  27643. ...spec,
  27644. default: defaultValue,
  27645. processor
  27646. };
  27647. const initValue = get$a(values, name).orThunk(() => get$a(initialOptions, name));
  27648. initValue.each(value => setValue(name, value, processor));
  27649. };
  27650. const isRegistered = name => has$2(registry, name);
  27651. const get = name => get$a(values, name).orThunk(() => get$a(registry, name).map(spec => spec.default)).getOrUndefined();
  27652. const set = (name, value) => {
  27653. if (!isRegistered(name)) {
  27654. console.warn(`"${ name }" is not a registered option. Ensure the option has been registered before setting a value.`);
  27655. return false;
  27656. } else {
  27657. const spec = registry[name];
  27658. if (spec.immutable) {
  27659. console.error(`"${ name }" is an immutable option and cannot be updated`);
  27660. return false;
  27661. } else {
  27662. return setValue(name, value, spec.processor);
  27663. }
  27664. }
  27665. };
  27666. const unset = name => {
  27667. const registered = isRegistered(name);
  27668. if (registered) {
  27669. delete values[name];
  27670. }
  27671. return registered;
  27672. };
  27673. const isSet = name => has$2(values, name);
  27674. return {
  27675. register,
  27676. isRegistered,
  27677. get,
  27678. set,
  27679. unset,
  27680. isSet
  27681. };
  27682. };
  27683. const defaultModes = [
  27684. 'design',
  27685. 'readonly'
  27686. ];
  27687. const switchToMode = (editor, activeMode, availableModes, mode) => {
  27688. const oldMode = availableModes[activeMode.get()];
  27689. const newMode = availableModes[mode];
  27690. try {
  27691. newMode.activate();
  27692. } catch (e) {
  27693. console.error(`problem while activating editor mode ${ mode }:`, e);
  27694. return;
  27695. }
  27696. oldMode.deactivate();
  27697. if (oldMode.editorReadOnly !== newMode.editorReadOnly) {
  27698. toggleReadOnly(editor, newMode.editorReadOnly);
  27699. }
  27700. activeMode.set(mode);
  27701. fireSwitchMode(editor, mode);
  27702. };
  27703. const setMode = (editor, availableModes, activeMode, mode) => {
  27704. if (mode === activeMode.get()) {
  27705. return;
  27706. } else if (!has$2(availableModes, mode)) {
  27707. throw new Error(`Editor mode '${ mode }' is invalid`);
  27708. }
  27709. if (editor.initialized) {
  27710. switchToMode(editor, activeMode, availableModes, mode);
  27711. } else {
  27712. editor.on('init', () => switchToMode(editor, activeMode, availableModes, mode));
  27713. }
  27714. };
  27715. const registerMode = (availableModes, mode, api) => {
  27716. if (contains$2(defaultModes, mode)) {
  27717. throw new Error(`Cannot override default mode ${ mode }`);
  27718. }
  27719. return {
  27720. ...availableModes,
  27721. [mode]: {
  27722. ...api,
  27723. deactivate: () => {
  27724. try {
  27725. api.deactivate();
  27726. } catch (e) {
  27727. console.error(`problem while deactivating editor mode ${ mode }:`, e);
  27728. }
  27729. }
  27730. }
  27731. };
  27732. };
  27733. const create$4 = editor => {
  27734. const activeMode = Cell('design');
  27735. const availableModes = Cell({
  27736. design: {
  27737. activate: noop,
  27738. deactivate: noop,
  27739. editorReadOnly: false
  27740. },
  27741. readonly: {
  27742. activate: noop,
  27743. deactivate: noop,
  27744. editorReadOnly: true
  27745. }
  27746. });
  27747. registerReadOnlyContentFilters(editor);
  27748. registerReadOnlySelectionBlockers(editor);
  27749. return {
  27750. isReadOnly: () => isReadOnly(editor),
  27751. set: mode => setMode(editor, availableModes.get(), activeMode, mode),
  27752. get: () => activeMode.get(),
  27753. register: (mode, api) => {
  27754. availableModes.set(registerMode(availableModes.get(), mode, api));
  27755. }
  27756. };
  27757. };
  27758. const each$2 = Tools.each, explode = Tools.explode;
  27759. const keyCodeLookup = {
  27760. f1: 112,
  27761. f2: 113,
  27762. f3: 114,
  27763. f4: 115,
  27764. f5: 116,
  27765. f6: 117,
  27766. f7: 118,
  27767. f8: 119,
  27768. f9: 120,
  27769. f10: 121,
  27770. f11: 122,
  27771. f12: 123
  27772. };
  27773. const modifierNames = Tools.makeMap('alt,ctrl,shift,meta,access');
  27774. const parseShortcut = pattern => {
  27775. let key;
  27776. const shortcut = {};
  27777. const isMac = Env.os.isMacOS() || Env.os.isiOS();
  27778. each$2(explode(pattern.toLowerCase(), '+'), value => {
  27779. if (value in modifierNames) {
  27780. shortcut[value] = true;
  27781. } else {
  27782. if (/^[0-9]{2,}$/.test(value)) {
  27783. shortcut.keyCode = parseInt(value, 10);
  27784. } else {
  27785. shortcut.charCode = value.charCodeAt(0);
  27786. shortcut.keyCode = keyCodeLookup[value] || value.toUpperCase().charCodeAt(0);
  27787. }
  27788. }
  27789. });
  27790. const id = [shortcut.keyCode];
  27791. for (key in modifierNames) {
  27792. if (shortcut[key]) {
  27793. id.push(key);
  27794. } else {
  27795. shortcut[key] = false;
  27796. }
  27797. }
  27798. shortcut.id = id.join(',');
  27799. if (shortcut.access) {
  27800. shortcut.alt = true;
  27801. if (isMac) {
  27802. shortcut.ctrl = true;
  27803. } else {
  27804. shortcut.shift = true;
  27805. }
  27806. }
  27807. if (shortcut.meta) {
  27808. if (isMac) {
  27809. shortcut.meta = true;
  27810. } else {
  27811. shortcut.ctrl = true;
  27812. shortcut.meta = false;
  27813. }
  27814. }
  27815. return shortcut;
  27816. };
  27817. class Shortcuts {
  27818. constructor(editor) {
  27819. this.shortcuts = {};
  27820. this.pendingPatterns = [];
  27821. this.editor = editor;
  27822. const self = this;
  27823. editor.on('keyup keypress keydown', e => {
  27824. if ((self.hasModifier(e) || self.isFunctionKey(e)) && !e.isDefaultPrevented()) {
  27825. each$2(self.shortcuts, shortcut => {
  27826. if (self.matchShortcut(e, shortcut)) {
  27827. self.pendingPatterns = shortcut.subpatterns.slice(0);
  27828. if (e.type === 'keydown') {
  27829. self.executeShortcutAction(shortcut);
  27830. }
  27831. return true;
  27832. }
  27833. });
  27834. if (self.matchShortcut(e, self.pendingPatterns[0])) {
  27835. if (self.pendingPatterns.length === 1) {
  27836. if (e.type === 'keydown') {
  27837. self.executeShortcutAction(self.pendingPatterns[0]);
  27838. }
  27839. }
  27840. self.pendingPatterns.shift();
  27841. }
  27842. }
  27843. });
  27844. }
  27845. add(pattern, desc, cmdFunc, scope) {
  27846. const self = this;
  27847. const func = self.normalizeCommandFunc(cmdFunc);
  27848. each$2(explode(Tools.trim(pattern)), pattern => {
  27849. const shortcut = self.createShortcut(pattern, desc, func, scope);
  27850. self.shortcuts[shortcut.id] = shortcut;
  27851. });
  27852. return true;
  27853. }
  27854. remove(pattern) {
  27855. const shortcut = this.createShortcut(pattern);
  27856. if (this.shortcuts[shortcut.id]) {
  27857. delete this.shortcuts[shortcut.id];
  27858. return true;
  27859. }
  27860. return false;
  27861. }
  27862. normalizeCommandFunc(cmdFunc) {
  27863. const self = this;
  27864. const cmd = cmdFunc;
  27865. if (typeof cmd === 'string') {
  27866. return () => {
  27867. self.editor.execCommand(cmd, false, null);
  27868. };
  27869. } else if (Tools.isArray(cmd)) {
  27870. return () => {
  27871. self.editor.execCommand(cmd[0], cmd[1], cmd[2]);
  27872. };
  27873. } else {
  27874. return cmd;
  27875. }
  27876. }
  27877. createShortcut(pattern, desc, cmdFunc, scope) {
  27878. const shortcuts = Tools.map(explode(pattern, '>'), parseShortcut);
  27879. shortcuts[shortcuts.length - 1] = Tools.extend(shortcuts[shortcuts.length - 1], {
  27880. func: cmdFunc,
  27881. scope: scope || this.editor
  27882. });
  27883. return Tools.extend(shortcuts[0], {
  27884. desc: this.editor.translate(desc),
  27885. subpatterns: shortcuts.slice(1)
  27886. });
  27887. }
  27888. hasModifier(e) {
  27889. return e.altKey || e.ctrlKey || e.metaKey;
  27890. }
  27891. isFunctionKey(e) {
  27892. return e.type === 'keydown' && e.keyCode >= 112 && e.keyCode <= 123;
  27893. }
  27894. matchShortcut(e, shortcut) {
  27895. if (!shortcut) {
  27896. return false;
  27897. }
  27898. if (shortcut.ctrl !== e.ctrlKey || shortcut.meta !== e.metaKey) {
  27899. return false;
  27900. }
  27901. if (shortcut.alt !== e.altKey || shortcut.shift !== e.shiftKey) {
  27902. return false;
  27903. }
  27904. if (e.keyCode === shortcut.keyCode || e.charCode && e.charCode === shortcut.charCode) {
  27905. e.preventDefault();
  27906. return true;
  27907. }
  27908. return false;
  27909. }
  27910. executeShortcutAction(shortcut) {
  27911. return shortcut.func ? shortcut.func.call(shortcut.scope) : null;
  27912. }
  27913. }
  27914. const create$3 = () => {
  27915. const buttons = {};
  27916. const menuItems = {};
  27917. const popups = {};
  27918. const icons = {};
  27919. const contextMenus = {};
  27920. const contextToolbars = {};
  27921. const sidebars = {};
  27922. const add = (collection, type) => (name, spec) => collection[name.toLowerCase()] = {
  27923. ...spec,
  27924. type
  27925. };
  27926. const addIcon = (name, svgData) => icons[name.toLowerCase()] = svgData;
  27927. return {
  27928. addButton: add(buttons, 'button'),
  27929. addGroupToolbarButton: add(buttons, 'grouptoolbarbutton'),
  27930. addToggleButton: add(buttons, 'togglebutton'),
  27931. addMenuButton: add(buttons, 'menubutton'),
  27932. addSplitButton: add(buttons, 'splitbutton'),
  27933. addMenuItem: add(menuItems, 'menuitem'),
  27934. addNestedMenuItem: add(menuItems, 'nestedmenuitem'),
  27935. addToggleMenuItem: add(menuItems, 'togglemenuitem'),
  27936. addAutocompleter: add(popups, 'autocompleter'),
  27937. addContextMenu: add(contextMenus, 'contextmenu'),
  27938. addContextToolbar: add(contextToolbars, 'contexttoolbar'),
  27939. addContextForm: add(contextToolbars, 'contextform'),
  27940. addSidebar: add(sidebars, 'sidebar'),
  27941. addIcon,
  27942. getAll: () => ({
  27943. buttons,
  27944. menuItems,
  27945. icons,
  27946. popups,
  27947. contextMenus,
  27948. contextToolbars,
  27949. sidebars
  27950. })
  27951. };
  27952. };
  27953. const registry = () => {
  27954. const bridge = create$3();
  27955. return {
  27956. addAutocompleter: bridge.addAutocompleter,
  27957. addButton: bridge.addButton,
  27958. addContextForm: bridge.addContextForm,
  27959. addContextMenu: bridge.addContextMenu,
  27960. addContextToolbar: bridge.addContextToolbar,
  27961. addIcon: bridge.addIcon,
  27962. addMenuButton: bridge.addMenuButton,
  27963. addMenuItem: bridge.addMenuItem,
  27964. addNestedMenuItem: bridge.addNestedMenuItem,
  27965. addSidebar: bridge.addSidebar,
  27966. addSplitButton: bridge.addSplitButton,
  27967. addToggleButton: bridge.addToggleButton,
  27968. addGroupToolbarButton: bridge.addGroupToolbarButton,
  27969. addToggleMenuItem: bridge.addToggleMenuItem,
  27970. getAll: bridge.getAll
  27971. };
  27972. };
  27973. const DOM$1 = DOMUtils.DOM;
  27974. const extend = Tools.extend, each$1 = Tools.each;
  27975. class Editor {
  27976. constructor(id, options, editorManager) {
  27977. this.plugins = {};
  27978. this.contentCSS = [];
  27979. this.contentStyles = [];
  27980. this.loadedCSS = {};
  27981. this.isNotDirty = false;
  27982. this.editorManager = editorManager;
  27983. this.documentBaseUrl = editorManager.documentBaseURL;
  27984. extend(this, EditorObservable);
  27985. const self = this;
  27986. this.id = id;
  27987. this.hidden = false;
  27988. const normalizedOptions = normalizeOptions(editorManager.defaultOptions, options);
  27989. this.options = create$5(self, normalizedOptions);
  27990. register$7(self);
  27991. const getOption = this.options.get;
  27992. if (getOption('deprecation_warnings')) {
  27993. logWarnings(options, normalizedOptions);
  27994. }
  27995. const suffix = getOption('suffix');
  27996. if (suffix) {
  27997. editorManager.suffix = suffix;
  27998. }
  27999. this.suffix = editorManager.suffix;
  28000. const baseUrl = getOption('base_url');
  28001. if (baseUrl) {
  28002. editorManager._setBaseUrl(baseUrl);
  28003. }
  28004. this.baseUri = editorManager.baseURI;
  28005. const referrerPolicy = getReferrerPolicy(self);
  28006. if (referrerPolicy) {
  28007. ScriptLoader.ScriptLoader._setReferrerPolicy(referrerPolicy);
  28008. DOMUtils.DOM.styleSheetLoader._setReferrerPolicy(referrerPolicy);
  28009. }
  28010. AddOnManager.languageLoad = getOption('language_load');
  28011. AddOnManager.baseURL = editorManager.baseURL;
  28012. this.setDirty(false);
  28013. this.documentBaseURI = new URI(getDocumentBaseUrl(self), { base_uri: this.baseUri });
  28014. this.baseURI = this.baseUri;
  28015. this.inline = isInline(self);
  28016. this.shortcuts = new Shortcuts(this);
  28017. this.editorCommands = new EditorCommands(this);
  28018. registerCommands(this);
  28019. const cacheSuffix = getOption('cache_suffix');
  28020. if (cacheSuffix) {
  28021. Env.cacheSuffix = cacheSuffix.replace(/^[\?\&]+/, '');
  28022. }
  28023. this.ui = {
  28024. registry: registry(),
  28025. styleSheetLoader: undefined,
  28026. show: noop,
  28027. hide: noop,
  28028. setEnabled: noop,
  28029. isEnabled: always
  28030. };
  28031. this.mode = create$4(self);
  28032. editorManager.dispatch('SetupEditor', { editor: this });
  28033. const setupCallback = getSetupCallback(self);
  28034. if (isFunction(setupCallback)) {
  28035. setupCallback.call(self, self);
  28036. }
  28037. }
  28038. render() {
  28039. render(this);
  28040. }
  28041. focus(skipFocus) {
  28042. this.execCommand('mceFocus', false, skipFocus);
  28043. }
  28044. hasFocus() {
  28045. return hasFocus(this);
  28046. }
  28047. translate(text) {
  28048. return I18n.translate(text);
  28049. }
  28050. getParam(name, defaultVal, type) {
  28051. const options = this.options;
  28052. if (!options.isRegistered(name)) {
  28053. if (isNonNullable(type)) {
  28054. options.register(name, {
  28055. processor: type,
  28056. default: defaultVal
  28057. });
  28058. } else {
  28059. options.register(name, {
  28060. processor: always,
  28061. default: defaultVal
  28062. });
  28063. }
  28064. }
  28065. return !options.isSet(name) && !isUndefined(defaultVal) ? defaultVal : options.get(name);
  28066. }
  28067. hasPlugin(name, loaded) {
  28068. const hasPlugin = contains$2(getPlugins(this), name);
  28069. if (hasPlugin) {
  28070. return loaded ? PluginManager.get(name) !== undefined : true;
  28071. } else {
  28072. return false;
  28073. }
  28074. }
  28075. nodeChanged(args) {
  28076. this._nodeChangeDispatcher.nodeChanged(args);
  28077. }
  28078. addCommand(name, callback, scope) {
  28079. this.editorCommands.addCommand(name, callback, scope);
  28080. }
  28081. addQueryStateHandler(name, callback, scope) {
  28082. this.editorCommands.addQueryStateHandler(name, callback, scope);
  28083. }
  28084. addQueryValueHandler(name, callback, scope) {
  28085. this.editorCommands.addQueryValueHandler(name, callback, scope);
  28086. }
  28087. addShortcut(pattern, desc, cmdFunc, scope) {
  28088. this.shortcuts.add(pattern, desc, cmdFunc, scope);
  28089. }
  28090. execCommand(cmd, ui, value, args) {
  28091. return this.editorCommands.execCommand(cmd, ui, value, args);
  28092. }
  28093. queryCommandState(cmd) {
  28094. return this.editorCommands.queryCommandState(cmd);
  28095. }
  28096. queryCommandValue(cmd) {
  28097. return this.editorCommands.queryCommandValue(cmd);
  28098. }
  28099. queryCommandSupported(cmd) {
  28100. return this.editorCommands.queryCommandSupported(cmd);
  28101. }
  28102. show() {
  28103. const self = this;
  28104. if (self.hidden) {
  28105. self.hidden = false;
  28106. if (self.inline) {
  28107. self.getBody().contentEditable = 'true';
  28108. } else {
  28109. DOM$1.show(self.getContainer());
  28110. DOM$1.hide(self.id);
  28111. }
  28112. self.load();
  28113. self.dispatch('show');
  28114. }
  28115. }
  28116. hide() {
  28117. const self = this;
  28118. if (!self.hidden) {
  28119. self.save();
  28120. if (self.inline) {
  28121. self.getBody().contentEditable = 'false';
  28122. if (self === self.editorManager.focusedEditor) {
  28123. self.editorManager.focusedEditor = null;
  28124. }
  28125. } else {
  28126. DOM$1.hide(self.getContainer());
  28127. DOM$1.setStyle(self.id, 'display', self.orgDisplay);
  28128. }
  28129. self.hidden = true;
  28130. self.dispatch('hide');
  28131. }
  28132. }
  28133. isHidden() {
  28134. return this.hidden;
  28135. }
  28136. setProgressState(state, time) {
  28137. this.dispatch('ProgressState', {
  28138. state,
  28139. time
  28140. });
  28141. }
  28142. load(args) {
  28143. const self = this;
  28144. let elm = self.getElement(), html;
  28145. if (self.removed) {
  28146. return '';
  28147. }
  28148. if (elm) {
  28149. args = args || {};
  28150. args.load = true;
  28151. const value = isTextareaOrInput(elm) ? elm.value : elm.innerHTML;
  28152. html = self.setContent(value, args);
  28153. args.element = elm;
  28154. if (!args.no_events) {
  28155. self.dispatch('LoadContent', args);
  28156. }
  28157. args.element = elm = null;
  28158. return html;
  28159. }
  28160. }
  28161. save(args) {
  28162. const self = this;
  28163. let elm = self.getElement(), html, form;
  28164. if (!elm || !self.initialized || self.removed) {
  28165. return;
  28166. }
  28167. args = args || {};
  28168. args.save = true;
  28169. args.element = elm;
  28170. html = args.content = self.getContent(args);
  28171. if (!args.no_events) {
  28172. self.dispatch('SaveContent', args);
  28173. }
  28174. if (args.format === 'raw') {
  28175. self.dispatch('RawSaveContent', args);
  28176. }
  28177. html = args.content;
  28178. if (!isTextareaOrInput(elm)) {
  28179. if (args.is_removing || !self.inline) {
  28180. elm.innerHTML = html;
  28181. }
  28182. if (form = DOM$1.getParent(self.id, 'form')) {
  28183. each$1(form.elements, elm => {
  28184. if (elm.name === self.id) {
  28185. elm.value = html;
  28186. return false;
  28187. }
  28188. });
  28189. }
  28190. } else {
  28191. elm.value = html;
  28192. }
  28193. args.element = elm = null;
  28194. if (args.set_dirty !== false) {
  28195. self.setDirty(false);
  28196. }
  28197. return html;
  28198. }
  28199. setContent(content, args) {
  28200. return setContent(this, content, args);
  28201. }
  28202. getContent(args) {
  28203. return getContent(this, args);
  28204. }
  28205. insertContent(content, args) {
  28206. if (args) {
  28207. content = extend({ content }, args);
  28208. }
  28209. this.execCommand('mceInsertContent', false, content);
  28210. }
  28211. resetContent(initialContent) {
  28212. if (initialContent === undefined) {
  28213. setContent(this, this.startContent, { format: 'raw' });
  28214. } else {
  28215. setContent(this, initialContent);
  28216. }
  28217. this.undoManager.reset();
  28218. this.setDirty(false);
  28219. this.nodeChanged();
  28220. }
  28221. isDirty() {
  28222. return !this.isNotDirty;
  28223. }
  28224. setDirty(state) {
  28225. const oldState = !this.isNotDirty;
  28226. this.isNotDirty = !state;
  28227. if (state && state !== oldState) {
  28228. this.dispatch('dirty');
  28229. }
  28230. }
  28231. getContainer() {
  28232. const self = this;
  28233. if (!self.container) {
  28234. self.container = DOM$1.get(self.editorContainer || self.id + '_parent');
  28235. }
  28236. return self.container;
  28237. }
  28238. getContentAreaContainer() {
  28239. return this.contentAreaContainer;
  28240. }
  28241. getElement() {
  28242. if (!this.targetElm) {
  28243. this.targetElm = DOM$1.get(this.id);
  28244. }
  28245. return this.targetElm;
  28246. }
  28247. getWin() {
  28248. const self = this;
  28249. let elm;
  28250. if (!self.contentWindow) {
  28251. elm = self.iframeElement;
  28252. if (elm) {
  28253. self.contentWindow = elm.contentWindow;
  28254. }
  28255. }
  28256. return self.contentWindow;
  28257. }
  28258. getDoc() {
  28259. const self = this;
  28260. let win;
  28261. if (!self.contentDocument) {
  28262. win = self.getWin();
  28263. if (win) {
  28264. self.contentDocument = win.document;
  28265. }
  28266. }
  28267. return self.contentDocument;
  28268. }
  28269. getBody() {
  28270. const doc = this.getDoc();
  28271. return this.bodyElement || (doc ? doc.body : null);
  28272. }
  28273. convertURL(url, name, elm) {
  28274. const self = this, getOption = self.options.get;
  28275. const urlConverterCallback = getUrlConverterCallback(self);
  28276. if (isFunction(urlConverterCallback)) {
  28277. return urlConverterCallback.call(self, url, elm, true, name);
  28278. }
  28279. if (!getOption('convert_urls') || elm && elm.nodeName === 'LINK' || url.indexOf('file:') === 0 || url.length === 0) {
  28280. return url;
  28281. }
  28282. if (getOption('relative_urls')) {
  28283. return self.documentBaseURI.toRelative(url);
  28284. }
  28285. url = self.documentBaseURI.toAbsolute(url, getOption('remove_script_host'));
  28286. return url;
  28287. }
  28288. addVisual(elm) {
  28289. addVisual(this, elm);
  28290. }
  28291. remove() {
  28292. remove$1(this);
  28293. }
  28294. destroy(automatic) {
  28295. destroy(this, automatic);
  28296. }
  28297. uploadImages() {
  28298. return this.editorUpload.uploadImages();
  28299. }
  28300. _scanForImages() {
  28301. return this.editorUpload.scanForImages();
  28302. }
  28303. }
  28304. const DOM = DOMUtils.DOM;
  28305. const each = Tools.each;
  28306. let boundGlobalEvents = false;
  28307. let beforeUnloadDelegate;
  28308. let editors = [];
  28309. const globalEventDelegate = e => {
  28310. const type = e.type;
  28311. each(EditorManager.get(), editor => {
  28312. switch (type) {
  28313. case 'scroll':
  28314. editor.dispatch('ScrollWindow', e);
  28315. break;
  28316. case 'resize':
  28317. editor.dispatch('ResizeWindow', e);
  28318. break;
  28319. }
  28320. });
  28321. };
  28322. const toggleGlobalEvents = state => {
  28323. if (state !== boundGlobalEvents) {
  28324. const DOM = DOMUtils.DOM;
  28325. if (state) {
  28326. DOM.bind(window, 'resize', globalEventDelegate);
  28327. DOM.bind(window, 'scroll', globalEventDelegate);
  28328. } else {
  28329. DOM.unbind(window, 'resize', globalEventDelegate);
  28330. DOM.unbind(window, 'scroll', globalEventDelegate);
  28331. }
  28332. boundGlobalEvents = state;
  28333. }
  28334. };
  28335. const removeEditorFromList = targetEditor => {
  28336. const oldEditors = editors;
  28337. editors = filter$6(editors, editor => {
  28338. return targetEditor !== editor;
  28339. });
  28340. if (EditorManager.activeEditor === targetEditor) {
  28341. EditorManager.activeEditor = editors.length > 0 ? editors[0] : null;
  28342. }
  28343. if (EditorManager.focusedEditor === targetEditor) {
  28344. EditorManager.focusedEditor = null;
  28345. }
  28346. return oldEditors.length !== editors.length;
  28347. };
  28348. const purgeDestroyedEditor = editor => {
  28349. if (editor && editor.initialized && !(editor.getContainer() || editor.getBody()).parentNode) {
  28350. removeEditorFromList(editor);
  28351. editor.unbindAllNativeEvents();
  28352. editor.destroy(true);
  28353. editor.removed = true;
  28354. editor = null;
  28355. }
  28356. return editor;
  28357. };
  28358. const isQuirksMode = document.compatMode !== 'CSS1Compat';
  28359. const EditorManager = {
  28360. ...Observable,
  28361. baseURI: null,
  28362. baseURL: null,
  28363. defaultOptions: {},
  28364. documentBaseURL: null,
  28365. suffix: null,
  28366. majorVersion: '6',
  28367. minorVersion: '1.0',
  28368. releaseDate: '2022-06-29',
  28369. i18n: I18n,
  28370. activeEditor: null,
  28371. focusedEditor: null,
  28372. setup() {
  28373. const self = this;
  28374. let baseURL, documentBaseURL, suffix = '';
  28375. documentBaseURL = URI.getDocumentBaseUrl(document.location);
  28376. if (/^[^:]+:\/\/\/?[^\/]+\//.test(documentBaseURL)) {
  28377. documentBaseURL = documentBaseURL.replace(/[\?#].*$/, '').replace(/[\/\\][^\/]+$/, '');
  28378. if (!/[\/\\]$/.test(documentBaseURL)) {
  28379. documentBaseURL += '/';
  28380. }
  28381. }
  28382. const preInit = window.tinymce || window.tinyMCEPreInit;
  28383. if (preInit) {
  28384. baseURL = preInit.base || preInit.baseURL;
  28385. suffix = preInit.suffix;
  28386. } else {
  28387. const scripts = document.getElementsByTagName('script');
  28388. for (let i = 0; i < scripts.length; i++) {
  28389. const src = scripts[i].src || '';
  28390. if (src === '') {
  28391. continue;
  28392. }
  28393. const srcScript = src.substring(src.lastIndexOf('/'));
  28394. if (/tinymce(\.full|\.jquery|)(\.min|\.dev|)\.js/.test(src)) {
  28395. if (srcScript.indexOf('.min') !== -1) {
  28396. suffix = '.min';
  28397. }
  28398. baseURL = src.substring(0, src.lastIndexOf('/'));
  28399. break;
  28400. }
  28401. }
  28402. if (!baseURL && document.currentScript) {
  28403. const src = document.currentScript.src;
  28404. if (src.indexOf('.min') !== -1) {
  28405. suffix = '.min';
  28406. }
  28407. baseURL = src.substring(0, src.lastIndexOf('/'));
  28408. }
  28409. }
  28410. self.baseURL = new URI(documentBaseURL).toAbsolute(baseURL);
  28411. self.documentBaseURL = documentBaseURL;
  28412. self.baseURI = new URI(self.baseURL);
  28413. self.suffix = suffix;
  28414. setup$v(self);
  28415. },
  28416. overrideDefaults(defaultOptions) {
  28417. const baseUrl = defaultOptions.base_url;
  28418. if (baseUrl) {
  28419. this._setBaseUrl(baseUrl);
  28420. }
  28421. const suffix = defaultOptions.suffix;
  28422. if (defaultOptions.suffix) {
  28423. this.suffix = suffix;
  28424. }
  28425. this.defaultOptions = defaultOptions;
  28426. const pluginBaseUrls = defaultOptions.plugin_base_urls;
  28427. if (pluginBaseUrls !== undefined) {
  28428. each$e(pluginBaseUrls, (pluginBaseUrl, pluginName) => {
  28429. AddOnManager.PluginManager.urls[pluginName] = pluginBaseUrl;
  28430. });
  28431. }
  28432. },
  28433. init(options) {
  28434. const self = this;
  28435. let result;
  28436. 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', ' ');
  28437. const isInvalidInlineTarget = (options, elm) => options.inline && elm.tagName.toLowerCase() in invalidInlineTargets;
  28438. const createId = elm => {
  28439. let id = elm.id;
  28440. if (!id) {
  28441. id = get$a(elm, 'name').filter(name => !DOM.get(name)).getOrThunk(DOM.uniqueId);
  28442. elm.setAttribute('id', id);
  28443. }
  28444. return id;
  28445. };
  28446. const execCallback = name => {
  28447. const callback = options[name];
  28448. if (!callback) {
  28449. return;
  28450. }
  28451. return callback.apply(self, []);
  28452. };
  28453. const findTargets = options => {
  28454. if (Env.browser.isIE() || Env.browser.isEdge()) {
  28455. 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');
  28456. return [];
  28457. } else if (isQuirksMode) {
  28458. initError('Failed to initialize the editor as the document is not in standards mode. ' + 'TinyMCE requires standards mode.');
  28459. return [];
  28460. } else if (isString(options.selector)) {
  28461. return DOM.select(options.selector);
  28462. } else if (isNonNullable(options.target)) {
  28463. return [options.target];
  28464. } else {
  28465. return [];
  28466. }
  28467. };
  28468. let provideResults = editors => {
  28469. result = editors;
  28470. };
  28471. const initEditors = () => {
  28472. let initCount = 0;
  28473. const editors = [];
  28474. let targets;
  28475. const createEditor = (id, options, targetElm) => {
  28476. const editor = new Editor(id, options, self);
  28477. editors.push(editor);
  28478. editor.on('init', () => {
  28479. if (++initCount === targets.length) {
  28480. provideResults(editors);
  28481. }
  28482. });
  28483. editor.targetElm = editor.targetElm || targetElm;
  28484. editor.render();
  28485. };
  28486. DOM.unbind(window, 'ready', initEditors);
  28487. execCallback('onpageload');
  28488. targets = unique$1(findTargets(options));
  28489. Tools.each(targets, elm => {
  28490. purgeDestroyedEditor(self.get(elm.id));
  28491. });
  28492. targets = Tools.grep(targets, elm => {
  28493. return !self.get(elm.id);
  28494. });
  28495. if (targets.length === 0) {
  28496. provideResults([]);
  28497. } else {
  28498. each(targets, elm => {
  28499. if (isInvalidInlineTarget(options, elm)) {
  28500. initError('Could not initialize inline editor on invalid inline target element', elm);
  28501. } else {
  28502. createEditor(createId(elm), options, elm);
  28503. }
  28504. });
  28505. }
  28506. };
  28507. DOM.bind(window, 'ready', initEditors);
  28508. return new Promise(resolve => {
  28509. if (result) {
  28510. resolve(result);
  28511. } else {
  28512. provideResults = editors => {
  28513. resolve(editors);
  28514. };
  28515. }
  28516. });
  28517. },
  28518. get(id) {
  28519. if (arguments.length === 0) {
  28520. return editors.slice(0);
  28521. } else if (isString(id)) {
  28522. return find$2(editors, editor => {
  28523. return editor.id === id;
  28524. }).getOr(null);
  28525. } else if (isNumber(id)) {
  28526. return editors[id] ? editors[id] : null;
  28527. } else {
  28528. return null;
  28529. }
  28530. },
  28531. add(editor) {
  28532. const self = this;
  28533. const existingEditor = self.get(editor.id);
  28534. if (existingEditor === editor) {
  28535. return editor;
  28536. }
  28537. if (existingEditor === null) {
  28538. editors.push(editor);
  28539. }
  28540. toggleGlobalEvents(true);
  28541. self.activeEditor = editor;
  28542. self.dispatch('AddEditor', { editor });
  28543. if (!beforeUnloadDelegate) {
  28544. beforeUnloadDelegate = e => {
  28545. const event = self.dispatch('BeforeUnload');
  28546. if (event.returnValue) {
  28547. e.preventDefault();
  28548. e.returnValue = event.returnValue;
  28549. return event.returnValue;
  28550. }
  28551. };
  28552. window.addEventListener('beforeunload', beforeUnloadDelegate);
  28553. }
  28554. return editor;
  28555. },
  28556. createEditor(id, options) {
  28557. return this.add(new Editor(id, options, this));
  28558. },
  28559. remove(selector) {
  28560. const self = this;
  28561. let i, editor;
  28562. if (!selector) {
  28563. for (i = editors.length - 1; i >= 0; i--) {
  28564. self.remove(editors[i]);
  28565. }
  28566. return;
  28567. }
  28568. if (isString(selector)) {
  28569. each(DOM.select(selector), elm => {
  28570. editor = self.get(elm.id);
  28571. if (editor) {
  28572. self.remove(editor);
  28573. }
  28574. });
  28575. return;
  28576. }
  28577. editor = selector;
  28578. if (isNull(self.get(editor.id))) {
  28579. return null;
  28580. }
  28581. if (removeEditorFromList(editor)) {
  28582. self.dispatch('RemoveEditor', { editor });
  28583. }
  28584. if (editors.length === 0) {
  28585. window.removeEventListener('beforeunload', beforeUnloadDelegate);
  28586. }
  28587. editor.remove();
  28588. toggleGlobalEvents(editors.length > 0);
  28589. return editor;
  28590. },
  28591. execCommand(cmd, ui, value) {
  28592. var _a;
  28593. const self = this;
  28594. const editorId = isObject(value) ? (_a = value.id) !== null && _a !== void 0 ? _a : value.index : value;
  28595. switch (cmd) {
  28596. case 'mceAddEditor': {
  28597. if (!self.get(editorId)) {
  28598. const editorOptions = value.options;
  28599. new Editor(editorId, editorOptions, self).render();
  28600. }
  28601. return true;
  28602. }
  28603. case 'mceRemoveEditor': {
  28604. const editor = self.get(editorId);
  28605. if (editor) {
  28606. editor.remove();
  28607. }
  28608. return true;
  28609. }
  28610. case 'mceToggleEditor': {
  28611. const editor = self.get(editorId);
  28612. if (!editor) {
  28613. self.execCommand('mceAddEditor', false, value);
  28614. return true;
  28615. }
  28616. if (editor.isHidden()) {
  28617. editor.show();
  28618. } else {
  28619. editor.hide();
  28620. }
  28621. return true;
  28622. }
  28623. }
  28624. if (self.activeEditor) {
  28625. return self.activeEditor.execCommand(cmd, ui, value);
  28626. }
  28627. return false;
  28628. },
  28629. triggerSave: () => {
  28630. each(editors, editor => {
  28631. editor.save();
  28632. });
  28633. },
  28634. addI18n: (code, items) => {
  28635. I18n.add(code, items);
  28636. },
  28637. translate: text => {
  28638. return I18n.translate(text);
  28639. },
  28640. setActive(editor) {
  28641. const activeEditor = this.activeEditor;
  28642. if (this.activeEditor !== editor) {
  28643. if (activeEditor) {
  28644. activeEditor.dispatch('deactivate', { relatedTarget: editor });
  28645. }
  28646. editor.dispatch('activate', { relatedTarget: activeEditor });
  28647. }
  28648. this.activeEditor = editor;
  28649. },
  28650. _setBaseUrl(baseUrl) {
  28651. this.baseURL = new URI(this.documentBaseURL).toAbsolute(baseUrl.replace(/\/+$/, ''));
  28652. this.baseURI = new URI(this.baseURL);
  28653. }
  28654. };
  28655. EditorManager.setup();
  28656. const setup = () => {
  28657. const dataValue = value$2();
  28658. const FakeClipboardItem = items => ({
  28659. items,
  28660. types: keys(items),
  28661. getType: type => get$a(items, type).getOrUndefined()
  28662. });
  28663. const write = data => {
  28664. dataValue.set(data);
  28665. };
  28666. const read = () => dataValue.get().getOrUndefined();
  28667. const clear = dataValue.clear;
  28668. return {
  28669. FakeClipboardItem,
  28670. write,
  28671. read,
  28672. clear
  28673. };
  28674. };
  28675. const FakeClipboard = setup();
  28676. const min = Math.min, max = Math.max, round = Math.round;
  28677. const relativePosition = (rect, targetRect, rel) => {
  28678. let x = targetRect.x;
  28679. let y = targetRect.y;
  28680. const w = rect.w;
  28681. const h = rect.h;
  28682. const targetW = targetRect.w;
  28683. const targetH = targetRect.h;
  28684. const relChars = (rel || '').split('');
  28685. if (relChars[0] === 'b') {
  28686. y += targetH;
  28687. }
  28688. if (relChars[1] === 'r') {
  28689. x += targetW;
  28690. }
  28691. if (relChars[0] === 'c') {
  28692. y += round(targetH / 2);
  28693. }
  28694. if (relChars[1] === 'c') {
  28695. x += round(targetW / 2);
  28696. }
  28697. if (relChars[3] === 'b') {
  28698. y -= h;
  28699. }
  28700. if (relChars[4] === 'r') {
  28701. x -= w;
  28702. }
  28703. if (relChars[3] === 'c') {
  28704. y -= round(h / 2);
  28705. }
  28706. if (relChars[4] === 'c') {
  28707. x -= round(w / 2);
  28708. }
  28709. return create$2(x, y, w, h);
  28710. };
  28711. const findBestRelativePosition = (rect, targetRect, constrainRect, rels) => {
  28712. let pos, i;
  28713. for (i = 0; i < rels.length; i++) {
  28714. pos = relativePosition(rect, targetRect, rels[i]);
  28715. 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) {
  28716. return rels[i];
  28717. }
  28718. }
  28719. return null;
  28720. };
  28721. const inflate = (rect, w, h) => {
  28722. return create$2(rect.x - w, rect.y - h, rect.w + w * 2, rect.h + h * 2);
  28723. };
  28724. const intersect = (rect, cropRect) => {
  28725. const x1 = max(rect.x, cropRect.x);
  28726. const y1 = max(rect.y, cropRect.y);
  28727. const x2 = min(rect.x + rect.w, cropRect.x + cropRect.w);
  28728. const y2 = min(rect.y + rect.h, cropRect.y + cropRect.h);
  28729. if (x2 - x1 < 0 || y2 - y1 < 0) {
  28730. return null;
  28731. }
  28732. return create$2(x1, y1, x2 - x1, y2 - y1);
  28733. };
  28734. const clamp = (rect, clampRect, fixedSize) => {
  28735. let x1 = rect.x;
  28736. let y1 = rect.y;
  28737. let x2 = rect.x + rect.w;
  28738. let y2 = rect.y + rect.h;
  28739. const cx2 = clampRect.x + clampRect.w;
  28740. const cy2 = clampRect.y + clampRect.h;
  28741. const underflowX1 = max(0, clampRect.x - x1);
  28742. const underflowY1 = max(0, clampRect.y - y1);
  28743. const overflowX2 = max(0, x2 - cx2);
  28744. const overflowY2 = max(0, y2 - cy2);
  28745. x1 += underflowX1;
  28746. y1 += underflowY1;
  28747. if (fixedSize) {
  28748. x2 += underflowX1;
  28749. y2 += underflowY1;
  28750. x1 -= overflowX2;
  28751. y1 -= overflowY2;
  28752. }
  28753. x2 -= overflowX2;
  28754. y2 -= overflowY2;
  28755. return create$2(x1, y1, x2 - x1, y2 - y1);
  28756. };
  28757. const create$2 = (x, y, w, h) => {
  28758. return {
  28759. x,
  28760. y,
  28761. w,
  28762. h
  28763. };
  28764. };
  28765. const fromClientRect = clientRect => {
  28766. return create$2(clientRect.left, clientRect.top, clientRect.width, clientRect.height);
  28767. };
  28768. const Rect = {
  28769. inflate,
  28770. relativePosition,
  28771. findBestRelativePosition,
  28772. intersect,
  28773. clamp,
  28774. create: create$2,
  28775. fromClientRect
  28776. };
  28777. const awaiter = (resolveCb, rejectCb, timeout = 1000) => {
  28778. let done = false;
  28779. let timer = null;
  28780. const complete = completer => (...args) => {
  28781. if (!done) {
  28782. done = true;
  28783. if (timer !== null) {
  28784. clearTimeout(timer);
  28785. timer = null;
  28786. }
  28787. completer.apply(null, args);
  28788. }
  28789. };
  28790. const resolve = complete(resolveCb);
  28791. const reject = complete(rejectCb);
  28792. const start = (...args) => {
  28793. if (!done && timer === null) {
  28794. timer = setTimeout(() => reject.apply(null, args), timeout);
  28795. }
  28796. };
  28797. return {
  28798. start,
  28799. resolve,
  28800. reject
  28801. };
  28802. };
  28803. const create$1 = () => {
  28804. const tasks = {};
  28805. const resultFns = {};
  28806. const load = (id, url) => {
  28807. const loadErrMsg = `Script at URL "${ url }" failed to load`;
  28808. const runErrMsg = `Script at URL "${ url }" did not call \`tinymce.Resource.add('${ id }', data)\` within 1 second`;
  28809. if (tasks[id] !== undefined) {
  28810. return tasks[id];
  28811. } else {
  28812. const task = new Promise((resolve, reject) => {
  28813. const waiter = awaiter(resolve, reject);
  28814. resultFns[id] = waiter.resolve;
  28815. ScriptLoader.ScriptLoader.loadScript(url).then(() => waiter.start(runErrMsg), () => waiter.reject(loadErrMsg));
  28816. });
  28817. tasks[id] = task;
  28818. return task;
  28819. }
  28820. };
  28821. const add = (id, data) => {
  28822. if (resultFns[id] !== undefined) {
  28823. resultFns[id](data);
  28824. delete resultFns[id];
  28825. }
  28826. tasks[id] = Promise.resolve(data);
  28827. };
  28828. const unload = id => {
  28829. delete tasks[id];
  28830. };
  28831. return {
  28832. load,
  28833. add,
  28834. unload
  28835. };
  28836. };
  28837. const Resource = create$1();
  28838. const create = () => (() => {
  28839. let data = {};
  28840. let keys = [];
  28841. const storage = {
  28842. getItem: key => {
  28843. const item = data[key];
  28844. return item ? item : null;
  28845. },
  28846. setItem: (key, value) => {
  28847. keys.push(key);
  28848. data[key] = String(value);
  28849. },
  28850. key: index => {
  28851. return keys[index];
  28852. },
  28853. removeItem: key => {
  28854. keys = keys.filter(k => k === key);
  28855. delete data[key];
  28856. },
  28857. clear: () => {
  28858. keys = [];
  28859. data = {};
  28860. },
  28861. length: 0
  28862. };
  28863. Object.defineProperty(storage, 'length', {
  28864. get: () => keys.length,
  28865. configurable: false,
  28866. enumerable: false
  28867. });
  28868. return storage;
  28869. })();
  28870. let localStorage;
  28871. try {
  28872. const test = '__storage_test__';
  28873. localStorage = window.localStorage;
  28874. localStorage.setItem(test, test);
  28875. localStorage.removeItem(test);
  28876. } catch (e) {
  28877. localStorage = create();
  28878. }
  28879. var LocalStorage = localStorage;
  28880. const publicApi = {
  28881. geom: { Rect },
  28882. util: {
  28883. Delay,
  28884. Tools,
  28885. VK,
  28886. URI,
  28887. EventDispatcher,
  28888. Observable,
  28889. I18n,
  28890. LocalStorage,
  28891. ImageUploader
  28892. },
  28893. dom: {
  28894. EventUtils,
  28895. TreeWalker: DomTreeWalker,
  28896. TextSeeker,
  28897. DOMUtils,
  28898. ScriptLoader,
  28899. RangeUtils,
  28900. Serializer: DomSerializer,
  28901. StyleSheetLoader,
  28902. ControlSelection,
  28903. BookmarkManager,
  28904. Selection: EditorSelection,
  28905. Event: EventUtils.Event
  28906. },
  28907. html: {
  28908. Styles,
  28909. Entities,
  28910. Node: AstNode,
  28911. Schema,
  28912. DomParser,
  28913. Writer,
  28914. Serializer: HtmlSerializer
  28915. },
  28916. Env,
  28917. AddOnManager,
  28918. Annotator,
  28919. Formatter,
  28920. UndoManager,
  28921. EditorCommands,
  28922. WindowManager,
  28923. NotificationManager,
  28924. EditorObservable,
  28925. Shortcuts,
  28926. Editor,
  28927. FocusManager,
  28928. EditorManager,
  28929. DOM: DOMUtils.DOM,
  28930. ScriptLoader: ScriptLoader.ScriptLoader,
  28931. PluginManager,
  28932. ThemeManager,
  28933. ModelManager,
  28934. IconManager,
  28935. Resource,
  28936. FakeClipboard,
  28937. trim: Tools.trim,
  28938. isArray: Tools.isArray,
  28939. is: Tools.is,
  28940. toArray: Tools.toArray,
  28941. makeMap: Tools.makeMap,
  28942. each: Tools.each,
  28943. map: Tools.map,
  28944. grep: Tools.grep,
  28945. inArray: Tools.inArray,
  28946. extend: Tools.extend,
  28947. walk: Tools.walk,
  28948. resolve: Tools.resolve,
  28949. explode: Tools.explode,
  28950. _addCacheSuffix: Tools._addCacheSuffix
  28951. };
  28952. const tinymce = Tools.extend(EditorManager, publicApi);
  28953. const exportToModuleLoaders = tinymce => {
  28954. if (typeof module === 'object') {
  28955. try {
  28956. module.exports = tinymce;
  28957. } catch (_) {
  28958. }
  28959. }
  28960. };
  28961. const exportToWindowGlobal = tinymce => {
  28962. window.tinymce = tinymce;
  28963. window.tinyMCE = tinymce;
  28964. };
  28965. exportToWindowGlobal(tinymce);
  28966. exportToModuleLoaders(tinymce);
  28967. })();