tinymce.js 1.1 MB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580155811558215583155841558515586155871558815589155901559115592155931559415595155961559715598155991560015601156021560315604156051560615607156081560915610156111561215613156141561515616156171561815619156201562115622156231562415625156261562715628156291563015631156321563315634156351563615637156381563915640156411564215643156441564515646156471564815649156501565115652156531565415655156561565715658156591566015661156621566315664156651566615667156681566915670156711567215673156741567515676156771567815679156801568115682156831568415685156861568715688156891569015691156921569315694156951569615697156981569915700157011570215703157041570515706157071570815709157101571115712157131571415715157161571715718157191572015721157221572315724157251572615727157281572915730157311573215733157341573515736157371573815739157401574115742157431574415745157461574715748157491575015751157521575315754157551575615757157581575915760157611576215763157641576515766157671576815769157701577115772157731577415775157761577715778157791578015781157821578315784157851578615787157881578915790157911579215793157941579515796157971579815799158001580115802158031580415805158061580715808158091581015811158121581315814158151581615817158181581915820158211582215823158241582515826158271582815829158301583115832158331583415835158361583715838158391584015841158421584315844158451584615847158481584915850158511585215853158541585515856158571585815859158601586115862158631586415865158661586715868158691587015871158721587315874158751587615877158781587915880158811588215883158841588515886158871588815889158901589115892158931589415895158961589715898158991590015901159021590315904159051590615907159081590915910159111591215913159141591515916159171591815919159201592115922159231592415925159261592715928159291593015931159321593315934159351593615937159381593915940159411594215943159441594515946159471594815949159501595115952159531595415955159561595715958159591596015961159621596315964159651596615967159681596915970159711597215973159741597515976159771597815979159801598115982159831598415985159861598715988159891599015991159921599315994159951599615997159981599916000160011600216003160041600516006160071600816009160101601116012160131601416015160161601716018160191602016021160221602316024160251602616027160281602916030160311603216033160341603516036160371603816039160401604116042160431604416045160461604716048160491605016051160521605316054160551605616057160581605916060160611606216063160641606516066160671606816069160701607116072160731607416075160761607716078160791608016081160821608316084160851608616087160881608916090160911609216093160941609516096160971609816099161001610116102161031610416105161061610716108161091611016111161121611316114161151611616117161181611916120161211612216123161241612516126161271612816129161301613116132161331613416135161361613716138161391614016141161421614316144161451614616147161481614916150161511615216153161541615516156161571615816159161601616116162161631616416165161661616716168161691617016171161721617316174161751617616177161781617916180161811618216183161841618516186161871618816189161901619116192161931619416195161961619716198161991620016201162021620316204162051620616207162081620916210162111621216213162141621516216162171621816219162201622116222162231622416225162261622716228162291623016231162321623316234162351623616237162381623916240162411624216243162441624516246162471624816249162501625116252162531625416255162561625716258162591626016261162621626316264162651626616267162681626916270162711627216273162741627516276162771627816279162801628116282162831628416285162861628716288162891629016291162921629316294162951629616297162981629916300163011630216303163041630516306163071630816309163101631116312163131631416315163161631716318163191632016321163221632316324163251632616327163281632916330163311633216333163341633516336163371633816339163401634116342163431634416345163461634716348163491635016351163521635316354163551635616357163581635916360163611636216363163641636516366163671636816369163701637116372163731637416375163761637716378163791638016381163821638316384163851638616387163881638916390163911639216393163941639516396163971639816399164001640116402164031640416405164061640716408164091641016411164121641316414164151641616417164181641916420164211642216423164241642516426164271642816429164301643116432164331643416435164361643716438164391644016441164421644316444164451644616447164481644916450164511645216453164541645516456164571645816459164601646116462164631646416465164661646716468164691647016471164721647316474164751647616477164781647916480164811648216483164841648516486164871648816489164901649116492164931649416495164961649716498164991650016501165021650316504165051650616507165081650916510165111651216513165141651516516165171651816519165201652116522165231652416525165261652716528165291653016531165321653316534165351653616537165381653916540165411654216543165441654516546165471654816549165501655116552165531655416555165561655716558165591656016561165621656316564165651656616567165681656916570165711657216573165741657516576165771657816579165801658116582165831658416585165861658716588165891659016591165921659316594165951659616597165981659916600166011660216603166041660516606166071660816609166101661116612166131661416615166161661716618166191662016621166221662316624166251662616627166281662916630166311663216633166341663516636166371663816639166401664116642166431664416645166461664716648166491665016651166521665316654166551665616657166581665916660166611666216663166641666516666166671666816669166701667116672166731667416675166761667716678166791668016681166821668316684166851668616687166881668916690166911669216693166941669516696166971669816699167001670116702167031670416705167061670716708167091671016711167121671316714167151671616717167181671916720167211672216723167241672516726167271672816729167301673116732167331673416735167361673716738167391674016741167421674316744167451674616747167481674916750167511675216753167541675516756167571675816759167601676116762167631676416765167661676716768167691677016771167721677316774167751677616777167781677916780167811678216783167841678516786167871678816789167901679116792167931679416795167961679716798167991680016801168021680316804168051680616807168081680916810168111681216813168141681516816168171681816819168201682116822168231682416825168261682716828168291683016831168321683316834168351683616837168381683916840168411684216843168441684516846168471684816849168501685116852168531685416855168561685716858168591686016861168621686316864168651686616867168681686916870168711687216873168741687516876168771687816879168801688116882168831688416885168861688716888168891689016891168921689316894168951689616897168981689916900169011690216903169041690516906169071690816909169101691116912169131691416915169161691716918169191692016921169221692316924169251692616927169281692916930169311693216933169341693516936169371693816939169401694116942169431694416945169461694716948169491695016951169521695316954169551695616957169581695916960169611696216963169641696516966169671696816969169701697116972169731697416975169761697716978169791698016981169821698316984169851698616987169881698916990169911699216993169941699516996169971699816999170001700117002170031700417005170061700717008170091701017011170121701317014170151701617017170181701917020170211702217023170241702517026170271702817029170301703117032170331703417035170361703717038170391704017041170421704317044170451704617047170481704917050170511705217053170541705517056170571705817059170601706117062170631706417065170661706717068170691707017071170721707317074170751707617077170781707917080170811708217083170841708517086170871708817089170901709117092170931709417095170961709717098170991710017101171021710317104171051710617107171081710917110171111711217113171141711517116171171711817119171201712117122171231712417125171261712717128171291713017131171321713317134171351713617137171381713917140171411714217143171441714517146171471714817149171501715117152171531715417155171561715717158171591716017161171621716317164171651716617167171681716917170171711717217173171741717517176171771717817179171801718117182171831718417185171861718717188171891719017191171921719317194171951719617197171981719917200172011720217203172041720517206172071720817209172101721117212172131721417215172161721717218172191722017221172221722317224172251722617227172281722917230172311723217233172341723517236172371723817239172401724117242172431724417245172461724717248172491725017251172521725317254172551725617257172581725917260172611726217263172641726517266172671726817269172701727117272172731727417275172761727717278172791728017281172821728317284172851728617287172881728917290172911729217293172941729517296172971729817299173001730117302173031730417305173061730717308173091731017311173121731317314173151731617317173181731917320173211732217323173241732517326173271732817329173301733117332173331733417335173361733717338173391734017341173421734317344173451734617347173481734917350173511735217353173541735517356173571735817359173601736117362173631736417365173661736717368173691737017371173721737317374173751737617377173781737917380173811738217383173841738517386173871738817389173901739117392173931739417395173961739717398173991740017401174021740317404174051740617407174081740917410174111741217413174141741517416174171741817419174201742117422174231742417425174261742717428174291743017431174321743317434174351743617437174381743917440174411744217443174441744517446174471744817449174501745117452174531745417455174561745717458174591746017461174621746317464174651746617467174681746917470174711747217473174741747517476174771747817479174801748117482174831748417485174861748717488174891749017491174921749317494174951749617497174981749917500175011750217503175041750517506175071750817509175101751117512175131751417515175161751717518175191752017521175221752317524175251752617527175281752917530175311753217533175341753517536175371753817539175401754117542175431754417545175461754717548175491755017551175521755317554175551755617557175581755917560175611756217563175641756517566175671756817569175701757117572175731757417575175761757717578175791758017581175821758317584175851758617587175881758917590175911759217593175941759517596175971759817599176001760117602176031760417605176061760717608176091761017611176121761317614176151761617617176181761917620176211762217623176241762517626176271762817629176301763117632176331763417635176361763717638176391764017641176421764317644176451764617647176481764917650176511765217653176541765517656176571765817659176601766117662176631766417665176661766717668176691767017671176721767317674176751767617677176781767917680176811768217683176841768517686176871768817689176901769117692176931769417695176961769717698176991770017701177021770317704177051770617707177081770917710177111771217713177141771517716177171771817719177201772117722177231772417725177261772717728177291773017731177321773317734177351773617737177381773917740177411774217743177441774517746177471774817749177501775117752177531775417755177561775717758177591776017761177621776317764177651776617767177681776917770177711777217773177741777517776177771777817779177801778117782177831778417785177861778717788177891779017791177921779317794177951779617797177981779917800178011780217803178041780517806178071780817809178101781117812178131781417815178161781717818178191782017821178221782317824178251782617827178281782917830178311783217833178341783517836178371783817839178401784117842178431784417845178461784717848178491785017851178521785317854178551785617857178581785917860178611786217863178641786517866178671786817869178701787117872178731787417875178761787717878178791788017881178821788317884178851788617887178881788917890178911789217893178941789517896178971789817899179001790117902179031790417905179061790717908179091791017911179121791317914179151791617917179181791917920179211792217923179241792517926179271792817929179301793117932179331793417935179361793717938179391794017941179421794317944179451794617947179481794917950179511795217953179541795517956179571795817959179601796117962179631796417965179661796717968179691797017971179721797317974179751797617977179781797917980179811798217983179841798517986179871798817989179901799117992179931799417995179961799717998179991800018001180021800318004180051800618007180081800918010180111801218013180141801518016180171801818019180201802118022180231802418025180261802718028180291803018031180321803318034180351803618037180381803918040180411804218043180441804518046180471804818049180501805118052180531805418055180561805718058180591806018061180621806318064180651806618067180681806918070180711807218073180741807518076180771807818079180801808118082180831808418085180861808718088180891809018091180921809318094180951809618097180981809918100181011810218103181041810518106181071810818109181101811118112181131811418115181161811718118181191812018121181221812318124181251812618127181281812918130181311813218133181341813518136181371813818139181401814118142181431814418145181461814718148181491815018151181521815318154181551815618157181581815918160181611816218163181641816518166181671816818169181701817118172181731817418175181761817718178181791818018181181821818318184181851818618187181881818918190181911819218193181941819518196181971819818199182001820118202182031820418205182061820718208182091821018211182121821318214182151821618217182181821918220182211822218223182241822518226182271822818229182301823118232182331823418235182361823718238182391824018241182421824318244182451824618247182481824918250182511825218253182541825518256182571825818259182601826118262182631826418265182661826718268182691827018271182721827318274182751827618277182781827918280182811828218283182841828518286182871828818289182901829118292182931829418295182961829718298182991830018301183021830318304183051830618307183081830918310183111831218313183141831518316183171831818319183201832118322183231832418325183261832718328183291833018331183321833318334183351833618337183381833918340183411834218343183441834518346183471834818349183501835118352183531835418355183561835718358183591836018361183621836318364183651836618367183681836918370183711837218373183741837518376183771837818379183801838118382183831838418385183861838718388183891839018391183921839318394183951839618397183981839918400184011840218403184041840518406184071840818409184101841118412184131841418415184161841718418184191842018421184221842318424184251842618427184281842918430184311843218433184341843518436184371843818439184401844118442184431844418445184461844718448184491845018451184521845318454184551845618457184581845918460184611846218463184641846518466184671846818469184701847118472184731847418475184761847718478184791848018481184821848318484184851848618487184881848918490184911849218493184941849518496184971849818499185001850118502185031850418505185061850718508185091851018511185121851318514185151851618517185181851918520185211852218523185241852518526185271852818529185301853118532185331853418535185361853718538185391854018541185421854318544185451854618547185481854918550185511855218553185541855518556185571855818559185601856118562185631856418565185661856718568185691857018571185721857318574185751857618577185781857918580185811858218583185841858518586185871858818589185901859118592185931859418595185961859718598185991860018601186021860318604186051860618607186081860918610186111861218613186141861518616186171861818619186201862118622186231862418625186261862718628186291863018631186321863318634186351863618637186381863918640186411864218643186441864518646186471864818649186501865118652186531865418655186561865718658186591866018661186621866318664186651866618667186681866918670186711867218673186741867518676186771867818679186801868118682186831868418685186861868718688186891869018691186921869318694186951869618697186981869918700187011870218703187041870518706187071870818709187101871118712187131871418715187161871718718187191872018721187221872318724187251872618727187281872918730187311873218733187341873518736187371873818739187401874118742187431874418745187461874718748187491875018751187521875318754187551875618757187581875918760187611876218763187641876518766187671876818769187701877118772187731877418775187761877718778187791878018781187821878318784187851878618787187881878918790187911879218793187941879518796187971879818799188001880118802188031880418805188061880718808188091881018811188121881318814188151881618817188181881918820188211882218823188241882518826188271882818829188301883118832188331883418835188361883718838188391884018841188421884318844188451884618847188481884918850188511885218853188541885518856188571885818859188601886118862188631886418865188661886718868188691887018871188721887318874188751887618877188781887918880188811888218883188841888518886188871888818889188901889118892188931889418895188961889718898188991890018901189021890318904189051890618907189081890918910189111891218913189141891518916189171891818919189201892118922189231892418925189261892718928189291893018931189321893318934189351893618937189381893918940189411894218943189441894518946189471894818949189501895118952189531895418955189561895718958189591896018961189621896318964189651896618967189681896918970189711897218973189741897518976189771897818979189801898118982189831898418985189861898718988189891899018991189921899318994189951899618997189981899919000190011900219003190041900519006190071900819009190101901119012190131901419015190161901719018190191902019021190221902319024190251902619027190281902919030190311903219033190341903519036190371903819039190401904119042190431904419045190461904719048190491905019051190521905319054190551905619057190581905919060190611906219063190641906519066190671906819069190701907119072190731907419075190761907719078190791908019081190821908319084190851908619087190881908919090190911909219093190941909519096190971909819099191001910119102191031910419105191061910719108191091911019111191121911319114191151911619117191181911919120191211912219123191241912519126191271912819129191301913119132191331913419135191361913719138191391914019141191421914319144191451914619147191481914919150191511915219153191541915519156191571915819159191601916119162191631916419165191661916719168191691917019171191721917319174191751917619177191781917919180191811918219183191841918519186191871918819189191901919119192191931919419195191961919719198191991920019201192021920319204192051920619207192081920919210192111921219213192141921519216192171921819219192201922119222192231922419225192261922719228192291923019231192321923319234192351923619237192381923919240192411924219243192441924519246192471924819249192501925119252192531925419255192561925719258192591926019261192621926319264192651926619267192681926919270192711927219273192741927519276192771927819279192801928119282192831928419285192861928719288192891929019291192921929319294192951929619297192981929919300193011930219303193041930519306193071930819309193101931119312193131931419315193161931719318193191932019321193221932319324193251932619327193281932919330193311933219333193341933519336193371933819339193401934119342193431934419345193461934719348193491935019351193521935319354193551935619357193581935919360193611936219363193641936519366193671936819369193701937119372193731937419375193761937719378193791938019381193821938319384193851938619387193881938919390193911939219393193941939519396193971939819399194001940119402194031940419405194061940719408194091941019411194121941319414194151941619417194181941919420194211942219423194241942519426194271942819429194301943119432194331943419435194361943719438194391944019441194421944319444194451944619447194481944919450194511945219453194541945519456194571945819459194601946119462194631946419465194661946719468194691947019471194721947319474194751947619477194781947919480194811948219483194841948519486194871948819489194901949119492194931949419495194961949719498194991950019501195021950319504195051950619507195081950919510195111951219513195141951519516195171951819519195201952119522195231952419525195261952719528195291953019531195321953319534195351953619537195381953919540195411954219543195441954519546195471954819549195501955119552195531955419555195561955719558195591956019561195621956319564195651956619567195681956919570195711957219573195741957519576195771957819579195801958119582195831958419585195861958719588195891959019591195921959319594195951959619597195981959919600196011960219603196041960519606196071960819609196101961119612196131961419615196161961719618196191962019621196221962319624196251962619627196281962919630196311963219633196341963519636196371963819639196401964119642196431964419645196461964719648196491965019651196521965319654196551965619657196581965919660196611966219663196641966519666196671966819669196701967119672196731967419675196761967719678196791968019681196821968319684196851968619687196881968919690196911969219693196941969519696196971969819699197001970119702197031970419705197061970719708197091971019711197121971319714197151971619717197181971919720197211972219723197241972519726197271972819729197301973119732197331973419735197361973719738197391974019741197421974319744197451974619747197481974919750197511975219753197541975519756197571975819759197601976119762197631976419765197661976719768197691977019771197721977319774197751977619777197781977919780197811978219783197841978519786197871978819789197901979119792197931979419795197961979719798197991980019801198021980319804198051980619807198081980919810198111981219813198141981519816198171981819819198201982119822198231982419825198261982719828198291983019831198321983319834198351983619837198381983919840198411984219843198441984519846198471984819849198501985119852198531985419855198561985719858198591986019861198621986319864198651986619867198681986919870198711987219873198741987519876198771987819879198801988119882198831988419885198861988719888198891989019891198921989319894198951989619897198981989919900199011990219903199041990519906199071990819909199101991119912199131991419915199161991719918199191992019921199221992319924199251992619927199281992919930199311993219933199341993519936199371993819939199401994119942199431994419945199461994719948199491995019951199521995319954199551995619957199581995919960199611996219963199641996519966199671996819969199701997119972199731997419975199761997719978199791998019981199821998319984199851998619987199881998919990199911999219993199941999519996199971999819999200002000120002200032000420005200062000720008200092001020011200122001320014200152001620017200182001920020200212002220023200242002520026200272002820029200302003120032200332003420035200362003720038200392004020041200422004320044200452004620047200482004920050200512005220053200542005520056200572005820059200602006120062200632006420065200662006720068200692007020071200722007320074200752007620077200782007920080200812008220083200842008520086200872008820089200902009120092200932009420095200962009720098200992010020101201022010320104201052010620107201082010920110201112011220113201142011520116201172011820119201202012120122201232012420125201262012720128201292013020131201322013320134201352013620137201382013920140201412014220143201442014520146201472014820149201502015120152201532015420155201562015720158201592016020161201622016320164201652016620167201682016920170201712017220173201742017520176201772017820179201802018120182201832018420185201862018720188201892019020191201922019320194201952019620197201982019920200202012020220203202042020520206202072020820209202102021120212202132021420215202162021720218202192022020221202222022320224202252022620227202282022920230202312023220233202342023520236202372023820239202402024120242202432024420245202462024720248202492025020251202522025320254202552025620257202582025920260202612026220263202642026520266202672026820269202702027120272202732027420275202762027720278202792028020281202822028320284202852028620287202882028920290202912029220293202942029520296202972029820299203002030120302203032030420305203062030720308203092031020311203122031320314203152031620317203182031920320203212032220323203242032520326203272032820329203302033120332203332033420335203362033720338203392034020341203422034320344203452034620347203482034920350203512035220353203542035520356203572035820359203602036120362203632036420365203662036720368203692037020371203722037320374203752037620377203782037920380203812038220383203842038520386203872038820389203902039120392203932039420395203962039720398203992040020401204022040320404204052040620407204082040920410204112041220413204142041520416204172041820419204202042120422204232042420425204262042720428204292043020431204322043320434204352043620437204382043920440204412044220443204442044520446204472044820449204502045120452204532045420455204562045720458204592046020461204622046320464204652046620467204682046920470204712047220473204742047520476204772047820479204802048120482204832048420485204862048720488204892049020491204922049320494204952049620497204982049920500205012050220503205042050520506205072050820509205102051120512205132051420515205162051720518205192052020521205222052320524205252052620527205282052920530205312053220533205342053520536205372053820539205402054120542205432054420545205462054720548205492055020551205522055320554205552055620557205582055920560205612056220563205642056520566205672056820569205702057120572205732057420575205762057720578205792058020581205822058320584205852058620587205882058920590205912059220593205942059520596205972059820599206002060120602206032060420605206062060720608206092061020611206122061320614206152061620617206182061920620206212062220623206242062520626206272062820629206302063120632206332063420635206362063720638206392064020641206422064320644206452064620647206482064920650206512065220653206542065520656206572065820659206602066120662206632066420665206662066720668206692067020671206722067320674206752067620677206782067920680206812068220683206842068520686206872068820689206902069120692206932069420695206962069720698206992070020701207022070320704207052070620707207082070920710207112071220713207142071520716207172071820719207202072120722207232072420725207262072720728207292073020731207322073320734207352073620737207382073920740207412074220743207442074520746207472074820749207502075120752207532075420755207562075720758207592076020761207622076320764207652076620767207682076920770207712077220773207742077520776207772077820779207802078120782207832078420785207862078720788207892079020791207922079320794207952079620797207982079920800208012080220803208042080520806208072080820809208102081120812208132081420815208162081720818208192082020821208222082320824208252082620827208282082920830208312083220833208342083520836208372083820839208402084120842208432084420845208462084720848208492085020851208522085320854208552085620857208582085920860208612086220863208642086520866208672086820869208702087120872208732087420875208762087720878208792088020881208822088320884208852088620887208882088920890208912089220893208942089520896208972089820899209002090120902209032090420905209062090720908209092091020911209122091320914209152091620917209182091920920209212092220923209242092520926209272092820929209302093120932209332093420935209362093720938209392094020941209422094320944209452094620947209482094920950209512095220953209542095520956209572095820959209602096120962209632096420965209662096720968209692097020971209722097320974209752097620977209782097920980209812098220983209842098520986209872098820989209902099120992209932099420995209962099720998209992100021001210022100321004210052100621007210082100921010210112101221013210142101521016210172101821019210202102121022210232102421025210262102721028210292103021031210322103321034210352103621037210382103921040210412104221043210442104521046210472104821049210502105121052210532105421055210562105721058210592106021061210622106321064210652106621067210682106921070210712107221073210742107521076210772107821079210802108121082210832108421085210862108721088210892109021091210922109321094210952109621097210982109921100211012110221103211042110521106211072110821109211102111121112211132111421115211162111721118211192112021121211222112321124211252112621127211282112921130211312113221133211342113521136211372113821139211402114121142211432114421145211462114721148211492115021151211522115321154211552115621157211582115921160211612116221163211642116521166211672116821169211702117121172211732117421175211762117721178211792118021181211822118321184211852118621187211882118921190211912119221193211942119521196211972119821199212002120121202212032120421205212062120721208212092121021211212122121321214212152121621217212182121921220212212122221223212242122521226212272122821229212302123121232212332123421235212362123721238212392124021241212422124321244212452124621247212482124921250212512125221253212542125521256212572125821259212602126121262212632126421265212662126721268212692127021271212722127321274212752127621277212782127921280212812128221283212842128521286212872128821289212902129121292212932129421295212962129721298212992130021301213022130321304213052130621307213082130921310213112131221313213142131521316213172131821319213202132121322213232132421325213262132721328213292133021331213322133321334213352133621337213382133921340213412134221343213442134521346213472134821349213502135121352213532135421355213562135721358213592136021361213622136321364213652136621367213682136921370213712137221373213742137521376213772137821379213802138121382213832138421385213862138721388213892139021391213922139321394213952139621397213982139921400214012140221403214042140521406214072140821409214102141121412214132141421415214162141721418214192142021421214222142321424214252142621427214282142921430214312143221433214342143521436214372143821439214402144121442214432144421445214462144721448214492145021451214522145321454214552145621457214582145921460214612146221463214642146521466214672146821469214702147121472214732147421475214762147721478214792148021481214822148321484214852148621487214882148921490214912149221493214942149521496214972149821499215002150121502215032150421505215062150721508215092151021511215122151321514215152151621517215182151921520215212152221523215242152521526215272152821529215302153121532215332153421535215362153721538215392154021541215422154321544215452154621547215482154921550215512155221553215542155521556215572155821559215602156121562215632156421565215662156721568215692157021571215722157321574215752157621577215782157921580215812158221583215842158521586215872158821589215902159121592215932159421595215962159721598215992160021601216022160321604216052160621607216082160921610216112161221613216142161521616216172161821619216202162121622216232162421625216262162721628216292163021631216322163321634216352163621637216382163921640216412164221643216442164521646216472164821649216502165121652216532165421655216562165721658216592166021661216622166321664216652166621667216682166921670216712167221673216742167521676216772167821679216802168121682216832168421685216862168721688216892169021691216922169321694216952169621697216982169921700217012170221703217042170521706217072170821709217102171121712217132171421715217162171721718217192172021721217222172321724217252172621727217282172921730217312173221733217342173521736217372173821739217402174121742217432174421745217462174721748217492175021751217522175321754217552175621757217582175921760217612176221763217642176521766217672176821769217702177121772217732177421775217762177721778217792178021781217822178321784217852178621787217882178921790217912179221793217942179521796217972179821799218002180121802218032180421805218062180721808218092181021811218122181321814218152181621817218182181921820218212182221823218242182521826218272182821829218302183121832218332183421835218362183721838218392184021841218422184321844218452184621847218482184921850218512185221853218542185521856218572185821859218602186121862218632186421865218662186721868218692187021871218722187321874218752187621877218782187921880218812188221883218842188521886218872188821889218902189121892218932189421895218962189721898218992190021901219022190321904219052190621907219082190921910219112191221913219142191521916219172191821919219202192121922219232192421925219262192721928219292193021931219322193321934219352193621937219382193921940219412194221943219442194521946219472194821949219502195121952219532195421955219562195721958219592196021961219622196321964219652196621967219682196921970219712197221973219742197521976219772197821979219802198121982219832198421985219862198721988219892199021991219922199321994219952199621997219982199922000220012200222003220042200522006220072200822009220102201122012220132201422015220162201722018220192202022021220222202322024220252202622027220282202922030220312203222033220342203522036220372203822039220402204122042220432204422045220462204722048220492205022051220522205322054220552205622057220582205922060220612206222063220642206522066220672206822069220702207122072220732207422075220762207722078220792208022081220822208322084220852208622087220882208922090220912209222093220942209522096220972209822099221002210122102221032210422105221062210722108221092211022111221122211322114221152211622117221182211922120221212212222123221242212522126221272212822129221302213122132221332213422135221362213722138221392214022141221422214322144221452214622147221482214922150221512215222153221542215522156221572215822159221602216122162221632216422165221662216722168221692217022171221722217322174221752217622177221782217922180221812218222183221842218522186221872218822189221902219122192221932219422195221962219722198221992220022201222022220322204222052220622207222082220922210222112221222213222142221522216222172221822219222202222122222222232222422225222262222722228222292223022231222322223322234222352223622237222382223922240222412224222243222442224522246222472224822249222502225122252222532225422255222562225722258222592226022261222622226322264222652226622267222682226922270222712227222273222742227522276222772227822279222802228122282222832228422285222862228722288222892229022291222922229322294222952229622297222982229922300223012230222303223042230522306223072230822309223102231122312223132231422315223162231722318223192232022321223222232322324223252232622327223282232922330223312233222333223342233522336223372233822339223402234122342223432234422345223462234722348223492235022351223522235322354223552235622357223582235922360223612236222363223642236522366223672236822369223702237122372223732237422375223762237722378223792238022381223822238322384223852238622387223882238922390223912239222393223942239522396223972239822399224002240122402224032240422405224062240722408224092241022411224122241322414224152241622417224182241922420224212242222423224242242522426224272242822429224302243122432224332243422435224362243722438224392244022441224422244322444224452244622447224482244922450224512245222453224542245522456224572245822459224602246122462224632246422465224662246722468224692247022471224722247322474224752247622477224782247922480224812248222483224842248522486224872248822489224902249122492224932249422495224962249722498224992250022501225022250322504225052250622507225082250922510225112251222513225142251522516225172251822519225202252122522225232252422525225262252722528225292253022531225322253322534225352253622537225382253922540225412254222543225442254522546225472254822549225502255122552225532255422555225562255722558225592256022561225622256322564225652256622567225682256922570225712257222573225742257522576225772257822579225802258122582225832258422585225862258722588225892259022591225922259322594225952259622597225982259922600226012260222603226042260522606226072260822609226102261122612226132261422615226162261722618226192262022621226222262322624226252262622627226282262922630226312263222633226342263522636226372263822639226402264122642226432264422645226462264722648226492265022651226522265322654226552265622657226582265922660226612266222663226642266522666226672266822669226702267122672226732267422675226762267722678226792268022681226822268322684226852268622687226882268922690226912269222693226942269522696226972269822699227002270122702227032270422705227062270722708227092271022711227122271322714227152271622717227182271922720227212272222723227242272522726227272272822729227302273122732227332273422735227362273722738227392274022741227422274322744227452274622747227482274922750227512275222753227542275522756227572275822759227602276122762227632276422765227662276722768227692277022771227722277322774227752277622777227782277922780227812278222783227842278522786227872278822789227902279122792227932279422795227962279722798227992280022801228022280322804228052280622807228082280922810228112281222813228142281522816228172281822819228202282122822228232282422825228262282722828228292283022831228322283322834228352283622837228382283922840228412284222843228442284522846228472284822849228502285122852228532285422855228562285722858228592286022861228622286322864228652286622867228682286922870228712287222873228742287522876228772287822879228802288122882228832288422885228862288722888228892289022891228922289322894228952289622897228982289922900229012290222903229042290522906229072290822909229102291122912229132291422915229162291722918229192292022921229222292322924229252292622927229282292922930229312293222933229342293522936229372293822939229402294122942229432294422945229462294722948229492295022951229522295322954229552295622957229582295922960229612296222963229642296522966229672296822969229702297122972229732297422975229762297722978229792298022981229822298322984229852298622987229882298922990229912299222993229942299522996229972299822999230002300123002230032300423005230062300723008230092301023011230122301323014230152301623017230182301923020230212302223023230242302523026230272302823029230302303123032230332303423035230362303723038230392304023041230422304323044230452304623047230482304923050230512305223053230542305523056230572305823059230602306123062230632306423065230662306723068230692307023071230722307323074230752307623077230782307923080230812308223083230842308523086230872308823089230902309123092230932309423095230962309723098230992310023101231022310323104231052310623107231082310923110231112311223113231142311523116231172311823119231202312123122231232312423125231262312723128231292313023131231322313323134231352313623137231382313923140231412314223143231442314523146231472314823149231502315123152231532315423155231562315723158231592316023161231622316323164231652316623167231682316923170231712317223173231742317523176231772317823179231802318123182231832318423185231862318723188231892319023191231922319323194231952319623197231982319923200232012320223203232042320523206232072320823209232102321123212232132321423215232162321723218232192322023221232222322323224232252322623227232282322923230232312323223233232342323523236232372323823239232402324123242232432324423245232462324723248232492325023251232522325323254232552325623257232582325923260232612326223263232642326523266232672326823269232702327123272232732327423275232762327723278232792328023281232822328323284232852328623287232882328923290232912329223293232942329523296232972329823299233002330123302233032330423305233062330723308233092331023311233122331323314233152331623317233182331923320233212332223323233242332523326233272332823329233302333123332233332333423335233362333723338233392334023341233422334323344233452334623347233482334923350233512335223353233542335523356233572335823359233602336123362233632336423365233662336723368233692337023371233722337323374233752337623377233782337923380233812338223383233842338523386233872338823389233902339123392233932339423395233962339723398233992340023401234022340323404234052340623407234082340923410234112341223413234142341523416234172341823419234202342123422234232342423425234262342723428234292343023431234322343323434234352343623437234382343923440234412344223443234442344523446234472344823449234502345123452234532345423455234562345723458234592346023461234622346323464234652346623467234682346923470234712347223473234742347523476234772347823479234802348123482234832348423485234862348723488234892349023491234922349323494234952349623497234982349923500235012350223503235042350523506235072350823509235102351123512235132351423515235162351723518235192352023521235222352323524235252352623527235282352923530235312353223533235342353523536235372353823539235402354123542235432354423545235462354723548235492355023551235522355323554235552355623557235582355923560235612356223563235642356523566235672356823569235702357123572235732357423575235762357723578235792358023581235822358323584235852358623587235882358923590235912359223593235942359523596235972359823599236002360123602236032360423605236062360723608236092361023611236122361323614236152361623617236182361923620236212362223623236242362523626236272362823629236302363123632236332363423635236362363723638236392364023641236422364323644236452364623647236482364923650236512365223653236542365523656236572365823659236602366123662236632366423665236662366723668236692367023671236722367323674236752367623677236782367923680236812368223683236842368523686236872368823689236902369123692236932369423695236962369723698236992370023701237022370323704237052370623707237082370923710237112371223713237142371523716237172371823719237202372123722237232372423725237262372723728237292373023731237322373323734237352373623737237382373923740237412374223743237442374523746237472374823749237502375123752237532375423755237562375723758237592376023761237622376323764237652376623767237682376923770237712377223773237742377523776237772377823779237802378123782237832378423785237862378723788237892379023791237922379323794237952379623797237982379923800238012380223803238042380523806238072380823809238102381123812238132381423815238162381723818238192382023821238222382323824238252382623827238282382923830238312383223833238342383523836238372383823839238402384123842238432384423845238462384723848238492385023851238522385323854238552385623857238582385923860238612386223863238642386523866238672386823869238702387123872238732387423875238762387723878238792388023881238822388323884238852388623887238882388923890238912389223893238942389523896238972389823899239002390123902239032390423905239062390723908239092391023911239122391323914239152391623917239182391923920239212392223923239242392523926239272392823929239302393123932239332393423935239362393723938239392394023941239422394323944239452394623947239482394923950239512395223953239542395523956239572395823959239602396123962239632396423965239662396723968239692397023971239722397323974239752397623977239782397923980239812398223983239842398523986239872398823989239902399123992239932399423995239962399723998239992400024001240022400324004240052400624007240082400924010240112401224013240142401524016240172401824019240202402124022240232402424025240262402724028240292403024031240322403324034240352403624037240382403924040240412404224043240442404524046240472404824049240502405124052240532405424055240562405724058240592406024061240622406324064240652406624067240682406924070240712407224073240742407524076240772407824079240802408124082240832408424085240862408724088240892409024091240922409324094240952409624097240982409924100241012410224103241042410524106241072410824109241102411124112241132411424115241162411724118241192412024121241222412324124241252412624127241282412924130241312413224133241342413524136241372413824139241402414124142241432414424145241462414724148241492415024151241522415324154241552415624157241582415924160241612416224163241642416524166241672416824169241702417124172241732417424175241762417724178241792418024181241822418324184241852418624187241882418924190241912419224193241942419524196241972419824199242002420124202242032420424205242062420724208242092421024211242122421324214242152421624217242182421924220242212422224223242242422524226242272422824229242302423124232242332423424235242362423724238242392424024241242422424324244242452424624247242482424924250242512425224253242542425524256242572425824259242602426124262242632426424265242662426724268242692427024271242722427324274242752427624277242782427924280242812428224283242842428524286242872428824289242902429124292242932429424295242962429724298242992430024301243022430324304243052430624307243082430924310243112431224313243142431524316243172431824319243202432124322243232432424325243262432724328243292433024331243322433324334243352433624337243382433924340243412434224343243442434524346243472434824349243502435124352243532435424355243562435724358243592436024361243622436324364243652436624367243682436924370243712437224373243742437524376243772437824379243802438124382243832438424385243862438724388243892439024391243922439324394243952439624397243982439924400244012440224403244042440524406244072440824409244102441124412244132441424415244162441724418244192442024421244222442324424244252442624427244282442924430244312443224433244342443524436244372443824439244402444124442244432444424445244462444724448244492445024451244522445324454244552445624457244582445924460244612446224463244642446524466244672446824469244702447124472244732447424475244762447724478244792448024481244822448324484244852448624487244882448924490244912449224493244942449524496244972449824499245002450124502245032450424505245062450724508245092451024511245122451324514245152451624517245182451924520245212452224523245242452524526245272452824529245302453124532245332453424535245362453724538245392454024541245422454324544245452454624547245482454924550245512455224553245542455524556245572455824559245602456124562245632456424565245662456724568245692457024571245722457324574245752457624577245782457924580245812458224583245842458524586245872458824589245902459124592245932459424595245962459724598245992460024601246022460324604246052460624607246082460924610246112461224613246142461524616246172461824619246202462124622246232462424625246262462724628246292463024631246322463324634246352463624637246382463924640246412464224643246442464524646246472464824649246502465124652246532465424655246562465724658246592466024661246622466324664246652466624667246682466924670246712467224673246742467524676246772467824679246802468124682246832468424685246862468724688246892469024691246922469324694246952469624697246982469924700247012470224703247042470524706247072470824709247102471124712247132471424715247162471724718247192472024721247222472324724247252472624727247282472924730247312473224733247342473524736247372473824739247402474124742247432474424745247462474724748247492475024751247522475324754247552475624757247582475924760247612476224763247642476524766247672476824769247702477124772247732477424775247762477724778247792478024781247822478324784247852478624787247882478924790247912479224793247942479524796247972479824799248002480124802248032480424805248062480724808248092481024811248122481324814248152481624817248182481924820248212482224823248242482524826248272482824829248302483124832248332483424835248362483724838248392484024841248422484324844248452484624847248482484924850248512485224853248542485524856248572485824859248602486124862248632486424865248662486724868248692487024871248722487324874248752487624877248782487924880248812488224883248842488524886248872488824889248902489124892248932489424895248962489724898248992490024901249022490324904249052490624907249082490924910249112491224913249142491524916249172491824919249202492124922249232492424925249262492724928249292493024931249322493324934249352493624937249382493924940249412494224943249442494524946249472494824949249502495124952249532495424955249562495724958249592496024961249622496324964249652496624967249682496924970249712497224973249742497524976249772497824979249802498124982249832498424985249862498724988249892499024991249922499324994249952499624997249982499925000250012500225003250042500525006250072500825009250102501125012250132501425015250162501725018250192502025021250222502325024250252502625027250282502925030250312503225033250342503525036250372503825039250402504125042250432504425045250462504725048250492505025051250522505325054250552505625057250582505925060250612506225063250642506525066250672506825069250702507125072250732507425075250762507725078250792508025081250822508325084250852508625087250882508925090250912509225093250942509525096250972509825099251002510125102251032510425105251062510725108251092511025111251122511325114251152511625117251182511925120251212512225123251242512525126251272512825129251302513125132251332513425135251362513725138251392514025141251422514325144251452514625147251482514925150251512515225153251542515525156251572515825159251602516125162251632516425165251662516725168251692517025171251722517325174251752517625177251782517925180251812518225183251842518525186251872518825189251902519125192251932519425195251962519725198251992520025201252022520325204252052520625207252082520925210252112521225213252142521525216252172521825219252202522125222252232522425225252262522725228252292523025231252322523325234252352523625237252382523925240252412524225243252442524525246252472524825249252502525125252252532525425255252562525725258252592526025261252622526325264252652526625267252682526925270252712527225273252742527525276252772527825279252802528125282252832528425285252862528725288252892529025291252922529325294252952529625297252982529925300253012530225303253042530525306253072530825309253102531125312253132531425315253162531725318253192532025321253222532325324253252532625327253282532925330253312533225333253342533525336253372533825339253402534125342253432534425345253462534725348253492535025351253522535325354253552535625357253582535925360253612536225363253642536525366253672536825369253702537125372253732537425375253762537725378253792538025381253822538325384253852538625387253882538925390253912539225393253942539525396253972539825399254002540125402254032540425405254062540725408254092541025411254122541325414254152541625417254182541925420254212542225423254242542525426254272542825429254302543125432254332543425435254362543725438254392544025441254422544325444254452544625447254482544925450254512545225453254542545525456254572545825459254602546125462254632546425465254662546725468254692547025471254722547325474254752547625477254782547925480254812548225483254842548525486254872548825489254902549125492254932549425495254962549725498254992550025501255022550325504255052550625507255082550925510255112551225513255142551525516255172551825519255202552125522255232552425525255262552725528255292553025531255322553325534255352553625537255382553925540255412554225543255442554525546255472554825549255502555125552255532555425555255562555725558255592556025561255622556325564255652556625567255682556925570255712557225573255742557525576255772557825579255802558125582255832558425585255862558725588255892559025591255922559325594255952559625597255982559925600256012560225603256042560525606256072560825609256102561125612256132561425615256162561725618256192562025621256222562325624256252562625627256282562925630256312563225633256342563525636256372563825639256402564125642256432564425645256462564725648256492565025651256522565325654256552565625657256582565925660256612566225663256642566525666256672566825669256702567125672256732567425675256762567725678256792568025681256822568325684256852568625687256882568925690256912569225693256942569525696256972569825699257002570125702257032570425705257062570725708257092571025711257122571325714257152571625717257182571925720257212572225723257242572525726257272572825729257302573125732257332573425735257362573725738257392574025741257422574325744257452574625747257482574925750257512575225753257542575525756257572575825759257602576125762257632576425765257662576725768257692577025771257722577325774257752577625777257782577925780257812578225783257842578525786257872578825789257902579125792257932579425795257962579725798257992580025801258022580325804258052580625807258082580925810258112581225813258142581525816258172581825819258202582125822258232582425825258262582725828258292583025831258322583325834258352583625837258382583925840258412584225843258442584525846258472584825849258502585125852258532585425855258562585725858258592586025861258622586325864258652586625867258682586925870258712587225873258742587525876258772587825879258802588125882258832588425885258862588725888258892589025891258922589325894258952589625897258982589925900259012590225903259042590525906259072590825909259102591125912259132591425915259162591725918259192592025921259222592325924259252592625927259282592925930259312593225933259342593525936259372593825939259402594125942259432594425945259462594725948259492595025951259522595325954259552595625957259582595925960259612596225963259642596525966259672596825969259702597125972259732597425975259762597725978259792598025981259822598325984259852598625987259882598925990259912599225993259942599525996259972599825999260002600126002260032600426005260062600726008260092601026011260122601326014260152601626017260182601926020260212602226023260242602526026260272602826029260302603126032260332603426035260362603726038260392604026041260422604326044260452604626047260482604926050260512605226053260542605526056260572605826059260602606126062260632606426065260662606726068260692607026071260722607326074260752607626077260782607926080260812608226083260842608526086260872608826089260902609126092260932609426095260962609726098260992610026101261022610326104261052610626107261082610926110261112611226113261142611526116261172611826119261202612126122261232612426125261262612726128261292613026131261322613326134261352613626137261382613926140261412614226143261442614526146261472614826149261502615126152261532615426155261562615726158261592616026161261622616326164261652616626167261682616926170261712617226173261742617526176261772617826179261802618126182261832618426185261862618726188261892619026191261922619326194261952619626197261982619926200262012620226203262042620526206262072620826209262102621126212262132621426215262162621726218262192622026221262222622326224262252622626227262282622926230262312623226233262342623526236262372623826239262402624126242262432624426245262462624726248262492625026251262522625326254262552625626257262582625926260262612626226263262642626526266262672626826269262702627126272262732627426275262762627726278262792628026281262822628326284262852628626287262882628926290262912629226293262942629526296262972629826299263002630126302263032630426305263062630726308263092631026311263122631326314263152631626317263182631926320263212632226323263242632526326263272632826329263302633126332263332633426335263362633726338263392634026341263422634326344263452634626347263482634926350263512635226353263542635526356263572635826359263602636126362263632636426365263662636726368263692637026371263722637326374263752637626377263782637926380263812638226383263842638526386263872638826389263902639126392263932639426395263962639726398263992640026401264022640326404264052640626407264082640926410264112641226413264142641526416264172641826419264202642126422264232642426425264262642726428264292643026431264322643326434264352643626437264382643926440264412644226443264442644526446264472644826449264502645126452264532645426455264562645726458264592646026461264622646326464264652646626467264682646926470264712647226473264742647526476264772647826479264802648126482264832648426485264862648726488264892649026491264922649326494264952649626497264982649926500265012650226503265042650526506265072650826509265102651126512265132651426515265162651726518265192652026521265222652326524265252652626527265282652926530265312653226533265342653526536265372653826539265402654126542265432654426545265462654726548265492655026551265522655326554265552655626557265582655926560265612656226563265642656526566265672656826569265702657126572265732657426575265762657726578265792658026581265822658326584265852658626587265882658926590265912659226593265942659526596265972659826599266002660126602266032660426605266062660726608266092661026611266122661326614266152661626617266182661926620266212662226623266242662526626266272662826629266302663126632266332663426635266362663726638266392664026641266422664326644266452664626647266482664926650266512665226653266542665526656266572665826659266602666126662266632666426665266662666726668266692667026671266722667326674266752667626677266782667926680266812668226683266842668526686266872668826689266902669126692266932669426695266962669726698266992670026701267022670326704267052670626707267082670926710267112671226713267142671526716267172671826719267202672126722267232672426725267262672726728267292673026731267322673326734267352673626737267382673926740267412674226743267442674526746267472674826749267502675126752267532675426755267562675726758267592676026761267622676326764267652676626767267682676926770267712677226773267742677526776267772677826779267802678126782267832678426785267862678726788267892679026791267922679326794267952679626797267982679926800268012680226803268042680526806268072680826809268102681126812268132681426815268162681726818268192682026821268222682326824268252682626827268282682926830268312683226833268342683526836268372683826839268402684126842268432684426845268462684726848268492685026851268522685326854268552685626857268582685926860268612686226863268642686526866268672686826869268702687126872268732687426875268762687726878268792688026881268822688326884268852688626887268882688926890268912689226893268942689526896268972689826899269002690126902269032690426905269062690726908269092691026911269122691326914269152691626917269182691926920269212692226923269242692526926269272692826929269302693126932269332693426935269362693726938269392694026941269422694326944269452694626947269482694926950269512695226953269542695526956269572695826959269602696126962269632696426965269662696726968269692697026971269722697326974269752697626977269782697926980269812698226983269842698526986269872698826989269902699126992269932699426995269962699726998269992700027001270022700327004270052700627007270082700927010270112701227013270142701527016270172701827019270202702127022270232702427025270262702727028270292703027031270322703327034270352703627037270382703927040270412704227043270442704527046270472704827049270502705127052270532705427055270562705727058270592706027061270622706327064270652706627067270682706927070270712707227073270742707527076270772707827079270802708127082270832708427085270862708727088270892709027091270922709327094270952709627097270982709927100271012710227103271042710527106271072710827109271102711127112271132711427115271162711727118271192712027121271222712327124271252712627127271282712927130271312713227133271342713527136271372713827139271402714127142271432714427145271462714727148271492715027151271522715327154271552715627157271582715927160271612716227163271642716527166271672716827169271702717127172271732717427175271762717727178271792718027181271822718327184271852718627187271882718927190271912719227193271942719527196271972719827199272002720127202272032720427205272062720727208272092721027211272122721327214272152721627217272182721927220272212722227223272242722527226272272722827229272302723127232272332723427235272362723727238272392724027241272422724327244272452724627247272482724927250272512725227253272542725527256272572725827259272602726127262272632726427265272662726727268272692727027271272722727327274272752727627277272782727927280272812728227283272842728527286272872728827289272902729127292272932729427295272962729727298272992730027301273022730327304273052730627307273082730927310273112731227313273142731527316273172731827319273202732127322273232732427325273262732727328273292733027331273322733327334273352733627337273382733927340273412734227343273442734527346273472734827349273502735127352273532735427355273562735727358273592736027361273622736327364273652736627367273682736927370273712737227373273742737527376273772737827379273802738127382273832738427385273862738727388273892739027391273922739327394273952739627397273982739927400274012740227403274042740527406274072740827409274102741127412274132741427415274162741727418274192742027421274222742327424274252742627427274282742927430274312743227433274342743527436274372743827439274402744127442274432744427445274462744727448274492745027451274522745327454274552745627457274582745927460274612746227463274642746527466274672746827469274702747127472274732747427475274762747727478274792748027481274822748327484274852748627487274882748927490274912749227493274942749527496274972749827499275002750127502275032750427505275062750727508275092751027511275122751327514275152751627517275182751927520275212752227523275242752527526275272752827529275302753127532275332753427535275362753727538275392754027541275422754327544275452754627547275482754927550275512755227553275542755527556275572755827559275602756127562275632756427565275662756727568275692757027571275722757327574275752757627577275782757927580275812758227583275842758527586275872758827589275902759127592275932759427595275962759727598275992760027601276022760327604276052760627607276082760927610276112761227613276142761527616276172761827619276202762127622276232762427625276262762727628276292763027631276322763327634276352763627637276382763927640276412764227643276442764527646276472764827649276502765127652276532765427655276562765727658276592766027661276622766327664276652766627667276682766927670276712767227673276742767527676276772767827679276802768127682276832768427685276862768727688276892769027691276922769327694276952769627697276982769927700277012770227703277042770527706277072770827709277102771127712277132771427715277162771727718277192772027721277222772327724277252772627727277282772927730277312773227733277342773527736277372773827739277402774127742277432774427745277462774727748277492775027751277522775327754277552775627757277582775927760277612776227763277642776527766277672776827769277702777127772277732777427775277762777727778277792778027781277822778327784277852778627787277882778927790277912779227793277942779527796277972779827799278002780127802278032780427805278062780727808278092781027811278122781327814278152781627817278182781927820278212782227823278242782527826278272782827829278302783127832278332783427835278362783727838278392784027841278422784327844278452784627847278482784927850278512785227853278542785527856278572785827859278602786127862278632786427865278662786727868278692787027871278722787327874278752787627877278782787927880278812788227883278842788527886278872788827889278902789127892278932789427895278962789727898278992790027901279022790327904279052790627907279082790927910279112791227913279142791527916279172791827919279202792127922279232792427925279262792727928279292793027931279322793327934279352793627937279382793927940279412794227943279442794527946279472794827949279502795127952279532795427955279562795727958279592796027961279622796327964279652796627967279682796927970279712797227973279742797527976279772797827979279802798127982279832798427985279862798727988279892799027991279922799327994279952799627997279982799928000280012800228003280042800528006280072800828009280102801128012280132801428015280162801728018280192802028021280222802328024280252802628027280282802928030280312803228033280342803528036280372803828039280402804128042280432804428045280462804728048280492805028051280522805328054280552805628057280582805928060280612806228063280642806528066280672806828069280702807128072280732807428075280762807728078280792808028081280822808328084280852808628087280882808928090280912809228093280942809528096280972809828099281002810128102281032810428105281062810728108281092811028111281122811328114281152811628117281182811928120281212812228123281242812528126281272812828129281302813128132281332813428135281362813728138281392814028141281422814328144281452814628147281482814928150281512815228153281542815528156281572815828159281602816128162281632816428165281662816728168281692817028171281722817328174281752817628177281782817928180281812818228183281842818528186281872818828189281902819128192281932819428195281962819728198281992820028201282022820328204282052820628207282082820928210282112821228213282142821528216282172821828219282202822128222282232822428225282262822728228282292823028231282322823328234282352823628237282382823928240282412824228243282442824528246282472824828249282502825128252282532825428255282562825728258282592826028261282622826328264282652826628267282682826928270282712827228273282742827528276282772827828279282802828128282282832828428285282862828728288282892829028291282922829328294282952829628297282982829928300283012830228303283042830528306283072830828309283102831128312283132831428315283162831728318283192832028321283222832328324283252832628327283282832928330283312833228333283342833528336283372833828339283402834128342283432834428345283462834728348283492835028351283522835328354283552835628357283582835928360283612836228363283642836528366283672836828369283702837128372283732837428375283762837728378283792838028381283822838328384283852838628387283882838928390283912839228393283942839528396283972839828399284002840128402284032840428405284062840728408284092841028411284122841328414284152841628417284182841928420284212842228423284242842528426284272842828429284302843128432284332843428435284362843728438284392844028441284422844328444284452844628447284482844928450284512845228453284542845528456284572845828459284602846128462284632846428465284662846728468284692847028471284722847328474284752847628477284782847928480284812848228483284842848528486284872848828489284902849128492284932849428495284962849728498284992850028501285022850328504285052850628507285082850928510285112851228513285142851528516285172851828519285202852128522285232852428525285262852728528285292853028531285322853328534285352853628537285382853928540285412854228543285442854528546285472854828549285502855128552285532855428555285562855728558285592856028561285622856328564285652856628567285682856928570285712857228573285742857528576285772857828579285802858128582285832858428585285862858728588285892859028591285922859328594285952859628597285982859928600286012860228603286042860528606286072860828609286102861128612286132861428615286162861728618286192862028621286222862328624286252862628627286282862928630286312863228633286342863528636286372863828639286402864128642286432864428645286462864728648286492865028651286522865328654286552865628657286582865928660286612866228663286642866528666286672866828669286702867128672286732867428675286762867728678286792868028681286822868328684286852868628687286882868928690286912869228693286942869528696286972869828699287002870128702287032870428705287062870728708287092871028711287122871328714287152871628717287182871928720287212872228723287242872528726287272872828729287302873128732287332873428735287362873728738287392874028741287422874328744287452874628747287482874928750287512875228753287542875528756287572875828759287602876128762287632876428765287662876728768287692877028771287722877328774287752877628777287782877928780287812878228783287842878528786287872878828789287902879128792287932879428795287962879728798287992880028801288022880328804288052880628807288082880928810288112881228813288142881528816288172881828819288202882128822288232882428825288262882728828288292883028831288322883328834288352883628837288382883928840288412884228843288442884528846288472884828849288502885128852288532885428855288562885728858288592886028861288622886328864288652886628867288682886928870288712887228873288742887528876288772887828879288802888128882288832888428885288862888728888288892889028891288922889328894288952889628897288982889928900289012890228903289042890528906289072890828909289102891128912289132891428915289162891728918289192892028921289222892328924289252892628927289282892928930289312893228933289342893528936289372893828939289402894128942289432894428945289462894728948289492895028951289522895328954289552895628957289582895928960289612896228963289642896528966289672896828969289702897128972289732897428975289762897728978289792898028981289822898328984289852898628987289882898928990289912899228993289942899528996289972899828999290002900129002290032900429005290062900729008290092901029011290122901329014290152901629017290182901929020290212902229023290242902529026290272902829029290302903129032290332903429035290362903729038290392904029041290422904329044290452904629047290482904929050290512905229053290542905529056290572905829059290602906129062290632906429065290662906729068290692907029071290722907329074290752907629077290782907929080290812908229083290842908529086290872908829089290902909129092290932909429095290962909729098290992910029101291022910329104291052910629107291082910929110291112911229113291142911529116291172911829119291202912129122291232912429125291262912729128291292913029131291322913329134291352913629137291382913929140291412914229143291442914529146291472914829149291502915129152291532915429155291562915729158291592916029161291622916329164291652916629167291682916929170291712917229173291742917529176291772917829179291802918129182291832918429185291862918729188291892919029191291922919329194291952919629197291982919929200292012920229203292042920529206292072920829209292102921129212292132921429215292162921729218292192922029221292222922329224292252922629227292282922929230292312923229233292342923529236292372923829239292402924129242292432924429245292462924729248292492925029251292522925329254292552925629257292582925929260292612926229263292642926529266292672926829269292702927129272292732927429275292762927729278292792928029281292822928329284292852928629287292882928929290292912929229293292942929529296292972929829299293002930129302293032930429305293062930729308293092931029311293122931329314293152931629317293182931929320293212932229323293242932529326293272932829329293302933129332293332933429335293362933729338293392934029341293422934329344293452934629347293482934929350293512935229353293542935529356293572935829359293602936129362293632936429365293662936729368293692937029371293722937329374293752937629377293782937929380293812938229383293842938529386293872938829389293902939129392293932939429395293962939729398293992940029401294022940329404294052940629407294082940929410294112941229413294142941529416294172941829419294202942129422294232942429425294262942729428294292943029431294322943329434294352943629437294382943929440294412944229443294442944529446294472944829449294502945129452294532945429455294562945729458294592946029461294622946329464294652946629467294682946929470294712947229473294742947529476294772947829479294802948129482294832948429485294862948729488294892949029491294922949329494294952949629497294982949929500295012950229503295042950529506295072950829509295102951129512295132951429515295162951729518295192952029521295222952329524295252952629527295282952929530295312953229533295342953529536295372953829539295402954129542295432954429545295462954729548295492955029551295522955329554295552955629557295582955929560295612956229563295642956529566295672956829569295702957129572295732957429575295762957729578295792958029581295822958329584295852958629587295882958929590295912959229593295942959529596295972959829599296002960129602296032960429605296062960729608296092961029611296122961329614296152961629617296182961929620296212962229623296242962529626296272962829629296302963129632296332963429635296362963729638296392964029641296422964329644296452964629647296482964929650296512965229653296542965529656296572965829659296602966129662296632966429665296662966729668296692967029671296722967329674296752967629677296782967929680296812968229683296842968529686296872968829689296902969129692296932969429695296962969729698296992970029701297022970329704297052970629707297082970929710297112971229713297142971529716297172971829719297202972129722297232972429725297262972729728297292973029731297322973329734297352973629737297382973929740297412974229743297442974529746297472974829749297502975129752297532975429755297562975729758297592976029761297622976329764297652976629767297682976929770297712977229773297742977529776297772977829779297802978129782297832978429785297862978729788297892979029791297922979329794297952979629797297982979929800298012980229803298042980529806298072980829809298102981129812298132981429815298162981729818298192982029821298222982329824298252982629827298282982929830298312983229833298342983529836298372983829839298402984129842298432984429845298462984729848298492985029851298522985329854298552985629857298582985929860298612986229863298642986529866298672986829869298702987129872298732987429875298762987729878298792988029881298822988329884298852988629887298882988929890298912989229893298942989529896298972989829899299002990129902299032990429905299062990729908299092991029911299122991329914299152991629917299182991929920299212992229923299242992529926299272992829929299302993129932299332993429935299362993729938299392994029941299422994329944299452994629947299482994929950299512995229953299542995529956299572995829959299602996129962299632996429965299662996729968299692997029971299722997329974299752997629977299782997929980299812998229983299842998529986299872998829989299902999129992299932999429995299962999729998299993000030001300023000330004300053000630007300083000930010300113001230013300143001530016300173001830019300203002130022300233002430025300263002730028300293003030031300323003330034300353003630037300383003930040300413004230043300443004530046300473004830049300503005130052300533005430055300563005730058300593006030061300623006330064300653006630067300683006930070300713007230073300743007530076300773007830079300803008130082300833008430085300863008730088300893009030091300923009330094300953009630097300983009930100301013010230103301043010530106301073010830109301103011130112301133011430115301163011730118301193012030121301223012330124301253012630127301283012930130301313013230133301343013530136301373013830139301403014130142301433014430145301463014730148301493015030151301523015330154301553015630157301583015930160301613016230163301643016530166301673016830169301703017130172301733017430175301763017730178301793018030181301823018330184301853018630187301883018930190301913019230193301943019530196301973019830199302003020130202302033020430205302063020730208302093021030211302123021330214302153021630217302183021930220302213022230223302243022530226302273022830229302303023130232302333023430235302363023730238302393024030241302423024330244302453024630247302483024930250302513025230253302543025530256302573025830259302603026130262302633026430265302663026730268302693027030271302723027330274302753027630277302783027930280302813028230283302843028530286302873028830289302903029130292302933029430295302963029730298302993030030301303023030330304303053030630307303083030930310303113031230313303143031530316303173031830319303203032130322303233032430325303263032730328303293033030331303323033330334303353033630337303383033930340303413034230343303443034530346303473034830349303503035130352303533035430355303563035730358303593036030361303623036330364303653036630367303683036930370303713037230373303743037530376303773037830379303803038130382303833038430385303863038730388303893039030391303923039330394303953039630397303983039930400304013040230403304043040530406304073040830409304103041130412304133041430415304163041730418304193042030421304223042330424304253042630427304283042930430304313043230433304343043530436304373043830439304403044130442304433044430445304463044730448304493045030451304523045330454304553045630457304583045930460304613046230463304643046530466304673046830469304703047130472304733047430475304763047730478304793048030481304823048330484304853048630487304883048930490304913049230493304943049530496304973049830499305003050130502305033050430505305063050730508305093051030511305123051330514305153051630517305183051930520305213052230523305243052530526305273052830529305303053130532305333053430535305363053730538305393054030541305423054330544305453054630547305483054930550305513055230553305543055530556305573055830559305603056130562305633056430565305663056730568305693057030571305723057330574305753057630577305783057930580305813058230583305843058530586305873058830589305903059130592305933059430595305963059730598
  1. /**
  2. * TinyMCE version 6.4.2 (2023-04-26)
  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$2 = 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$2(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$e = (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$5 = (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$e(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$5(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$d = (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$d(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. each$d(obj, (x, i) => {
  470. (pred(x, i) ? onTrue : onFalse)(x, i);
  471. });
  472. };
  473. const bifilter = (obj, pred) => {
  474. const t = {};
  475. const f = {};
  476. internalFilter(obj, pred, objAcc(t), objAcc(f));
  477. return {
  478. t,
  479. f
  480. };
  481. };
  482. const filter$4 = (obj, pred) => {
  483. const t = {};
  484. internalFilter(obj, pred, objAcc(t), noop);
  485. return t;
  486. };
  487. const mapToArray = (obj, f) => {
  488. const r = [];
  489. each$d(obj, (value, name) => {
  490. r.push(f(value, name));
  491. });
  492. return r;
  493. };
  494. const values = obj => {
  495. return mapToArray(obj, identity);
  496. };
  497. const get$a = (obj, key) => {
  498. return has$2(obj, key) ? Optional.from(obj[key]) : Optional.none();
  499. };
  500. const has$2 = (obj, key) => hasOwnProperty$2.call(obj, key);
  501. const hasNonNullableKey = (obj, key) => has$2(obj, key) && obj[key] !== undefined && obj[key] !== null;
  502. const equal$1 = (a1, a2, eq = eqAny) => eqRecord(eq).eq(a1, a2);
  503. const stringArray = a => {
  504. const all = {};
  505. each$e(a, key => {
  506. all[key] = {};
  507. });
  508. return keys(all);
  509. };
  510. const isArrayLike = o => o.length !== undefined;
  511. const isArray = Array.isArray;
  512. const toArray$1 = obj => {
  513. if (!isArray(obj)) {
  514. const array = [];
  515. for (let i = 0, l = obj.length; i < l; i++) {
  516. array[i] = obj[i];
  517. }
  518. return array;
  519. } else {
  520. return obj;
  521. }
  522. };
  523. const each$c = (o, cb, s) => {
  524. if (!o) {
  525. return false;
  526. }
  527. s = s || o;
  528. if (isArrayLike(o)) {
  529. for (let n = 0, l = o.length; n < l; n++) {
  530. if (cb.call(s, o[n], n, o) === false) {
  531. return false;
  532. }
  533. }
  534. } else {
  535. for (const n in o) {
  536. if (has$2(o, n)) {
  537. if (cb.call(s, o[n], n, o) === false) {
  538. return false;
  539. }
  540. }
  541. }
  542. }
  543. return true;
  544. };
  545. const map$1 = (array, callback) => {
  546. const out = [];
  547. each$c(array, (item, index) => {
  548. out.push(callback(item, index, array));
  549. });
  550. return out;
  551. };
  552. const filter$3 = (a, f) => {
  553. const o = [];
  554. each$c(a, (v, index) => {
  555. if (!f || f(v, index, a)) {
  556. o.push(v);
  557. }
  558. });
  559. return o;
  560. };
  561. const indexOf = (a, v) => {
  562. if (a) {
  563. for (let i = 0, l = a.length; i < l; i++) {
  564. if (a[i] === v) {
  565. return i;
  566. }
  567. }
  568. }
  569. return -1;
  570. };
  571. const reduce = (collection, iteratee, accumulator, thisArg) => {
  572. let acc = isUndefined(accumulator) ? collection[0] : accumulator;
  573. for (let i = 0; i < collection.length; i++) {
  574. acc = iteratee.call(thisArg, acc, collection[i], i);
  575. }
  576. return acc;
  577. };
  578. const findIndex$1 = (array, predicate, thisArg) => {
  579. for (let i = 0, l = array.length; i < l; i++) {
  580. if (predicate.call(thisArg, array[i], i, array)) {
  581. return i;
  582. }
  583. }
  584. return -1;
  585. };
  586. const last$2 = collection => collection[collection.length - 1];
  587. const cached = f => {
  588. let called = false;
  589. let r;
  590. return (...args) => {
  591. if (!called) {
  592. called = true;
  593. r = f.apply(null, args);
  594. }
  595. return r;
  596. };
  597. };
  598. const DeviceType = (os, browser, userAgent, mediaMatch) => {
  599. const isiPad = os.isiOS() && /ipad/i.test(userAgent) === true;
  600. const isiPhone = os.isiOS() && !isiPad;
  601. const isMobile = os.isiOS() || os.isAndroid();
  602. const isTouch = isMobile || mediaMatch('(pointer:coarse)');
  603. const isTablet = isiPad || !isiPhone && isMobile && mediaMatch('(min-device-width:768px)');
  604. const isPhone = isiPhone || isMobile && !isTablet;
  605. const iOSwebview = browser.isSafari() && os.isiOS() && /safari/i.test(userAgent) === false;
  606. const isDesktop = !isPhone && !isTablet && !iOSwebview;
  607. return {
  608. isiPad: constant(isiPad),
  609. isiPhone: constant(isiPhone),
  610. isTablet: constant(isTablet),
  611. isPhone: constant(isPhone),
  612. isTouch: constant(isTouch),
  613. isAndroid: os.isAndroid,
  614. isiOS: os.isiOS,
  615. isWebView: constant(iOSwebview),
  616. isDesktop: constant(isDesktop)
  617. };
  618. };
  619. const firstMatch = (regexes, s) => {
  620. for (let i = 0; i < regexes.length; i++) {
  621. const x = regexes[i];
  622. if (x.test(s)) {
  623. return x;
  624. }
  625. }
  626. return undefined;
  627. };
  628. const find$1 = (regexes, agent) => {
  629. const r = firstMatch(regexes, agent);
  630. if (!r) {
  631. return {
  632. major: 0,
  633. minor: 0
  634. };
  635. }
  636. const group = i => {
  637. return Number(agent.replace(r, '$' + i));
  638. };
  639. return nu$3(group(1), group(2));
  640. };
  641. const detect$5 = (versionRegexes, agent) => {
  642. const cleanedAgent = String(agent).toLowerCase();
  643. if (versionRegexes.length === 0) {
  644. return unknown$2();
  645. }
  646. return find$1(versionRegexes, cleanedAgent);
  647. };
  648. const unknown$2 = () => {
  649. return nu$3(0, 0);
  650. };
  651. const nu$3 = (major, minor) => {
  652. return {
  653. major,
  654. minor
  655. };
  656. };
  657. const Version = {
  658. nu: nu$3,
  659. detect: detect$5,
  660. unknown: unknown$2
  661. };
  662. const detectBrowser$1 = (browsers, userAgentData) => {
  663. return findMap(userAgentData.brands, uaBrand => {
  664. const lcBrand = uaBrand.brand.toLowerCase();
  665. return find$2(browsers, browser => {
  666. var _a;
  667. return lcBrand === ((_a = browser.brand) === null || _a === void 0 ? void 0 : _a.toLowerCase());
  668. }).map(info => ({
  669. current: info.name,
  670. version: Version.nu(parseInt(uaBrand.version, 10), 0)
  671. }));
  672. });
  673. };
  674. const detect$4 = (candidates, userAgent) => {
  675. const agent = String(userAgent).toLowerCase();
  676. return find$2(candidates, candidate => {
  677. return candidate.search(agent);
  678. });
  679. };
  680. const detectBrowser = (browsers, userAgent) => {
  681. return detect$4(browsers, userAgent).map(browser => {
  682. const version = Version.detect(browser.versionRegexes, userAgent);
  683. return {
  684. current: browser.name,
  685. version
  686. };
  687. });
  688. };
  689. const detectOs = (oses, userAgent) => {
  690. return detect$4(oses, userAgent).map(os => {
  691. const version = Version.detect(os.versionRegexes, userAgent);
  692. return {
  693. current: os.name,
  694. version
  695. };
  696. });
  697. };
  698. const removeFromStart = (str, numChars) => {
  699. return str.substring(numChars);
  700. };
  701. const checkRange = (str, substr, start) => substr === '' || str.length >= substr.length && str.substr(start, start + substr.length) === substr;
  702. const removeLeading = (str, prefix) => {
  703. return startsWith(str, prefix) ? removeFromStart(str, prefix.length) : str;
  704. };
  705. const contains$1 = (str, substr, start = 0, end) => {
  706. const idx = str.indexOf(substr, start);
  707. if (idx !== -1) {
  708. return isUndefined(end) ? true : idx + substr.length <= end;
  709. } else {
  710. return false;
  711. }
  712. };
  713. const startsWith = (str, prefix) => {
  714. return checkRange(str, prefix, 0);
  715. };
  716. const endsWith = (str, suffix) => {
  717. return checkRange(str, suffix, str.length - suffix.length);
  718. };
  719. const blank = r => s => s.replace(r, '');
  720. const trim$3 = blank(/^\s+|\s+$/g);
  721. const lTrim = blank(/^\s+/g);
  722. const rTrim = blank(/\s+$/g);
  723. const isNotEmpty = s => s.length > 0;
  724. const isEmpty$3 = s => !isNotEmpty(s);
  725. const repeat = (s, count) => count <= 0 ? '' : new Array(count + 1).join(s);
  726. const toInt = (value, radix = 10) => {
  727. const num = parseInt(value, radix);
  728. return isNaN(num) ? Optional.none() : Optional.some(num);
  729. };
  730. const normalVersionRegex = /.*?version\/\ ?([0-9]+)\.([0-9]+).*/;
  731. const checkContains = target => {
  732. return uastring => {
  733. return contains$1(uastring, target);
  734. };
  735. };
  736. const browsers = [
  737. {
  738. name: 'Edge',
  739. versionRegexes: [/.*?edge\/ ?([0-9]+)\.([0-9]+)$/],
  740. search: uastring => {
  741. return contains$1(uastring, 'edge/') && contains$1(uastring, 'chrome') && contains$1(uastring, 'safari') && contains$1(uastring, 'applewebkit');
  742. }
  743. },
  744. {
  745. name: 'Chromium',
  746. brand: 'Chromium',
  747. versionRegexes: [
  748. /.*?chrome\/([0-9]+)\.([0-9]+).*/,
  749. normalVersionRegex
  750. ],
  751. search: uastring => {
  752. return contains$1(uastring, 'chrome') && !contains$1(uastring, 'chromeframe');
  753. }
  754. },
  755. {
  756. name: 'IE',
  757. versionRegexes: [
  758. /.*?msie\ ?([0-9]+)\.([0-9]+).*/,
  759. /.*?rv:([0-9]+)\.([0-9]+).*/
  760. ],
  761. search: uastring => {
  762. return contains$1(uastring, 'msie') || contains$1(uastring, 'trident');
  763. }
  764. },
  765. {
  766. name: 'Opera',
  767. versionRegexes: [
  768. normalVersionRegex,
  769. /.*?opera\/([0-9]+)\.([0-9]+).*/
  770. ],
  771. search: checkContains('opera')
  772. },
  773. {
  774. name: 'Firefox',
  775. versionRegexes: [/.*?firefox\/\ ?([0-9]+)\.([0-9]+).*/],
  776. search: checkContains('firefox')
  777. },
  778. {
  779. name: 'Safari',
  780. versionRegexes: [
  781. normalVersionRegex,
  782. /.*?cpu os ([0-9]+)_([0-9]+).*/
  783. ],
  784. search: uastring => {
  785. return (contains$1(uastring, 'safari') || contains$1(uastring, 'mobile/')) && contains$1(uastring, 'applewebkit');
  786. }
  787. }
  788. ];
  789. const oses = [
  790. {
  791. name: 'Windows',
  792. search: checkContains('win'),
  793. versionRegexes: [/.*?windows\ nt\ ?([0-9]+)\.([0-9]+).*/]
  794. },
  795. {
  796. name: 'iOS',
  797. search: uastring => {
  798. return contains$1(uastring, 'iphone') || contains$1(uastring, 'ipad');
  799. },
  800. versionRegexes: [
  801. /.*?version\/\ ?([0-9]+)\.([0-9]+).*/,
  802. /.*cpu os ([0-9]+)_([0-9]+).*/,
  803. /.*cpu iphone os ([0-9]+)_([0-9]+).*/
  804. ]
  805. },
  806. {
  807. name: 'Android',
  808. search: checkContains('android'),
  809. versionRegexes: [/.*?android\ ?([0-9]+)\.([0-9]+).*/]
  810. },
  811. {
  812. name: 'macOS',
  813. search: checkContains('mac os x'),
  814. versionRegexes: [/.*?mac\ os\ x\ ?([0-9]+)_([0-9]+).*/]
  815. },
  816. {
  817. name: 'Linux',
  818. search: checkContains('linux'),
  819. versionRegexes: []
  820. },
  821. {
  822. name: 'Solaris',
  823. search: checkContains('sunos'),
  824. versionRegexes: []
  825. },
  826. {
  827. name: 'FreeBSD',
  828. search: checkContains('freebsd'),
  829. versionRegexes: []
  830. },
  831. {
  832. name: 'ChromeOS',
  833. search: checkContains('cros'),
  834. versionRegexes: [/.*?chrome\/([0-9]+)\.([0-9]+).*/]
  835. }
  836. ];
  837. const PlatformInfo = {
  838. browsers: constant(browsers),
  839. oses: constant(oses)
  840. };
  841. const edge = 'Edge';
  842. const chromium = 'Chromium';
  843. const ie = 'IE';
  844. const opera = 'Opera';
  845. const firefox = 'Firefox';
  846. const safari = 'Safari';
  847. const unknown$1 = () => {
  848. return nu$2({
  849. current: undefined,
  850. version: Version.unknown()
  851. });
  852. };
  853. const nu$2 = info => {
  854. const current = info.current;
  855. const version = info.version;
  856. const isBrowser = name => () => current === name;
  857. return {
  858. current,
  859. version,
  860. isEdge: isBrowser(edge),
  861. isChromium: isBrowser(chromium),
  862. isIE: isBrowser(ie),
  863. isOpera: isBrowser(opera),
  864. isFirefox: isBrowser(firefox),
  865. isSafari: isBrowser(safari)
  866. };
  867. };
  868. const Browser = {
  869. unknown: unknown$1,
  870. nu: nu$2,
  871. edge: constant(edge),
  872. chromium: constant(chromium),
  873. ie: constant(ie),
  874. opera: constant(opera),
  875. firefox: constant(firefox),
  876. safari: constant(safari)
  877. };
  878. const windows = 'Windows';
  879. const ios = 'iOS';
  880. const android = 'Android';
  881. const linux = 'Linux';
  882. const macos = 'macOS';
  883. const solaris = 'Solaris';
  884. const freebsd = 'FreeBSD';
  885. const chromeos = 'ChromeOS';
  886. const unknown = () => {
  887. return nu$1({
  888. current: undefined,
  889. version: Version.unknown()
  890. });
  891. };
  892. const nu$1 = info => {
  893. const current = info.current;
  894. const version = info.version;
  895. const isOS = name => () => current === name;
  896. return {
  897. current,
  898. version,
  899. isWindows: isOS(windows),
  900. isiOS: isOS(ios),
  901. isAndroid: isOS(android),
  902. isMacOS: isOS(macos),
  903. isLinux: isOS(linux),
  904. isSolaris: isOS(solaris),
  905. isFreeBSD: isOS(freebsd),
  906. isChromeOS: isOS(chromeos)
  907. };
  908. };
  909. const OperatingSystem = {
  910. unknown,
  911. nu: nu$1,
  912. windows: constant(windows),
  913. ios: constant(ios),
  914. android: constant(android),
  915. linux: constant(linux),
  916. macos: constant(macos),
  917. solaris: constant(solaris),
  918. freebsd: constant(freebsd),
  919. chromeos: constant(chromeos)
  920. };
  921. const detect$3 = (userAgent, userAgentDataOpt, mediaMatch) => {
  922. const browsers = PlatformInfo.browsers();
  923. const oses = PlatformInfo.oses();
  924. const browser = userAgentDataOpt.bind(userAgentData => detectBrowser$1(browsers, userAgentData)).orThunk(() => detectBrowser(browsers, userAgent)).fold(Browser.unknown, Browser.nu);
  925. const os = detectOs(oses, userAgent).fold(OperatingSystem.unknown, OperatingSystem.nu);
  926. const deviceType = DeviceType(os, browser, userAgent, mediaMatch);
  927. return {
  928. browser,
  929. os,
  930. deviceType
  931. };
  932. };
  933. const PlatformDetection = { detect: detect$3 };
  934. const mediaMatch = query => window.matchMedia(query).matches;
  935. let platform$2 = cached(() => PlatformDetection.detect(navigator.userAgent, Optional.from(navigator.userAgentData), mediaMatch));
  936. const detect$2 = () => platform$2();
  937. const userAgent = navigator.userAgent;
  938. const platform$1 = detect$2();
  939. const browser$1 = platform$1.browser;
  940. const os = platform$1.os;
  941. const deviceType = platform$1.deviceType;
  942. const windowsPhone = userAgent.indexOf('Windows Phone') !== -1;
  943. const Env = {
  944. transparentSrc: 'data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7',
  945. documentMode: browser$1.isIE() ? document.documentMode || 7 : 10,
  946. cacheSuffix: null,
  947. container: null,
  948. canHaveCSP: !browser$1.isIE(),
  949. windowsPhone,
  950. browser: {
  951. current: browser$1.current,
  952. version: browser$1.version,
  953. isChromium: browser$1.isChromium,
  954. isEdge: browser$1.isEdge,
  955. isFirefox: browser$1.isFirefox,
  956. isIE: browser$1.isIE,
  957. isOpera: browser$1.isOpera,
  958. isSafari: browser$1.isSafari
  959. },
  960. os: {
  961. current: os.current,
  962. version: os.version,
  963. isAndroid: os.isAndroid,
  964. isChromeOS: os.isChromeOS,
  965. isFreeBSD: os.isFreeBSD,
  966. isiOS: os.isiOS,
  967. isLinux: os.isLinux,
  968. isMacOS: os.isMacOS,
  969. isSolaris: os.isSolaris,
  970. isWindows: os.isWindows
  971. },
  972. deviceType: {
  973. isDesktop: deviceType.isDesktop,
  974. isiPad: deviceType.isiPad,
  975. isiPhone: deviceType.isiPhone,
  976. isPhone: deviceType.isPhone,
  977. isTablet: deviceType.isTablet,
  978. isTouch: deviceType.isTouch,
  979. isWebView: deviceType.isWebView
  980. }
  981. };
  982. const whiteSpaceRegExp$1 = /^\s*|\s*$/g;
  983. const trim$2 = str => {
  984. return isNullable(str) ? '' : ('' + str).replace(whiteSpaceRegExp$1, '');
  985. };
  986. const is$3 = (obj, type) => {
  987. if (!type) {
  988. return obj !== undefined;
  989. }
  990. if (type === 'array' && isArray(obj)) {
  991. return true;
  992. }
  993. return typeof obj === type;
  994. };
  995. const makeMap$4 = (items, delim, map = {}) => {
  996. const resolvedItems = isString(items) ? items.split(delim || ',') : items || [];
  997. let i = resolvedItems.length;
  998. while (i--) {
  999. map[resolvedItems[i]] = {};
  1000. }
  1001. return map;
  1002. };
  1003. const hasOwnProperty$1 = has$2;
  1004. const extend$3 = (obj, ...exts) => {
  1005. for (let i = 0; i < exts.length; i++) {
  1006. const ext = exts[i];
  1007. for (const name in ext) {
  1008. if (has$2(ext, name)) {
  1009. const value = ext[name];
  1010. if (value !== undefined) {
  1011. obj[name] = value;
  1012. }
  1013. }
  1014. }
  1015. }
  1016. return obj;
  1017. };
  1018. const walk$4 = function (o, f, n, s) {
  1019. s = s || this;
  1020. if (o) {
  1021. if (n) {
  1022. o = o[n];
  1023. }
  1024. each$c(o, (o, i) => {
  1025. if (f.call(s, o, i, n) === false) {
  1026. return false;
  1027. } else {
  1028. walk$4(o, f, n, s);
  1029. return true;
  1030. }
  1031. });
  1032. }
  1033. };
  1034. const resolve$3 = (n, o = window) => {
  1035. const path = n.split('.');
  1036. for (let i = 0, l = path.length; i < l; i++) {
  1037. o = o[path[i]];
  1038. if (!o) {
  1039. break;
  1040. }
  1041. }
  1042. return o;
  1043. };
  1044. const explode$3 = (s, d) => {
  1045. if (isArray$1(s)) {
  1046. return s;
  1047. } else if (s === '') {
  1048. return [];
  1049. } else {
  1050. return map$1(s.split(d || ','), trim$2);
  1051. }
  1052. };
  1053. const _addCacheSuffix = url => {
  1054. const cacheSuffix = Env.cacheSuffix;
  1055. if (cacheSuffix) {
  1056. url += (url.indexOf('?') === -1 ? '?' : '&') + cacheSuffix;
  1057. }
  1058. return url;
  1059. };
  1060. const Tools = {
  1061. trim: trim$2,
  1062. isArray: isArray,
  1063. is: is$3,
  1064. toArray: toArray$1,
  1065. makeMap: makeMap$4,
  1066. each: each$c,
  1067. map: map$1,
  1068. grep: filter$3,
  1069. inArray: indexOf,
  1070. hasOwn: hasOwnProperty$1,
  1071. extend: extend$3,
  1072. walk: walk$4,
  1073. resolve: resolve$3,
  1074. explode: explode$3,
  1075. _addCacheSuffix
  1076. };
  1077. const is$2 = (lhs, rhs, comparator = tripleEquals) => lhs.exists(left => comparator(left, rhs));
  1078. const cat = arr => {
  1079. const r = [];
  1080. const push = x => {
  1081. r.push(x);
  1082. };
  1083. for (let i = 0; i < arr.length; i++) {
  1084. arr[i].each(push);
  1085. }
  1086. return r;
  1087. };
  1088. const lift2 = (oa, ob, f) => oa.isSome() && ob.isSome() ? Optional.some(f(oa.getOrDie(), ob.getOrDie())) : Optional.none();
  1089. const lift3 = (oa, ob, oc, f) => oa.isSome() && ob.isSome() && oc.isSome() ? Optional.some(f(oa.getOrDie(), ob.getOrDie(), oc.getOrDie())) : Optional.none();
  1090. const someIf = (b, a) => b ? Optional.some(a) : Optional.none();
  1091. const Global = typeof window !== 'undefined' ? window : Function('return this;')();
  1092. const path = (parts, scope) => {
  1093. let o = scope !== undefined && scope !== null ? scope : Global;
  1094. for (let i = 0; i < parts.length && o !== undefined && o !== null; ++i) {
  1095. o = o[parts[i]];
  1096. }
  1097. return o;
  1098. };
  1099. const resolve$2 = (p, scope) => {
  1100. const parts = p.split('.');
  1101. return path(parts, scope);
  1102. };
  1103. const unsafe = (name, scope) => {
  1104. return resolve$2(name, scope);
  1105. };
  1106. const getOrDie = (name, scope) => {
  1107. const actual = unsafe(name, scope);
  1108. if (actual === undefined || actual === null) {
  1109. throw new Error(name + ' not available on this browser');
  1110. }
  1111. return actual;
  1112. };
  1113. const getPrototypeOf$1 = Object.getPrototypeOf;
  1114. const sandHTMLElement = scope => {
  1115. return getOrDie('HTMLElement', scope);
  1116. };
  1117. const isPrototypeOf = x => {
  1118. const scope = resolve$2('ownerDocument.defaultView', x);
  1119. return isObject(x) && (sandHTMLElement(scope).prototype.isPrototypeOf(x) || /^HTML\w*Element$/.test(getPrototypeOf$1(x).constructor.name));
  1120. };
  1121. const COMMENT = 8;
  1122. const DOCUMENT = 9;
  1123. const DOCUMENT_FRAGMENT = 11;
  1124. const ELEMENT = 1;
  1125. const TEXT = 3;
  1126. const name = element => {
  1127. const r = element.dom.nodeName;
  1128. return r.toLowerCase();
  1129. };
  1130. const type$1 = element => element.dom.nodeType;
  1131. const isType = t => element => type$1(element) === t;
  1132. const isComment$1 = element => type$1(element) === COMMENT || name(element) === '#comment';
  1133. const isHTMLElement = element => isElement$7(element) && isPrototypeOf(element.dom);
  1134. const isElement$7 = isType(ELEMENT);
  1135. const isText$b = isType(TEXT);
  1136. const isDocument$2 = isType(DOCUMENT);
  1137. const isDocumentFragment$1 = isType(DOCUMENT_FRAGMENT);
  1138. const isTag = tag => e => isElement$7(e) && name(e) === tag;
  1139. const rawSet = (dom, key, value) => {
  1140. if (isString(value) || isBoolean(value) || isNumber(value)) {
  1141. dom.setAttribute(key, value + '');
  1142. } else {
  1143. console.error('Invalid call to Attribute.set. Key ', key, ':: Value ', value, ':: Element ', dom);
  1144. throw new Error('Attribute value was not simple');
  1145. }
  1146. };
  1147. const set$3 = (element, key, value) => {
  1148. rawSet(element.dom, key, value);
  1149. };
  1150. const setAll$1 = (element, attrs) => {
  1151. const dom = element.dom;
  1152. each$d(attrs, (v, k) => {
  1153. rawSet(dom, k, v);
  1154. });
  1155. };
  1156. const get$9 = (element, key) => {
  1157. const v = element.dom.getAttribute(key);
  1158. return v === null ? undefined : v;
  1159. };
  1160. const getOpt = (element, key) => Optional.from(get$9(element, key));
  1161. const has$1 = (element, key) => {
  1162. const dom = element.dom;
  1163. return dom && dom.hasAttribute ? dom.hasAttribute(key) : false;
  1164. };
  1165. const remove$b = (element, key) => {
  1166. element.dom.removeAttribute(key);
  1167. };
  1168. const hasNone = element => {
  1169. const attrs = element.dom.attributes;
  1170. return attrs === undefined || attrs === null || attrs.length === 0;
  1171. };
  1172. const clone$4 = element => foldl(element.dom.attributes, (acc, attr) => {
  1173. acc[attr.name] = attr.value;
  1174. return acc;
  1175. }, {});
  1176. const read$4 = (element, attr) => {
  1177. const value = get$9(element, attr);
  1178. return value === undefined || value === '' ? [] : value.split(' ');
  1179. };
  1180. const add$4 = (element, attr, id) => {
  1181. const old = read$4(element, attr);
  1182. const nu = old.concat([id]);
  1183. set$3(element, attr, nu.join(' '));
  1184. return true;
  1185. };
  1186. const remove$a = (element, attr, id) => {
  1187. const nu = filter$5(read$4(element, attr), v => v !== id);
  1188. if (nu.length > 0) {
  1189. set$3(element, attr, nu.join(' '));
  1190. } else {
  1191. remove$b(element, attr);
  1192. }
  1193. return false;
  1194. };
  1195. const supports = element => element.dom.classList !== undefined;
  1196. const get$8 = element => read$4(element, 'class');
  1197. const add$3 = (element, clazz) => add$4(element, 'class', clazz);
  1198. const remove$9 = (element, clazz) => remove$a(element, 'class', clazz);
  1199. const toggle$2 = (element, clazz) => {
  1200. if (contains$2(get$8(element), clazz)) {
  1201. return remove$9(element, clazz);
  1202. } else {
  1203. return add$3(element, clazz);
  1204. }
  1205. };
  1206. const add$2 = (element, clazz) => {
  1207. if (supports(element)) {
  1208. element.dom.classList.add(clazz);
  1209. } else {
  1210. add$3(element, clazz);
  1211. }
  1212. };
  1213. const cleanClass = element => {
  1214. const classList = supports(element) ? element.dom.classList : get$8(element);
  1215. if (classList.length === 0) {
  1216. remove$b(element, 'class');
  1217. }
  1218. };
  1219. const remove$8 = (element, clazz) => {
  1220. if (supports(element)) {
  1221. const classList = element.dom.classList;
  1222. classList.remove(clazz);
  1223. } else {
  1224. remove$9(element, clazz);
  1225. }
  1226. cleanClass(element);
  1227. };
  1228. const toggle$1 = (element, clazz) => {
  1229. const result = supports(element) ? element.dom.classList.toggle(clazz) : toggle$2(element, clazz);
  1230. cleanClass(element);
  1231. return result;
  1232. };
  1233. const has = (element, clazz) => supports(element) && element.dom.classList.contains(clazz);
  1234. const fromHtml$1 = (html, scope) => {
  1235. const doc = scope || document;
  1236. const div = doc.createElement('div');
  1237. div.innerHTML = html;
  1238. if (!div.hasChildNodes() || div.childNodes.length > 1) {
  1239. const message = 'HTML does not have a single root node';
  1240. console.error(message, html);
  1241. throw new Error(message);
  1242. }
  1243. return fromDom$2(div.childNodes[0]);
  1244. };
  1245. const fromTag = (tag, scope) => {
  1246. const doc = scope || document;
  1247. const node = doc.createElement(tag);
  1248. return fromDom$2(node);
  1249. };
  1250. const fromText = (text, scope) => {
  1251. const doc = scope || document;
  1252. const node = doc.createTextNode(text);
  1253. return fromDom$2(node);
  1254. };
  1255. const fromDom$2 = node => {
  1256. if (node === null || node === undefined) {
  1257. throw new Error('Node cannot be null or undefined');
  1258. }
  1259. return { dom: node };
  1260. };
  1261. const fromPoint$2 = (docElm, x, y) => Optional.from(docElm.dom.elementFromPoint(x, y)).map(fromDom$2);
  1262. const SugarElement = {
  1263. fromHtml: fromHtml$1,
  1264. fromTag,
  1265. fromText,
  1266. fromDom: fromDom$2,
  1267. fromPoint: fromPoint$2
  1268. };
  1269. const toArray = (target, f) => {
  1270. const r = [];
  1271. const recurse = e => {
  1272. r.push(e);
  1273. return f(e);
  1274. };
  1275. let cur = f(target);
  1276. do {
  1277. cur = cur.bind(recurse);
  1278. } while (cur.isSome());
  1279. return r;
  1280. };
  1281. const is$1 = (element, selector) => {
  1282. const dom = element.dom;
  1283. if (dom.nodeType !== ELEMENT) {
  1284. return false;
  1285. } else {
  1286. const elem = dom;
  1287. if (elem.matches !== undefined) {
  1288. return elem.matches(selector);
  1289. } else if (elem.msMatchesSelector !== undefined) {
  1290. return elem.msMatchesSelector(selector);
  1291. } else if (elem.webkitMatchesSelector !== undefined) {
  1292. return elem.webkitMatchesSelector(selector);
  1293. } else if (elem.mozMatchesSelector !== undefined) {
  1294. return elem.mozMatchesSelector(selector);
  1295. } else {
  1296. throw new Error('Browser lacks native selectors');
  1297. }
  1298. }
  1299. };
  1300. const bypassSelector = dom => dom.nodeType !== ELEMENT && dom.nodeType !== DOCUMENT && dom.nodeType !== DOCUMENT_FRAGMENT || dom.childElementCount === 0;
  1301. const all = (selector, scope) => {
  1302. const base = scope === undefined ? document : scope.dom;
  1303. return bypassSelector(base) ? [] : map$3(base.querySelectorAll(selector), SugarElement.fromDom);
  1304. };
  1305. const one = (selector, scope) => {
  1306. const base = scope === undefined ? document : scope.dom;
  1307. return bypassSelector(base) ? Optional.none() : Optional.from(base.querySelector(selector)).map(SugarElement.fromDom);
  1308. };
  1309. const eq = (e1, e2) => e1.dom === e2.dom;
  1310. const contains = (e1, e2) => {
  1311. const d1 = e1.dom;
  1312. const d2 = e2.dom;
  1313. return d1 === d2 ? false : d1.contains(d2);
  1314. };
  1315. const owner$1 = element => SugarElement.fromDom(element.dom.ownerDocument);
  1316. const documentOrOwner = dos => isDocument$2(dos) ? dos : owner$1(dos);
  1317. const documentElement = element => SugarElement.fromDom(documentOrOwner(element).dom.documentElement);
  1318. const defaultView = element => SugarElement.fromDom(documentOrOwner(element).dom.defaultView);
  1319. const parent = element => Optional.from(element.dom.parentNode).map(SugarElement.fromDom);
  1320. const parentElement = element => Optional.from(element.dom.parentElement).map(SugarElement.fromDom);
  1321. const parents$1 = (element, isRoot) => {
  1322. const stop = isFunction(isRoot) ? isRoot : never;
  1323. let dom = element.dom;
  1324. const ret = [];
  1325. while (dom.parentNode !== null && dom.parentNode !== undefined) {
  1326. const rawParent = dom.parentNode;
  1327. const p = SugarElement.fromDom(rawParent);
  1328. ret.push(p);
  1329. if (stop(p) === true) {
  1330. break;
  1331. } else {
  1332. dom = rawParent;
  1333. }
  1334. }
  1335. return ret;
  1336. };
  1337. const siblings = element => {
  1338. const filterSelf = elements => filter$5(elements, x => !eq(element, x));
  1339. return parent(element).map(children$1).map(filterSelf).getOr([]);
  1340. };
  1341. const prevSibling = element => Optional.from(element.dom.previousSibling).map(SugarElement.fromDom);
  1342. const nextSibling = element => Optional.from(element.dom.nextSibling).map(SugarElement.fromDom);
  1343. const prevSiblings = element => reverse(toArray(element, prevSibling));
  1344. const nextSiblings = element => toArray(element, nextSibling);
  1345. const children$1 = element => map$3(element.dom.childNodes, SugarElement.fromDom);
  1346. const child$1 = (element, index) => {
  1347. const cs = element.dom.childNodes;
  1348. return Optional.from(cs[index]).map(SugarElement.fromDom);
  1349. };
  1350. const firstChild = element => child$1(element, 0);
  1351. const lastChild = element => child$1(element, element.dom.childNodes.length - 1);
  1352. const childNodesCount = element => element.dom.childNodes.length;
  1353. const getHead = doc => {
  1354. const b = doc.dom.head;
  1355. if (b === null || b === undefined) {
  1356. throw new Error('Head is not available yet');
  1357. }
  1358. return SugarElement.fromDom(b);
  1359. };
  1360. const isShadowRoot = dos => isDocumentFragment$1(dos) && isNonNullable(dos.dom.host);
  1361. const supported = isFunction(Element.prototype.attachShadow) && isFunction(Node.prototype.getRootNode);
  1362. const isSupported$1 = constant(supported);
  1363. const getRootNode = supported ? e => SugarElement.fromDom(e.dom.getRootNode()) : documentOrOwner;
  1364. const getStyleContainer = dos => isShadowRoot(dos) ? dos : getHead(documentOrOwner(dos));
  1365. const getContentContainer = dos => isShadowRoot(dos) ? dos : SugarElement.fromDom(documentOrOwner(dos).dom.body);
  1366. const getShadowRoot = e => {
  1367. const r = getRootNode(e);
  1368. return isShadowRoot(r) ? Optional.some(r) : Optional.none();
  1369. };
  1370. const getShadowHost = e => SugarElement.fromDom(e.dom.host);
  1371. const getOriginalEventTarget = event => {
  1372. if (isSupported$1() && isNonNullable(event.target)) {
  1373. const el = SugarElement.fromDom(event.target);
  1374. if (isElement$7(el) && isOpenShadowHost(el)) {
  1375. if (event.composed && event.composedPath) {
  1376. const composedPath = event.composedPath();
  1377. if (composedPath) {
  1378. return head(composedPath);
  1379. }
  1380. }
  1381. }
  1382. }
  1383. return Optional.from(event.target);
  1384. };
  1385. const isOpenShadowHost = element => isNonNullable(element.dom.shadowRoot);
  1386. const inBody = element => {
  1387. const dom = isText$b(element) ? element.dom.parentNode : element.dom;
  1388. if (dom === undefined || dom === null || dom.ownerDocument === null) {
  1389. return false;
  1390. }
  1391. const doc = dom.ownerDocument;
  1392. return getShadowRoot(SugarElement.fromDom(dom)).fold(() => doc.body.contains(dom), compose1(inBody, getShadowHost));
  1393. };
  1394. var ClosestOrAncestor = (is, ancestor, scope, a, isRoot) => {
  1395. if (is(scope, a)) {
  1396. return Optional.some(scope);
  1397. } else if (isFunction(isRoot) && isRoot(scope)) {
  1398. return Optional.none();
  1399. } else {
  1400. return ancestor(scope, a, isRoot);
  1401. }
  1402. };
  1403. const ancestor$4 = (scope, predicate, isRoot) => {
  1404. let element = scope.dom;
  1405. const stop = isFunction(isRoot) ? isRoot : never;
  1406. while (element.parentNode) {
  1407. element = element.parentNode;
  1408. const el = SugarElement.fromDom(element);
  1409. if (predicate(el)) {
  1410. return Optional.some(el);
  1411. } else if (stop(el)) {
  1412. break;
  1413. }
  1414. }
  1415. return Optional.none();
  1416. };
  1417. const closest$4 = (scope, predicate, isRoot) => {
  1418. const is = (s, test) => test(s);
  1419. return ClosestOrAncestor(is, ancestor$4, scope, predicate, isRoot);
  1420. };
  1421. const sibling$1 = (scope, predicate) => {
  1422. const element = scope.dom;
  1423. if (!element.parentNode) {
  1424. return Optional.none();
  1425. }
  1426. return child(SugarElement.fromDom(element.parentNode), x => !eq(scope, x) && predicate(x));
  1427. };
  1428. const child = (scope, predicate) => {
  1429. const pred = node => predicate(SugarElement.fromDom(node));
  1430. const result = find$2(scope.dom.childNodes, pred);
  1431. return result.map(SugarElement.fromDom);
  1432. };
  1433. const descendant$1 = (scope, predicate) => {
  1434. const descend = node => {
  1435. for (let i = 0; i < node.childNodes.length; i++) {
  1436. const child = SugarElement.fromDom(node.childNodes[i]);
  1437. if (predicate(child)) {
  1438. return Optional.some(child);
  1439. }
  1440. const res = descend(node.childNodes[i]);
  1441. if (res.isSome()) {
  1442. return res;
  1443. }
  1444. }
  1445. return Optional.none();
  1446. };
  1447. return descend(scope.dom);
  1448. };
  1449. const ancestor$3 = (scope, selector, isRoot) => ancestor$4(scope, e => is$1(e, selector), isRoot);
  1450. const descendant = (scope, selector) => one(selector, scope);
  1451. const closest$3 = (scope, selector, isRoot) => {
  1452. const is = (element, selector) => is$1(element, selector);
  1453. return ClosestOrAncestor(is, ancestor$3, scope, selector, isRoot);
  1454. };
  1455. const closest$2 = target => closest$3(target, '[contenteditable]');
  1456. const isEditable$3 = (element, assumeEditable = false) => {
  1457. if (inBody(element)) {
  1458. return element.dom.isContentEditable;
  1459. } else {
  1460. return closest$2(element).fold(constant(assumeEditable), editable => getRaw$1(editable) === 'true');
  1461. }
  1462. };
  1463. const getRaw$1 = element => element.dom.contentEditable;
  1464. const isSupported = dom => dom.style !== undefined && isFunction(dom.style.getPropertyValue);
  1465. const internalSet = (dom, property, value) => {
  1466. if (!isString(value)) {
  1467. console.error('Invalid call to CSS.set. Property ', property, ':: Value ', value, ':: Element ', dom);
  1468. throw new Error('CSS value must be a string: ' + value);
  1469. }
  1470. if (isSupported(dom)) {
  1471. dom.style.setProperty(property, value);
  1472. }
  1473. };
  1474. const internalRemove = (dom, property) => {
  1475. if (isSupported(dom)) {
  1476. dom.style.removeProperty(property);
  1477. }
  1478. };
  1479. const set$2 = (element, property, value) => {
  1480. const dom = element.dom;
  1481. internalSet(dom, property, value);
  1482. };
  1483. const setAll = (element, css) => {
  1484. const dom = element.dom;
  1485. each$d(css, (v, k) => {
  1486. internalSet(dom, k, v);
  1487. });
  1488. };
  1489. const get$7 = (element, property) => {
  1490. const dom = element.dom;
  1491. const styles = window.getComputedStyle(dom);
  1492. const r = styles.getPropertyValue(property);
  1493. return r === '' && !inBody(element) ? getUnsafeProperty(dom, property) : r;
  1494. };
  1495. const getUnsafeProperty = (dom, property) => isSupported(dom) ? dom.style.getPropertyValue(property) : '';
  1496. const getRaw = (element, property) => {
  1497. const dom = element.dom;
  1498. const raw = getUnsafeProperty(dom, property);
  1499. return Optional.from(raw).filter(r => r.length > 0);
  1500. };
  1501. const getAllRaw = element => {
  1502. const css = {};
  1503. const dom = element.dom;
  1504. if (isSupported(dom)) {
  1505. for (let i = 0; i < dom.style.length; i++) {
  1506. const ruleName = dom.style.item(i);
  1507. css[ruleName] = dom.style[ruleName];
  1508. }
  1509. }
  1510. return css;
  1511. };
  1512. const remove$7 = (element, property) => {
  1513. const dom = element.dom;
  1514. internalRemove(dom, property);
  1515. if (is$2(getOpt(element, 'style').map(trim$3), '')) {
  1516. remove$b(element, 'style');
  1517. }
  1518. };
  1519. const reflow = e => e.dom.offsetWidth;
  1520. const before$3 = (marker, element) => {
  1521. const parent$1 = parent(marker);
  1522. parent$1.each(v => {
  1523. v.dom.insertBefore(element.dom, marker.dom);
  1524. });
  1525. };
  1526. const after$4 = (marker, element) => {
  1527. const sibling = nextSibling(marker);
  1528. sibling.fold(() => {
  1529. const parent$1 = parent(marker);
  1530. parent$1.each(v => {
  1531. append$1(v, element);
  1532. });
  1533. }, v => {
  1534. before$3(v, element);
  1535. });
  1536. };
  1537. const prepend = (parent, element) => {
  1538. const firstChild$1 = firstChild(parent);
  1539. firstChild$1.fold(() => {
  1540. append$1(parent, element);
  1541. }, v => {
  1542. parent.dom.insertBefore(element.dom, v.dom);
  1543. });
  1544. };
  1545. const append$1 = (parent, element) => {
  1546. parent.dom.appendChild(element.dom);
  1547. };
  1548. const wrap$2 = (element, wrapper) => {
  1549. before$3(element, wrapper);
  1550. append$1(wrapper, element);
  1551. };
  1552. const after$3 = (marker, elements) => {
  1553. each$e(elements, (x, i) => {
  1554. const e = i === 0 ? marker : elements[i - 1];
  1555. after$4(e, x);
  1556. });
  1557. };
  1558. const append = (parent, elements) => {
  1559. each$e(elements, x => {
  1560. append$1(parent, x);
  1561. });
  1562. };
  1563. const empty = element => {
  1564. element.dom.textContent = '';
  1565. each$e(children$1(element), rogue => {
  1566. remove$6(rogue);
  1567. });
  1568. };
  1569. const remove$6 = element => {
  1570. const dom = element.dom;
  1571. if (dom.parentNode !== null) {
  1572. dom.parentNode.removeChild(dom);
  1573. }
  1574. };
  1575. const unwrap = wrapper => {
  1576. const children = children$1(wrapper);
  1577. if (children.length > 0) {
  1578. after$3(wrapper, children);
  1579. }
  1580. remove$6(wrapper);
  1581. };
  1582. const fromHtml = (html, scope) => {
  1583. const doc = scope || document;
  1584. const div = doc.createElement('div');
  1585. div.innerHTML = html;
  1586. return children$1(SugarElement.fromDom(div));
  1587. };
  1588. const fromDom$1 = nodes => map$3(nodes, SugarElement.fromDom);
  1589. const get$6 = element => element.dom.innerHTML;
  1590. const set$1 = (element, content) => {
  1591. const owner = owner$1(element);
  1592. const docDom = owner.dom;
  1593. const fragment = SugarElement.fromDom(docDom.createDocumentFragment());
  1594. const contentElements = fromHtml(content, docDom);
  1595. append(fragment, contentElements);
  1596. empty(element);
  1597. append$1(element, fragment);
  1598. };
  1599. const getOuter = element => {
  1600. const container = SugarElement.fromTag('div');
  1601. const clone = SugarElement.fromDom(element.dom.cloneNode(true));
  1602. append$1(container, clone);
  1603. return get$6(container);
  1604. };
  1605. const mkEvent = (target, x, y, stop, prevent, kill, raw) => ({
  1606. target,
  1607. x,
  1608. y,
  1609. stop,
  1610. prevent,
  1611. kill,
  1612. raw
  1613. });
  1614. const fromRawEvent = rawEvent => {
  1615. const target = SugarElement.fromDom(getOriginalEventTarget(rawEvent).getOr(rawEvent.target));
  1616. const stop = () => rawEvent.stopPropagation();
  1617. const prevent = () => rawEvent.preventDefault();
  1618. const kill = compose(prevent, stop);
  1619. return mkEvent(target, rawEvent.clientX, rawEvent.clientY, stop, prevent, kill, rawEvent);
  1620. };
  1621. const handle$1 = (filter, handler) => rawEvent => {
  1622. if (filter(rawEvent)) {
  1623. handler(fromRawEvent(rawEvent));
  1624. }
  1625. };
  1626. const binder = (element, event, filter, handler, useCapture) => {
  1627. const wrapped = handle$1(filter, handler);
  1628. element.dom.addEventListener(event, wrapped, useCapture);
  1629. return { unbind: curry(unbind, element, event, wrapped, useCapture) };
  1630. };
  1631. const bind$2 = (element, event, filter, handler) => binder(element, event, filter, handler, false);
  1632. const unbind = (element, event, handler, useCapture) => {
  1633. element.dom.removeEventListener(event, handler, useCapture);
  1634. };
  1635. const r = (left, top) => {
  1636. const translate = (x, y) => r(left + x, top + y);
  1637. return {
  1638. left,
  1639. top,
  1640. translate
  1641. };
  1642. };
  1643. const SugarPosition = r;
  1644. const boxPosition = dom => {
  1645. const box = dom.getBoundingClientRect();
  1646. return SugarPosition(box.left, box.top);
  1647. };
  1648. const firstDefinedOrZero = (a, b) => {
  1649. if (a !== undefined) {
  1650. return a;
  1651. } else {
  1652. return b !== undefined ? b : 0;
  1653. }
  1654. };
  1655. const absolute = element => {
  1656. const doc = element.dom.ownerDocument;
  1657. const body = doc.body;
  1658. const win = doc.defaultView;
  1659. const html = doc.documentElement;
  1660. if (body === element.dom) {
  1661. return SugarPosition(body.offsetLeft, body.offsetTop);
  1662. }
  1663. const scrollTop = firstDefinedOrZero(win === null || win === void 0 ? void 0 : win.pageYOffset, html.scrollTop);
  1664. const scrollLeft = firstDefinedOrZero(win === null || win === void 0 ? void 0 : win.pageXOffset, html.scrollLeft);
  1665. const clientTop = firstDefinedOrZero(html.clientTop, body.clientTop);
  1666. const clientLeft = firstDefinedOrZero(html.clientLeft, body.clientLeft);
  1667. return viewport(element).translate(scrollLeft - clientLeft, scrollTop - clientTop);
  1668. };
  1669. const viewport = element => {
  1670. const dom = element.dom;
  1671. const doc = dom.ownerDocument;
  1672. const body = doc.body;
  1673. if (body === dom) {
  1674. return SugarPosition(body.offsetLeft, body.offsetTop);
  1675. }
  1676. if (!inBody(element)) {
  1677. return SugarPosition(0, 0);
  1678. }
  1679. return boxPosition(dom);
  1680. };
  1681. const get$5 = _DOC => {
  1682. const doc = _DOC !== undefined ? _DOC.dom : document;
  1683. const x = doc.body.scrollLeft || doc.documentElement.scrollLeft;
  1684. const y = doc.body.scrollTop || doc.documentElement.scrollTop;
  1685. return SugarPosition(x, y);
  1686. };
  1687. const intoView = (element, alignToTop) => {
  1688. const isSafari = detect$2().browser.isSafari();
  1689. if (isSafari && isFunction(element.dom.scrollIntoViewIfNeeded)) {
  1690. element.dom.scrollIntoViewIfNeeded(false);
  1691. } else {
  1692. element.dom.scrollIntoView(alignToTop);
  1693. }
  1694. };
  1695. const get$4 = _win => {
  1696. const win = _win === undefined ? window : _win;
  1697. if (detect$2().browser.isFirefox()) {
  1698. return Optional.none();
  1699. } else {
  1700. return Optional.from(win.visualViewport);
  1701. }
  1702. };
  1703. const bounds = (x, y, width, height) => ({
  1704. x,
  1705. y,
  1706. width,
  1707. height,
  1708. right: x + width,
  1709. bottom: y + height
  1710. });
  1711. const getBounds = _win => {
  1712. const win = _win === undefined ? window : _win;
  1713. const doc = win.document;
  1714. const scroll = get$5(SugarElement.fromDom(doc));
  1715. return get$4(win).fold(() => {
  1716. const html = win.document.documentElement;
  1717. const width = html.clientWidth;
  1718. const height = html.clientHeight;
  1719. return bounds(scroll.left, scroll.top, width, height);
  1720. }, visualViewport => bounds(Math.max(visualViewport.pageLeft, scroll.left), Math.max(visualViewport.pageTop, scroll.top), visualViewport.width, visualViewport.height));
  1721. };
  1722. const children = (scope, predicate) => filter$5(children$1(scope), predicate);
  1723. const descendants$1 = (scope, predicate) => {
  1724. let result = [];
  1725. each$e(children$1(scope), x => {
  1726. if (predicate(x)) {
  1727. result = result.concat([x]);
  1728. }
  1729. result = result.concat(descendants$1(x, predicate));
  1730. });
  1731. return result;
  1732. };
  1733. const descendants = (scope, selector) => all(selector, scope);
  1734. const ancestor$2 = (scope, selector, isRoot) => ancestor$3(scope, selector, isRoot).isSome();
  1735. class DomTreeWalker {
  1736. constructor(startNode, rootNode) {
  1737. this.node = startNode;
  1738. this.rootNode = rootNode;
  1739. this.current = this.current.bind(this);
  1740. this.next = this.next.bind(this);
  1741. this.prev = this.prev.bind(this);
  1742. this.prev2 = this.prev2.bind(this);
  1743. }
  1744. current() {
  1745. return this.node;
  1746. }
  1747. next(shallow) {
  1748. this.node = this.findSibling(this.node, 'firstChild', 'nextSibling', shallow);
  1749. return this.node;
  1750. }
  1751. prev(shallow) {
  1752. this.node = this.findSibling(this.node, 'lastChild', 'previousSibling', shallow);
  1753. return this.node;
  1754. }
  1755. prev2(shallow) {
  1756. this.node = this.findPreviousNode(this.node, shallow);
  1757. return this.node;
  1758. }
  1759. findSibling(node, startName, siblingName, shallow) {
  1760. if (node) {
  1761. if (!shallow && node[startName]) {
  1762. return node[startName];
  1763. }
  1764. if (node !== this.rootNode) {
  1765. let sibling = node[siblingName];
  1766. if (sibling) {
  1767. return sibling;
  1768. }
  1769. for (let parent = node.parentNode; parent && parent !== this.rootNode; parent = parent.parentNode) {
  1770. sibling = parent[siblingName];
  1771. if (sibling) {
  1772. return sibling;
  1773. }
  1774. }
  1775. }
  1776. }
  1777. return undefined;
  1778. }
  1779. findPreviousNode(node, shallow) {
  1780. if (node) {
  1781. const sibling = node.previousSibling;
  1782. if (this.rootNode && sibling === this.rootNode) {
  1783. return;
  1784. }
  1785. if (sibling) {
  1786. if (!shallow) {
  1787. for (let child = sibling.lastChild; child; child = child.lastChild) {
  1788. if (!child.lastChild) {
  1789. return child;
  1790. }
  1791. }
  1792. }
  1793. return sibling;
  1794. }
  1795. const parent = node.parentNode;
  1796. if (parent && parent !== this.rootNode) {
  1797. return parent;
  1798. }
  1799. }
  1800. return undefined;
  1801. }
  1802. }
  1803. const isNodeType = type => {
  1804. return node => {
  1805. return !!node && node.nodeType === type;
  1806. };
  1807. };
  1808. const isRestrictedNode = node => !!node && !Object.getPrototypeOf(node);
  1809. const isElement$6 = isNodeType(1);
  1810. const matchNodeName = name => {
  1811. const lowerCasedName = name.toLowerCase();
  1812. return node => isNonNullable(node) && node.nodeName.toLowerCase() === lowerCasedName;
  1813. };
  1814. const matchNodeNames = names => {
  1815. const lowerCasedNames = names.map(s => s.toLowerCase());
  1816. return node => {
  1817. if (node && node.nodeName) {
  1818. const nodeName = node.nodeName.toLowerCase();
  1819. return contains$2(lowerCasedNames, nodeName);
  1820. }
  1821. return false;
  1822. };
  1823. };
  1824. const matchStyleValues = (name, values) => {
  1825. const items = values.toLowerCase().split(' ');
  1826. return node => {
  1827. if (isElement$6(node)) {
  1828. const win = node.ownerDocument.defaultView;
  1829. if (win) {
  1830. for (let i = 0; i < items.length; i++) {
  1831. const computed = win.getComputedStyle(node, null);
  1832. const cssValue = computed ? computed.getPropertyValue(name) : null;
  1833. if (cssValue === items[i]) {
  1834. return true;
  1835. }
  1836. }
  1837. }
  1838. }
  1839. return false;
  1840. };
  1841. };
  1842. const hasAttribute = attrName => {
  1843. return node => {
  1844. return isElement$6(node) && node.hasAttribute(attrName);
  1845. };
  1846. };
  1847. const hasAttributeValue = (attrName, attrValue) => {
  1848. return node => {
  1849. return isElement$6(node) && node.getAttribute(attrName) === attrValue;
  1850. };
  1851. };
  1852. const isBogus$2 = node => isElement$6(node) && node.hasAttribute('data-mce-bogus');
  1853. const isBogusAll$1 = node => isElement$6(node) && node.getAttribute('data-mce-bogus') === 'all';
  1854. const isTable$2 = node => isElement$6(node) && node.tagName === 'TABLE';
  1855. const hasContentEditableState = value => {
  1856. return node => {
  1857. if (isElement$6(node)) {
  1858. if (node.contentEditable === value) {
  1859. return true;
  1860. }
  1861. if (node.getAttribute('data-mce-contenteditable') === value) {
  1862. return true;
  1863. }
  1864. }
  1865. return false;
  1866. };
  1867. };
  1868. const isTextareaOrInput = matchNodeNames([
  1869. 'textarea',
  1870. 'input'
  1871. ]);
  1872. const isText$a = isNodeType(3);
  1873. const isCData = isNodeType(4);
  1874. const isPi = isNodeType(7);
  1875. const isComment = isNodeType(8);
  1876. const isDocument$1 = isNodeType(9);
  1877. const isDocumentFragment = isNodeType(11);
  1878. const isBr$6 = matchNodeName('br');
  1879. const isImg = matchNodeName('img');
  1880. const isContentEditableTrue$3 = hasContentEditableState('true');
  1881. const isContentEditableFalse$b = hasContentEditableState('false');
  1882. const isTableCell$3 = matchNodeNames([
  1883. 'td',
  1884. 'th'
  1885. ]);
  1886. const isTableCellOrCaption = matchNodeNames([
  1887. 'td',
  1888. 'th',
  1889. 'caption'
  1890. ]);
  1891. const isMedia$2 = matchNodeNames([
  1892. 'video',
  1893. 'audio',
  1894. 'object',
  1895. 'embed'
  1896. ]);
  1897. const isListItem$2 = matchNodeName('li');
  1898. const zeroWidth = '\uFEFF';
  1899. const nbsp = '\xA0';
  1900. const isZwsp$1 = char => char === zeroWidth;
  1901. const removeZwsp = s => s.replace(/\uFEFF/g, '');
  1902. const NodeValue = (is, name) => {
  1903. const get = element => {
  1904. if (!is(element)) {
  1905. throw new Error('Can only get ' + name + ' value of a ' + name + ' node');
  1906. }
  1907. return getOption(element).getOr('');
  1908. };
  1909. const getOption = element => is(element) ? Optional.from(element.dom.nodeValue) : Optional.none();
  1910. const set = (element, value) => {
  1911. if (!is(element)) {
  1912. throw new Error('Can only set raw ' + name + ' value of a ' + name + ' node');
  1913. }
  1914. element.dom.nodeValue = value;
  1915. };
  1916. return {
  1917. get,
  1918. getOption,
  1919. set
  1920. };
  1921. };
  1922. const api$1 = NodeValue(isText$b, 'text');
  1923. const get$3 = element => api$1.get(element);
  1924. const getOption = element => api$1.getOption(element);
  1925. const set = (element, value) => api$1.set(element, value);
  1926. const blocks = [
  1927. 'article',
  1928. 'aside',
  1929. 'details',
  1930. 'div',
  1931. 'dt',
  1932. 'figcaption',
  1933. 'footer',
  1934. 'form',
  1935. 'fieldset',
  1936. 'header',
  1937. 'hgroup',
  1938. 'html',
  1939. 'main',
  1940. 'nav',
  1941. 'section',
  1942. 'summary',
  1943. 'body',
  1944. 'p',
  1945. 'dl',
  1946. 'multicol',
  1947. 'dd',
  1948. 'figure',
  1949. 'address',
  1950. 'center',
  1951. 'blockquote',
  1952. 'h1',
  1953. 'h2',
  1954. 'h3',
  1955. 'h4',
  1956. 'h5',
  1957. 'h6',
  1958. 'listing',
  1959. 'xmp',
  1960. 'pre',
  1961. 'plaintext',
  1962. 'menu',
  1963. 'dir',
  1964. 'ul',
  1965. 'ol',
  1966. 'li',
  1967. 'hr',
  1968. 'table',
  1969. 'tbody',
  1970. 'thead',
  1971. 'tfoot',
  1972. 'th',
  1973. 'tr',
  1974. 'td',
  1975. 'caption'
  1976. ];
  1977. const tableCells = [
  1978. 'td',
  1979. 'th'
  1980. ];
  1981. const tableSections = [
  1982. 'thead',
  1983. 'tbody',
  1984. 'tfoot'
  1985. ];
  1986. const textBlocks = [
  1987. 'h1',
  1988. 'h2',
  1989. 'h3',
  1990. 'h4',
  1991. 'h5',
  1992. 'h6',
  1993. 'p',
  1994. 'div',
  1995. 'address',
  1996. 'pre',
  1997. 'form',
  1998. 'blockquote',
  1999. 'center',
  2000. 'dir',
  2001. 'fieldset',
  2002. 'header',
  2003. 'footer',
  2004. 'article',
  2005. 'section',
  2006. 'hgroup',
  2007. 'aside',
  2008. 'nav',
  2009. 'figure'
  2010. ];
  2011. const headings = [
  2012. 'h1',
  2013. 'h2',
  2014. 'h3',
  2015. 'h4',
  2016. 'h5',
  2017. 'h6'
  2018. ];
  2019. const listItems$1 = [
  2020. 'li',
  2021. 'dd',
  2022. 'dt'
  2023. ];
  2024. const lists = [
  2025. 'ul',
  2026. 'ol',
  2027. 'dl'
  2028. ];
  2029. const wsElements = [
  2030. 'pre',
  2031. 'script',
  2032. 'textarea',
  2033. 'style'
  2034. ];
  2035. const wrapBlockElements = ['pre'].concat(headings);
  2036. const lazyLookup = items => {
  2037. let lookup;
  2038. return node => {
  2039. lookup = lookup ? lookup : mapToObject(items, always);
  2040. return has$2(lookup, name(node));
  2041. };
  2042. };
  2043. const isBlock$2 = lazyLookup(blocks);
  2044. const isTable$1 = node => name(node) === 'table';
  2045. const isInline$1 = node => isElement$7(node) && !isBlock$2(node);
  2046. const isBr$5 = node => isElement$7(node) && name(node) === 'br';
  2047. const isTextBlock$2 = lazyLookup(textBlocks);
  2048. const isList = lazyLookup(lists);
  2049. const isListItem$1 = lazyLookup(listItems$1);
  2050. const isTableSection = lazyLookup(tableSections);
  2051. const isTableCell$2 = lazyLookup(tableCells);
  2052. const isWsPreserveElement = lazyLookup(wsElements);
  2053. const isWrapBlockElement = lazyLookup(wrapBlockElements);
  2054. const isWrapElement = node => isWrapBlockElement(node) || isInline$1(node);
  2055. const getLastChildren$1 = elm => {
  2056. const children = [];
  2057. let rawNode = elm.dom;
  2058. while (rawNode) {
  2059. children.push(SugarElement.fromDom(rawNode));
  2060. rawNode = rawNode.lastChild;
  2061. }
  2062. return children;
  2063. };
  2064. const removeTrailingBr = elm => {
  2065. const allBrs = descendants(elm, 'br');
  2066. const brs = filter$5(getLastChildren$1(elm).slice(-1), isBr$5);
  2067. if (allBrs.length === brs.length) {
  2068. each$e(brs, remove$6);
  2069. }
  2070. };
  2071. const createPaddingBr = () => {
  2072. const br = SugarElement.fromTag('br');
  2073. set$3(br, 'data-mce-bogus', '1');
  2074. return br;
  2075. };
  2076. const fillWithPaddingBr = elm => {
  2077. empty(elm);
  2078. append$1(elm, createPaddingBr());
  2079. };
  2080. const trimBlockTrailingBr = elm => {
  2081. lastChild(elm).each(lastChild => {
  2082. prevSibling(lastChild).each(lastChildPrevSibling => {
  2083. if (isBlock$2(elm) && isBr$5(lastChild) && isBlock$2(lastChildPrevSibling)) {
  2084. remove$6(lastChild);
  2085. }
  2086. });
  2087. });
  2088. };
  2089. const ZWSP$1 = zeroWidth;
  2090. const isZwsp = isZwsp$1;
  2091. const trim$1 = removeZwsp;
  2092. const isElement$5 = isElement$6;
  2093. const isText$9 = isText$a;
  2094. const isCaretContainerBlock$1 = node => {
  2095. if (isText$9(node)) {
  2096. node = node.parentNode;
  2097. }
  2098. return isElement$5(node) && node.hasAttribute('data-mce-caret');
  2099. };
  2100. const isCaretContainerInline = node => isText$9(node) && isZwsp(node.data);
  2101. const isCaretContainer$2 = node => isCaretContainerBlock$1(node) || isCaretContainerInline(node);
  2102. const hasContent = node => node.firstChild !== node.lastChild || !isBr$6(node.firstChild);
  2103. const insertInline$1 = (node, before) => {
  2104. var _a;
  2105. const doc = (_a = node.ownerDocument) !== null && _a !== void 0 ? _a : document;
  2106. const textNode = doc.createTextNode(ZWSP$1);
  2107. const parentNode = node.parentNode;
  2108. if (!before) {
  2109. const sibling = node.nextSibling;
  2110. if (isText$9(sibling)) {
  2111. if (isCaretContainer$2(sibling)) {
  2112. return sibling;
  2113. }
  2114. if (startsWithCaretContainer$1(sibling)) {
  2115. sibling.splitText(1);
  2116. return sibling;
  2117. }
  2118. }
  2119. if (node.nextSibling) {
  2120. parentNode === null || parentNode === void 0 ? void 0 : parentNode.insertBefore(textNode, node.nextSibling);
  2121. } else {
  2122. parentNode === null || parentNode === void 0 ? void 0 : parentNode.appendChild(textNode);
  2123. }
  2124. } else {
  2125. const sibling = node.previousSibling;
  2126. if (isText$9(sibling)) {
  2127. if (isCaretContainer$2(sibling)) {
  2128. return sibling;
  2129. }
  2130. if (endsWithCaretContainer$1(sibling)) {
  2131. return sibling.splitText(sibling.data.length - 1);
  2132. }
  2133. }
  2134. parentNode === null || parentNode === void 0 ? void 0 : parentNode.insertBefore(textNode, node);
  2135. }
  2136. return textNode;
  2137. };
  2138. const isBeforeInline = pos => {
  2139. const container = pos.container();
  2140. if (!isText$a(container)) {
  2141. return false;
  2142. }
  2143. return container.data.charAt(pos.offset()) === ZWSP$1 || pos.isAtStart() && isCaretContainerInline(container.previousSibling);
  2144. };
  2145. const isAfterInline = pos => {
  2146. const container = pos.container();
  2147. if (!isText$a(container)) {
  2148. return false;
  2149. }
  2150. return container.data.charAt(pos.offset() - 1) === ZWSP$1 || pos.isAtEnd() && isCaretContainerInline(container.nextSibling);
  2151. };
  2152. const insertBlock = (blockName, node, before) => {
  2153. var _a;
  2154. const doc = (_a = node.ownerDocument) !== null && _a !== void 0 ? _a : document;
  2155. const blockNode = doc.createElement(blockName);
  2156. blockNode.setAttribute('data-mce-caret', before ? 'before' : 'after');
  2157. blockNode.setAttribute('data-mce-bogus', 'all');
  2158. blockNode.appendChild(createPaddingBr().dom);
  2159. const parentNode = node.parentNode;
  2160. if (!before) {
  2161. if (node.nextSibling) {
  2162. parentNode === null || parentNode === void 0 ? void 0 : parentNode.insertBefore(blockNode, node.nextSibling);
  2163. } else {
  2164. parentNode === null || parentNode === void 0 ? void 0 : parentNode.appendChild(blockNode);
  2165. }
  2166. } else {
  2167. parentNode === null || parentNode === void 0 ? void 0 : parentNode.insertBefore(blockNode, node);
  2168. }
  2169. return blockNode;
  2170. };
  2171. const startsWithCaretContainer$1 = node => isText$9(node) && node.data[0] === ZWSP$1;
  2172. const endsWithCaretContainer$1 = node => isText$9(node) && node.data[node.data.length - 1] === ZWSP$1;
  2173. const trimBogusBr = elm => {
  2174. var _a;
  2175. const brs = elm.getElementsByTagName('br');
  2176. const lastBr = brs[brs.length - 1];
  2177. if (isBogus$2(lastBr)) {
  2178. (_a = lastBr.parentNode) === null || _a === void 0 ? void 0 : _a.removeChild(lastBr);
  2179. }
  2180. };
  2181. const showCaretContainerBlock = caretContainer => {
  2182. if (caretContainer && caretContainer.hasAttribute('data-mce-caret')) {
  2183. trimBogusBr(caretContainer);
  2184. caretContainer.removeAttribute('data-mce-caret');
  2185. caretContainer.removeAttribute('data-mce-bogus');
  2186. caretContainer.removeAttribute('style');
  2187. caretContainer.removeAttribute('data-mce-style');
  2188. caretContainer.removeAttribute('_moz_abspos');
  2189. return caretContainer;
  2190. }
  2191. return null;
  2192. };
  2193. const isRangeInCaretContainerBlock = range => isCaretContainerBlock$1(range.startContainer);
  2194. const isContentEditableTrue$2 = isContentEditableTrue$3;
  2195. const isContentEditableFalse$a = isContentEditableFalse$b;
  2196. const isBr$4 = isBr$6;
  2197. const isText$8 = isText$a;
  2198. const isInvalidTextElement = matchNodeNames([
  2199. 'script',
  2200. 'style',
  2201. 'textarea'
  2202. ]);
  2203. const isAtomicInline = matchNodeNames([
  2204. 'img',
  2205. 'input',
  2206. 'textarea',
  2207. 'hr',
  2208. 'iframe',
  2209. 'video',
  2210. 'audio',
  2211. 'object',
  2212. 'embed'
  2213. ]);
  2214. const isTable = matchNodeNames(['table']);
  2215. const isCaretContainer$1 = isCaretContainer$2;
  2216. const isCaretCandidate$3 = node => {
  2217. if (isCaretContainer$1(node)) {
  2218. return false;
  2219. }
  2220. if (isText$8(node)) {
  2221. return !isInvalidTextElement(node.parentNode);
  2222. }
  2223. return isAtomicInline(node) || isBr$4(node) || isTable(node) || isNonUiContentEditableFalse(node);
  2224. };
  2225. const isUnselectable = node => isElement$6(node) && node.getAttribute('unselectable') === 'true';
  2226. const isNonUiContentEditableFalse = node => !isUnselectable(node) && isContentEditableFalse$a(node);
  2227. const isInEditable = (node, root) => {
  2228. for (let tempNode = node.parentNode; tempNode && tempNode !== root; tempNode = tempNode.parentNode) {
  2229. if (isNonUiContentEditableFalse(tempNode)) {
  2230. return false;
  2231. }
  2232. if (isContentEditableTrue$2(tempNode)) {
  2233. return true;
  2234. }
  2235. }
  2236. return true;
  2237. };
  2238. const isAtomicContentEditableFalse = node => {
  2239. if (!isNonUiContentEditableFalse(node)) {
  2240. return false;
  2241. }
  2242. return !foldl(from(node.getElementsByTagName('*')), (result, elm) => {
  2243. return result || isContentEditableTrue$2(elm);
  2244. }, false);
  2245. };
  2246. const isAtomic$1 = node => isAtomicInline(node) || isAtomicContentEditableFalse(node);
  2247. const isEditableCaretCandidate$1 = (node, root) => isCaretCandidate$3(node) && isInEditable(node, root);
  2248. const whiteSpaceRegExp = /^[ \t\r\n]*$/;
  2249. const isWhitespaceText = text => whiteSpaceRegExp.test(text);
  2250. const isCollapsibleWhitespace$1 = c => ' \f\t\x0B'.indexOf(c) !== -1;
  2251. const isNewLineChar = c => c === '\n' || c === '\r';
  2252. const isNewline = (text, idx) => idx < text.length && idx >= 0 ? isNewLineChar(text[idx]) : false;
  2253. const normalize$4 = (text, tabSpaces = 4, isStartOfContent = true, isEndOfContent = true) => {
  2254. const tabSpace = repeat(' ', tabSpaces);
  2255. const normalizedText = text.replace(/\t/g, tabSpace);
  2256. const result = foldl(normalizedText, (acc, c) => {
  2257. if (isCollapsibleWhitespace$1(c) || c === nbsp) {
  2258. if (acc.pcIsSpace || acc.str === '' && isStartOfContent || acc.str.length === normalizedText.length - 1 && isEndOfContent || isNewline(normalizedText, acc.str.length + 1)) {
  2259. return {
  2260. pcIsSpace: false,
  2261. str: acc.str + nbsp
  2262. };
  2263. } else {
  2264. return {
  2265. pcIsSpace: true,
  2266. str: acc.str + ' '
  2267. };
  2268. }
  2269. } else {
  2270. return {
  2271. pcIsSpace: isNewLineChar(c),
  2272. str: acc.str + c
  2273. };
  2274. }
  2275. }, {
  2276. pcIsSpace: false,
  2277. str: ''
  2278. });
  2279. return result.str;
  2280. };
  2281. const hasWhitespacePreserveParent = (node, rootNode) => {
  2282. const rootElement = SugarElement.fromDom(rootNode);
  2283. const startNode = SugarElement.fromDom(node);
  2284. return ancestor$2(startNode, 'pre,code', curry(eq, rootElement));
  2285. };
  2286. const isWhitespace$1 = (node, rootNode) => {
  2287. return isText$a(node) && isWhitespaceText(node.data) && !hasWhitespacePreserveParent(node, rootNode);
  2288. };
  2289. const isNamedAnchor = node => {
  2290. return isElement$6(node) && node.nodeName === 'A' && !node.hasAttribute('href') && (node.hasAttribute('name') || node.hasAttribute('id'));
  2291. };
  2292. const isContent$1 = (node, rootNode) => {
  2293. return isCaretCandidate$3(node) && !isWhitespace$1(node, rootNode) || isNamedAnchor(node) || isBookmark(node);
  2294. };
  2295. const isBookmark = hasAttribute('data-mce-bookmark');
  2296. const isBogus$1 = hasAttribute('data-mce-bogus');
  2297. const isBogusAll = hasAttributeValue('data-mce-bogus', 'all');
  2298. const isEmptyNode = (targetNode, skipBogus) => {
  2299. let brCount = 0;
  2300. if (isContent$1(targetNode, targetNode)) {
  2301. return false;
  2302. } else {
  2303. let node = targetNode.firstChild;
  2304. if (!node) {
  2305. return true;
  2306. }
  2307. const walker = new DomTreeWalker(node, targetNode);
  2308. do {
  2309. if (skipBogus) {
  2310. if (isBogusAll(node)) {
  2311. node = walker.next(true);
  2312. continue;
  2313. }
  2314. if (isBogus$1(node)) {
  2315. node = walker.next();
  2316. continue;
  2317. }
  2318. }
  2319. if (isBr$6(node)) {
  2320. brCount++;
  2321. node = walker.next();
  2322. continue;
  2323. }
  2324. if (isContent$1(node, targetNode)) {
  2325. return false;
  2326. }
  2327. node = walker.next();
  2328. } while (node);
  2329. return brCount <= 1;
  2330. }
  2331. };
  2332. const isEmpty$2 = (elm, skipBogus = true) => isEmptyNode(elm.dom, skipBogus);
  2333. const transparentBlockAttr = 'data-mce-block';
  2334. const elementNames = map => filter$5(keys(map), key => !/[A-Z]/.test(key));
  2335. const makeSelectorFromSchemaMap = map => elementNames(map).join(',');
  2336. const updateTransparent = (blocksSelector, transparent) => {
  2337. if (isNonNullable(transparent.querySelector(blocksSelector))) {
  2338. transparent.setAttribute(transparentBlockAttr, 'true');
  2339. if (transparent.getAttribute('data-mce-selected') === 'inline-boundary') {
  2340. transparent.removeAttribute('data-mce-selected');
  2341. }
  2342. return true;
  2343. } else {
  2344. transparent.removeAttribute(transparentBlockAttr);
  2345. return false;
  2346. }
  2347. };
  2348. const updateBlockStateOnChildren = (schema, scope) => {
  2349. const transparentSelector = makeSelectorFromSchemaMap(schema.getTransparentElements());
  2350. const blocksSelector = makeSelectorFromSchemaMap(schema.getBlockElements());
  2351. return filter$5(scope.querySelectorAll(transparentSelector), transparent => updateTransparent(blocksSelector, transparent));
  2352. };
  2353. const trimEdge = (el, leftSide) => {
  2354. var _a;
  2355. const childPropertyName = leftSide ? 'lastChild' : 'firstChild';
  2356. for (let child = el[childPropertyName]; child; child = child[childPropertyName]) {
  2357. if (isEmpty$2(SugarElement.fromDom(child))) {
  2358. (_a = child.parentNode) === null || _a === void 0 ? void 0 : _a.removeChild(child);
  2359. return;
  2360. }
  2361. }
  2362. };
  2363. const split$2 = (parentElm, splitElm) => {
  2364. const range = document.createRange();
  2365. const parentNode = parentElm.parentNode;
  2366. if (parentNode) {
  2367. range.setStartBefore(parentElm);
  2368. range.setEndBefore(splitElm);
  2369. const beforeFragment = range.extractContents();
  2370. trimEdge(beforeFragment, true);
  2371. range.setStartAfter(splitElm);
  2372. range.setEndAfter(parentElm);
  2373. const afterFragment = range.extractContents();
  2374. trimEdge(afterFragment, false);
  2375. if (!isEmpty$2(SugarElement.fromDom(beforeFragment))) {
  2376. parentNode.insertBefore(beforeFragment, parentElm);
  2377. }
  2378. if (!isEmpty$2(SugarElement.fromDom(splitElm))) {
  2379. parentNode.insertBefore(splitElm, parentElm);
  2380. }
  2381. if (!isEmpty$2(SugarElement.fromDom(afterFragment))) {
  2382. parentNode.insertBefore(afterFragment, parentElm);
  2383. }
  2384. parentNode.removeChild(parentElm);
  2385. }
  2386. };
  2387. const splitInvalidChildren = (schema, scope, transparentBlocks) => {
  2388. const blocksElements = schema.getBlockElements();
  2389. const rootNode = SugarElement.fromDom(scope);
  2390. const isBlock = el => name(el) in blocksElements;
  2391. const isRoot = el => eq(el, rootNode);
  2392. each$e(fromDom$1(transparentBlocks), transparentBlock => {
  2393. ancestor$4(transparentBlock, isBlock, isRoot).each(parentBlock => {
  2394. const invalidChildren = children(transparentBlock, el => isBlock(el) && !schema.isValidChild(name(parentBlock), name(el)));
  2395. if (invalidChildren.length > 0) {
  2396. const stateScope = parentElement(parentBlock);
  2397. each$e(invalidChildren, child => {
  2398. ancestor$4(child, isBlock, isRoot).each(parentBlock => {
  2399. split$2(parentBlock.dom, child.dom);
  2400. });
  2401. });
  2402. stateScope.each(scope => updateBlockStateOnChildren(schema, scope.dom));
  2403. }
  2404. });
  2405. });
  2406. };
  2407. const unwrapInvalidChildren = (schema, scope, transparentBlocks) => {
  2408. each$e([
  2409. ...transparentBlocks,
  2410. ...isTransparentBlock(schema, scope) ? [scope] : []
  2411. ], block => each$e(descendants(SugarElement.fromDom(block), block.nodeName.toLowerCase()), elm => {
  2412. if (isTransparentInline(schema, elm.dom)) {
  2413. unwrap(elm);
  2414. }
  2415. }));
  2416. };
  2417. const updateChildren = (schema, scope) => {
  2418. const transparentBlocks = updateBlockStateOnChildren(schema, scope);
  2419. splitInvalidChildren(schema, scope, transparentBlocks);
  2420. unwrapInvalidChildren(schema, scope, transparentBlocks);
  2421. };
  2422. const updateElement = (schema, target) => {
  2423. if (isTransparentElement(schema, target)) {
  2424. const blocksSelector = makeSelectorFromSchemaMap(schema.getBlockElements());
  2425. updateTransparent(blocksSelector, target);
  2426. }
  2427. };
  2428. const updateCaret = (schema, root, caretParent) => {
  2429. const isRoot = el => eq(el, SugarElement.fromDom(root));
  2430. const parents = parents$1(SugarElement.fromDom(caretParent), isRoot);
  2431. get$b(parents, parents.length - 2).filter(isElement$7).fold(() => updateChildren(schema, root), scope => updateChildren(schema, scope.dom));
  2432. };
  2433. const hasBlockAttr = el => el.hasAttribute(transparentBlockAttr);
  2434. const isTransparentElementName = (schema, name) => has$2(schema.getTransparentElements(), name);
  2435. const isTransparentElement = (schema, node) => isElement$6(node) && isTransparentElementName(schema, node.nodeName);
  2436. const isTransparentBlock = (schema, node) => isTransparentElement(schema, node) && hasBlockAttr(node);
  2437. const isTransparentInline = (schema, node) => isTransparentElement(schema, node) && !hasBlockAttr(node);
  2438. const isTransparentAstBlock = (schema, node) => node.type === 1 && isTransparentElementName(schema, node.name) && isString(node.attr(transparentBlockAttr));
  2439. const isTransparentAstInline = (schema, node) => node.type === 1 && isTransparentElementName(schema, node.name) && isUndefined(node.attr(transparentBlockAttr));
  2440. const browser = detect$2().browser;
  2441. const firstElement = nodes => find$2(nodes, isElement$7);
  2442. const getTableCaptionDeltaY = elm => {
  2443. if (browser.isFirefox() && name(elm) === 'table') {
  2444. return firstElement(children$1(elm)).filter(elm => {
  2445. return name(elm) === 'caption';
  2446. }).bind(caption => {
  2447. return firstElement(nextSiblings(caption)).map(body => {
  2448. const bodyTop = body.dom.offsetTop;
  2449. const captionTop = caption.dom.offsetTop;
  2450. const captionHeight = caption.dom.offsetHeight;
  2451. return bodyTop <= captionTop ? -captionHeight : 0;
  2452. });
  2453. }).getOr(0);
  2454. } else {
  2455. return 0;
  2456. }
  2457. };
  2458. const hasChild = (elm, child) => elm.children && contains$2(elm.children, child);
  2459. const getPos = (body, elm, rootElm) => {
  2460. let x = 0, y = 0;
  2461. const doc = body.ownerDocument;
  2462. rootElm = rootElm ? rootElm : body;
  2463. if (elm) {
  2464. if (rootElm === body && elm.getBoundingClientRect && get$7(SugarElement.fromDom(body), 'position') === 'static') {
  2465. const pos = elm.getBoundingClientRect();
  2466. x = pos.left + (doc.documentElement.scrollLeft || body.scrollLeft) - doc.documentElement.clientLeft;
  2467. y = pos.top + (doc.documentElement.scrollTop || body.scrollTop) - doc.documentElement.clientTop;
  2468. return {
  2469. x,
  2470. y
  2471. };
  2472. }
  2473. let offsetParent = elm;
  2474. while (offsetParent && offsetParent !== rootElm && offsetParent.nodeType && !hasChild(offsetParent, rootElm)) {
  2475. const castOffsetParent = offsetParent;
  2476. x += castOffsetParent.offsetLeft || 0;
  2477. y += castOffsetParent.offsetTop || 0;
  2478. offsetParent = castOffsetParent.offsetParent;
  2479. }
  2480. offsetParent = elm.parentNode;
  2481. while (offsetParent && offsetParent !== rootElm && offsetParent.nodeType && !hasChild(offsetParent, rootElm)) {
  2482. x -= offsetParent.scrollLeft || 0;
  2483. y -= offsetParent.scrollTop || 0;
  2484. offsetParent = offsetParent.parentNode;
  2485. }
  2486. y += getTableCaptionDeltaY(SugarElement.fromDom(elm));
  2487. }
  2488. return {
  2489. x,
  2490. y
  2491. };
  2492. };
  2493. const StyleSheetLoader = (documentOrShadowRoot, settings = {}) => {
  2494. let idCount = 0;
  2495. const loadedStates = {};
  2496. const edos = SugarElement.fromDom(documentOrShadowRoot);
  2497. const doc = documentOrOwner(edos);
  2498. const _setReferrerPolicy = referrerPolicy => {
  2499. settings.referrerPolicy = referrerPolicy;
  2500. };
  2501. const _setContentCssCors = contentCssCors => {
  2502. settings.contentCssCors = contentCssCors;
  2503. };
  2504. const addStyle = element => {
  2505. append$1(getStyleContainer(edos), element);
  2506. };
  2507. const removeStyle = id => {
  2508. const styleContainer = getStyleContainer(edos);
  2509. descendant(styleContainer, '#' + id).each(remove$6);
  2510. };
  2511. const getOrCreateState = url => get$a(loadedStates, url).getOrThunk(() => ({
  2512. id: 'mce-u' + idCount++,
  2513. passed: [],
  2514. failed: [],
  2515. count: 0
  2516. }));
  2517. const load = url => new Promise((success, failure) => {
  2518. let link;
  2519. const urlWithSuffix = Tools._addCacheSuffix(url);
  2520. const state = getOrCreateState(urlWithSuffix);
  2521. loadedStates[urlWithSuffix] = state;
  2522. state.count++;
  2523. const resolve = (callbacks, status) => {
  2524. each$e(callbacks, call);
  2525. state.status = status;
  2526. state.passed = [];
  2527. state.failed = [];
  2528. if (link) {
  2529. link.onload = null;
  2530. link.onerror = null;
  2531. link = null;
  2532. }
  2533. };
  2534. const passed = () => resolve(state.passed, 2);
  2535. const failed = () => resolve(state.failed, 3);
  2536. if (success) {
  2537. state.passed.push(success);
  2538. }
  2539. if (failure) {
  2540. state.failed.push(failure);
  2541. }
  2542. if (state.status === 1) {
  2543. return;
  2544. }
  2545. if (state.status === 2) {
  2546. passed();
  2547. return;
  2548. }
  2549. if (state.status === 3) {
  2550. failed();
  2551. return;
  2552. }
  2553. state.status = 1;
  2554. const linkElem = SugarElement.fromTag('link', doc.dom);
  2555. setAll$1(linkElem, {
  2556. rel: 'stylesheet',
  2557. type: 'text/css',
  2558. id: state.id
  2559. });
  2560. if (settings.contentCssCors) {
  2561. set$3(linkElem, 'crossOrigin', 'anonymous');
  2562. }
  2563. if (settings.referrerPolicy) {
  2564. set$3(linkElem, 'referrerpolicy', settings.referrerPolicy);
  2565. }
  2566. link = linkElem.dom;
  2567. link.onload = passed;
  2568. link.onerror = failed;
  2569. addStyle(linkElem);
  2570. set$3(linkElem, 'href', urlWithSuffix);
  2571. });
  2572. const loadAll = urls => {
  2573. const loadedUrls = Promise.allSettled(map$3(urls, url => load(url).then(constant(url))));
  2574. return loadedUrls.then(results => {
  2575. const parts = partition$2(results, r => r.status === 'fulfilled');
  2576. if (parts.fail.length > 0) {
  2577. return Promise.reject(map$3(parts.fail, result => result.reason));
  2578. } else {
  2579. return map$3(parts.pass, result => result.value);
  2580. }
  2581. });
  2582. };
  2583. const unload = url => {
  2584. const urlWithSuffix = Tools._addCacheSuffix(url);
  2585. get$a(loadedStates, urlWithSuffix).each(state => {
  2586. const count = --state.count;
  2587. if (count === 0) {
  2588. delete loadedStates[urlWithSuffix];
  2589. removeStyle(state.id);
  2590. }
  2591. });
  2592. };
  2593. const unloadAll = urls => {
  2594. each$e(urls, url => {
  2595. unload(url);
  2596. });
  2597. };
  2598. return {
  2599. load,
  2600. loadAll,
  2601. unload,
  2602. unloadAll,
  2603. _setReferrerPolicy,
  2604. _setContentCssCors
  2605. };
  2606. };
  2607. const create$d = () => {
  2608. const map = new WeakMap();
  2609. const forElement = (referenceElement, settings) => {
  2610. const root = getRootNode(referenceElement);
  2611. const rootDom = root.dom;
  2612. return Optional.from(map.get(rootDom)).getOrThunk(() => {
  2613. const sl = StyleSheetLoader(rootDom, settings);
  2614. map.set(rootDom, sl);
  2615. return sl;
  2616. });
  2617. };
  2618. return { forElement };
  2619. };
  2620. const instance = create$d();
  2621. const isSpan = node => node.nodeName.toLowerCase() === 'span';
  2622. const isInlineContent = (node, root) => isNonNullable(node) && (isContent$1(node, root) || isInline$1(SugarElement.fromDom(node)));
  2623. const surroundedByInlineContent = (node, root) => {
  2624. const prev = new DomTreeWalker(node, root).prev(false);
  2625. const next = new DomTreeWalker(node, root).next(false);
  2626. const prevIsInline = isUndefined(prev) || isInlineContent(prev, root);
  2627. const nextIsInline = isUndefined(next) || isInlineContent(next, root);
  2628. return prevIsInline && nextIsInline;
  2629. };
  2630. const isBookmarkNode$2 = node => isSpan(node) && node.getAttribute('data-mce-type') === 'bookmark';
  2631. const isKeepTextNode = (node, root) => isText$a(node) && node.data.length > 0 && surroundedByInlineContent(node, root);
  2632. const isKeepElement = node => isElement$6(node) ? node.childNodes.length > 0 : false;
  2633. const isDocument = node => isDocumentFragment(node) || isDocument$1(node);
  2634. const trimNode = (dom, node, root) => {
  2635. var _a;
  2636. const rootNode = root || node;
  2637. if (isElement$6(node) && isBookmarkNode$2(node)) {
  2638. return node;
  2639. }
  2640. const children = node.childNodes;
  2641. for (let i = children.length - 1; i >= 0; i--) {
  2642. trimNode(dom, children[i], rootNode);
  2643. }
  2644. if (isElement$6(node)) {
  2645. const currentChildren = node.childNodes;
  2646. if (currentChildren.length === 1 && isBookmarkNode$2(currentChildren[0])) {
  2647. (_a = node.parentNode) === null || _a === void 0 ? void 0 : _a.insertBefore(currentChildren[0], node);
  2648. }
  2649. }
  2650. if (!isDocument(node) && !isContent$1(node, rootNode) && !isKeepElement(node) && !isKeepTextNode(node, rootNode)) {
  2651. dom.remove(node);
  2652. }
  2653. return node;
  2654. };
  2655. const makeMap$3 = Tools.makeMap;
  2656. const attrsCharsRegExp = /[&<>\"\u0060\u007E-\uD7FF\uE000-\uFFEF]|[\uD800-\uDBFF][\uDC00-\uDFFF]/g;
  2657. const textCharsRegExp = /[<>&\u007E-\uD7FF\uE000-\uFFEF]|[\uD800-\uDBFF][\uDC00-\uDFFF]/g;
  2658. const rawCharsRegExp = /[<>&\"\']/g;
  2659. const entityRegExp = /&#([a-z0-9]+);?|&([a-z0-9]+);/gi;
  2660. const asciiMap = {
  2661. 128: '\u20AC',
  2662. 130: '\u201A',
  2663. 131: '\u0192',
  2664. 132: '\u201E',
  2665. 133: '\u2026',
  2666. 134: '\u2020',
  2667. 135: '\u2021',
  2668. 136: '\u02c6',
  2669. 137: '\u2030',
  2670. 138: '\u0160',
  2671. 139: '\u2039',
  2672. 140: '\u0152',
  2673. 142: '\u017d',
  2674. 145: '\u2018',
  2675. 146: '\u2019',
  2676. 147: '\u201C',
  2677. 148: '\u201D',
  2678. 149: '\u2022',
  2679. 150: '\u2013',
  2680. 151: '\u2014',
  2681. 152: '\u02DC',
  2682. 153: '\u2122',
  2683. 154: '\u0161',
  2684. 155: '\u203A',
  2685. 156: '\u0153',
  2686. 158: '\u017e',
  2687. 159: '\u0178'
  2688. };
  2689. const baseEntities = {
  2690. '"': '&quot;',
  2691. '\'': '&#39;',
  2692. '<': '&lt;',
  2693. '>': '&gt;',
  2694. '&': '&amp;',
  2695. '`': '&#96;'
  2696. };
  2697. const reverseEntities = {
  2698. '&lt;': '<',
  2699. '&gt;': '>',
  2700. '&amp;': '&',
  2701. '&quot;': '"',
  2702. '&apos;': `'`
  2703. };
  2704. const nativeDecode = text => {
  2705. const elm = SugarElement.fromTag('div').dom;
  2706. elm.innerHTML = text;
  2707. return elm.textContent || elm.innerText || text;
  2708. };
  2709. const buildEntitiesLookup = (items, radix) => {
  2710. const lookup = {};
  2711. if (items) {
  2712. const itemList = items.split(',');
  2713. radix = radix || 10;
  2714. for (let i = 0; i < itemList.length; i += 2) {
  2715. const chr = String.fromCharCode(parseInt(itemList[i], radix));
  2716. if (!baseEntities[chr]) {
  2717. const entity = '&' + itemList[i + 1] + ';';
  2718. lookup[chr] = entity;
  2719. lookup[entity] = chr;
  2720. }
  2721. }
  2722. return lookup;
  2723. } else {
  2724. return undefined;
  2725. }
  2726. };
  2727. 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);
  2728. const encodeRaw = (text, attr) => text.replace(attr ? attrsCharsRegExp : textCharsRegExp, chr => {
  2729. return baseEntities[chr] || chr;
  2730. });
  2731. const encodeAllRaw = text => ('' + text).replace(rawCharsRegExp, chr => {
  2732. return baseEntities[chr] || chr;
  2733. });
  2734. const encodeNumeric = (text, attr) => text.replace(attr ? attrsCharsRegExp : textCharsRegExp, chr => {
  2735. if (chr.length > 1) {
  2736. return '&#' + ((chr.charCodeAt(0) - 55296) * 1024 + (chr.charCodeAt(1) - 56320) + 65536) + ';';
  2737. }
  2738. return baseEntities[chr] || '&#' + chr.charCodeAt(0) + ';';
  2739. });
  2740. const encodeNamed = (text, attr, entities) => {
  2741. const resolveEntities = entities || namedEntities;
  2742. return text.replace(attr ? attrsCharsRegExp : textCharsRegExp, chr => {
  2743. return baseEntities[chr] || resolveEntities[chr] || chr;
  2744. });
  2745. };
  2746. const getEncodeFunc = (name, entities) => {
  2747. const entitiesMap = buildEntitiesLookup(entities) || namedEntities;
  2748. const encodeNamedAndNumeric = (text, attr) => text.replace(attr ? attrsCharsRegExp : textCharsRegExp, chr => {
  2749. if (baseEntities[chr] !== undefined) {
  2750. return baseEntities[chr];
  2751. }
  2752. if (entitiesMap[chr] !== undefined) {
  2753. return entitiesMap[chr];
  2754. }
  2755. if (chr.length > 1) {
  2756. return '&#' + ((chr.charCodeAt(0) - 55296) * 1024 + (chr.charCodeAt(1) - 56320) + 65536) + ';';
  2757. }
  2758. return '&#' + chr.charCodeAt(0) + ';';
  2759. });
  2760. const encodeCustomNamed = (text, attr) => {
  2761. return encodeNamed(text, attr, entitiesMap);
  2762. };
  2763. const nameMap = makeMap$3(name.replace(/\+/g, ','));
  2764. if (nameMap.named && nameMap.numeric) {
  2765. return encodeNamedAndNumeric;
  2766. }
  2767. if (nameMap.named) {
  2768. if (entities) {
  2769. return encodeCustomNamed;
  2770. }
  2771. return encodeNamed;
  2772. }
  2773. if (nameMap.numeric) {
  2774. return encodeNumeric;
  2775. }
  2776. return encodeRaw;
  2777. };
  2778. const decode = text => text.replace(entityRegExp, (all, numeric) => {
  2779. if (numeric) {
  2780. if (numeric.charAt(0).toLowerCase() === 'x') {
  2781. numeric = parseInt(numeric.substr(1), 16);
  2782. } else {
  2783. numeric = parseInt(numeric, 10);
  2784. }
  2785. if (numeric > 65535) {
  2786. numeric -= 65536;
  2787. return String.fromCharCode(55296 + (numeric >> 10), 56320 + (numeric & 1023));
  2788. }
  2789. return asciiMap[numeric] || String.fromCharCode(numeric);
  2790. }
  2791. return reverseEntities[all] || namedEntities[all] || nativeDecode(all);
  2792. });
  2793. const Entities = {
  2794. encodeRaw,
  2795. encodeAllRaw,
  2796. encodeNumeric,
  2797. encodeNamed,
  2798. getEncodeFunc,
  2799. decode
  2800. };
  2801. const lookupCache = {};
  2802. const mapCache = {};
  2803. const dummyObj = {};
  2804. const makeMap$2 = Tools.makeMap, each$b = Tools.each, extend$2 = Tools.extend, explode$2 = Tools.explode, inArray = Tools.inArray;
  2805. const split$1 = (items, delim) => {
  2806. items = Tools.trim(items);
  2807. return items ? items.split(delim || ' ') : [];
  2808. };
  2809. const createMap = (defaultValue, extendWith = {}) => {
  2810. const value = makeMap$2(defaultValue, ' ', makeMap$2(defaultValue.toUpperCase(), ' '));
  2811. return extend$2(value, extendWith);
  2812. };
  2813. const getTextRootBlockElements = schema => createMap('td th li dt dd figcaption caption details summary', schema.getTextBlockElements());
  2814. const compileSchema = type => {
  2815. const schema = {};
  2816. let globalAttributes, blockContent;
  2817. let phrasingContent, flowContent;
  2818. const add = (name, attributes = '', children = '') => {
  2819. const childNames = split$1(children);
  2820. const names = split$1(name);
  2821. let ni = names.length;
  2822. while (ni--) {
  2823. const attributesOrder = split$1([
  2824. globalAttributes,
  2825. attributes
  2826. ].join(' '));
  2827. schema[names[ni]] = {
  2828. attributes: mapToObject(attributesOrder, () => ({})),
  2829. attributesOrder,
  2830. children: mapToObject(childNames, constant(dummyObj))
  2831. };
  2832. }
  2833. };
  2834. const addAttrs = (name, attributes) => {
  2835. const names = split$1(name);
  2836. const attrs = split$1(attributes);
  2837. let ni = names.length;
  2838. while (ni--) {
  2839. const schemaItem = schema[names[ni]];
  2840. for (let i = 0, l = attrs.length; i < l; i++) {
  2841. schemaItem.attributes[attrs[i]] = {};
  2842. schemaItem.attributesOrder.push(attrs[i]);
  2843. }
  2844. }
  2845. };
  2846. if (lookupCache[type]) {
  2847. return lookupCache[type];
  2848. }
  2849. globalAttributes = 'id accesskey class dir lang style tabindex title role';
  2850. blockContent = 'address blockquote div dl fieldset form h1 h2 h3 h4 h5 h6 hr menu ol p pre table ul';
  2851. 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';
  2852. if (type !== 'html4') {
  2853. const transparentContent = 'a ins del canvas map';
  2854. globalAttributes += ' contenteditable contextmenu draggable dropzone ' + 'hidden spellcheck translate';
  2855. blockContent += ' article aside details dialog figure main header footer hgroup section nav ' + transparentContent;
  2856. phrasingContent += ' audio canvas command datalist mark meter output picture ' + 'progress time wbr video ruby bdi keygen';
  2857. }
  2858. if (type !== 'html5-strict') {
  2859. globalAttributes += ' xml:lang';
  2860. const html4PhrasingContent = 'acronym applet basefont big font strike tt';
  2861. phrasingContent = [
  2862. phrasingContent,
  2863. html4PhrasingContent
  2864. ].join(' ');
  2865. each$b(split$1(html4PhrasingContent), name => {
  2866. add(name, '', phrasingContent);
  2867. });
  2868. const html4BlockContent = 'center dir isindex noframes';
  2869. blockContent = [
  2870. blockContent,
  2871. html4BlockContent
  2872. ].join(' ');
  2873. flowContent = [
  2874. blockContent,
  2875. phrasingContent
  2876. ].join(' ');
  2877. each$b(split$1(html4BlockContent), name => {
  2878. add(name, '', flowContent);
  2879. });
  2880. }
  2881. flowContent = flowContent || [
  2882. blockContent,
  2883. phrasingContent
  2884. ].join(' ');
  2885. add('html', 'manifest', 'head body');
  2886. add('head', '', 'base command link meta noscript script style title');
  2887. add('title hr noscript br');
  2888. add('base', 'href target');
  2889. add('link', 'href rel media hreflang type sizes hreflang');
  2890. add('meta', 'name http-equiv content charset');
  2891. add('style', 'media type scoped');
  2892. add('script', 'src async defer type charset');
  2893. add('body', 'onafterprint onbeforeprint onbeforeunload onblur onerror onfocus ' + 'onhashchange onload onmessage onoffline ononline onpagehide onpageshow ' + 'onpopstate onresize onscroll onstorage onunload', flowContent);
  2894. add('address dt dd div caption', '', flowContent);
  2895. 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);
  2896. add('blockquote', 'cite', flowContent);
  2897. add('ol', 'reversed start type', 'li');
  2898. add('ul', '', 'li');
  2899. add('li', 'value', flowContent);
  2900. add('dl', '', 'dt dd');
  2901. add('a', 'href target rel media hreflang type', flowContent);
  2902. add('q', 'cite', phrasingContent);
  2903. add('ins del', 'cite datetime', flowContent);
  2904. add('img', 'src sizes srcset alt usemap ismap width height');
  2905. add('iframe', 'src name width height', flowContent);
  2906. add('embed', 'src type width height');
  2907. add('object', 'data type typemustmatch name usemap form width height', [
  2908. flowContent,
  2909. 'param'
  2910. ].join(' '));
  2911. add('param', 'name value');
  2912. add('map', 'name', [
  2913. flowContent,
  2914. 'area'
  2915. ].join(' '));
  2916. add('area', 'alt coords shape href target rel media hreflang type');
  2917. add('table', 'border', 'caption colgroup thead tfoot tbody tr' + (type === 'html4' ? ' col' : ''));
  2918. add('colgroup', 'span', 'col');
  2919. add('col', 'span');
  2920. add('tbody thead tfoot', '', 'tr');
  2921. add('tr', '', 'td th');
  2922. add('td', 'colspan rowspan headers', flowContent);
  2923. add('th', 'colspan rowspan headers scope abbr', flowContent);
  2924. add('form', 'accept-charset action autocomplete enctype method name novalidate target', flowContent);
  2925. add('fieldset', 'disabled form name', [
  2926. flowContent,
  2927. 'legend'
  2928. ].join(' '));
  2929. add('label', 'form for', phrasingContent);
  2930. 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');
  2931. add('button', 'disabled form formaction formenctype formmethod formnovalidate formtarget name type value', type === 'html4' ? flowContent : phrasingContent);
  2932. add('select', 'disabled form multiple name required size', 'option optgroup');
  2933. add('optgroup', 'disabled label', 'option');
  2934. add('option', 'disabled label selected value');
  2935. add('textarea', 'cols dirname disabled form maxlength name readonly required rows wrap');
  2936. add('menu', 'type label', [
  2937. flowContent,
  2938. 'li'
  2939. ].join(' '));
  2940. add('noscript', '', flowContent);
  2941. if (type !== 'html4') {
  2942. add('wbr');
  2943. add('ruby', '', [
  2944. phrasingContent,
  2945. 'rt rp'
  2946. ].join(' '));
  2947. add('figcaption', '', flowContent);
  2948. add('mark rt rp summary bdi', '', phrasingContent);
  2949. add('canvas', 'width height', flowContent);
  2950. add('video', 'src crossorigin poster preload autoplay mediagroup loop ' + 'muted controls width height buffered', [
  2951. flowContent,
  2952. 'track source'
  2953. ].join(' '));
  2954. add('audio', 'src crossorigin preload autoplay mediagroup loop muted controls ' + 'buffered volume', [
  2955. flowContent,
  2956. 'track source'
  2957. ].join(' '));
  2958. add('picture', '', 'img source');
  2959. add('source', 'src srcset type media sizes');
  2960. add('track', 'kind src srclang label default');
  2961. add('datalist', '', [
  2962. phrasingContent,
  2963. 'option'
  2964. ].join(' '));
  2965. add('article section nav aside main header footer', '', flowContent);
  2966. add('hgroup', '', 'h1 h2 h3 h4 h5 h6');
  2967. add('figure', '', [
  2968. flowContent,
  2969. 'figcaption'
  2970. ].join(' '));
  2971. add('time', 'datetime', phrasingContent);
  2972. add('dialog', 'open', flowContent);
  2973. add('command', 'type label icon disabled checked radiogroup command');
  2974. add('output', 'for form name', phrasingContent);
  2975. add('progress', 'value max', phrasingContent);
  2976. add('meter', 'value min max low high optimum', phrasingContent);
  2977. add('details', 'open', [
  2978. flowContent,
  2979. 'summary'
  2980. ].join(' '));
  2981. add('keygen', 'autofocus challenge disabled form keytype name');
  2982. }
  2983. if (type !== 'html5-strict') {
  2984. addAttrs('script', 'language xml:space');
  2985. addAttrs('style', 'xml:space');
  2986. addAttrs('object', 'declare classid code codebase codetype archive standby align border hspace vspace');
  2987. addAttrs('embed', 'align name hspace vspace');
  2988. addAttrs('param', 'valuetype type');
  2989. addAttrs('a', 'charset name rev shape coords');
  2990. addAttrs('br', 'clear');
  2991. addAttrs('applet', 'codebase archive code object alt name width height align hspace vspace');
  2992. addAttrs('img', 'name longdesc align border hspace vspace');
  2993. addAttrs('iframe', 'longdesc frameborder marginwidth marginheight scrolling align');
  2994. addAttrs('font basefont', 'size color face');
  2995. addAttrs('input', 'usemap align');
  2996. addAttrs('select');
  2997. addAttrs('textarea');
  2998. addAttrs('h1 h2 h3 h4 h5 h6 div p legend caption', 'align');
  2999. addAttrs('ul', 'type compact');
  3000. addAttrs('li', 'type');
  3001. addAttrs('ol dl menu dir', 'compact');
  3002. addAttrs('pre', 'width xml:space');
  3003. addAttrs('hr', 'align noshade size width');
  3004. addAttrs('isindex', 'prompt');
  3005. addAttrs('table', 'summary width frame rules cellspacing cellpadding align bgcolor');
  3006. addAttrs('col', 'width align char charoff valign');
  3007. addAttrs('colgroup', 'width align char charoff valign');
  3008. addAttrs('thead', 'align char charoff valign');
  3009. addAttrs('tr', 'align char charoff valign bgcolor');
  3010. addAttrs('th', 'axis align char charoff valign nowrap bgcolor width height');
  3011. addAttrs('form', 'accept');
  3012. addAttrs('td', 'abbr axis scope align char charoff valign nowrap bgcolor width height');
  3013. addAttrs('tfoot', 'align char charoff valign');
  3014. addAttrs('tbody', 'align char charoff valign');
  3015. addAttrs('area', 'nohref');
  3016. addAttrs('body', 'background bgcolor text link vlink alink');
  3017. }
  3018. if (type !== 'html4') {
  3019. addAttrs('input button select textarea', 'autofocus');
  3020. addAttrs('input textarea', 'placeholder');
  3021. addAttrs('a', 'download');
  3022. addAttrs('link script img', 'crossorigin');
  3023. addAttrs('img', 'loading');
  3024. addAttrs('iframe', 'sandbox seamless allow allowfullscreen loading');
  3025. }
  3026. if (type !== 'html4') {
  3027. each$e([
  3028. schema.video,
  3029. schema.audio
  3030. ], item => {
  3031. delete item.children.audio;
  3032. delete item.children.video;
  3033. });
  3034. }
  3035. each$b(split$1('a form meter progress dfn'), name => {
  3036. if (schema[name]) {
  3037. delete schema[name].children[name];
  3038. }
  3039. });
  3040. delete schema.caption.children.table;
  3041. delete schema.script;
  3042. lookupCache[type] = schema;
  3043. return schema;
  3044. };
  3045. const compileElementMap = (value, mode) => {
  3046. if (value) {
  3047. const styles = {};
  3048. if (isString(value)) {
  3049. value = { '*': value };
  3050. }
  3051. each$b(value, (value, key) => {
  3052. styles[key] = styles[key.toUpperCase()] = mode === 'map' ? makeMap$2(value, /[, ]/) : explode$2(value, /[, ]/);
  3053. });
  3054. return styles;
  3055. } else {
  3056. return undefined;
  3057. }
  3058. };
  3059. const Schema = (settings = {}) => {
  3060. var _a;
  3061. const elements = {};
  3062. const children = {};
  3063. let patternElements = [];
  3064. const customElementsMap = {};
  3065. const specialElements = {};
  3066. const createLookupTable = (option, defaultValue, extendWith) => {
  3067. const value = settings[option];
  3068. if (!value) {
  3069. let newValue = mapCache[option];
  3070. if (!newValue) {
  3071. newValue = createMap(defaultValue, extendWith);
  3072. mapCache[option] = newValue;
  3073. }
  3074. return newValue;
  3075. } else {
  3076. return makeMap$2(value, /[, ]/, makeMap$2(value.toUpperCase(), /[, ]/));
  3077. }
  3078. };
  3079. const schemaType = (_a = settings.schema) !== null && _a !== void 0 ? _a : 'html5';
  3080. const schemaItems = compileSchema(schemaType);
  3081. if (settings.verify_html === false) {
  3082. settings.valid_elements = '*[*]';
  3083. }
  3084. const validStyles = compileElementMap(settings.valid_styles);
  3085. const invalidStyles = compileElementMap(settings.invalid_styles, 'map');
  3086. const validClasses = compileElementMap(settings.valid_classes, 'map');
  3087. const whitespaceElementsMap = createLookupTable('whitespace_elements', 'pre script noscript style textarea video audio iframe object code');
  3088. const selfClosingElementsMap = createLookupTable('self_closing_elements', 'colgroup dd dt li option p td tfoot th thead tr');
  3089. const voidElementsMap = createLookupTable('void_elements', 'area base basefont br col frame hr img input isindex link ' + 'meta param embed source wbr track');
  3090. const boolAttrMap = createLookupTable('boolean_attributes', 'checked compact declare defer disabled ismap multiple nohref noresize ' + 'noshade nowrap readonly selected autoplay loop controls allowfullscreen');
  3091. const nonEmptyOrMoveCaretBeforeOnEnter = 'td th iframe video audio object script code';
  3092. const nonEmptyElementsMap = createLookupTable('non_empty_elements', nonEmptyOrMoveCaretBeforeOnEnter + ' pre', voidElementsMap);
  3093. const moveCaretBeforeOnEnterElementsMap = createLookupTable('move_caret_before_on_enter_elements', nonEmptyOrMoveCaretBeforeOnEnter + ' table', voidElementsMap);
  3094. 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');
  3095. 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);
  3096. const textInlineElementsMap = createLookupTable('text_inline_elements', 'span strong b em i font s strike u var cite ' + 'dfn code mark q sup sub samp');
  3097. const transparentElementsMap = createLookupTable('transparent_elements', 'a ins del canvas map');
  3098. each$b('script noscript iframe noframes noembed title style textarea xmp plaintext'.split(' '), name => {
  3099. specialElements[name] = new RegExp('</' + name + '[^>]*>', 'gi');
  3100. });
  3101. const patternToRegExp = str => new RegExp('^' + str.replace(/([?+*])/g, '.$1') + '$');
  3102. const addValidElements = validElements => {
  3103. const elementRuleRegExp = /^([#+\-])?([^\[!\/]+)(?:\/([^\[!]+))?(?:(!?)\[([^\]]+)])?$/;
  3104. const attrRuleRegExp = /^([!\-])?(\w+[\\:]:\w+|[^=~<]+)?(?:([=~<])(.*))?$/;
  3105. const hasPatternsRegExp = /[*?+]/;
  3106. if (validElements) {
  3107. const validElementsArr = split$1(validElements, ',');
  3108. let globalAttributes;
  3109. let globalAttributesOrder;
  3110. if (elements['@']) {
  3111. globalAttributes = elements['@'].attributes;
  3112. globalAttributesOrder = elements['@'].attributesOrder;
  3113. }
  3114. for (let ei = 0, el = validElementsArr.length; ei < el; ei++) {
  3115. let matches = elementRuleRegExp.exec(validElementsArr[ei]);
  3116. if (matches) {
  3117. const prefix = matches[1];
  3118. const elementName = matches[2];
  3119. const outputName = matches[3];
  3120. const attrData = matches[5];
  3121. const attributes = {};
  3122. const attributesOrder = [];
  3123. const element = {
  3124. attributes,
  3125. attributesOrder
  3126. };
  3127. if (prefix === '#') {
  3128. element.paddEmpty = true;
  3129. }
  3130. if (prefix === '-') {
  3131. element.removeEmpty = true;
  3132. }
  3133. if (matches[4] === '!') {
  3134. element.removeEmptyAttrs = true;
  3135. }
  3136. if (globalAttributes) {
  3137. each$d(globalAttributes, (value, key) => {
  3138. attributes[key] = value;
  3139. });
  3140. if (globalAttributesOrder) {
  3141. attributesOrder.push(...globalAttributesOrder);
  3142. }
  3143. }
  3144. if (attrData) {
  3145. const attrDatas = split$1(attrData, '|');
  3146. for (let ai = 0, al = attrDatas.length; ai < al; ai++) {
  3147. matches = attrRuleRegExp.exec(attrDatas[ai]);
  3148. if (matches) {
  3149. const attr = {};
  3150. const attrType = matches[1];
  3151. const attrName = matches[2].replace(/[\\:]:/g, ':');
  3152. const attrPrefix = matches[3];
  3153. const value = matches[4];
  3154. if (attrType === '!') {
  3155. element.attributesRequired = element.attributesRequired || [];
  3156. element.attributesRequired.push(attrName);
  3157. attr.required = true;
  3158. }
  3159. if (attrType === '-') {
  3160. delete attributes[attrName];
  3161. attributesOrder.splice(inArray(attributesOrder, attrName), 1);
  3162. continue;
  3163. }
  3164. if (attrPrefix) {
  3165. if (attrPrefix === '=') {
  3166. element.attributesDefault = element.attributesDefault || [];
  3167. element.attributesDefault.push({
  3168. name: attrName,
  3169. value
  3170. });
  3171. attr.defaultValue = value;
  3172. }
  3173. if (attrPrefix === '~') {
  3174. element.attributesForced = element.attributesForced || [];
  3175. element.attributesForced.push({
  3176. name: attrName,
  3177. value
  3178. });
  3179. attr.forcedValue = value;
  3180. }
  3181. if (attrPrefix === '<') {
  3182. attr.validValues = makeMap$2(value, '?');
  3183. }
  3184. }
  3185. if (hasPatternsRegExp.test(attrName)) {
  3186. const attrPattern = attr;
  3187. element.attributePatterns = element.attributePatterns || [];
  3188. attrPattern.pattern = patternToRegExp(attrName);
  3189. element.attributePatterns.push(attrPattern);
  3190. } else {
  3191. if (!attributes[attrName]) {
  3192. attributesOrder.push(attrName);
  3193. }
  3194. attributes[attrName] = attr;
  3195. }
  3196. }
  3197. }
  3198. }
  3199. if (!globalAttributes && elementName === '@') {
  3200. globalAttributes = attributes;
  3201. globalAttributesOrder = attributesOrder;
  3202. }
  3203. if (outputName) {
  3204. element.outputName = elementName;
  3205. elements[outputName] = element;
  3206. }
  3207. if (hasPatternsRegExp.test(elementName)) {
  3208. const patternElement = element;
  3209. patternElement.pattern = patternToRegExp(elementName);
  3210. patternElements.push(patternElement);
  3211. } else {
  3212. elements[elementName] = element;
  3213. }
  3214. }
  3215. }
  3216. }
  3217. };
  3218. const setValidElements = validElements => {
  3219. patternElements = [];
  3220. each$e(keys(elements), name => {
  3221. delete elements[name];
  3222. });
  3223. addValidElements(validElements);
  3224. each$b(schemaItems, (element, name) => {
  3225. children[name] = element.children;
  3226. });
  3227. };
  3228. const addCustomElements = customElements => {
  3229. const customElementRegExp = /^(~)?(.+)$/;
  3230. if (customElements) {
  3231. delete mapCache.text_block_elements;
  3232. delete mapCache.block_elements;
  3233. each$b(split$1(customElements, ','), rule => {
  3234. const matches = customElementRegExp.exec(rule);
  3235. if (matches) {
  3236. const inline = matches[1] === '~';
  3237. const cloneName = inline ? 'span' : 'div';
  3238. const name = matches[2];
  3239. children[name] = children[cloneName];
  3240. customElementsMap[name] = cloneName;
  3241. nonEmptyElementsMap[name.toUpperCase()] = {};
  3242. nonEmptyElementsMap[name] = {};
  3243. if (!inline) {
  3244. blockElementsMap[name.toUpperCase()] = {};
  3245. blockElementsMap[name] = {};
  3246. }
  3247. if (!elements[name]) {
  3248. let customRule = elements[cloneName];
  3249. customRule = extend$2({}, customRule);
  3250. delete customRule.removeEmptyAttrs;
  3251. delete customRule.removeEmpty;
  3252. elements[name] = customRule;
  3253. }
  3254. each$b(children, (element, elmName) => {
  3255. if (element[cloneName]) {
  3256. children[elmName] = element = extend$2({}, children[elmName]);
  3257. element[name] = element[cloneName];
  3258. }
  3259. });
  3260. }
  3261. });
  3262. }
  3263. };
  3264. const addValidChildren = validChildren => {
  3265. 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]+)\[([^\]]+)]$/;
  3266. delete lookupCache[schemaType];
  3267. if (validChildren) {
  3268. each$b(split$1(validChildren, ','), rule => {
  3269. const matches = childRuleRegExp.exec(rule);
  3270. if (matches) {
  3271. const prefix = matches[1];
  3272. let parent;
  3273. if (prefix) {
  3274. parent = children[matches[2]];
  3275. } else {
  3276. parent = children[matches[2]] = { '#comment': {} };
  3277. }
  3278. parent = children[matches[2]];
  3279. each$b(split$1(matches[3], '|'), child => {
  3280. if (prefix === '-') {
  3281. delete parent[child];
  3282. } else {
  3283. parent[child] = {};
  3284. }
  3285. });
  3286. }
  3287. });
  3288. }
  3289. };
  3290. const getElementRule = name => {
  3291. const element = elements[name];
  3292. if (element) {
  3293. return element;
  3294. }
  3295. let i = patternElements.length;
  3296. while (i--) {
  3297. const patternElement = patternElements[i];
  3298. if (patternElement.pattern.test(name)) {
  3299. return patternElement;
  3300. }
  3301. }
  3302. return undefined;
  3303. };
  3304. if (!settings.valid_elements) {
  3305. each$b(schemaItems, (element, name) => {
  3306. elements[name] = {
  3307. attributes: element.attributes,
  3308. attributesOrder: element.attributesOrder
  3309. };
  3310. children[name] = element.children;
  3311. });
  3312. each$b(split$1('strong/b em/i'), item => {
  3313. const items = split$1(item, '/');
  3314. elements[items[1]].outputName = items[0];
  3315. });
  3316. each$b(textInlineElementsMap, (_val, name) => {
  3317. if (elements[name]) {
  3318. if (settings.padd_empty_block_inline_children) {
  3319. elements[name].paddInEmptyBlock = true;
  3320. }
  3321. elements[name].removeEmpty = true;
  3322. }
  3323. });
  3324. each$b(split$1('ol ul blockquote a table tbody'), name => {
  3325. if (elements[name]) {
  3326. elements[name].removeEmpty = true;
  3327. }
  3328. });
  3329. each$b(split$1('p h1 h2 h3 h4 h5 h6 th td pre div address caption li'), name => {
  3330. elements[name].paddEmpty = true;
  3331. });
  3332. each$b(split$1('span'), name => {
  3333. elements[name].removeEmptyAttrs = true;
  3334. });
  3335. } else {
  3336. setValidElements(settings.valid_elements);
  3337. }
  3338. addCustomElements(settings.custom_elements);
  3339. addValidChildren(settings.valid_children);
  3340. addValidElements(settings.extended_valid_elements);
  3341. addValidChildren('+ol[ul|ol],+ul[ul|ol]');
  3342. each$b({
  3343. dd: 'dl',
  3344. dt: 'dl',
  3345. li: 'ul ol',
  3346. td: 'tr',
  3347. th: 'tr',
  3348. tr: 'tbody thead tfoot',
  3349. tbody: 'table',
  3350. thead: 'table',
  3351. tfoot: 'table',
  3352. legend: 'fieldset',
  3353. area: 'map',
  3354. param: 'video audio object'
  3355. }, (parents, item) => {
  3356. if (elements[item]) {
  3357. elements[item].parentsRequired = split$1(parents);
  3358. }
  3359. });
  3360. if (settings.invalid_elements) {
  3361. each$b(explode$2(settings.invalid_elements), item => {
  3362. if (elements[item]) {
  3363. delete elements[item];
  3364. }
  3365. });
  3366. }
  3367. if (!getElementRule('span')) {
  3368. addValidElements('span[!data-mce-type|*]');
  3369. }
  3370. const getValidStyles = constant(validStyles);
  3371. const getInvalidStyles = constant(invalidStyles);
  3372. const getValidClasses = constant(validClasses);
  3373. const getBoolAttrs = constant(boolAttrMap);
  3374. const getBlockElements = constant(blockElementsMap);
  3375. const getTextBlockElements = constant(textBlockElementsMap);
  3376. const getTextInlineElements = constant(textInlineElementsMap);
  3377. const getVoidElements = constant(Object.seal(voidElementsMap));
  3378. const getSelfClosingElements = constant(selfClosingElementsMap);
  3379. const getNonEmptyElements = constant(nonEmptyElementsMap);
  3380. const getMoveCaretBeforeOnEnterElements = constant(moveCaretBeforeOnEnterElementsMap);
  3381. const getWhitespaceElements = constant(whitespaceElementsMap);
  3382. const getTransparentElements = constant(transparentElementsMap);
  3383. const getSpecialElements = constant(Object.seal(specialElements));
  3384. const isValidChild = (name, child) => {
  3385. const parent = children[name.toLowerCase()];
  3386. return !!(parent && parent[child.toLowerCase()]);
  3387. };
  3388. const isValid = (name, attr) => {
  3389. const rule = getElementRule(name);
  3390. if (rule) {
  3391. if (attr) {
  3392. if (rule.attributes[attr]) {
  3393. return true;
  3394. }
  3395. const attrPatterns = rule.attributePatterns;
  3396. if (attrPatterns) {
  3397. let i = attrPatterns.length;
  3398. while (i--) {
  3399. if (attrPatterns[i].pattern.test(attr)) {
  3400. return true;
  3401. }
  3402. }
  3403. }
  3404. } else {
  3405. return true;
  3406. }
  3407. }
  3408. return false;
  3409. };
  3410. const getCustomElements = constant(customElementsMap);
  3411. return {
  3412. type: schemaType,
  3413. children,
  3414. elements,
  3415. getValidStyles,
  3416. getValidClasses,
  3417. getBlockElements,
  3418. getInvalidStyles,
  3419. getVoidElements,
  3420. getTextBlockElements,
  3421. getTextInlineElements,
  3422. getBoolAttrs,
  3423. getElementRule,
  3424. getSelfClosingElements,
  3425. getNonEmptyElements,
  3426. getMoveCaretBeforeOnEnterElements,
  3427. getWhitespaceElements,
  3428. getTransparentElements,
  3429. getSpecialElements,
  3430. isValidChild,
  3431. isValid,
  3432. getCustomElements,
  3433. addValidElements,
  3434. setValidElements,
  3435. addCustomElements,
  3436. addValidChildren
  3437. };
  3438. };
  3439. const Styles = (settings = {}, schema) => {
  3440. const urlOrStrRegExp = /(?:url(?:(?:\(\s*\"([^\"]+)\"\s*\))|(?:\(\s*\'([^\']+)\'\s*\))|(?:\(\s*([^)\s]+)\s*\))))|(?:\'([^\']+)\')|(?:\"([^\"]+)\")/gi;
  3441. const styleRegExp = /\s*([^:]+):\s*([^;]+);?/g;
  3442. const trimRightRegExp = /\s+$/;
  3443. const encodingLookup = {};
  3444. let validStyles;
  3445. let invalidStyles;
  3446. const invisibleChar = zeroWidth;
  3447. if (schema) {
  3448. validStyles = schema.getValidStyles();
  3449. invalidStyles = schema.getInvalidStyles();
  3450. }
  3451. const encodingItems = (`\\" \\' \\; \\: ; : ` + invisibleChar).split(' ');
  3452. for (let i = 0; i < encodingItems.length; i++) {
  3453. encodingLookup[encodingItems[i]] = invisibleChar + i;
  3454. encodingLookup[invisibleChar + i] = encodingItems[i];
  3455. }
  3456. const self = {
  3457. parse: css => {
  3458. const styles = {};
  3459. let isEncoded = false;
  3460. const urlConverter = settings.url_converter;
  3461. const urlConverterScope = settings.url_converter_scope || self;
  3462. const compress = (prefix, suffix, noJoin) => {
  3463. const top = styles[prefix + '-top' + suffix];
  3464. if (!top) {
  3465. return;
  3466. }
  3467. const right = styles[prefix + '-right' + suffix];
  3468. if (!right) {
  3469. return;
  3470. }
  3471. const bottom = styles[prefix + '-bottom' + suffix];
  3472. if (!bottom) {
  3473. return;
  3474. }
  3475. const left = styles[prefix + '-left' + suffix];
  3476. if (!left) {
  3477. return;
  3478. }
  3479. const box = [
  3480. top,
  3481. right,
  3482. bottom,
  3483. left
  3484. ];
  3485. let i = box.length - 1;
  3486. while (i--) {
  3487. if (box[i] !== box[i + 1]) {
  3488. break;
  3489. }
  3490. }
  3491. if (i > -1 && noJoin) {
  3492. return;
  3493. }
  3494. styles[prefix + suffix] = i === -1 ? box[0] : box.join(' ');
  3495. delete styles[prefix + '-top' + suffix];
  3496. delete styles[prefix + '-right' + suffix];
  3497. delete styles[prefix + '-bottom' + suffix];
  3498. delete styles[prefix + '-left' + suffix];
  3499. };
  3500. const canCompress = key => {
  3501. const value = styles[key];
  3502. if (!value) {
  3503. return;
  3504. }
  3505. const values = value.split(' ');
  3506. let i = values.length;
  3507. while (i--) {
  3508. if (values[i] !== values[0]) {
  3509. return false;
  3510. }
  3511. }
  3512. styles[key] = values[0];
  3513. return true;
  3514. };
  3515. const compress2 = (target, a, b, c) => {
  3516. if (!canCompress(a)) {
  3517. return;
  3518. }
  3519. if (!canCompress(b)) {
  3520. return;
  3521. }
  3522. if (!canCompress(c)) {
  3523. return;
  3524. }
  3525. styles[target] = styles[a] + ' ' + styles[b] + ' ' + styles[c];
  3526. delete styles[a];
  3527. delete styles[b];
  3528. delete styles[c];
  3529. };
  3530. const encode = str => {
  3531. isEncoded = true;
  3532. return encodingLookup[str];
  3533. };
  3534. const decode = (str, keepSlashes) => {
  3535. if (isEncoded) {
  3536. str = str.replace(/\uFEFF[0-9]/g, str => {
  3537. return encodingLookup[str];
  3538. });
  3539. }
  3540. if (!keepSlashes) {
  3541. str = str.replace(/\\([\'\";:])/g, '$1');
  3542. }
  3543. return str;
  3544. };
  3545. const decodeSingleHexSequence = escSeq => {
  3546. return String.fromCharCode(parseInt(escSeq.slice(1), 16));
  3547. };
  3548. const decodeHexSequences = value => {
  3549. return value.replace(/\\[0-9a-f]+/gi, decodeSingleHexSequence);
  3550. };
  3551. const processUrl = (match, url, url2, url3, str, str2) => {
  3552. str = str || str2;
  3553. if (str) {
  3554. str = decode(str);
  3555. return `'` + str.replace(/\'/g, `\\'`) + `'`;
  3556. }
  3557. url = decode(url || url2 || url3 || '');
  3558. if (!settings.allow_script_urls) {
  3559. const scriptUrl = url.replace(/[\s\r\n]+/g, '');
  3560. if (/(java|vb)script:/i.test(scriptUrl)) {
  3561. return '';
  3562. }
  3563. if (!settings.allow_svg_data_urls && /^data:image\/svg/i.test(scriptUrl)) {
  3564. return '';
  3565. }
  3566. }
  3567. if (urlConverter) {
  3568. url = urlConverter.call(urlConverterScope, url, 'style');
  3569. }
  3570. return `url('` + url.replace(/\'/g, `\\'`) + `')`;
  3571. };
  3572. if (css) {
  3573. css = css.replace(/[\u0000-\u001F]/g, '');
  3574. css = css.replace(/\\[\"\';:\uFEFF]/g, encode).replace(/\"[^\"]+\"|\'[^\']+\'/g, str => {
  3575. return str.replace(/[;:]/g, encode);
  3576. });
  3577. let matches;
  3578. while (matches = styleRegExp.exec(css)) {
  3579. styleRegExp.lastIndex = matches.index + matches[0].length;
  3580. let name = matches[1].replace(trimRightRegExp, '').toLowerCase();
  3581. let value = matches[2].replace(trimRightRegExp, '');
  3582. if (name && value) {
  3583. name = decodeHexSequences(name);
  3584. value = decodeHexSequences(value);
  3585. if (name.indexOf(invisibleChar) !== -1 || name.indexOf('"') !== -1) {
  3586. continue;
  3587. }
  3588. if (!settings.allow_script_urls && (name === 'behavior' || /expression\s*\(|\/\*|\*\//.test(value))) {
  3589. continue;
  3590. }
  3591. if (name === 'font-weight' && value === '700') {
  3592. value = 'bold';
  3593. } else if (name === 'color' || name === 'background-color') {
  3594. value = value.toLowerCase();
  3595. }
  3596. value = value.replace(urlOrStrRegExp, processUrl);
  3597. styles[name] = isEncoded ? decode(value, true) : value;
  3598. }
  3599. }
  3600. compress('border', '', true);
  3601. compress('border', '-width');
  3602. compress('border', '-color');
  3603. compress('border', '-style');
  3604. compress('padding', '');
  3605. compress('margin', '');
  3606. compress2('border', 'border-width', 'border-style', 'border-color');
  3607. if (styles.border === 'medium none') {
  3608. delete styles.border;
  3609. }
  3610. if (styles['border-image'] === 'none') {
  3611. delete styles['border-image'];
  3612. }
  3613. }
  3614. return styles;
  3615. },
  3616. serialize: (styles, elementName) => {
  3617. let css = '';
  3618. const serializeStyles = (elemName, validStyleList) => {
  3619. const styleList = validStyleList[elemName];
  3620. if (styleList) {
  3621. for (let i = 0, l = styleList.length; i < l; i++) {
  3622. const name = styleList[i];
  3623. const value = styles[name];
  3624. if (value) {
  3625. css += (css.length > 0 ? ' ' : '') + name + ': ' + value + ';';
  3626. }
  3627. }
  3628. }
  3629. };
  3630. const isValid = (name, elemName) => {
  3631. if (!invalidStyles || !elemName) {
  3632. return true;
  3633. }
  3634. let styleMap = invalidStyles['*'];
  3635. if (styleMap && styleMap[name]) {
  3636. return false;
  3637. }
  3638. styleMap = invalidStyles[elemName];
  3639. return !(styleMap && styleMap[name]);
  3640. };
  3641. if (elementName && validStyles) {
  3642. serializeStyles('*', validStyles);
  3643. serializeStyles(elementName, validStyles);
  3644. } else {
  3645. each$d(styles, (value, name) => {
  3646. if (value && isValid(name, elementName)) {
  3647. css += (css.length > 0 ? ' ' : '') + name + ': ' + value + ';';
  3648. }
  3649. });
  3650. }
  3651. return css;
  3652. }
  3653. };
  3654. return self;
  3655. };
  3656. const deprecated = {
  3657. keyLocation: true,
  3658. layerX: true,
  3659. layerY: true,
  3660. returnValue: true,
  3661. webkitMovementX: true,
  3662. webkitMovementY: true,
  3663. keyIdentifier: true,
  3664. mozPressure: true
  3665. };
  3666. const isNativeEvent = event => event instanceof Event || isFunction(event.initEvent);
  3667. const hasIsDefaultPrevented = event => event.isDefaultPrevented === always || event.isDefaultPrevented === never;
  3668. const needsNormalizing = event => isNullable(event.preventDefault) || isNativeEvent(event);
  3669. const clone$3 = (originalEvent, data) => {
  3670. const event = data !== null && data !== void 0 ? data : {};
  3671. for (const name in originalEvent) {
  3672. if (!has$2(deprecated, name)) {
  3673. event[name] = originalEvent[name];
  3674. }
  3675. }
  3676. if (isNonNullable(originalEvent.composedPath)) {
  3677. event.composedPath = () => originalEvent.composedPath();
  3678. }
  3679. return event;
  3680. };
  3681. const normalize$3 = (type, originalEvent, fallbackTarget, data) => {
  3682. var _a;
  3683. const event = clone$3(originalEvent, data);
  3684. event.type = type;
  3685. if (isNullable(event.target)) {
  3686. event.target = (_a = event.srcElement) !== null && _a !== void 0 ? _a : fallbackTarget;
  3687. }
  3688. if (needsNormalizing(originalEvent)) {
  3689. event.preventDefault = () => {
  3690. event.defaultPrevented = true;
  3691. event.isDefaultPrevented = always;
  3692. if (isFunction(originalEvent.preventDefault)) {
  3693. originalEvent.preventDefault();
  3694. }
  3695. };
  3696. event.stopPropagation = () => {
  3697. event.cancelBubble = true;
  3698. event.isPropagationStopped = always;
  3699. if (isFunction(originalEvent.stopPropagation)) {
  3700. originalEvent.stopPropagation();
  3701. }
  3702. };
  3703. event.stopImmediatePropagation = () => {
  3704. event.isImmediatePropagationStopped = always;
  3705. event.stopPropagation();
  3706. };
  3707. if (!hasIsDefaultPrevented(event)) {
  3708. event.isDefaultPrevented = event.defaultPrevented === true ? always : never;
  3709. event.isPropagationStopped = event.cancelBubble === true ? always : never;
  3710. event.isImmediatePropagationStopped = never;
  3711. }
  3712. }
  3713. return event;
  3714. };
  3715. const eventExpandoPrefix = 'mce-data-';
  3716. const mouseEventRe = /^(?:mouse|contextmenu)|click/;
  3717. const addEvent = (target, name, callback, capture) => {
  3718. target.addEventListener(name, callback, capture || false);
  3719. };
  3720. const removeEvent = (target, name, callback, capture) => {
  3721. target.removeEventListener(name, callback, capture || false);
  3722. };
  3723. const isMouseEvent = event => isNonNullable(event) && mouseEventRe.test(event.type);
  3724. const fix = (originalEvent, data) => {
  3725. const event = normalize$3(originalEvent.type, originalEvent, document, data);
  3726. if (isMouseEvent(originalEvent) && isUndefined(originalEvent.pageX) && !isUndefined(originalEvent.clientX)) {
  3727. const eventDoc = event.target.ownerDocument || document;
  3728. const doc = eventDoc.documentElement;
  3729. const body = eventDoc.body;
  3730. const mouseEvent = event;
  3731. mouseEvent.pageX = originalEvent.clientX + (doc && doc.scrollLeft || body && body.scrollLeft || 0) - (doc && doc.clientLeft || body && body.clientLeft || 0);
  3732. mouseEvent.pageY = originalEvent.clientY + (doc && doc.scrollTop || body && body.scrollTop || 0) - (doc && doc.clientTop || body && body.clientTop || 0);
  3733. }
  3734. return event;
  3735. };
  3736. const bindOnReady = (win, callback, eventUtils) => {
  3737. const doc = win.document, event = { type: 'ready' };
  3738. if (eventUtils.domLoaded) {
  3739. callback(event);
  3740. return;
  3741. }
  3742. const isDocReady = () => {
  3743. return doc.readyState === 'complete' || doc.readyState === 'interactive' && doc.body;
  3744. };
  3745. const readyHandler = () => {
  3746. removeEvent(win, 'DOMContentLoaded', readyHandler);
  3747. removeEvent(win, 'load', readyHandler);
  3748. if (!eventUtils.domLoaded) {
  3749. eventUtils.domLoaded = true;
  3750. callback(event);
  3751. }
  3752. win = null;
  3753. };
  3754. if (isDocReady()) {
  3755. readyHandler();
  3756. } else {
  3757. addEvent(win, 'DOMContentLoaded', readyHandler);
  3758. }
  3759. if (!eventUtils.domLoaded) {
  3760. addEvent(win, 'load', readyHandler);
  3761. }
  3762. };
  3763. class EventUtils {
  3764. constructor() {
  3765. this.domLoaded = false;
  3766. this.events = {};
  3767. this.count = 1;
  3768. this.expando = eventExpandoPrefix + (+new Date()).toString(32);
  3769. this.hasFocusIn = 'onfocusin' in document.documentElement;
  3770. this.count = 1;
  3771. }
  3772. bind(target, names, callback, scope) {
  3773. const self = this;
  3774. let callbackList;
  3775. const win = window;
  3776. const defaultNativeHandler = evt => {
  3777. self.executeHandlers(fix(evt || win.event), id);
  3778. };
  3779. if (!target || isText$a(target) || isComment(target)) {
  3780. return callback;
  3781. }
  3782. let id;
  3783. if (!target[self.expando]) {
  3784. id = self.count++;
  3785. target[self.expando] = id;
  3786. self.events[id] = {};
  3787. } else {
  3788. id = target[self.expando];
  3789. }
  3790. scope = scope || target;
  3791. const namesList = names.split(' ');
  3792. let i = namesList.length;
  3793. while (i--) {
  3794. let name = namesList[i];
  3795. let nativeHandler = defaultNativeHandler;
  3796. let capture = false;
  3797. let fakeName = false;
  3798. if (name === 'DOMContentLoaded') {
  3799. name = 'ready';
  3800. }
  3801. if (self.domLoaded && name === 'ready' && target.readyState === 'complete') {
  3802. callback.call(scope, fix({ type: name }));
  3803. continue;
  3804. }
  3805. if (!self.hasFocusIn && (name === 'focusin' || name === 'focusout')) {
  3806. capture = true;
  3807. fakeName = name === 'focusin' ? 'focus' : 'blur';
  3808. nativeHandler = evt => {
  3809. const event = fix(evt || win.event);
  3810. event.type = event.type === 'focus' ? 'focusin' : 'focusout';
  3811. self.executeHandlers(event, id);
  3812. };
  3813. }
  3814. callbackList = self.events[id][name];
  3815. if (!callbackList) {
  3816. self.events[id][name] = callbackList = [{
  3817. func: callback,
  3818. scope
  3819. }];
  3820. callbackList.fakeName = fakeName;
  3821. callbackList.capture = capture;
  3822. callbackList.nativeHandler = nativeHandler;
  3823. if (name === 'ready') {
  3824. bindOnReady(target, nativeHandler, self);
  3825. } else {
  3826. addEvent(target, fakeName || name, nativeHandler, capture);
  3827. }
  3828. } else {
  3829. if (name === 'ready' && self.domLoaded) {
  3830. callback(fix({ type: name }));
  3831. } else {
  3832. callbackList.push({
  3833. func: callback,
  3834. scope
  3835. });
  3836. }
  3837. }
  3838. }
  3839. target = callbackList = null;
  3840. return callback;
  3841. }
  3842. unbind(target, names, callback) {
  3843. if (!target || isText$a(target) || isComment(target)) {
  3844. return this;
  3845. }
  3846. const id = target[this.expando];
  3847. if (id) {
  3848. let eventMap = this.events[id];
  3849. if (names) {
  3850. const namesList = names.split(' ');
  3851. let i = namesList.length;
  3852. while (i--) {
  3853. const name = namesList[i];
  3854. const callbackList = eventMap[name];
  3855. if (callbackList) {
  3856. if (callback) {
  3857. let ci = callbackList.length;
  3858. while (ci--) {
  3859. if (callbackList[ci].func === callback) {
  3860. const nativeHandler = callbackList.nativeHandler;
  3861. const fakeName = callbackList.fakeName, capture = callbackList.capture;
  3862. const newCallbackList = callbackList.slice(0, ci).concat(callbackList.slice(ci + 1));
  3863. newCallbackList.nativeHandler = nativeHandler;
  3864. newCallbackList.fakeName = fakeName;
  3865. newCallbackList.capture = capture;
  3866. eventMap[name] = newCallbackList;
  3867. }
  3868. }
  3869. }
  3870. if (!callback || callbackList.length === 0) {
  3871. delete eventMap[name];
  3872. removeEvent(target, callbackList.fakeName || name, callbackList.nativeHandler, callbackList.capture);
  3873. }
  3874. }
  3875. }
  3876. } else {
  3877. each$d(eventMap, (callbackList, name) => {
  3878. removeEvent(target, callbackList.fakeName || name, callbackList.nativeHandler, callbackList.capture);
  3879. });
  3880. eventMap = {};
  3881. }
  3882. for (const name in eventMap) {
  3883. if (has$2(eventMap, name)) {
  3884. return this;
  3885. }
  3886. }
  3887. delete this.events[id];
  3888. try {
  3889. delete target[this.expando];
  3890. } catch (ex) {
  3891. target[this.expando] = null;
  3892. }
  3893. }
  3894. return this;
  3895. }
  3896. fire(target, name, args) {
  3897. return this.dispatch(target, name, args);
  3898. }
  3899. dispatch(target, name, args) {
  3900. if (!target || isText$a(target) || isComment(target)) {
  3901. return this;
  3902. }
  3903. const event = fix({
  3904. type: name,
  3905. target
  3906. }, args);
  3907. do {
  3908. const id = target[this.expando];
  3909. if (id) {
  3910. this.executeHandlers(event, id);
  3911. }
  3912. target = target.parentNode || target.ownerDocument || target.defaultView || target.parentWindow;
  3913. } while (target && !event.isPropagationStopped());
  3914. return this;
  3915. }
  3916. clean(target) {
  3917. if (!target || isText$a(target) || isComment(target)) {
  3918. return this;
  3919. }
  3920. if (target[this.expando]) {
  3921. this.unbind(target);
  3922. }
  3923. if (!target.getElementsByTagName) {
  3924. target = target.document;
  3925. }
  3926. if (target && target.getElementsByTagName) {
  3927. this.unbind(target);
  3928. const children = target.getElementsByTagName('*');
  3929. let i = children.length;
  3930. while (i--) {
  3931. target = children[i];
  3932. if (target[this.expando]) {
  3933. this.unbind(target);
  3934. }
  3935. }
  3936. }
  3937. return this;
  3938. }
  3939. destroy() {
  3940. this.events = {};
  3941. }
  3942. cancel(e) {
  3943. if (e) {
  3944. e.preventDefault();
  3945. e.stopImmediatePropagation();
  3946. }
  3947. return false;
  3948. }
  3949. executeHandlers(evt, id) {
  3950. const container = this.events[id];
  3951. const callbackList = container && container[evt.type];
  3952. if (callbackList) {
  3953. for (let i = 0, l = callbackList.length; i < l; i++) {
  3954. const callback = callbackList[i];
  3955. if (callback && callback.func.call(callback.scope, evt) === false) {
  3956. evt.preventDefault();
  3957. }
  3958. if (evt.isImmediatePropagationStopped()) {
  3959. return;
  3960. }
  3961. }
  3962. }
  3963. }
  3964. }
  3965. EventUtils.Event = new EventUtils();
  3966. const each$a = Tools.each;
  3967. const grep = Tools.grep;
  3968. const internalStyleName = 'data-mce-style';
  3969. const numericalCssMap = Tools.makeMap('fill-opacity font-weight line-height opacity orphans widows z-index zoom', ' ');
  3970. const legacySetAttribute = (elm, name, value) => {
  3971. if (isNullable(value) || value === '') {
  3972. remove$b(elm, name);
  3973. } else {
  3974. set$3(elm, name, value);
  3975. }
  3976. };
  3977. const camelCaseToHyphens = name => name.replace(/[A-Z]/g, v => '-' + v.toLowerCase());
  3978. const findNodeIndex = (node, normalized) => {
  3979. let idx = 0;
  3980. if (node) {
  3981. for (let lastNodeType = node.nodeType, tempNode = node.previousSibling; tempNode; tempNode = tempNode.previousSibling) {
  3982. const nodeType = tempNode.nodeType;
  3983. if (normalized && isText$a(tempNode)) {
  3984. if (nodeType === lastNodeType || !tempNode.data.length) {
  3985. continue;
  3986. }
  3987. }
  3988. idx++;
  3989. lastNodeType = nodeType;
  3990. }
  3991. }
  3992. return idx;
  3993. };
  3994. const updateInternalStyleAttr = (styles, elm) => {
  3995. const rawValue = get$9(elm, 'style');
  3996. const value = styles.serialize(styles.parse(rawValue), name(elm));
  3997. legacySetAttribute(elm, internalStyleName, value);
  3998. };
  3999. const convertStyleToString = (cssValue, cssName) => {
  4000. if (isNumber(cssValue)) {
  4001. return has$2(numericalCssMap, cssName) ? cssValue + '' : cssValue + 'px';
  4002. } else {
  4003. return cssValue;
  4004. }
  4005. };
  4006. const applyStyle$1 = ($elm, cssName, cssValue) => {
  4007. const normalizedName = camelCaseToHyphens(cssName);
  4008. if (isNullable(cssValue) || cssValue === '') {
  4009. remove$7($elm, normalizedName);
  4010. } else {
  4011. set$2($elm, normalizedName, convertStyleToString(cssValue, normalizedName));
  4012. }
  4013. };
  4014. const setupAttrHooks = (styles, settings, getContext) => {
  4015. const keepValues = settings.keep_values;
  4016. const keepUrlHook = {
  4017. set: (elm, value, name) => {
  4018. const sugarElm = SugarElement.fromDom(elm);
  4019. if (isFunction(settings.url_converter) && isNonNullable(value)) {
  4020. value = settings.url_converter.call(settings.url_converter_scope || getContext(), String(value), name, elm);
  4021. }
  4022. const internalName = 'data-mce-' + name;
  4023. legacySetAttribute(sugarElm, internalName, value);
  4024. legacySetAttribute(sugarElm, name, value);
  4025. },
  4026. get: (elm, name) => {
  4027. const sugarElm = SugarElement.fromDom(elm);
  4028. return get$9(sugarElm, 'data-mce-' + name) || get$9(sugarElm, name);
  4029. }
  4030. };
  4031. const attrHooks = {
  4032. style: {
  4033. set: (elm, value) => {
  4034. const sugarElm = SugarElement.fromDom(elm);
  4035. if (keepValues) {
  4036. legacySetAttribute(sugarElm, internalStyleName, value);
  4037. }
  4038. remove$b(sugarElm, 'style');
  4039. if (isString(value)) {
  4040. setAll(sugarElm, styles.parse(value));
  4041. }
  4042. },
  4043. get: elm => {
  4044. const sugarElm = SugarElement.fromDom(elm);
  4045. const value = get$9(sugarElm, internalStyleName) || get$9(sugarElm, 'style');
  4046. return styles.serialize(styles.parse(value), name(sugarElm));
  4047. }
  4048. }
  4049. };
  4050. if (keepValues) {
  4051. attrHooks.href = attrHooks.src = keepUrlHook;
  4052. }
  4053. return attrHooks;
  4054. };
  4055. const DOMUtils = (doc, settings = {}) => {
  4056. const addedStyles = {};
  4057. const win = window;
  4058. const files = {};
  4059. let counter = 0;
  4060. const stdMode = true;
  4061. const boxModel = true;
  4062. const styleSheetLoader = instance.forElement(SugarElement.fromDom(doc), {
  4063. contentCssCors: settings.contentCssCors,
  4064. referrerPolicy: settings.referrerPolicy
  4065. });
  4066. const boundEvents = [];
  4067. const schema = settings.schema ? settings.schema : Schema({});
  4068. const styles = Styles({
  4069. url_converter: settings.url_converter,
  4070. url_converter_scope: settings.url_converter_scope
  4071. }, settings.schema);
  4072. const events = settings.ownEvents ? new EventUtils() : EventUtils.Event;
  4073. const blockElementsMap = schema.getBlockElements();
  4074. const isBlock = node => {
  4075. if (isString(node)) {
  4076. return has$2(blockElementsMap, node);
  4077. } else {
  4078. return isElement$6(node) && (has$2(blockElementsMap, node.nodeName) || isTransparentBlock(schema, node));
  4079. }
  4080. };
  4081. const get = elm => elm && doc && isString(elm) ? doc.getElementById(elm) : elm;
  4082. const _get = elm => {
  4083. const value = get(elm);
  4084. return isNonNullable(value) ? SugarElement.fromDom(value) : null;
  4085. };
  4086. const getAttrib = (elm, name, defaultVal = '') => {
  4087. let value;
  4088. const $elm = _get(elm);
  4089. if (isNonNullable($elm) && isElement$7($elm)) {
  4090. const hook = attrHooks[name];
  4091. if (hook && hook.get) {
  4092. value = hook.get($elm.dom, name);
  4093. } else {
  4094. value = get$9($elm, name);
  4095. }
  4096. }
  4097. return isNonNullable(value) ? value : defaultVal;
  4098. };
  4099. const getAttribs = elm => {
  4100. const node = get(elm);
  4101. return isNullable(node) ? [] : node.attributes;
  4102. };
  4103. const setAttrib = (elm, name, value) => {
  4104. run(elm, e => {
  4105. if (isElement$6(e)) {
  4106. const $elm = SugarElement.fromDom(e);
  4107. const val = value === '' ? null : value;
  4108. const originalValue = get$9($elm, name);
  4109. const hook = attrHooks[name];
  4110. if (hook && hook.set) {
  4111. hook.set($elm.dom, val, name);
  4112. } else {
  4113. legacySetAttribute($elm, name, val);
  4114. }
  4115. if (originalValue !== val && settings.onSetAttrib) {
  4116. settings.onSetAttrib({
  4117. attrElm: $elm.dom,
  4118. attrName: name,
  4119. attrValue: val
  4120. });
  4121. }
  4122. }
  4123. });
  4124. };
  4125. const clone = (node, deep) => {
  4126. return node.cloneNode(deep);
  4127. };
  4128. const getRoot = () => settings.root_element || doc.body;
  4129. const getViewPort = argWin => {
  4130. const vp = getBounds(argWin);
  4131. return {
  4132. x: vp.x,
  4133. y: vp.y,
  4134. w: vp.width,
  4135. h: vp.height
  4136. };
  4137. };
  4138. const getPos$1 = (elm, rootElm) => getPos(doc.body, get(elm), rootElm);
  4139. const setStyle = (elm, name, value) => {
  4140. run(elm, e => {
  4141. const $elm = SugarElement.fromDom(e);
  4142. applyStyle$1($elm, name, value);
  4143. if (settings.update_styles) {
  4144. updateInternalStyleAttr(styles, $elm);
  4145. }
  4146. });
  4147. };
  4148. const setStyles = (elm, stylesArg) => {
  4149. run(elm, e => {
  4150. const $elm = SugarElement.fromDom(e);
  4151. each$d(stylesArg, (v, n) => {
  4152. applyStyle$1($elm, n, v);
  4153. });
  4154. if (settings.update_styles) {
  4155. updateInternalStyleAttr(styles, $elm);
  4156. }
  4157. });
  4158. };
  4159. const getStyle = (elm, name, computed) => {
  4160. const $elm = get(elm);
  4161. if (isNullable($elm) || !isElement$6($elm)) {
  4162. return undefined;
  4163. }
  4164. if (computed) {
  4165. return get$7(SugarElement.fromDom($elm), camelCaseToHyphens(name));
  4166. } else {
  4167. name = name.replace(/-(\D)/g, (a, b) => b.toUpperCase());
  4168. if (name === 'float') {
  4169. name = 'cssFloat';
  4170. }
  4171. return $elm.style ? $elm.style[name] : undefined;
  4172. }
  4173. };
  4174. const getSize = elm => {
  4175. const $elm = get(elm);
  4176. if (!$elm) {
  4177. return {
  4178. w: 0,
  4179. h: 0
  4180. };
  4181. }
  4182. let w = getStyle($elm, 'width');
  4183. let h = getStyle($elm, 'height');
  4184. if (!w || w.indexOf('px') === -1) {
  4185. w = '0';
  4186. }
  4187. if (!h || h.indexOf('px') === -1) {
  4188. h = '0';
  4189. }
  4190. return {
  4191. w: parseInt(w, 10) || $elm.offsetWidth || $elm.clientWidth,
  4192. h: parseInt(h, 10) || $elm.offsetHeight || $elm.clientHeight
  4193. };
  4194. };
  4195. const getRect = elm => {
  4196. const $elm = get(elm);
  4197. const pos = getPos$1($elm);
  4198. const size = getSize($elm);
  4199. return {
  4200. x: pos.x,
  4201. y: pos.y,
  4202. w: size.w,
  4203. h: size.h
  4204. };
  4205. };
  4206. const is = (elm, selector) => {
  4207. if (!elm) {
  4208. return false;
  4209. }
  4210. const elms = isArray$1(elm) ? elm : [elm];
  4211. return exists(elms, e => {
  4212. return is$1(SugarElement.fromDom(e), selector);
  4213. });
  4214. };
  4215. const getParents = (elm, selector, root, collect) => {
  4216. const result = [];
  4217. let node = get(elm);
  4218. collect = collect === undefined;
  4219. const resolvedRoot = root || (getRoot().nodeName !== 'BODY' ? getRoot().parentNode : null);
  4220. if (isString(selector)) {
  4221. if (selector === '*') {
  4222. selector = isElement$6;
  4223. } else {
  4224. const selectorVal = selector;
  4225. selector = node => is(node, selectorVal);
  4226. }
  4227. }
  4228. while (node) {
  4229. if (node === resolvedRoot || isNullable(node.nodeType) || isDocument$1(node) || isDocumentFragment(node)) {
  4230. break;
  4231. }
  4232. if (!selector || selector(node)) {
  4233. if (collect) {
  4234. result.push(node);
  4235. } else {
  4236. return [node];
  4237. }
  4238. }
  4239. node = node.parentNode;
  4240. }
  4241. return collect ? result : null;
  4242. };
  4243. const getParent = (node, selector, root) => {
  4244. const parents = getParents(node, selector, root, false);
  4245. return parents && parents.length > 0 ? parents[0] : null;
  4246. };
  4247. const _findSib = (node, selector, name) => {
  4248. let func = selector;
  4249. if (node) {
  4250. if (isString(selector)) {
  4251. func = node => {
  4252. return is(node, selector);
  4253. };
  4254. }
  4255. for (let tempNode = node[name]; tempNode; tempNode = tempNode[name]) {
  4256. if (isFunction(func) && func(tempNode)) {
  4257. return tempNode;
  4258. }
  4259. }
  4260. }
  4261. return null;
  4262. };
  4263. const getNext = (node, selector) => _findSib(node, selector, 'nextSibling');
  4264. const getPrev = (node, selector) => _findSib(node, selector, 'previousSibling');
  4265. const isParentNode = node => isFunction(node.querySelectorAll);
  4266. const select = (selector, scope) => {
  4267. var _a, _b;
  4268. const elm = (_b = (_a = get(scope)) !== null && _a !== void 0 ? _a : settings.root_element) !== null && _b !== void 0 ? _b : doc;
  4269. return isParentNode(elm) ? from(elm.querySelectorAll(selector)) : [];
  4270. };
  4271. const run = function (elm, func, scope) {
  4272. const context = scope !== null && scope !== void 0 ? scope : this;
  4273. if (isArray$1(elm)) {
  4274. const result = [];
  4275. each$a(elm, (e, i) => {
  4276. const node = get(e);
  4277. if (node) {
  4278. result.push(func.call(context, node, i));
  4279. }
  4280. });
  4281. return result;
  4282. } else {
  4283. const node = get(elm);
  4284. return !node ? false : func.call(context, node);
  4285. }
  4286. };
  4287. const setAttribs = (elm, attrs) => {
  4288. run(elm, $elm => {
  4289. each$d(attrs, (value, name) => {
  4290. setAttrib($elm, name, value);
  4291. });
  4292. });
  4293. };
  4294. const setHTML = (elm, html) => {
  4295. run(elm, e => {
  4296. const $elm = SugarElement.fromDom(e);
  4297. set$1($elm, html);
  4298. });
  4299. };
  4300. const add = (parentElm, name, attrs, html, create) => run(parentElm, parentElm => {
  4301. const newElm = isString(name) ? doc.createElement(name) : name;
  4302. if (isNonNullable(attrs)) {
  4303. setAttribs(newElm, attrs);
  4304. }
  4305. if (html) {
  4306. if (!isString(html) && html.nodeType) {
  4307. newElm.appendChild(html);
  4308. } else if (isString(html)) {
  4309. setHTML(newElm, html);
  4310. }
  4311. }
  4312. return !create ? parentElm.appendChild(newElm) : newElm;
  4313. });
  4314. const create = (name, attrs, html) => add(doc.createElement(name), name, attrs, html, true);
  4315. const decode = Entities.decode;
  4316. const encode = Entities.encodeAllRaw;
  4317. const createHTML = (name, attrs, html = '') => {
  4318. let outHtml = '<' + name;
  4319. for (const key in attrs) {
  4320. if (hasNonNullableKey(attrs, key)) {
  4321. outHtml += ' ' + key + '="' + encode(attrs[key]) + '"';
  4322. }
  4323. }
  4324. if (isEmpty$3(html) && has$2(schema.getVoidElements(), name)) {
  4325. return outHtml + ' />';
  4326. } else {
  4327. return outHtml + '>' + html + '</' + name + '>';
  4328. }
  4329. };
  4330. const createFragment = html => {
  4331. const container = doc.createElement('div');
  4332. const frag = doc.createDocumentFragment();
  4333. frag.appendChild(container);
  4334. if (html) {
  4335. container.innerHTML = html;
  4336. }
  4337. let node;
  4338. while (node = container.firstChild) {
  4339. frag.appendChild(node);
  4340. }
  4341. frag.removeChild(container);
  4342. return frag;
  4343. };
  4344. const remove = (node, keepChildren) => {
  4345. return run(node, n => {
  4346. const $node = SugarElement.fromDom(n);
  4347. if (keepChildren) {
  4348. each$e(children$1($node), child => {
  4349. if (isText$b(child) && child.dom.length === 0) {
  4350. remove$6(child);
  4351. } else {
  4352. before$3($node, child);
  4353. }
  4354. });
  4355. }
  4356. remove$6($node);
  4357. return $node.dom;
  4358. });
  4359. };
  4360. const removeAllAttribs = e => run(e, e => {
  4361. const attrs = e.attributes;
  4362. for (let i = attrs.length - 1; i >= 0; i--) {
  4363. e.removeAttributeNode(attrs.item(i));
  4364. }
  4365. });
  4366. const parseStyle = cssText => styles.parse(cssText);
  4367. const serializeStyle = (stylesArg, name) => styles.serialize(stylesArg, name);
  4368. const addStyle = cssText => {
  4369. if (self !== DOMUtils.DOM && doc === document) {
  4370. if (addedStyles[cssText]) {
  4371. return;
  4372. }
  4373. addedStyles[cssText] = true;
  4374. }
  4375. let styleElm = doc.getElementById('mceDefaultStyles');
  4376. if (!styleElm) {
  4377. styleElm = doc.createElement('style');
  4378. styleElm.id = 'mceDefaultStyles';
  4379. styleElm.type = 'text/css';
  4380. const head = doc.head;
  4381. if (head.firstChild) {
  4382. head.insertBefore(styleElm, head.firstChild);
  4383. } else {
  4384. head.appendChild(styleElm);
  4385. }
  4386. }
  4387. if (styleElm.styleSheet) {
  4388. styleElm.styleSheet.cssText += cssText;
  4389. } else {
  4390. styleElm.appendChild(doc.createTextNode(cssText));
  4391. }
  4392. };
  4393. const loadCSS = urls => {
  4394. if (!urls) {
  4395. urls = '';
  4396. }
  4397. each$e(urls.split(','), url => {
  4398. files[url] = true;
  4399. styleSheetLoader.load(url).catch(noop);
  4400. });
  4401. };
  4402. const toggleClass = (elm, cls, state) => {
  4403. run(elm, e => {
  4404. if (isElement$6(e)) {
  4405. const $elm = SugarElement.fromDom(e);
  4406. const classes = cls.split(' ');
  4407. each$e(classes, c => {
  4408. if (isNonNullable(state)) {
  4409. const fn = state ? add$2 : remove$8;
  4410. fn($elm, c);
  4411. } else {
  4412. toggle$1($elm, c);
  4413. }
  4414. });
  4415. }
  4416. });
  4417. };
  4418. const addClass = (elm, cls) => {
  4419. toggleClass(elm, cls, true);
  4420. };
  4421. const removeClass = (elm, cls) => {
  4422. toggleClass(elm, cls, false);
  4423. };
  4424. const hasClass = (elm, cls) => {
  4425. const $elm = _get(elm);
  4426. const classes = cls.split(' ');
  4427. return isNonNullable($elm) && forall(classes, c => has($elm, c));
  4428. };
  4429. const show = elm => {
  4430. run(elm, e => remove$7(SugarElement.fromDom(e), 'display'));
  4431. };
  4432. const hide = elm => {
  4433. run(elm, e => set$2(SugarElement.fromDom(e), 'display', 'none'));
  4434. };
  4435. const isHidden = elm => {
  4436. const $elm = _get(elm);
  4437. return isNonNullable($elm) && is$2(getRaw($elm, 'display'), 'none');
  4438. };
  4439. const uniqueId = prefix => (!prefix ? 'mce_' : prefix) + counter++;
  4440. const getOuterHTML = elm => {
  4441. const $elm = _get(elm);
  4442. if (isNonNullable($elm)) {
  4443. return isElement$6($elm.dom) ? $elm.dom.outerHTML : getOuter($elm);
  4444. } else {
  4445. return '';
  4446. }
  4447. };
  4448. const setOuterHTML = (elm, html) => {
  4449. run(elm, $elm => {
  4450. if (isElement$6($elm)) {
  4451. $elm.outerHTML = html;
  4452. }
  4453. });
  4454. };
  4455. const insertAfter = (node, reference) => {
  4456. const referenceNode = get(reference);
  4457. return run(node, node => {
  4458. const parent = referenceNode === null || referenceNode === void 0 ? void 0 : referenceNode.parentNode;
  4459. const nextSibling = referenceNode === null || referenceNode === void 0 ? void 0 : referenceNode.nextSibling;
  4460. if (parent) {
  4461. if (nextSibling) {
  4462. parent.insertBefore(node, nextSibling);
  4463. } else {
  4464. parent.appendChild(node);
  4465. }
  4466. }
  4467. return node;
  4468. });
  4469. };
  4470. const replace = (newElm, oldElm, keepChildren) => run(oldElm, elm => {
  4471. var _a;
  4472. const replacee = isArray$1(oldElm) ? newElm.cloneNode(true) : newElm;
  4473. if (keepChildren) {
  4474. each$a(grep(elm.childNodes), node => {
  4475. replacee.appendChild(node);
  4476. });
  4477. }
  4478. (_a = elm.parentNode) === null || _a === void 0 ? void 0 : _a.replaceChild(replacee, elm);
  4479. return elm;
  4480. });
  4481. const rename = (elm, name) => {
  4482. if (elm.nodeName !== name.toUpperCase()) {
  4483. const newElm = create(name);
  4484. each$a(getAttribs(elm), attrNode => {
  4485. setAttrib(newElm, attrNode.nodeName, getAttrib(elm, attrNode.nodeName));
  4486. });
  4487. replace(newElm, elm, true);
  4488. return newElm;
  4489. } else {
  4490. return elm;
  4491. }
  4492. };
  4493. const findCommonAncestor = (a, b) => {
  4494. let ps = a;
  4495. while (ps) {
  4496. let pe = b;
  4497. while (pe && ps !== pe) {
  4498. pe = pe.parentNode;
  4499. }
  4500. if (ps === pe) {
  4501. break;
  4502. }
  4503. ps = ps.parentNode;
  4504. }
  4505. if (!ps && a.ownerDocument) {
  4506. return a.ownerDocument.documentElement;
  4507. } else {
  4508. return ps;
  4509. }
  4510. };
  4511. const isNonEmptyElement = node => {
  4512. if (isElement$6(node)) {
  4513. const isNamedAnchor = node.nodeName.toLowerCase() === 'a' && !getAttrib(node, 'href') && getAttrib(node, 'id');
  4514. if (getAttrib(node, 'name') || getAttrib(node, 'data-mce-bookmark') || isNamedAnchor) {
  4515. return true;
  4516. }
  4517. }
  4518. return false;
  4519. };
  4520. const isEmpty = (node, elements) => {
  4521. let brCount = 0;
  4522. if (isNonEmptyElement(node)) {
  4523. return false;
  4524. }
  4525. const firstChild = node.firstChild;
  4526. if (firstChild) {
  4527. const walker = new DomTreeWalker(firstChild, node);
  4528. const whitespaceElements = schema ? schema.getWhitespaceElements() : {};
  4529. const nonEmptyElements = elements || (schema ? schema.getNonEmptyElements() : null);
  4530. let tempNode = firstChild;
  4531. do {
  4532. if (isElement$6(tempNode)) {
  4533. const bogusVal = tempNode.getAttribute('data-mce-bogus');
  4534. if (bogusVal) {
  4535. tempNode = walker.next(bogusVal === 'all');
  4536. continue;
  4537. }
  4538. const name = tempNode.nodeName.toLowerCase();
  4539. if (nonEmptyElements && nonEmptyElements[name]) {
  4540. if (name === 'br') {
  4541. brCount++;
  4542. tempNode = walker.next();
  4543. continue;
  4544. }
  4545. return false;
  4546. }
  4547. if (isNonEmptyElement(tempNode)) {
  4548. return false;
  4549. }
  4550. }
  4551. if (isComment(tempNode)) {
  4552. return false;
  4553. }
  4554. if (isText$a(tempNode) && !isWhitespaceText(tempNode.data)) {
  4555. return false;
  4556. }
  4557. if (isText$a(tempNode) && tempNode.parentNode && whitespaceElements[tempNode.parentNode.nodeName] && isWhitespaceText(tempNode.data)) {
  4558. return false;
  4559. }
  4560. tempNode = walker.next();
  4561. } while (tempNode);
  4562. }
  4563. return brCount <= 1;
  4564. };
  4565. const createRng = () => doc.createRange();
  4566. const split = (parentElm, splitElm, replacementElm) => {
  4567. let range = createRng();
  4568. let beforeFragment;
  4569. let afterFragment;
  4570. if (parentElm && splitElm && parentElm.parentNode && splitElm.parentNode) {
  4571. const parentNode = parentElm.parentNode;
  4572. range.setStart(parentNode, findNodeIndex(parentElm));
  4573. range.setEnd(splitElm.parentNode, findNodeIndex(splitElm));
  4574. beforeFragment = range.extractContents();
  4575. range = createRng();
  4576. range.setStart(splitElm.parentNode, findNodeIndex(splitElm) + 1);
  4577. range.setEnd(parentNode, findNodeIndex(parentElm) + 1);
  4578. afterFragment = range.extractContents();
  4579. parentNode.insertBefore(trimNode(self, beforeFragment), parentElm);
  4580. if (replacementElm) {
  4581. parentNode.insertBefore(replacementElm, parentElm);
  4582. } else {
  4583. parentNode.insertBefore(splitElm, parentElm);
  4584. }
  4585. parentNode.insertBefore(trimNode(self, afterFragment), parentElm);
  4586. remove(parentElm);
  4587. return replacementElm || splitElm;
  4588. } else {
  4589. return undefined;
  4590. }
  4591. };
  4592. const bind = (target, name, func, scope) => {
  4593. if (isArray$1(target)) {
  4594. let i = target.length;
  4595. const rv = [];
  4596. while (i--) {
  4597. rv[i] = bind(target[i], name, func, scope);
  4598. }
  4599. return rv;
  4600. } else {
  4601. if (settings.collect && (target === doc || target === win)) {
  4602. boundEvents.push([
  4603. target,
  4604. name,
  4605. func,
  4606. scope
  4607. ]);
  4608. }
  4609. return events.bind(target, name, func, scope || self);
  4610. }
  4611. };
  4612. const unbind = (target, name, func) => {
  4613. if (isArray$1(target)) {
  4614. let i = target.length;
  4615. const rv = [];
  4616. while (i--) {
  4617. rv[i] = unbind(target[i], name, func);
  4618. }
  4619. return rv;
  4620. } else {
  4621. if (boundEvents.length > 0 && (target === doc || target === win)) {
  4622. let i = boundEvents.length;
  4623. while (i--) {
  4624. const [boundTarget, boundName, boundFunc] = boundEvents[i];
  4625. if (target === boundTarget && (!name || name === boundName) && (!func || func === boundFunc)) {
  4626. events.unbind(boundTarget, boundName, boundFunc);
  4627. }
  4628. }
  4629. }
  4630. return events.unbind(target, name, func);
  4631. }
  4632. };
  4633. const dispatch = (target, name, evt) => events.dispatch(target, name, evt);
  4634. const fire = (target, name, evt) => events.dispatch(target, name, evt);
  4635. const getContentEditable = node => {
  4636. if (node && isElement$6(node)) {
  4637. const contentEditable = node.getAttribute('data-mce-contenteditable');
  4638. if (contentEditable && contentEditable !== 'inherit') {
  4639. return contentEditable;
  4640. }
  4641. return node.contentEditable !== 'inherit' ? node.contentEditable : null;
  4642. } else {
  4643. return null;
  4644. }
  4645. };
  4646. const getContentEditableParent = node => {
  4647. const root = getRoot();
  4648. let state = null;
  4649. for (let tempNode = node; tempNode && tempNode !== root; tempNode = tempNode.parentNode) {
  4650. state = getContentEditable(tempNode);
  4651. if (state !== null) {
  4652. break;
  4653. }
  4654. }
  4655. return state;
  4656. };
  4657. const isEditable = node => {
  4658. if (isNonNullable(node)) {
  4659. const scope = isElement$6(node) ? node : node.parentElement;
  4660. const isRootEditable = getContentEditable(getRoot()) === 'true';
  4661. return isNonNullable(scope) && isEditable$3(SugarElement.fromDom(scope), isRootEditable);
  4662. } else {
  4663. return false;
  4664. }
  4665. };
  4666. const destroy = () => {
  4667. if (boundEvents.length > 0) {
  4668. let i = boundEvents.length;
  4669. while (i--) {
  4670. const [boundTarget, boundName, boundFunc] = boundEvents[i];
  4671. events.unbind(boundTarget, boundName, boundFunc);
  4672. }
  4673. }
  4674. each$d(files, (_, url) => {
  4675. styleSheetLoader.unload(url);
  4676. delete files[url];
  4677. });
  4678. };
  4679. const isChildOf = (node, parent) => {
  4680. return node === parent || parent.contains(node);
  4681. };
  4682. const dumpRng = r => 'startContainer: ' + r.startContainer.nodeName + ', startOffset: ' + r.startOffset + ', endContainer: ' + r.endContainer.nodeName + ', endOffset: ' + r.endOffset;
  4683. const self = {
  4684. doc,
  4685. settings,
  4686. win,
  4687. files,
  4688. stdMode,
  4689. boxModel,
  4690. styleSheetLoader,
  4691. boundEvents,
  4692. styles,
  4693. schema,
  4694. events,
  4695. isBlock: isBlock,
  4696. root: null,
  4697. clone,
  4698. getRoot,
  4699. getViewPort,
  4700. getRect,
  4701. getSize,
  4702. getParent,
  4703. getParents: getParents,
  4704. get,
  4705. getNext,
  4706. getPrev,
  4707. select,
  4708. is,
  4709. add,
  4710. create,
  4711. createHTML,
  4712. createFragment,
  4713. remove,
  4714. setStyle,
  4715. getStyle: getStyle,
  4716. setStyles,
  4717. removeAllAttribs,
  4718. setAttrib,
  4719. setAttribs,
  4720. getAttrib,
  4721. getPos: getPos$1,
  4722. parseStyle,
  4723. serializeStyle,
  4724. addStyle,
  4725. loadCSS,
  4726. addClass,
  4727. removeClass,
  4728. hasClass,
  4729. toggleClass,
  4730. show,
  4731. hide,
  4732. isHidden,
  4733. uniqueId,
  4734. setHTML,
  4735. getOuterHTML,
  4736. setOuterHTML,
  4737. decode,
  4738. encode,
  4739. insertAfter,
  4740. replace,
  4741. rename,
  4742. findCommonAncestor,
  4743. run,
  4744. getAttribs,
  4745. isEmpty,
  4746. createRng,
  4747. nodeIndex: findNodeIndex,
  4748. split,
  4749. bind: bind,
  4750. unbind: unbind,
  4751. fire,
  4752. dispatch,
  4753. getContentEditable,
  4754. getContentEditableParent,
  4755. isEditable,
  4756. destroy,
  4757. isChildOf,
  4758. dumpRng
  4759. };
  4760. const attrHooks = setupAttrHooks(styles, settings, constant(self));
  4761. return self;
  4762. };
  4763. DOMUtils.DOM = DOMUtils(document);
  4764. DOMUtils.nodeIndex = findNodeIndex;
  4765. const DOM$b = DOMUtils.DOM;
  4766. const QUEUED = 0;
  4767. const LOADING = 1;
  4768. const LOADED = 2;
  4769. const FAILED = 3;
  4770. class ScriptLoader {
  4771. constructor(settings = {}) {
  4772. this.states = {};
  4773. this.queue = [];
  4774. this.scriptLoadedCallbacks = {};
  4775. this.queueLoadedCallbacks = [];
  4776. this.loading = false;
  4777. this.settings = settings;
  4778. }
  4779. _setReferrerPolicy(referrerPolicy) {
  4780. this.settings.referrerPolicy = referrerPolicy;
  4781. }
  4782. loadScript(url) {
  4783. return new Promise((resolve, reject) => {
  4784. const dom = DOM$b;
  4785. let elm;
  4786. const cleanup = () => {
  4787. dom.remove(id);
  4788. if (elm) {
  4789. elm.onerror = elm.onload = elm = null;
  4790. }
  4791. };
  4792. const done = () => {
  4793. cleanup();
  4794. resolve();
  4795. };
  4796. const error = () => {
  4797. cleanup();
  4798. reject('Failed to load script: ' + url);
  4799. };
  4800. const id = dom.uniqueId();
  4801. elm = document.createElement('script');
  4802. elm.id = id;
  4803. elm.type = 'text/javascript';
  4804. elm.src = Tools._addCacheSuffix(url);
  4805. if (this.settings.referrerPolicy) {
  4806. dom.setAttrib(elm, 'referrerpolicy', this.settings.referrerPolicy);
  4807. }
  4808. elm.onload = done;
  4809. elm.onerror = error;
  4810. (document.getElementsByTagName('head')[0] || document.body).appendChild(elm);
  4811. });
  4812. }
  4813. isDone(url) {
  4814. return this.states[url] === LOADED;
  4815. }
  4816. markDone(url) {
  4817. this.states[url] = LOADED;
  4818. }
  4819. add(url) {
  4820. const self = this;
  4821. self.queue.push(url);
  4822. const state = self.states[url];
  4823. if (state === undefined) {
  4824. self.states[url] = QUEUED;
  4825. }
  4826. return new Promise((resolve, reject) => {
  4827. if (!self.scriptLoadedCallbacks[url]) {
  4828. self.scriptLoadedCallbacks[url] = [];
  4829. }
  4830. self.scriptLoadedCallbacks[url].push({
  4831. resolve,
  4832. reject
  4833. });
  4834. });
  4835. }
  4836. load(url) {
  4837. return this.add(url);
  4838. }
  4839. remove(url) {
  4840. delete this.states[url];
  4841. delete this.scriptLoadedCallbacks[url];
  4842. }
  4843. loadQueue() {
  4844. const queue = this.queue;
  4845. this.queue = [];
  4846. return this.loadScripts(queue);
  4847. }
  4848. loadScripts(scripts) {
  4849. const self = this;
  4850. const execCallbacks = (name, url) => {
  4851. get$a(self.scriptLoadedCallbacks, url).each(callbacks => {
  4852. each$e(callbacks, callback => callback[name](url));
  4853. });
  4854. delete self.scriptLoadedCallbacks[url];
  4855. };
  4856. const processResults = results => {
  4857. const failures = filter$5(results, result => result.status === 'rejected');
  4858. if (failures.length > 0) {
  4859. return Promise.reject(bind$3(failures, ({reason}) => isArray$1(reason) ? reason : [reason]));
  4860. } else {
  4861. return Promise.resolve();
  4862. }
  4863. };
  4864. const load = urls => Promise.allSettled(map$3(urls, url => {
  4865. if (self.states[url] === LOADED) {
  4866. execCallbacks('resolve', url);
  4867. return Promise.resolve();
  4868. } else if (self.states[url] === FAILED) {
  4869. execCallbacks('reject', url);
  4870. return Promise.reject(url);
  4871. } else {
  4872. self.states[url] = LOADING;
  4873. return self.loadScript(url).then(() => {
  4874. self.states[url] = LOADED;
  4875. execCallbacks('resolve', url);
  4876. const queue = self.queue;
  4877. if (queue.length > 0) {
  4878. self.queue = [];
  4879. return load(queue).then(processResults);
  4880. } else {
  4881. return Promise.resolve();
  4882. }
  4883. }, () => {
  4884. self.states[url] = FAILED;
  4885. execCallbacks('reject', url);
  4886. return Promise.reject(url);
  4887. });
  4888. }
  4889. }));
  4890. const processQueue = urls => {
  4891. self.loading = true;
  4892. return load(urls).then(results => {
  4893. self.loading = false;
  4894. const nextQueuedItem = self.queueLoadedCallbacks.shift();
  4895. Optional.from(nextQueuedItem).each(call);
  4896. return processResults(results);
  4897. });
  4898. };
  4899. const uniqueScripts = stringArray(scripts);
  4900. if (self.loading) {
  4901. return new Promise((resolve, reject) => {
  4902. self.queueLoadedCallbacks.push(() => processQueue(uniqueScripts).then(resolve, reject));
  4903. });
  4904. } else {
  4905. return processQueue(uniqueScripts);
  4906. }
  4907. }
  4908. }
  4909. ScriptLoader.ScriptLoader = new ScriptLoader();
  4910. const Cell = initial => {
  4911. let value = initial;
  4912. const get = () => {
  4913. return value;
  4914. };
  4915. const set = v => {
  4916. value = v;
  4917. };
  4918. return {
  4919. get,
  4920. set
  4921. };
  4922. };
  4923. const isRaw = str => isObject(str) && has$2(str, 'raw');
  4924. const isTokenised = str => isArray$1(str) && str.length > 1;
  4925. const data = {};
  4926. const currentCode = Cell('en');
  4927. const getLanguageData = () => get$a(data, currentCode.get());
  4928. const getData$1 = () => map$2(data, value => ({ ...value }));
  4929. const setCode = newCode => {
  4930. if (newCode) {
  4931. currentCode.set(newCode);
  4932. }
  4933. };
  4934. const getCode = () => currentCode.get();
  4935. const add$1 = (code, items) => {
  4936. let langData = data[code];
  4937. if (!langData) {
  4938. data[code] = langData = {};
  4939. }
  4940. each$d(items, (translation, name) => {
  4941. langData[name.toLowerCase()] = translation;
  4942. });
  4943. };
  4944. const translate = text => {
  4945. const langData = getLanguageData().getOr({});
  4946. const toString = obj => {
  4947. if (isFunction(obj)) {
  4948. return Object.prototype.toString.call(obj);
  4949. }
  4950. return !isEmpty(obj) ? '' + obj : '';
  4951. };
  4952. const isEmpty = text => text === '' || text === null || text === undefined;
  4953. const getLangData = text => {
  4954. const textstr = toString(text);
  4955. return get$a(langData, textstr.toLowerCase()).map(toString).getOr(textstr);
  4956. };
  4957. const removeContext = str => str.replace(/{context:\w+}$/, '');
  4958. if (isEmpty(text)) {
  4959. return '';
  4960. }
  4961. if (isRaw(text)) {
  4962. return toString(text.raw);
  4963. }
  4964. if (isTokenised(text)) {
  4965. const values = text.slice(1);
  4966. const substitued = getLangData(text[0]).replace(/\{([0-9]+)\}/g, ($1, $2) => has$2(values, $2) ? toString(values[$2]) : $1);
  4967. return removeContext(substitued);
  4968. }
  4969. return removeContext(getLangData(text));
  4970. };
  4971. const isRtl$1 = () => getLanguageData().bind(items => get$a(items, '_dir')).exists(dir => dir === 'rtl');
  4972. const hasCode = code => has$2(data, code);
  4973. const I18n = {
  4974. getData: getData$1,
  4975. setCode,
  4976. getCode,
  4977. add: add$1,
  4978. translate,
  4979. isRtl: isRtl$1,
  4980. hasCode
  4981. };
  4982. const AddOnManager = () => {
  4983. const items = [];
  4984. const urls = {};
  4985. const lookup = {};
  4986. const _listeners = [];
  4987. const runListeners = (name, state) => {
  4988. const matchedListeners = filter$5(_listeners, listener => listener.name === name && listener.state === state);
  4989. each$e(matchedListeners, listener => listener.resolve());
  4990. };
  4991. const isLoaded = name => has$2(urls, name);
  4992. const isAdded = name => has$2(lookup, name);
  4993. const get = name => {
  4994. if (lookup[name]) {
  4995. return lookup[name].instance;
  4996. }
  4997. return undefined;
  4998. };
  4999. const loadLanguagePack = (name, languages) => {
  5000. const language = I18n.getCode();
  5001. const wrappedLanguages = ',' + (languages || '') + ',';
  5002. if (!language || languages && wrappedLanguages.indexOf(',' + language + ',') === -1) {
  5003. return;
  5004. }
  5005. ScriptLoader.ScriptLoader.add(urls[name] + '/langs/' + language + '.js');
  5006. };
  5007. const requireLangPack = (name, languages) => {
  5008. if (AddOnManager.languageLoad !== false) {
  5009. if (isLoaded(name)) {
  5010. loadLanguagePack(name, languages);
  5011. } else {
  5012. waitFor(name, 'loaded').then(() => loadLanguagePack(name, languages));
  5013. }
  5014. }
  5015. };
  5016. const add = (id, addOn) => {
  5017. items.push(addOn);
  5018. lookup[id] = { instance: addOn };
  5019. runListeners(id, 'added');
  5020. return addOn;
  5021. };
  5022. const remove = name => {
  5023. delete urls[name];
  5024. delete lookup[name];
  5025. };
  5026. const createUrl = (baseUrl, dep) => {
  5027. if (isString(dep)) {
  5028. return isString(baseUrl) ? {
  5029. prefix: '',
  5030. resource: dep,
  5031. suffix: ''
  5032. } : {
  5033. prefix: baseUrl.prefix,
  5034. resource: dep,
  5035. suffix: baseUrl.suffix
  5036. };
  5037. } else {
  5038. return dep;
  5039. }
  5040. };
  5041. const load = (name, addOnUrl) => {
  5042. if (urls[name]) {
  5043. return Promise.resolve();
  5044. }
  5045. let urlString = isString(addOnUrl) ? addOnUrl : addOnUrl.prefix + addOnUrl.resource + addOnUrl.suffix;
  5046. if (urlString.indexOf('/') !== 0 && urlString.indexOf('://') === -1) {
  5047. urlString = AddOnManager.baseURL + '/' + urlString;
  5048. }
  5049. urls[name] = urlString.substring(0, urlString.lastIndexOf('/'));
  5050. const done = () => {
  5051. runListeners(name, 'loaded');
  5052. return Promise.resolve();
  5053. };
  5054. if (lookup[name]) {
  5055. return done();
  5056. } else {
  5057. return ScriptLoader.ScriptLoader.add(urlString).then(done);
  5058. }
  5059. };
  5060. const waitFor = (name, state = 'added') => {
  5061. if (state === 'added' && isAdded(name)) {
  5062. return Promise.resolve();
  5063. } else if (state === 'loaded' && isLoaded(name)) {
  5064. return Promise.resolve();
  5065. } else {
  5066. return new Promise(resolve => {
  5067. _listeners.push({
  5068. name,
  5069. state,
  5070. resolve
  5071. });
  5072. });
  5073. }
  5074. };
  5075. return {
  5076. items,
  5077. urls,
  5078. lookup,
  5079. get,
  5080. requireLangPack,
  5081. add,
  5082. remove,
  5083. createUrl,
  5084. load,
  5085. waitFor
  5086. };
  5087. };
  5088. AddOnManager.languageLoad = true;
  5089. AddOnManager.baseURL = '';
  5090. AddOnManager.PluginManager = AddOnManager();
  5091. AddOnManager.ThemeManager = AddOnManager();
  5092. AddOnManager.ModelManager = AddOnManager();
  5093. const singleton = doRevoke => {
  5094. const subject = Cell(Optional.none());
  5095. const revoke = () => subject.get().each(doRevoke);
  5096. const clear = () => {
  5097. revoke();
  5098. subject.set(Optional.none());
  5099. };
  5100. const isSet = () => subject.get().isSome();
  5101. const get = () => subject.get();
  5102. const set = s => {
  5103. revoke();
  5104. subject.set(Optional.some(s));
  5105. };
  5106. return {
  5107. clear,
  5108. isSet,
  5109. get,
  5110. set
  5111. };
  5112. };
  5113. const repeatable = delay => {
  5114. const intervalId = Cell(Optional.none());
  5115. const revoke = () => intervalId.get().each(id => clearInterval(id));
  5116. const clear = () => {
  5117. revoke();
  5118. intervalId.set(Optional.none());
  5119. };
  5120. const isSet = () => intervalId.get().isSome();
  5121. const get = () => intervalId.get();
  5122. const set = functionToRepeat => {
  5123. revoke();
  5124. intervalId.set(Optional.some(setInterval(functionToRepeat, delay)));
  5125. };
  5126. return {
  5127. clear,
  5128. isSet,
  5129. get,
  5130. set
  5131. };
  5132. };
  5133. const value$2 = () => {
  5134. const subject = singleton(noop);
  5135. const on = f => subject.get().each(f);
  5136. return {
  5137. ...subject,
  5138. on
  5139. };
  5140. };
  5141. const first$1 = (fn, rate) => {
  5142. let timer = null;
  5143. const cancel = () => {
  5144. if (!isNull(timer)) {
  5145. clearTimeout(timer);
  5146. timer = null;
  5147. }
  5148. };
  5149. const throttle = (...args) => {
  5150. if (isNull(timer)) {
  5151. timer = setTimeout(() => {
  5152. timer = null;
  5153. fn.apply(null, args);
  5154. }, rate);
  5155. }
  5156. };
  5157. return {
  5158. cancel,
  5159. throttle
  5160. };
  5161. };
  5162. const last$1 = (fn, rate) => {
  5163. let timer = null;
  5164. const cancel = () => {
  5165. if (!isNull(timer)) {
  5166. clearTimeout(timer);
  5167. timer = null;
  5168. }
  5169. };
  5170. const throttle = (...args) => {
  5171. cancel();
  5172. timer = setTimeout(() => {
  5173. timer = null;
  5174. fn.apply(null, args);
  5175. }, rate);
  5176. };
  5177. return {
  5178. cancel,
  5179. throttle
  5180. };
  5181. };
  5182. const annotation = constant('mce-annotation');
  5183. const dataAnnotation = constant('data-mce-annotation');
  5184. const dataAnnotationId = constant('data-mce-annotation-uid');
  5185. const dataAnnotationActive = constant('data-mce-annotation-active');
  5186. const dataAnnotationClasses = constant('data-mce-annotation-classes');
  5187. const dataAnnotationAttributes = constant('data-mce-annotation-attrs');
  5188. const isRoot$1 = root => node => eq(node, root);
  5189. const identify = (editor, annotationName) => {
  5190. const rng = editor.selection.getRng();
  5191. const start = SugarElement.fromDom(rng.startContainer);
  5192. const root = SugarElement.fromDom(editor.getBody());
  5193. const selector = annotationName.fold(() => '.' + annotation(), an => `[${ dataAnnotation() }="${ an }"]`);
  5194. const newStart = child$1(start, rng.startOffset).getOr(start);
  5195. const closest = closest$3(newStart, selector, isRoot$1(root));
  5196. return closest.bind(c => getOpt(c, `${ dataAnnotationId() }`).bind(uid => getOpt(c, `${ dataAnnotation() }`).map(name => {
  5197. const elements = findMarkers(editor, uid);
  5198. return {
  5199. uid,
  5200. name,
  5201. elements
  5202. };
  5203. })));
  5204. };
  5205. const isAnnotation = elem => isElement$7(elem) && has(elem, annotation());
  5206. const isBogusElement = (elem, root) => has$1(elem, 'data-mce-bogus') || ancestor$2(elem, '[data-mce-bogus="all"]', isRoot$1(root));
  5207. const findMarkers = (editor, uid) => {
  5208. const body = SugarElement.fromDom(editor.getBody());
  5209. const descendants$1 = descendants(body, `[${ dataAnnotationId() }="${ uid }"]`);
  5210. return filter$5(descendants$1, descendant => !isBogusElement(descendant, body));
  5211. };
  5212. const findAll = (editor, name) => {
  5213. const body = SugarElement.fromDom(editor.getBody());
  5214. const markers = descendants(body, `[${ dataAnnotation() }="${ name }"]`);
  5215. const directory = {};
  5216. each$e(markers, m => {
  5217. if (!isBogusElement(m, body)) {
  5218. const uid = get$9(m, dataAnnotationId());
  5219. const nodesAlready = get$a(directory, uid).getOr([]);
  5220. directory[uid] = nodesAlready.concat([m]);
  5221. }
  5222. });
  5223. return directory;
  5224. };
  5225. const setup$x = (editor, registry) => {
  5226. const changeCallbacks = Cell({});
  5227. const initData = () => ({
  5228. listeners: [],
  5229. previous: value$2()
  5230. });
  5231. const withCallbacks = (name, f) => {
  5232. updateCallbacks(name, data => {
  5233. f(data);
  5234. return data;
  5235. });
  5236. };
  5237. const updateCallbacks = (name, f) => {
  5238. const callbackMap = changeCallbacks.get();
  5239. const data = get$a(callbackMap, name).getOrThunk(initData);
  5240. const outputData = f(data);
  5241. callbackMap[name] = outputData;
  5242. changeCallbacks.set(callbackMap);
  5243. };
  5244. const fireCallbacks = (name, uid, elements) => {
  5245. withCallbacks(name, data => {
  5246. each$e(data.listeners, f => f(true, name, {
  5247. uid,
  5248. nodes: map$3(elements, elem => elem.dom)
  5249. }));
  5250. });
  5251. };
  5252. const fireNoAnnotation = name => {
  5253. withCallbacks(name, data => {
  5254. each$e(data.listeners, f => f(false, name));
  5255. });
  5256. };
  5257. const toggleActiveAttr = (uid, state) => {
  5258. each$e(findMarkers(editor, uid), elem => {
  5259. if (state) {
  5260. set$3(elem, dataAnnotationActive(), 'true');
  5261. } else {
  5262. remove$b(elem, dataAnnotationActive());
  5263. }
  5264. });
  5265. };
  5266. const onNodeChange = last$1(() => {
  5267. const annotations = sort(registry.getNames());
  5268. each$e(annotations, name => {
  5269. updateCallbacks(name, data => {
  5270. const prev = data.previous.get();
  5271. identify(editor, Optional.some(name)).fold(() => {
  5272. prev.each(uid => {
  5273. fireNoAnnotation(name);
  5274. data.previous.clear();
  5275. toggleActiveAttr(uid, false);
  5276. });
  5277. }, ({uid, name, elements}) => {
  5278. if (!is$2(prev, uid)) {
  5279. prev.each(uid => toggleActiveAttr(uid, false));
  5280. fireCallbacks(name, uid, elements);
  5281. data.previous.set(uid);
  5282. toggleActiveAttr(uid, true);
  5283. }
  5284. });
  5285. return {
  5286. previous: data.previous,
  5287. listeners: data.listeners
  5288. };
  5289. });
  5290. });
  5291. }, 30);
  5292. editor.on('remove', () => {
  5293. onNodeChange.cancel();
  5294. });
  5295. editor.on('NodeChange', () => {
  5296. onNodeChange.throttle();
  5297. });
  5298. const addListener = (name, f) => {
  5299. updateCallbacks(name, data => ({
  5300. previous: data.previous,
  5301. listeners: data.listeners.concat([f])
  5302. }));
  5303. };
  5304. return { addListener };
  5305. };
  5306. const setup$w = (editor, registry) => {
  5307. const dataAnnotation$1 = dataAnnotation();
  5308. const identifyParserNode = node => Optional.from(node.attr(dataAnnotation$1)).bind(registry.lookup);
  5309. const removeDirectAnnotation = node => {
  5310. var _a, _b;
  5311. node.attr(dataAnnotationId(), null);
  5312. node.attr(dataAnnotation(), null);
  5313. node.attr(dataAnnotationActive(), null);
  5314. const customAttrNames = Optional.from(node.attr(dataAnnotationAttributes())).map(names => names.split(',')).getOr([]);
  5315. const customClasses = Optional.from(node.attr(dataAnnotationClasses())).map(names => names.split(',')).getOr([]);
  5316. each$e(customAttrNames, name => node.attr(name, null));
  5317. const classList = (_b = (_a = node.attr('class')) === null || _a === void 0 ? void 0 : _a.split(' ')) !== null && _b !== void 0 ? _b : [];
  5318. const newClassList = difference(classList, [annotation()].concat(customClasses));
  5319. node.attr('class', newClassList.length > 0 ? newClassList.join(' ') : null);
  5320. node.attr(dataAnnotationClasses(), null);
  5321. node.attr(dataAnnotationAttributes(), null);
  5322. };
  5323. editor.serializer.addTempAttr(dataAnnotationActive());
  5324. editor.serializer.addAttributeFilter(dataAnnotation$1, nodes => {
  5325. for (const node of nodes) {
  5326. identifyParserNode(node).each(settings => {
  5327. if (settings.persistent === false) {
  5328. if (node.name === 'span') {
  5329. node.unwrap();
  5330. } else {
  5331. removeDirectAnnotation(node);
  5332. }
  5333. }
  5334. });
  5335. }
  5336. });
  5337. };
  5338. const create$c = () => {
  5339. const annotations = {};
  5340. const register = (name, settings) => {
  5341. annotations[name] = {
  5342. name,
  5343. settings
  5344. };
  5345. };
  5346. const lookup = name => get$a(annotations, name).map(a => a.settings);
  5347. const getNames = () => keys(annotations);
  5348. return {
  5349. register,
  5350. lookup,
  5351. getNames
  5352. };
  5353. };
  5354. let unique = 0;
  5355. const generate$1 = prefix => {
  5356. const date = new Date();
  5357. const time = date.getTime();
  5358. const random = Math.floor(Math.random() * 1000000000);
  5359. unique++;
  5360. return prefix + '_' + random + unique + String(time);
  5361. };
  5362. const add = (element, classes) => {
  5363. each$e(classes, x => {
  5364. add$2(element, x);
  5365. });
  5366. };
  5367. const remove$5 = (element, classes) => {
  5368. each$e(classes, x => {
  5369. remove$8(element, x);
  5370. });
  5371. };
  5372. const clone$2 = (original, isDeep) => SugarElement.fromDom(original.dom.cloneNode(isDeep));
  5373. const shallow$1 = original => clone$2(original, false);
  5374. const deep$1 = original => clone$2(original, true);
  5375. const shallowAs = (original, tag) => {
  5376. const nu = SugarElement.fromTag(tag);
  5377. const attributes = clone$4(original);
  5378. setAll$1(nu, attributes);
  5379. return nu;
  5380. };
  5381. const mutate = (original, tag) => {
  5382. const nu = shallowAs(original, tag);
  5383. after$4(original, nu);
  5384. const children = children$1(original);
  5385. append(nu, children);
  5386. remove$6(original);
  5387. return nu;
  5388. };
  5389. const TextWalker = (startNode, rootNode, isBoundary = never) => {
  5390. const walker = new DomTreeWalker(startNode, rootNode);
  5391. const walk = direction => {
  5392. let next;
  5393. do {
  5394. next = walker[direction]();
  5395. } while (next && !isText$a(next) && !isBoundary(next));
  5396. return Optional.from(next).filter(isText$a);
  5397. };
  5398. return {
  5399. current: () => Optional.from(walker.current()).filter(isText$a),
  5400. next: () => walk('next'),
  5401. prev: () => walk('prev'),
  5402. prev2: () => walk('prev2')
  5403. };
  5404. };
  5405. const TextSeeker = (dom, isBoundary) => {
  5406. const isBlockBoundary = isBoundary ? isBoundary : node => dom.isBlock(node) || isBr$6(node) || isContentEditableFalse$b(node);
  5407. const walk = (node, offset, walker, process) => {
  5408. if (isText$a(node)) {
  5409. const newOffset = process(node, offset, node.data);
  5410. if (newOffset !== -1) {
  5411. return Optional.some({
  5412. container: node,
  5413. offset: newOffset
  5414. });
  5415. }
  5416. }
  5417. return walker().bind(next => walk(next.container, next.offset, walker, process));
  5418. };
  5419. const backwards = (node, offset, process, root) => {
  5420. const walker = TextWalker(node, root !== null && root !== void 0 ? root : dom.getRoot(), isBlockBoundary);
  5421. return walk(node, offset, () => walker.prev().map(prev => ({
  5422. container: prev,
  5423. offset: prev.length
  5424. })), process).getOrNull();
  5425. };
  5426. const forwards = (node, offset, process, root) => {
  5427. const walker = TextWalker(node, root !== null && root !== void 0 ? root : dom.getRoot(), isBlockBoundary);
  5428. return walk(node, offset, () => walker.next().map(next => ({
  5429. container: next,
  5430. offset: 0
  5431. })), process).getOrNull();
  5432. };
  5433. return {
  5434. backwards,
  5435. forwards
  5436. };
  5437. };
  5438. const round$2 = Math.round;
  5439. const clone$1 = rect => {
  5440. if (!rect) {
  5441. return {
  5442. left: 0,
  5443. top: 0,
  5444. bottom: 0,
  5445. right: 0,
  5446. width: 0,
  5447. height: 0
  5448. };
  5449. }
  5450. return {
  5451. left: round$2(rect.left),
  5452. top: round$2(rect.top),
  5453. bottom: round$2(rect.bottom),
  5454. right: round$2(rect.right),
  5455. width: round$2(rect.width),
  5456. height: round$2(rect.height)
  5457. };
  5458. };
  5459. const collapse = (rect, toStart) => {
  5460. rect = clone$1(rect);
  5461. if (toStart) {
  5462. rect.right = rect.left;
  5463. } else {
  5464. rect.left = rect.left + rect.width;
  5465. rect.right = rect.left;
  5466. }
  5467. rect.width = 0;
  5468. return rect;
  5469. };
  5470. const isEqual = (rect1, rect2) => rect1.left === rect2.left && rect1.top === rect2.top && rect1.bottom === rect2.bottom && rect1.right === rect2.right;
  5471. const isValidOverflow = (overflowY, rect1, rect2) => overflowY >= 0 && overflowY <= Math.min(rect1.height, rect2.height) / 2;
  5472. const isAbove$1 = (rect1, rect2) => {
  5473. const halfHeight = Math.min(rect2.height / 2, rect1.height / 2);
  5474. if (rect1.bottom - halfHeight < rect2.top) {
  5475. return true;
  5476. }
  5477. if (rect1.top > rect2.bottom) {
  5478. return false;
  5479. }
  5480. return isValidOverflow(rect2.top - rect1.bottom, rect1, rect2);
  5481. };
  5482. const isBelow$1 = (rect1, rect2) => {
  5483. if (rect1.top > rect2.bottom) {
  5484. return true;
  5485. }
  5486. if (rect1.bottom < rect2.top) {
  5487. return false;
  5488. }
  5489. return isValidOverflow(rect2.bottom - rect1.top, rect1, rect2);
  5490. };
  5491. const containsXY = (rect, clientX, clientY) => clientX >= rect.left && clientX <= rect.right && clientY >= rect.top && clientY <= rect.bottom;
  5492. const boundingClientRectFromRects = rects => {
  5493. return foldl(rects, (acc, rect) => {
  5494. return acc.fold(() => Optional.some(rect), prevRect => {
  5495. const left = Math.min(rect.left, prevRect.left);
  5496. const top = Math.min(rect.top, prevRect.top);
  5497. const right = Math.max(rect.right, prevRect.right);
  5498. const bottom = Math.max(rect.bottom, prevRect.bottom);
  5499. return Optional.some({
  5500. top,
  5501. right,
  5502. bottom,
  5503. left,
  5504. width: right - left,
  5505. height: bottom - top
  5506. });
  5507. });
  5508. }, Optional.none());
  5509. };
  5510. const distanceToRectEdgeFromXY = (rect, x, y) => {
  5511. const cx = Math.max(Math.min(x, rect.left + rect.width), rect.left);
  5512. const cy = Math.max(Math.min(y, rect.top + rect.height), rect.top);
  5513. return Math.sqrt((x - cx) * (x - cx) + (y - cy) * (y - cy));
  5514. };
  5515. const overlapY = (r1, r2) => Math.max(0, Math.min(r1.bottom, r2.bottom) - Math.max(r1.top, r2.top));
  5516. const clamp$2 = (value, min, max) => Math.min(Math.max(value, min), max);
  5517. const getSelectedNode = range => {
  5518. const startContainer = range.startContainer, startOffset = range.startOffset;
  5519. if (startContainer === range.endContainer && startContainer.hasChildNodes() && range.endOffset === startOffset + 1) {
  5520. return startContainer.childNodes[startOffset];
  5521. }
  5522. return null;
  5523. };
  5524. const getNode$1 = (container, offset) => {
  5525. if (isElement$6(container) && container.hasChildNodes()) {
  5526. const childNodes = container.childNodes;
  5527. const safeOffset = clamp$2(offset, 0, childNodes.length - 1);
  5528. return childNodes[safeOffset];
  5529. } else {
  5530. return container;
  5531. }
  5532. };
  5533. const getNodeUnsafe = (container, offset) => {
  5534. if (offset < 0 && isElement$6(container) && container.hasChildNodes()) {
  5535. return undefined;
  5536. } else {
  5537. return getNode$1(container, offset);
  5538. }
  5539. };
  5540. 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]');
  5541. const isExtendingChar = ch => isString(ch) && ch.charCodeAt(0) >= 768 && extendingChars.test(ch);
  5542. const or = (...args) => {
  5543. return x => {
  5544. for (let i = 0; i < args.length; i++) {
  5545. if (args[i](x)) {
  5546. return true;
  5547. }
  5548. }
  5549. return false;
  5550. };
  5551. };
  5552. const and = (...args) => {
  5553. return x => {
  5554. for (let i = 0; i < args.length; i++) {
  5555. if (!args[i](x)) {
  5556. return false;
  5557. }
  5558. }
  5559. return true;
  5560. };
  5561. };
  5562. const isElement$4 = isElement$6;
  5563. const isCaretCandidate$2 = isCaretCandidate$3;
  5564. const isBlock$1 = matchStyleValues('display', 'block table');
  5565. const isFloated = matchStyleValues('float', 'left right');
  5566. const isValidElementCaretCandidate = and(isElement$4, isCaretCandidate$2, not(isFloated));
  5567. const isNotPre = not(matchStyleValues('white-space', 'pre pre-line pre-wrap'));
  5568. const isText$7 = isText$a;
  5569. const isBr$3 = isBr$6;
  5570. const nodeIndex$1 = DOMUtils.nodeIndex;
  5571. const resolveIndex$1 = getNodeUnsafe;
  5572. const createRange$1 = doc => doc ? doc.createRange() : DOMUtils.DOM.createRng();
  5573. const isWhiteSpace$1 = chr => isString(chr) && /[\r\n\t ]/.test(chr);
  5574. const isRange = rng => !!rng.setStart && !!rng.setEnd;
  5575. const isHiddenWhiteSpaceRange = range => {
  5576. const container = range.startContainer;
  5577. const offset = range.startOffset;
  5578. if (isWhiteSpace$1(range.toString()) && isNotPre(container.parentNode) && isText$a(container)) {
  5579. const text = container.data;
  5580. if (isWhiteSpace$1(text[offset - 1]) || isWhiteSpace$1(text[offset + 1])) {
  5581. return true;
  5582. }
  5583. }
  5584. return false;
  5585. };
  5586. const getBrClientRect = brNode => {
  5587. const doc = brNode.ownerDocument;
  5588. const rng = createRange$1(doc);
  5589. const nbsp$1 = doc.createTextNode(nbsp);
  5590. const parentNode = brNode.parentNode;
  5591. parentNode.insertBefore(nbsp$1, brNode);
  5592. rng.setStart(nbsp$1, 0);
  5593. rng.setEnd(nbsp$1, 1);
  5594. const clientRect = clone$1(rng.getBoundingClientRect());
  5595. parentNode.removeChild(nbsp$1);
  5596. return clientRect;
  5597. };
  5598. const getBoundingClientRectWebKitText = rng => {
  5599. const sc = rng.startContainer;
  5600. const ec = rng.endContainer;
  5601. const so = rng.startOffset;
  5602. const eo = rng.endOffset;
  5603. if (sc === ec && isText$a(ec) && so === 0 && eo === 1) {
  5604. const newRng = rng.cloneRange();
  5605. newRng.setEndAfter(ec);
  5606. return getBoundingClientRect$1(newRng);
  5607. } else {
  5608. return null;
  5609. }
  5610. };
  5611. const isZeroRect = r => r.left === 0 && r.right === 0 && r.top === 0 && r.bottom === 0;
  5612. const getBoundingClientRect$1 = item => {
  5613. var _a;
  5614. let clientRect;
  5615. const clientRects = item.getClientRects();
  5616. if (clientRects.length > 0) {
  5617. clientRect = clone$1(clientRects[0]);
  5618. } else {
  5619. clientRect = clone$1(item.getBoundingClientRect());
  5620. }
  5621. if (!isRange(item) && isBr$3(item) && isZeroRect(clientRect)) {
  5622. return getBrClientRect(item);
  5623. }
  5624. if (isZeroRect(clientRect) && isRange(item)) {
  5625. return (_a = getBoundingClientRectWebKitText(item)) !== null && _a !== void 0 ? _a : clientRect;
  5626. }
  5627. return clientRect;
  5628. };
  5629. const collapseAndInflateWidth = (clientRect, toStart) => {
  5630. const newClientRect = collapse(clientRect, toStart);
  5631. newClientRect.width = 1;
  5632. newClientRect.right = newClientRect.left + 1;
  5633. return newClientRect;
  5634. };
  5635. const getCaretPositionClientRects = caretPosition => {
  5636. const clientRects = [];
  5637. const addUniqueAndValidRect = clientRect => {
  5638. if (clientRect.height === 0) {
  5639. return;
  5640. }
  5641. if (clientRects.length > 0) {
  5642. if (isEqual(clientRect, clientRects[clientRects.length - 1])) {
  5643. return;
  5644. }
  5645. }
  5646. clientRects.push(clientRect);
  5647. };
  5648. const addCharacterOffset = (container, offset) => {
  5649. const range = createRange$1(container.ownerDocument);
  5650. if (offset < container.data.length) {
  5651. if (isExtendingChar(container.data[offset])) {
  5652. return;
  5653. }
  5654. if (isExtendingChar(container.data[offset - 1])) {
  5655. range.setStart(container, offset);
  5656. range.setEnd(container, offset + 1);
  5657. if (!isHiddenWhiteSpaceRange(range)) {
  5658. addUniqueAndValidRect(collapseAndInflateWidth(getBoundingClientRect$1(range), false));
  5659. return;
  5660. }
  5661. }
  5662. }
  5663. if (offset > 0) {
  5664. range.setStart(container, offset - 1);
  5665. range.setEnd(container, offset);
  5666. if (!isHiddenWhiteSpaceRange(range)) {
  5667. addUniqueAndValidRect(collapseAndInflateWidth(getBoundingClientRect$1(range), false));
  5668. }
  5669. }
  5670. if (offset < container.data.length) {
  5671. range.setStart(container, offset);
  5672. range.setEnd(container, offset + 1);
  5673. if (!isHiddenWhiteSpaceRange(range)) {
  5674. addUniqueAndValidRect(collapseAndInflateWidth(getBoundingClientRect$1(range), true));
  5675. }
  5676. }
  5677. };
  5678. const container = caretPosition.container();
  5679. const offset = caretPosition.offset();
  5680. if (isText$7(container)) {
  5681. addCharacterOffset(container, offset);
  5682. return clientRects;
  5683. }
  5684. if (isElement$4(container)) {
  5685. if (caretPosition.isAtEnd()) {
  5686. const node = resolveIndex$1(container, offset);
  5687. if (isText$7(node)) {
  5688. addCharacterOffset(node, node.data.length);
  5689. }
  5690. if (isValidElementCaretCandidate(node) && !isBr$3(node)) {
  5691. addUniqueAndValidRect(collapseAndInflateWidth(getBoundingClientRect$1(node), false));
  5692. }
  5693. } else {
  5694. const node = resolveIndex$1(container, offset);
  5695. if (isText$7(node)) {
  5696. addCharacterOffset(node, 0);
  5697. }
  5698. if (isValidElementCaretCandidate(node) && caretPosition.isAtEnd()) {
  5699. addUniqueAndValidRect(collapseAndInflateWidth(getBoundingClientRect$1(node), false));
  5700. return clientRects;
  5701. }
  5702. const beforeNode = resolveIndex$1(caretPosition.container(), caretPosition.offset() - 1);
  5703. if (isValidElementCaretCandidate(beforeNode) && !isBr$3(beforeNode)) {
  5704. if (isBlock$1(beforeNode) || isBlock$1(node) || !isValidElementCaretCandidate(node)) {
  5705. addUniqueAndValidRect(collapseAndInflateWidth(getBoundingClientRect$1(beforeNode), false));
  5706. }
  5707. }
  5708. if (isValidElementCaretCandidate(node)) {
  5709. addUniqueAndValidRect(collapseAndInflateWidth(getBoundingClientRect$1(node), true));
  5710. }
  5711. }
  5712. }
  5713. return clientRects;
  5714. };
  5715. const CaretPosition = (container, offset, clientRects) => {
  5716. const isAtStart = () => {
  5717. if (isText$7(container)) {
  5718. return offset === 0;
  5719. }
  5720. return offset === 0;
  5721. };
  5722. const isAtEnd = () => {
  5723. if (isText$7(container)) {
  5724. return offset >= container.data.length;
  5725. }
  5726. return offset >= container.childNodes.length;
  5727. };
  5728. const toRange = () => {
  5729. const range = createRange$1(container.ownerDocument);
  5730. range.setStart(container, offset);
  5731. range.setEnd(container, offset);
  5732. return range;
  5733. };
  5734. const getClientRects = () => {
  5735. if (!clientRects) {
  5736. clientRects = getCaretPositionClientRects(CaretPosition(container, offset));
  5737. }
  5738. return clientRects;
  5739. };
  5740. const isVisible = () => getClientRects().length > 0;
  5741. const isEqual = caretPosition => caretPosition && container === caretPosition.container() && offset === caretPosition.offset();
  5742. const getNode = before => resolveIndex$1(container, before ? offset - 1 : offset);
  5743. return {
  5744. container: constant(container),
  5745. offset: constant(offset),
  5746. toRange,
  5747. getClientRects,
  5748. isVisible,
  5749. isAtStart,
  5750. isAtEnd,
  5751. isEqual,
  5752. getNode
  5753. };
  5754. };
  5755. CaretPosition.fromRangeStart = range => CaretPosition(range.startContainer, range.startOffset);
  5756. CaretPosition.fromRangeEnd = range => CaretPosition(range.endContainer, range.endOffset);
  5757. CaretPosition.after = node => CaretPosition(node.parentNode, nodeIndex$1(node) + 1);
  5758. CaretPosition.before = node => CaretPosition(node.parentNode, nodeIndex$1(node));
  5759. CaretPosition.isAbove = (pos1, pos2) => lift2(head(pos2.getClientRects()), last$3(pos1.getClientRects()), isAbove$1).getOr(false);
  5760. CaretPosition.isBelow = (pos1, pos2) => lift2(last$3(pos2.getClientRects()), head(pos1.getClientRects()), isBelow$1).getOr(false);
  5761. CaretPosition.isAtStart = pos => pos ? pos.isAtStart() : false;
  5762. CaretPosition.isAtEnd = pos => pos ? pos.isAtEnd() : false;
  5763. CaretPosition.isTextPosition = pos => pos ? isText$a(pos.container()) : false;
  5764. CaretPosition.isElementPosition = pos => !CaretPosition.isTextPosition(pos);
  5765. const trimEmptyTextNode$1 = (dom, node) => {
  5766. if (isText$a(node) && node.data.length === 0) {
  5767. dom.remove(node);
  5768. }
  5769. };
  5770. const insertNode = (dom, rng, node) => {
  5771. rng.insertNode(node);
  5772. trimEmptyTextNode$1(dom, node.previousSibling);
  5773. trimEmptyTextNode$1(dom, node.nextSibling);
  5774. };
  5775. const insertFragment = (dom, rng, frag) => {
  5776. const firstChild = Optional.from(frag.firstChild);
  5777. const lastChild = Optional.from(frag.lastChild);
  5778. rng.insertNode(frag);
  5779. firstChild.each(child => trimEmptyTextNode$1(dom, child.previousSibling));
  5780. lastChild.each(child => trimEmptyTextNode$1(dom, child.nextSibling));
  5781. };
  5782. const rangeInsertNode = (dom, rng, node) => {
  5783. if (isDocumentFragment(node)) {
  5784. insertFragment(dom, rng, node);
  5785. } else {
  5786. insertNode(dom, rng, node);
  5787. }
  5788. };
  5789. const isText$6 = isText$a;
  5790. const isBogus = isBogus$2;
  5791. const nodeIndex = DOMUtils.nodeIndex;
  5792. const normalizedParent = node => {
  5793. const parentNode = node.parentNode;
  5794. if (isBogus(parentNode)) {
  5795. return normalizedParent(parentNode);
  5796. }
  5797. return parentNode;
  5798. };
  5799. const getChildNodes = node => {
  5800. if (!node) {
  5801. return [];
  5802. }
  5803. return reduce(node.childNodes, (result, node) => {
  5804. if (isBogus(node) && node.nodeName !== 'BR') {
  5805. result = result.concat(getChildNodes(node));
  5806. } else {
  5807. result.push(node);
  5808. }
  5809. return result;
  5810. }, []);
  5811. };
  5812. const normalizedTextOffset = (node, offset) => {
  5813. let tempNode = node;
  5814. while (tempNode = tempNode.previousSibling) {
  5815. if (!isText$6(tempNode)) {
  5816. break;
  5817. }
  5818. offset += tempNode.data.length;
  5819. }
  5820. return offset;
  5821. };
  5822. const equal = a => b => a === b;
  5823. const normalizedNodeIndex = node => {
  5824. let nodes, index;
  5825. nodes = getChildNodes(normalizedParent(node));
  5826. index = findIndex$1(nodes, equal(node), node);
  5827. nodes = nodes.slice(0, index + 1);
  5828. const numTextFragments = reduce(nodes, (result, node, i) => {
  5829. if (isText$6(node) && isText$6(nodes[i - 1])) {
  5830. result++;
  5831. }
  5832. return result;
  5833. }, 0);
  5834. nodes = filter$3(nodes, matchNodeNames([node.nodeName]));
  5835. index = findIndex$1(nodes, equal(node), node);
  5836. return index - numTextFragments;
  5837. };
  5838. const createPathItem = node => {
  5839. const name = isText$6(node) ? 'text()' : node.nodeName.toLowerCase();
  5840. return name + '[' + normalizedNodeIndex(node) + ']';
  5841. };
  5842. const parentsUntil$1 = (root, node, predicate) => {
  5843. const parents = [];
  5844. for (let tempNode = node.parentNode; tempNode && tempNode !== root; tempNode = tempNode.parentNode) {
  5845. if (predicate && predicate(tempNode)) {
  5846. break;
  5847. }
  5848. parents.push(tempNode);
  5849. }
  5850. return parents;
  5851. };
  5852. const create$b = (root, caretPosition) => {
  5853. let path = [];
  5854. let container = caretPosition.container();
  5855. let offset = caretPosition.offset();
  5856. let outputOffset;
  5857. if (isText$6(container)) {
  5858. outputOffset = normalizedTextOffset(container, offset);
  5859. } else {
  5860. const childNodes = container.childNodes;
  5861. if (offset >= childNodes.length) {
  5862. outputOffset = 'after';
  5863. offset = childNodes.length - 1;
  5864. } else {
  5865. outputOffset = 'before';
  5866. }
  5867. container = childNodes[offset];
  5868. }
  5869. path.push(createPathItem(container));
  5870. let parents = parentsUntil$1(root, container);
  5871. parents = filter$3(parents, not(isBogus$2));
  5872. path = path.concat(map$1(parents, node => {
  5873. return createPathItem(node);
  5874. }));
  5875. return path.reverse().join('/') + ',' + outputOffset;
  5876. };
  5877. const resolvePathItem = (node, name, index) => {
  5878. let nodes = getChildNodes(node);
  5879. nodes = filter$3(nodes, (node, index) => {
  5880. return !isText$6(node) || !isText$6(nodes[index - 1]);
  5881. });
  5882. nodes = filter$3(nodes, matchNodeNames([name]));
  5883. return nodes[index];
  5884. };
  5885. const findTextPosition = (container, offset) => {
  5886. let node = container;
  5887. let targetOffset = 0;
  5888. while (isText$6(node)) {
  5889. const dataLen = node.data.length;
  5890. if (offset >= targetOffset && offset <= targetOffset + dataLen) {
  5891. container = node;
  5892. offset = offset - targetOffset;
  5893. break;
  5894. }
  5895. if (!isText$6(node.nextSibling)) {
  5896. container = node;
  5897. offset = dataLen;
  5898. break;
  5899. }
  5900. targetOffset += dataLen;
  5901. node = node.nextSibling;
  5902. }
  5903. if (isText$6(container) && offset > container.data.length) {
  5904. offset = container.data.length;
  5905. }
  5906. return CaretPosition(container, offset);
  5907. };
  5908. const resolve$1 = (root, path) => {
  5909. if (!path) {
  5910. return null;
  5911. }
  5912. const parts = path.split(',');
  5913. const paths = parts[0].split('/');
  5914. const offset = parts.length > 1 ? parts[1] : 'before';
  5915. const container = reduce(paths, (result, value) => {
  5916. const match = /([\w\-\(\)]+)\[([0-9]+)\]/.exec(value);
  5917. if (!match) {
  5918. return null;
  5919. }
  5920. if (match[1] === 'text()') {
  5921. match[1] = '#text';
  5922. }
  5923. return resolvePathItem(result, match[1], parseInt(match[2], 10));
  5924. }, root);
  5925. if (!container) {
  5926. return null;
  5927. }
  5928. if (!isText$6(container) && container.parentNode) {
  5929. let nodeOffset;
  5930. if (offset === 'after') {
  5931. nodeOffset = nodeIndex(container) + 1;
  5932. } else {
  5933. nodeOffset = nodeIndex(container);
  5934. }
  5935. return CaretPosition(container.parentNode, nodeOffset);
  5936. }
  5937. return findTextPosition(container, parseInt(offset, 10));
  5938. };
  5939. const isContentEditableFalse$9 = isContentEditableFalse$b;
  5940. const getNormalizedTextOffset$1 = (trim, container, offset) => {
  5941. let trimmedOffset = trim(container.data.slice(0, offset)).length;
  5942. for (let node = container.previousSibling; node && isText$a(node); node = node.previousSibling) {
  5943. trimmedOffset += trim(node.data).length;
  5944. }
  5945. return trimmedOffset;
  5946. };
  5947. const getPoint = (dom, trim, normalized, rng, start) => {
  5948. const container = start ? rng.startContainer : rng.endContainer;
  5949. let offset = start ? rng.startOffset : rng.endOffset;
  5950. const point = [];
  5951. const root = dom.getRoot();
  5952. if (isText$a(container)) {
  5953. point.push(normalized ? getNormalizedTextOffset$1(trim, container, offset) : offset);
  5954. } else {
  5955. let after = 0;
  5956. const childNodes = container.childNodes;
  5957. if (offset >= childNodes.length && childNodes.length) {
  5958. after = 1;
  5959. offset = Math.max(0, childNodes.length - 1);
  5960. }
  5961. point.push(dom.nodeIndex(childNodes[offset], normalized) + after);
  5962. }
  5963. for (let node = container; node && node !== root; node = node.parentNode) {
  5964. point.push(dom.nodeIndex(node, normalized));
  5965. }
  5966. return point;
  5967. };
  5968. const getLocation = (trim, selection, normalized, rng) => {
  5969. const dom = selection.dom;
  5970. const start = getPoint(dom, trim, normalized, rng, true);
  5971. const forward = selection.isForward();
  5972. const fakeCaret = isRangeInCaretContainerBlock(rng) ? { isFakeCaret: true } : {};
  5973. if (!selection.isCollapsed()) {
  5974. const end = getPoint(dom, trim, normalized, rng, false);
  5975. return {
  5976. start,
  5977. end,
  5978. forward,
  5979. ...fakeCaret
  5980. };
  5981. } else {
  5982. return {
  5983. start,
  5984. forward,
  5985. ...fakeCaret
  5986. };
  5987. }
  5988. };
  5989. const findIndex = (dom, name, element) => {
  5990. let count = 0;
  5991. Tools.each(dom.select(name), node => {
  5992. if (node.getAttribute('data-mce-bogus') === 'all') {
  5993. return;
  5994. } else if (node === element) {
  5995. return false;
  5996. } else {
  5997. count++;
  5998. return;
  5999. }
  6000. });
  6001. return count;
  6002. };
  6003. const moveEndPoint$1 = (rng, start) => {
  6004. let container = start ? rng.startContainer : rng.endContainer;
  6005. let offset = start ? rng.startOffset : rng.endOffset;
  6006. if (isElement$6(container) && container.nodeName === 'TR') {
  6007. const childNodes = container.childNodes;
  6008. container = childNodes[Math.min(start ? offset : offset - 1, childNodes.length - 1)];
  6009. if (container) {
  6010. offset = start ? 0 : container.childNodes.length;
  6011. if (start) {
  6012. rng.setStart(container, offset);
  6013. } else {
  6014. rng.setEnd(container, offset);
  6015. }
  6016. }
  6017. }
  6018. };
  6019. const normalizeTableCellSelection = rng => {
  6020. moveEndPoint$1(rng, true);
  6021. moveEndPoint$1(rng, false);
  6022. return rng;
  6023. };
  6024. const findSibling = (node, offset) => {
  6025. if (isElement$6(node)) {
  6026. node = getNode$1(node, offset);
  6027. if (isContentEditableFalse$9(node)) {
  6028. return node;
  6029. }
  6030. }
  6031. if (isCaretContainer$2(node)) {
  6032. if (isText$a(node) && isCaretContainerBlock$1(node)) {
  6033. node = node.parentNode;
  6034. }
  6035. let sibling = node.previousSibling;
  6036. if (isContentEditableFalse$9(sibling)) {
  6037. return sibling;
  6038. }
  6039. sibling = node.nextSibling;
  6040. if (isContentEditableFalse$9(sibling)) {
  6041. return sibling;
  6042. }
  6043. }
  6044. return undefined;
  6045. };
  6046. const findAdjacentContentEditableFalseElm = rng => {
  6047. return findSibling(rng.startContainer, rng.startOffset) || findSibling(rng.endContainer, rng.endOffset);
  6048. };
  6049. const getOffsetBookmark = (trim, normalized, selection) => {
  6050. const element = selection.getNode();
  6051. const rng = selection.getRng();
  6052. if (element.nodeName === 'IMG' || isContentEditableFalse$9(element)) {
  6053. const name = element.nodeName;
  6054. return {
  6055. name,
  6056. index: findIndex(selection.dom, name, element)
  6057. };
  6058. }
  6059. const sibling = findAdjacentContentEditableFalseElm(rng);
  6060. if (sibling) {
  6061. const name = sibling.tagName;
  6062. return {
  6063. name,
  6064. index: findIndex(selection.dom, name, sibling)
  6065. };
  6066. }
  6067. return getLocation(trim, selection, normalized, rng);
  6068. };
  6069. const getCaretBookmark = selection => {
  6070. const rng = selection.getRng();
  6071. return {
  6072. start: create$b(selection.dom.getRoot(), CaretPosition.fromRangeStart(rng)),
  6073. end: create$b(selection.dom.getRoot(), CaretPosition.fromRangeEnd(rng)),
  6074. forward: selection.isForward()
  6075. };
  6076. };
  6077. const getRangeBookmark = selection => {
  6078. return {
  6079. rng: selection.getRng(),
  6080. forward: selection.isForward()
  6081. };
  6082. };
  6083. const createBookmarkSpan = (dom, id, filled) => {
  6084. const args = {
  6085. 'data-mce-type': 'bookmark',
  6086. id,
  6087. 'style': 'overflow:hidden;line-height:0px'
  6088. };
  6089. return filled ? dom.create('span', args, '&#xFEFF;') : dom.create('span', args);
  6090. };
  6091. const getPersistentBookmark = (selection, filled) => {
  6092. const dom = selection.dom;
  6093. let rng = selection.getRng();
  6094. const id = dom.uniqueId();
  6095. const collapsed = selection.isCollapsed();
  6096. const element = selection.getNode();
  6097. const name = element.nodeName;
  6098. const forward = selection.isForward();
  6099. if (name === 'IMG') {
  6100. return {
  6101. name,
  6102. index: findIndex(dom, name, element)
  6103. };
  6104. }
  6105. const rng2 = normalizeTableCellSelection(rng.cloneRange());
  6106. if (!collapsed) {
  6107. rng2.collapse(false);
  6108. const endBookmarkNode = createBookmarkSpan(dom, id + '_end', filled);
  6109. rangeInsertNode(dom, rng2, endBookmarkNode);
  6110. }
  6111. rng = normalizeTableCellSelection(rng);
  6112. rng.collapse(true);
  6113. const startBookmarkNode = createBookmarkSpan(dom, id + '_start', filled);
  6114. rangeInsertNode(dom, rng, startBookmarkNode);
  6115. selection.moveToBookmark({
  6116. id,
  6117. keep: true,
  6118. forward
  6119. });
  6120. return {
  6121. id,
  6122. forward
  6123. };
  6124. };
  6125. const getBookmark$2 = (selection, type, normalized = false) => {
  6126. if (type === 2) {
  6127. return getOffsetBookmark(trim$1, normalized, selection);
  6128. } else if (type === 3) {
  6129. return getCaretBookmark(selection);
  6130. } else if (type) {
  6131. return getRangeBookmark(selection);
  6132. } else {
  6133. return getPersistentBookmark(selection, false);
  6134. }
  6135. };
  6136. const getUndoBookmark = curry(getOffsetBookmark, identity, true);
  6137. const value$1 = value => {
  6138. const applyHelper = fn => fn(value);
  6139. const constHelper = constant(value);
  6140. const outputHelper = () => output;
  6141. const output = {
  6142. tag: true,
  6143. inner: value,
  6144. fold: (_onError, onValue) => onValue(value),
  6145. isValue: always,
  6146. isError: never,
  6147. map: mapper => Result.value(mapper(value)),
  6148. mapError: outputHelper,
  6149. bind: applyHelper,
  6150. exists: applyHelper,
  6151. forall: applyHelper,
  6152. getOr: constHelper,
  6153. or: outputHelper,
  6154. getOrThunk: constHelper,
  6155. orThunk: outputHelper,
  6156. getOrDie: constHelper,
  6157. each: fn => {
  6158. fn(value);
  6159. },
  6160. toOptional: () => Optional.some(value)
  6161. };
  6162. return output;
  6163. };
  6164. const error = error => {
  6165. const outputHelper = () => output;
  6166. const output = {
  6167. tag: false,
  6168. inner: error,
  6169. fold: (onError, _onValue) => onError(error),
  6170. isValue: never,
  6171. isError: always,
  6172. map: outputHelper,
  6173. mapError: mapper => Result.error(mapper(error)),
  6174. bind: outputHelper,
  6175. exists: never,
  6176. forall: always,
  6177. getOr: identity,
  6178. or: identity,
  6179. getOrThunk: apply$1,
  6180. orThunk: apply$1,
  6181. getOrDie: die(String(error)),
  6182. each: noop,
  6183. toOptional: Optional.none
  6184. };
  6185. return output;
  6186. };
  6187. const fromOption = (optional, err) => optional.fold(() => error(err), value$1);
  6188. const Result = {
  6189. value: value$1,
  6190. error,
  6191. fromOption
  6192. };
  6193. const generate = cases => {
  6194. if (!isArray$1(cases)) {
  6195. throw new Error('cases must be an array');
  6196. }
  6197. if (cases.length === 0) {
  6198. throw new Error('there must be at least one case');
  6199. }
  6200. const constructors = [];
  6201. const adt = {};
  6202. each$e(cases, (acase, count) => {
  6203. const keys$1 = keys(acase);
  6204. if (keys$1.length !== 1) {
  6205. throw new Error('one and only one name per case');
  6206. }
  6207. const key = keys$1[0];
  6208. const value = acase[key];
  6209. if (adt[key] !== undefined) {
  6210. throw new Error('duplicate key detected:' + key);
  6211. } else if (key === 'cata') {
  6212. throw new Error('cannot have a case named cata (sorry)');
  6213. } else if (!isArray$1(value)) {
  6214. throw new Error('case arguments must be an array');
  6215. }
  6216. constructors.push(key);
  6217. adt[key] = (...args) => {
  6218. const argLength = args.length;
  6219. if (argLength !== value.length) {
  6220. throw new Error('Wrong number of arguments to case ' + key + '. Expected ' + value.length + ' (' + value + '), got ' + argLength);
  6221. }
  6222. const match = branches => {
  6223. const branchKeys = keys(branches);
  6224. if (constructors.length !== branchKeys.length) {
  6225. throw new Error('Wrong number of arguments to match. Expected: ' + constructors.join(',') + '\nActual: ' + branchKeys.join(','));
  6226. }
  6227. const allReqd = forall(constructors, reqKey => {
  6228. return contains$2(branchKeys, reqKey);
  6229. });
  6230. if (!allReqd) {
  6231. throw new Error('Not all branches were specified when using match. Specified: ' + branchKeys.join(', ') + '\nRequired: ' + constructors.join(', '));
  6232. }
  6233. return branches[key].apply(null, args);
  6234. };
  6235. return {
  6236. fold: (...foldArgs) => {
  6237. if (foldArgs.length !== cases.length) {
  6238. throw new Error('Wrong number of arguments to fold. Expected ' + cases.length + ', got ' + foldArgs.length);
  6239. }
  6240. const target = foldArgs[count];
  6241. return target.apply(null, args);
  6242. },
  6243. match,
  6244. log: label => {
  6245. console.log(label, {
  6246. constructors,
  6247. constructor: key,
  6248. params: args
  6249. });
  6250. }
  6251. };
  6252. };
  6253. });
  6254. return adt;
  6255. };
  6256. const Adt = { generate };
  6257. Adt.generate([
  6258. {
  6259. bothErrors: [
  6260. 'error1',
  6261. 'error2'
  6262. ]
  6263. },
  6264. {
  6265. firstError: [
  6266. 'error1',
  6267. 'value2'
  6268. ]
  6269. },
  6270. {
  6271. secondError: [
  6272. 'value1',
  6273. 'error2'
  6274. ]
  6275. },
  6276. {
  6277. bothValues: [
  6278. 'value1',
  6279. 'value2'
  6280. ]
  6281. }
  6282. ]);
  6283. const partition$1 = results => {
  6284. const errors = [];
  6285. const values = [];
  6286. each$e(results, result => {
  6287. result.fold(err => {
  6288. errors.push(err);
  6289. }, value => {
  6290. values.push(value);
  6291. });
  6292. });
  6293. return {
  6294. errors,
  6295. values
  6296. };
  6297. };
  6298. const isInlinePattern = pattern => pattern.type === 'inline-command' || pattern.type === 'inline-format';
  6299. const isBlockPattern = pattern => pattern.type === 'block-command' || pattern.type === 'block-format';
  6300. const normalizePattern = pattern => {
  6301. const err = message => Result.error({
  6302. message,
  6303. pattern
  6304. });
  6305. const formatOrCmd = (name, onFormat, onCommand) => {
  6306. if (pattern.format !== undefined) {
  6307. let formats;
  6308. if (isArray$1(pattern.format)) {
  6309. if (!forall(pattern.format, isString)) {
  6310. return err(name + ' pattern has non-string items in the `format` array');
  6311. }
  6312. formats = pattern.format;
  6313. } else if (isString(pattern.format)) {
  6314. formats = [pattern.format];
  6315. } else {
  6316. return err(name + ' pattern has non-string `format` parameter');
  6317. }
  6318. return Result.value(onFormat(formats));
  6319. } else if (pattern.cmd !== undefined) {
  6320. if (!isString(pattern.cmd)) {
  6321. return err(name + ' pattern has non-string `cmd` parameter');
  6322. }
  6323. return Result.value(onCommand(pattern.cmd, pattern.value));
  6324. } else {
  6325. return err(name + ' pattern is missing both `format` and `cmd` parameters');
  6326. }
  6327. };
  6328. if (!isObject(pattern)) {
  6329. return err('Raw pattern is not an object');
  6330. }
  6331. if (!isString(pattern.start)) {
  6332. return err('Raw pattern is missing `start` parameter');
  6333. }
  6334. if (pattern.end !== undefined) {
  6335. if (!isString(pattern.end)) {
  6336. return err('Inline pattern has non-string `end` parameter');
  6337. }
  6338. if (pattern.start.length === 0 && pattern.end.length === 0) {
  6339. return err('Inline pattern has empty `start` and `end` parameters');
  6340. }
  6341. let start = pattern.start;
  6342. let end = pattern.end;
  6343. if (end.length === 0) {
  6344. end = start;
  6345. start = '';
  6346. }
  6347. return formatOrCmd('Inline', format => ({
  6348. type: 'inline-format',
  6349. start,
  6350. end,
  6351. format
  6352. }), (cmd, value) => ({
  6353. type: 'inline-command',
  6354. start,
  6355. end,
  6356. cmd,
  6357. value
  6358. }));
  6359. } else if (pattern.replacement !== undefined) {
  6360. if (!isString(pattern.replacement)) {
  6361. return err('Replacement pattern has non-string `replacement` parameter');
  6362. }
  6363. if (pattern.start.length === 0) {
  6364. return err('Replacement pattern has empty `start` parameter');
  6365. }
  6366. return Result.value({
  6367. type: 'inline-command',
  6368. start: '',
  6369. end: pattern.start,
  6370. cmd: 'mceInsertContent',
  6371. value: pattern.replacement
  6372. });
  6373. } else {
  6374. if (pattern.start.length === 0) {
  6375. return err('Block pattern has empty `start` parameter');
  6376. }
  6377. return formatOrCmd('Block', formats => ({
  6378. type: 'block-format',
  6379. start: pattern.start,
  6380. format: formats[0]
  6381. }), (command, commandValue) => ({
  6382. type: 'block-command',
  6383. start: pattern.start,
  6384. cmd: command,
  6385. value: commandValue
  6386. }));
  6387. }
  6388. };
  6389. const getBlockPatterns = patterns => filter$5(patterns, isBlockPattern);
  6390. const getInlinePatterns = patterns => filter$5(patterns, isInlinePattern);
  6391. const createPatternSet = (patterns, dynamicPatternsLookup) => ({
  6392. inlinePatterns: getInlinePatterns(patterns),
  6393. blockPatterns: getBlockPatterns(patterns),
  6394. dynamicPatternsLookup
  6395. });
  6396. const fromRawPatterns = patterns => {
  6397. const normalized = partition$1(map$3(patterns, normalizePattern));
  6398. each$e(normalized.errors, err => console.error(err.message, err.pattern));
  6399. return normalized.values;
  6400. };
  6401. const fromRawPatternsLookup = lookupFn => {
  6402. return ctx => {
  6403. const rawPatterns = lookupFn(ctx);
  6404. return fromRawPatterns(rawPatterns);
  6405. };
  6406. };
  6407. const deviceDetection$1 = detect$2().deviceType;
  6408. const isTouch = deviceDetection$1.isTouch();
  6409. const DOM$a = DOMUtils.DOM;
  6410. const getHash = value => {
  6411. const items = value.indexOf('=') > 0 ? value.split(/[;,](?![^=;,]*(?:[;,]|$))/) : value.split(',');
  6412. return foldl(items, (output, item) => {
  6413. const arr = item.split('=');
  6414. const key = arr[0];
  6415. const val = arr.length > 1 ? arr[1] : key;
  6416. output[trim$3(key)] = trim$3(val);
  6417. return output;
  6418. }, {});
  6419. };
  6420. const isRegExp = x => is$4(x, RegExp);
  6421. const option = name => editor => editor.options.get(name);
  6422. const stringOrObjectProcessor = value => isString(value) || isObject(value);
  6423. const bodyOptionProcessor = (editor, defaultValue = '') => value => {
  6424. const valid = isString(value);
  6425. if (valid) {
  6426. if (value.indexOf('=') !== -1) {
  6427. const bodyObj = getHash(value);
  6428. return {
  6429. value: get$a(bodyObj, editor.id).getOr(defaultValue),
  6430. valid
  6431. };
  6432. } else {
  6433. return {
  6434. value,
  6435. valid
  6436. };
  6437. }
  6438. } else {
  6439. return {
  6440. valid: false,
  6441. message: 'Must be a string.'
  6442. };
  6443. }
  6444. };
  6445. const register$7 = editor => {
  6446. const registerOption = editor.options.register;
  6447. registerOption('id', {
  6448. processor: 'string',
  6449. default: editor.id
  6450. });
  6451. registerOption('selector', { processor: 'string' });
  6452. registerOption('target', { processor: 'object' });
  6453. registerOption('suffix', { processor: 'string' });
  6454. registerOption('cache_suffix', { processor: 'string' });
  6455. registerOption('base_url', { processor: 'string' });
  6456. registerOption('referrer_policy', {
  6457. processor: 'string',
  6458. default: ''
  6459. });
  6460. registerOption('language_load', {
  6461. processor: 'boolean',
  6462. default: true
  6463. });
  6464. registerOption('inline', {
  6465. processor: 'boolean',
  6466. default: false
  6467. });
  6468. registerOption('iframe_attrs', {
  6469. processor: 'object',
  6470. default: {}
  6471. });
  6472. registerOption('doctype', {
  6473. processor: 'string',
  6474. default: '<!DOCTYPE html>'
  6475. });
  6476. registerOption('document_base_url', {
  6477. processor: 'string',
  6478. default: editor.documentBaseUrl
  6479. });
  6480. registerOption('body_id', {
  6481. processor: bodyOptionProcessor(editor, 'tinymce'),
  6482. default: 'tinymce'
  6483. });
  6484. registerOption('body_class', {
  6485. processor: bodyOptionProcessor(editor),
  6486. default: ''
  6487. });
  6488. registerOption('content_security_policy', {
  6489. processor: 'string',
  6490. default: ''
  6491. });
  6492. registerOption('br_in_pre', {
  6493. processor: 'boolean',
  6494. default: true
  6495. });
  6496. registerOption('forced_root_block', {
  6497. processor: value => {
  6498. const valid = isString(value) && isNotEmpty(value);
  6499. if (valid) {
  6500. return {
  6501. value,
  6502. valid
  6503. };
  6504. } else {
  6505. return {
  6506. valid: false,
  6507. message: 'Must be a non-empty string.'
  6508. };
  6509. }
  6510. },
  6511. default: 'p'
  6512. });
  6513. registerOption('forced_root_block_attrs', {
  6514. processor: 'object',
  6515. default: {}
  6516. });
  6517. registerOption('newline_behavior', {
  6518. processor: value => {
  6519. const valid = contains$2([
  6520. 'block',
  6521. 'linebreak',
  6522. 'invert',
  6523. 'default'
  6524. ], value);
  6525. return valid ? {
  6526. value,
  6527. valid
  6528. } : {
  6529. valid: false,
  6530. message: 'Must be one of: block, linebreak, invert or default.'
  6531. };
  6532. },
  6533. default: 'default'
  6534. });
  6535. registerOption('br_newline_selector', {
  6536. processor: 'string',
  6537. default: '.mce-toc h2,figcaption,caption'
  6538. });
  6539. registerOption('no_newline_selector', {
  6540. processor: 'string',
  6541. default: ''
  6542. });
  6543. registerOption('keep_styles', {
  6544. processor: 'boolean',
  6545. default: true
  6546. });
  6547. registerOption('end_container_on_empty_block', {
  6548. processor: value => {
  6549. if (isBoolean(value)) {
  6550. return {
  6551. valid: true,
  6552. value
  6553. };
  6554. } else if (isString(value)) {
  6555. return {
  6556. valid: true,
  6557. value
  6558. };
  6559. } else {
  6560. return {
  6561. valid: false,
  6562. message: 'Must be boolean or a string'
  6563. };
  6564. }
  6565. },
  6566. default: 'blockquote'
  6567. });
  6568. registerOption('font_size_style_values', {
  6569. processor: 'string',
  6570. default: 'xx-small,x-small,small,medium,large,x-large,xx-large'
  6571. });
  6572. registerOption('font_size_legacy_values', {
  6573. processor: 'string',
  6574. default: 'xx-small,small,medium,large,x-large,xx-large,300%'
  6575. });
  6576. registerOption('font_size_classes', {
  6577. processor: 'string',
  6578. default: ''
  6579. });
  6580. registerOption('automatic_uploads', {
  6581. processor: 'boolean',
  6582. default: true
  6583. });
  6584. registerOption('images_reuse_filename', {
  6585. processor: 'boolean',
  6586. default: false
  6587. });
  6588. registerOption('images_replace_blob_uris', {
  6589. processor: 'boolean',
  6590. default: true
  6591. });
  6592. registerOption('icons', {
  6593. processor: 'string',
  6594. default: ''
  6595. });
  6596. registerOption('icons_url', {
  6597. processor: 'string',
  6598. default: ''
  6599. });
  6600. registerOption('images_upload_url', {
  6601. processor: 'string',
  6602. default: ''
  6603. });
  6604. registerOption('images_upload_base_path', {
  6605. processor: 'string',
  6606. default: ''
  6607. });
  6608. registerOption('images_upload_credentials', {
  6609. processor: 'boolean',
  6610. default: false
  6611. });
  6612. registerOption('images_upload_handler', { processor: 'function' });
  6613. registerOption('language', {
  6614. processor: 'string',
  6615. default: 'en'
  6616. });
  6617. registerOption('language_url', {
  6618. processor: 'string',
  6619. default: ''
  6620. });
  6621. registerOption('entity_encoding', {
  6622. processor: 'string',
  6623. default: 'named'
  6624. });
  6625. registerOption('indent', {
  6626. processor: 'boolean',
  6627. default: true
  6628. });
  6629. registerOption('indent_before', {
  6630. processor: 'string',
  6631. 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'
  6632. });
  6633. registerOption('indent_after', {
  6634. processor: 'string',
  6635. 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'
  6636. });
  6637. registerOption('indent_use_margin', {
  6638. processor: 'boolean',
  6639. default: false
  6640. });
  6641. registerOption('indentation', {
  6642. processor: 'string',
  6643. default: '40px'
  6644. });
  6645. registerOption('content_css', {
  6646. processor: value => {
  6647. const valid = value === false || isString(value) || isArrayOf(value, isString);
  6648. if (valid) {
  6649. if (isString(value)) {
  6650. return {
  6651. value: map$3(value.split(','), trim$3),
  6652. valid
  6653. };
  6654. } else if (isArray$1(value)) {
  6655. return {
  6656. value,
  6657. valid
  6658. };
  6659. } else if (value === false) {
  6660. return {
  6661. value: [],
  6662. valid
  6663. };
  6664. } else {
  6665. return {
  6666. value,
  6667. valid
  6668. };
  6669. }
  6670. } else {
  6671. return {
  6672. valid: false,
  6673. message: 'Must be false, a string or an array of strings.'
  6674. };
  6675. }
  6676. },
  6677. default: isInline(editor) ? [] : ['default']
  6678. });
  6679. registerOption('content_style', { processor: 'string' });
  6680. registerOption('content_css_cors', {
  6681. processor: 'boolean',
  6682. default: false
  6683. });
  6684. registerOption('font_css', {
  6685. processor: value => {
  6686. const valid = isString(value) || isArrayOf(value, isString);
  6687. if (valid) {
  6688. const newValue = isArray$1(value) ? value : map$3(value.split(','), trim$3);
  6689. return {
  6690. value: newValue,
  6691. valid
  6692. };
  6693. } else {
  6694. return {
  6695. valid: false,
  6696. message: 'Must be a string or an array of strings.'
  6697. };
  6698. }
  6699. },
  6700. default: []
  6701. });
  6702. registerOption('inline_boundaries', {
  6703. processor: 'boolean',
  6704. default: true
  6705. });
  6706. registerOption('inline_boundaries_selector', {
  6707. processor: 'string',
  6708. default: 'a[href],code,span.mce-annotation'
  6709. });
  6710. registerOption('object_resizing', {
  6711. processor: value => {
  6712. const valid = isBoolean(value) || isString(value);
  6713. if (valid) {
  6714. if (value === false || deviceDetection$1.isiPhone() || deviceDetection$1.isiPad()) {
  6715. return {
  6716. value: '',
  6717. valid
  6718. };
  6719. } else {
  6720. return {
  6721. value: value === true ? 'table,img,figure.image,div,video,iframe' : value,
  6722. valid
  6723. };
  6724. }
  6725. } else {
  6726. return {
  6727. valid: false,
  6728. message: 'Must be boolean or a string'
  6729. };
  6730. }
  6731. },
  6732. default: !isTouch
  6733. });
  6734. registerOption('resize_img_proportional', {
  6735. processor: 'boolean',
  6736. default: true
  6737. });
  6738. registerOption('event_root', { processor: 'object' });
  6739. registerOption('service_message', { processor: 'string' });
  6740. registerOption('theme', {
  6741. processor: value => value === false || isString(value) || isFunction(value),
  6742. default: 'silver'
  6743. });
  6744. registerOption('theme_url', { processor: 'string' });
  6745. registerOption('formats', { processor: 'object' });
  6746. registerOption('format_empty_lines', {
  6747. processor: 'boolean',
  6748. default: false
  6749. });
  6750. registerOption('format_noneditable_selector', {
  6751. processor: 'string',
  6752. default: ''
  6753. });
  6754. registerOption('preview_styles', {
  6755. processor: value => {
  6756. const valid = value === false || isString(value);
  6757. if (valid) {
  6758. return {
  6759. value: value === false ? '' : value,
  6760. valid
  6761. };
  6762. } else {
  6763. return {
  6764. valid: false,
  6765. message: 'Must be false or a string'
  6766. };
  6767. }
  6768. },
  6769. default: 'font-family font-size font-weight font-style text-decoration text-transform color background-color border border-radius outline text-shadow'
  6770. });
  6771. registerOption('custom_ui_selector', {
  6772. processor: 'string',
  6773. default: ''
  6774. });
  6775. registerOption('hidden_input', {
  6776. processor: 'boolean',
  6777. default: true
  6778. });
  6779. registerOption('submit_patch', {
  6780. processor: 'boolean',
  6781. default: true
  6782. });
  6783. registerOption('encoding', { processor: 'string' });
  6784. registerOption('add_form_submit_trigger', {
  6785. processor: 'boolean',
  6786. default: true
  6787. });
  6788. registerOption('add_unload_trigger', {
  6789. processor: 'boolean',
  6790. default: true
  6791. });
  6792. registerOption('custom_undo_redo_levels', {
  6793. processor: 'number',
  6794. default: 0
  6795. });
  6796. registerOption('disable_nodechange', {
  6797. processor: 'boolean',
  6798. default: false
  6799. });
  6800. registerOption('readonly', {
  6801. processor: 'boolean',
  6802. default: false
  6803. });
  6804. registerOption('plugins', {
  6805. processor: 'string[]',
  6806. default: []
  6807. });
  6808. registerOption('external_plugins', { processor: 'object' });
  6809. registerOption('forced_plugins', { processor: 'string[]' });
  6810. registerOption('model', {
  6811. processor: 'string',
  6812. default: editor.hasPlugin('rtc') ? 'plugin' : 'dom'
  6813. });
  6814. registerOption('model_url', { processor: 'string' });
  6815. registerOption('block_unsupported_drop', {
  6816. processor: 'boolean',
  6817. default: true
  6818. });
  6819. registerOption('visual', {
  6820. processor: 'boolean',
  6821. default: true
  6822. });
  6823. registerOption('visual_table_class', {
  6824. processor: 'string',
  6825. default: 'mce-item-table'
  6826. });
  6827. registerOption('visual_anchor_class', {
  6828. processor: 'string',
  6829. default: 'mce-item-anchor'
  6830. });
  6831. registerOption('iframe_aria_text', {
  6832. processor: 'string',
  6833. default: 'Rich Text Area. Press ALT-0 for help.'
  6834. });
  6835. registerOption('setup', { processor: 'function' });
  6836. registerOption('init_instance_callback', { processor: 'function' });
  6837. registerOption('url_converter', {
  6838. processor: 'function',
  6839. default: editor.convertURL
  6840. });
  6841. registerOption('url_converter_scope', {
  6842. processor: 'object',
  6843. default: editor
  6844. });
  6845. registerOption('urlconverter_callback', { processor: 'function' });
  6846. registerOption('allow_conditional_comments', {
  6847. processor: 'boolean',
  6848. default: false
  6849. });
  6850. registerOption('allow_html_data_urls', {
  6851. processor: 'boolean',
  6852. default: false
  6853. });
  6854. registerOption('allow_svg_data_urls', { processor: 'boolean' });
  6855. registerOption('allow_html_in_named_anchor', {
  6856. processor: 'boolean',
  6857. default: false
  6858. });
  6859. registerOption('allow_script_urls', {
  6860. processor: 'boolean',
  6861. default: false
  6862. });
  6863. registerOption('allow_unsafe_link_target', {
  6864. processor: 'boolean',
  6865. default: false
  6866. });
  6867. registerOption('convert_fonts_to_spans', {
  6868. processor: 'boolean',
  6869. default: true,
  6870. deprecated: true
  6871. });
  6872. registerOption('fix_list_elements', {
  6873. processor: 'boolean',
  6874. default: false
  6875. });
  6876. registerOption('preserve_cdata', {
  6877. processor: 'boolean',
  6878. default: false
  6879. });
  6880. registerOption('remove_trailing_brs', { processor: 'boolean' });
  6881. registerOption('inline_styles', {
  6882. processor: 'boolean',
  6883. default: true,
  6884. deprecated: true
  6885. });
  6886. registerOption('element_format', {
  6887. processor: 'string',
  6888. default: 'html'
  6889. });
  6890. registerOption('entities', { processor: 'string' });
  6891. registerOption('schema', {
  6892. processor: 'string',
  6893. default: 'html5'
  6894. });
  6895. registerOption('convert_urls', {
  6896. processor: 'boolean',
  6897. default: true
  6898. });
  6899. registerOption('relative_urls', {
  6900. processor: 'boolean',
  6901. default: true
  6902. });
  6903. registerOption('remove_script_host', {
  6904. processor: 'boolean',
  6905. default: true
  6906. });
  6907. registerOption('custom_elements', { processor: 'string' });
  6908. registerOption('extended_valid_elements', { processor: 'string' });
  6909. registerOption('invalid_elements', { processor: 'string' });
  6910. registerOption('invalid_styles', { processor: stringOrObjectProcessor });
  6911. registerOption('valid_children', { processor: 'string' });
  6912. registerOption('valid_classes', { processor: stringOrObjectProcessor });
  6913. registerOption('valid_elements', { processor: 'string' });
  6914. registerOption('valid_styles', { processor: stringOrObjectProcessor });
  6915. registerOption('verify_html', {
  6916. processor: 'boolean',
  6917. default: true
  6918. });
  6919. registerOption('auto_focus', { processor: value => isString(value) || value === true });
  6920. registerOption('browser_spellcheck', {
  6921. processor: 'boolean',
  6922. default: false
  6923. });
  6924. registerOption('protect', { processor: 'array' });
  6925. registerOption('images_file_types', {
  6926. processor: 'string',
  6927. default: 'jpeg,jpg,jpe,jfi,jif,jfif,png,gif,bmp,webp'
  6928. });
  6929. registerOption('deprecation_warnings', {
  6930. processor: 'boolean',
  6931. default: true
  6932. });
  6933. registerOption('a11y_advanced_options', {
  6934. processor: 'boolean',
  6935. default: false
  6936. });
  6937. registerOption('api_key', { processor: 'string' });
  6938. registerOption('paste_block_drop', {
  6939. processor: 'boolean',
  6940. default: false
  6941. });
  6942. registerOption('paste_data_images', {
  6943. processor: 'boolean',
  6944. default: true
  6945. });
  6946. registerOption('paste_preprocess', { processor: 'function' });
  6947. registerOption('paste_postprocess', { processor: 'function' });
  6948. registerOption('paste_webkit_styles', {
  6949. processor: 'string',
  6950. default: 'none'
  6951. });
  6952. registerOption('paste_remove_styles_if_webkit', {
  6953. processor: 'boolean',
  6954. default: true
  6955. });
  6956. registerOption('paste_merge_formats', {
  6957. processor: 'boolean',
  6958. default: true
  6959. });
  6960. registerOption('smart_paste', {
  6961. processor: 'boolean',
  6962. default: true
  6963. });
  6964. registerOption('paste_as_text', {
  6965. processor: 'boolean',
  6966. default: false
  6967. });
  6968. registerOption('paste_tab_spaces', {
  6969. processor: 'number',
  6970. default: 4
  6971. });
  6972. registerOption('text_patterns', {
  6973. processor: value => {
  6974. if (isArrayOf(value, isObject) || value === false) {
  6975. const patterns = value === false ? [] : value;
  6976. return {
  6977. value: fromRawPatterns(patterns),
  6978. valid: true
  6979. };
  6980. } else {
  6981. return {
  6982. valid: false,
  6983. message: 'Must be an array of objects or false.'
  6984. };
  6985. }
  6986. },
  6987. default: [
  6988. {
  6989. start: '*',
  6990. end: '*',
  6991. format: 'italic'
  6992. },
  6993. {
  6994. start: '**',
  6995. end: '**',
  6996. format: 'bold'
  6997. },
  6998. {
  6999. start: '#',
  7000. format: 'h1'
  7001. },
  7002. {
  7003. start: '##',
  7004. format: 'h2'
  7005. },
  7006. {
  7007. start: '###',
  7008. format: 'h3'
  7009. },
  7010. {
  7011. start: '####',
  7012. format: 'h4'
  7013. },
  7014. {
  7015. start: '#####',
  7016. format: 'h5'
  7017. },
  7018. {
  7019. start: '######',
  7020. format: 'h6'
  7021. },
  7022. {
  7023. start: '1. ',
  7024. cmd: 'InsertOrderedList'
  7025. },
  7026. {
  7027. start: '* ',
  7028. cmd: 'InsertUnorderedList'
  7029. },
  7030. {
  7031. start: '- ',
  7032. cmd: 'InsertUnorderedList'
  7033. }
  7034. ]
  7035. });
  7036. registerOption('text_patterns_lookup', {
  7037. processor: value => {
  7038. if (isFunction(value)) {
  7039. return {
  7040. value: fromRawPatternsLookup(value),
  7041. valid: true
  7042. };
  7043. } else {
  7044. return {
  7045. valid: false,
  7046. message: 'Must be a single function'
  7047. };
  7048. }
  7049. },
  7050. default: _ctx => []
  7051. });
  7052. registerOption('noneditable_class', {
  7053. processor: 'string',
  7054. default: 'mceNonEditable'
  7055. });
  7056. registerOption('editable_class', {
  7057. processor: 'string',
  7058. default: 'mceEditable'
  7059. });
  7060. registerOption('noneditable_regexp', {
  7061. processor: value => {
  7062. if (isArrayOf(value, isRegExp)) {
  7063. return {
  7064. value,
  7065. valid: true
  7066. };
  7067. } else if (isRegExp(value)) {
  7068. return {
  7069. value: [value],
  7070. valid: true
  7071. };
  7072. } else {
  7073. return {
  7074. valid: false,
  7075. message: 'Must be a RegExp or an array of RegExp.'
  7076. };
  7077. }
  7078. },
  7079. default: []
  7080. });
  7081. registerOption('table_tab_navigation', {
  7082. processor: 'boolean',
  7083. default: true
  7084. });
  7085. registerOption('highlight_on_focus', {
  7086. processor: 'boolean',
  7087. default: false
  7088. });
  7089. registerOption('xss_sanitization', {
  7090. processor: 'boolean',
  7091. default: true
  7092. });
  7093. editor.on('ScriptsLoaded', () => {
  7094. registerOption('directionality', {
  7095. processor: 'string',
  7096. default: I18n.isRtl() ? 'rtl' : undefined
  7097. });
  7098. registerOption('placeholder', {
  7099. processor: 'string',
  7100. default: DOM$a.getAttrib(editor.getElement(), 'placeholder')
  7101. });
  7102. });
  7103. };
  7104. const getIframeAttrs = option('iframe_attrs');
  7105. const getDocType = option('doctype');
  7106. const getDocumentBaseUrl = option('document_base_url');
  7107. const getBodyId = option('body_id');
  7108. const getBodyClass = option('body_class');
  7109. const getContentSecurityPolicy = option('content_security_policy');
  7110. const shouldPutBrInPre$1 = option('br_in_pre');
  7111. const getForcedRootBlock = option('forced_root_block');
  7112. const getForcedRootBlockAttrs = option('forced_root_block_attrs');
  7113. const getNewlineBehavior = option('newline_behavior');
  7114. const getBrNewLineSelector = option('br_newline_selector');
  7115. const getNoNewLineSelector = option('no_newline_selector');
  7116. const shouldKeepStyles = option('keep_styles');
  7117. const shouldEndContainerOnEmptyBlock = option('end_container_on_empty_block');
  7118. const isAutomaticUploadsEnabled = option('automatic_uploads');
  7119. const shouldReuseFileName = option('images_reuse_filename');
  7120. const shouldReplaceBlobUris = option('images_replace_blob_uris');
  7121. const getIconPackName = option('icons');
  7122. const getIconsUrl = option('icons_url');
  7123. const getImageUploadUrl = option('images_upload_url');
  7124. const getImageUploadBasePath = option('images_upload_base_path');
  7125. const getImagesUploadCredentials = option('images_upload_credentials');
  7126. const getImagesUploadHandler = option('images_upload_handler');
  7127. const shouldUseContentCssCors = option('content_css_cors');
  7128. const getReferrerPolicy = option('referrer_policy');
  7129. const getLanguageCode = option('language');
  7130. const getLanguageUrl = option('language_url');
  7131. const shouldIndentUseMargin = option('indent_use_margin');
  7132. const getIndentation = option('indentation');
  7133. const getContentCss = option('content_css');
  7134. const getContentStyle = option('content_style');
  7135. const getFontCss = option('font_css');
  7136. const getDirectionality = option('directionality');
  7137. const getInlineBoundarySelector = option('inline_boundaries_selector');
  7138. const getObjectResizing = option('object_resizing');
  7139. const getResizeImgProportional = option('resize_img_proportional');
  7140. const getPlaceholder = option('placeholder');
  7141. const getEventRoot = option('event_root');
  7142. const getServiceMessage = option('service_message');
  7143. const getTheme = option('theme');
  7144. const getThemeUrl = option('theme_url');
  7145. const getModel = option('model');
  7146. const getModelUrl = option('model_url');
  7147. const isInlineBoundariesEnabled = option('inline_boundaries');
  7148. const getFormats = option('formats');
  7149. const getPreviewStyles = option('preview_styles');
  7150. const canFormatEmptyLines = option('format_empty_lines');
  7151. const getFormatNoneditableSelector = option('format_noneditable_selector');
  7152. const getCustomUiSelector = option('custom_ui_selector');
  7153. const isInline = option('inline');
  7154. const hasHiddenInput = option('hidden_input');
  7155. const shouldPatchSubmit = option('submit_patch');
  7156. const shouldAddFormSubmitTrigger = option('add_form_submit_trigger');
  7157. const shouldAddUnloadTrigger = option('add_unload_trigger');
  7158. const getCustomUndoRedoLevels = option('custom_undo_redo_levels');
  7159. const shouldDisableNodeChange = option('disable_nodechange');
  7160. const isReadOnly$1 = option('readonly');
  7161. const hasContentCssCors = option('content_css_cors');
  7162. const getPlugins = option('plugins');
  7163. const getExternalPlugins$1 = option('external_plugins');
  7164. const shouldBlockUnsupportedDrop = option('block_unsupported_drop');
  7165. const isVisualAidsEnabled = option('visual');
  7166. const getVisualAidsTableClass = option('visual_table_class');
  7167. const getVisualAidsAnchorClass = option('visual_anchor_class');
  7168. const getIframeAriaText = option('iframe_aria_text');
  7169. const getSetupCallback = option('setup');
  7170. const getInitInstanceCallback = option('init_instance_callback');
  7171. const getUrlConverterCallback = option('urlconverter_callback');
  7172. const getAutoFocus = option('auto_focus');
  7173. const shouldBrowserSpellcheck = option('browser_spellcheck');
  7174. const getProtect = option('protect');
  7175. const shouldPasteBlockDrop = option('paste_block_drop');
  7176. const shouldPasteDataImages = option('paste_data_images');
  7177. const getPastePreProcess = option('paste_preprocess');
  7178. const getPastePostProcess = option('paste_postprocess');
  7179. const getPasteWebkitStyles = option('paste_webkit_styles');
  7180. const shouldPasteRemoveWebKitStyles = option('paste_remove_styles_if_webkit');
  7181. const shouldPasteMergeFormats = option('paste_merge_formats');
  7182. const isSmartPasteEnabled = option('smart_paste');
  7183. const isPasteAsTextEnabled = option('paste_as_text');
  7184. const getPasteTabSpaces = option('paste_tab_spaces');
  7185. const shouldAllowHtmlDataUrls = option('allow_html_data_urls');
  7186. const getTextPatterns = option('text_patterns');
  7187. const getTextPatternsLookup = option('text_patterns_lookup');
  7188. const getNonEditableClass = option('noneditable_class');
  7189. const getEditableClass = option('editable_class');
  7190. const getNonEditableRegExps = option('noneditable_regexp');
  7191. const shouldPreserveCData = option('preserve_cdata');
  7192. const shouldHighlightOnFocus = option('highlight_on_focus');
  7193. const shouldSanitizeXss = option('xss_sanitization');
  7194. const hasTextPatternsLookup = editor => editor.options.isSet('text_patterns_lookup');
  7195. const getFontStyleValues = editor => Tools.explode(editor.options.get('font_size_style_values'));
  7196. const getFontSizeClasses = editor => Tools.explode(editor.options.get('font_size_classes'));
  7197. const isEncodingXml = editor => editor.options.get('encoding') === 'xml';
  7198. const getAllowedImageFileTypes = editor => Tools.explode(editor.options.get('images_file_types'));
  7199. const hasTableTabNavigation = option('table_tab_navigation');
  7200. const isElement$3 = isElement$6;
  7201. const isText$5 = isText$a;
  7202. const removeNode$1 = node => {
  7203. const parentNode = node.parentNode;
  7204. if (parentNode) {
  7205. parentNode.removeChild(node);
  7206. }
  7207. };
  7208. const trimCount = text => {
  7209. const trimmedText = trim$1(text);
  7210. return {
  7211. count: text.length - trimmedText.length,
  7212. text: trimmedText
  7213. };
  7214. };
  7215. const deleteZwspChars = caretContainer => {
  7216. let idx;
  7217. while ((idx = caretContainer.data.lastIndexOf(ZWSP$1)) !== -1) {
  7218. caretContainer.deleteData(idx, 1);
  7219. }
  7220. };
  7221. const removeUnchanged = (caretContainer, pos) => {
  7222. remove$4(caretContainer);
  7223. return pos;
  7224. };
  7225. const removeTextAndReposition = (caretContainer, pos) => {
  7226. const before = trimCount(caretContainer.data.substr(0, pos.offset()));
  7227. const after = trimCount(caretContainer.data.substr(pos.offset()));
  7228. const text = before.text + after.text;
  7229. if (text.length > 0) {
  7230. deleteZwspChars(caretContainer);
  7231. return CaretPosition(caretContainer, pos.offset() - before.count);
  7232. } else {
  7233. return pos;
  7234. }
  7235. };
  7236. const removeElementAndReposition = (caretContainer, pos) => {
  7237. const parentNode = pos.container();
  7238. const newPosition = indexOf$1(from(parentNode.childNodes), caretContainer).map(index => {
  7239. return index < pos.offset() ? CaretPosition(parentNode, pos.offset() - 1) : pos;
  7240. }).getOr(pos);
  7241. remove$4(caretContainer);
  7242. return newPosition;
  7243. };
  7244. const removeTextCaretContainer = (caretContainer, pos) => isText$5(caretContainer) && pos.container() === caretContainer ? removeTextAndReposition(caretContainer, pos) : removeUnchanged(caretContainer, pos);
  7245. const removeElementCaretContainer = (caretContainer, pos) => pos.container() === caretContainer.parentNode ? removeElementAndReposition(caretContainer, pos) : removeUnchanged(caretContainer, pos);
  7246. const removeAndReposition = (container, pos) => CaretPosition.isTextPosition(pos) ? removeTextCaretContainer(container, pos) : removeElementCaretContainer(container, pos);
  7247. const remove$4 = caretContainerNode => {
  7248. if (isElement$3(caretContainerNode) && isCaretContainer$2(caretContainerNode)) {
  7249. if (hasContent(caretContainerNode)) {
  7250. caretContainerNode.removeAttribute('data-mce-caret');
  7251. } else {
  7252. removeNode$1(caretContainerNode);
  7253. }
  7254. }
  7255. if (isText$5(caretContainerNode)) {
  7256. deleteZwspChars(caretContainerNode);
  7257. if (caretContainerNode.data.length === 0) {
  7258. removeNode$1(caretContainerNode);
  7259. }
  7260. }
  7261. };
  7262. const isContentEditableFalse$8 = isContentEditableFalse$b;
  7263. const isMedia$1 = isMedia$2;
  7264. const isTableCell$1 = isTableCell$3;
  7265. const inlineFakeCaretSelector = '*[contentEditable=false],video,audio,embed,object';
  7266. const getAbsoluteClientRect = (root, element, before) => {
  7267. const clientRect = collapse(element.getBoundingClientRect(), before);
  7268. let scrollX;
  7269. let scrollY;
  7270. if (root.tagName === 'BODY') {
  7271. const docElm = root.ownerDocument.documentElement;
  7272. scrollX = root.scrollLeft || docElm.scrollLeft;
  7273. scrollY = root.scrollTop || docElm.scrollTop;
  7274. } else {
  7275. const rootRect = root.getBoundingClientRect();
  7276. scrollX = root.scrollLeft - rootRect.left;
  7277. scrollY = root.scrollTop - rootRect.top;
  7278. }
  7279. clientRect.left += scrollX;
  7280. clientRect.right += scrollX;
  7281. clientRect.top += scrollY;
  7282. clientRect.bottom += scrollY;
  7283. clientRect.width = 1;
  7284. let margin = element.offsetWidth - element.clientWidth;
  7285. if (margin > 0) {
  7286. if (before) {
  7287. margin *= -1;
  7288. }
  7289. clientRect.left += margin;
  7290. clientRect.right += margin;
  7291. }
  7292. return clientRect;
  7293. };
  7294. const trimInlineCaretContainers = root => {
  7295. var _a, _b;
  7296. const fakeCaretTargetNodes = descendants(SugarElement.fromDom(root), inlineFakeCaretSelector);
  7297. for (let i = 0; i < fakeCaretTargetNodes.length; i++) {
  7298. const node = fakeCaretTargetNodes[i].dom;
  7299. let sibling = node.previousSibling;
  7300. if (endsWithCaretContainer$1(sibling)) {
  7301. const data = sibling.data;
  7302. if (data.length === 1) {
  7303. (_a = sibling.parentNode) === null || _a === void 0 ? void 0 : _a.removeChild(sibling);
  7304. } else {
  7305. sibling.deleteData(data.length - 1, 1);
  7306. }
  7307. }
  7308. sibling = node.nextSibling;
  7309. if (startsWithCaretContainer$1(sibling)) {
  7310. const data = sibling.data;
  7311. if (data.length === 1) {
  7312. (_b = sibling.parentNode) === null || _b === void 0 ? void 0 : _b.removeChild(sibling);
  7313. } else {
  7314. sibling.deleteData(0, 1);
  7315. }
  7316. }
  7317. }
  7318. };
  7319. const FakeCaret = (editor, root, isBlock, hasFocus) => {
  7320. const lastVisualCaret = value$2();
  7321. let cursorInterval;
  7322. let caretContainerNode;
  7323. const caretBlock = getForcedRootBlock(editor);
  7324. const dom = editor.dom;
  7325. const show = (before, element) => {
  7326. let rng;
  7327. hide();
  7328. if (isTableCell$1(element)) {
  7329. return null;
  7330. }
  7331. if (isBlock(element)) {
  7332. const caretContainer = insertBlock(caretBlock, element, before);
  7333. const clientRect = getAbsoluteClientRect(root, element, before);
  7334. dom.setStyle(caretContainer, 'top', clientRect.top);
  7335. caretContainerNode = caretContainer;
  7336. const caret = dom.create('div', {
  7337. 'class': 'mce-visual-caret',
  7338. 'data-mce-bogus': 'all'
  7339. });
  7340. dom.setStyles(caret, { ...clientRect });
  7341. dom.add(root, caret);
  7342. lastVisualCaret.set({
  7343. caret,
  7344. element,
  7345. before
  7346. });
  7347. if (before) {
  7348. dom.addClass(caret, 'mce-visual-caret-before');
  7349. }
  7350. startBlink();
  7351. rng = element.ownerDocument.createRange();
  7352. rng.setStart(caretContainer, 0);
  7353. rng.setEnd(caretContainer, 0);
  7354. } else {
  7355. caretContainerNode = insertInline$1(element, before);
  7356. rng = element.ownerDocument.createRange();
  7357. if (isInlineFakeCaretTarget(caretContainerNode.nextSibling)) {
  7358. rng.setStart(caretContainerNode, 0);
  7359. rng.setEnd(caretContainerNode, 0);
  7360. } else {
  7361. rng.setStart(caretContainerNode, 1);
  7362. rng.setEnd(caretContainerNode, 1);
  7363. }
  7364. return rng;
  7365. }
  7366. return rng;
  7367. };
  7368. const hide = () => {
  7369. trimInlineCaretContainers(root);
  7370. if (caretContainerNode) {
  7371. remove$4(caretContainerNode);
  7372. caretContainerNode = null;
  7373. }
  7374. lastVisualCaret.on(caretState => {
  7375. dom.remove(caretState.caret);
  7376. lastVisualCaret.clear();
  7377. });
  7378. if (cursorInterval) {
  7379. clearInterval(cursorInterval);
  7380. cursorInterval = undefined;
  7381. }
  7382. };
  7383. const startBlink = () => {
  7384. cursorInterval = setInterval(() => {
  7385. lastVisualCaret.on(caretState => {
  7386. if (hasFocus()) {
  7387. dom.toggleClass(caretState.caret, 'mce-visual-caret-hidden');
  7388. } else {
  7389. dom.addClass(caretState.caret, 'mce-visual-caret-hidden');
  7390. }
  7391. });
  7392. }, 500);
  7393. };
  7394. const reposition = () => {
  7395. lastVisualCaret.on(caretState => {
  7396. const clientRect = getAbsoluteClientRect(root, caretState.element, caretState.before);
  7397. dom.setStyles(caretState.caret, { ...clientRect });
  7398. });
  7399. };
  7400. const destroy = () => clearInterval(cursorInterval);
  7401. 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;' + '}';
  7402. return {
  7403. show,
  7404. hide,
  7405. getCss,
  7406. reposition,
  7407. destroy
  7408. };
  7409. };
  7410. const isFakeCaretTableBrowser = () => Env.browser.isFirefox();
  7411. const isInlineFakeCaretTarget = node => isContentEditableFalse$8(node) || isMedia$1(node);
  7412. const isFakeCaretTarget = node => {
  7413. const isTarget = isInlineFakeCaretTarget(node) || isTable$2(node) && isFakeCaretTableBrowser();
  7414. return isTarget && parentElement(SugarElement.fromDom(node)).exists(isEditable$3);
  7415. };
  7416. const isContentEditableTrue$1 = isContentEditableTrue$3;
  7417. const isContentEditableFalse$7 = isContentEditableFalse$b;
  7418. const isMedia = isMedia$2;
  7419. const isBlockLike = matchStyleValues('display', 'block table table-cell table-caption list-item');
  7420. const isCaretContainer = isCaretContainer$2;
  7421. const isCaretContainerBlock = isCaretContainerBlock$1;
  7422. const isElement$2 = isElement$6;
  7423. const isText$4 = isText$a;
  7424. const isCaretCandidate$1 = isCaretCandidate$3;
  7425. const isForwards = direction => direction > 0;
  7426. const isBackwards = direction => direction < 0;
  7427. const skipCaretContainers = (walk, shallow) => {
  7428. let node;
  7429. while (node = walk(shallow)) {
  7430. if (!isCaretContainerBlock(node)) {
  7431. return node;
  7432. }
  7433. }
  7434. return null;
  7435. };
  7436. const findNode = (node, direction, predicateFn, rootNode, shallow) => {
  7437. const walker = new DomTreeWalker(node, rootNode);
  7438. const isCefOrCaretContainer = isContentEditableFalse$7(node) || isCaretContainerBlock(node);
  7439. let tempNode;
  7440. if (isBackwards(direction)) {
  7441. if (isCefOrCaretContainer) {
  7442. tempNode = skipCaretContainers(walker.prev.bind(walker), true);
  7443. if (predicateFn(tempNode)) {
  7444. return tempNode;
  7445. }
  7446. }
  7447. while (tempNode = skipCaretContainers(walker.prev.bind(walker), shallow)) {
  7448. if (predicateFn(tempNode)) {
  7449. return tempNode;
  7450. }
  7451. }
  7452. }
  7453. if (isForwards(direction)) {
  7454. if (isCefOrCaretContainer) {
  7455. tempNode = skipCaretContainers(walker.next.bind(walker), true);
  7456. if (predicateFn(tempNode)) {
  7457. return tempNode;
  7458. }
  7459. }
  7460. while (tempNode = skipCaretContainers(walker.next.bind(walker), shallow)) {
  7461. if (predicateFn(tempNode)) {
  7462. return tempNode;
  7463. }
  7464. }
  7465. }
  7466. return null;
  7467. };
  7468. const getEditingHost = (node, rootNode) => {
  7469. const isCETrue = node => isContentEditableTrue$1(node.dom);
  7470. const isRoot = node => node.dom === rootNode;
  7471. return ancestor$4(SugarElement.fromDom(node), isCETrue, isRoot).map(elm => elm.dom).getOr(rootNode);
  7472. };
  7473. const getParentBlock$3 = (node, rootNode) => {
  7474. while (node && node !== rootNode) {
  7475. if (isBlockLike(node)) {
  7476. return node;
  7477. }
  7478. node = node.parentNode;
  7479. }
  7480. return null;
  7481. };
  7482. const isInSameBlock = (caretPosition1, caretPosition2, rootNode) => getParentBlock$3(caretPosition1.container(), rootNode) === getParentBlock$3(caretPosition2.container(), rootNode);
  7483. const getChildNodeAtRelativeOffset = (relativeOffset, caretPosition) => {
  7484. if (!caretPosition) {
  7485. return Optional.none();
  7486. }
  7487. const container = caretPosition.container();
  7488. const offset = caretPosition.offset();
  7489. if (!isElement$2(container)) {
  7490. return Optional.none();
  7491. }
  7492. return Optional.from(container.childNodes[offset + relativeOffset]);
  7493. };
  7494. const beforeAfter = (before, node) => {
  7495. var _a;
  7496. const doc = (_a = node.ownerDocument) !== null && _a !== void 0 ? _a : document;
  7497. const range = doc.createRange();
  7498. if (before) {
  7499. range.setStartBefore(node);
  7500. range.setEndBefore(node);
  7501. } else {
  7502. range.setStartAfter(node);
  7503. range.setEndAfter(node);
  7504. }
  7505. return range;
  7506. };
  7507. const isNodesInSameBlock = (root, node1, node2) => getParentBlock$3(node1, root) === getParentBlock$3(node2, root);
  7508. const lean = (left, root, node) => {
  7509. const siblingName = left ? 'previousSibling' : 'nextSibling';
  7510. let tempNode = node;
  7511. while (tempNode && tempNode !== root) {
  7512. let sibling = tempNode[siblingName];
  7513. if (sibling && isCaretContainer(sibling)) {
  7514. sibling = sibling[siblingName];
  7515. }
  7516. if (isContentEditableFalse$7(sibling) || isMedia(sibling)) {
  7517. if (isNodesInSameBlock(root, sibling, tempNode)) {
  7518. return sibling;
  7519. }
  7520. break;
  7521. }
  7522. if (isCaretCandidate$1(sibling)) {
  7523. break;
  7524. }
  7525. tempNode = tempNode.parentNode;
  7526. }
  7527. return null;
  7528. };
  7529. const before$2 = curry(beforeAfter, true);
  7530. const after$2 = curry(beforeAfter, false);
  7531. const normalizeRange = (direction, root, range) => {
  7532. let node;
  7533. const leanLeft = curry(lean, true, root);
  7534. const leanRight = curry(lean, false, root);
  7535. const container = range.startContainer;
  7536. const offset = range.startOffset;
  7537. if (isCaretContainerBlock$1(container)) {
  7538. const block = isText$4(container) ? container.parentNode : container;
  7539. const location = block.getAttribute('data-mce-caret');
  7540. if (location === 'before') {
  7541. node = block.nextSibling;
  7542. if (isFakeCaretTarget(node)) {
  7543. return before$2(node);
  7544. }
  7545. }
  7546. if (location === 'after') {
  7547. node = block.previousSibling;
  7548. if (isFakeCaretTarget(node)) {
  7549. return after$2(node);
  7550. }
  7551. }
  7552. }
  7553. if (!range.collapsed) {
  7554. return range;
  7555. }
  7556. if (isText$a(container)) {
  7557. if (isCaretContainer(container)) {
  7558. if (direction === 1) {
  7559. node = leanRight(container);
  7560. if (node) {
  7561. return before$2(node);
  7562. }
  7563. node = leanLeft(container);
  7564. if (node) {
  7565. return after$2(node);
  7566. }
  7567. }
  7568. if (direction === -1) {
  7569. node = leanLeft(container);
  7570. if (node) {
  7571. return after$2(node);
  7572. }
  7573. node = leanRight(container);
  7574. if (node) {
  7575. return before$2(node);
  7576. }
  7577. }
  7578. return range;
  7579. }
  7580. if (endsWithCaretContainer$1(container) && offset >= container.data.length - 1) {
  7581. if (direction === 1) {
  7582. node = leanRight(container);
  7583. if (node) {
  7584. return before$2(node);
  7585. }
  7586. }
  7587. return range;
  7588. }
  7589. if (startsWithCaretContainer$1(container) && offset <= 1) {
  7590. if (direction === -1) {
  7591. node = leanLeft(container);
  7592. if (node) {
  7593. return after$2(node);
  7594. }
  7595. }
  7596. return range;
  7597. }
  7598. if (offset === container.data.length) {
  7599. node = leanRight(container);
  7600. if (node) {
  7601. return before$2(node);
  7602. }
  7603. return range;
  7604. }
  7605. if (offset === 0) {
  7606. node = leanLeft(container);
  7607. if (node) {
  7608. return after$2(node);
  7609. }
  7610. return range;
  7611. }
  7612. }
  7613. return range;
  7614. };
  7615. const getRelativeCefElm = (forward, caretPosition) => getChildNodeAtRelativeOffset(forward ? 0 : -1, caretPosition).filter(isContentEditableFalse$7);
  7616. const getNormalizedRangeEndPoint = (direction, root, range) => {
  7617. const normalizedRange = normalizeRange(direction, root, range);
  7618. return direction === -1 ? CaretPosition.fromRangeStart(normalizedRange) : CaretPosition.fromRangeEnd(normalizedRange);
  7619. };
  7620. const getElementFromPosition = pos => Optional.from(pos.getNode()).map(SugarElement.fromDom);
  7621. const getElementFromPrevPosition = pos => Optional.from(pos.getNode(true)).map(SugarElement.fromDom);
  7622. const getVisualCaretPosition = (walkFn, caretPosition) => {
  7623. let pos = caretPosition;
  7624. while (pos = walkFn(pos)) {
  7625. if (pos.isVisible()) {
  7626. return pos;
  7627. }
  7628. }
  7629. return pos;
  7630. };
  7631. const isMoveInsideSameBlock = (from, to) => {
  7632. const inSameBlock = isInSameBlock(from, to);
  7633. if (!inSameBlock && isBr$6(from.getNode())) {
  7634. return true;
  7635. }
  7636. return inSameBlock;
  7637. };
  7638. var HDirection;
  7639. (function (HDirection) {
  7640. HDirection[HDirection['Backwards'] = -1] = 'Backwards';
  7641. HDirection[HDirection['Forwards'] = 1] = 'Forwards';
  7642. }(HDirection || (HDirection = {})));
  7643. const isContentEditableFalse$6 = isContentEditableFalse$b;
  7644. const isText$3 = isText$a;
  7645. const isElement$1 = isElement$6;
  7646. const isBr$2 = isBr$6;
  7647. const isCaretCandidate = isCaretCandidate$3;
  7648. const isAtomic = isAtomic$1;
  7649. const isEditableCaretCandidate = isEditableCaretCandidate$1;
  7650. const getParents$3 = (node, root) => {
  7651. const parents = [];
  7652. let tempNode = node;
  7653. while (tempNode && tempNode !== root) {
  7654. parents.push(tempNode);
  7655. tempNode = tempNode.parentNode;
  7656. }
  7657. return parents;
  7658. };
  7659. const nodeAtIndex = (container, offset) => {
  7660. if (container.hasChildNodes() && offset < container.childNodes.length) {
  7661. return container.childNodes[offset];
  7662. }
  7663. return null;
  7664. };
  7665. const getCaretCandidatePosition = (direction, node) => {
  7666. if (isForwards(direction)) {
  7667. if (isCaretCandidate(node.previousSibling) && !isText$3(node.previousSibling)) {
  7668. return CaretPosition.before(node);
  7669. }
  7670. if (isText$3(node)) {
  7671. return CaretPosition(node, 0);
  7672. }
  7673. }
  7674. if (isBackwards(direction)) {
  7675. if (isCaretCandidate(node.nextSibling) && !isText$3(node.nextSibling)) {
  7676. return CaretPosition.after(node);
  7677. }
  7678. if (isText$3(node)) {
  7679. return CaretPosition(node, node.data.length);
  7680. }
  7681. }
  7682. if (isBackwards(direction)) {
  7683. if (isBr$2(node)) {
  7684. return CaretPosition.before(node);
  7685. }
  7686. return CaretPosition.after(node);
  7687. }
  7688. return CaretPosition.before(node);
  7689. };
  7690. const moveForwardFromBr = (root, nextNode) => {
  7691. const nextSibling = nextNode.nextSibling;
  7692. if (nextSibling && isCaretCandidate(nextSibling)) {
  7693. if (isText$3(nextSibling)) {
  7694. return CaretPosition(nextSibling, 0);
  7695. } else {
  7696. return CaretPosition.before(nextSibling);
  7697. }
  7698. } else {
  7699. return findCaretPosition$1(HDirection.Forwards, CaretPosition.after(nextNode), root);
  7700. }
  7701. };
  7702. const findCaretPosition$1 = (direction, startPos, root) => {
  7703. let node;
  7704. let nextNode;
  7705. let innerNode;
  7706. let caretPosition;
  7707. if (!isElement$1(root) || !startPos) {
  7708. return null;
  7709. }
  7710. if (startPos.isEqual(CaretPosition.after(root)) && root.lastChild) {
  7711. caretPosition = CaretPosition.after(root.lastChild);
  7712. if (isBackwards(direction) && isCaretCandidate(root.lastChild) && isElement$1(root.lastChild)) {
  7713. return isBr$2(root.lastChild) ? CaretPosition.before(root.lastChild) : caretPosition;
  7714. }
  7715. } else {
  7716. caretPosition = startPos;
  7717. }
  7718. const container = caretPosition.container();
  7719. let offset = caretPosition.offset();
  7720. if (isText$3(container)) {
  7721. if (isBackwards(direction) && offset > 0) {
  7722. return CaretPosition(container, --offset);
  7723. }
  7724. if (isForwards(direction) && offset < container.length) {
  7725. return CaretPosition(container, ++offset);
  7726. }
  7727. node = container;
  7728. } else {
  7729. if (isBackwards(direction) && offset > 0) {
  7730. nextNode = nodeAtIndex(container, offset - 1);
  7731. if (isCaretCandidate(nextNode)) {
  7732. if (!isAtomic(nextNode)) {
  7733. innerNode = findNode(nextNode, direction, isEditableCaretCandidate, nextNode);
  7734. if (innerNode) {
  7735. if (isText$3(innerNode)) {
  7736. return CaretPosition(innerNode, innerNode.data.length);
  7737. }
  7738. return CaretPosition.after(innerNode);
  7739. }
  7740. }
  7741. if (isText$3(nextNode)) {
  7742. return CaretPosition(nextNode, nextNode.data.length);
  7743. }
  7744. return CaretPosition.before(nextNode);
  7745. }
  7746. }
  7747. if (isForwards(direction) && offset < container.childNodes.length) {
  7748. nextNode = nodeAtIndex(container, offset);
  7749. if (isCaretCandidate(nextNode)) {
  7750. if (isBr$2(nextNode)) {
  7751. return moveForwardFromBr(root, nextNode);
  7752. }
  7753. if (!isAtomic(nextNode)) {
  7754. innerNode = findNode(nextNode, direction, isEditableCaretCandidate, nextNode);
  7755. if (innerNode) {
  7756. if (isText$3(innerNode)) {
  7757. return CaretPosition(innerNode, 0);
  7758. }
  7759. return CaretPosition.before(innerNode);
  7760. }
  7761. }
  7762. if (isText$3(nextNode)) {
  7763. return CaretPosition(nextNode, 0);
  7764. }
  7765. return CaretPosition.after(nextNode);
  7766. }
  7767. }
  7768. node = nextNode ? nextNode : caretPosition.getNode();
  7769. }
  7770. if (node && (isForwards(direction) && caretPosition.isAtEnd() || isBackwards(direction) && caretPosition.isAtStart())) {
  7771. node = findNode(node, direction, always, root, true);
  7772. if (isEditableCaretCandidate(node, root)) {
  7773. return getCaretCandidatePosition(direction, node);
  7774. }
  7775. }
  7776. nextNode = node ? findNode(node, direction, isEditableCaretCandidate, root) : node;
  7777. const rootContentEditableFalseElm = last$2(filter$5(getParents$3(container, root), isContentEditableFalse$6));
  7778. if (rootContentEditableFalseElm && (!nextNode || !rootContentEditableFalseElm.contains(nextNode))) {
  7779. if (isForwards(direction)) {
  7780. caretPosition = CaretPosition.after(rootContentEditableFalseElm);
  7781. } else {
  7782. caretPosition = CaretPosition.before(rootContentEditableFalseElm);
  7783. }
  7784. return caretPosition;
  7785. }
  7786. if (nextNode) {
  7787. return getCaretCandidatePosition(direction, nextNode);
  7788. }
  7789. return null;
  7790. };
  7791. const CaretWalker = root => ({
  7792. next: caretPosition => {
  7793. return findCaretPosition$1(HDirection.Forwards, caretPosition, root);
  7794. },
  7795. prev: caretPosition => {
  7796. return findCaretPosition$1(HDirection.Backwards, caretPosition, root);
  7797. }
  7798. });
  7799. const walkToPositionIn = (forward, root, start) => {
  7800. const position = forward ? CaretPosition.before(start) : CaretPosition.after(start);
  7801. return fromPosition(forward, root, position);
  7802. };
  7803. const afterElement = node => isBr$6(node) ? CaretPosition.before(node) : CaretPosition.after(node);
  7804. const isBeforeOrStart = position => {
  7805. if (CaretPosition.isTextPosition(position)) {
  7806. return position.offset() === 0;
  7807. } else {
  7808. return isCaretCandidate$3(position.getNode());
  7809. }
  7810. };
  7811. const isAfterOrEnd = position => {
  7812. if (CaretPosition.isTextPosition(position)) {
  7813. const container = position.container();
  7814. return position.offset() === container.data.length;
  7815. } else {
  7816. return isCaretCandidate$3(position.getNode(true));
  7817. }
  7818. };
  7819. const isBeforeAfterSameElement = (from, to) => !CaretPosition.isTextPosition(from) && !CaretPosition.isTextPosition(to) && from.getNode() === to.getNode(true);
  7820. const isAtBr = position => !CaretPosition.isTextPosition(position) && isBr$6(position.getNode());
  7821. const shouldSkipPosition = (forward, from, to) => {
  7822. if (forward) {
  7823. return !isBeforeAfterSameElement(from, to) && !isAtBr(from) && isAfterOrEnd(from) && isBeforeOrStart(to);
  7824. } else {
  7825. return !isBeforeAfterSameElement(to, from) && isBeforeOrStart(from) && isAfterOrEnd(to);
  7826. }
  7827. };
  7828. const fromPosition = (forward, root, pos) => {
  7829. const walker = CaretWalker(root);
  7830. return Optional.from(forward ? walker.next(pos) : walker.prev(pos));
  7831. };
  7832. const navigate = (forward, root, from) => fromPosition(forward, root, from).bind(to => {
  7833. if (isInSameBlock(from, to, root) && shouldSkipPosition(forward, from, to)) {
  7834. return fromPosition(forward, root, to);
  7835. } else {
  7836. return Optional.some(to);
  7837. }
  7838. });
  7839. const navigateIgnore = (forward, root, from, ignoreFilter) => navigate(forward, root, from).bind(pos => ignoreFilter(pos) ? navigateIgnore(forward, root, pos, ignoreFilter) : Optional.some(pos));
  7840. const positionIn = (forward, element) => {
  7841. const startNode = forward ? element.firstChild : element.lastChild;
  7842. if (isText$a(startNode)) {
  7843. return Optional.some(CaretPosition(startNode, forward ? 0 : startNode.data.length));
  7844. } else if (startNode) {
  7845. if (isCaretCandidate$3(startNode)) {
  7846. return Optional.some(forward ? CaretPosition.before(startNode) : afterElement(startNode));
  7847. } else {
  7848. return walkToPositionIn(forward, element, startNode);
  7849. }
  7850. } else {
  7851. return Optional.none();
  7852. }
  7853. };
  7854. const nextPosition = curry(fromPosition, true);
  7855. const prevPosition = curry(fromPosition, false);
  7856. const firstPositionIn = curry(positionIn, true);
  7857. const lastPositionIn = curry(positionIn, false);
  7858. const CARET_ID = '_mce_caret';
  7859. const isCaretNode = node => isElement$6(node) && node.id === CARET_ID;
  7860. const getParentCaretContainer = (body, node) => {
  7861. let currentNode = node;
  7862. while (currentNode && currentNode !== body) {
  7863. if (isCaretNode(currentNode)) {
  7864. return currentNode;
  7865. }
  7866. currentNode = currentNode.parentNode;
  7867. }
  7868. return null;
  7869. };
  7870. const isStringPathBookmark = bookmark => isString(bookmark.start);
  7871. const isRangeBookmark = bookmark => has$2(bookmark, 'rng');
  7872. const isIdBookmark = bookmark => has$2(bookmark, 'id');
  7873. const isIndexBookmark = bookmark => has$2(bookmark, 'name');
  7874. const isPathBookmark = bookmark => Tools.isArray(bookmark.start);
  7875. const isForwardBookmark = bookmark => !isIndexBookmark(bookmark) && isBoolean(bookmark.forward) ? bookmark.forward : true;
  7876. const addBogus = (dom, node) => {
  7877. if (isElement$6(node) && dom.isBlock(node) && !node.innerHTML) {
  7878. node.innerHTML = '<br data-mce-bogus="1" />';
  7879. }
  7880. return node;
  7881. };
  7882. const resolveCaretPositionBookmark = (dom, bookmark) => {
  7883. const startPos = Optional.from(resolve$1(dom.getRoot(), bookmark.start));
  7884. const endPos = Optional.from(resolve$1(dom.getRoot(), bookmark.end));
  7885. return lift2(startPos, endPos, (start, end) => {
  7886. const range = dom.createRng();
  7887. range.setStart(start.container(), start.offset());
  7888. range.setEnd(end.container(), end.offset());
  7889. return {
  7890. range,
  7891. forward: isForwardBookmark(bookmark)
  7892. };
  7893. });
  7894. };
  7895. const insertZwsp = (node, rng) => {
  7896. var _a;
  7897. const doc = (_a = node.ownerDocument) !== null && _a !== void 0 ? _a : document;
  7898. const textNode = doc.createTextNode(ZWSP$1);
  7899. node.appendChild(textNode);
  7900. rng.setStart(textNode, 0);
  7901. rng.setEnd(textNode, 0);
  7902. };
  7903. const isEmpty$1 = node => !node.hasChildNodes();
  7904. const tryFindRangePosition = (node, rng) => lastPositionIn(node).fold(never, pos => {
  7905. rng.setStart(pos.container(), pos.offset());
  7906. rng.setEnd(pos.container(), pos.offset());
  7907. return true;
  7908. });
  7909. const padEmptyCaretContainer = (root, node, rng) => {
  7910. if (isEmpty$1(node) && getParentCaretContainer(root, node)) {
  7911. insertZwsp(node, rng);
  7912. return true;
  7913. } else {
  7914. return false;
  7915. }
  7916. };
  7917. const setEndPoint = (dom, start, bookmark, rng) => {
  7918. const point = bookmark[start ? 'start' : 'end'];
  7919. const root = dom.getRoot();
  7920. if (point) {
  7921. let node = root;
  7922. let offset = point[0];
  7923. for (let i = point.length - 1; node && i >= 1; i--) {
  7924. const children = node.childNodes;
  7925. if (padEmptyCaretContainer(root, node, rng)) {
  7926. return true;
  7927. }
  7928. if (point[i] > children.length - 1) {
  7929. if (padEmptyCaretContainer(root, node, rng)) {
  7930. return true;
  7931. }
  7932. return tryFindRangePosition(node, rng);
  7933. }
  7934. node = children[point[i]];
  7935. }
  7936. if (isText$a(node)) {
  7937. offset = Math.min(point[0], node.data.length);
  7938. }
  7939. if (isElement$6(node)) {
  7940. offset = Math.min(point[0], node.childNodes.length);
  7941. }
  7942. if (start) {
  7943. rng.setStart(node, offset);
  7944. } else {
  7945. rng.setEnd(node, offset);
  7946. }
  7947. }
  7948. return true;
  7949. };
  7950. const isValidTextNode = node => isText$a(node) && node.data.length > 0;
  7951. const restoreEndPoint = (dom, suffix, bookmark) => {
  7952. const marker = dom.get(bookmark.id + '_' + suffix);
  7953. const markerParent = marker === null || marker === void 0 ? void 0 : marker.parentNode;
  7954. const keep = bookmark.keep;
  7955. if (marker && markerParent) {
  7956. let container;
  7957. let offset;
  7958. if (suffix === 'start') {
  7959. if (!keep) {
  7960. container = markerParent;
  7961. offset = dom.nodeIndex(marker);
  7962. } else {
  7963. if (marker.hasChildNodes()) {
  7964. container = marker.firstChild;
  7965. offset = 1;
  7966. } else if (isValidTextNode(marker.nextSibling)) {
  7967. container = marker.nextSibling;
  7968. offset = 0;
  7969. } else if (isValidTextNode(marker.previousSibling)) {
  7970. container = marker.previousSibling;
  7971. offset = marker.previousSibling.data.length;
  7972. } else {
  7973. container = markerParent;
  7974. offset = dom.nodeIndex(marker) + 1;
  7975. }
  7976. }
  7977. } else {
  7978. if (!keep) {
  7979. container = markerParent;
  7980. offset = dom.nodeIndex(marker);
  7981. } else {
  7982. if (marker.hasChildNodes()) {
  7983. container = marker.firstChild;
  7984. offset = 1;
  7985. } else if (isValidTextNode(marker.previousSibling)) {
  7986. container = marker.previousSibling;
  7987. offset = marker.previousSibling.data.length;
  7988. } else {
  7989. container = markerParent;
  7990. offset = dom.nodeIndex(marker);
  7991. }
  7992. }
  7993. }
  7994. if (!keep) {
  7995. const prev = marker.previousSibling;
  7996. const next = marker.nextSibling;
  7997. Tools.each(Tools.grep(marker.childNodes), node => {
  7998. if (isText$a(node)) {
  7999. node.data = node.data.replace(/\uFEFF/g, '');
  8000. }
  8001. });
  8002. let otherMarker;
  8003. while (otherMarker = dom.get(bookmark.id + '_' + suffix)) {
  8004. dom.remove(otherMarker, true);
  8005. }
  8006. if (isText$a(next) && isText$a(prev) && !Env.browser.isOpera()) {
  8007. const idx = prev.data.length;
  8008. prev.appendData(next.data);
  8009. dom.remove(next);
  8010. container = prev;
  8011. offset = idx;
  8012. }
  8013. }
  8014. return Optional.some(CaretPosition(container, offset));
  8015. } else {
  8016. return Optional.none();
  8017. }
  8018. };
  8019. const resolvePaths = (dom, bookmark) => {
  8020. const range = dom.createRng();
  8021. if (setEndPoint(dom, true, bookmark, range) && setEndPoint(dom, false, bookmark, range)) {
  8022. return Optional.some({
  8023. range,
  8024. forward: isForwardBookmark(bookmark)
  8025. });
  8026. } else {
  8027. return Optional.none();
  8028. }
  8029. };
  8030. const resolveId = (dom, bookmark) => {
  8031. const startPos = restoreEndPoint(dom, 'start', bookmark);
  8032. const endPos = restoreEndPoint(dom, 'end', bookmark);
  8033. return lift2(startPos, endPos.or(startPos), (spos, epos) => {
  8034. const range = dom.createRng();
  8035. range.setStart(addBogus(dom, spos.container()), spos.offset());
  8036. range.setEnd(addBogus(dom, epos.container()), epos.offset());
  8037. return {
  8038. range,
  8039. forward: isForwardBookmark(bookmark)
  8040. };
  8041. });
  8042. };
  8043. const resolveIndex = (dom, bookmark) => Optional.from(dom.select(bookmark.name)[bookmark.index]).map(elm => {
  8044. const range = dom.createRng();
  8045. range.selectNode(elm);
  8046. return {
  8047. range,
  8048. forward: true
  8049. };
  8050. });
  8051. const resolve = (selection, bookmark) => {
  8052. const dom = selection.dom;
  8053. if (bookmark) {
  8054. if (isPathBookmark(bookmark)) {
  8055. return resolvePaths(dom, bookmark);
  8056. } else if (isStringPathBookmark(bookmark)) {
  8057. return resolveCaretPositionBookmark(dom, bookmark);
  8058. } else if (isIdBookmark(bookmark)) {
  8059. return resolveId(dom, bookmark);
  8060. } else if (isIndexBookmark(bookmark)) {
  8061. return resolveIndex(dom, bookmark);
  8062. } else if (isRangeBookmark(bookmark)) {
  8063. return Optional.some({
  8064. range: bookmark.rng,
  8065. forward: isForwardBookmark(bookmark)
  8066. });
  8067. }
  8068. }
  8069. return Optional.none();
  8070. };
  8071. const getBookmark$1 = (selection, type, normalized) => {
  8072. return getBookmark$2(selection, type, normalized);
  8073. };
  8074. const moveToBookmark = (selection, bookmark) => {
  8075. resolve(selection, bookmark).each(({range, forward}) => {
  8076. selection.setRng(range, forward);
  8077. });
  8078. };
  8079. const isBookmarkNode$1 = node => {
  8080. return isElement$6(node) && node.tagName === 'SPAN' && node.getAttribute('data-mce-type') === 'bookmark';
  8081. };
  8082. const is = expected => actual => expected === actual;
  8083. const isNbsp = is(nbsp);
  8084. const isWhiteSpace = chr => chr !== '' && ' \f\n\r\t\x0B'.indexOf(chr) !== -1;
  8085. const isContent = chr => !isWhiteSpace(chr) && !isNbsp(chr) && !isZwsp$1(chr);
  8086. const hexColour = value => ({ value: normalizeHex(value) });
  8087. const normalizeHex = hex => removeLeading(hex, '#').toUpperCase();
  8088. const toHex = component => {
  8089. const hex = component.toString(16);
  8090. return (hex.length === 1 ? '0' + hex : hex).toUpperCase();
  8091. };
  8092. const fromRgba = rgbaColour => {
  8093. const value = toHex(rgbaColour.red) + toHex(rgbaColour.green) + toHex(rgbaColour.blue);
  8094. return hexColour(value);
  8095. };
  8096. const rgbRegex = /^\s*rgb\s*\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*\)\s*$/i;
  8097. const rgbaRegex = /^\s*rgba\s*\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d?(?:\.\d+)?)\s*\)\s*$/i;
  8098. const rgbaColour = (red, green, blue, alpha) => ({
  8099. red,
  8100. green,
  8101. blue,
  8102. alpha
  8103. });
  8104. const fromStringValues = (red, green, blue, alpha) => {
  8105. const r = parseInt(red, 10);
  8106. const g = parseInt(green, 10);
  8107. const b = parseInt(blue, 10);
  8108. const a = parseFloat(alpha);
  8109. return rgbaColour(r, g, b, a);
  8110. };
  8111. const fromString = rgbaString => {
  8112. if (rgbaString === 'transparent') {
  8113. return Optional.some(rgbaColour(0, 0, 0, 0));
  8114. }
  8115. const rgbMatch = rgbRegex.exec(rgbaString);
  8116. if (rgbMatch !== null) {
  8117. return Optional.some(fromStringValues(rgbMatch[1], rgbMatch[2], rgbMatch[3], '1'));
  8118. }
  8119. const rgbaMatch = rgbaRegex.exec(rgbaString);
  8120. if (rgbaMatch !== null) {
  8121. return Optional.some(fromStringValues(rgbaMatch[1], rgbaMatch[2], rgbaMatch[3], rgbaMatch[4]));
  8122. }
  8123. return Optional.none();
  8124. };
  8125. const rgbaToHexString = color => fromString(color).map(fromRgba).map(h => '#' + h.value).getOr(color);
  8126. const getRanges$1 = selection => {
  8127. const ranges = [];
  8128. if (selection) {
  8129. for (let i = 0; i < selection.rangeCount; i++) {
  8130. ranges.push(selection.getRangeAt(i));
  8131. }
  8132. }
  8133. return ranges;
  8134. };
  8135. const getSelectedNodes = ranges => {
  8136. return bind$3(ranges, range => {
  8137. const node = getSelectedNode(range);
  8138. return node ? [SugarElement.fromDom(node)] : [];
  8139. });
  8140. };
  8141. const hasMultipleRanges = selection => {
  8142. return getRanges$1(selection).length > 1;
  8143. };
  8144. const getCellsFromRanges = ranges => filter$5(getSelectedNodes(ranges), isTableCell$2);
  8145. const getCellsFromElement = elm => descendants(elm, 'td[data-mce-selected],th[data-mce-selected]');
  8146. const getCellsFromElementOrRanges = (ranges, element) => {
  8147. const selectedCells = getCellsFromElement(element);
  8148. return selectedCells.length > 0 ? selectedCells : getCellsFromRanges(ranges);
  8149. };
  8150. const getCellsFromEditor = editor => getCellsFromElementOrRanges(getRanges$1(editor.selection.getSel()), SugarElement.fromDom(editor.getBody()));
  8151. const getClosestTable = (cell, isRoot) => ancestor$3(cell, 'table', isRoot);
  8152. const getStartNode = rng => {
  8153. const sc = rng.startContainer, so = rng.startOffset;
  8154. if (isText$a(sc)) {
  8155. return so === 0 ? Optional.some(SugarElement.fromDom(sc)) : Optional.none();
  8156. } else {
  8157. return Optional.from(sc.childNodes[so]).map(SugarElement.fromDom);
  8158. }
  8159. };
  8160. const getEndNode = rng => {
  8161. const ec = rng.endContainer, eo = rng.endOffset;
  8162. if (isText$a(ec)) {
  8163. return eo === ec.data.length ? Optional.some(SugarElement.fromDom(ec)) : Optional.none();
  8164. } else {
  8165. return Optional.from(ec.childNodes[eo - 1]).map(SugarElement.fromDom);
  8166. }
  8167. };
  8168. const getFirstChildren = node => {
  8169. return firstChild(node).fold(constant([node]), child => {
  8170. return [node].concat(getFirstChildren(child));
  8171. });
  8172. };
  8173. const getLastChildren = node => {
  8174. return lastChild(node).fold(constant([node]), child => {
  8175. if (name(child) === 'br') {
  8176. return prevSibling(child).map(sibling => {
  8177. return [node].concat(getLastChildren(sibling));
  8178. }).getOr([]);
  8179. } else {
  8180. return [node].concat(getLastChildren(child));
  8181. }
  8182. });
  8183. };
  8184. const hasAllContentsSelected = (elm, rng) => {
  8185. return lift2(getStartNode(rng), getEndNode(rng), (startNode, endNode) => {
  8186. const start = find$2(getFirstChildren(elm), curry(eq, startNode));
  8187. const end = find$2(getLastChildren(elm), curry(eq, endNode));
  8188. return start.isSome() && end.isSome();
  8189. }).getOr(false);
  8190. };
  8191. const moveEndPoint = (dom, rng, node, start) => {
  8192. const root = node;
  8193. const walker = new DomTreeWalker(node, root);
  8194. const moveCaretBeforeOnEnterElementsMap = filter$4(dom.schema.getMoveCaretBeforeOnEnterElements(), (_, name) => !contains$2([
  8195. 'td',
  8196. 'th',
  8197. 'table'
  8198. ], name.toLowerCase()));
  8199. let currentNode = node;
  8200. do {
  8201. if (isText$a(currentNode) && Tools.trim(currentNode.data).length !== 0) {
  8202. if (start) {
  8203. rng.setStart(currentNode, 0);
  8204. } else {
  8205. rng.setEnd(currentNode, currentNode.data.length);
  8206. }
  8207. return;
  8208. }
  8209. if (moveCaretBeforeOnEnterElementsMap[currentNode.nodeName]) {
  8210. if (start) {
  8211. rng.setStartBefore(currentNode);
  8212. } else {
  8213. if (currentNode.nodeName === 'BR') {
  8214. rng.setEndBefore(currentNode);
  8215. } else {
  8216. rng.setEndAfter(currentNode);
  8217. }
  8218. }
  8219. return;
  8220. }
  8221. } while (currentNode = start ? walker.next() : walker.prev());
  8222. if (root.nodeName === 'BODY') {
  8223. if (start) {
  8224. rng.setStart(root, 0);
  8225. } else {
  8226. rng.setEnd(root, root.childNodes.length);
  8227. }
  8228. }
  8229. };
  8230. const hasAnyRanges = editor => {
  8231. const sel = editor.selection.getSel();
  8232. return isNonNullable(sel) && sel.rangeCount > 0;
  8233. };
  8234. const runOnRanges = (editor, executor) => {
  8235. const fakeSelectionNodes = getCellsFromEditor(editor);
  8236. if (fakeSelectionNodes.length > 0) {
  8237. each$e(fakeSelectionNodes, elem => {
  8238. const node = elem.dom;
  8239. const fakeNodeRng = editor.dom.createRng();
  8240. fakeNodeRng.setStartBefore(node);
  8241. fakeNodeRng.setEndAfter(node);
  8242. executor(fakeNodeRng, true);
  8243. });
  8244. } else {
  8245. executor(editor.selection.getRng(), false);
  8246. }
  8247. };
  8248. const preserve = (selection, fillBookmark, executor) => {
  8249. const bookmark = getPersistentBookmark(selection, fillBookmark);
  8250. executor(bookmark);
  8251. selection.moveToBookmark(bookmark);
  8252. };
  8253. const isNode = node => isNumber(node === null || node === void 0 ? void 0 : node.nodeType);
  8254. const isElementNode$1 = node => isElement$6(node) && !isBookmarkNode$1(node) && !isCaretNode(node) && !isBogus$2(node);
  8255. const isElementDirectlySelected = (dom, node) => {
  8256. if (isElementNode$1(node) && !/^(TD|TH)$/.test(node.nodeName)) {
  8257. const selectedAttr = dom.getAttrib(node, 'data-mce-selected');
  8258. const value = parseInt(selectedAttr, 10);
  8259. return !isNaN(value) && value > 0;
  8260. } else {
  8261. return false;
  8262. }
  8263. };
  8264. const isEditable$2 = elm => elm.isContentEditable === true;
  8265. const preserveSelection = (editor, action, shouldMoveStart) => {
  8266. const {selection, dom} = editor;
  8267. const selectedNodeBeforeAction = selection.getNode();
  8268. const isSelectedBeforeNodeNoneditable = isContentEditableFalse$b(selectedNodeBeforeAction);
  8269. preserve(selection, true, () => {
  8270. action();
  8271. });
  8272. const isBeforeNodeStillNoneditable = isSelectedBeforeNodeNoneditable && isContentEditableFalse$b(selectedNodeBeforeAction);
  8273. if (isBeforeNodeStillNoneditable && dom.isChildOf(selectedNodeBeforeAction, editor.getBody())) {
  8274. editor.selection.select(selectedNodeBeforeAction);
  8275. } else if (shouldMoveStart(selection.getStart())) {
  8276. moveStartToNearestText(dom, selection);
  8277. }
  8278. };
  8279. const moveStartToNearestText = (dom, selection) => {
  8280. var _a, _b;
  8281. const rng = selection.getRng();
  8282. const {startContainer, startOffset} = rng;
  8283. const selectedNode = selection.getNode();
  8284. if (isElementDirectlySelected(dom, selectedNode)) {
  8285. return;
  8286. }
  8287. if (isElement$6(startContainer)) {
  8288. const nodes = startContainer.childNodes;
  8289. const root = dom.getRoot();
  8290. let walker;
  8291. if (startOffset < nodes.length) {
  8292. const startNode = nodes[startOffset];
  8293. walker = new DomTreeWalker(startNode, (_a = dom.getParent(startNode, dom.isBlock)) !== null && _a !== void 0 ? _a : root);
  8294. } else {
  8295. const startNode = nodes[nodes.length - 1];
  8296. walker = new DomTreeWalker(startNode, (_b = dom.getParent(startNode, dom.isBlock)) !== null && _b !== void 0 ? _b : root);
  8297. walker.next(true);
  8298. }
  8299. for (let node = walker.current(); node; node = walker.next()) {
  8300. if (dom.getContentEditable(node) === 'false') {
  8301. return;
  8302. } else if (isText$a(node) && !isWhiteSpaceNode$1(node)) {
  8303. rng.setStart(node, 0);
  8304. selection.setRng(rng);
  8305. return;
  8306. }
  8307. }
  8308. }
  8309. };
  8310. const getNonWhiteSpaceSibling = (node, next, inc) => {
  8311. if (node) {
  8312. const nextName = next ? 'nextSibling' : 'previousSibling';
  8313. for (node = inc ? node : node[nextName]; node; node = node[nextName]) {
  8314. if (isElement$6(node) || !isWhiteSpaceNode$1(node)) {
  8315. return node;
  8316. }
  8317. }
  8318. }
  8319. return undefined;
  8320. };
  8321. const isTextBlock$1 = (schema, node) => !!schema.getTextBlockElements()[node.nodeName.toLowerCase()] || isTransparentBlock(schema, node);
  8322. const isValid = (ed, parent, child) => {
  8323. return ed.schema.isValidChild(parent, child);
  8324. };
  8325. const isWhiteSpaceNode$1 = (node, allowSpaces = false) => {
  8326. if (isNonNullable(node) && isText$a(node)) {
  8327. const data = allowSpaces ? node.data.replace(/ /g, '\xA0') : node.data;
  8328. return isWhitespaceText(data);
  8329. } else {
  8330. return false;
  8331. }
  8332. };
  8333. const isEmptyTextNode$1 = node => {
  8334. return isNonNullable(node) && isText$a(node) && node.length === 0;
  8335. };
  8336. const isWrapNoneditableTarget = (editor, node) => {
  8337. const baseDataSelector = '[data-mce-cef-wrappable]';
  8338. const formatNoneditableSelector = getFormatNoneditableSelector(editor);
  8339. const selector = isEmpty$3(formatNoneditableSelector) ? baseDataSelector : `${ baseDataSelector },${ formatNoneditableSelector }`;
  8340. return is$1(SugarElement.fromDom(node), selector);
  8341. };
  8342. const isWrappableNoneditable = (editor, node) => {
  8343. const dom = editor.dom;
  8344. return isElementNode$1(node) && dom.getContentEditable(node) === 'false' && isWrapNoneditableTarget(editor, node) && dom.select('[contenteditable="true"]', node).length === 0;
  8345. };
  8346. const replaceVars = (value, vars) => {
  8347. if (isFunction(value)) {
  8348. return value(vars);
  8349. } else if (isNonNullable(vars)) {
  8350. value = value.replace(/%(\w+)/g, (str, name) => {
  8351. return vars[name] || str;
  8352. });
  8353. }
  8354. return value;
  8355. };
  8356. const isEq$5 = (str1, str2) => {
  8357. str1 = str1 || '';
  8358. str2 = str2 || '';
  8359. str1 = '' + (str1.nodeName || str1);
  8360. str2 = '' + (str2.nodeName || str2);
  8361. return str1.toLowerCase() === str2.toLowerCase();
  8362. };
  8363. const normalizeStyleValue = (value, name) => {
  8364. if (isNullable(value)) {
  8365. return null;
  8366. } else {
  8367. let strValue = String(value);
  8368. if (name === 'color' || name === 'backgroundColor') {
  8369. strValue = rgbaToHexString(strValue);
  8370. }
  8371. if (name === 'fontWeight' && value === 700) {
  8372. strValue = 'bold';
  8373. }
  8374. if (name === 'fontFamily') {
  8375. strValue = strValue.replace(/[\'\"]/g, '').replace(/,\s+/g, ',');
  8376. }
  8377. return strValue;
  8378. }
  8379. };
  8380. const getStyle = (dom, node, name) => {
  8381. const style = dom.getStyle(node, name);
  8382. return normalizeStyleValue(style, name);
  8383. };
  8384. const getTextDecoration = (dom, node) => {
  8385. let decoration;
  8386. dom.getParent(node, n => {
  8387. if (isElement$6(n)) {
  8388. decoration = dom.getStyle(n, 'text-decoration');
  8389. return !!decoration && decoration !== 'none';
  8390. } else {
  8391. return false;
  8392. }
  8393. });
  8394. return decoration;
  8395. };
  8396. const getParents$2 = (dom, node, selector) => {
  8397. return dom.getParents(node, selector, dom.getRoot());
  8398. };
  8399. const isFormatPredicate = (editor, formatName, predicate) => {
  8400. const formats = editor.formatter.get(formatName);
  8401. return isNonNullable(formats) && exists(formats, predicate);
  8402. };
  8403. const isVariableFormatName = (editor, formatName) => {
  8404. const hasVariableValues = format => {
  8405. const isVariableValue = val => isFunction(val) || val.length > 1 && val.charAt(0) === '%';
  8406. return exists([
  8407. 'styles',
  8408. 'attributes'
  8409. ], key => get$a(format, key).exists(field => {
  8410. const fieldValues = isArray$1(field) ? field : values(field);
  8411. return exists(fieldValues, isVariableValue);
  8412. }));
  8413. };
  8414. return isFormatPredicate(editor, formatName, hasVariableValues);
  8415. };
  8416. const areSimilarFormats = (editor, formatName, otherFormatName) => {
  8417. const validKeys = [
  8418. 'inline',
  8419. 'block',
  8420. 'selector',
  8421. 'attributes',
  8422. 'styles',
  8423. 'classes'
  8424. ];
  8425. const filterObj = format => filter$4(format, (_, key) => exists(validKeys, validKey => validKey === key));
  8426. return isFormatPredicate(editor, formatName, fmt1 => {
  8427. const filteredFmt1 = filterObj(fmt1);
  8428. return isFormatPredicate(editor, otherFormatName, fmt2 => {
  8429. const filteredFmt2 = filterObj(fmt2);
  8430. return equal$1(filteredFmt1, filteredFmt2);
  8431. });
  8432. });
  8433. };
  8434. const isBlockFormat = format => hasNonNullableKey(format, 'block');
  8435. const isWrappingBlockFormat = format => isBlockFormat(format) && format.wrapper === true;
  8436. const isNonWrappingBlockFormat = format => isBlockFormat(format) && format.wrapper !== true;
  8437. const isSelectorFormat = format => hasNonNullableKey(format, 'selector');
  8438. const isInlineFormat = format => hasNonNullableKey(format, 'inline');
  8439. const isMixedFormat = format => isSelectorFormat(format) && isInlineFormat(format) && is$2(get$a(format, 'mixed'), true);
  8440. const shouldExpandToSelector = format => isSelectorFormat(format) && format.expand !== false && !isInlineFormat(format);
  8441. const isBookmarkNode = isBookmarkNode$1;
  8442. const getParents$1 = getParents$2;
  8443. const isWhiteSpaceNode = isWhiteSpaceNode$1;
  8444. const isTextBlock = isTextBlock$1;
  8445. const isBogusBr = node => {
  8446. return isBr$6(node) && node.getAttribute('data-mce-bogus') && !node.nextSibling;
  8447. };
  8448. const findParentContentEditable = (dom, node) => {
  8449. let parent = node;
  8450. while (parent) {
  8451. if (isElement$6(parent) && dom.getContentEditable(parent)) {
  8452. return dom.getContentEditable(parent) === 'false' ? parent : node;
  8453. }
  8454. parent = parent.parentNode;
  8455. }
  8456. return node;
  8457. };
  8458. const walkText = (start, node, offset, predicate) => {
  8459. const str = node.data;
  8460. if (start) {
  8461. for (let i = offset; i > 0; i--) {
  8462. if (predicate(str.charAt(i - 1))) {
  8463. return i;
  8464. }
  8465. }
  8466. } else {
  8467. for (let i = offset; i < str.length; i++) {
  8468. if (predicate(str.charAt(i))) {
  8469. return i;
  8470. }
  8471. }
  8472. }
  8473. return -1;
  8474. };
  8475. const findSpace = (start, node, offset) => walkText(start, node, offset, c => isNbsp(c) || isWhiteSpace(c));
  8476. const findContent = (start, node, offset) => walkText(start, node, offset, isContent);
  8477. const findWordEndPoint = (dom, body, container, offset, start, includeTrailingSpaces) => {
  8478. let lastTextNode;
  8479. const rootNode = dom.getParent(container, dom.isBlock) || body;
  8480. const walk = (container, offset, pred) => {
  8481. const textSeeker = TextSeeker(dom);
  8482. const walker = start ? textSeeker.backwards : textSeeker.forwards;
  8483. return Optional.from(walker(container, offset, (text, textOffset) => {
  8484. if (isBookmarkNode(text.parentNode)) {
  8485. return -1;
  8486. } else {
  8487. lastTextNode = text;
  8488. return pred(start, text, textOffset);
  8489. }
  8490. }, rootNode));
  8491. };
  8492. const spaceResult = walk(container, offset, findSpace);
  8493. return spaceResult.bind(result => includeTrailingSpaces ? walk(result.container, result.offset + (start ? -1 : 0), findContent) : Optional.some(result)).orThunk(() => lastTextNode ? Optional.some({
  8494. container: lastTextNode,
  8495. offset: start ? 0 : lastTextNode.length
  8496. }) : Optional.none());
  8497. };
  8498. const findSelectorEndPoint = (dom, formatList, rng, container, siblingName) => {
  8499. const sibling = container[siblingName];
  8500. if (isText$a(container) && isEmpty$3(container.data) && sibling) {
  8501. container = sibling;
  8502. }
  8503. const parents = getParents$1(dom, container);
  8504. for (let i = 0; i < parents.length; i++) {
  8505. for (let y = 0; y < formatList.length; y++) {
  8506. const curFormat = formatList[y];
  8507. if (isNonNullable(curFormat.collapsed) && curFormat.collapsed !== rng.collapsed) {
  8508. continue;
  8509. }
  8510. if (isSelectorFormat(curFormat) && dom.is(parents[i], curFormat.selector)) {
  8511. return parents[i];
  8512. }
  8513. }
  8514. }
  8515. return container;
  8516. };
  8517. const findBlockEndPoint = (dom, formatList, container, siblingName) => {
  8518. var _a;
  8519. let node = container;
  8520. const root = dom.getRoot();
  8521. const format = formatList[0];
  8522. if (isBlockFormat(format)) {
  8523. node = format.wrapper ? null : dom.getParent(container, format.block, root);
  8524. }
  8525. if (!node) {
  8526. const scopeRoot = (_a = dom.getParent(container, 'LI,TD,TH')) !== null && _a !== void 0 ? _a : root;
  8527. node = dom.getParent(isText$a(container) ? container.parentNode : container, node => node !== root && isTextBlock(dom.schema, node), scopeRoot);
  8528. }
  8529. if (node && isBlockFormat(format) && format.wrapper) {
  8530. node = getParents$1(dom, node, 'ul,ol').reverse()[0] || node;
  8531. }
  8532. if (!node) {
  8533. node = container;
  8534. while (node && node[siblingName] && !dom.isBlock(node[siblingName])) {
  8535. node = node[siblingName];
  8536. if (isEq$5(node, 'br')) {
  8537. break;
  8538. }
  8539. }
  8540. }
  8541. return node || container;
  8542. };
  8543. const isAtBlockBoundary$1 = (dom, root, container, siblingName) => {
  8544. const parent = container.parentNode;
  8545. if (isNonNullable(container[siblingName])) {
  8546. return false;
  8547. } else if (parent === root || isNullable(parent) || dom.isBlock(parent)) {
  8548. return true;
  8549. } else {
  8550. return isAtBlockBoundary$1(dom, root, parent, siblingName);
  8551. }
  8552. };
  8553. const findParentContainer = (dom, formatList, container, offset, start) => {
  8554. let parent = container;
  8555. const siblingName = start ? 'previousSibling' : 'nextSibling';
  8556. const root = dom.getRoot();
  8557. if (isText$a(container) && !isWhiteSpaceNode(container)) {
  8558. if (start ? offset > 0 : offset < container.data.length) {
  8559. return container;
  8560. }
  8561. }
  8562. while (parent) {
  8563. if (!formatList[0].block_expand && dom.isBlock(parent)) {
  8564. return parent;
  8565. }
  8566. for (let sibling = parent[siblingName]; sibling; sibling = sibling[siblingName]) {
  8567. const allowSpaces = isText$a(sibling) && !isAtBlockBoundary$1(dom, root, sibling, siblingName);
  8568. if (!isBookmarkNode(sibling) && !isBogusBr(sibling) && !isWhiteSpaceNode(sibling, allowSpaces)) {
  8569. return parent;
  8570. }
  8571. }
  8572. if (parent === root || parent.parentNode === root) {
  8573. container = parent;
  8574. break;
  8575. }
  8576. parent = parent.parentNode;
  8577. }
  8578. return container;
  8579. };
  8580. const isSelfOrParentBookmark = container => isBookmarkNode(container.parentNode) || isBookmarkNode(container);
  8581. const expandRng = (dom, rng, formatList, includeTrailingSpace = false) => {
  8582. let {startContainer, startOffset, endContainer, endOffset} = rng;
  8583. const format = formatList[0];
  8584. if (isElement$6(startContainer) && startContainer.hasChildNodes()) {
  8585. startContainer = getNode$1(startContainer, startOffset);
  8586. if (isText$a(startContainer)) {
  8587. startOffset = 0;
  8588. }
  8589. }
  8590. if (isElement$6(endContainer) && endContainer.hasChildNodes()) {
  8591. endContainer = getNode$1(endContainer, rng.collapsed ? endOffset : endOffset - 1);
  8592. if (isText$a(endContainer)) {
  8593. endOffset = endContainer.data.length;
  8594. }
  8595. }
  8596. startContainer = findParentContentEditable(dom, startContainer);
  8597. endContainer = findParentContentEditable(dom, endContainer);
  8598. if (isSelfOrParentBookmark(startContainer)) {
  8599. startContainer = isBookmarkNode(startContainer) ? startContainer : startContainer.parentNode;
  8600. if (rng.collapsed) {
  8601. startContainer = startContainer.previousSibling || startContainer;
  8602. } else {
  8603. startContainer = startContainer.nextSibling || startContainer;
  8604. }
  8605. if (isText$a(startContainer)) {
  8606. startOffset = rng.collapsed ? startContainer.length : 0;
  8607. }
  8608. }
  8609. if (isSelfOrParentBookmark(endContainer)) {
  8610. endContainer = isBookmarkNode(endContainer) ? endContainer : endContainer.parentNode;
  8611. if (rng.collapsed) {
  8612. endContainer = endContainer.nextSibling || endContainer;
  8613. } else {
  8614. endContainer = endContainer.previousSibling || endContainer;
  8615. }
  8616. if (isText$a(endContainer)) {
  8617. endOffset = rng.collapsed ? 0 : endContainer.length;
  8618. }
  8619. }
  8620. if (rng.collapsed) {
  8621. const startPoint = findWordEndPoint(dom, dom.getRoot(), startContainer, startOffset, true, includeTrailingSpace);
  8622. startPoint.each(({container, offset}) => {
  8623. startContainer = container;
  8624. startOffset = offset;
  8625. });
  8626. const endPoint = findWordEndPoint(dom, dom.getRoot(), endContainer, endOffset, false, includeTrailingSpace);
  8627. endPoint.each(({container, offset}) => {
  8628. endContainer = container;
  8629. endOffset = offset;
  8630. });
  8631. }
  8632. if (isInlineFormat(format) || format.block_expand) {
  8633. if (!isInlineFormat(format) || (!isText$a(startContainer) || startOffset === 0)) {
  8634. startContainer = findParentContainer(dom, formatList, startContainer, startOffset, true);
  8635. }
  8636. if (!isInlineFormat(format) || (!isText$a(endContainer) || endOffset === endContainer.data.length)) {
  8637. endContainer = findParentContainer(dom, formatList, endContainer, endOffset, false);
  8638. }
  8639. }
  8640. if (shouldExpandToSelector(format)) {
  8641. startContainer = findSelectorEndPoint(dom, formatList, rng, startContainer, 'previousSibling');
  8642. endContainer = findSelectorEndPoint(dom, formatList, rng, endContainer, 'nextSibling');
  8643. }
  8644. if (isBlockFormat(format) || isSelectorFormat(format)) {
  8645. startContainer = findBlockEndPoint(dom, formatList, startContainer, 'previousSibling');
  8646. endContainer = findBlockEndPoint(dom, formatList, endContainer, 'nextSibling');
  8647. if (isBlockFormat(format)) {
  8648. if (!dom.isBlock(startContainer)) {
  8649. startContainer = findParentContainer(dom, formatList, startContainer, startOffset, true);
  8650. }
  8651. if (!dom.isBlock(endContainer)) {
  8652. endContainer = findParentContainer(dom, formatList, endContainer, endOffset, false);
  8653. }
  8654. }
  8655. }
  8656. if (isElement$6(startContainer) && startContainer.parentNode) {
  8657. startOffset = dom.nodeIndex(startContainer);
  8658. startContainer = startContainer.parentNode;
  8659. }
  8660. if (isElement$6(endContainer) && endContainer.parentNode) {
  8661. endOffset = dom.nodeIndex(endContainer) + 1;
  8662. endContainer = endContainer.parentNode;
  8663. }
  8664. return {
  8665. startContainer,
  8666. startOffset,
  8667. endContainer,
  8668. endOffset
  8669. };
  8670. };
  8671. const walk$3 = (dom, rng, callback) => {
  8672. var _a;
  8673. const startOffset = rng.startOffset;
  8674. const startContainer = getNode$1(rng.startContainer, startOffset);
  8675. const endOffset = rng.endOffset;
  8676. const endContainer = getNode$1(rng.endContainer, endOffset - 1);
  8677. const exclude = nodes => {
  8678. const firstNode = nodes[0];
  8679. if (isText$a(firstNode) && firstNode === startContainer && startOffset >= firstNode.data.length) {
  8680. nodes.splice(0, 1);
  8681. }
  8682. const lastNode = nodes[nodes.length - 1];
  8683. if (endOffset === 0 && nodes.length > 0 && lastNode === endContainer && isText$a(lastNode)) {
  8684. nodes.splice(nodes.length - 1, 1);
  8685. }
  8686. return nodes;
  8687. };
  8688. const collectSiblings = (node, name, endNode) => {
  8689. const siblings = [];
  8690. for (; node && node !== endNode; node = node[name]) {
  8691. siblings.push(node);
  8692. }
  8693. return siblings;
  8694. };
  8695. const findEndPoint = (node, root) => dom.getParent(node, node => node.parentNode === root, root);
  8696. const walkBoundary = (startNode, endNode, next) => {
  8697. const siblingName = next ? 'nextSibling' : 'previousSibling';
  8698. for (let node = startNode, parent = node.parentNode; node && node !== endNode; node = parent) {
  8699. parent = node.parentNode;
  8700. const siblings = collectSiblings(node === startNode ? node : node[siblingName], siblingName);
  8701. if (siblings.length) {
  8702. if (!next) {
  8703. siblings.reverse();
  8704. }
  8705. callback(exclude(siblings));
  8706. }
  8707. }
  8708. };
  8709. if (startContainer === endContainer) {
  8710. return callback(exclude([startContainer]));
  8711. }
  8712. const ancestor = (_a = dom.findCommonAncestor(startContainer, endContainer)) !== null && _a !== void 0 ? _a : dom.getRoot();
  8713. if (dom.isChildOf(startContainer, endContainer)) {
  8714. return walkBoundary(startContainer, ancestor, true);
  8715. }
  8716. if (dom.isChildOf(endContainer, startContainer)) {
  8717. return walkBoundary(endContainer, ancestor);
  8718. }
  8719. const startPoint = findEndPoint(startContainer, ancestor) || startContainer;
  8720. const endPoint = findEndPoint(endContainer, ancestor) || endContainer;
  8721. walkBoundary(startContainer, startPoint, true);
  8722. const siblings = collectSiblings(startPoint === startContainer ? startPoint : startPoint.nextSibling, 'nextSibling', endPoint === endContainer ? endPoint.nextSibling : endPoint);
  8723. if (siblings.length) {
  8724. callback(exclude(siblings));
  8725. }
  8726. walkBoundary(endContainer, endPoint);
  8727. };
  8728. const validBlocks = [
  8729. 'pre[class*=language-][contenteditable="false"]',
  8730. 'figure.image',
  8731. 'div[data-ephox-embed-iri]',
  8732. 'div.tiny-pageembed',
  8733. 'div.mce-toc',
  8734. 'div[data-mce-toc]'
  8735. ];
  8736. const isZeroWidth = elem => isText$b(elem) && get$3(elem) === ZWSP$1;
  8737. const context = (editor, elem, wrapName, nodeName) => parent(elem).fold(() => 'skipping', parent => {
  8738. if (nodeName === 'br' || isZeroWidth(elem)) {
  8739. return 'valid';
  8740. } else if (isAnnotation(elem)) {
  8741. return 'existing';
  8742. } else if (isCaretNode(elem.dom)) {
  8743. return 'caret';
  8744. } else if (exists(validBlocks, selector => is$1(elem, selector))) {
  8745. return 'valid-block';
  8746. } else if (!isValid(editor, wrapName, nodeName) || !isValid(editor, name(parent), wrapName)) {
  8747. return 'invalid-child';
  8748. } else {
  8749. return 'valid';
  8750. }
  8751. });
  8752. const applyWordGrab = (editor, rng) => {
  8753. const r = expandRng(editor.dom, rng, [{ inline: 'span' }]);
  8754. rng.setStart(r.startContainer, r.startOffset);
  8755. rng.setEnd(r.endContainer, r.endOffset);
  8756. editor.selection.setRng(rng);
  8757. };
  8758. const applyAnnotation = (elem, masterUId, data, annotationName, decorate, directAnnotation) => {
  8759. const {uid = masterUId, ...otherData} = data;
  8760. add$2(elem, annotation());
  8761. set$3(elem, `${ dataAnnotationId() }`, uid);
  8762. set$3(elem, `${ dataAnnotation() }`, annotationName);
  8763. const {attributes = {}, classes = []} = decorate(uid, otherData);
  8764. setAll$1(elem, attributes);
  8765. add(elem, classes);
  8766. if (directAnnotation) {
  8767. if (classes.length > 0) {
  8768. set$3(elem, `${ dataAnnotationClasses() }`, classes.join(','));
  8769. }
  8770. const attributeNames = keys(attributes);
  8771. if (attributeNames.length > 0) {
  8772. set$3(elem, `${ dataAnnotationAttributes() }`, attributeNames.join(','));
  8773. }
  8774. }
  8775. };
  8776. const removeDirectAnnotation = elem => {
  8777. remove$8(elem, annotation());
  8778. remove$b(elem, `${ dataAnnotationId() }`);
  8779. remove$b(elem, `${ dataAnnotation() }`);
  8780. remove$b(elem, `${ dataAnnotationActive() }`);
  8781. const customAttrNames = getOpt(elem, `${ dataAnnotationAttributes() }`).map(names => names.split(',')).getOr([]);
  8782. const customClasses = getOpt(elem, `${ dataAnnotationClasses() }`).map(names => names.split(',')).getOr([]);
  8783. each$e(customAttrNames, name => remove$b(elem, name));
  8784. remove$5(elem, customClasses);
  8785. remove$b(elem, `${ dataAnnotationClasses() }`);
  8786. remove$b(elem, `${ dataAnnotationAttributes() }`);
  8787. };
  8788. const makeAnnotation = (eDoc, uid, data, annotationName, decorate) => {
  8789. const master = SugarElement.fromTag('span', eDoc);
  8790. applyAnnotation(master, uid, data, annotationName, decorate, false);
  8791. return master;
  8792. };
  8793. const annotate = (editor, rng, uid, annotationName, decorate, data) => {
  8794. const newWrappers = [];
  8795. const master = makeAnnotation(editor.getDoc(), uid, data, annotationName, decorate);
  8796. const wrapper = value$2();
  8797. const finishWrapper = () => {
  8798. wrapper.clear();
  8799. };
  8800. const getOrOpenWrapper = () => wrapper.get().getOrThunk(() => {
  8801. const nu = shallow$1(master);
  8802. newWrappers.push(nu);
  8803. wrapper.set(nu);
  8804. return nu;
  8805. });
  8806. const processElements = elems => {
  8807. each$e(elems, processElement);
  8808. };
  8809. const processElement = elem => {
  8810. const ctx = context(editor, elem, 'span', name(elem));
  8811. switch (ctx) {
  8812. case 'invalid-child': {
  8813. finishWrapper();
  8814. const children = children$1(elem);
  8815. processElements(children);
  8816. finishWrapper();
  8817. break;
  8818. }
  8819. case 'valid-block': {
  8820. finishWrapper();
  8821. applyAnnotation(elem, uid, data, annotationName, decorate, true);
  8822. break;
  8823. }
  8824. case 'valid': {
  8825. const w = getOrOpenWrapper();
  8826. wrap$2(elem, w);
  8827. break;
  8828. }
  8829. }
  8830. };
  8831. const processNodes = nodes => {
  8832. const elems = map$3(nodes, SugarElement.fromDom);
  8833. processElements(elems);
  8834. };
  8835. walk$3(editor.dom, rng, nodes => {
  8836. finishWrapper();
  8837. processNodes(nodes);
  8838. });
  8839. return newWrappers;
  8840. };
  8841. const annotateWithBookmark = (editor, name, settings, data) => {
  8842. editor.undoManager.transact(() => {
  8843. const selection = editor.selection;
  8844. const initialRng = selection.getRng();
  8845. const hasFakeSelection = getCellsFromEditor(editor).length > 0;
  8846. const masterUid = generate$1('mce-annotation');
  8847. if (initialRng.collapsed && !hasFakeSelection) {
  8848. applyWordGrab(editor, initialRng);
  8849. }
  8850. if (selection.getRng().collapsed && !hasFakeSelection) {
  8851. const wrapper = makeAnnotation(editor.getDoc(), masterUid, data, name, settings.decorate);
  8852. set$1(wrapper, nbsp);
  8853. selection.getRng().insertNode(wrapper.dom);
  8854. selection.select(wrapper.dom);
  8855. } else {
  8856. preserve(selection, false, () => {
  8857. runOnRanges(editor, selectionRng => {
  8858. annotate(editor, selectionRng, masterUid, name, settings.decorate, data);
  8859. });
  8860. });
  8861. }
  8862. });
  8863. };
  8864. const Annotator = editor => {
  8865. const registry = create$c();
  8866. setup$w(editor, registry);
  8867. const changes = setup$x(editor, registry);
  8868. const isSpan = isTag('span');
  8869. const removeAnnotations = elements => {
  8870. each$e(elements, element => {
  8871. if (isSpan(element)) {
  8872. unwrap(element);
  8873. } else {
  8874. removeDirectAnnotation(element);
  8875. }
  8876. });
  8877. };
  8878. return {
  8879. register: (name, settings) => {
  8880. registry.register(name, settings);
  8881. },
  8882. annotate: (name, data) => {
  8883. registry.lookup(name).each(settings => {
  8884. annotateWithBookmark(editor, name, settings, data);
  8885. });
  8886. },
  8887. annotationChanged: (name, callback) => {
  8888. changes.addListener(name, callback);
  8889. },
  8890. remove: name => {
  8891. identify(editor, Optional.some(name)).each(({elements}) => {
  8892. const bookmark = editor.selection.getBookmark();
  8893. removeAnnotations(elements);
  8894. editor.selection.moveToBookmark(bookmark);
  8895. });
  8896. },
  8897. removeAll: name => {
  8898. const bookmark = editor.selection.getBookmark();
  8899. each$d(findAll(editor, name), (elements, _) => {
  8900. removeAnnotations(elements);
  8901. });
  8902. editor.selection.moveToBookmark(bookmark);
  8903. },
  8904. getAll: name => {
  8905. const directory = findAll(editor, name);
  8906. return map$2(directory, elems => map$3(elems, elem => elem.dom));
  8907. }
  8908. };
  8909. };
  8910. const BookmarkManager = selection => {
  8911. return {
  8912. getBookmark: curry(getBookmark$1, selection),
  8913. moveToBookmark: curry(moveToBookmark, selection)
  8914. };
  8915. };
  8916. BookmarkManager.isBookmarkNode = isBookmarkNode$1;
  8917. const isXYWithinRange = (clientX, clientY, range) => {
  8918. if (range.collapsed) {
  8919. return false;
  8920. } else {
  8921. return exists(range.getClientRects(), rect => containsXY(rect, clientX, clientY));
  8922. }
  8923. };
  8924. const firePreProcess = (editor, args) => editor.dispatch('PreProcess', args);
  8925. const firePostProcess = (editor, args) => editor.dispatch('PostProcess', args);
  8926. const fireRemove = editor => {
  8927. editor.dispatch('remove');
  8928. };
  8929. const fireDetach = editor => {
  8930. editor.dispatch('detach');
  8931. };
  8932. const fireSwitchMode = (editor, mode) => {
  8933. editor.dispatch('SwitchMode', { mode });
  8934. };
  8935. const fireObjectResizeStart = (editor, target, width, height, origin) => {
  8936. editor.dispatch('ObjectResizeStart', {
  8937. target,
  8938. width,
  8939. height,
  8940. origin
  8941. });
  8942. };
  8943. const fireObjectResized = (editor, target, width, height, origin) => {
  8944. editor.dispatch('ObjectResized', {
  8945. target,
  8946. width,
  8947. height,
  8948. origin
  8949. });
  8950. };
  8951. const firePreInit = editor => {
  8952. editor.dispatch('PreInit');
  8953. };
  8954. const firePostRender = editor => {
  8955. editor.dispatch('PostRender');
  8956. };
  8957. const fireInit = editor => {
  8958. editor.dispatch('Init');
  8959. };
  8960. const firePlaceholderToggle = (editor, state) => {
  8961. editor.dispatch('PlaceholderToggle', { state });
  8962. };
  8963. const fireError = (editor, errorType, error) => {
  8964. editor.dispatch(errorType, error);
  8965. };
  8966. const fireFormatApply = (editor, format, node, vars) => {
  8967. editor.dispatch('FormatApply', {
  8968. format,
  8969. node,
  8970. vars
  8971. });
  8972. };
  8973. const fireFormatRemove = (editor, format, node, vars) => {
  8974. editor.dispatch('FormatRemove', {
  8975. format,
  8976. node,
  8977. vars
  8978. });
  8979. };
  8980. const fireBeforeSetContent = (editor, args) => editor.dispatch('BeforeSetContent', args);
  8981. const fireSetContent = (editor, args) => editor.dispatch('SetContent', args);
  8982. const fireBeforeGetContent = (editor, args) => editor.dispatch('BeforeGetContent', args);
  8983. const fireGetContent = (editor, args) => editor.dispatch('GetContent', args);
  8984. const fireAutocompleterStart = (editor, args) => {
  8985. editor.dispatch('AutocompleterStart', args);
  8986. };
  8987. const fireAutocompleterUpdate = (editor, args) => {
  8988. editor.dispatch('AutocompleterUpdate', args);
  8989. };
  8990. const fireAutocompleterEnd = editor => {
  8991. editor.dispatch('AutocompleterEnd');
  8992. };
  8993. const firePastePreProcess = (editor, html, internal) => editor.dispatch('PastePreProcess', {
  8994. content: html,
  8995. internal
  8996. });
  8997. const firePastePostProcess = (editor, node, internal) => editor.dispatch('PastePostProcess', {
  8998. node,
  8999. internal
  9000. });
  9001. const firePastePlainTextToggle = (editor, state) => editor.dispatch('PastePlainTextToggle', { state });
  9002. const VK = {
  9003. BACKSPACE: 8,
  9004. DELETE: 46,
  9005. DOWN: 40,
  9006. ENTER: 13,
  9007. ESC: 27,
  9008. LEFT: 37,
  9009. RIGHT: 39,
  9010. SPACEBAR: 32,
  9011. TAB: 9,
  9012. UP: 38,
  9013. PAGE_UP: 33,
  9014. PAGE_DOWN: 34,
  9015. END: 35,
  9016. HOME: 36,
  9017. modifierPressed: e => {
  9018. return e.shiftKey || e.ctrlKey || e.altKey || VK.metaKeyPressed(e);
  9019. },
  9020. metaKeyPressed: e => {
  9021. return Env.os.isMacOS() || Env.os.isiOS() ? e.metaKey : e.ctrlKey && !e.altKey;
  9022. }
  9023. };
  9024. const elementSelectionAttr = 'data-mce-selected';
  9025. const controlElmSelector = 'table,img,figure.image,hr,video,span.mce-preview-object';
  9026. const abs = Math.abs;
  9027. const round$1 = Math.round;
  9028. const resizeHandles = {
  9029. nw: [
  9030. 0,
  9031. 0,
  9032. -1,
  9033. -1
  9034. ],
  9035. ne: [
  9036. 1,
  9037. 0,
  9038. 1,
  9039. -1
  9040. ],
  9041. se: [
  9042. 1,
  9043. 1,
  9044. 1,
  9045. 1
  9046. ],
  9047. sw: [
  9048. 0,
  9049. 1,
  9050. -1,
  9051. 1
  9052. ]
  9053. };
  9054. const isTouchEvent = evt => evt.type === 'longpress' || evt.type.indexOf('touch') === 0;
  9055. const ControlSelection = (selection, editor) => {
  9056. const dom = editor.dom;
  9057. const editableDoc = editor.getDoc();
  9058. const rootDocument = document;
  9059. const rootElement = editor.getBody();
  9060. let selectedElm, selectedElmGhost, resizeHelper, selectedHandle, resizeBackdrop;
  9061. let startX, startY, selectedElmX, selectedElmY, startW, startH, ratio, resizeStarted;
  9062. let width;
  9063. let height;
  9064. let startScrollWidth;
  9065. let startScrollHeight;
  9066. const isImage = elm => isNonNullable(elm) && (isImg(elm) || dom.is(elm, 'figure.image'));
  9067. const isMedia = elm => isMedia$2(elm) || dom.hasClass(elm, 'mce-preview-object');
  9068. const isEventOnImageOutsideRange = (evt, range) => {
  9069. if (isTouchEvent(evt)) {
  9070. const touch = evt.touches[0];
  9071. return isImage(evt.target) && !isXYWithinRange(touch.clientX, touch.clientY, range);
  9072. } else {
  9073. return isImage(evt.target) && !isXYWithinRange(evt.clientX, evt.clientY, range);
  9074. }
  9075. };
  9076. const contextMenuSelectImage = evt => {
  9077. const target = evt.target;
  9078. if (isEventOnImageOutsideRange(evt, editor.selection.getRng()) && !evt.isDefaultPrevented()) {
  9079. editor.selection.select(target);
  9080. }
  9081. };
  9082. const getResizeTargets = elm => {
  9083. if (dom.hasClass(elm, 'mce-preview-object') && isNonNullable(elm.firstElementChild)) {
  9084. return [
  9085. elm,
  9086. elm.firstElementChild
  9087. ];
  9088. } else if (dom.is(elm, 'figure.image')) {
  9089. return [elm.querySelector('img')];
  9090. } else {
  9091. return [elm];
  9092. }
  9093. };
  9094. const isResizable = elm => {
  9095. const selector = getObjectResizing(editor);
  9096. if (!selector) {
  9097. return false;
  9098. }
  9099. if (elm.getAttribute('data-mce-resize') === 'false') {
  9100. return false;
  9101. }
  9102. if (elm === editor.getBody()) {
  9103. return false;
  9104. }
  9105. if (dom.hasClass(elm, 'mce-preview-object') && isNonNullable(elm.firstElementChild)) {
  9106. return is$1(SugarElement.fromDom(elm.firstElementChild), selector);
  9107. } else {
  9108. return is$1(SugarElement.fromDom(elm), selector);
  9109. }
  9110. };
  9111. const createGhostElement = elm => {
  9112. if (isMedia(elm)) {
  9113. return dom.create('img', { src: Env.transparentSrc });
  9114. } else {
  9115. return elm.cloneNode(true);
  9116. }
  9117. };
  9118. const setSizeProp = (element, name, value) => {
  9119. if (isNonNullable(value)) {
  9120. const targets = getResizeTargets(element);
  9121. each$e(targets, target => {
  9122. if (target.style[name] || !editor.schema.isValid(target.nodeName.toLowerCase(), name)) {
  9123. dom.setStyle(target, name, value);
  9124. } else {
  9125. dom.setAttrib(target, name, '' + value);
  9126. }
  9127. });
  9128. }
  9129. };
  9130. const setGhostElmSize = (ghostElm, width, height) => {
  9131. setSizeProp(ghostElm, 'width', width);
  9132. setSizeProp(ghostElm, 'height', height);
  9133. };
  9134. const resizeGhostElement = e => {
  9135. let deltaX, deltaY, proportional;
  9136. let resizeHelperX, resizeHelperY;
  9137. deltaX = e.screenX - startX;
  9138. deltaY = e.screenY - startY;
  9139. width = deltaX * selectedHandle[2] + startW;
  9140. height = deltaY * selectedHandle[3] + startH;
  9141. width = width < 5 ? 5 : width;
  9142. height = height < 5 ? 5 : height;
  9143. if ((isImage(selectedElm) || isMedia(selectedElm)) && getResizeImgProportional(editor) !== false) {
  9144. proportional = !VK.modifierPressed(e);
  9145. } else {
  9146. proportional = VK.modifierPressed(e);
  9147. }
  9148. if (proportional) {
  9149. if (abs(deltaX) > abs(deltaY)) {
  9150. height = round$1(width * ratio);
  9151. width = round$1(height / ratio);
  9152. } else {
  9153. width = round$1(height / ratio);
  9154. height = round$1(width * ratio);
  9155. }
  9156. }
  9157. setGhostElmSize(selectedElmGhost, width, height);
  9158. resizeHelperX = selectedHandle.startPos.x + deltaX;
  9159. resizeHelperY = selectedHandle.startPos.y + deltaY;
  9160. resizeHelperX = resizeHelperX > 0 ? resizeHelperX : 0;
  9161. resizeHelperY = resizeHelperY > 0 ? resizeHelperY : 0;
  9162. dom.setStyles(resizeHelper, {
  9163. left: resizeHelperX,
  9164. top: resizeHelperY,
  9165. display: 'block'
  9166. });
  9167. resizeHelper.innerHTML = width + ' &times; ' + height;
  9168. if (selectedHandle[2] < 0 && selectedElmGhost.clientWidth <= width) {
  9169. dom.setStyle(selectedElmGhost, 'left', selectedElmX + (startW - width));
  9170. }
  9171. if (selectedHandle[3] < 0 && selectedElmGhost.clientHeight <= height) {
  9172. dom.setStyle(selectedElmGhost, 'top', selectedElmY + (startH - height));
  9173. }
  9174. deltaX = rootElement.scrollWidth - startScrollWidth;
  9175. deltaY = rootElement.scrollHeight - startScrollHeight;
  9176. if (deltaX + deltaY !== 0) {
  9177. dom.setStyles(resizeHelper, {
  9178. left: resizeHelperX - deltaX,
  9179. top: resizeHelperY - deltaY
  9180. });
  9181. }
  9182. if (!resizeStarted) {
  9183. fireObjectResizeStart(editor, selectedElm, startW, startH, 'corner-' + selectedHandle.name);
  9184. resizeStarted = true;
  9185. }
  9186. };
  9187. const endGhostResize = () => {
  9188. const wasResizeStarted = resizeStarted;
  9189. resizeStarted = false;
  9190. if (wasResizeStarted) {
  9191. setSizeProp(selectedElm, 'width', width);
  9192. setSizeProp(selectedElm, 'height', height);
  9193. }
  9194. dom.unbind(editableDoc, 'mousemove', resizeGhostElement);
  9195. dom.unbind(editableDoc, 'mouseup', endGhostResize);
  9196. if (rootDocument !== editableDoc) {
  9197. dom.unbind(rootDocument, 'mousemove', resizeGhostElement);
  9198. dom.unbind(rootDocument, 'mouseup', endGhostResize);
  9199. }
  9200. dom.remove(selectedElmGhost);
  9201. dom.remove(resizeHelper);
  9202. dom.remove(resizeBackdrop);
  9203. showResizeRect(selectedElm);
  9204. if (wasResizeStarted) {
  9205. fireObjectResized(editor, selectedElm, width, height, 'corner-' + selectedHandle.name);
  9206. dom.setAttrib(selectedElm, 'style', dom.getAttrib(selectedElm, 'style'));
  9207. }
  9208. editor.nodeChanged();
  9209. };
  9210. const showResizeRect = targetElm => {
  9211. unbindResizeHandleEvents();
  9212. const position = dom.getPos(targetElm, rootElement);
  9213. const selectedElmX = position.x;
  9214. const selectedElmY = position.y;
  9215. const rect = targetElm.getBoundingClientRect();
  9216. const targetWidth = rect.width || rect.right - rect.left;
  9217. const targetHeight = rect.height || rect.bottom - rect.top;
  9218. if (selectedElm !== targetElm) {
  9219. hideResizeRect();
  9220. selectedElm = targetElm;
  9221. width = height = 0;
  9222. }
  9223. const e = editor.dispatch('ObjectSelected', { target: targetElm });
  9224. if (isResizable(targetElm) && !e.isDefaultPrevented()) {
  9225. each$d(resizeHandles, (handle, name) => {
  9226. const startDrag = e => {
  9227. const target = getResizeTargets(selectedElm)[0];
  9228. startX = e.screenX;
  9229. startY = e.screenY;
  9230. startW = target.clientWidth;
  9231. startH = target.clientHeight;
  9232. ratio = startH / startW;
  9233. selectedHandle = handle;
  9234. selectedHandle.name = name;
  9235. selectedHandle.startPos = {
  9236. x: targetWidth * handle[0] + selectedElmX,
  9237. y: targetHeight * handle[1] + selectedElmY
  9238. };
  9239. startScrollWidth = rootElement.scrollWidth;
  9240. startScrollHeight = rootElement.scrollHeight;
  9241. resizeBackdrop = dom.add(rootElement, 'div', {
  9242. 'class': 'mce-resize-backdrop',
  9243. 'data-mce-bogus': 'all'
  9244. });
  9245. dom.setStyles(resizeBackdrop, {
  9246. position: 'fixed',
  9247. left: '0',
  9248. top: '0',
  9249. width: '100%',
  9250. height: '100%'
  9251. });
  9252. selectedElmGhost = createGhostElement(selectedElm);
  9253. dom.addClass(selectedElmGhost, 'mce-clonedresizable');
  9254. dom.setAttrib(selectedElmGhost, 'data-mce-bogus', 'all');
  9255. selectedElmGhost.contentEditable = 'false';
  9256. dom.setStyles(selectedElmGhost, {
  9257. left: selectedElmX,
  9258. top: selectedElmY,
  9259. margin: 0
  9260. });
  9261. setGhostElmSize(selectedElmGhost, targetWidth, targetHeight);
  9262. selectedElmGhost.removeAttribute(elementSelectionAttr);
  9263. rootElement.appendChild(selectedElmGhost);
  9264. dom.bind(editableDoc, 'mousemove', resizeGhostElement);
  9265. dom.bind(editableDoc, 'mouseup', endGhostResize);
  9266. if (rootDocument !== editableDoc) {
  9267. dom.bind(rootDocument, 'mousemove', resizeGhostElement);
  9268. dom.bind(rootDocument, 'mouseup', endGhostResize);
  9269. }
  9270. resizeHelper = dom.add(rootElement, 'div', {
  9271. 'class': 'mce-resize-helper',
  9272. 'data-mce-bogus': 'all'
  9273. }, startW + ' &times; ' + startH);
  9274. };
  9275. let handleElm = dom.get('mceResizeHandle' + name);
  9276. if (handleElm) {
  9277. dom.remove(handleElm);
  9278. }
  9279. handleElm = dom.add(rootElement, 'div', {
  9280. 'id': 'mceResizeHandle' + name,
  9281. 'data-mce-bogus': 'all',
  9282. 'class': 'mce-resizehandle',
  9283. 'unselectable': true,
  9284. 'style': 'cursor:' + name + '-resize; margin:0; padding:0'
  9285. });
  9286. dom.bind(handleElm, 'mousedown', e => {
  9287. e.stopImmediatePropagation();
  9288. e.preventDefault();
  9289. startDrag(e);
  9290. });
  9291. handle.elm = handleElm;
  9292. dom.setStyles(handleElm, {
  9293. left: targetWidth * handle[0] + selectedElmX - handleElm.offsetWidth / 2,
  9294. top: targetHeight * handle[1] + selectedElmY - handleElm.offsetHeight / 2
  9295. });
  9296. });
  9297. } else {
  9298. hideResizeRect(false);
  9299. }
  9300. };
  9301. const throttledShowResizeRect = first$1(showResizeRect, 0);
  9302. const hideResizeRect = (removeSelected = true) => {
  9303. throttledShowResizeRect.cancel();
  9304. unbindResizeHandleEvents();
  9305. if (selectedElm && removeSelected) {
  9306. selectedElm.removeAttribute(elementSelectionAttr);
  9307. }
  9308. each$d(resizeHandles, (value, name) => {
  9309. const handleElm = dom.get('mceResizeHandle' + name);
  9310. if (handleElm) {
  9311. dom.unbind(handleElm);
  9312. dom.remove(handleElm);
  9313. }
  9314. });
  9315. };
  9316. const isChildOrEqual = (node, parent) => dom.isChildOf(node, parent);
  9317. const updateResizeRect = e => {
  9318. if (resizeStarted || editor.removed || editor.composing) {
  9319. return;
  9320. }
  9321. const targetElm = e.type === 'mousedown' ? e.target : selection.getNode();
  9322. const controlElm = closest$3(SugarElement.fromDom(targetElm), controlElmSelector).map(e => e.dom).filter(e => dom.isEditable(e.parentElement)).getOrUndefined();
  9323. const selectedValue = isNonNullable(controlElm) ? dom.getAttrib(controlElm, elementSelectionAttr, '1') : '1';
  9324. each$e(dom.select(`img[${ elementSelectionAttr }],hr[${ elementSelectionAttr }]`), img => {
  9325. img.removeAttribute(elementSelectionAttr);
  9326. });
  9327. if (isNonNullable(controlElm) && isChildOrEqual(controlElm, rootElement)) {
  9328. disableGeckoResize();
  9329. const startElm = selection.getStart(true);
  9330. if (isChildOrEqual(startElm, controlElm) && isChildOrEqual(selection.getEnd(true), controlElm)) {
  9331. dom.setAttrib(controlElm, elementSelectionAttr, selectedValue);
  9332. throttledShowResizeRect.throttle(controlElm);
  9333. return;
  9334. }
  9335. }
  9336. hideResizeRect();
  9337. };
  9338. const unbindResizeHandleEvents = () => {
  9339. each$d(resizeHandles, handle => {
  9340. if (handle.elm) {
  9341. dom.unbind(handle.elm);
  9342. delete handle.elm;
  9343. }
  9344. });
  9345. };
  9346. const disableGeckoResize = () => {
  9347. try {
  9348. editor.getDoc().execCommand('enableObjectResizing', false, 'false');
  9349. } catch (ex) {
  9350. }
  9351. };
  9352. editor.on('init', () => {
  9353. disableGeckoResize();
  9354. editor.on('NodeChange ResizeEditor ResizeWindow ResizeContent drop', updateResizeRect);
  9355. editor.on('keyup compositionend', e => {
  9356. if (selectedElm && selectedElm.nodeName === 'TABLE') {
  9357. updateResizeRect(e);
  9358. }
  9359. });
  9360. editor.on('hide blur', hideResizeRect);
  9361. editor.on('contextmenu longpress', contextMenuSelectImage, true);
  9362. });
  9363. editor.on('remove', unbindResizeHandleEvents);
  9364. const destroy = () => {
  9365. throttledShowResizeRect.cancel();
  9366. selectedElm = selectedElmGhost = resizeBackdrop = null;
  9367. };
  9368. return {
  9369. isResizable,
  9370. showResizeRect,
  9371. hideResizeRect,
  9372. updateResizeRect,
  9373. destroy
  9374. };
  9375. };
  9376. const setStart = (rng, situ) => {
  9377. situ.fold(e => {
  9378. rng.setStartBefore(e.dom);
  9379. }, (e, o) => {
  9380. rng.setStart(e.dom, o);
  9381. }, e => {
  9382. rng.setStartAfter(e.dom);
  9383. });
  9384. };
  9385. const setFinish = (rng, situ) => {
  9386. situ.fold(e => {
  9387. rng.setEndBefore(e.dom);
  9388. }, (e, o) => {
  9389. rng.setEnd(e.dom, o);
  9390. }, e => {
  9391. rng.setEndAfter(e.dom);
  9392. });
  9393. };
  9394. const relativeToNative = (win, startSitu, finishSitu) => {
  9395. const range = win.document.createRange();
  9396. setStart(range, startSitu);
  9397. setFinish(range, finishSitu);
  9398. return range;
  9399. };
  9400. const exactToNative = (win, start, soffset, finish, foffset) => {
  9401. const rng = win.document.createRange();
  9402. rng.setStart(start.dom, soffset);
  9403. rng.setEnd(finish.dom, foffset);
  9404. return rng;
  9405. };
  9406. const adt$3 = Adt.generate([
  9407. {
  9408. ltr: [
  9409. 'start',
  9410. 'soffset',
  9411. 'finish',
  9412. 'foffset'
  9413. ]
  9414. },
  9415. {
  9416. rtl: [
  9417. 'start',
  9418. 'soffset',
  9419. 'finish',
  9420. 'foffset'
  9421. ]
  9422. }
  9423. ]);
  9424. const fromRange = (win, type, range) => type(SugarElement.fromDom(range.startContainer), range.startOffset, SugarElement.fromDom(range.endContainer), range.endOffset);
  9425. const getRanges = (win, selection) => selection.match({
  9426. domRange: rng => {
  9427. return {
  9428. ltr: constant(rng),
  9429. rtl: Optional.none
  9430. };
  9431. },
  9432. relative: (startSitu, finishSitu) => {
  9433. return {
  9434. ltr: cached(() => relativeToNative(win, startSitu, finishSitu)),
  9435. rtl: cached(() => Optional.some(relativeToNative(win, finishSitu, startSitu)))
  9436. };
  9437. },
  9438. exact: (start, soffset, finish, foffset) => {
  9439. return {
  9440. ltr: cached(() => exactToNative(win, start, soffset, finish, foffset)),
  9441. rtl: cached(() => Optional.some(exactToNative(win, finish, foffset, start, soffset)))
  9442. };
  9443. }
  9444. });
  9445. const doDiagnose = (win, ranges) => {
  9446. const rng = ranges.ltr();
  9447. if (rng.collapsed) {
  9448. const reversed = ranges.rtl().filter(rev => rev.collapsed === false);
  9449. 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));
  9450. } else {
  9451. return fromRange(win, adt$3.ltr, rng);
  9452. }
  9453. };
  9454. const diagnose = (win, selection) => {
  9455. const ranges = getRanges(win, selection);
  9456. return doDiagnose(win, ranges);
  9457. };
  9458. adt$3.ltr;
  9459. adt$3.rtl;
  9460. const create$a = (start, soffset, finish, foffset) => ({
  9461. start,
  9462. soffset,
  9463. finish,
  9464. foffset
  9465. });
  9466. const SimRange = { create: create$a };
  9467. const caretPositionFromPoint = (doc, x, y) => {
  9468. var _a, _b;
  9469. return Optional.from((_b = (_a = doc.dom).caretPositionFromPoint) === null || _b === void 0 ? void 0 : _b.call(_a, x, y)).bind(pos => {
  9470. if (pos.offsetNode === null) {
  9471. return Optional.none();
  9472. }
  9473. const r = doc.dom.createRange();
  9474. r.setStart(pos.offsetNode, pos.offset);
  9475. r.collapse();
  9476. return Optional.some(r);
  9477. });
  9478. };
  9479. const caretRangeFromPoint = (doc, x, y) => {
  9480. var _a, _b;
  9481. return Optional.from((_b = (_a = doc.dom).caretRangeFromPoint) === null || _b === void 0 ? void 0 : _b.call(_a, x, y));
  9482. };
  9483. const availableSearch = (() => {
  9484. if (document.caretPositionFromPoint) {
  9485. return caretPositionFromPoint;
  9486. } else if (document.caretRangeFromPoint) {
  9487. return caretRangeFromPoint;
  9488. } else {
  9489. return Optional.none;
  9490. }
  9491. })();
  9492. const fromPoint$1 = (win, x, y) => {
  9493. const doc = SugarElement.fromDom(win.document);
  9494. return availableSearch(doc, x, y).map(rng => SimRange.create(SugarElement.fromDom(rng.startContainer), rng.startOffset, SugarElement.fromDom(rng.endContainer), rng.endOffset));
  9495. };
  9496. const adt$2 = Adt.generate([
  9497. { before: ['element'] },
  9498. {
  9499. on: [
  9500. 'element',
  9501. 'offset'
  9502. ]
  9503. },
  9504. { after: ['element'] }
  9505. ]);
  9506. const cata = (subject, onBefore, onOn, onAfter) => subject.fold(onBefore, onOn, onAfter);
  9507. const getStart$2 = situ => situ.fold(identity, identity, identity);
  9508. const before$1 = adt$2.before;
  9509. const on = adt$2.on;
  9510. const after$1 = adt$2.after;
  9511. const Situ = {
  9512. before: before$1,
  9513. on,
  9514. after: after$1,
  9515. cata,
  9516. getStart: getStart$2
  9517. };
  9518. const adt$1 = Adt.generate([
  9519. { domRange: ['rng'] },
  9520. {
  9521. relative: [
  9522. 'startSitu',
  9523. 'finishSitu'
  9524. ]
  9525. },
  9526. {
  9527. exact: [
  9528. 'start',
  9529. 'soffset',
  9530. 'finish',
  9531. 'foffset'
  9532. ]
  9533. }
  9534. ]);
  9535. const exactFromRange = simRange => adt$1.exact(simRange.start, simRange.soffset, simRange.finish, simRange.foffset);
  9536. const getStart$1 = selection => selection.match({
  9537. domRange: rng => SugarElement.fromDom(rng.startContainer),
  9538. relative: (startSitu, _finishSitu) => Situ.getStart(startSitu),
  9539. exact: (start, _soffset, _finish, _foffset) => start
  9540. });
  9541. const domRange = adt$1.domRange;
  9542. const relative = adt$1.relative;
  9543. const exact = adt$1.exact;
  9544. const getWin = selection => {
  9545. const start = getStart$1(selection);
  9546. return defaultView(start);
  9547. };
  9548. const range = SimRange.create;
  9549. const SimSelection = {
  9550. domRange,
  9551. relative,
  9552. exact,
  9553. exactFromRange,
  9554. getWin,
  9555. range
  9556. };
  9557. const beforeSpecial = (element, offset) => {
  9558. const name$1 = name(element);
  9559. if ('input' === name$1) {
  9560. return Situ.after(element);
  9561. } else if (!contains$2([
  9562. 'br',
  9563. 'img'
  9564. ], name$1)) {
  9565. return Situ.on(element, offset);
  9566. } else {
  9567. return offset === 0 ? Situ.before(element) : Situ.after(element);
  9568. }
  9569. };
  9570. const preprocessRelative = (startSitu, finishSitu) => {
  9571. const start = startSitu.fold(Situ.before, beforeSpecial, Situ.after);
  9572. const finish = finishSitu.fold(Situ.before, beforeSpecial, Situ.after);
  9573. return SimSelection.relative(start, finish);
  9574. };
  9575. const preprocessExact = (start, soffset, finish, foffset) => {
  9576. const startSitu = beforeSpecial(start, soffset);
  9577. const finishSitu = beforeSpecial(finish, foffset);
  9578. return SimSelection.relative(startSitu, finishSitu);
  9579. };
  9580. const preprocess = selection => selection.match({
  9581. domRange: rng => {
  9582. const start = SugarElement.fromDom(rng.startContainer);
  9583. const finish = SugarElement.fromDom(rng.endContainer);
  9584. return preprocessExact(start, rng.startOffset, finish, rng.endOffset);
  9585. },
  9586. relative: preprocessRelative,
  9587. exact: preprocessExact
  9588. });
  9589. const fromElements = (elements, scope) => {
  9590. const doc = scope || document;
  9591. const fragment = doc.createDocumentFragment();
  9592. each$e(elements, element => {
  9593. fragment.appendChild(element.dom);
  9594. });
  9595. return SugarElement.fromDom(fragment);
  9596. };
  9597. const toNative = selection => {
  9598. const win = SimSelection.getWin(selection).dom;
  9599. const getDomRange = (start, soffset, finish, foffset) => exactToNative(win, start, soffset, finish, foffset);
  9600. const filtered = preprocess(selection);
  9601. return diagnose(win, filtered).match({
  9602. ltr: getDomRange,
  9603. rtl: getDomRange
  9604. });
  9605. };
  9606. const getAtPoint = (win, x, y) => fromPoint$1(win, x, y);
  9607. const fromPoint = (clientX, clientY, doc) => {
  9608. const win = defaultView(SugarElement.fromDom(doc));
  9609. return getAtPoint(win.dom, clientX, clientY).map(simRange => {
  9610. const rng = doc.createRange();
  9611. rng.setStart(simRange.start.dom, simRange.soffset);
  9612. rng.setEnd(simRange.finish.dom, simRange.foffset);
  9613. return rng;
  9614. }).getOrUndefined();
  9615. };
  9616. const isEq$4 = (rng1, rng2) => {
  9617. return isNonNullable(rng1) && isNonNullable(rng2) && (rng1.startContainer === rng2.startContainer && rng1.startOffset === rng2.startOffset) && (rng1.endContainer === rng2.endContainer && rng1.endOffset === rng2.endOffset);
  9618. };
  9619. const findParent = (node, rootNode, predicate) => {
  9620. let currentNode = node;
  9621. while (currentNode && currentNode !== rootNode) {
  9622. if (predicate(currentNode)) {
  9623. return currentNode;
  9624. }
  9625. currentNode = currentNode.parentNode;
  9626. }
  9627. return null;
  9628. };
  9629. const hasParent$1 = (node, rootNode, predicate) => findParent(node, rootNode, predicate) !== null;
  9630. const hasParentWithName = (node, rootNode, name) => hasParent$1(node, rootNode, node => node.nodeName === name);
  9631. const isCeFalseCaretContainer = (node, rootNode) => isCaretContainer$2(node) && !hasParent$1(node, rootNode, isCaretNode);
  9632. const hasBrBeforeAfter = (dom, node, left) => {
  9633. const parentNode = node.parentNode;
  9634. if (parentNode) {
  9635. const walker = new DomTreeWalker(node, dom.getParent(parentNode, dom.isBlock) || dom.getRoot());
  9636. let currentNode;
  9637. while (currentNode = walker[left ? 'prev' : 'next']()) {
  9638. if (isBr$6(currentNode)) {
  9639. return true;
  9640. }
  9641. }
  9642. }
  9643. return false;
  9644. };
  9645. const isPrevNode = (node, name) => {
  9646. var _a;
  9647. return ((_a = node.previousSibling) === null || _a === void 0 ? void 0 : _a.nodeName) === name;
  9648. };
  9649. const hasContentEditableFalseParent = (root, node) => {
  9650. let currentNode = node;
  9651. while (currentNode && currentNode !== root) {
  9652. if (isContentEditableFalse$b(currentNode)) {
  9653. return true;
  9654. }
  9655. currentNode = currentNode.parentNode;
  9656. }
  9657. return false;
  9658. };
  9659. const findTextNodeRelative = (dom, isAfterNode, collapsed, left, startNode) => {
  9660. const body = dom.getRoot();
  9661. const nonEmptyElementsMap = dom.schema.getNonEmptyElements();
  9662. const parentNode = startNode.parentNode;
  9663. let lastInlineElement;
  9664. let node;
  9665. if (!parentNode) {
  9666. return Optional.none();
  9667. }
  9668. const parentBlockContainer = dom.getParent(parentNode, dom.isBlock) || body;
  9669. if (left && isBr$6(startNode) && isAfterNode && dom.isEmpty(parentBlockContainer)) {
  9670. return Optional.some(CaretPosition(parentNode, dom.nodeIndex(startNode)));
  9671. }
  9672. const walker = new DomTreeWalker(startNode, parentBlockContainer);
  9673. while (node = walker[left ? 'prev' : 'next']()) {
  9674. if (dom.getContentEditableParent(node) === 'false' || isCeFalseCaretContainer(node, body)) {
  9675. return Optional.none();
  9676. }
  9677. if (isText$a(node) && node.data.length > 0) {
  9678. if (!hasParentWithName(node, body, 'A')) {
  9679. return Optional.some(CaretPosition(node, left ? node.data.length : 0));
  9680. }
  9681. return Optional.none();
  9682. }
  9683. if (dom.isBlock(node) || nonEmptyElementsMap[node.nodeName.toLowerCase()]) {
  9684. return Optional.none();
  9685. }
  9686. lastInlineElement = node;
  9687. }
  9688. if (isComment(lastInlineElement)) {
  9689. return Optional.none();
  9690. }
  9691. if (collapsed && lastInlineElement) {
  9692. return Optional.some(CaretPosition(lastInlineElement, 0));
  9693. }
  9694. return Optional.none();
  9695. };
  9696. const normalizeEndPoint = (dom, collapsed, start, rng) => {
  9697. const body = dom.getRoot();
  9698. let node;
  9699. let normalized = false;
  9700. let container = start ? rng.startContainer : rng.endContainer;
  9701. let offset = start ? rng.startOffset : rng.endOffset;
  9702. const isAfterNode = isElement$6(container) && offset === container.childNodes.length;
  9703. const nonEmptyElementsMap = dom.schema.getNonEmptyElements();
  9704. let directionLeft = start;
  9705. if (isCaretContainer$2(container)) {
  9706. return Optional.none();
  9707. }
  9708. if (isElement$6(container) && offset > container.childNodes.length - 1) {
  9709. directionLeft = false;
  9710. }
  9711. if (isDocument$1(container)) {
  9712. container = body;
  9713. offset = 0;
  9714. }
  9715. if (container === body) {
  9716. if (directionLeft) {
  9717. node = container.childNodes[offset > 0 ? offset - 1 : 0];
  9718. if (node) {
  9719. if (isCaretContainer$2(node)) {
  9720. return Optional.none();
  9721. }
  9722. if (nonEmptyElementsMap[node.nodeName] || isTable$2(node)) {
  9723. return Optional.none();
  9724. }
  9725. }
  9726. }
  9727. if (container.hasChildNodes()) {
  9728. offset = Math.min(!directionLeft && offset > 0 ? offset - 1 : offset, container.childNodes.length - 1);
  9729. container = container.childNodes[offset];
  9730. offset = isText$a(container) && isAfterNode ? container.data.length : 0;
  9731. if (!collapsed && container === body.lastChild && isTable$2(container)) {
  9732. return Optional.none();
  9733. }
  9734. if (hasContentEditableFalseParent(body, container) || isCaretContainer$2(container)) {
  9735. return Optional.none();
  9736. }
  9737. if (container.hasChildNodes() && !isTable$2(container)) {
  9738. node = container;
  9739. const walker = new DomTreeWalker(container, body);
  9740. do {
  9741. if (isContentEditableFalse$b(node) || isCaretContainer$2(node)) {
  9742. normalized = false;
  9743. break;
  9744. }
  9745. if (isText$a(node) && node.data.length > 0) {
  9746. offset = directionLeft ? 0 : node.data.length;
  9747. container = node;
  9748. normalized = true;
  9749. break;
  9750. }
  9751. if (nonEmptyElementsMap[node.nodeName.toLowerCase()] && !isTableCellOrCaption(node)) {
  9752. offset = dom.nodeIndex(node);
  9753. container = node.parentNode;
  9754. if (!directionLeft) {
  9755. offset++;
  9756. }
  9757. normalized = true;
  9758. break;
  9759. }
  9760. } while (node = directionLeft ? walker.next() : walker.prev());
  9761. }
  9762. }
  9763. }
  9764. if (collapsed) {
  9765. if (isText$a(container) && offset === 0) {
  9766. findTextNodeRelative(dom, isAfterNode, collapsed, true, container).each(pos => {
  9767. container = pos.container();
  9768. offset = pos.offset();
  9769. normalized = true;
  9770. });
  9771. }
  9772. if (isElement$6(container)) {
  9773. node = container.childNodes[offset];
  9774. if (!node) {
  9775. node = container.childNodes[offset - 1];
  9776. }
  9777. if (node && isBr$6(node) && !isPrevNode(node, 'A') && !hasBrBeforeAfter(dom, node, false) && !hasBrBeforeAfter(dom, node, true)) {
  9778. findTextNodeRelative(dom, isAfterNode, collapsed, true, node).each(pos => {
  9779. container = pos.container();
  9780. offset = pos.offset();
  9781. normalized = true;
  9782. });
  9783. }
  9784. }
  9785. }
  9786. if (directionLeft && !collapsed && isText$a(container) && offset === container.data.length) {
  9787. findTextNodeRelative(dom, isAfterNode, collapsed, false, container).each(pos => {
  9788. container = pos.container();
  9789. offset = pos.offset();
  9790. normalized = true;
  9791. });
  9792. }
  9793. return normalized && container ? Optional.some(CaretPosition(container, offset)) : Optional.none();
  9794. };
  9795. const normalize$2 = (dom, rng) => {
  9796. const collapsed = rng.collapsed, normRng = rng.cloneRange();
  9797. const startPos = CaretPosition.fromRangeStart(rng);
  9798. normalizeEndPoint(dom, collapsed, true, normRng).each(pos => {
  9799. if (!collapsed || !CaretPosition.isAbove(startPos, pos)) {
  9800. normRng.setStart(pos.container(), pos.offset());
  9801. }
  9802. });
  9803. if (!collapsed) {
  9804. normalizeEndPoint(dom, collapsed, false, normRng).each(pos => {
  9805. normRng.setEnd(pos.container(), pos.offset());
  9806. });
  9807. }
  9808. if (collapsed) {
  9809. normRng.collapse(true);
  9810. }
  9811. return isEq$4(rng, normRng) ? Optional.none() : Optional.some(normRng);
  9812. };
  9813. const splitText = (node, offset) => {
  9814. return node.splitText(offset);
  9815. };
  9816. const split = rng => {
  9817. let startContainer = rng.startContainer, startOffset = rng.startOffset, endContainer = rng.endContainer, endOffset = rng.endOffset;
  9818. if (startContainer === endContainer && isText$a(startContainer)) {
  9819. if (startOffset > 0 && startOffset < startContainer.data.length) {
  9820. endContainer = splitText(startContainer, startOffset);
  9821. startContainer = endContainer.previousSibling;
  9822. if (endOffset > startOffset) {
  9823. endOffset = endOffset - startOffset;
  9824. const newContainer = splitText(endContainer, endOffset).previousSibling;
  9825. startContainer = endContainer = newContainer;
  9826. endOffset = newContainer.data.length;
  9827. startOffset = 0;
  9828. } else {
  9829. endOffset = 0;
  9830. }
  9831. }
  9832. } else {
  9833. if (isText$a(startContainer) && startOffset > 0 && startOffset < startContainer.data.length) {
  9834. startContainer = splitText(startContainer, startOffset);
  9835. startOffset = 0;
  9836. }
  9837. if (isText$a(endContainer) && endOffset > 0 && endOffset < endContainer.data.length) {
  9838. const newContainer = splitText(endContainer, endOffset).previousSibling;
  9839. endContainer = newContainer;
  9840. endOffset = newContainer.data.length;
  9841. }
  9842. }
  9843. return {
  9844. startContainer,
  9845. startOffset,
  9846. endContainer,
  9847. endOffset
  9848. };
  9849. };
  9850. const RangeUtils = dom => {
  9851. const walk = (rng, callback) => {
  9852. return walk$3(dom, rng, callback);
  9853. };
  9854. const split$1 = split;
  9855. const normalize = rng => {
  9856. return normalize$2(dom, rng).fold(never, normalizedRng => {
  9857. rng.setStart(normalizedRng.startContainer, normalizedRng.startOffset);
  9858. rng.setEnd(normalizedRng.endContainer, normalizedRng.endOffset);
  9859. return true;
  9860. });
  9861. };
  9862. const expand = (rng, options = { type: 'word' }) => {
  9863. if (options.type === 'word') {
  9864. const rangeLike = expandRng(dom, rng, [{ inline: 'span' }]);
  9865. const newRange = dom.createRng();
  9866. newRange.setStart(rangeLike.startContainer, rangeLike.startOffset);
  9867. newRange.setEnd(rangeLike.endContainer, rangeLike.endOffset);
  9868. return newRange;
  9869. }
  9870. return rng;
  9871. };
  9872. return {
  9873. walk,
  9874. split: split$1,
  9875. expand,
  9876. normalize
  9877. };
  9878. };
  9879. RangeUtils.compareRanges = isEq$4;
  9880. RangeUtils.getCaretRangeFromPoint = fromPoint;
  9881. RangeUtils.getSelectedNode = getSelectedNode;
  9882. RangeUtils.getNode = getNode$1;
  9883. const Dimension = (name, getOffset) => {
  9884. const set = (element, h) => {
  9885. if (!isNumber(h) && !h.match(/^[0-9]+$/)) {
  9886. throw new Error(name + '.set accepts only positive integer values. Value was ' + h);
  9887. }
  9888. const dom = element.dom;
  9889. if (isSupported(dom)) {
  9890. dom.style[name] = h + 'px';
  9891. }
  9892. };
  9893. const get = element => {
  9894. const r = getOffset(element);
  9895. if (r <= 0 || r === null) {
  9896. const css = get$7(element, name);
  9897. return parseFloat(css) || 0;
  9898. }
  9899. return r;
  9900. };
  9901. const getOuter = get;
  9902. const aggregate = (element, properties) => foldl(properties, (acc, property) => {
  9903. const val = get$7(element, property);
  9904. const value = val === undefined ? 0 : parseInt(val, 10);
  9905. return isNaN(value) ? acc : acc + value;
  9906. }, 0);
  9907. const max = (element, value, properties) => {
  9908. const cumulativeInclusions = aggregate(element, properties);
  9909. const absoluteMax = value > cumulativeInclusions ? value - cumulativeInclusions : 0;
  9910. return absoluteMax;
  9911. };
  9912. return {
  9913. set,
  9914. get,
  9915. getOuter,
  9916. aggregate,
  9917. max
  9918. };
  9919. };
  9920. const api = Dimension('height', element => {
  9921. const dom = element.dom;
  9922. return inBody(element) ? dom.getBoundingClientRect().height : dom.offsetHeight;
  9923. });
  9924. const get$2 = element => api.get(element);
  9925. const getDocument = () => SugarElement.fromDom(document);
  9926. const walkUp = (navigation, doc) => {
  9927. const frame = navigation.view(doc);
  9928. return frame.fold(constant([]), f => {
  9929. const parent = navigation.owner(f);
  9930. const rest = walkUp(navigation, parent);
  9931. return [f].concat(rest);
  9932. });
  9933. };
  9934. const pathTo = (element, navigation) => {
  9935. const d = navigation.owner(element);
  9936. return walkUp(navigation, d);
  9937. };
  9938. const view = doc => {
  9939. var _a;
  9940. const element = doc.dom === document ? Optional.none() : Optional.from((_a = doc.dom.defaultView) === null || _a === void 0 ? void 0 : _a.frameElement);
  9941. return element.map(SugarElement.fromDom);
  9942. };
  9943. const owner = element => documentOrOwner(element);
  9944. var Navigation = /*#__PURE__*/Object.freeze({
  9945. __proto__: null,
  9946. view: view,
  9947. owner: owner
  9948. });
  9949. const find = element => {
  9950. const doc = getDocument();
  9951. const scroll = get$5(doc);
  9952. const frames = pathTo(element, Navigation);
  9953. const offset = viewport(element);
  9954. const r = foldr(frames, (b, a) => {
  9955. const loc = viewport(a);
  9956. return {
  9957. left: b.left + loc.left,
  9958. top: b.top + loc.top
  9959. };
  9960. }, {
  9961. left: 0,
  9962. top: 0
  9963. });
  9964. return SugarPosition(r.left + offset.left + scroll.left, r.top + offset.top + scroll.top);
  9965. };
  9966. const excludeFromDescend = element => name(element) === 'textarea';
  9967. const fireScrollIntoViewEvent = (editor, data) => {
  9968. const scrollEvent = editor.dispatch('ScrollIntoView', data);
  9969. return scrollEvent.isDefaultPrevented();
  9970. };
  9971. const fireAfterScrollIntoViewEvent = (editor, data) => {
  9972. editor.dispatch('AfterScrollIntoView', data);
  9973. };
  9974. const descend = (element, offset) => {
  9975. const children = children$1(element);
  9976. if (children.length === 0 || excludeFromDescend(element)) {
  9977. return {
  9978. element,
  9979. offset
  9980. };
  9981. } else if (offset < children.length && !excludeFromDescend(children[offset])) {
  9982. return {
  9983. element: children[offset],
  9984. offset: 0
  9985. };
  9986. } else {
  9987. const last = children[children.length - 1];
  9988. if (excludeFromDescend(last)) {
  9989. return {
  9990. element,
  9991. offset
  9992. };
  9993. } else {
  9994. if (name(last) === 'img') {
  9995. return {
  9996. element: last,
  9997. offset: 1
  9998. };
  9999. } else if (isText$b(last)) {
  10000. return {
  10001. element: last,
  10002. offset: get$3(last).length
  10003. };
  10004. } else {
  10005. return {
  10006. element: last,
  10007. offset: children$1(last).length
  10008. };
  10009. }
  10010. }
  10011. }
  10012. };
  10013. const markerInfo = (element, cleanupFun) => {
  10014. const pos = absolute(element);
  10015. const height = get$2(element);
  10016. return {
  10017. element,
  10018. bottom: pos.top + height,
  10019. height,
  10020. pos,
  10021. cleanup: cleanupFun
  10022. };
  10023. };
  10024. const createMarker$1 = (element, offset) => {
  10025. const startPoint = descend(element, offset);
  10026. const span = SugarElement.fromHtml('<span data-mce-bogus="all" style="display: inline-block;">' + ZWSP$1 + '</span>');
  10027. before$3(startPoint.element, span);
  10028. return markerInfo(span, () => remove$6(span));
  10029. };
  10030. const elementMarker = element => markerInfo(SugarElement.fromDom(element), noop);
  10031. const withMarker = (editor, f, rng, alignToTop) => {
  10032. preserveWith(editor, (_s, _e) => applyWithMarker(editor, f, rng, alignToTop), rng);
  10033. };
  10034. const withScrollEvents = (editor, doc, f, marker, alignToTop) => {
  10035. const data = {
  10036. elm: marker.element.dom,
  10037. alignToTop
  10038. };
  10039. if (fireScrollIntoViewEvent(editor, data)) {
  10040. return;
  10041. }
  10042. const scrollTop = get$5(doc).top;
  10043. f(doc, scrollTop, marker, alignToTop);
  10044. fireAfterScrollIntoViewEvent(editor, data);
  10045. };
  10046. const applyWithMarker = (editor, f, rng, alignToTop) => {
  10047. const body = SugarElement.fromDom(editor.getBody());
  10048. const doc = SugarElement.fromDom(editor.getDoc());
  10049. reflow(body);
  10050. const marker = createMarker$1(SugarElement.fromDom(rng.startContainer), rng.startOffset);
  10051. withScrollEvents(editor, doc, f, marker, alignToTop);
  10052. marker.cleanup();
  10053. };
  10054. const withElement = (editor, element, f, alignToTop) => {
  10055. const doc = SugarElement.fromDom(editor.getDoc());
  10056. withScrollEvents(editor, doc, f, elementMarker(element), alignToTop);
  10057. };
  10058. const preserveWith = (editor, f, rng) => {
  10059. const startElement = rng.startContainer;
  10060. const startOffset = rng.startOffset;
  10061. const endElement = rng.endContainer;
  10062. const endOffset = rng.endOffset;
  10063. f(SugarElement.fromDom(startElement), SugarElement.fromDom(endElement));
  10064. const newRng = editor.dom.createRng();
  10065. newRng.setStart(startElement, startOffset);
  10066. newRng.setEnd(endElement, endOffset);
  10067. editor.selection.setRng(rng);
  10068. };
  10069. const scrollToMarker = (marker, alignToTop) => marker.element.dom.scrollIntoView({ block: alignToTop ? 'start' : 'end' });
  10070. const intoWindowIfNeeded = (scrollTop, viewHeight, marker, alignToTop) => {
  10071. const viewportBottom = viewHeight + scrollTop;
  10072. const markerTop = marker.pos.top;
  10073. const markerBottom = marker.bottom;
  10074. const largerThanViewport = markerBottom - markerTop >= viewHeight;
  10075. if (markerTop < scrollTop) {
  10076. scrollToMarker(marker, alignToTop !== false);
  10077. } else if (markerTop > viewportBottom) {
  10078. const align = largerThanViewport ? alignToTop !== false : alignToTop === true;
  10079. scrollToMarker(marker, align);
  10080. } else if (markerBottom > viewportBottom && !largerThanViewport) {
  10081. scrollToMarker(marker, alignToTop === true);
  10082. }
  10083. };
  10084. const intoWindow = (doc, scrollTop, marker, alignToTop) => {
  10085. const viewHeight = defaultView(doc).dom.innerHeight;
  10086. intoWindowIfNeeded(scrollTop, viewHeight, marker, alignToTop);
  10087. };
  10088. const intoFrame = (doc, scrollTop, marker, alignToTop) => {
  10089. const frameViewHeight = defaultView(doc).dom.innerHeight;
  10090. intoWindowIfNeeded(scrollTop, frameViewHeight, marker, alignToTop);
  10091. const op = find(marker.element);
  10092. const viewportBounds = getBounds(window);
  10093. if (op.top < viewportBounds.y) {
  10094. intoView(marker.element, alignToTop !== false);
  10095. } else if (op.top > viewportBounds.bottom) {
  10096. intoView(marker.element, alignToTop === true);
  10097. }
  10098. };
  10099. const rangeIntoWindow = (editor, rng, alignToTop) => withMarker(editor, intoWindow, rng, alignToTop);
  10100. const elementIntoWindow = (editor, element, alignToTop) => withElement(editor, element, intoWindow, alignToTop);
  10101. const rangeIntoFrame = (editor, rng, alignToTop) => withMarker(editor, intoFrame, rng, alignToTop);
  10102. const elementIntoFrame = (editor, element, alignToTop) => withElement(editor, element, intoFrame, alignToTop);
  10103. const scrollElementIntoView = (editor, element, alignToTop) => {
  10104. const scroller = editor.inline ? elementIntoWindow : elementIntoFrame;
  10105. scroller(editor, element, alignToTop);
  10106. };
  10107. const scrollRangeIntoView = (editor, rng, alignToTop) => {
  10108. const scroller = editor.inline ? rangeIntoWindow : rangeIntoFrame;
  10109. scroller(editor, rng, alignToTop);
  10110. };
  10111. const focus$1 = element => element.dom.focus();
  10112. const hasFocus$1 = element => {
  10113. const root = getRootNode(element).dom;
  10114. return element.dom === root.activeElement;
  10115. };
  10116. const active$1 = (root = getDocument()) => Optional.from(root.dom.activeElement).map(SugarElement.fromDom);
  10117. const search = element => active$1(getRootNode(element)).filter(e => element.dom.contains(e.dom));
  10118. const clamp$1 = (offset, element) => {
  10119. const max = isText$b(element) ? get$3(element).length : children$1(element).length + 1;
  10120. if (offset > max) {
  10121. return max;
  10122. } else if (offset < 0) {
  10123. return 0;
  10124. }
  10125. return offset;
  10126. };
  10127. const normalizeRng = rng => SimSelection.range(rng.start, clamp$1(rng.soffset, rng.start), rng.finish, clamp$1(rng.foffset, rng.finish));
  10128. const isOrContains = (root, elm) => !isRestrictedNode(elm.dom) && (contains(root, elm) || eq(root, elm));
  10129. const isRngInRoot = root => rng => isOrContains(root, rng.start) && isOrContains(root, rng.finish);
  10130. const shouldStore = editor => editor.inline || Env.browser.isFirefox();
  10131. const nativeRangeToSelectionRange = r => SimSelection.range(SugarElement.fromDom(r.startContainer), r.startOffset, SugarElement.fromDom(r.endContainer), r.endOffset);
  10132. const readRange = win => {
  10133. const selection = win.getSelection();
  10134. const rng = !selection || selection.rangeCount === 0 ? Optional.none() : Optional.from(selection.getRangeAt(0));
  10135. return rng.map(nativeRangeToSelectionRange);
  10136. };
  10137. const getBookmark = root => {
  10138. const win = defaultView(root);
  10139. return readRange(win.dom).filter(isRngInRoot(root));
  10140. };
  10141. const validate = (root, bookmark) => Optional.from(bookmark).filter(isRngInRoot(root)).map(normalizeRng);
  10142. const bookmarkToNativeRng = bookmark => {
  10143. const rng = document.createRange();
  10144. try {
  10145. rng.setStart(bookmark.start.dom, bookmark.soffset);
  10146. rng.setEnd(bookmark.finish.dom, bookmark.foffset);
  10147. return Optional.some(rng);
  10148. } catch (_) {
  10149. return Optional.none();
  10150. }
  10151. };
  10152. const store = editor => {
  10153. const newBookmark = shouldStore(editor) ? getBookmark(SugarElement.fromDom(editor.getBody())) : Optional.none();
  10154. editor.bookmark = newBookmark.isSome() ? newBookmark : editor.bookmark;
  10155. };
  10156. const getRng = editor => {
  10157. const bookmark = editor.bookmark ? editor.bookmark : Optional.none();
  10158. return bookmark.bind(x => validate(SugarElement.fromDom(editor.getBody()), x)).bind(bookmarkToNativeRng);
  10159. };
  10160. const restore = editor => {
  10161. getRng(editor).each(rng => editor.selection.setRng(rng));
  10162. };
  10163. const isEditorUIElement$1 = elm => {
  10164. const className = elm.className.toString();
  10165. return className.indexOf('tox-') !== -1 || className.indexOf('mce-') !== -1;
  10166. };
  10167. const FocusManager = { isEditorUIElement: isEditorUIElement$1 };
  10168. const wrappedSetTimeout = (callback, time) => {
  10169. if (!isNumber(time)) {
  10170. time = 0;
  10171. }
  10172. return setTimeout(callback, time);
  10173. };
  10174. const wrappedSetInterval = (callback, time) => {
  10175. if (!isNumber(time)) {
  10176. time = 0;
  10177. }
  10178. return setInterval(callback, time);
  10179. };
  10180. const Delay = {
  10181. setEditorTimeout: (editor, callback, time) => {
  10182. return wrappedSetTimeout(() => {
  10183. if (!editor.removed) {
  10184. callback();
  10185. }
  10186. }, time);
  10187. },
  10188. setEditorInterval: (editor, callback, time) => {
  10189. const timer = wrappedSetInterval(() => {
  10190. if (!editor.removed) {
  10191. callback();
  10192. } else {
  10193. clearInterval(timer);
  10194. }
  10195. }, time);
  10196. return timer;
  10197. }
  10198. };
  10199. const isManualNodeChange = e => {
  10200. return e.type === 'nodechange' && e.selectionChange;
  10201. };
  10202. const registerPageMouseUp = (editor, throttledStore) => {
  10203. const mouseUpPage = () => {
  10204. throttledStore.throttle();
  10205. };
  10206. DOMUtils.DOM.bind(document, 'mouseup', mouseUpPage);
  10207. editor.on('remove', () => {
  10208. DOMUtils.DOM.unbind(document, 'mouseup', mouseUpPage);
  10209. });
  10210. };
  10211. const registerMouseUp = (editor, throttledStore) => {
  10212. editor.on('mouseup touchend', _e => {
  10213. throttledStore.throttle();
  10214. });
  10215. };
  10216. const registerEditorEvents = (editor, throttledStore) => {
  10217. registerMouseUp(editor, throttledStore);
  10218. editor.on('keyup NodeChange AfterSetSelectionRange', e => {
  10219. if (!isManualNodeChange(e)) {
  10220. store(editor);
  10221. }
  10222. });
  10223. };
  10224. const register$6 = editor => {
  10225. const throttledStore = first$1(() => {
  10226. store(editor);
  10227. }, 0);
  10228. editor.on('init', () => {
  10229. if (editor.inline) {
  10230. registerPageMouseUp(editor, throttledStore);
  10231. }
  10232. registerEditorEvents(editor, throttledStore);
  10233. });
  10234. editor.on('remove', () => {
  10235. throttledStore.cancel();
  10236. });
  10237. };
  10238. let documentFocusInHandler;
  10239. const DOM$9 = DOMUtils.DOM;
  10240. const isEditorUIElement = elm => {
  10241. return isElement$6(elm) && FocusManager.isEditorUIElement(elm);
  10242. };
  10243. const isEditorContentAreaElement = elm => {
  10244. const classList = elm.classList;
  10245. if (classList !== undefined) {
  10246. return classList.contains('tox-edit-area') || classList.contains('tox-edit-area__iframe') || classList.contains('mce-content-body');
  10247. } else {
  10248. return false;
  10249. }
  10250. };
  10251. const isUIElement = (editor, elm) => {
  10252. const customSelector = getCustomUiSelector(editor);
  10253. const parent = DOM$9.getParent(elm, elm => {
  10254. return isEditorUIElement(elm) || (customSelector ? editor.dom.is(elm, customSelector) : false);
  10255. });
  10256. return parent !== null;
  10257. };
  10258. const getActiveElement = editor => {
  10259. try {
  10260. const root = getRootNode(SugarElement.fromDom(editor.getElement()));
  10261. return active$1(root).fold(() => document.body, x => x.dom);
  10262. } catch (ex) {
  10263. return document.body;
  10264. }
  10265. };
  10266. const registerEvents$1 = (editorManager, e) => {
  10267. const editor = e.editor;
  10268. register$6(editor);
  10269. const toggleContentAreaOnFocus = (editor, fn) => {
  10270. if (shouldHighlightOnFocus(editor) && editor.inline !== true) {
  10271. const contentArea = SugarElement.fromDom(editor.getContainer());
  10272. fn(contentArea, 'tox-edit-focus');
  10273. }
  10274. };
  10275. editor.on('focusin', () => {
  10276. const focusedEditor = editorManager.focusedEditor;
  10277. if (isEditorContentAreaElement(getActiveElement(editor))) {
  10278. toggleContentAreaOnFocus(editor, add$2);
  10279. }
  10280. if (focusedEditor !== editor) {
  10281. if (focusedEditor) {
  10282. focusedEditor.dispatch('blur', { focusedEditor: editor });
  10283. }
  10284. editorManager.setActive(editor);
  10285. editorManager.focusedEditor = editor;
  10286. editor.dispatch('focus', { blurredEditor: focusedEditor });
  10287. editor.focus(true);
  10288. }
  10289. });
  10290. editor.on('focusout', () => {
  10291. Delay.setEditorTimeout(editor, () => {
  10292. const focusedEditor = editorManager.focusedEditor;
  10293. if (!isEditorContentAreaElement(getActiveElement(editor)) || focusedEditor !== editor) {
  10294. toggleContentAreaOnFocus(editor, remove$8);
  10295. }
  10296. if (!isUIElement(editor, getActiveElement(editor)) && focusedEditor === editor) {
  10297. editor.dispatch('blur', { focusedEditor: null });
  10298. editorManager.focusedEditor = null;
  10299. }
  10300. });
  10301. });
  10302. if (!documentFocusInHandler) {
  10303. documentFocusInHandler = e => {
  10304. const activeEditor = editorManager.activeEditor;
  10305. if (activeEditor) {
  10306. getOriginalEventTarget(e).each(target => {
  10307. const elem = target;
  10308. if (elem.ownerDocument === document) {
  10309. if (elem !== document.body && !isUIElement(activeEditor, elem) && editorManager.focusedEditor === activeEditor) {
  10310. activeEditor.dispatch('blur', { focusedEditor: null });
  10311. editorManager.focusedEditor = null;
  10312. }
  10313. }
  10314. });
  10315. }
  10316. };
  10317. DOM$9.bind(document, 'focusin', documentFocusInHandler);
  10318. }
  10319. };
  10320. const unregisterDocumentEvents = (editorManager, e) => {
  10321. if (editorManager.focusedEditor === e.editor) {
  10322. editorManager.focusedEditor = null;
  10323. }
  10324. if (!editorManager.activeEditor && documentFocusInHandler) {
  10325. DOM$9.unbind(document, 'focusin', documentFocusInHandler);
  10326. documentFocusInHandler = null;
  10327. }
  10328. };
  10329. const setup$v = editorManager => {
  10330. editorManager.on('AddEditor', curry(registerEvents$1, editorManager));
  10331. editorManager.on('RemoveEditor', curry(unregisterDocumentEvents, editorManager));
  10332. };
  10333. const getContentEditableHost = (editor, node) => editor.dom.getParent(node, node => editor.dom.getContentEditable(node) === 'true');
  10334. const getCollapsedNode = rng => rng.collapsed ? Optional.from(getNode$1(rng.startContainer, rng.startOffset)).map(SugarElement.fromDom) : Optional.none();
  10335. const getFocusInElement = (root, rng) => getCollapsedNode(rng).bind(node => {
  10336. if (isTableSection(node)) {
  10337. return Optional.some(node);
  10338. } else if (!contains(root, node)) {
  10339. return Optional.some(root);
  10340. } else {
  10341. return Optional.none();
  10342. }
  10343. });
  10344. const normalizeSelection = (editor, rng) => {
  10345. getFocusInElement(SugarElement.fromDom(editor.getBody()), rng).bind(elm => {
  10346. return firstPositionIn(elm.dom);
  10347. }).fold(() => {
  10348. editor.selection.normalize();
  10349. }, caretPos => editor.selection.setRng(caretPos.toRange()));
  10350. };
  10351. const focusBody = body => {
  10352. if (body.setActive) {
  10353. try {
  10354. body.setActive();
  10355. } catch (ex) {
  10356. body.focus();
  10357. }
  10358. } else {
  10359. body.focus();
  10360. }
  10361. };
  10362. const hasElementFocus = elm => hasFocus$1(elm) || search(elm).isSome();
  10363. const hasIframeFocus = editor => isNonNullable(editor.iframeElement) && hasFocus$1(SugarElement.fromDom(editor.iframeElement));
  10364. const hasInlineFocus = editor => {
  10365. const rawBody = editor.getBody();
  10366. return rawBody && hasElementFocus(SugarElement.fromDom(rawBody));
  10367. };
  10368. const hasUiFocus = editor => {
  10369. const dos = getRootNode(SugarElement.fromDom(editor.getElement()));
  10370. return active$1(dos).filter(elem => !isEditorContentAreaElement(elem.dom) && isUIElement(editor, elem.dom)).isSome();
  10371. };
  10372. const hasFocus = editor => editor.inline ? hasInlineFocus(editor) : hasIframeFocus(editor);
  10373. const hasEditorOrUiFocus = editor => hasFocus(editor) || hasUiFocus(editor);
  10374. const focusEditor = editor => {
  10375. const selection = editor.selection;
  10376. const body = editor.getBody();
  10377. let rng = selection.getRng();
  10378. editor.quirks.refreshContentEditable();
  10379. if (isNonNullable(editor.bookmark) && !hasFocus(editor)) {
  10380. getRng(editor).each(bookmarkRng => {
  10381. editor.selection.setRng(bookmarkRng);
  10382. rng = bookmarkRng;
  10383. });
  10384. }
  10385. const contentEditableHost = getContentEditableHost(editor, selection.getNode());
  10386. if (contentEditableHost && editor.dom.isChildOf(contentEditableHost, body)) {
  10387. focusBody(contentEditableHost);
  10388. normalizeSelection(editor, rng);
  10389. activateEditor(editor);
  10390. return;
  10391. }
  10392. if (!editor.inline) {
  10393. if (!Env.browser.isOpera()) {
  10394. focusBody(body);
  10395. }
  10396. editor.getWin().focus();
  10397. }
  10398. if (Env.browser.isFirefox() || editor.inline) {
  10399. focusBody(body);
  10400. normalizeSelection(editor, rng);
  10401. }
  10402. activateEditor(editor);
  10403. };
  10404. const activateEditor = editor => editor.editorManager.setActive(editor);
  10405. const focus = (editor, skipFocus) => {
  10406. if (editor.removed) {
  10407. return;
  10408. }
  10409. if (skipFocus) {
  10410. activateEditor(editor);
  10411. } else {
  10412. focusEditor(editor);
  10413. }
  10414. };
  10415. const getEndpointElement = (root, rng, start, real, resolve) => {
  10416. const container = start ? rng.startContainer : rng.endContainer;
  10417. const offset = start ? rng.startOffset : rng.endOffset;
  10418. 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);
  10419. };
  10420. const getStart = (root, rng, real = false) => getEndpointElement(root, rng, true, real, (elm, offset) => Math.min(childNodesCount(elm), offset));
  10421. const getEnd$1 = (root, rng, real = false) => getEndpointElement(root, rng, false, real, (elm, offset) => offset > 0 ? offset - 1 : offset);
  10422. const skipEmptyTextNodes = (node, forwards) => {
  10423. const orig = node;
  10424. while (node && isText$a(node) && node.length === 0) {
  10425. node = forwards ? node.nextSibling : node.previousSibling;
  10426. }
  10427. return node || orig;
  10428. };
  10429. const getNode = (root, rng) => {
  10430. if (!rng) {
  10431. return root;
  10432. }
  10433. let startContainer = rng.startContainer;
  10434. let endContainer = rng.endContainer;
  10435. const startOffset = rng.startOffset;
  10436. const endOffset = rng.endOffset;
  10437. let node = rng.commonAncestorContainer;
  10438. if (!rng.collapsed) {
  10439. if (startContainer === endContainer) {
  10440. if (endOffset - startOffset < 2) {
  10441. if (startContainer.hasChildNodes()) {
  10442. node = startContainer.childNodes[startOffset];
  10443. }
  10444. }
  10445. }
  10446. if (isText$a(startContainer) && isText$a(endContainer)) {
  10447. if (startContainer.length === startOffset) {
  10448. startContainer = skipEmptyTextNodes(startContainer.nextSibling, true);
  10449. } else {
  10450. startContainer = startContainer.parentNode;
  10451. }
  10452. if (endOffset === 0) {
  10453. endContainer = skipEmptyTextNodes(endContainer.previousSibling, false);
  10454. } else {
  10455. endContainer = endContainer.parentNode;
  10456. }
  10457. if (startContainer && startContainer === endContainer) {
  10458. node = startContainer;
  10459. }
  10460. }
  10461. }
  10462. const elm = isText$a(node) ? node.parentNode : node;
  10463. return isElement$6(elm) ? elm : root;
  10464. };
  10465. const getSelectedBlocks = (dom, rng, startElm, endElm) => {
  10466. const selectedBlocks = [];
  10467. const root = dom.getRoot();
  10468. const start = dom.getParent(startElm || getStart(root, rng, rng.collapsed), dom.isBlock);
  10469. const end = dom.getParent(endElm || getEnd$1(root, rng, rng.collapsed), dom.isBlock);
  10470. if (start && start !== root) {
  10471. selectedBlocks.push(start);
  10472. }
  10473. if (start && end && start !== end) {
  10474. let node;
  10475. const walker = new DomTreeWalker(start, root);
  10476. while ((node = walker.next()) && node !== end) {
  10477. if (dom.isBlock(node)) {
  10478. selectedBlocks.push(node);
  10479. }
  10480. }
  10481. }
  10482. if (end && start !== end && end !== root) {
  10483. selectedBlocks.push(end);
  10484. }
  10485. return selectedBlocks;
  10486. };
  10487. const select = (dom, node, content) => Optional.from(node).bind(node => Optional.from(node.parentNode).map(parent => {
  10488. const idx = dom.nodeIndex(node);
  10489. const rng = dom.createRng();
  10490. rng.setStart(parent, idx);
  10491. rng.setEnd(parent, idx + 1);
  10492. if (content) {
  10493. moveEndPoint(dom, rng, node, true);
  10494. moveEndPoint(dom, rng, node, false);
  10495. }
  10496. return rng;
  10497. }));
  10498. const processRanges = (editor, ranges) => map$3(ranges, range => {
  10499. const evt = editor.dispatch('GetSelectionRange', { range });
  10500. return evt.range !== range ? evt.range : range;
  10501. });
  10502. const getEnd = element => name(element) === 'img' ? 1 : getOption(element).fold(() => children$1(element).length, v => v.length);
  10503. const isTextNodeWithCursorPosition = el => getOption(el).filter(text => text.trim().length !== 0 || text.indexOf(nbsp) > -1).isSome();
  10504. const isContentEditableFalse$5 = elem => isHTMLElement(elem) && get$9(elem, 'contenteditable') === 'false';
  10505. const elementsWithCursorPosition = [
  10506. 'img',
  10507. 'br'
  10508. ];
  10509. const isCursorPosition = elem => {
  10510. const hasCursorPosition = isTextNodeWithCursorPosition(elem);
  10511. return hasCursorPosition || contains$2(elementsWithCursorPosition, name(elem)) || isContentEditableFalse$5(elem);
  10512. };
  10513. const first = element => descendant$1(element, isCursorPosition);
  10514. const last = element => descendantRtl(element, isCursorPosition);
  10515. const descendantRtl = (scope, predicate) => {
  10516. const descend = element => {
  10517. const children = children$1(element);
  10518. for (let i = children.length - 1; i >= 0; i--) {
  10519. const child = children[i];
  10520. if (predicate(child)) {
  10521. return Optional.some(child);
  10522. }
  10523. const res = descend(child);
  10524. if (res.isSome()) {
  10525. return res;
  10526. }
  10527. }
  10528. return Optional.none();
  10529. };
  10530. return descend(scope);
  10531. };
  10532. const autocompleteSelector = '[data-mce-autocompleter]';
  10533. const create$9 = (editor, range) => {
  10534. if (findIn(SugarElement.fromDom(editor.getBody())).isNone()) {
  10535. const wrapper = SugarElement.fromHtml('<span data-mce-autocompleter="1" data-mce-bogus="1"></span>', editor.getDoc());
  10536. append$1(wrapper, SugarElement.fromDom(range.extractContents()));
  10537. range.insertNode(wrapper.dom);
  10538. parent(wrapper).each(elm => elm.dom.normalize());
  10539. last(wrapper).map(last => {
  10540. editor.selection.setCursorLocation(last.dom, getEnd(last));
  10541. });
  10542. }
  10543. };
  10544. const detect$1 = elm => closest$3(elm, autocompleteSelector);
  10545. const findIn = elm => descendant(elm, autocompleteSelector);
  10546. const remove$3 = (editor, elm) => findIn(elm).each(wrapper => {
  10547. const bookmark = editor.selection.getBookmark();
  10548. unwrap(wrapper);
  10549. editor.selection.moveToBookmark(bookmark);
  10550. });
  10551. const typeLookup = {
  10552. '#text': 3,
  10553. '#comment': 8,
  10554. '#cdata': 4,
  10555. '#pi': 7,
  10556. '#doctype': 10,
  10557. '#document-fragment': 11
  10558. };
  10559. const walk$2 = (node, root, prev) => {
  10560. const startName = prev ? 'lastChild' : 'firstChild';
  10561. const siblingName = prev ? 'prev' : 'next';
  10562. if (node[startName]) {
  10563. return node[startName];
  10564. }
  10565. if (node !== root) {
  10566. let sibling = node[siblingName];
  10567. if (sibling) {
  10568. return sibling;
  10569. }
  10570. for (let parent = node.parent; parent && parent !== root; parent = parent.parent) {
  10571. sibling = parent[siblingName];
  10572. if (sibling) {
  10573. return sibling;
  10574. }
  10575. }
  10576. }
  10577. return undefined;
  10578. };
  10579. const isEmptyTextNode = node => {
  10580. var _a;
  10581. const text = (_a = node.value) !== null && _a !== void 0 ? _a : '';
  10582. if (!isWhitespaceText(text)) {
  10583. return false;
  10584. }
  10585. const parentNode = node.parent;
  10586. if (parentNode && (parentNode.name !== 'span' || parentNode.attr('style')) && /^[ ]+$/.test(text)) {
  10587. return false;
  10588. }
  10589. return true;
  10590. };
  10591. const isNonEmptyElement = node => {
  10592. const isNamedAnchor = node.name === 'a' && !node.attr('href') && node.attr('id');
  10593. return node.attr('name') || node.attr('id') && !node.firstChild || node.attr('data-mce-bookmark') || isNamedAnchor;
  10594. };
  10595. class AstNode {
  10596. constructor(name, type) {
  10597. this.name = name;
  10598. this.type = type;
  10599. if (type === 1) {
  10600. this.attributes = [];
  10601. this.attributes.map = {};
  10602. }
  10603. }
  10604. static create(name, attrs) {
  10605. const node = new AstNode(name, typeLookup[name] || 1);
  10606. if (attrs) {
  10607. each$d(attrs, (value, attrName) => {
  10608. node.attr(attrName, value);
  10609. });
  10610. }
  10611. return node;
  10612. }
  10613. replace(node) {
  10614. const self = this;
  10615. if (node.parent) {
  10616. node.remove();
  10617. }
  10618. self.insert(node, self);
  10619. self.remove();
  10620. return self;
  10621. }
  10622. attr(name, value) {
  10623. const self = this;
  10624. if (!isString(name)) {
  10625. if (isNonNullable(name)) {
  10626. each$d(name, (value, key) => {
  10627. self.attr(key, value);
  10628. });
  10629. }
  10630. return self;
  10631. }
  10632. const attrs = self.attributes;
  10633. if (attrs) {
  10634. if (value !== undefined) {
  10635. if (value === null) {
  10636. if (name in attrs.map) {
  10637. delete attrs.map[name];
  10638. let i = attrs.length;
  10639. while (i--) {
  10640. if (attrs[i].name === name) {
  10641. attrs.splice(i, 1);
  10642. return self;
  10643. }
  10644. }
  10645. }
  10646. return self;
  10647. }
  10648. if (name in attrs.map) {
  10649. let i = attrs.length;
  10650. while (i--) {
  10651. if (attrs[i].name === name) {
  10652. attrs[i].value = value;
  10653. break;
  10654. }
  10655. }
  10656. } else {
  10657. attrs.push({
  10658. name,
  10659. value
  10660. });
  10661. }
  10662. attrs.map[name] = value;
  10663. return self;
  10664. }
  10665. return attrs.map[name];
  10666. }
  10667. return undefined;
  10668. }
  10669. clone() {
  10670. const self = this;
  10671. const clone = new AstNode(self.name, self.type);
  10672. const selfAttrs = self.attributes;
  10673. if (selfAttrs) {
  10674. const cloneAttrs = [];
  10675. cloneAttrs.map = {};
  10676. for (let i = 0, l = selfAttrs.length; i < l; i++) {
  10677. const selfAttr = selfAttrs[i];
  10678. if (selfAttr.name !== 'id') {
  10679. cloneAttrs[cloneAttrs.length] = {
  10680. name: selfAttr.name,
  10681. value: selfAttr.value
  10682. };
  10683. cloneAttrs.map[selfAttr.name] = selfAttr.value;
  10684. }
  10685. }
  10686. clone.attributes = cloneAttrs;
  10687. }
  10688. clone.value = self.value;
  10689. return clone;
  10690. }
  10691. wrap(wrapper) {
  10692. const self = this;
  10693. if (self.parent) {
  10694. self.parent.insert(wrapper, self);
  10695. wrapper.append(self);
  10696. }
  10697. return self;
  10698. }
  10699. unwrap() {
  10700. const self = this;
  10701. for (let node = self.firstChild; node;) {
  10702. const next = node.next;
  10703. self.insert(node, self, true);
  10704. node = next;
  10705. }
  10706. self.remove();
  10707. }
  10708. remove() {
  10709. const self = this, parent = self.parent, next = self.next, prev = self.prev;
  10710. if (parent) {
  10711. if (parent.firstChild === self) {
  10712. parent.firstChild = next;
  10713. if (next) {
  10714. next.prev = null;
  10715. }
  10716. } else if (prev) {
  10717. prev.next = next;
  10718. }
  10719. if (parent.lastChild === self) {
  10720. parent.lastChild = prev;
  10721. if (prev) {
  10722. prev.next = null;
  10723. }
  10724. } else if (next) {
  10725. next.prev = prev;
  10726. }
  10727. self.parent = self.next = self.prev = null;
  10728. }
  10729. return self;
  10730. }
  10731. append(node) {
  10732. const self = this;
  10733. if (node.parent) {
  10734. node.remove();
  10735. }
  10736. const last = self.lastChild;
  10737. if (last) {
  10738. last.next = node;
  10739. node.prev = last;
  10740. self.lastChild = node;
  10741. } else {
  10742. self.lastChild = self.firstChild = node;
  10743. }
  10744. node.parent = self;
  10745. return node;
  10746. }
  10747. insert(node, refNode, before) {
  10748. if (node.parent) {
  10749. node.remove();
  10750. }
  10751. const parent = refNode.parent || this;
  10752. if (before) {
  10753. if (refNode === parent.firstChild) {
  10754. parent.firstChild = node;
  10755. } else if (refNode.prev) {
  10756. refNode.prev.next = node;
  10757. }
  10758. node.prev = refNode.prev;
  10759. node.next = refNode;
  10760. refNode.prev = node;
  10761. } else {
  10762. if (refNode === parent.lastChild) {
  10763. parent.lastChild = node;
  10764. } else if (refNode.next) {
  10765. refNode.next.prev = node;
  10766. }
  10767. node.next = refNode.next;
  10768. node.prev = refNode;
  10769. refNode.next = node;
  10770. }
  10771. node.parent = parent;
  10772. return node;
  10773. }
  10774. getAll(name) {
  10775. const self = this;
  10776. const collection = [];
  10777. for (let node = self.firstChild; node; node = walk$2(node, self)) {
  10778. if (node.name === name) {
  10779. collection.push(node);
  10780. }
  10781. }
  10782. return collection;
  10783. }
  10784. children() {
  10785. const self = this;
  10786. const collection = [];
  10787. for (let node = self.firstChild; node; node = node.next) {
  10788. collection.push(node);
  10789. }
  10790. return collection;
  10791. }
  10792. empty() {
  10793. const self = this;
  10794. if (self.firstChild) {
  10795. const nodes = [];
  10796. for (let node = self.firstChild; node; node = walk$2(node, self)) {
  10797. nodes.push(node);
  10798. }
  10799. let i = nodes.length;
  10800. while (i--) {
  10801. const node = nodes[i];
  10802. node.parent = node.firstChild = node.lastChild = node.next = node.prev = null;
  10803. }
  10804. }
  10805. self.firstChild = self.lastChild = null;
  10806. return self;
  10807. }
  10808. isEmpty(elements, whitespace = {}, predicate) {
  10809. var _a;
  10810. const self = this;
  10811. let node = self.firstChild;
  10812. if (isNonEmptyElement(self)) {
  10813. return false;
  10814. }
  10815. if (node) {
  10816. do {
  10817. if (node.type === 1) {
  10818. if (node.attr('data-mce-bogus')) {
  10819. continue;
  10820. }
  10821. if (elements[node.name]) {
  10822. return false;
  10823. }
  10824. if (isNonEmptyElement(node)) {
  10825. return false;
  10826. }
  10827. }
  10828. if (node.type === 8) {
  10829. return false;
  10830. }
  10831. if (node.type === 3 && !isEmptyTextNode(node)) {
  10832. return false;
  10833. }
  10834. if (node.type === 3 && node.parent && whitespace[node.parent.name] && isWhitespaceText((_a = node.value) !== null && _a !== void 0 ? _a : '')) {
  10835. return false;
  10836. }
  10837. if (predicate && predicate(node)) {
  10838. return false;
  10839. }
  10840. } while (node = walk$2(node, self));
  10841. }
  10842. return true;
  10843. }
  10844. walk(prev) {
  10845. return walk$2(this, null, prev);
  10846. }
  10847. }
  10848. const isConditionalComment = (html, startIndex) => /^\s*\[if [\w\W]+\]>.*<!\[endif\](--!?)?>/.test(html.substr(startIndex));
  10849. const findCommentEndIndex = (html, isBogus, startIndex = 0) => {
  10850. const lcHtml = html.toLowerCase();
  10851. if (lcHtml.indexOf('[if ', startIndex) !== -1 && isConditionalComment(lcHtml, startIndex)) {
  10852. const endIfIndex = lcHtml.indexOf('[endif]', startIndex);
  10853. return lcHtml.indexOf('>', endIfIndex);
  10854. } else {
  10855. if (isBogus) {
  10856. const endIndex = lcHtml.indexOf('>', startIndex);
  10857. return endIndex !== -1 ? endIndex : lcHtml.length;
  10858. } else {
  10859. const endCommentRegexp = /--!?>/g;
  10860. endCommentRegexp.lastIndex = startIndex;
  10861. const match = endCommentRegexp.exec(html);
  10862. return match ? match.index + match[0].length : lcHtml.length;
  10863. }
  10864. }
  10865. };
  10866. const findMatchingEndTagIndex = (schema, html, startIndex) => {
  10867. const startTagRegExp = /<([!?\/])?([A-Za-z0-9\-_:.]+)/g;
  10868. const endTagRegExp = /(?:\s(?:[^'">]+(?:"[^"]*"|'[^']*'))*[^"'>]*(?:"[^">]*|'[^'>]*)?|\s*|\/)>/g;
  10869. const voidElements = schema.getVoidElements();
  10870. let count = 1, index = startIndex;
  10871. while (count !== 0) {
  10872. startTagRegExp.lastIndex = index;
  10873. while (true) {
  10874. const startMatch = startTagRegExp.exec(html);
  10875. if (startMatch === null) {
  10876. return index;
  10877. } else if (startMatch[1] === '!') {
  10878. if (startsWith(startMatch[2], '--')) {
  10879. index = findCommentEndIndex(html, false, startMatch.index + '!--'.length);
  10880. } else {
  10881. index = findCommentEndIndex(html, true, startMatch.index + 1);
  10882. }
  10883. break;
  10884. } else {
  10885. endTagRegExp.lastIndex = startTagRegExp.lastIndex;
  10886. const endMatch = endTagRegExp.exec(html);
  10887. if (isNull(endMatch) || endMatch.index !== startTagRegExp.lastIndex) {
  10888. continue;
  10889. }
  10890. if (startMatch[1] === '/') {
  10891. count -= 1;
  10892. } else if (!has$2(voidElements, startMatch[2])) {
  10893. count += 1;
  10894. }
  10895. index = startTagRegExp.lastIndex + endMatch[0].length;
  10896. break;
  10897. }
  10898. }
  10899. }
  10900. return index;
  10901. };
  10902. const trimHtml$1 = (tempAttrs, html) => {
  10903. const trimContentRegExp = new RegExp(['\\s?(' + tempAttrs.join('|') + ')="[^"]+"'].join('|'), 'gi');
  10904. return html.replace(trimContentRegExp, '');
  10905. };
  10906. const trimInternal = (serializer, html) => {
  10907. const bogusAllRegExp = /<(\w+) [^>]*data-mce-bogus="all"[^>]*>/g;
  10908. const schema = serializer.schema;
  10909. let content = trimHtml$1(serializer.getTempAttrs(), html);
  10910. const voidElements = schema.getVoidElements();
  10911. let matches;
  10912. while (matches = bogusAllRegExp.exec(content)) {
  10913. const index = bogusAllRegExp.lastIndex;
  10914. const matchLength = matches[0].length;
  10915. let endTagIndex;
  10916. if (voidElements[matches[1]]) {
  10917. endTagIndex = index;
  10918. } else {
  10919. endTagIndex = findMatchingEndTagIndex(schema, content, index);
  10920. }
  10921. content = content.substring(0, index - matchLength) + content.substring(endTagIndex);
  10922. bogusAllRegExp.lastIndex = index - matchLength;
  10923. }
  10924. return trim$1(content);
  10925. };
  10926. const trimExternal = trimInternal;
  10927. const cleanupBogusElements = parent => {
  10928. const bogusElements = descendants(parent, '[data-mce-bogus]');
  10929. each$e(bogusElements, elem => {
  10930. const bogusValue = get$9(elem, 'data-mce-bogus');
  10931. if (bogusValue === 'all') {
  10932. remove$6(elem);
  10933. } else if (isBr$5(elem)) {
  10934. before$3(elem, SugarElement.fromText(zeroWidth));
  10935. remove$6(elem);
  10936. } else {
  10937. unwrap(elem);
  10938. }
  10939. });
  10940. };
  10941. const cleanupInputNames = parent => {
  10942. const inputs = descendants(parent, 'input');
  10943. each$e(inputs, input => {
  10944. remove$b(input, 'name');
  10945. });
  10946. };
  10947. const trimEmptyContents = (editor, html) => {
  10948. const blockName = getForcedRootBlock(editor);
  10949. const emptyRegExp = new RegExp(`^(<${ blockName }[^>]*>(&nbsp;|&#160;|\\s|\u00a0|<br \\/>|)<\\/${ blockName }>[\r\n]*|<br \\/>[\r\n]*)$`);
  10950. return html.replace(emptyRegExp, '');
  10951. };
  10952. const getPlainTextContent = (editor, body) => {
  10953. const doc = editor.getDoc();
  10954. const dos = getRootNode(SugarElement.fromDom(editor.getBody()));
  10955. const offscreenDiv = SugarElement.fromTag('div', doc);
  10956. set$3(offscreenDiv, 'data-mce-bogus', 'all');
  10957. setAll(offscreenDiv, {
  10958. position: 'fixed',
  10959. left: '-9999999px',
  10960. top: '0'
  10961. });
  10962. set$1(offscreenDiv, body.innerHTML);
  10963. cleanupBogusElements(offscreenDiv);
  10964. cleanupInputNames(offscreenDiv);
  10965. const root = getContentContainer(dos);
  10966. append$1(root, offscreenDiv);
  10967. const content = trim$1(offscreenDiv.dom.innerText);
  10968. remove$6(offscreenDiv);
  10969. return content;
  10970. };
  10971. const getContentFromBody = (editor, args, body) => {
  10972. let content;
  10973. if (args.format === 'raw') {
  10974. content = Tools.trim(trimExternal(editor.serializer, body.innerHTML));
  10975. } else if (args.format === 'text') {
  10976. content = getPlainTextContent(editor, body);
  10977. } else if (args.format === 'tree') {
  10978. content = editor.serializer.serialize(body, args);
  10979. } else {
  10980. content = trimEmptyContents(editor, editor.serializer.serialize(body, args));
  10981. }
  10982. const shouldTrim = args.format !== 'text' && !isWsPreserveElement(SugarElement.fromDom(body));
  10983. return shouldTrim && isString(content) ? Tools.trim(content) : content;
  10984. };
  10985. const getContentInternal = (editor, args) => Optional.from(editor.getBody()).fold(constant(args.format === 'tree' ? new AstNode('body', 11) : ''), body => getContentFromBody(editor, args, body));
  10986. const makeMap$1 = Tools.makeMap;
  10987. const Writer = settings => {
  10988. const html = [];
  10989. settings = settings || {};
  10990. const indent = settings.indent;
  10991. const indentBefore = makeMap$1(settings.indent_before || '');
  10992. const indentAfter = makeMap$1(settings.indent_after || '');
  10993. const encode = Entities.getEncodeFunc(settings.entity_encoding || 'raw', settings.entities);
  10994. const htmlOutput = settings.element_format !== 'xhtml';
  10995. return {
  10996. start: (name, attrs, empty) => {
  10997. if (indent && indentBefore[name] && html.length > 0) {
  10998. const value = html[html.length - 1];
  10999. if (value.length > 0 && value !== '\n') {
  11000. html.push('\n');
  11001. }
  11002. }
  11003. html.push('<', name);
  11004. if (attrs) {
  11005. for (let i = 0, l = attrs.length; i < l; i++) {
  11006. const attr = attrs[i];
  11007. html.push(' ', attr.name, '="', encode(attr.value, true), '"');
  11008. }
  11009. }
  11010. if (!empty || htmlOutput) {
  11011. html[html.length] = '>';
  11012. } else {
  11013. html[html.length] = ' />';
  11014. }
  11015. if (empty && indent && indentAfter[name] && html.length > 0) {
  11016. const value = html[html.length - 1];
  11017. if (value.length > 0 && value !== '\n') {
  11018. html.push('\n');
  11019. }
  11020. }
  11021. },
  11022. end: name => {
  11023. let value;
  11024. html.push('</', name, '>');
  11025. if (indent && indentAfter[name] && html.length > 0) {
  11026. value = html[html.length - 1];
  11027. if (value.length > 0 && value !== '\n') {
  11028. html.push('\n');
  11029. }
  11030. }
  11031. },
  11032. text: (text, raw) => {
  11033. if (text.length > 0) {
  11034. html[html.length] = raw ? text : encode(text);
  11035. }
  11036. },
  11037. cdata: text => {
  11038. html.push('<![CDATA[', text, ']]>');
  11039. },
  11040. comment: text => {
  11041. html.push('<!--', text, '-->');
  11042. },
  11043. pi: (name, text) => {
  11044. if (text) {
  11045. html.push('<?', name, ' ', encode(text), '?>');
  11046. } else {
  11047. html.push('<?', name, '?>');
  11048. }
  11049. if (indent) {
  11050. html.push('\n');
  11051. }
  11052. },
  11053. doctype: text => {
  11054. html.push('<!DOCTYPE', text, '>', indent ? '\n' : '');
  11055. },
  11056. reset: () => {
  11057. html.length = 0;
  11058. },
  11059. getContent: () => {
  11060. return html.join('').replace(/\n$/, '');
  11061. }
  11062. };
  11063. };
  11064. const HtmlSerializer = (settings = {}, schema = Schema()) => {
  11065. const writer = Writer(settings);
  11066. settings.validate = 'validate' in settings ? settings.validate : true;
  11067. const serialize = node => {
  11068. const validate = settings.validate;
  11069. const handlers = {
  11070. 3: node => {
  11071. var _a;
  11072. writer.text((_a = node.value) !== null && _a !== void 0 ? _a : '', node.raw);
  11073. },
  11074. 8: node => {
  11075. var _a;
  11076. writer.comment((_a = node.value) !== null && _a !== void 0 ? _a : '');
  11077. },
  11078. 7: node => {
  11079. writer.pi(node.name, node.value);
  11080. },
  11081. 10: node => {
  11082. var _a;
  11083. writer.doctype((_a = node.value) !== null && _a !== void 0 ? _a : '');
  11084. },
  11085. 4: node => {
  11086. var _a;
  11087. writer.cdata((_a = node.value) !== null && _a !== void 0 ? _a : '');
  11088. },
  11089. 11: node => {
  11090. let tempNode = node;
  11091. if (tempNode = tempNode.firstChild) {
  11092. do {
  11093. walk(tempNode);
  11094. } while (tempNode = tempNode.next);
  11095. }
  11096. }
  11097. };
  11098. writer.reset();
  11099. const walk = node => {
  11100. var _a;
  11101. const handler = handlers[node.type];
  11102. if (!handler) {
  11103. const name = node.name;
  11104. const isEmpty = name in schema.getVoidElements();
  11105. let attrs = node.attributes;
  11106. if (validate && attrs && attrs.length > 1) {
  11107. const sortedAttrs = [];
  11108. sortedAttrs.map = {};
  11109. const elementRule = schema.getElementRule(node.name);
  11110. if (elementRule) {
  11111. for (let i = 0, l = elementRule.attributesOrder.length; i < l; i++) {
  11112. const attrName = elementRule.attributesOrder[i];
  11113. if (attrName in attrs.map) {
  11114. const attrValue = attrs.map[attrName];
  11115. sortedAttrs.map[attrName] = attrValue;
  11116. sortedAttrs.push({
  11117. name: attrName,
  11118. value: attrValue
  11119. });
  11120. }
  11121. }
  11122. for (let i = 0, l = attrs.length; i < l; i++) {
  11123. const attrName = attrs[i].name;
  11124. if (!(attrName in sortedAttrs.map)) {
  11125. const attrValue = attrs.map[attrName];
  11126. sortedAttrs.map[attrName] = attrValue;
  11127. sortedAttrs.push({
  11128. name: attrName,
  11129. value: attrValue
  11130. });
  11131. }
  11132. }
  11133. attrs = sortedAttrs;
  11134. }
  11135. }
  11136. writer.start(name, attrs, isEmpty);
  11137. if (!isEmpty) {
  11138. let child = node.firstChild;
  11139. if (child) {
  11140. if ((name === 'pre' || name === 'textarea') && child.type === 3 && ((_a = child.value) === null || _a === void 0 ? void 0 : _a[0]) === '\n') {
  11141. writer.text('\n', true);
  11142. }
  11143. do {
  11144. walk(child);
  11145. } while (child = child.next);
  11146. }
  11147. writer.end(name);
  11148. }
  11149. } else {
  11150. handler(node);
  11151. }
  11152. };
  11153. if (node.type === 1 && !settings.inner) {
  11154. walk(node);
  11155. } else if (node.type === 3) {
  11156. handlers[3](node);
  11157. } else {
  11158. handlers[11](node);
  11159. }
  11160. return writer.getContent();
  11161. };
  11162. return { serialize };
  11163. };
  11164. const nonInheritableStyles = new Set();
  11165. (() => {
  11166. const nonInheritableStylesArr = [
  11167. 'margin',
  11168. 'margin-left',
  11169. 'margin-right',
  11170. 'margin-top',
  11171. 'margin-bottom',
  11172. 'padding',
  11173. 'padding-left',
  11174. 'padding-right',
  11175. 'padding-top',
  11176. 'padding-bottom',
  11177. 'border',
  11178. 'border-width',
  11179. 'border-style',
  11180. 'border-color',
  11181. 'background',
  11182. 'background-attachment',
  11183. 'background-clip',
  11184. 'background-color',
  11185. 'background-image',
  11186. 'background-origin',
  11187. 'background-position',
  11188. 'background-repeat',
  11189. 'background-size',
  11190. 'float',
  11191. 'position',
  11192. 'left',
  11193. 'right',
  11194. 'top',
  11195. 'bottom',
  11196. 'z-index',
  11197. 'display',
  11198. 'transform',
  11199. 'width',
  11200. 'max-width',
  11201. 'min-width',
  11202. 'height',
  11203. 'max-height',
  11204. 'min-height',
  11205. 'overflow',
  11206. 'overflow-x',
  11207. 'overflow-y',
  11208. 'text-overflow',
  11209. 'vertical-align',
  11210. 'transition',
  11211. 'transition-delay',
  11212. 'transition-duration',
  11213. 'transition-property',
  11214. 'transition-timing-function'
  11215. ];
  11216. each$e(nonInheritableStylesArr, style => {
  11217. nonInheritableStyles.add(style);
  11218. });
  11219. })();
  11220. const shorthandStyleProps = [
  11221. 'font',
  11222. 'text-decoration',
  11223. 'text-emphasis'
  11224. ];
  11225. const getStyleProps = (dom, node) => keys(dom.parseStyle(dom.getAttrib(node, 'style')));
  11226. const isNonInheritableStyle = style => nonInheritableStyles.has(style);
  11227. const hasInheritableStyles = (dom, node) => forall(getStyleProps(dom, node), style => !isNonInheritableStyle(style));
  11228. const getLonghandStyleProps = styles => filter$5(styles, style => exists(shorthandStyleProps, prop => startsWith(style, prop)));
  11229. const hasStyleConflict = (dom, node, parentNode) => {
  11230. const nodeStyleProps = getStyleProps(dom, node);
  11231. const parentNodeStyleProps = getStyleProps(dom, parentNode);
  11232. const valueMismatch = prop => {
  11233. var _a, _b;
  11234. const nodeValue = (_a = dom.getStyle(node, prop)) !== null && _a !== void 0 ? _a : '';
  11235. const parentValue = (_b = dom.getStyle(parentNode, prop)) !== null && _b !== void 0 ? _b : '';
  11236. return isNotEmpty(nodeValue) && isNotEmpty(parentValue) && nodeValue !== parentValue;
  11237. };
  11238. return exists(nodeStyleProps, nodeStyleProp => {
  11239. const propExists = props => exists(props, prop => prop === nodeStyleProp);
  11240. if (!propExists(parentNodeStyleProps) && propExists(shorthandStyleProps)) {
  11241. const longhandProps = getLonghandStyleProps(parentNodeStyleProps);
  11242. return exists(longhandProps, valueMismatch);
  11243. } else {
  11244. return valueMismatch(nodeStyleProp);
  11245. }
  11246. });
  11247. };
  11248. const isChar = (forward, predicate, pos) => Optional.from(pos.container()).filter(isText$a).exists(text => {
  11249. const delta = forward ? 0 : -1;
  11250. return predicate(text.data.charAt(pos.offset() + delta));
  11251. });
  11252. const isBeforeSpace = curry(isChar, true, isWhiteSpace);
  11253. const isAfterSpace = curry(isChar, false, isWhiteSpace);
  11254. const isEmptyText = pos => {
  11255. const container = pos.container();
  11256. return isText$a(container) && (container.data.length === 0 || isZwsp(container.data) && BookmarkManager.isBookmarkNode(container.parentNode));
  11257. };
  11258. const matchesElementPosition = (before, predicate) => pos => getChildNodeAtRelativeOffset(before ? 0 : -1, pos).filter(predicate).isSome();
  11259. const isImageBlock = node => isImg(node) && get$7(SugarElement.fromDom(node), 'display') === 'block';
  11260. const isCefNode = node => isContentEditableFalse$b(node) && !isBogusAll$1(node);
  11261. const isBeforeImageBlock = matchesElementPosition(true, isImageBlock);
  11262. const isAfterImageBlock = matchesElementPosition(false, isImageBlock);
  11263. const isBeforeMedia = matchesElementPosition(true, isMedia$2);
  11264. const isAfterMedia = matchesElementPosition(false, isMedia$2);
  11265. const isBeforeTable = matchesElementPosition(true, isTable$2);
  11266. const isAfterTable = matchesElementPosition(false, isTable$2);
  11267. const isBeforeContentEditableFalse = matchesElementPosition(true, isCefNode);
  11268. const isAfterContentEditableFalse = matchesElementPosition(false, isCefNode);
  11269. const dropLast = xs => xs.slice(0, -1);
  11270. const parentsUntil = (start, root, predicate) => {
  11271. if (contains(root, start)) {
  11272. return dropLast(parents$1(start, elm => {
  11273. return predicate(elm) || eq(elm, root);
  11274. }));
  11275. } else {
  11276. return [];
  11277. }
  11278. };
  11279. const parents = (start, root) => parentsUntil(start, root, never);
  11280. const parentsAndSelf = (start, root) => [start].concat(parents(start, root));
  11281. const navigateIgnoreEmptyTextNodes = (forward, root, from) => navigateIgnore(forward, root, from, isEmptyText);
  11282. const getClosestBlock$1 = (root, pos) => find$2(parentsAndSelf(SugarElement.fromDom(pos.container()), root), isBlock$2);
  11283. const isAtBeforeAfterBlockBoundary = (forward, root, pos) => navigateIgnoreEmptyTextNodes(forward, root.dom, pos).forall(newPos => getClosestBlock$1(root, pos).fold(() => !isInSameBlock(newPos, pos, root.dom), fromBlock => !isInSameBlock(newPos, pos, root.dom) && contains(fromBlock, SugarElement.fromDom(newPos.container()))));
  11284. const isAtBlockBoundary = (forward, root, pos) => getClosestBlock$1(root, pos).fold(() => navigateIgnoreEmptyTextNodes(forward, root.dom, pos).forall(newPos => !isInSameBlock(newPos, pos, root.dom)), parent => navigateIgnoreEmptyTextNodes(forward, parent.dom, pos).isNone());
  11285. const isAtStartOfBlock = curry(isAtBlockBoundary, false);
  11286. const isAtEndOfBlock = curry(isAtBlockBoundary, true);
  11287. const isBeforeBlock = curry(isAtBeforeAfterBlockBoundary, false);
  11288. const isAfterBlock = curry(isAtBeforeAfterBlockBoundary, true);
  11289. const isBr$1 = pos => getElementFromPosition(pos).exists(isBr$5);
  11290. const findBr = (forward, root, pos) => {
  11291. const parentBlocks = filter$5(parentsAndSelf(SugarElement.fromDom(pos.container()), root), isBlock$2);
  11292. const scope = head(parentBlocks).getOr(root);
  11293. return fromPosition(forward, scope.dom, pos).filter(isBr$1);
  11294. };
  11295. const isBeforeBr$1 = (root, pos) => getElementFromPosition(pos).exists(isBr$5) || findBr(true, root, pos).isSome();
  11296. const isAfterBr = (root, pos) => getElementFromPrevPosition(pos).exists(isBr$5) || findBr(false, root, pos).isSome();
  11297. const findPreviousBr = curry(findBr, false);
  11298. const findNextBr = curry(findBr, true);
  11299. const isInMiddleOfText = pos => CaretPosition.isTextPosition(pos) && !pos.isAtStart() && !pos.isAtEnd();
  11300. const getClosestBlock = (root, pos) => {
  11301. const parentBlocks = filter$5(parentsAndSelf(SugarElement.fromDom(pos.container()), root), isBlock$2);
  11302. return head(parentBlocks).getOr(root);
  11303. };
  11304. const hasSpaceBefore = (root, pos) => {
  11305. if (isInMiddleOfText(pos)) {
  11306. return isAfterSpace(pos);
  11307. } else {
  11308. return isAfterSpace(pos) || prevPosition(getClosestBlock(root, pos).dom, pos).exists(isAfterSpace);
  11309. }
  11310. };
  11311. const hasSpaceAfter = (root, pos) => {
  11312. if (isInMiddleOfText(pos)) {
  11313. return isBeforeSpace(pos);
  11314. } else {
  11315. return isBeforeSpace(pos) || nextPosition(getClosestBlock(root, pos).dom, pos).exists(isBeforeSpace);
  11316. }
  11317. };
  11318. const isPreValue = value => contains$2([
  11319. 'pre',
  11320. 'pre-wrap'
  11321. ], value);
  11322. const isInPre = pos => getElementFromPosition(pos).bind(elm => closest$4(elm, isElement$7)).exists(elm => isPreValue(get$7(elm, 'white-space')));
  11323. const isAtBeginningOfBody = (root, pos) => prevPosition(root.dom, pos).isNone();
  11324. const isAtEndOfBody = (root, pos) => nextPosition(root.dom, pos).isNone();
  11325. const isAtLineBoundary = (root, pos) => isAtBeginningOfBody(root, pos) || isAtEndOfBody(root, pos) || isAtStartOfBlock(root, pos) || isAtEndOfBlock(root, pos) || isAfterBr(root, pos) || isBeforeBr$1(root, pos);
  11326. const isCefBlock = node => isNonNullable(node) && isContentEditableFalse$b(node) && isBlockLike(node);
  11327. const isSiblingCefBlock = (root, direction) => container => {
  11328. return isCefBlock(new DomTreeWalker(container, root)[direction]());
  11329. };
  11330. const isBeforeCefBlock = (root, pos) => {
  11331. const nextPos = nextPosition(root.dom, pos).getOr(pos);
  11332. const isNextCefBlock = isSiblingCefBlock(root.dom, 'next');
  11333. return pos.isAtEnd() && (isNextCefBlock(pos.container()) || isNextCefBlock(nextPos.container()));
  11334. };
  11335. const isAfterCefBlock = (root, pos) => {
  11336. const prevPos = prevPosition(root.dom, pos).getOr(pos);
  11337. const isPrevCefBlock = isSiblingCefBlock(root.dom, 'prev');
  11338. return pos.isAtStart() && (isPrevCefBlock(pos.container()) || isPrevCefBlock(prevPos.container()));
  11339. };
  11340. const needsToHaveNbsp = (root, pos) => {
  11341. if (isInPre(pos)) {
  11342. return false;
  11343. } else {
  11344. return isAtLineBoundary(root, pos) || hasSpaceBefore(root, pos) || hasSpaceAfter(root, pos);
  11345. }
  11346. };
  11347. const needsToBeNbspLeft = (root, pos) => {
  11348. if (isInPre(pos)) {
  11349. return false;
  11350. } else {
  11351. return isAtStartOfBlock(root, pos) || isBeforeBlock(root, pos) || isAfterBr(root, pos) || hasSpaceBefore(root, pos) || isAfterCefBlock(root, pos);
  11352. }
  11353. };
  11354. const leanRight = pos => {
  11355. const container = pos.container();
  11356. const offset = pos.offset();
  11357. if (isText$a(container) && offset < container.data.length) {
  11358. return CaretPosition(container, offset + 1);
  11359. } else {
  11360. return pos;
  11361. }
  11362. };
  11363. const needsToBeNbspRight = (root, pos) => {
  11364. if (isInPre(pos)) {
  11365. return false;
  11366. } else {
  11367. return isAtEndOfBlock(root, pos) || isAfterBlock(root, pos) || isBeforeBr$1(root, pos) || hasSpaceAfter(root, pos) || isBeforeCefBlock(root, pos);
  11368. }
  11369. };
  11370. const needsToBeNbsp = (root, pos) => needsToBeNbspLeft(root, pos) || needsToBeNbspRight(root, leanRight(pos));
  11371. const isNbspAt = (text, offset) => isNbsp(text.charAt(offset));
  11372. const isWhiteSpaceAt = (text, offset) => isWhiteSpace(text.charAt(offset));
  11373. const hasNbsp = pos => {
  11374. const container = pos.container();
  11375. return isText$a(container) && contains$1(container.data, nbsp);
  11376. };
  11377. const normalizeNbspMiddle = text => {
  11378. const chars = text.split('');
  11379. return map$3(chars, (chr, i) => {
  11380. if (isNbsp(chr) && i > 0 && i < chars.length - 1 && isContent(chars[i - 1]) && isContent(chars[i + 1])) {
  11381. return ' ';
  11382. } else {
  11383. return chr;
  11384. }
  11385. }).join('');
  11386. };
  11387. const normalizeNbspAtStart = (root, node, makeNbsp) => {
  11388. const text = node.data;
  11389. const firstPos = CaretPosition(node, 0);
  11390. if (!makeNbsp && isNbspAt(text, 0) && !needsToBeNbsp(root, firstPos)) {
  11391. node.data = ' ' + text.slice(1);
  11392. return true;
  11393. } else if (makeNbsp && isWhiteSpaceAt(text, 0) && needsToBeNbspLeft(root, firstPos)) {
  11394. node.data = nbsp + text.slice(1);
  11395. return true;
  11396. } else {
  11397. return false;
  11398. }
  11399. };
  11400. const normalizeNbspInMiddleOfTextNode = node => {
  11401. const text = node.data;
  11402. const newText = normalizeNbspMiddle(text);
  11403. if (newText !== text) {
  11404. node.data = newText;
  11405. return true;
  11406. } else {
  11407. return false;
  11408. }
  11409. };
  11410. const normalizeNbspAtEnd = (root, node, makeNbsp) => {
  11411. const text = node.data;
  11412. const lastPos = CaretPosition(node, text.length - 1);
  11413. if (!makeNbsp && isNbspAt(text, text.length - 1) && !needsToBeNbsp(root, lastPos)) {
  11414. node.data = text.slice(0, -1) + ' ';
  11415. return true;
  11416. } else if (makeNbsp && isWhiteSpaceAt(text, text.length - 1) && needsToBeNbspRight(root, lastPos)) {
  11417. node.data = text.slice(0, -1) + nbsp;
  11418. return true;
  11419. } else {
  11420. return false;
  11421. }
  11422. };
  11423. const normalizeNbsps = (root, pos) => {
  11424. const container = pos.container();
  11425. if (!isText$a(container)) {
  11426. return Optional.none();
  11427. }
  11428. if (hasNbsp(pos)) {
  11429. const normalized = normalizeNbspAtStart(root, container, false) || normalizeNbspInMiddleOfTextNode(container) || normalizeNbspAtEnd(root, container, false);
  11430. return someIf(normalized, pos);
  11431. } else if (needsToBeNbsp(root, pos)) {
  11432. const normalized = normalizeNbspAtStart(root, container, true) || normalizeNbspAtEnd(root, container, true);
  11433. return someIf(normalized, pos);
  11434. } else {
  11435. return Optional.none();
  11436. }
  11437. };
  11438. const normalizeNbspsInEditor = editor => {
  11439. const root = SugarElement.fromDom(editor.getBody());
  11440. if (editor.selection.isCollapsed()) {
  11441. normalizeNbsps(root, CaretPosition.fromRangeStart(editor.selection.getRng())).each(pos => {
  11442. editor.selection.setRng(pos.toRange());
  11443. });
  11444. }
  11445. };
  11446. const normalize$1 = (node, offset, count) => {
  11447. if (count === 0) {
  11448. return;
  11449. }
  11450. const elm = SugarElement.fromDom(node);
  11451. const root = ancestor$4(elm, isBlock$2).getOr(elm);
  11452. const whitespace = node.data.slice(offset, offset + count);
  11453. const isEndOfContent = offset + count >= node.data.length && needsToBeNbspRight(root, CaretPosition(node, node.data.length));
  11454. const isStartOfContent = offset === 0 && needsToBeNbspLeft(root, CaretPosition(node, 0));
  11455. node.replaceData(offset, count, normalize$4(whitespace, 4, isStartOfContent, isEndOfContent));
  11456. };
  11457. const normalizeWhitespaceAfter = (node, offset) => {
  11458. const content = node.data.slice(offset);
  11459. const whitespaceCount = content.length - lTrim(content).length;
  11460. normalize$1(node, offset, whitespaceCount);
  11461. };
  11462. const normalizeWhitespaceBefore = (node, offset) => {
  11463. const content = node.data.slice(0, offset);
  11464. const whitespaceCount = content.length - rTrim(content).length;
  11465. normalize$1(node, offset - whitespaceCount, whitespaceCount);
  11466. };
  11467. const mergeTextNodes = (prevNode, nextNode, normalizeWhitespace, mergeToPrev = true) => {
  11468. const whitespaceOffset = rTrim(prevNode.data).length;
  11469. const newNode = mergeToPrev ? prevNode : nextNode;
  11470. const removeNode = mergeToPrev ? nextNode : prevNode;
  11471. if (mergeToPrev) {
  11472. newNode.appendData(removeNode.data);
  11473. } else {
  11474. newNode.insertData(0, removeNode.data);
  11475. }
  11476. remove$6(SugarElement.fromDom(removeNode));
  11477. if (normalizeWhitespace) {
  11478. normalizeWhitespaceAfter(newNode, whitespaceOffset);
  11479. }
  11480. return newNode;
  11481. };
  11482. const needsReposition = (pos, elm) => {
  11483. const container = pos.container();
  11484. const offset = pos.offset();
  11485. return !CaretPosition.isTextPosition(pos) && container === elm.parentNode && offset > CaretPosition.before(elm).offset();
  11486. };
  11487. const reposition = (elm, pos) => needsReposition(pos, elm) ? CaretPosition(pos.container(), pos.offset() - 1) : pos;
  11488. const beforeOrStartOf = node => isText$a(node) ? CaretPosition(node, 0) : CaretPosition.before(node);
  11489. const afterOrEndOf = node => isText$a(node) ? CaretPosition(node, node.data.length) : CaretPosition.after(node);
  11490. const getPreviousSiblingCaretPosition = elm => {
  11491. if (isCaretCandidate$3(elm.previousSibling)) {
  11492. return Optional.some(afterOrEndOf(elm.previousSibling));
  11493. } else {
  11494. return elm.previousSibling ? lastPositionIn(elm.previousSibling) : Optional.none();
  11495. }
  11496. };
  11497. const getNextSiblingCaretPosition = elm => {
  11498. if (isCaretCandidate$3(elm.nextSibling)) {
  11499. return Optional.some(beforeOrStartOf(elm.nextSibling));
  11500. } else {
  11501. return elm.nextSibling ? firstPositionIn(elm.nextSibling) : Optional.none();
  11502. }
  11503. };
  11504. const findCaretPositionBackwardsFromElm = (rootElement, elm) => {
  11505. return Optional.from(elm.previousSibling ? elm.previousSibling : elm.parentNode).bind(node => prevPosition(rootElement, CaretPosition.before(node))).orThunk(() => nextPosition(rootElement, CaretPosition.after(elm)));
  11506. };
  11507. const findCaretPositionForwardsFromElm = (rootElement, elm) => nextPosition(rootElement, CaretPosition.after(elm)).orThunk(() => prevPosition(rootElement, CaretPosition.before(elm)));
  11508. const findCaretPositionBackwards = (rootElement, elm) => getPreviousSiblingCaretPosition(elm).orThunk(() => getNextSiblingCaretPosition(elm)).orThunk(() => findCaretPositionBackwardsFromElm(rootElement, elm));
  11509. const findCaretPositionForward = (rootElement, elm) => getNextSiblingCaretPosition(elm).orThunk(() => getPreviousSiblingCaretPosition(elm)).orThunk(() => findCaretPositionForwardsFromElm(rootElement, elm));
  11510. const findCaretPosition = (forward, rootElement, elm) => forward ? findCaretPositionForward(rootElement, elm) : findCaretPositionBackwards(rootElement, elm);
  11511. const findCaretPosOutsideElmAfterDelete = (forward, rootElement, elm) => findCaretPosition(forward, rootElement, elm).map(curry(reposition, elm));
  11512. const setSelection$1 = (editor, forward, pos) => {
  11513. pos.fold(() => {
  11514. editor.focus();
  11515. }, pos => {
  11516. editor.selection.setRng(pos.toRange(), forward);
  11517. });
  11518. };
  11519. const eqRawNode = rawNode => elm => elm.dom === rawNode;
  11520. const isBlock = (editor, elm) => elm && has$2(editor.schema.getBlockElements(), name(elm));
  11521. const paddEmptyBlock = elm => {
  11522. if (isEmpty$2(elm)) {
  11523. const br = SugarElement.fromHtml('<br data-mce-bogus="1">');
  11524. empty(elm);
  11525. append$1(elm, br);
  11526. return Optional.some(CaretPosition.before(br.dom));
  11527. } else {
  11528. return Optional.none();
  11529. }
  11530. };
  11531. const deleteNormalized = (elm, afterDeletePosOpt, normalizeWhitespace) => {
  11532. const prevTextOpt = prevSibling(elm).filter(isText$b);
  11533. const nextTextOpt = nextSibling(elm).filter(isText$b);
  11534. remove$6(elm);
  11535. return lift3(prevTextOpt, nextTextOpt, afterDeletePosOpt, (prev, next, pos) => {
  11536. const prevNode = prev.dom, nextNode = next.dom;
  11537. const offset = prevNode.data.length;
  11538. mergeTextNodes(prevNode, nextNode, normalizeWhitespace);
  11539. return pos.container() === nextNode ? CaretPosition(prevNode, offset) : pos;
  11540. }).orThunk(() => {
  11541. if (normalizeWhitespace) {
  11542. prevTextOpt.each(elm => normalizeWhitespaceBefore(elm.dom, elm.dom.length));
  11543. nextTextOpt.each(elm => normalizeWhitespaceAfter(elm.dom, 0));
  11544. }
  11545. return afterDeletePosOpt;
  11546. });
  11547. };
  11548. const isInlineElement = (editor, element) => has$2(editor.schema.getTextInlineElements(), name(element));
  11549. const deleteElement$2 = (editor, forward, elm, moveCaret = true) => {
  11550. const afterDeletePos = findCaretPosOutsideElmAfterDelete(forward, editor.getBody(), elm.dom);
  11551. const parentBlock = ancestor$4(elm, curry(isBlock, editor), eqRawNode(editor.getBody()));
  11552. const normalizedAfterDeletePos = deleteNormalized(elm, afterDeletePos, isInlineElement(editor, elm));
  11553. if (editor.dom.isEmpty(editor.getBody())) {
  11554. editor.setContent('');
  11555. editor.selection.setCursorLocation();
  11556. } else {
  11557. parentBlock.bind(paddEmptyBlock).fold(() => {
  11558. if (moveCaret) {
  11559. setSelection$1(editor, forward, normalizedAfterDeletePos);
  11560. }
  11561. }, paddPos => {
  11562. if (moveCaret) {
  11563. setSelection$1(editor, forward, Optional.some(paddPos));
  11564. }
  11565. });
  11566. }
  11567. };
  11568. const strongRtl = /[\u0591-\u07FF\uFB1D-\uFDFF\uFE70-\uFEFC]/;
  11569. const hasStrongRtl = text => strongRtl.test(text);
  11570. const isInlineTarget = (editor, elm) => is$1(SugarElement.fromDom(elm), getInlineBoundarySelector(editor)) && !isTransparentBlock(editor.schema, elm) && editor.dom.isEditable(elm);
  11571. const isRtl = element => {
  11572. var _a;
  11573. return DOMUtils.DOM.getStyle(element, 'direction', true) === 'rtl' || hasStrongRtl((_a = element.textContent) !== null && _a !== void 0 ? _a : '');
  11574. };
  11575. const findInlineParents = (isInlineTarget, rootNode, pos) => filter$5(DOMUtils.DOM.getParents(pos.container(), '*', rootNode), isInlineTarget);
  11576. const findRootInline = (isInlineTarget, rootNode, pos) => {
  11577. const parents = findInlineParents(isInlineTarget, rootNode, pos);
  11578. return Optional.from(parents[parents.length - 1]);
  11579. };
  11580. const hasSameParentBlock = (rootNode, node1, node2) => {
  11581. const block1 = getParentBlock$3(node1, rootNode);
  11582. const block2 = getParentBlock$3(node2, rootNode);
  11583. return isNonNullable(block1) && block1 === block2;
  11584. };
  11585. const isAtZwsp = pos => isBeforeInline(pos) || isAfterInline(pos);
  11586. const normalizePosition = (forward, pos) => {
  11587. const container = pos.container(), offset = pos.offset();
  11588. if (forward) {
  11589. if (isCaretContainerInline(container)) {
  11590. if (isText$a(container.nextSibling)) {
  11591. return CaretPosition(container.nextSibling, 0);
  11592. } else {
  11593. return CaretPosition.after(container);
  11594. }
  11595. } else {
  11596. return isBeforeInline(pos) ? CaretPosition(container, offset + 1) : pos;
  11597. }
  11598. } else {
  11599. if (isCaretContainerInline(container)) {
  11600. if (isText$a(container.previousSibling)) {
  11601. return CaretPosition(container.previousSibling, container.previousSibling.data.length);
  11602. } else {
  11603. return CaretPosition.before(container);
  11604. }
  11605. } else {
  11606. return isAfterInline(pos) ? CaretPosition(container, offset - 1) : pos;
  11607. }
  11608. }
  11609. };
  11610. const normalizeForwards = curry(normalizePosition, true);
  11611. const normalizeBackwards = curry(normalizePosition, false);
  11612. const execCommandIgnoreInputEvents = (editor, command) => {
  11613. const inputBlocker = e => e.stopImmediatePropagation();
  11614. editor.on('beforeinput input', inputBlocker, true);
  11615. editor.getDoc().execCommand(command);
  11616. editor.off('beforeinput input', inputBlocker);
  11617. };
  11618. const execEditorDeleteCommand = editor => {
  11619. editor.execCommand('delete');
  11620. };
  11621. const execNativeDeleteCommand = editor => execCommandIgnoreInputEvents(editor, 'Delete');
  11622. const execNativeForwardDeleteCommand = editor => execCommandIgnoreInputEvents(editor, 'ForwardDelete');
  11623. const isBeforeRoot = rootNode => elm => is$2(parent(elm), rootNode, eq);
  11624. const isTextBlockOrListItem = element => isTextBlock$2(element) || isListItem$1(element);
  11625. const getParentBlock$2 = (rootNode, elm) => {
  11626. if (contains(rootNode, elm)) {
  11627. return closest$4(elm, isTextBlockOrListItem, isBeforeRoot(rootNode));
  11628. } else {
  11629. return Optional.none();
  11630. }
  11631. };
  11632. const paddEmptyBody = (editor, moveSelection = true) => {
  11633. if (editor.dom.isEmpty(editor.getBody())) {
  11634. editor.setContent('', { no_selection: !moveSelection });
  11635. }
  11636. };
  11637. const willDeleteLastPositionInElement = (forward, fromPos, elm) => lift2(firstPositionIn(elm), lastPositionIn(elm), (firstPos, lastPos) => {
  11638. const normalizedFirstPos = normalizePosition(true, firstPos);
  11639. const normalizedLastPos = normalizePosition(false, lastPos);
  11640. const normalizedFromPos = normalizePosition(false, fromPos);
  11641. if (forward) {
  11642. return nextPosition(elm, normalizedFromPos).exists(nextPos => nextPos.isEqual(normalizedLastPos) && fromPos.isEqual(normalizedFirstPos));
  11643. } else {
  11644. return prevPosition(elm, normalizedFromPos).exists(prevPos => prevPos.isEqual(normalizedFirstPos) && fromPos.isEqual(normalizedLastPos));
  11645. }
  11646. }).getOr(true);
  11647. const freefallRtl = root => {
  11648. const child = isComment$1(root) ? prevSibling(root) : lastChild(root);
  11649. return child.bind(freefallRtl).orThunk(() => Optional.some(root));
  11650. };
  11651. const deleteRangeContents = (editor, rng, root, moveSelection = true) => {
  11652. var _a;
  11653. rng.deleteContents();
  11654. const lastNode = freefallRtl(root).getOr(root);
  11655. const lastBlock = SugarElement.fromDom((_a = editor.dom.getParent(lastNode.dom, editor.dom.isBlock)) !== null && _a !== void 0 ? _a : root.dom);
  11656. if (lastBlock.dom === editor.getBody()) {
  11657. paddEmptyBody(editor, moveSelection);
  11658. } else if (isEmpty$2(lastBlock)) {
  11659. fillWithPaddingBr(lastBlock);
  11660. if (moveSelection) {
  11661. editor.selection.setCursorLocation(lastBlock.dom, 0);
  11662. }
  11663. }
  11664. if (!eq(root, lastBlock)) {
  11665. const additionalCleanupNodes = is$2(parent(lastBlock), root) ? [] : siblings(lastBlock);
  11666. each$e(additionalCleanupNodes.concat(children$1(root)), node => {
  11667. if (!eq(node, lastBlock) && !contains(node, lastBlock) && isEmpty$2(node)) {
  11668. remove$6(node);
  11669. }
  11670. });
  11671. }
  11672. };
  11673. const isRootFromElement = root => cur => eq(root, cur);
  11674. const getTableCells = table => descendants(table, 'td,th');
  11675. const getTableDetailsFromRange = (rng, isRoot) => {
  11676. const getTable = node => getClosestTable(SugarElement.fromDom(node), isRoot);
  11677. const startTable = getTable(rng.startContainer);
  11678. const endTable = getTable(rng.endContainer);
  11679. const isStartInTable = startTable.isSome();
  11680. const isEndInTable = endTable.isSome();
  11681. const isSameTable = lift2(startTable, endTable, eq).getOr(false);
  11682. const isMultiTable = !isSameTable && isStartInTable && isEndInTable;
  11683. return {
  11684. startTable,
  11685. endTable,
  11686. isStartInTable,
  11687. isEndInTable,
  11688. isSameTable,
  11689. isMultiTable
  11690. };
  11691. };
  11692. const tableCellRng = (start, end) => ({
  11693. start,
  11694. end
  11695. });
  11696. const tableSelection = (rng, table, cells) => ({
  11697. rng,
  11698. table,
  11699. cells
  11700. });
  11701. const deleteAction = Adt.generate([
  11702. {
  11703. singleCellTable: [
  11704. 'rng',
  11705. 'cell'
  11706. ]
  11707. },
  11708. { fullTable: ['table'] },
  11709. {
  11710. partialTable: [
  11711. 'cells',
  11712. 'outsideDetails'
  11713. ]
  11714. },
  11715. {
  11716. multiTable: [
  11717. 'startTableCells',
  11718. 'endTableCells',
  11719. 'betweenRng'
  11720. ]
  11721. }
  11722. ]);
  11723. const getClosestCell$1 = (container, isRoot) => closest$3(SugarElement.fromDom(container), 'td,th', isRoot);
  11724. const isExpandedCellRng = cellRng => !eq(cellRng.start, cellRng.end);
  11725. const getTableFromCellRng = (cellRng, isRoot) => getClosestTable(cellRng.start, isRoot).bind(startParentTable => getClosestTable(cellRng.end, isRoot).bind(endParentTable => someIf(eq(startParentTable, endParentTable), startParentTable)));
  11726. const isSingleCellTable = (cellRng, isRoot) => !isExpandedCellRng(cellRng) && getTableFromCellRng(cellRng, isRoot).exists(table => {
  11727. const rows = table.dom.rows;
  11728. return rows.length === 1 && rows[0].cells.length === 1;
  11729. });
  11730. const getCellRng = (rng, isRoot) => {
  11731. const startCell = getClosestCell$1(rng.startContainer, isRoot);
  11732. const endCell = getClosestCell$1(rng.endContainer, isRoot);
  11733. return lift2(startCell, endCell, tableCellRng);
  11734. };
  11735. const getCellRangeFromStartTable = isRoot => startCell => getClosestTable(startCell, isRoot).bind(table => last$3(getTableCells(table)).map(endCell => tableCellRng(startCell, endCell)));
  11736. const getCellRangeFromEndTable = isRoot => endCell => getClosestTable(endCell, isRoot).bind(table => head(getTableCells(table)).map(startCell => tableCellRng(startCell, endCell)));
  11737. const getTableSelectionFromCellRng = isRoot => cellRng => getTableFromCellRng(cellRng, isRoot).map(table => tableSelection(cellRng, table, getTableCells(table)));
  11738. const getTableSelections = (cellRng, selectionDetails, rng, isRoot) => {
  11739. if (rng.collapsed || !cellRng.forall(isExpandedCellRng)) {
  11740. return Optional.none();
  11741. } else if (selectionDetails.isSameTable) {
  11742. const sameTableSelection = cellRng.bind(getTableSelectionFromCellRng(isRoot));
  11743. return Optional.some({
  11744. start: sameTableSelection,
  11745. end: sameTableSelection
  11746. });
  11747. } else {
  11748. const startCell = getClosestCell$1(rng.startContainer, isRoot);
  11749. const endCell = getClosestCell$1(rng.endContainer, isRoot);
  11750. const startTableSelection = startCell.bind(getCellRangeFromStartTable(isRoot)).bind(getTableSelectionFromCellRng(isRoot));
  11751. const endTableSelection = endCell.bind(getCellRangeFromEndTable(isRoot)).bind(getTableSelectionFromCellRng(isRoot));
  11752. return Optional.some({
  11753. start: startTableSelection,
  11754. end: endTableSelection
  11755. });
  11756. }
  11757. };
  11758. const getCellIndex = (cells, cell) => findIndex$2(cells, x => eq(x, cell));
  11759. const getSelectedCells = tableSelection => lift2(getCellIndex(tableSelection.cells, tableSelection.rng.start), getCellIndex(tableSelection.cells, tableSelection.rng.end), (startIndex, endIndex) => tableSelection.cells.slice(startIndex, endIndex + 1));
  11760. const isSingleCellTableContentSelected = (optCellRng, rng, isRoot) => optCellRng.exists(cellRng => isSingleCellTable(cellRng, isRoot) && hasAllContentsSelected(cellRng.start, rng));
  11761. const unselectCells = (rng, selectionDetails) => {
  11762. const {startTable, endTable} = selectionDetails;
  11763. const otherContentRng = rng.cloneRange();
  11764. startTable.each(table => otherContentRng.setStartAfter(table.dom));
  11765. endTable.each(table => otherContentRng.setEndBefore(table.dom));
  11766. return otherContentRng;
  11767. };
  11768. const handleSingleTable = (cellRng, selectionDetails, rng, isRoot) => getTableSelections(cellRng, selectionDetails, rng, isRoot).bind(({start, end}) => start.or(end)).bind(tableSelection => {
  11769. const {isSameTable} = selectionDetails;
  11770. const selectedCells = getSelectedCells(tableSelection).getOr([]);
  11771. if (isSameTable && tableSelection.cells.length === selectedCells.length) {
  11772. return Optional.some(deleteAction.fullTable(tableSelection.table));
  11773. } else if (selectedCells.length > 0) {
  11774. if (isSameTable) {
  11775. return Optional.some(deleteAction.partialTable(selectedCells, Optional.none()));
  11776. } else {
  11777. const otherContentRng = unselectCells(rng, selectionDetails);
  11778. return Optional.some(deleteAction.partialTable(selectedCells, Optional.some({
  11779. ...selectionDetails,
  11780. rng: otherContentRng
  11781. })));
  11782. }
  11783. } else {
  11784. return Optional.none();
  11785. }
  11786. });
  11787. const handleMultiTable = (cellRng, selectionDetails, rng, isRoot) => getTableSelections(cellRng, selectionDetails, rng, isRoot).bind(({start, end}) => {
  11788. const startTableSelectedCells = start.bind(getSelectedCells).getOr([]);
  11789. const endTableSelectedCells = end.bind(getSelectedCells).getOr([]);
  11790. if (startTableSelectedCells.length > 0 && endTableSelectedCells.length > 0) {
  11791. const otherContentRng = unselectCells(rng, selectionDetails);
  11792. return Optional.some(deleteAction.multiTable(startTableSelectedCells, endTableSelectedCells, otherContentRng));
  11793. } else {
  11794. return Optional.none();
  11795. }
  11796. });
  11797. const getActionFromRange = (root, rng) => {
  11798. const isRoot = isRootFromElement(root);
  11799. const optCellRng = getCellRng(rng, isRoot);
  11800. const selectionDetails = getTableDetailsFromRange(rng, isRoot);
  11801. if (isSingleCellTableContentSelected(optCellRng, rng, isRoot)) {
  11802. return optCellRng.map(cellRng => deleteAction.singleCellTable(rng, cellRng.start));
  11803. } else if (selectionDetails.isMultiTable) {
  11804. return handleMultiTable(optCellRng, selectionDetails, rng, isRoot);
  11805. } else {
  11806. return handleSingleTable(optCellRng, selectionDetails, rng, isRoot);
  11807. }
  11808. };
  11809. const cleanCells = cells => each$e(cells, cell => {
  11810. remove$b(cell, 'contenteditable');
  11811. fillWithPaddingBr(cell);
  11812. });
  11813. const getOutsideBlock = (editor, container) => Optional.from(editor.dom.getParent(container, editor.dom.isBlock)).map(SugarElement.fromDom);
  11814. const handleEmptyBlock = (editor, startInTable, emptyBlock) => {
  11815. emptyBlock.each(block => {
  11816. if (startInTable) {
  11817. remove$6(block);
  11818. } else {
  11819. fillWithPaddingBr(block);
  11820. editor.selection.setCursorLocation(block.dom, 0);
  11821. }
  11822. });
  11823. };
  11824. const deleteContentInsideCell = (editor, cell, rng, isFirstCellInSelection) => {
  11825. const insideTableRng = rng.cloneRange();
  11826. if (isFirstCellInSelection) {
  11827. insideTableRng.setStart(rng.startContainer, rng.startOffset);
  11828. insideTableRng.setEndAfter(cell.dom.lastChild);
  11829. } else {
  11830. insideTableRng.setStartBefore(cell.dom.firstChild);
  11831. insideTableRng.setEnd(rng.endContainer, rng.endOffset);
  11832. }
  11833. deleteCellContents(editor, insideTableRng, cell, false).each(action => action());
  11834. };
  11835. const collapseAndRestoreCellSelection = editor => {
  11836. const selectedCells = getCellsFromEditor(editor);
  11837. const selectedNode = SugarElement.fromDom(editor.selection.getNode());
  11838. if (isTableCell$3(selectedNode.dom) && isEmpty$2(selectedNode)) {
  11839. editor.selection.setCursorLocation(selectedNode.dom, 0);
  11840. } else {
  11841. editor.selection.collapse(true);
  11842. }
  11843. if (selectedCells.length > 1 && exists(selectedCells, cell => eq(cell, selectedNode))) {
  11844. set$3(selectedNode, 'data-mce-selected', '1');
  11845. }
  11846. };
  11847. const emptySingleTableCells = (editor, cells, outsideDetails) => Optional.some(() => {
  11848. const editorRng = editor.selection.getRng();
  11849. const cellsToClean = outsideDetails.bind(({rng, isStartInTable}) => {
  11850. const outsideBlock = getOutsideBlock(editor, isStartInTable ? rng.endContainer : rng.startContainer);
  11851. rng.deleteContents();
  11852. handleEmptyBlock(editor, isStartInTable, outsideBlock.filter(isEmpty$2));
  11853. const endPointCell = isStartInTable ? cells[0] : cells[cells.length - 1];
  11854. deleteContentInsideCell(editor, endPointCell, editorRng, isStartInTable);
  11855. if (!isEmpty$2(endPointCell)) {
  11856. return Optional.some(isStartInTable ? cells.slice(1) : cells.slice(0, -1));
  11857. } else {
  11858. return Optional.none();
  11859. }
  11860. }).getOr(cells);
  11861. cleanCells(cellsToClean);
  11862. collapseAndRestoreCellSelection(editor);
  11863. });
  11864. const emptyMultiTableCells = (editor, startTableCells, endTableCells, betweenRng) => Optional.some(() => {
  11865. const rng = editor.selection.getRng();
  11866. const startCell = startTableCells[0];
  11867. const endCell = endTableCells[endTableCells.length - 1];
  11868. deleteContentInsideCell(editor, startCell, rng, true);
  11869. deleteContentInsideCell(editor, endCell, rng, false);
  11870. const startTableCellsToClean = isEmpty$2(startCell) ? startTableCells : startTableCells.slice(1);
  11871. const endTableCellsToClean = isEmpty$2(endCell) ? endTableCells : endTableCells.slice(0, -1);
  11872. cleanCells(startTableCellsToClean.concat(endTableCellsToClean));
  11873. betweenRng.deleteContents();
  11874. collapseAndRestoreCellSelection(editor);
  11875. });
  11876. const deleteCellContents = (editor, rng, cell, moveSelection = true) => Optional.some(() => {
  11877. deleteRangeContents(editor, rng, cell, moveSelection);
  11878. });
  11879. const deleteTableElement = (editor, table) => Optional.some(() => deleteElement$2(editor, false, table));
  11880. const deleteCellRange = (editor, rootElm, rng) => getActionFromRange(rootElm, rng).bind(action => action.fold(curry(deleteCellContents, editor), curry(deleteTableElement, editor), curry(emptySingleTableCells, editor), curry(emptyMultiTableCells, editor)));
  11881. const deleteCaptionRange = (editor, caption) => emptyElement(editor, caption);
  11882. const deleteTableRange = (editor, rootElm, rng, startElm) => getParentCaption(rootElm, startElm).fold(() => deleteCellRange(editor, rootElm, rng), caption => deleteCaptionRange(editor, caption));
  11883. const deleteRange$3 = (editor, startElm, selectedCells) => {
  11884. const rootNode = SugarElement.fromDom(editor.getBody());
  11885. const rng = editor.selection.getRng();
  11886. return selectedCells.length !== 0 ? emptySingleTableCells(editor, selectedCells, Optional.none()) : deleteTableRange(editor, rootNode, rng, startElm);
  11887. };
  11888. const getParentCell = (rootElm, elm) => find$2(parentsAndSelf(elm, rootElm), isTableCell$2);
  11889. const getParentCaption = (rootElm, elm) => find$2(parentsAndSelf(elm, rootElm), isTag('caption'));
  11890. 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)));
  11891. const emptyElement = (editor, elm) => Optional.some(() => {
  11892. fillWithPaddingBr(elm);
  11893. editor.selection.setCursorLocation(elm.dom, 0);
  11894. });
  11895. 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);
  11896. const emptyCaretCaption = (editor, elm) => emptyElement(editor, elm);
  11897. const validateCaretCaption = (rootElm, fromCaption, to) => getParentCaption(rootElm, SugarElement.fromDom(to.getNode())).fold(() => Optional.some(noop), toCaption => someIf(!eq(toCaption, fromCaption), noop));
  11898. 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));
  11899. const deleteCaretCells = (editor, forward, rootElm, startElm) => {
  11900. const from = CaretPosition.fromRangeStart(editor.selection.getRng());
  11901. return getParentCell(rootElm, startElm).bind(fromCell => isEmpty$2(fromCell) ? emptyElement(editor, fromCell) : deleteBetweenCells(editor, rootElm, forward, fromCell, from));
  11902. };
  11903. const deleteCaretCaption = (editor, forward, rootElm, fromCaption) => {
  11904. const from = CaretPosition.fromRangeStart(editor.selection.getRng());
  11905. return isEmpty$2(fromCaption) ? emptyElement(editor, fromCaption) : deleteCaretInsideCaption(editor, rootElm, forward, fromCaption, from);
  11906. };
  11907. const isNearTable = (forward, pos) => forward ? isBeforeTable(pos) : isAfterTable(pos);
  11908. const isBeforeOrAfterTable = (editor, forward) => {
  11909. const fromPos = CaretPosition.fromRangeStart(editor.selection.getRng());
  11910. return isNearTable(forward, fromPos) || fromPosition(forward, editor.getBody(), fromPos).exists(pos => isNearTable(forward, pos));
  11911. };
  11912. const deleteCaret$3 = (editor, forward, startElm) => {
  11913. const rootElm = SugarElement.fromDom(editor.getBody());
  11914. return getParentCaption(rootElm, startElm).fold(() => deleteCaretCells(editor, forward, rootElm, startElm).orThunk(() => someIf(isBeforeOrAfterTable(editor, forward), noop)), fromCaption => deleteCaretCaption(editor, forward, rootElm, fromCaption));
  11915. };
  11916. const backspaceDelete$9 = (editor, forward) => {
  11917. const startElm = SugarElement.fromDom(editor.selection.getStart(true));
  11918. const cells = getCellsFromEditor(editor);
  11919. return editor.selection.isCollapsed() && cells.length === 0 ? deleteCaret$3(editor, forward, startElm) : deleteRange$3(editor, startElm, cells);
  11920. };
  11921. const getContentEditableRoot$1 = (root, node) => {
  11922. let tempNode = node;
  11923. while (tempNode && tempNode !== root) {
  11924. if (isContentEditableTrue$3(tempNode) || isContentEditableFalse$b(tempNode)) {
  11925. return tempNode;
  11926. }
  11927. tempNode = tempNode.parentNode;
  11928. }
  11929. return null;
  11930. };
  11931. const internalAttributesPrefixes = [
  11932. 'data-ephox-',
  11933. 'data-mce-',
  11934. 'data-alloy-',
  11935. 'data-snooker-',
  11936. '_'
  11937. ];
  11938. const each$9 = Tools.each;
  11939. const ElementUtils = editor => {
  11940. const dom = editor.dom;
  11941. const internalAttributes = new Set(editor.serializer.getTempAttrs());
  11942. const compare = (node1, node2) => {
  11943. if (node1.nodeName !== node2.nodeName || node1.nodeType !== node2.nodeType) {
  11944. return false;
  11945. }
  11946. const getAttribs = node => {
  11947. const attribs = {};
  11948. each$9(dom.getAttribs(node), attr => {
  11949. const name = attr.nodeName.toLowerCase();
  11950. if (name !== 'style' && !isAttributeInternal(name)) {
  11951. attribs[name] = dom.getAttrib(node, name);
  11952. }
  11953. });
  11954. return attribs;
  11955. };
  11956. const compareObjects = (obj1, obj2) => {
  11957. for (const name in obj1) {
  11958. if (has$2(obj1, name)) {
  11959. const value = obj2[name];
  11960. if (isUndefined(value)) {
  11961. return false;
  11962. }
  11963. if (obj1[name] !== value) {
  11964. return false;
  11965. }
  11966. delete obj2[name];
  11967. }
  11968. }
  11969. for (const name in obj2) {
  11970. if (has$2(obj2, name)) {
  11971. return false;
  11972. }
  11973. }
  11974. return true;
  11975. };
  11976. if (isElement$6(node1) && isElement$6(node2)) {
  11977. if (!compareObjects(getAttribs(node1), getAttribs(node2))) {
  11978. return false;
  11979. }
  11980. if (!compareObjects(dom.parseStyle(dom.getAttrib(node1, 'style')), dom.parseStyle(dom.getAttrib(node2, 'style')))) {
  11981. return false;
  11982. }
  11983. }
  11984. return !isBookmarkNode$1(node1) && !isBookmarkNode$1(node2);
  11985. };
  11986. const isAttributeInternal = attributeName => exists(internalAttributesPrefixes, value => startsWith(attributeName, value)) || internalAttributes.has(attributeName);
  11987. return {
  11988. compare,
  11989. isAttributeInternal
  11990. };
  11991. };
  11992. const traverse = (root, fn) => {
  11993. let node = root;
  11994. while (node = node.walk()) {
  11995. fn(node);
  11996. }
  11997. };
  11998. const matchNode$1 = (nodeFilters, attributeFilters, node, matches) => {
  11999. const name = node.name;
  12000. for (let ni = 0, nl = nodeFilters.length; ni < nl; ni++) {
  12001. const filter = nodeFilters[ni];
  12002. if (filter.name === name) {
  12003. const match = matches.nodes[name];
  12004. if (match) {
  12005. match.nodes.push(node);
  12006. } else {
  12007. matches.nodes[name] = {
  12008. filter,
  12009. nodes: [node]
  12010. };
  12011. }
  12012. }
  12013. }
  12014. if (node.attributes) {
  12015. for (let ai = 0, al = attributeFilters.length; ai < al; ai++) {
  12016. const filter = attributeFilters[ai];
  12017. const attrName = filter.name;
  12018. if (attrName in node.attributes.map) {
  12019. const match = matches.attributes[attrName];
  12020. if (match) {
  12021. match.nodes.push(node);
  12022. } else {
  12023. matches.attributes[attrName] = {
  12024. filter,
  12025. nodes: [node]
  12026. };
  12027. }
  12028. }
  12029. }
  12030. }
  12031. };
  12032. const findMatchingNodes = (nodeFilters, attributeFilters, node) => {
  12033. const matches = {
  12034. nodes: {},
  12035. attributes: {}
  12036. };
  12037. if (node.firstChild) {
  12038. traverse(node, childNode => {
  12039. matchNode$1(nodeFilters, attributeFilters, childNode, matches);
  12040. });
  12041. }
  12042. return matches;
  12043. };
  12044. const runFilters = (matches, args) => {
  12045. const run = (matchRecord, filteringAttributes) => {
  12046. each$d(matchRecord, match => {
  12047. const nodes = from(match.nodes);
  12048. each$e(match.filter.callbacks, callback => {
  12049. for (let i = nodes.length - 1; i >= 0; i--) {
  12050. const node = nodes[i];
  12051. const valueMatches = filteringAttributes ? node.attr(match.filter.name) !== undefined : node.name === match.filter.name;
  12052. if (!valueMatches || isNullable(node.parent)) {
  12053. nodes.splice(i, 1);
  12054. }
  12055. }
  12056. if (nodes.length > 0) {
  12057. callback(nodes, match.filter.name, args);
  12058. }
  12059. });
  12060. });
  12061. };
  12062. run(matches.nodes, false);
  12063. run(matches.attributes, true);
  12064. };
  12065. const filter$2 = (nodeFilters, attributeFilters, node, args = {}) => {
  12066. const matches = findMatchingNodes(nodeFilters, attributeFilters, node);
  12067. runFilters(matches, args);
  12068. };
  12069. const paddEmptyNode = (args, isBlock, node) => {
  12070. if (args.insert && isBlock(node)) {
  12071. const astNode = new AstNode('br', 1);
  12072. astNode.attr('data-mce-bogus', '1');
  12073. node.empty().append(astNode);
  12074. } else {
  12075. node.empty().append(new AstNode('#text', 3)).value = nbsp;
  12076. }
  12077. };
  12078. const isPaddedWithNbsp = node => {
  12079. var _a;
  12080. return hasOnlyChild(node, '#text') && ((_a = node === null || node === void 0 ? void 0 : node.firstChild) === null || _a === void 0 ? void 0 : _a.value) === nbsp;
  12081. };
  12082. const hasOnlyChild = (node, name) => {
  12083. const firstChild = node === null || node === void 0 ? void 0 : node.firstChild;
  12084. return isNonNullable(firstChild) && firstChild === node.lastChild && firstChild.name === name;
  12085. };
  12086. const isPadded = (schema, node) => {
  12087. const rule = schema.getElementRule(node.name);
  12088. return (rule === null || rule === void 0 ? void 0 : rule.paddEmpty) === true;
  12089. };
  12090. const isEmpty = (schema, nonEmptyElements, whitespaceElements, node) => node.isEmpty(nonEmptyElements, whitespaceElements, node => isPadded(schema, node));
  12091. const isLineBreakNode = (node, isBlock) => isNonNullable(node) && (isBlock(node) || node.name === 'br');
  12092. const findClosestEditingHost = scope => {
  12093. let editableNode;
  12094. for (let node = scope; node; node = node.parent) {
  12095. const contentEditable = node.attr('contenteditable');
  12096. if (contentEditable === 'false') {
  12097. break;
  12098. } else if (contentEditable === 'true') {
  12099. editableNode = node;
  12100. }
  12101. }
  12102. return Optional.from(editableNode);
  12103. };
  12104. const removeOrUnwrapInvalidNode = (node, schema, originalNodeParent = node.parent) => {
  12105. if (schema.getSpecialElements()[node.name]) {
  12106. node.empty().remove();
  12107. } else {
  12108. const children = node.children();
  12109. for (const childNode of children) {
  12110. if (originalNodeParent && !schema.isValidChild(originalNodeParent.name, childNode.name)) {
  12111. removeOrUnwrapInvalidNode(childNode, schema, originalNodeParent);
  12112. }
  12113. }
  12114. node.unwrap();
  12115. }
  12116. };
  12117. const cleanInvalidNodes = (nodes, schema, rootNode, onCreate = noop) => {
  12118. const textBlockElements = schema.getTextBlockElements();
  12119. const nonEmptyElements = schema.getNonEmptyElements();
  12120. const whitespaceElements = schema.getWhitespaceElements();
  12121. const nonSplittableElements = Tools.makeMap('tr,td,th,tbody,thead,tfoot,table');
  12122. const fixed = new Set();
  12123. const isSplittableElement = node => node !== rootNode && !nonSplittableElements[node.name];
  12124. for (let ni = 0; ni < nodes.length; ni++) {
  12125. const node = nodes[ni];
  12126. let parent;
  12127. let newParent;
  12128. let tempNode;
  12129. if (!node.parent || fixed.has(node)) {
  12130. continue;
  12131. }
  12132. if (textBlockElements[node.name] && node.parent.name === 'li') {
  12133. let sibling = node.next;
  12134. while (sibling) {
  12135. if (textBlockElements[sibling.name]) {
  12136. sibling.name = 'li';
  12137. fixed.add(sibling);
  12138. node.parent.insert(sibling, node.parent);
  12139. } else {
  12140. break;
  12141. }
  12142. sibling = sibling.next;
  12143. }
  12144. node.unwrap();
  12145. continue;
  12146. }
  12147. const parents = [node];
  12148. for (parent = node.parent; parent && !schema.isValidChild(parent.name, node.name) && isSplittableElement(parent); parent = parent.parent) {
  12149. parents.push(parent);
  12150. }
  12151. if (parent && parents.length > 1) {
  12152. if (schema.isValidChild(parent.name, node.name)) {
  12153. parents.reverse();
  12154. newParent = parents[0].clone();
  12155. onCreate(newParent);
  12156. let currentNode = newParent;
  12157. for (let i = 0; i < parents.length - 1; i++) {
  12158. if (schema.isValidChild(currentNode.name, parents[i].name) && i > 0) {
  12159. tempNode = parents[i].clone();
  12160. onCreate(tempNode);
  12161. currentNode.append(tempNode);
  12162. } else {
  12163. tempNode = currentNode;
  12164. }
  12165. for (let childNode = parents[i].firstChild; childNode && childNode !== parents[i + 1];) {
  12166. const nextNode = childNode.next;
  12167. tempNode.append(childNode);
  12168. childNode = nextNode;
  12169. }
  12170. currentNode = tempNode;
  12171. }
  12172. if (!isEmpty(schema, nonEmptyElements, whitespaceElements, newParent)) {
  12173. parent.insert(newParent, parents[0], true);
  12174. parent.insert(node, newParent);
  12175. } else {
  12176. parent.insert(node, parents[0], true);
  12177. }
  12178. parent = parents[0];
  12179. if (isEmpty(schema, nonEmptyElements, whitespaceElements, parent) || hasOnlyChild(parent, 'br')) {
  12180. parent.empty().remove();
  12181. }
  12182. } else {
  12183. removeOrUnwrapInvalidNode(node, schema);
  12184. }
  12185. } else if (node.parent) {
  12186. if (node.name === 'li') {
  12187. let sibling = node.prev;
  12188. if (sibling && (sibling.name === 'ul' || sibling.name === 'ol')) {
  12189. sibling.append(node);
  12190. continue;
  12191. }
  12192. sibling = node.next;
  12193. if (sibling && (sibling.name === 'ul' || sibling.name === 'ol') && sibling.firstChild) {
  12194. sibling.insert(node, sibling.firstChild, true);
  12195. continue;
  12196. }
  12197. const wrapper = new AstNode('ul', 1);
  12198. onCreate(wrapper);
  12199. node.wrap(wrapper);
  12200. continue;
  12201. }
  12202. if (schema.isValidChild(node.parent.name, 'div') && schema.isValidChild('div', node.name)) {
  12203. const wrapper = new AstNode('div', 1);
  12204. onCreate(wrapper);
  12205. node.wrap(wrapper);
  12206. } else {
  12207. removeOrUnwrapInvalidNode(node, schema);
  12208. }
  12209. }
  12210. }
  12211. };
  12212. const hasClosest = (node, parentName) => {
  12213. let tempNode = node;
  12214. while (tempNode) {
  12215. if (tempNode.name === parentName) {
  12216. return true;
  12217. }
  12218. tempNode = tempNode.parent;
  12219. }
  12220. return false;
  12221. };
  12222. const isInvalid = (schema, node, parent = node.parent) => {
  12223. if (parent && schema.children[node.name] && !schema.isValidChild(parent.name, node.name)) {
  12224. return true;
  12225. } else if (parent && node.name === 'a' && hasClosest(parent, 'a')) {
  12226. return true;
  12227. } else {
  12228. return false;
  12229. }
  12230. };
  12231. const createRange = (sc, so, ec, eo) => {
  12232. const rng = document.createRange();
  12233. rng.setStart(sc, so);
  12234. rng.setEnd(ec, eo);
  12235. return rng;
  12236. };
  12237. const normalizeBlockSelectionRange = rng => {
  12238. const startPos = CaretPosition.fromRangeStart(rng);
  12239. const endPos = CaretPosition.fromRangeEnd(rng);
  12240. const rootNode = rng.commonAncestorContainer;
  12241. return fromPosition(false, rootNode, endPos).map(newEndPos => {
  12242. if (!isInSameBlock(startPos, endPos, rootNode) && isInSameBlock(startPos, newEndPos, rootNode)) {
  12243. return createRange(startPos.container(), startPos.offset(), newEndPos.container(), newEndPos.offset());
  12244. } else {
  12245. return rng;
  12246. }
  12247. }).getOr(rng);
  12248. };
  12249. const normalize = rng => rng.collapsed ? rng : normalizeBlockSelectionRange(rng);
  12250. const hasOnlyOneChild = node => {
  12251. return isNonNullable(node.firstChild) && node.firstChild === node.lastChild;
  12252. };
  12253. const isPaddingNode = node => {
  12254. return node.name === 'br' || node.value === nbsp;
  12255. };
  12256. const isPaddedEmptyBlock = (schema, node) => {
  12257. const blockElements = schema.getBlockElements();
  12258. return blockElements[node.name] && hasOnlyOneChild(node) && isPaddingNode(node.firstChild);
  12259. };
  12260. const isEmptyFragmentElement = (schema, node) => {
  12261. const nonEmptyElements = schema.getNonEmptyElements();
  12262. return isNonNullable(node) && (node.isEmpty(nonEmptyElements) || isPaddedEmptyBlock(schema, node));
  12263. };
  12264. const isListFragment = (schema, fragment) => {
  12265. let firstChild = fragment.firstChild;
  12266. let lastChild = fragment.lastChild;
  12267. if (firstChild && firstChild.name === 'meta') {
  12268. firstChild = firstChild.next;
  12269. }
  12270. if (lastChild && lastChild.attr('id') === 'mce_marker') {
  12271. lastChild = lastChild.prev;
  12272. }
  12273. if (isEmptyFragmentElement(schema, lastChild)) {
  12274. lastChild = lastChild === null || lastChild === void 0 ? void 0 : lastChild.prev;
  12275. }
  12276. if (!firstChild || firstChild !== lastChild) {
  12277. return false;
  12278. }
  12279. return firstChild.name === 'ul' || firstChild.name === 'ol';
  12280. };
  12281. const cleanupDomFragment = domFragment => {
  12282. var _a, _b;
  12283. const firstChild = domFragment.firstChild;
  12284. const lastChild = domFragment.lastChild;
  12285. if (firstChild && firstChild.nodeName === 'META') {
  12286. (_a = firstChild.parentNode) === null || _a === void 0 ? void 0 : _a.removeChild(firstChild);
  12287. }
  12288. if (lastChild && lastChild.id === 'mce_marker') {
  12289. (_b = lastChild.parentNode) === null || _b === void 0 ? void 0 : _b.removeChild(lastChild);
  12290. }
  12291. return domFragment;
  12292. };
  12293. const toDomFragment = (dom, serializer, fragment) => {
  12294. const html = serializer.serialize(fragment);
  12295. const domFragment = dom.createFragment(html);
  12296. return cleanupDomFragment(domFragment);
  12297. };
  12298. const listItems = elm => {
  12299. var _a;
  12300. return filter$5((_a = elm === null || elm === void 0 ? void 0 : elm.childNodes) !== null && _a !== void 0 ? _a : [], child => {
  12301. return child.nodeName === 'LI';
  12302. });
  12303. };
  12304. const isPadding = node => {
  12305. return node.data === nbsp || isBr$6(node);
  12306. };
  12307. const isListItemPadded = node => {
  12308. return isNonNullable(node === null || node === void 0 ? void 0 : node.firstChild) && node.firstChild === node.lastChild && isPadding(node.firstChild);
  12309. };
  12310. const isEmptyOrPadded = elm => {
  12311. return !elm.firstChild || isListItemPadded(elm);
  12312. };
  12313. const trimListItems = elms => {
  12314. return elms.length > 0 && isEmptyOrPadded(elms[elms.length - 1]) ? elms.slice(0, -1) : elms;
  12315. };
  12316. const getParentLi = (dom, node) => {
  12317. const parentBlock = dom.getParent(node, dom.isBlock);
  12318. return parentBlock && parentBlock.nodeName === 'LI' ? parentBlock : null;
  12319. };
  12320. const isParentBlockLi = (dom, node) => {
  12321. return !!getParentLi(dom, node);
  12322. };
  12323. const getSplit = (parentNode, rng) => {
  12324. const beforeRng = rng.cloneRange();
  12325. const afterRng = rng.cloneRange();
  12326. beforeRng.setStartBefore(parentNode);
  12327. afterRng.setEndAfter(parentNode);
  12328. return [
  12329. beforeRng.cloneContents(),
  12330. afterRng.cloneContents()
  12331. ];
  12332. };
  12333. const findFirstIn = (node, rootNode) => {
  12334. const caretPos = CaretPosition.before(node);
  12335. const caretWalker = CaretWalker(rootNode);
  12336. const newCaretPos = caretWalker.next(caretPos);
  12337. return newCaretPos ? newCaretPos.toRange() : null;
  12338. };
  12339. const findLastOf = (node, rootNode) => {
  12340. const caretPos = CaretPosition.after(node);
  12341. const caretWalker = CaretWalker(rootNode);
  12342. const newCaretPos = caretWalker.prev(caretPos);
  12343. return newCaretPos ? newCaretPos.toRange() : null;
  12344. };
  12345. const insertMiddle = (target, elms, rootNode, rng) => {
  12346. const parts = getSplit(target, rng);
  12347. const parentElm = target.parentNode;
  12348. if (parentElm) {
  12349. parentElm.insertBefore(parts[0], target);
  12350. Tools.each(elms, li => {
  12351. parentElm.insertBefore(li, target);
  12352. });
  12353. parentElm.insertBefore(parts[1], target);
  12354. parentElm.removeChild(target);
  12355. }
  12356. return findLastOf(elms[elms.length - 1], rootNode);
  12357. };
  12358. const insertBefore$1 = (target, elms, rootNode) => {
  12359. const parentElm = target.parentNode;
  12360. if (parentElm) {
  12361. Tools.each(elms, elm => {
  12362. parentElm.insertBefore(elm, target);
  12363. });
  12364. }
  12365. return findFirstIn(target, rootNode);
  12366. };
  12367. const insertAfter$1 = (target, elms, rootNode, dom) => {
  12368. dom.insertAfter(elms.reverse(), target);
  12369. return findLastOf(elms[0], rootNode);
  12370. };
  12371. const insertAtCaret$1 = (serializer, dom, rng, fragment) => {
  12372. const domFragment = toDomFragment(dom, serializer, fragment);
  12373. const liTarget = getParentLi(dom, rng.startContainer);
  12374. const liElms = trimListItems(listItems(domFragment.firstChild));
  12375. const BEGINNING = 1, END = 2;
  12376. const rootNode = dom.getRoot();
  12377. const isAt = location => {
  12378. const caretPos = CaretPosition.fromRangeStart(rng);
  12379. const caretWalker = CaretWalker(dom.getRoot());
  12380. const newPos = location === BEGINNING ? caretWalker.prev(caretPos) : caretWalker.next(caretPos);
  12381. const newPosNode = newPos === null || newPos === void 0 ? void 0 : newPos.getNode();
  12382. return newPosNode ? getParentLi(dom, newPosNode) !== liTarget : true;
  12383. };
  12384. if (!liTarget) {
  12385. return null;
  12386. } else if (isAt(BEGINNING)) {
  12387. return insertBefore$1(liTarget, liElms, rootNode);
  12388. } else if (isAt(END)) {
  12389. return insertAfter$1(liTarget, liElms, rootNode, dom);
  12390. } else {
  12391. return insertMiddle(liTarget, liElms, rootNode, rng);
  12392. }
  12393. };
  12394. const mergeableWrappedElements = ['pre'];
  12395. const shouldPasteContentOnly = (dom, fragment, parentNode, root) => {
  12396. var _a;
  12397. const firstNode = fragment.firstChild;
  12398. const lastNode = fragment.lastChild;
  12399. const last = lastNode.attr('data-mce-type') === 'bookmark' ? lastNode.prev : lastNode;
  12400. const isPastingSingleElement = firstNode === last;
  12401. const isWrappedElement = contains$2(mergeableWrappedElements, firstNode.name);
  12402. if (isPastingSingleElement && isWrappedElement) {
  12403. const isContentEditable = firstNode.attr('contenteditable') !== 'false';
  12404. const isPastingInTheSameBlockTag = ((_a = dom.getParent(parentNode, dom.isBlock)) === null || _a === void 0 ? void 0 : _a.nodeName.toLowerCase()) === firstNode.name;
  12405. const isPastingInContentEditable = Optional.from(getContentEditableRoot$1(root, parentNode)).forall(isContentEditableTrue$3);
  12406. return isContentEditable && isPastingInTheSameBlockTag && isPastingInContentEditable;
  12407. } else {
  12408. return false;
  12409. }
  12410. };
  12411. const isTableCell = isTableCell$3;
  12412. const isTableCellContentSelected = (dom, rng, cell) => {
  12413. if (isNonNullable(cell)) {
  12414. const endCell = dom.getParent(rng.endContainer, isTableCell);
  12415. return cell === endCell && hasAllContentsSelected(SugarElement.fromDom(cell), rng);
  12416. } else {
  12417. return false;
  12418. }
  12419. };
  12420. const validInsertion = (editor, value, parentNode) => {
  12421. var _a;
  12422. if (parentNode.getAttribute('data-mce-bogus') === 'all') {
  12423. (_a = parentNode.parentNode) === null || _a === void 0 ? void 0 : _a.insertBefore(editor.dom.createFragment(value), parentNode);
  12424. } else {
  12425. const node = parentNode.firstChild;
  12426. const node2 = parentNode.lastChild;
  12427. if (!node || node === node2 && node.nodeName === 'BR') {
  12428. editor.dom.setHTML(parentNode, value);
  12429. } else {
  12430. editor.selection.setContent(value, { no_events: true });
  12431. }
  12432. }
  12433. };
  12434. const trimBrsFromTableCell = (dom, elm) => {
  12435. Optional.from(dom.getParent(elm, 'td,th')).map(SugarElement.fromDom).each(trimBlockTrailingBr);
  12436. };
  12437. const reduceInlineTextElements = (editor, merge) => {
  12438. const textInlineElements = editor.schema.getTextInlineElements();
  12439. const dom = editor.dom;
  12440. if (merge) {
  12441. const root = editor.getBody();
  12442. const elementUtils = ElementUtils(editor);
  12443. Tools.each(dom.select('*[data-mce-fragment]'), node => {
  12444. const isInline = isNonNullable(textInlineElements[node.nodeName.toLowerCase()]);
  12445. if (isInline && hasInheritableStyles(dom, node)) {
  12446. for (let parentNode = node.parentElement; isNonNullable(parentNode) && parentNode !== root; parentNode = parentNode.parentElement) {
  12447. const styleConflict = hasStyleConflict(dom, node, parentNode);
  12448. if (styleConflict) {
  12449. break;
  12450. }
  12451. if (elementUtils.compare(parentNode, node)) {
  12452. dom.remove(node, true);
  12453. break;
  12454. }
  12455. }
  12456. }
  12457. });
  12458. }
  12459. };
  12460. const markFragmentElements = fragment => {
  12461. let node = fragment;
  12462. while (node = node.walk()) {
  12463. if (node.type === 1) {
  12464. node.attr('data-mce-fragment', '1');
  12465. }
  12466. }
  12467. };
  12468. const unmarkFragmentElements = elm => {
  12469. Tools.each(elm.getElementsByTagName('*'), elm => {
  12470. elm.removeAttribute('data-mce-fragment');
  12471. });
  12472. };
  12473. const isPartOfFragment = node => {
  12474. return !!node.getAttribute('data-mce-fragment');
  12475. };
  12476. const canHaveChildren = (editor, node) => {
  12477. return isNonNullable(node) && !editor.schema.getVoidElements()[node.nodeName];
  12478. };
  12479. const moveSelectionToMarker = (editor, marker) => {
  12480. var _a, _b, _c;
  12481. let nextRng;
  12482. const dom = editor.dom;
  12483. const selection = editor.selection;
  12484. if (!marker) {
  12485. return;
  12486. }
  12487. selection.scrollIntoView(marker);
  12488. const parentEditableElm = getContentEditableRoot$1(editor.getBody(), marker);
  12489. if (parentEditableElm && dom.getContentEditable(parentEditableElm) === 'false') {
  12490. dom.remove(marker);
  12491. selection.select(parentEditableElm);
  12492. return;
  12493. }
  12494. let rng = dom.createRng();
  12495. const node = marker.previousSibling;
  12496. if (isText$a(node)) {
  12497. rng.setStart(node, (_b = (_a = node.nodeValue) === null || _a === void 0 ? void 0 : _a.length) !== null && _b !== void 0 ? _b : 0);
  12498. const node2 = marker.nextSibling;
  12499. if (isText$a(node2)) {
  12500. node.appendData(node2.data);
  12501. (_c = node2.parentNode) === null || _c === void 0 ? void 0 : _c.removeChild(node2);
  12502. }
  12503. } else {
  12504. rng.setStartBefore(marker);
  12505. rng.setEndBefore(marker);
  12506. }
  12507. const findNextCaretRng = rng => {
  12508. let caretPos = CaretPosition.fromRangeStart(rng);
  12509. const caretWalker = CaretWalker(editor.getBody());
  12510. caretPos = caretWalker.next(caretPos);
  12511. return caretPos === null || caretPos === void 0 ? void 0 : caretPos.toRange();
  12512. };
  12513. const parentBlock = dom.getParent(marker, dom.isBlock);
  12514. dom.remove(marker);
  12515. if (parentBlock && dom.isEmpty(parentBlock)) {
  12516. empty(SugarElement.fromDom(parentBlock));
  12517. rng.setStart(parentBlock, 0);
  12518. rng.setEnd(parentBlock, 0);
  12519. if (!isTableCell(parentBlock) && !isPartOfFragment(parentBlock) && (nextRng = findNextCaretRng(rng))) {
  12520. rng = nextRng;
  12521. dom.remove(parentBlock);
  12522. } else {
  12523. dom.add(parentBlock, dom.create('br', { 'data-mce-bogus': '1' }));
  12524. }
  12525. }
  12526. selection.setRng(rng);
  12527. };
  12528. const deleteSelectedContent = editor => {
  12529. const dom = editor.dom;
  12530. const rng = normalize(editor.selection.getRng());
  12531. editor.selection.setRng(rng);
  12532. const startCell = dom.getParent(rng.startContainer, isTableCell);
  12533. if (isTableCellContentSelected(dom, rng, startCell)) {
  12534. deleteCellContents(editor, rng, SugarElement.fromDom(startCell));
  12535. } else if (rng.startContainer === rng.endContainer && rng.endOffset - rng.startOffset === 1 && isText$a(rng.startContainer.childNodes[rng.startOffset])) {
  12536. rng.deleteContents();
  12537. } else {
  12538. editor.getDoc().execCommand('Delete', false);
  12539. }
  12540. };
  12541. const findMarkerNode = scope => {
  12542. for (let markerNode = scope; markerNode; markerNode = markerNode.walk()) {
  12543. if (markerNode.attr('id') === 'mce_marker') {
  12544. return Optional.some(markerNode);
  12545. }
  12546. }
  12547. return Optional.none();
  12548. };
  12549. const insertHtmlAtCaret = (editor, value, details) => {
  12550. var _a, _b;
  12551. const selection = editor.selection;
  12552. const dom = editor.dom;
  12553. const parser = editor.parser;
  12554. const merge = details.merge;
  12555. const serializer = HtmlSerializer({ validate: true }, editor.schema);
  12556. const bookmarkHtml = '<span id="mce_marker" data-mce-type="bookmark">&#xFEFF;</span>';
  12557. if (value.indexOf('{$caret}') === -1) {
  12558. value += '{$caret}';
  12559. }
  12560. value = value.replace(/\{\$caret\}/, bookmarkHtml);
  12561. let rng = selection.getRng();
  12562. const caretElement = rng.startContainer;
  12563. const body = editor.getBody();
  12564. if (caretElement === body && selection.isCollapsed()) {
  12565. if (dom.isBlock(body.firstChild) && canHaveChildren(editor, body.firstChild) && dom.isEmpty(body.firstChild)) {
  12566. rng = dom.createRng();
  12567. rng.setStart(body.firstChild, 0);
  12568. rng.setEnd(body.firstChild, 0);
  12569. selection.setRng(rng);
  12570. }
  12571. }
  12572. if (!selection.isCollapsed()) {
  12573. deleteSelectedContent(editor);
  12574. }
  12575. const parentNode = selection.getNode();
  12576. const parserArgs = {
  12577. context: parentNode.nodeName.toLowerCase(),
  12578. data: details.data,
  12579. insert: true
  12580. };
  12581. const fragment = parser.parse(value, parserArgs);
  12582. if (details.paste === true && isListFragment(editor.schema, fragment) && isParentBlockLi(dom, parentNode)) {
  12583. rng = insertAtCaret$1(serializer, dom, selection.getRng(), fragment);
  12584. if (rng) {
  12585. selection.setRng(rng);
  12586. }
  12587. return value;
  12588. }
  12589. if (details.paste === true && shouldPasteContentOnly(dom, fragment, parentNode, editor.getBody())) {
  12590. (_a = fragment.firstChild) === null || _a === void 0 ? void 0 : _a.unwrap();
  12591. }
  12592. markFragmentElements(fragment);
  12593. let node = fragment.lastChild;
  12594. if (node && node.attr('id') === 'mce_marker') {
  12595. const marker = node;
  12596. for (node = node.prev; node; node = node.walk(true)) {
  12597. if (node.type === 3 || !dom.isBlock(node.name)) {
  12598. if (node.parent && editor.schema.isValidChild(node.parent.name, 'span')) {
  12599. node.parent.insert(marker, node, node.name === 'br');
  12600. }
  12601. break;
  12602. }
  12603. }
  12604. }
  12605. editor._selectionOverrides.showBlockCaretContainer(parentNode);
  12606. if (!parserArgs.invalid) {
  12607. value = serializer.serialize(fragment);
  12608. validInsertion(editor, value, parentNode);
  12609. } else {
  12610. editor.selection.setContent(bookmarkHtml);
  12611. let parentNode = selection.getNode();
  12612. let tempNode;
  12613. const rootNode = editor.getBody();
  12614. if (isDocument$1(parentNode)) {
  12615. parentNode = tempNode = rootNode;
  12616. } else {
  12617. tempNode = parentNode;
  12618. }
  12619. while (tempNode && tempNode !== rootNode) {
  12620. parentNode = tempNode;
  12621. tempNode = tempNode.parentNode;
  12622. }
  12623. value = parentNode === rootNode ? rootNode.innerHTML : dom.getOuterHTML(parentNode);
  12624. const root = parser.parse(value);
  12625. const markerNode = findMarkerNode(root);
  12626. const editingHost = markerNode.bind(findClosestEditingHost).getOr(root);
  12627. markerNode.each(marker => marker.replace(fragment));
  12628. const toExtract = fragment.children();
  12629. const parent = (_b = fragment.parent) !== null && _b !== void 0 ? _b : root;
  12630. fragment.unwrap();
  12631. const invalidChildren = filter$5(toExtract, node => isInvalid(editor.schema, node, parent));
  12632. cleanInvalidNodes(invalidChildren, editor.schema, editingHost);
  12633. filter$2(parser.getNodeFilters(), parser.getAttributeFilters(), root);
  12634. value = serializer.serialize(root);
  12635. if (parentNode === rootNode) {
  12636. dom.setHTML(rootNode, value);
  12637. } else {
  12638. dom.setOuterHTML(parentNode, value);
  12639. }
  12640. }
  12641. reduceInlineTextElements(editor, merge);
  12642. moveSelectionToMarker(editor, dom.get('mce_marker'));
  12643. unmarkFragmentElements(editor.getBody());
  12644. trimBrsFromTableCell(dom, selection.getStart());
  12645. updateCaret(editor.schema, editor.getBody(), selection.getStart());
  12646. return value;
  12647. };
  12648. const isTreeNode = content => content instanceof AstNode;
  12649. const moveSelection = editor => {
  12650. if (hasFocus(editor)) {
  12651. firstPositionIn(editor.getBody()).each(pos => {
  12652. const node = pos.getNode();
  12653. const caretPos = isTable$2(node) ? firstPositionIn(node).getOr(pos) : pos;
  12654. editor.selection.setRng(caretPos.toRange());
  12655. });
  12656. }
  12657. };
  12658. const setEditorHtml = (editor, html, noSelection) => {
  12659. editor.dom.setHTML(editor.getBody(), html);
  12660. if (noSelection !== true) {
  12661. moveSelection(editor);
  12662. }
  12663. };
  12664. const setContentString = (editor, body, content, args) => {
  12665. if (content.length === 0 || /^\s+$/.test(content)) {
  12666. const padd = '<br data-mce-bogus="1">';
  12667. if (body.nodeName === 'TABLE') {
  12668. content = '<tr><td>' + padd + '</td></tr>';
  12669. } else if (/^(UL|OL)$/.test(body.nodeName)) {
  12670. content = '<li>' + padd + '</li>';
  12671. }
  12672. const forcedRootBlockName = getForcedRootBlock(editor);
  12673. if (editor.schema.isValidChild(body.nodeName.toLowerCase(), forcedRootBlockName.toLowerCase())) {
  12674. content = padd;
  12675. content = editor.dom.createHTML(forcedRootBlockName, getForcedRootBlockAttrs(editor), content);
  12676. } else if (!content) {
  12677. content = padd;
  12678. }
  12679. setEditorHtml(editor, content, args.no_selection);
  12680. return {
  12681. content,
  12682. html: content
  12683. };
  12684. } else {
  12685. if (args.format !== 'raw') {
  12686. content = HtmlSerializer({ validate: false }, editor.schema).serialize(editor.parser.parse(content, {
  12687. isRootContent: true,
  12688. insert: true
  12689. }));
  12690. }
  12691. const trimmedHtml = isWsPreserveElement(SugarElement.fromDom(body)) ? content : Tools.trim(content);
  12692. setEditorHtml(editor, trimmedHtml, args.no_selection);
  12693. return {
  12694. content: trimmedHtml,
  12695. html: trimmedHtml
  12696. };
  12697. }
  12698. };
  12699. const setContentTree = (editor, body, content, args) => {
  12700. filter$2(editor.parser.getNodeFilters(), editor.parser.getAttributeFilters(), content);
  12701. const html = HtmlSerializer({ validate: false }, editor.schema).serialize(content);
  12702. const trimmedHtml = isWsPreserveElement(SugarElement.fromDom(body)) ? html : Tools.trim(html);
  12703. setEditorHtml(editor, trimmedHtml, args.no_selection);
  12704. return {
  12705. content,
  12706. html: trimmedHtml
  12707. };
  12708. };
  12709. const setContentInternal = (editor, content, args) => {
  12710. return Optional.from(editor.getBody()).map(body => {
  12711. if (isTreeNode(content)) {
  12712. return setContentTree(editor, body, content, args);
  12713. } else {
  12714. return setContentString(editor, body, content, args);
  12715. }
  12716. }).getOr({
  12717. content,
  12718. html: isTreeNode(args.content) ? '' : args.content
  12719. });
  12720. };
  12721. const ancestor$1 = (scope, predicate, isRoot) => ancestor$4(scope, predicate, isRoot).isSome();
  12722. const sibling = (scope, predicate) => sibling$1(scope, predicate).isSome();
  12723. const ensureIsRoot = isRoot => isFunction(isRoot) ? isRoot : never;
  12724. const ancestor = (scope, transform, isRoot) => {
  12725. let element = scope.dom;
  12726. const stop = ensureIsRoot(isRoot);
  12727. while (element.parentNode) {
  12728. element = element.parentNode;
  12729. const el = SugarElement.fromDom(element);
  12730. const transformed = transform(el);
  12731. if (transformed.isSome()) {
  12732. return transformed;
  12733. } else if (stop(el)) {
  12734. break;
  12735. }
  12736. }
  12737. return Optional.none();
  12738. };
  12739. const closest$1 = (scope, transform, isRoot) => {
  12740. const current = transform(scope);
  12741. const stop = ensureIsRoot(isRoot);
  12742. return current.orThunk(() => stop(scope) ? Optional.none() : ancestor(scope, transform, stop));
  12743. };
  12744. const isEq$3 = isEq$5;
  12745. const matchesUnInheritedFormatSelector = (ed, node, name) => {
  12746. const formatList = ed.formatter.get(name);
  12747. if (formatList) {
  12748. for (let i = 0; i < formatList.length; i++) {
  12749. const format = formatList[i];
  12750. if (isSelectorFormat(format) && format.inherit === false && ed.dom.is(node, format.selector)) {
  12751. return true;
  12752. }
  12753. }
  12754. }
  12755. return false;
  12756. };
  12757. const matchParents = (editor, node, name, vars, similar) => {
  12758. const root = editor.dom.getRoot();
  12759. if (node === root) {
  12760. return false;
  12761. }
  12762. const matchedNode = editor.dom.getParent(node, elm => {
  12763. if (matchesUnInheritedFormatSelector(editor, elm, name)) {
  12764. return true;
  12765. }
  12766. return elm.parentNode === root || !!matchNode(editor, elm, name, vars, true);
  12767. });
  12768. return !!matchNode(editor, matchedNode, name, vars, similar);
  12769. };
  12770. const matchName = (dom, node, format) => {
  12771. if (isInlineFormat(format) && isEq$3(node, format.inline)) {
  12772. return true;
  12773. }
  12774. if (isBlockFormat(format) && isEq$3(node, format.block)) {
  12775. return true;
  12776. }
  12777. if (isSelectorFormat(format)) {
  12778. return isElement$6(node) && dom.is(node, format.selector);
  12779. }
  12780. return false;
  12781. };
  12782. const matchItems = (dom, node, format, itemName, similar, vars) => {
  12783. const items = format[itemName];
  12784. const matchAttributes = itemName === 'attributes';
  12785. if (isFunction(format.onmatch)) {
  12786. return format.onmatch(node, format, itemName);
  12787. }
  12788. if (items) {
  12789. if (!isArrayLike(items)) {
  12790. for (const key in items) {
  12791. if (has$2(items, key)) {
  12792. const value = matchAttributes ? dom.getAttrib(node, key) : getStyle(dom, node, key);
  12793. const expectedValue = replaceVars(items[key], vars);
  12794. const isEmptyValue = isNullable(value) || isEmpty$3(value);
  12795. if (isEmptyValue && isNullable(expectedValue)) {
  12796. continue;
  12797. }
  12798. if (similar && isEmptyValue && !format.exact) {
  12799. return false;
  12800. }
  12801. if ((!similar || format.exact) && !isEq$3(value, normalizeStyleValue(expectedValue, key))) {
  12802. return false;
  12803. }
  12804. }
  12805. }
  12806. } else {
  12807. for (let i = 0; i < items.length; i++) {
  12808. if (matchAttributes ? dom.getAttrib(node, items[i]) : getStyle(dom, node, items[i])) {
  12809. return true;
  12810. }
  12811. }
  12812. }
  12813. }
  12814. return true;
  12815. };
  12816. const matchNode = (ed, node, name, vars, similar) => {
  12817. const formatList = ed.formatter.get(name);
  12818. const dom = ed.dom;
  12819. if (formatList && isElement$6(node)) {
  12820. for (let i = 0; i < formatList.length; i++) {
  12821. const format = formatList[i];
  12822. if (matchName(ed.dom, node, format) && matchItems(dom, node, format, 'attributes', similar, vars) && matchItems(dom, node, format, 'styles', similar, vars)) {
  12823. const classes = format.classes;
  12824. if (classes) {
  12825. for (let x = 0; x < classes.length; x++) {
  12826. if (!ed.dom.hasClass(node, replaceVars(classes[x], vars))) {
  12827. return;
  12828. }
  12829. }
  12830. }
  12831. return format;
  12832. }
  12833. }
  12834. }
  12835. return undefined;
  12836. };
  12837. const match$2 = (editor, name, vars, node, similar) => {
  12838. if (node) {
  12839. return matchParents(editor, node, name, vars, similar);
  12840. }
  12841. node = editor.selection.getNode();
  12842. if (matchParents(editor, node, name, vars, similar)) {
  12843. return true;
  12844. }
  12845. const startNode = editor.selection.getStart();
  12846. if (startNode !== node) {
  12847. if (matchParents(editor, startNode, name, vars, similar)) {
  12848. return true;
  12849. }
  12850. }
  12851. return false;
  12852. };
  12853. const matchAll = (editor, names, vars) => {
  12854. const matchedFormatNames = [];
  12855. const checkedMap = {};
  12856. const startElement = editor.selection.getStart();
  12857. editor.dom.getParent(startElement, node => {
  12858. for (let i = 0; i < names.length; i++) {
  12859. const name = names[i];
  12860. if (!checkedMap[name] && matchNode(editor, node, name, vars)) {
  12861. checkedMap[name] = true;
  12862. matchedFormatNames.push(name);
  12863. }
  12864. }
  12865. }, editor.dom.getRoot());
  12866. return matchedFormatNames;
  12867. };
  12868. const closest = (editor, names) => {
  12869. const isRoot = elm => eq(elm, SugarElement.fromDom(editor.getBody()));
  12870. const match = (elm, name) => matchNode(editor, elm.dom, name) ? Optional.some(name) : Optional.none();
  12871. return Optional.from(editor.selection.getStart(true)).bind(rawElm => closest$1(SugarElement.fromDom(rawElm), elm => findMap(names, name => match(elm, name)), isRoot)).getOrNull();
  12872. };
  12873. const canApply = (editor, name) => {
  12874. const formatList = editor.formatter.get(name);
  12875. const dom = editor.dom;
  12876. if (formatList) {
  12877. const startNode = editor.selection.getStart();
  12878. const parents = getParents$2(dom, startNode);
  12879. for (let x = formatList.length - 1; x >= 0; x--) {
  12880. const format = formatList[x];
  12881. if (!isSelectorFormat(format)) {
  12882. return true;
  12883. }
  12884. for (let i = parents.length - 1; i >= 0; i--) {
  12885. if (dom.is(parents[i], format.selector)) {
  12886. return true;
  12887. }
  12888. }
  12889. }
  12890. }
  12891. return false;
  12892. };
  12893. const matchAllOnNode = (editor, node, formatNames) => foldl(formatNames, (acc, name) => {
  12894. const matchSimilar = isVariableFormatName(editor, name);
  12895. if (editor.formatter.matchNode(node, name, {}, matchSimilar)) {
  12896. return acc.concat([name]);
  12897. } else {
  12898. return acc;
  12899. }
  12900. }, []);
  12901. const ZWSP = ZWSP$1;
  12902. const importNode = (ownerDocument, node) => {
  12903. return ownerDocument.importNode(node, true);
  12904. };
  12905. const getEmptyCaretContainers = node => {
  12906. const nodes = [];
  12907. let tempNode = node;
  12908. while (tempNode) {
  12909. if (isText$a(tempNode) && tempNode.data !== ZWSP || tempNode.childNodes.length > 1) {
  12910. return [];
  12911. }
  12912. if (isElement$6(tempNode)) {
  12913. nodes.push(tempNode);
  12914. }
  12915. tempNode = tempNode.firstChild;
  12916. }
  12917. return nodes;
  12918. };
  12919. const isCaretContainerEmpty = node => {
  12920. return getEmptyCaretContainers(node).length > 0;
  12921. };
  12922. const findFirstTextNode = node => {
  12923. if (node) {
  12924. const walker = new DomTreeWalker(node, node);
  12925. for (let tempNode = walker.current(); tempNode; tempNode = walker.next()) {
  12926. if (isText$a(tempNode)) {
  12927. return tempNode;
  12928. }
  12929. }
  12930. }
  12931. return null;
  12932. };
  12933. const createCaretContainer = fill => {
  12934. const caretContainer = SugarElement.fromTag('span');
  12935. setAll$1(caretContainer, {
  12936. 'id': CARET_ID,
  12937. 'data-mce-bogus': '1',
  12938. 'data-mce-type': 'format-caret'
  12939. });
  12940. if (fill) {
  12941. append$1(caretContainer, SugarElement.fromText(ZWSP));
  12942. }
  12943. return caretContainer;
  12944. };
  12945. const trimZwspFromCaretContainer = caretContainerNode => {
  12946. const textNode = findFirstTextNode(caretContainerNode);
  12947. if (textNode && textNode.data.charAt(0) === ZWSP) {
  12948. textNode.deleteData(0, 1);
  12949. }
  12950. return textNode;
  12951. };
  12952. const removeCaretContainerNode = (editor, node, moveCaret = true) => {
  12953. const dom = editor.dom, selection = editor.selection;
  12954. if (isCaretContainerEmpty(node)) {
  12955. deleteElement$2(editor, false, SugarElement.fromDom(node), moveCaret);
  12956. } else {
  12957. const rng = selection.getRng();
  12958. const block = dom.getParent(node, dom.isBlock);
  12959. const startContainer = rng.startContainer;
  12960. const startOffset = rng.startOffset;
  12961. const endContainer = rng.endContainer;
  12962. const endOffset = rng.endOffset;
  12963. const textNode = trimZwspFromCaretContainer(node);
  12964. dom.remove(node, true);
  12965. if (startContainer === textNode && startOffset > 0) {
  12966. rng.setStart(textNode, startOffset - 1);
  12967. }
  12968. if (endContainer === textNode && endOffset > 0) {
  12969. rng.setEnd(textNode, endOffset - 1);
  12970. }
  12971. if (block && dom.isEmpty(block)) {
  12972. fillWithPaddingBr(SugarElement.fromDom(block));
  12973. }
  12974. selection.setRng(rng);
  12975. }
  12976. };
  12977. const removeCaretContainer = (editor, node, moveCaret = true) => {
  12978. const dom = editor.dom, selection = editor.selection;
  12979. if (!node) {
  12980. node = getParentCaretContainer(editor.getBody(), selection.getStart());
  12981. if (!node) {
  12982. while (node = dom.get(CARET_ID)) {
  12983. removeCaretContainerNode(editor, node, false);
  12984. }
  12985. }
  12986. } else {
  12987. removeCaretContainerNode(editor, node, moveCaret);
  12988. }
  12989. };
  12990. const insertCaretContainerNode = (editor, caretContainer, formatNode) => {
  12991. var _a, _b;
  12992. const dom = editor.dom;
  12993. const block = dom.getParent(formatNode, curry(isTextBlock$1, editor.schema));
  12994. if (block && dom.isEmpty(block)) {
  12995. (_a = formatNode.parentNode) === null || _a === void 0 ? void 0 : _a.replaceChild(caretContainer, formatNode);
  12996. } else {
  12997. removeTrailingBr(SugarElement.fromDom(formatNode));
  12998. if (dom.isEmpty(formatNode)) {
  12999. (_b = formatNode.parentNode) === null || _b === void 0 ? void 0 : _b.replaceChild(caretContainer, formatNode);
  13000. } else {
  13001. dom.insertAfter(caretContainer, formatNode);
  13002. }
  13003. }
  13004. };
  13005. const appendNode = (parentNode, node) => {
  13006. parentNode.appendChild(node);
  13007. return node;
  13008. };
  13009. const insertFormatNodesIntoCaretContainer = (formatNodes, caretContainer) => {
  13010. var _a;
  13011. const innerMostFormatNode = foldr(formatNodes, (parentNode, formatNode) => {
  13012. return appendNode(parentNode, formatNode.cloneNode(false));
  13013. }, caretContainer);
  13014. const doc = (_a = innerMostFormatNode.ownerDocument) !== null && _a !== void 0 ? _a : document;
  13015. return appendNode(innerMostFormatNode, doc.createTextNode(ZWSP));
  13016. };
  13017. const cleanFormatNode = (editor, caretContainer, formatNode, name, vars, similar) => {
  13018. const formatter = editor.formatter;
  13019. const dom = editor.dom;
  13020. const validFormats = filter$5(keys(formatter.get()), formatName => formatName !== name && !contains$1(formatName, 'removeformat'));
  13021. const matchedFormats = matchAllOnNode(editor, formatNode, validFormats);
  13022. const uniqueFormats = filter$5(matchedFormats, fmtName => !areSimilarFormats(editor, fmtName, name));
  13023. if (uniqueFormats.length > 0) {
  13024. const clonedFormatNode = formatNode.cloneNode(false);
  13025. dom.add(caretContainer, clonedFormatNode);
  13026. formatter.remove(name, vars, clonedFormatNode, similar);
  13027. dom.remove(clonedFormatNode);
  13028. return Optional.some(clonedFormatNode);
  13029. } else {
  13030. return Optional.none();
  13031. }
  13032. };
  13033. const applyCaretFormat = (editor, name, vars) => {
  13034. let caretContainer;
  13035. const selection = editor.selection;
  13036. const formatList = editor.formatter.get(name);
  13037. if (!formatList) {
  13038. return;
  13039. }
  13040. const selectionRng = selection.getRng();
  13041. let offset = selectionRng.startOffset;
  13042. const container = selectionRng.startContainer;
  13043. const text = container.nodeValue;
  13044. caretContainer = getParentCaretContainer(editor.getBody(), selection.getStart());
  13045. const wordcharRegex = /[^\s\u00a0\u00ad\u200b\ufeff]/;
  13046. if (text && offset > 0 && offset < text.length && wordcharRegex.test(text.charAt(offset)) && wordcharRegex.test(text.charAt(offset - 1))) {
  13047. const bookmark = selection.getBookmark();
  13048. selectionRng.collapse(true);
  13049. let rng = expandRng(editor.dom, selectionRng, formatList);
  13050. rng = split(rng);
  13051. editor.formatter.apply(name, vars, rng);
  13052. selection.moveToBookmark(bookmark);
  13053. } else {
  13054. let textNode = caretContainer ? findFirstTextNode(caretContainer) : null;
  13055. if (!caretContainer || (textNode === null || textNode === void 0 ? void 0 : textNode.data) !== ZWSP) {
  13056. caretContainer = importNode(editor.getDoc(), createCaretContainer(true).dom);
  13057. textNode = caretContainer.firstChild;
  13058. selectionRng.insertNode(caretContainer);
  13059. offset = 1;
  13060. editor.formatter.apply(name, vars, caretContainer);
  13061. } else {
  13062. editor.formatter.apply(name, vars, caretContainer);
  13063. }
  13064. selection.setCursorLocation(textNode, offset);
  13065. }
  13066. };
  13067. const removeCaretFormat = (editor, name, vars, similar) => {
  13068. const dom = editor.dom;
  13069. const selection = editor.selection;
  13070. let hasContentAfter = false;
  13071. const formatList = editor.formatter.get(name);
  13072. if (!formatList) {
  13073. return;
  13074. }
  13075. const rng = selection.getRng();
  13076. const container = rng.startContainer;
  13077. const offset = rng.startOffset;
  13078. let node = container;
  13079. if (isText$a(container)) {
  13080. if (offset !== container.data.length) {
  13081. hasContentAfter = true;
  13082. }
  13083. node = node.parentNode;
  13084. }
  13085. const parents = [];
  13086. let formatNode;
  13087. while (node) {
  13088. if (matchNode(editor, node, name, vars, similar)) {
  13089. formatNode = node;
  13090. break;
  13091. }
  13092. if (node.nextSibling) {
  13093. hasContentAfter = true;
  13094. }
  13095. parents.push(node);
  13096. node = node.parentNode;
  13097. }
  13098. if (!formatNode) {
  13099. return;
  13100. }
  13101. if (hasContentAfter) {
  13102. const bookmark = selection.getBookmark();
  13103. rng.collapse(true);
  13104. let expandedRng = expandRng(dom, rng, formatList, true);
  13105. expandedRng = split(expandedRng);
  13106. editor.formatter.remove(name, vars, expandedRng, similar);
  13107. selection.moveToBookmark(bookmark);
  13108. } else {
  13109. const caretContainer = getParentCaretContainer(editor.getBody(), formatNode);
  13110. const newCaretContainer = createCaretContainer(false).dom;
  13111. insertCaretContainerNode(editor, newCaretContainer, caretContainer !== null && caretContainer !== void 0 ? caretContainer : formatNode);
  13112. const cleanedFormatNode = cleanFormatNode(editor, newCaretContainer, formatNode, name, vars, similar);
  13113. const caretTextNode = insertFormatNodesIntoCaretContainer(parents.concat(cleanedFormatNode.toArray()), newCaretContainer);
  13114. if (caretContainer) {
  13115. removeCaretContainerNode(editor, caretContainer, false);
  13116. }
  13117. selection.setCursorLocation(caretTextNode, 1);
  13118. if (dom.isEmpty(formatNode)) {
  13119. dom.remove(formatNode);
  13120. }
  13121. }
  13122. };
  13123. const disableCaretContainer = (editor, keyCode) => {
  13124. const selection = editor.selection, body = editor.getBody();
  13125. removeCaretContainer(editor, null, false);
  13126. if ((keyCode === 8 || keyCode === 46) && selection.isCollapsed() && selection.getStart().innerHTML === ZWSP) {
  13127. removeCaretContainer(editor, getParentCaretContainer(body, selection.getStart()));
  13128. }
  13129. if (keyCode === 37 || keyCode === 39) {
  13130. removeCaretContainer(editor, getParentCaretContainer(body, selection.getStart()));
  13131. }
  13132. };
  13133. const setup$u = editor => {
  13134. editor.on('mouseup keydown', e => {
  13135. disableCaretContainer(editor, e.keyCode);
  13136. });
  13137. };
  13138. const createCaretFormat = formatNodes => {
  13139. const caretContainer = createCaretContainer(false);
  13140. const innerMost = insertFormatNodesIntoCaretContainer(formatNodes, caretContainer.dom);
  13141. return {
  13142. caretContainer,
  13143. caretPosition: CaretPosition(innerMost, 0)
  13144. };
  13145. };
  13146. const replaceWithCaretFormat = (targetNode, formatNodes) => {
  13147. const {caretContainer, caretPosition} = createCaretFormat(formatNodes);
  13148. before$3(SugarElement.fromDom(targetNode), caretContainer);
  13149. remove$6(SugarElement.fromDom(targetNode));
  13150. return caretPosition;
  13151. };
  13152. const createCaretFormatAtStart$1 = (editor, formatNodes) => {
  13153. const {caretContainer, caretPosition} = createCaretFormat(formatNodes);
  13154. editor.selection.getRng().insertNode(caretContainer.dom);
  13155. return caretPosition;
  13156. };
  13157. const isFormatElement = (editor, element) => {
  13158. const inlineElements = editor.schema.getTextInlineElements();
  13159. return has$2(inlineElements, name(element)) && !isCaretNode(element.dom) && !isBogus$2(element.dom);
  13160. };
  13161. const isEmptyCaretFormatElement = element => {
  13162. return isCaretNode(element.dom) && isCaretContainerEmpty(element.dom);
  13163. };
  13164. const postProcessHooks = {};
  13165. const isPre = matchNodeNames(['pre']);
  13166. const addPostProcessHook = (name, hook) => {
  13167. const hooks = postProcessHooks[name];
  13168. if (!hooks) {
  13169. postProcessHooks[name] = [];
  13170. }
  13171. postProcessHooks[name].push(hook);
  13172. };
  13173. const postProcess$1 = (name, editor) => {
  13174. if (has$2(postProcessHooks, name)) {
  13175. each$e(postProcessHooks[name], hook => {
  13176. hook(editor);
  13177. });
  13178. }
  13179. };
  13180. addPostProcessHook('pre', editor => {
  13181. const rng = editor.selection.getRng();
  13182. const hasPreSibling = blocks => pre => {
  13183. const prev = pre.previousSibling;
  13184. return isPre(prev) && contains$2(blocks, prev);
  13185. };
  13186. const joinPre = (pre1, pre2) => {
  13187. const sPre2 = SugarElement.fromDom(pre2);
  13188. const doc = documentOrOwner(sPre2).dom;
  13189. remove$6(sPre2);
  13190. append(SugarElement.fromDom(pre1), [
  13191. SugarElement.fromTag('br', doc),
  13192. SugarElement.fromTag('br', doc),
  13193. ...children$1(sPre2)
  13194. ]);
  13195. };
  13196. if (!rng.collapsed) {
  13197. const blocks = editor.selection.getSelectedBlocks();
  13198. const preBlocks = filter$5(filter$5(blocks, isPre), hasPreSibling(blocks));
  13199. each$e(preBlocks, pre => {
  13200. joinPre(pre.previousSibling, pre);
  13201. });
  13202. }
  13203. });
  13204. const listItemStyles = [
  13205. 'fontWeight',
  13206. 'fontStyle',
  13207. 'color',
  13208. 'fontSize',
  13209. 'fontFamily'
  13210. ];
  13211. const hasListStyles = fmt => isObject(fmt.styles) && exists(keys(fmt.styles), name => contains$2(listItemStyles, name));
  13212. const findExpandedListItemFormat = formats => find$2(formats, fmt => isInlineFormat(fmt) && fmt.inline === 'span' && hasListStyles(fmt));
  13213. const getExpandedListItemFormat = (formatter, format) => {
  13214. const formatList = formatter.get(format);
  13215. return isArray$1(formatList) ? findExpandedListItemFormat(formatList) : Optional.none();
  13216. };
  13217. const isRngStartAtStartOfElement = (rng, elm) => prevPosition(elm, CaretPosition.fromRangeStart(rng)).isNone();
  13218. const isRngEndAtEndOfElement = (rng, elm) => {
  13219. return nextPosition(elm, CaretPosition.fromRangeEnd(rng)).exists(pos => !isBr$6(pos.getNode()) || nextPosition(elm, pos).isSome()) === false;
  13220. };
  13221. const isEditableListItem = dom => elm => isListItem$2(elm) && dom.isEditable(elm);
  13222. const getFullySelectedBlocks = selection => {
  13223. const blocks = selection.getSelectedBlocks();
  13224. const rng = selection.getRng();
  13225. if (selection.isCollapsed()) {
  13226. return [];
  13227. }
  13228. if (blocks.length === 1) {
  13229. return isRngStartAtStartOfElement(rng, blocks[0]) && isRngEndAtEndOfElement(rng, blocks[0]) ? blocks : [];
  13230. } else {
  13231. const first = head(blocks).filter(elm => isRngStartAtStartOfElement(rng, elm)).toArray();
  13232. const last = last$3(blocks).filter(elm => isRngEndAtEndOfElement(rng, elm)).toArray();
  13233. const middle = blocks.slice(1, -1);
  13234. return first.concat(middle).concat(last);
  13235. }
  13236. };
  13237. const getFullySelectedListItems = selection => filter$5(getFullySelectedBlocks(selection), isEditableListItem(selection.dom));
  13238. const getPartiallySelectedListItems = selection => filter$5(selection.getSelectedBlocks(), isEditableListItem(selection.dom));
  13239. const each$8 = Tools.each;
  13240. const isElementNode = node => isElement$6(node) && !isBookmarkNode$1(node) && !isCaretNode(node) && !isBogus$2(node);
  13241. const findElementSibling = (node, siblingName) => {
  13242. for (let sibling = node; sibling; sibling = sibling[siblingName]) {
  13243. if (isText$a(sibling) && isNotEmpty(sibling.data)) {
  13244. return node;
  13245. }
  13246. if (isElement$6(sibling) && !isBookmarkNode$1(sibling)) {
  13247. return sibling;
  13248. }
  13249. }
  13250. return node;
  13251. };
  13252. const mergeSiblingsNodes = (editor, prev, next) => {
  13253. const elementUtils = ElementUtils(editor);
  13254. const isPrevEditable = isElement$6(prev) && isEditable$2(prev);
  13255. const isNextEditable = isElement$6(next) && isEditable$2(next);
  13256. if (isPrevEditable && isNextEditable) {
  13257. const prevSibling = findElementSibling(prev, 'previousSibling');
  13258. const nextSibling = findElementSibling(next, 'nextSibling');
  13259. if (elementUtils.compare(prevSibling, nextSibling)) {
  13260. for (let sibling = prevSibling.nextSibling; sibling && sibling !== nextSibling;) {
  13261. const tmpSibling = sibling;
  13262. sibling = sibling.nextSibling;
  13263. prevSibling.appendChild(tmpSibling);
  13264. }
  13265. editor.dom.remove(nextSibling);
  13266. Tools.each(Tools.grep(nextSibling.childNodes), node => {
  13267. prevSibling.appendChild(node);
  13268. });
  13269. return prevSibling;
  13270. }
  13271. }
  13272. return next;
  13273. };
  13274. const mergeSiblings = (editor, format, vars, node) => {
  13275. var _a;
  13276. if (node && format.merge_siblings !== false) {
  13277. const newNode = (_a = mergeSiblingsNodes(editor, getNonWhiteSpaceSibling(node), node)) !== null && _a !== void 0 ? _a : node;
  13278. mergeSiblingsNodes(editor, newNode, getNonWhiteSpaceSibling(newNode, true));
  13279. }
  13280. };
  13281. const clearChildStyles = (dom, format, node) => {
  13282. if (format.clear_child_styles) {
  13283. const selector = format.links ? '*:not(a)' : '*';
  13284. each$8(dom.select(selector, node), childNode => {
  13285. if (isElementNode(childNode) && isEditable$2(childNode)) {
  13286. each$8(format.styles, (_value, name) => {
  13287. dom.setStyle(childNode, name, '');
  13288. });
  13289. }
  13290. });
  13291. }
  13292. };
  13293. const processChildElements = (node, filter, process) => {
  13294. each$8(node.childNodes, node => {
  13295. if (isElementNode(node)) {
  13296. if (filter(node)) {
  13297. process(node);
  13298. }
  13299. if (node.hasChildNodes()) {
  13300. processChildElements(node, filter, process);
  13301. }
  13302. }
  13303. });
  13304. };
  13305. const unwrapEmptySpan = (dom, node) => {
  13306. if (node.nodeName === 'SPAN' && dom.getAttribs(node).length === 0) {
  13307. dom.remove(node, true);
  13308. }
  13309. };
  13310. const hasStyle = (dom, name) => node => !!(node && getStyle(dom, node, name));
  13311. const applyStyle = (dom, name, value) => node => {
  13312. dom.setStyle(node, name, value);
  13313. if (node.getAttribute('style') === '') {
  13314. node.removeAttribute('style');
  13315. }
  13316. unwrapEmptySpan(dom, node);
  13317. };
  13318. const removeResult = Adt.generate([
  13319. { keep: [] },
  13320. { rename: ['name'] },
  13321. { removed: [] }
  13322. ]);
  13323. const MCE_ATTR_RE = /^(src|href|style)$/;
  13324. const each$7 = Tools.each;
  13325. const isEq$2 = isEq$5;
  13326. const isTableCellOrRow = node => /^(TR|TH|TD)$/.test(node.nodeName);
  13327. const isChildOfInlineParent = (dom, node, parent) => dom.isChildOf(node, parent) && node !== parent && !dom.isBlock(parent);
  13328. const getContainer = (ed, rng, start) => {
  13329. let container = rng[start ? 'startContainer' : 'endContainer'];
  13330. let offset = rng[start ? 'startOffset' : 'endOffset'];
  13331. if (isElement$6(container)) {
  13332. const lastIdx = container.childNodes.length - 1;
  13333. if (!start && offset) {
  13334. offset--;
  13335. }
  13336. container = container.childNodes[offset > lastIdx ? lastIdx : offset];
  13337. }
  13338. if (isText$a(container) && start && offset >= container.data.length) {
  13339. container = new DomTreeWalker(container, ed.getBody()).next() || container;
  13340. }
  13341. if (isText$a(container) && !start && offset === 0) {
  13342. container = new DomTreeWalker(container, ed.getBody()).prev() || container;
  13343. }
  13344. return container;
  13345. };
  13346. const normalizeTableSelection = (node, start) => {
  13347. const prop = start ? 'firstChild' : 'lastChild';
  13348. const childNode = node[prop];
  13349. if (isTableCellOrRow(node) && childNode) {
  13350. if (node.nodeName === 'TR') {
  13351. return childNode[prop] || childNode;
  13352. } else {
  13353. return childNode;
  13354. }
  13355. }
  13356. return node;
  13357. };
  13358. const wrap$1 = (dom, node, name, attrs) => {
  13359. var _a;
  13360. const wrapper = dom.create(name, attrs);
  13361. (_a = node.parentNode) === null || _a === void 0 ? void 0 : _a.insertBefore(wrapper, node);
  13362. wrapper.appendChild(node);
  13363. return wrapper;
  13364. };
  13365. const wrapWithSiblings = (dom, node, next, name, attrs) => {
  13366. const start = SugarElement.fromDom(node);
  13367. const wrapper = SugarElement.fromDom(dom.create(name, attrs));
  13368. const siblings = next ? nextSiblings(start) : prevSiblings(start);
  13369. append(wrapper, siblings);
  13370. if (next) {
  13371. before$3(start, wrapper);
  13372. prepend(wrapper, start);
  13373. } else {
  13374. after$4(start, wrapper);
  13375. append$1(wrapper, start);
  13376. }
  13377. return wrapper.dom;
  13378. };
  13379. const isColorFormatAndAnchor = (node, format) => format.links && node.nodeName === 'A';
  13380. const removeNode = (ed, node, format) => {
  13381. const parentNode = node.parentNode;
  13382. let rootBlockElm;
  13383. const dom = ed.dom;
  13384. const forcedRootBlock = getForcedRootBlock(ed);
  13385. if (isBlockFormat(format)) {
  13386. if (parentNode === dom.getRoot()) {
  13387. if (!format.list_block || !isEq$2(node, format.list_block)) {
  13388. each$e(from(node.childNodes), node => {
  13389. if (isValid(ed, forcedRootBlock, node.nodeName.toLowerCase())) {
  13390. if (!rootBlockElm) {
  13391. rootBlockElm = wrap$1(dom, node, forcedRootBlock);
  13392. dom.setAttribs(rootBlockElm, getForcedRootBlockAttrs(ed));
  13393. } else {
  13394. rootBlockElm.appendChild(node);
  13395. }
  13396. } else {
  13397. rootBlockElm = null;
  13398. }
  13399. });
  13400. }
  13401. }
  13402. }
  13403. if (isMixedFormat(format) && !isEq$2(format.inline, node)) {
  13404. return;
  13405. }
  13406. dom.remove(node, true);
  13407. };
  13408. const processFormatAttrOrStyle = (name, value, vars) => {
  13409. if (isNumber(name)) {
  13410. return {
  13411. name: value,
  13412. value: null
  13413. };
  13414. } else {
  13415. return {
  13416. name,
  13417. value: replaceVars(value, vars)
  13418. };
  13419. }
  13420. };
  13421. const removeEmptyStyleAttributeIfNeeded = (dom, elm) => {
  13422. if (dom.getAttrib(elm, 'style') === '') {
  13423. elm.removeAttribute('style');
  13424. elm.removeAttribute('data-mce-style');
  13425. }
  13426. };
  13427. const removeStyles = (dom, elm, format, vars, compareNode) => {
  13428. let stylesModified = false;
  13429. each$7(format.styles, (value, name) => {
  13430. const {
  13431. name: styleName,
  13432. value: styleValue
  13433. } = processFormatAttrOrStyle(name, value, vars);
  13434. const normalizedStyleValue = normalizeStyleValue(styleValue, styleName);
  13435. if (format.remove_similar || isNull(styleValue) || !isElement$6(compareNode) || isEq$2(getStyle(dom, compareNode, styleName), normalizedStyleValue)) {
  13436. dom.setStyle(elm, styleName, '');
  13437. }
  13438. stylesModified = true;
  13439. });
  13440. if (stylesModified) {
  13441. removeEmptyStyleAttributeIfNeeded(dom, elm);
  13442. }
  13443. };
  13444. const removeListStyleFormats = (editor, name, vars) => {
  13445. if (name === 'removeformat') {
  13446. each$e(getPartiallySelectedListItems(editor.selection), li => {
  13447. each$e(listItemStyles, name => editor.dom.setStyle(li, name, ''));
  13448. removeEmptyStyleAttributeIfNeeded(editor.dom, li);
  13449. });
  13450. } else {
  13451. getExpandedListItemFormat(editor.formatter, name).each(liFmt => {
  13452. each$e(getPartiallySelectedListItems(editor.selection), li => removeStyles(editor.dom, li, liFmt, vars, null));
  13453. });
  13454. }
  13455. };
  13456. const removeFormatInternal = (ed, format, vars, node, compareNode) => {
  13457. const dom = ed.dom;
  13458. const elementUtils = ElementUtils(ed);
  13459. const schema = ed.schema;
  13460. if (isInlineFormat(format) && isTransparentElementName(schema, format.inline) && isTransparentBlock(schema, node) && node.parentElement === ed.getBody()) {
  13461. removeNode(ed, node, format);
  13462. return removeResult.removed();
  13463. }
  13464. if (!format.ceFalseOverride && node && dom.getContentEditableParent(node) === 'false') {
  13465. return removeResult.keep();
  13466. }
  13467. if (node && !matchName(dom, node, format) && !isColorFormatAndAnchor(node, format)) {
  13468. return removeResult.keep();
  13469. }
  13470. const elm = node;
  13471. const preserveAttributes = format.preserve_attributes;
  13472. if (isInlineFormat(format) && format.remove === 'all' && isArray$1(preserveAttributes)) {
  13473. const attrsToPreserve = filter$5(dom.getAttribs(elm), attr => contains$2(preserveAttributes, attr.name.toLowerCase()));
  13474. dom.removeAllAttribs(elm);
  13475. each$e(attrsToPreserve, attr => dom.setAttrib(elm, attr.name, attr.value));
  13476. if (attrsToPreserve.length > 0) {
  13477. return removeResult.rename('span');
  13478. }
  13479. }
  13480. if (format.remove !== 'all') {
  13481. removeStyles(dom, elm, format, vars, compareNode);
  13482. each$7(format.attributes, (value, name) => {
  13483. const {
  13484. name: attrName,
  13485. value: attrValue
  13486. } = processFormatAttrOrStyle(name, value, vars);
  13487. if (format.remove_similar || isNull(attrValue) || !isElement$6(compareNode) || isEq$2(dom.getAttrib(compareNode, attrName), attrValue)) {
  13488. if (attrName === 'class') {
  13489. const currentValue = dom.getAttrib(elm, attrName);
  13490. if (currentValue) {
  13491. let valueOut = '';
  13492. each$e(currentValue.split(/\s+/), cls => {
  13493. if (/mce\-\w+/.test(cls)) {
  13494. valueOut += (valueOut ? ' ' : '') + cls;
  13495. }
  13496. });
  13497. if (valueOut) {
  13498. dom.setAttrib(elm, attrName, valueOut);
  13499. return;
  13500. }
  13501. }
  13502. }
  13503. if (MCE_ATTR_RE.test(attrName)) {
  13504. elm.removeAttribute('data-mce-' + attrName);
  13505. }
  13506. if (attrName === 'style' && matchNodeNames(['li'])(elm) && dom.getStyle(elm, 'list-style-type') === 'none') {
  13507. elm.removeAttribute(attrName);
  13508. dom.setStyle(elm, 'list-style-type', 'none');
  13509. return;
  13510. }
  13511. if (attrName === 'class') {
  13512. elm.removeAttribute('className');
  13513. }
  13514. elm.removeAttribute(attrName);
  13515. }
  13516. });
  13517. each$7(format.classes, value => {
  13518. value = replaceVars(value, vars);
  13519. if (!isElement$6(compareNode) || dom.hasClass(compareNode, value)) {
  13520. dom.removeClass(elm, value);
  13521. }
  13522. });
  13523. const attrs = dom.getAttribs(elm);
  13524. for (let i = 0; i < attrs.length; i++) {
  13525. const attrName = attrs[i].nodeName;
  13526. if (!elementUtils.isAttributeInternal(attrName)) {
  13527. return removeResult.keep();
  13528. }
  13529. }
  13530. }
  13531. if (format.remove !== 'none') {
  13532. removeNode(ed, elm, format);
  13533. return removeResult.removed();
  13534. }
  13535. return removeResult.keep();
  13536. };
  13537. const removeFormat$1 = (ed, format, vars, node, compareNode) => removeFormatInternal(ed, format, vars, node, compareNode).fold(never, newName => {
  13538. ed.dom.rename(node, newName);
  13539. return true;
  13540. }, always);
  13541. const findFormatRoot = (editor, container, name, vars, similar) => {
  13542. let formatRoot;
  13543. if (container.parentNode) {
  13544. each$e(getParents$2(editor.dom, container.parentNode).reverse(), parent => {
  13545. if (!formatRoot && isElement$6(parent) && parent.id !== '_start' && parent.id !== '_end') {
  13546. const format = matchNode(editor, parent, name, vars, similar);
  13547. if (format && format.split !== false) {
  13548. formatRoot = parent;
  13549. }
  13550. }
  13551. });
  13552. }
  13553. return formatRoot;
  13554. };
  13555. const removeFormatFromClone = (editor, format, vars, clone) => removeFormatInternal(editor, format, vars, clone, clone).fold(constant(clone), newName => {
  13556. const fragment = editor.dom.createFragment();
  13557. fragment.appendChild(clone);
  13558. return editor.dom.rename(clone, newName);
  13559. }, constant(null));
  13560. const wrapAndSplit = (editor, formatList, formatRoot, container, target, split, format, vars) => {
  13561. var _a, _b;
  13562. let lastClone;
  13563. let firstClone;
  13564. const dom = editor.dom;
  13565. if (formatRoot) {
  13566. const formatRootParent = formatRoot.parentNode;
  13567. for (let parent = container.parentNode; parent && parent !== formatRootParent; parent = parent.parentNode) {
  13568. let clone = dom.clone(parent, false);
  13569. for (let i = 0; i < formatList.length; i++) {
  13570. clone = removeFormatFromClone(editor, formatList[i], vars, clone);
  13571. if (clone === null) {
  13572. break;
  13573. }
  13574. }
  13575. if (clone) {
  13576. if (lastClone) {
  13577. clone.appendChild(lastClone);
  13578. }
  13579. if (!firstClone) {
  13580. firstClone = clone;
  13581. }
  13582. lastClone = clone;
  13583. }
  13584. }
  13585. if (split && (!format.mixed || !dom.isBlock(formatRoot))) {
  13586. container = (_a = dom.split(formatRoot, container)) !== null && _a !== void 0 ? _a : container;
  13587. }
  13588. if (lastClone && firstClone) {
  13589. (_b = target.parentNode) === null || _b === void 0 ? void 0 : _b.insertBefore(lastClone, target);
  13590. firstClone.appendChild(target);
  13591. if (isInlineFormat(format)) {
  13592. mergeSiblings(editor, format, vars, lastClone);
  13593. }
  13594. }
  13595. }
  13596. return container;
  13597. };
  13598. const remove$2 = (ed, name, vars, node, similar) => {
  13599. const formatList = ed.formatter.get(name);
  13600. const format = formatList[0];
  13601. const dom = ed.dom;
  13602. const selection = ed.selection;
  13603. const splitToFormatRoot = container => {
  13604. const formatRoot = findFormatRoot(ed, container, name, vars, similar);
  13605. return wrapAndSplit(ed, formatList, formatRoot, container, container, true, format, vars);
  13606. };
  13607. const isRemoveBookmarkNode = node => isBookmarkNode$1(node) && isElement$6(node) && (node.id === '_start' || node.id === '_end');
  13608. const removeNodeFormat = node => exists(formatList, fmt => removeFormat$1(ed, fmt, vars, node, node));
  13609. const process = node => {
  13610. const children = from(node.childNodes);
  13611. const removed = removeNodeFormat(node);
  13612. const currentNodeMatches = removed || exists(formatList, f => matchName(dom, node, f));
  13613. const parentNode = node.parentNode;
  13614. if (!currentNodeMatches && isNonNullable(parentNode) && shouldExpandToSelector(format)) {
  13615. removeNodeFormat(parentNode);
  13616. }
  13617. if (format.deep) {
  13618. if (children.length) {
  13619. for (let i = 0; i < children.length; i++) {
  13620. process(children[i]);
  13621. }
  13622. }
  13623. }
  13624. const textDecorations = [
  13625. 'underline',
  13626. 'line-through',
  13627. 'overline'
  13628. ];
  13629. each$e(textDecorations, decoration => {
  13630. if (isElement$6(node) && ed.dom.getStyle(node, 'text-decoration') === decoration && node.parentNode && getTextDecoration(dom, node.parentNode) === decoration) {
  13631. removeFormat$1(ed, {
  13632. deep: false,
  13633. exact: true,
  13634. inline: 'span',
  13635. styles: { textDecoration: decoration }
  13636. }, undefined, node);
  13637. }
  13638. });
  13639. };
  13640. const unwrap = start => {
  13641. const node = dom.get(start ? '_start' : '_end');
  13642. if (node) {
  13643. let out = node[start ? 'firstChild' : 'lastChild'];
  13644. if (isRemoveBookmarkNode(out)) {
  13645. out = out[start ? 'firstChild' : 'lastChild'];
  13646. }
  13647. if (isText$a(out) && out.data.length === 0) {
  13648. out = start ? node.previousSibling || node.nextSibling : node.nextSibling || node.previousSibling;
  13649. }
  13650. dom.remove(node, true);
  13651. return out;
  13652. } else {
  13653. return null;
  13654. }
  13655. };
  13656. const removeRngStyle = rng => {
  13657. let startContainer;
  13658. let endContainer;
  13659. let expandedRng = expandRng(dom, rng, formatList, rng.collapsed);
  13660. if (format.split) {
  13661. expandedRng = split(expandedRng);
  13662. startContainer = getContainer(ed, expandedRng, true);
  13663. endContainer = getContainer(ed, expandedRng);
  13664. if (startContainer !== endContainer) {
  13665. startContainer = normalizeTableSelection(startContainer, true);
  13666. endContainer = normalizeTableSelection(endContainer, false);
  13667. if (isChildOfInlineParent(dom, startContainer, endContainer)) {
  13668. const marker = Optional.from(startContainer.firstChild).getOr(startContainer);
  13669. splitToFormatRoot(wrapWithSiblings(dom, marker, true, 'span', {
  13670. 'id': '_start',
  13671. 'data-mce-type': 'bookmark'
  13672. }));
  13673. unwrap(true);
  13674. return;
  13675. }
  13676. if (isChildOfInlineParent(dom, endContainer, startContainer)) {
  13677. const marker = Optional.from(endContainer.lastChild).getOr(endContainer);
  13678. splitToFormatRoot(wrapWithSiblings(dom, marker, false, 'span', {
  13679. 'id': '_end',
  13680. 'data-mce-type': 'bookmark'
  13681. }));
  13682. unwrap(false);
  13683. return;
  13684. }
  13685. startContainer = wrap$1(dom, startContainer, 'span', {
  13686. 'id': '_start',
  13687. 'data-mce-type': 'bookmark'
  13688. });
  13689. endContainer = wrap$1(dom, endContainer, 'span', {
  13690. 'id': '_end',
  13691. 'data-mce-type': 'bookmark'
  13692. });
  13693. const newRng = dom.createRng();
  13694. newRng.setStartAfter(startContainer);
  13695. newRng.setEndBefore(endContainer);
  13696. walk$3(dom, newRng, nodes => {
  13697. each$e(nodes, n => {
  13698. if (!isBookmarkNode$1(n) && !isBookmarkNode$1(n.parentNode)) {
  13699. splitToFormatRoot(n);
  13700. }
  13701. });
  13702. });
  13703. splitToFormatRoot(startContainer);
  13704. splitToFormatRoot(endContainer);
  13705. startContainer = unwrap(true);
  13706. endContainer = unwrap();
  13707. } else {
  13708. startContainer = endContainer = splitToFormatRoot(startContainer);
  13709. }
  13710. expandedRng.startContainer = startContainer.parentNode ? startContainer.parentNode : startContainer;
  13711. expandedRng.startOffset = dom.nodeIndex(startContainer);
  13712. expandedRng.endContainer = endContainer.parentNode ? endContainer.parentNode : endContainer;
  13713. expandedRng.endOffset = dom.nodeIndex(endContainer) + 1;
  13714. }
  13715. walk$3(dom, expandedRng, nodes => {
  13716. each$e(nodes, process);
  13717. });
  13718. };
  13719. if (node) {
  13720. if (isNode(node)) {
  13721. const rng = dom.createRng();
  13722. rng.setStartBefore(node);
  13723. rng.setEndAfter(node);
  13724. removeRngStyle(rng);
  13725. } else {
  13726. removeRngStyle(node);
  13727. }
  13728. fireFormatRemove(ed, name, node, vars);
  13729. return;
  13730. }
  13731. if (!selection.isCollapsed() || !isInlineFormat(format) || getCellsFromEditor(ed).length) {
  13732. preserveSelection(ed, () => runOnRanges(ed, removeRngStyle), startNode => isInlineFormat(format) && match$2(ed, name, vars, startNode));
  13733. ed.nodeChanged();
  13734. } else {
  13735. removeCaretFormat(ed, name, vars, similar);
  13736. }
  13737. removeListStyleFormats(ed, name, vars);
  13738. fireFormatRemove(ed, name, node, vars);
  13739. };
  13740. const each$6 = Tools.each;
  13741. const mergeTextDecorationsAndColor = (dom, format, vars, node) => {
  13742. const processTextDecorationsAndColor = n => {
  13743. if (isElement$6(n) && isElement$6(n.parentNode) && isEditable$2(n)) {
  13744. const parentTextDecoration = getTextDecoration(dom, n.parentNode);
  13745. if (dom.getStyle(n, 'color') && parentTextDecoration) {
  13746. dom.setStyle(n, 'text-decoration', parentTextDecoration);
  13747. } else if (dom.getStyle(n, 'text-decoration') === parentTextDecoration) {
  13748. dom.setStyle(n, 'text-decoration', null);
  13749. }
  13750. }
  13751. };
  13752. if (format.styles && (format.styles.color || format.styles.textDecoration)) {
  13753. Tools.walk(node, processTextDecorationsAndColor, 'childNodes');
  13754. processTextDecorationsAndColor(node);
  13755. }
  13756. };
  13757. const mergeBackgroundColorAndFontSize = (dom, format, vars, node) => {
  13758. if (format.styles && format.styles.backgroundColor) {
  13759. const hasFontSize = hasStyle(dom, 'fontSize');
  13760. processChildElements(node, elm => hasFontSize(elm) && isEditable$2(elm), applyStyle(dom, 'backgroundColor', replaceVars(format.styles.backgroundColor, vars)));
  13761. }
  13762. };
  13763. const mergeSubSup = (dom, format, vars, node) => {
  13764. if (isInlineFormat(format) && (format.inline === 'sub' || format.inline === 'sup')) {
  13765. const hasFontSize = hasStyle(dom, 'fontSize');
  13766. processChildElements(node, elm => hasFontSize(elm) && isEditable$2(elm), applyStyle(dom, 'fontSize', ''));
  13767. const inverseTagDescendants = filter$5(dom.select(format.inline === 'sup' ? 'sub' : 'sup', node), isEditable$2);
  13768. dom.remove(inverseTagDescendants, true);
  13769. }
  13770. };
  13771. const mergeWithChildren = (editor, formatList, vars, node) => {
  13772. each$6(formatList, format => {
  13773. if (isInlineFormat(format)) {
  13774. each$6(editor.dom.select(format.inline, node), child => {
  13775. if (isElementNode(child)) {
  13776. removeFormat$1(editor, format, vars, child, format.exact ? child : null);
  13777. }
  13778. });
  13779. }
  13780. clearChildStyles(editor.dom, format, node);
  13781. });
  13782. };
  13783. const mergeWithParents = (editor, format, name, vars, node) => {
  13784. const parentNode = node.parentNode;
  13785. if (matchNode(editor, parentNode, name, vars)) {
  13786. if (removeFormat$1(editor, format, vars, node)) {
  13787. return;
  13788. }
  13789. }
  13790. if (format.merge_with_parents && parentNode) {
  13791. editor.dom.getParent(parentNode, parent => {
  13792. if (matchNode(editor, parent, name, vars)) {
  13793. removeFormat$1(editor, format, vars, node);
  13794. return true;
  13795. } else {
  13796. return false;
  13797. }
  13798. });
  13799. }
  13800. };
  13801. const each$5 = Tools.each;
  13802. const canFormatBR = (editor, format, node, parentName) => {
  13803. if (canFormatEmptyLines(editor) && isInlineFormat(format) && node.parentNode) {
  13804. const validBRParentElements = getTextRootBlockElements(editor.schema);
  13805. const hasCaretNodeSibling = sibling(SugarElement.fromDom(node), sibling => isCaretNode(sibling.dom));
  13806. return hasNonNullableKey(validBRParentElements, parentName) && isEmpty$2(SugarElement.fromDom(node.parentNode), false) && !hasCaretNodeSibling;
  13807. } else {
  13808. return false;
  13809. }
  13810. };
  13811. const applyStyles = (dom, elm, format, vars) => {
  13812. each$5(format.styles, (value, name) => {
  13813. dom.setStyle(elm, name, replaceVars(value, vars));
  13814. });
  13815. if (format.styles) {
  13816. const styleVal = dom.getAttrib(elm, 'style');
  13817. if (styleVal) {
  13818. dom.setAttrib(elm, 'data-mce-style', styleVal);
  13819. }
  13820. }
  13821. };
  13822. const applyFormat$1 = (ed, name, vars, node) => {
  13823. const formatList = ed.formatter.get(name);
  13824. const format = formatList[0];
  13825. const isCollapsed = !node && ed.selection.isCollapsed();
  13826. const dom = ed.dom;
  13827. const selection = ed.selection;
  13828. const setElementFormat = (elm, fmt = format) => {
  13829. if (isFunction(fmt.onformat)) {
  13830. fmt.onformat(elm, fmt, vars, node);
  13831. }
  13832. applyStyles(dom, elm, fmt, vars);
  13833. each$5(fmt.attributes, (value, name) => {
  13834. dom.setAttrib(elm, name, replaceVars(value, vars));
  13835. });
  13836. each$5(fmt.classes, value => {
  13837. const newValue = replaceVars(value, vars);
  13838. if (!dom.hasClass(elm, newValue)) {
  13839. dom.addClass(elm, newValue);
  13840. }
  13841. });
  13842. };
  13843. const applyNodeStyle = (formatList, node) => {
  13844. let found = false;
  13845. each$5(formatList, format => {
  13846. if (!isSelectorFormat(format)) {
  13847. return false;
  13848. }
  13849. if (dom.getContentEditable(node) === 'false' && !format.ceFalseOverride) {
  13850. return true;
  13851. }
  13852. if (isNonNullable(format.collapsed) && format.collapsed !== isCollapsed) {
  13853. return true;
  13854. }
  13855. if (dom.is(node, format.selector) && !isCaretNode(node)) {
  13856. setElementFormat(node, format);
  13857. found = true;
  13858. return false;
  13859. }
  13860. return true;
  13861. });
  13862. return found;
  13863. };
  13864. const createWrapElement = wrapName => {
  13865. if (isString(wrapName)) {
  13866. const wrapElm = dom.create(wrapName);
  13867. setElementFormat(wrapElm);
  13868. return wrapElm;
  13869. } else {
  13870. return null;
  13871. }
  13872. };
  13873. const applyRngStyle = (dom, rng, nodeSpecific) => {
  13874. const newWrappers = [];
  13875. let contentEditable = true;
  13876. const wrapName = format.inline || format.block;
  13877. const wrapElm = createWrapElement(wrapName);
  13878. const isMatchingWrappingBlock = node => isWrappingBlockFormat(format) && matchNode(ed, node, name, vars);
  13879. const canRenameBlock = (node, parentName, isEditableDescendant) => {
  13880. const isValidBlockFormatForNode = isNonWrappingBlockFormat(format) && isTextBlock$1(ed.schema, node) && isValid(ed, parentName, wrapName);
  13881. return isEditableDescendant && isValidBlockFormatForNode;
  13882. };
  13883. const canWrapNode = (node, parentName, isEditableDescendant, isWrappableNoneditableElm) => {
  13884. const nodeName = node.nodeName.toLowerCase();
  13885. const isValidWrapNode = isValid(ed, wrapName, nodeName) && isValid(ed, parentName, wrapName);
  13886. const isZwsp$1 = !nodeSpecific && isText$a(node) && isZwsp(node.data);
  13887. const isCaret = isCaretNode(node);
  13888. const isCorrectFormatForNode = !isInlineFormat(format) || !dom.isBlock(node);
  13889. return (isEditableDescendant || isWrappableNoneditableElm) && isValidWrapNode && !isZwsp$1 && !isCaret && isCorrectFormatForNode;
  13890. };
  13891. walk$3(dom, rng, nodes => {
  13892. let currentWrapElm;
  13893. const process = node => {
  13894. let hasContentEditableState = false;
  13895. let lastContentEditable = contentEditable;
  13896. let isWrappableNoneditableElm = false;
  13897. const parentNode = node.parentNode;
  13898. const parentName = parentNode.nodeName.toLowerCase();
  13899. const contentEditableValue = dom.getContentEditable(node);
  13900. if (isNonNullable(contentEditableValue)) {
  13901. lastContentEditable = contentEditable;
  13902. contentEditable = contentEditableValue === 'true';
  13903. hasContentEditableState = true;
  13904. isWrappableNoneditableElm = isWrappableNoneditable(ed, node);
  13905. }
  13906. const isEditableDescendant = contentEditable && !hasContentEditableState;
  13907. if (isBr$6(node) && !canFormatBR(ed, format, node, parentName)) {
  13908. currentWrapElm = null;
  13909. if (isBlockFormat(format)) {
  13910. dom.remove(node);
  13911. }
  13912. return;
  13913. }
  13914. if (isMatchingWrappingBlock(node)) {
  13915. currentWrapElm = null;
  13916. return;
  13917. }
  13918. if (canRenameBlock(node, parentName, isEditableDescendant)) {
  13919. const elm = dom.rename(node, wrapName);
  13920. setElementFormat(elm);
  13921. newWrappers.push(elm);
  13922. currentWrapElm = null;
  13923. return;
  13924. }
  13925. if (isSelectorFormat(format)) {
  13926. let found = applyNodeStyle(formatList, node);
  13927. if (!found && isNonNullable(parentNode) && shouldExpandToSelector(format)) {
  13928. found = applyNodeStyle(formatList, parentNode);
  13929. }
  13930. if (!isInlineFormat(format) || found) {
  13931. currentWrapElm = null;
  13932. return;
  13933. }
  13934. }
  13935. if (isNonNullable(wrapElm) && canWrapNode(node, parentName, isEditableDescendant, isWrappableNoneditableElm)) {
  13936. if (!currentWrapElm) {
  13937. currentWrapElm = dom.clone(wrapElm, false);
  13938. parentNode.insertBefore(currentWrapElm, node);
  13939. newWrappers.push(currentWrapElm);
  13940. }
  13941. if (isWrappableNoneditableElm && hasContentEditableState) {
  13942. contentEditable = lastContentEditable;
  13943. }
  13944. currentWrapElm.appendChild(node);
  13945. } else {
  13946. currentWrapElm = null;
  13947. each$e(from(node.childNodes), process);
  13948. if (hasContentEditableState) {
  13949. contentEditable = lastContentEditable;
  13950. }
  13951. currentWrapElm = null;
  13952. }
  13953. };
  13954. each$e(nodes, process);
  13955. });
  13956. if (format.links === true) {
  13957. each$e(newWrappers, node => {
  13958. const process = node => {
  13959. if (node.nodeName === 'A') {
  13960. setElementFormat(node, format);
  13961. }
  13962. each$e(from(node.childNodes), process);
  13963. };
  13964. process(node);
  13965. });
  13966. }
  13967. each$e(newWrappers, node => {
  13968. const getChildCount = node => {
  13969. let count = 0;
  13970. each$e(node.childNodes, node => {
  13971. if (!isEmptyTextNode$1(node) && !isBookmarkNode$1(node)) {
  13972. count++;
  13973. }
  13974. });
  13975. return count;
  13976. };
  13977. const mergeStyles = node => {
  13978. const childElement = find$2(node.childNodes, isElementNode$1).filter(child => dom.getContentEditable(child) !== 'false' && matchName(dom, child, format));
  13979. return childElement.map(child => {
  13980. const clone = dom.clone(child, false);
  13981. setElementFormat(clone);
  13982. dom.replace(clone, node, true);
  13983. dom.remove(child, true);
  13984. return clone;
  13985. }).getOr(node);
  13986. };
  13987. const childCount = getChildCount(node);
  13988. if ((newWrappers.length > 1 || !dom.isBlock(node)) && childCount === 0) {
  13989. dom.remove(node, true);
  13990. return;
  13991. }
  13992. if (isInlineFormat(format) || isBlockFormat(format) && format.wrapper) {
  13993. if (!format.exact && childCount === 1) {
  13994. node = mergeStyles(node);
  13995. }
  13996. mergeWithChildren(ed, formatList, vars, node);
  13997. mergeWithParents(ed, format, name, vars, node);
  13998. mergeBackgroundColorAndFontSize(dom, format, vars, node);
  13999. mergeTextDecorationsAndColor(dom, format, vars, node);
  14000. mergeSubSup(dom, format, vars, node);
  14001. mergeSiblings(ed, format, vars, node);
  14002. }
  14003. });
  14004. };
  14005. const targetNode = isNode(node) ? node : selection.getNode();
  14006. if (dom.getContentEditable(targetNode) === 'false' && !isWrappableNoneditable(ed, targetNode)) {
  14007. node = targetNode;
  14008. applyNodeStyle(formatList, node);
  14009. fireFormatApply(ed, name, node, vars);
  14010. return;
  14011. }
  14012. if (format) {
  14013. if (node) {
  14014. if (isNode(node)) {
  14015. if (!applyNodeStyle(formatList, node)) {
  14016. const rng = dom.createRng();
  14017. rng.setStartBefore(node);
  14018. rng.setEndAfter(node);
  14019. applyRngStyle(dom, expandRng(dom, rng, formatList), true);
  14020. }
  14021. } else {
  14022. applyRngStyle(dom, node, true);
  14023. }
  14024. } else {
  14025. if (!isCollapsed || !isInlineFormat(format) || getCellsFromEditor(ed).length) {
  14026. selection.setRng(normalize(selection.getRng()));
  14027. preserveSelection(ed, () => {
  14028. runOnRanges(ed, (selectionRng, fake) => {
  14029. const expandedRng = fake ? selectionRng : expandRng(dom, selectionRng, formatList);
  14030. applyRngStyle(dom, expandedRng, false);
  14031. });
  14032. }, always);
  14033. ed.nodeChanged();
  14034. } else {
  14035. applyCaretFormat(ed, name, vars);
  14036. }
  14037. getExpandedListItemFormat(ed.formatter, name).each(liFmt => {
  14038. each$e(getFullySelectedListItems(ed.selection), li => applyStyles(dom, li, liFmt, vars));
  14039. });
  14040. }
  14041. postProcess$1(name, ed);
  14042. }
  14043. fireFormatApply(ed, name, node, vars);
  14044. };
  14045. const hasVars = value => has$2(value, 'vars');
  14046. const setup$t = (registeredFormatListeners, editor) => {
  14047. registeredFormatListeners.set({});
  14048. editor.on('NodeChange', e => {
  14049. updateAndFireChangeCallbacks(editor, e.element, registeredFormatListeners.get());
  14050. });
  14051. editor.on('FormatApply FormatRemove', e => {
  14052. 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));
  14053. updateAndFireChangeCallbacks(editor, element, registeredFormatListeners.get());
  14054. });
  14055. };
  14056. const fallbackElement = editor => editor.selection.getStart();
  14057. const matchingNode = (editor, parents, format, similar, vars) => {
  14058. const isMatchingNode = node => {
  14059. const matchingFormat = editor.formatter.matchNode(node, format, vars !== null && vars !== void 0 ? vars : {}, similar);
  14060. return !isUndefined(matchingFormat);
  14061. };
  14062. const isUnableToMatch = node => {
  14063. if (matchesUnInheritedFormatSelector(editor, node, format)) {
  14064. return true;
  14065. } else {
  14066. if (!similar) {
  14067. return isNonNullable(editor.formatter.matchNode(node, format, vars, true));
  14068. } else {
  14069. return false;
  14070. }
  14071. }
  14072. };
  14073. return findUntil$1(parents, isMatchingNode, isUnableToMatch);
  14074. };
  14075. const getParents = (editor, elm) => {
  14076. const element = elm !== null && elm !== void 0 ? elm : fallbackElement(editor);
  14077. return filter$5(getParents$2(editor.dom, element), node => isElement$6(node) && !isBogus$2(node));
  14078. };
  14079. const updateAndFireChangeCallbacks = (editor, elm, registeredCallbacks) => {
  14080. const parents = getParents(editor, elm);
  14081. each$d(registeredCallbacks, (data, format) => {
  14082. const runIfChanged = spec => {
  14083. const match = matchingNode(editor, parents, format, spec.similar, hasVars(spec) ? spec.vars : undefined);
  14084. const isSet = match.isSome();
  14085. if (spec.state.get() !== isSet) {
  14086. spec.state.set(isSet);
  14087. const node = match.getOr(elm);
  14088. if (hasVars(spec)) {
  14089. spec.callback(isSet, {
  14090. node,
  14091. format,
  14092. parents
  14093. });
  14094. } else {
  14095. each$e(spec.callbacks, callback => callback(isSet, {
  14096. node,
  14097. format,
  14098. parents
  14099. }));
  14100. }
  14101. }
  14102. };
  14103. each$e([
  14104. data.withSimilar,
  14105. data.withoutSimilar
  14106. ], runIfChanged);
  14107. each$e(data.withVars, runIfChanged);
  14108. });
  14109. };
  14110. const addListeners = (editor, registeredFormatListeners, formats, callback, similar, vars) => {
  14111. const formatChangeItems = registeredFormatListeners.get();
  14112. each$e(formats.split(','), format => {
  14113. const group = get$a(formatChangeItems, format).getOrThunk(() => {
  14114. const base = {
  14115. withSimilar: {
  14116. state: Cell(false),
  14117. similar: true,
  14118. callbacks: []
  14119. },
  14120. withoutSimilar: {
  14121. state: Cell(false),
  14122. similar: false,
  14123. callbacks: []
  14124. },
  14125. withVars: []
  14126. };
  14127. formatChangeItems[format] = base;
  14128. return base;
  14129. });
  14130. const getCurrent = () => {
  14131. const parents = getParents(editor);
  14132. return matchingNode(editor, parents, format, similar, vars).isSome();
  14133. };
  14134. if (isUndefined(vars)) {
  14135. const toAppendTo = similar ? group.withSimilar : group.withoutSimilar;
  14136. toAppendTo.callbacks.push(callback);
  14137. if (toAppendTo.callbacks.length === 1) {
  14138. toAppendTo.state.set(getCurrent());
  14139. }
  14140. } else {
  14141. group.withVars.push({
  14142. state: Cell(getCurrent()),
  14143. similar,
  14144. vars,
  14145. callback
  14146. });
  14147. }
  14148. });
  14149. registeredFormatListeners.set(formatChangeItems);
  14150. };
  14151. const removeListeners = (registeredFormatListeners, formats, callback) => {
  14152. const formatChangeItems = registeredFormatListeners.get();
  14153. each$e(formats.split(','), format => get$a(formatChangeItems, format).each(group => {
  14154. formatChangeItems[format] = {
  14155. withSimilar: {
  14156. ...group.withSimilar,
  14157. callbacks: filter$5(group.withSimilar.callbacks, cb => cb !== callback)
  14158. },
  14159. withoutSimilar: {
  14160. ...group.withoutSimilar,
  14161. callbacks: filter$5(group.withoutSimilar.callbacks, cb => cb !== callback)
  14162. },
  14163. withVars: filter$5(group.withVars, item => item.callback !== callback)
  14164. };
  14165. }));
  14166. registeredFormatListeners.set(formatChangeItems);
  14167. };
  14168. const formatChangedInternal = (editor, registeredFormatListeners, formats, callback, similar, vars) => {
  14169. addListeners(editor, registeredFormatListeners, formats, callback, similar, vars);
  14170. return { unbind: () => removeListeners(registeredFormatListeners, formats, callback) };
  14171. };
  14172. const toggle = (editor, name, vars, node) => {
  14173. const fmt = editor.formatter.get(name);
  14174. if (fmt) {
  14175. if (match$2(editor, name, vars, node) && (!('toggle' in fmt[0]) || fmt[0].toggle)) {
  14176. remove$2(editor, name, vars, node);
  14177. } else {
  14178. applyFormat$1(editor, name, vars, node);
  14179. }
  14180. }
  14181. };
  14182. const explode$1 = Tools.explode;
  14183. const create$8 = () => {
  14184. const filters = {};
  14185. const addFilter = (name, callback) => {
  14186. each$e(explode$1(name), name => {
  14187. if (!has$2(filters, name)) {
  14188. filters[name] = {
  14189. name,
  14190. callbacks: []
  14191. };
  14192. }
  14193. filters[name].callbacks.push(callback);
  14194. });
  14195. };
  14196. const getFilters = () => values(filters);
  14197. const removeFilter = (name, callback) => {
  14198. each$e(explode$1(name), name => {
  14199. if (has$2(filters, name)) {
  14200. if (isNonNullable(callback)) {
  14201. const filter = filters[name];
  14202. const newCallbacks = filter$5(filter.callbacks, c => c !== callback);
  14203. if (newCallbacks.length > 0) {
  14204. filter.callbacks = newCallbacks;
  14205. } else {
  14206. delete filters[name];
  14207. }
  14208. } else {
  14209. delete filters[name];
  14210. }
  14211. }
  14212. });
  14213. };
  14214. return {
  14215. addFilter,
  14216. getFilters,
  14217. removeFilter
  14218. };
  14219. };
  14220. const removeAttrs = (node, names) => {
  14221. each$e(names, name => {
  14222. node.attr(name, null);
  14223. });
  14224. };
  14225. const addFontToSpansFilter = (domParser, styles, fontSizes) => {
  14226. domParser.addNodeFilter('font', nodes => {
  14227. each$e(nodes, node => {
  14228. const props = styles.parse(node.attr('style'));
  14229. const color = node.attr('color');
  14230. const face = node.attr('face');
  14231. const size = node.attr('size');
  14232. if (color) {
  14233. props.color = color;
  14234. }
  14235. if (face) {
  14236. props['font-family'] = face;
  14237. }
  14238. if (size) {
  14239. toInt(size).each(num => {
  14240. props['font-size'] = fontSizes[num - 1];
  14241. });
  14242. }
  14243. node.name = 'span';
  14244. node.attr('style', styles.serialize(props));
  14245. removeAttrs(node, [
  14246. 'color',
  14247. 'face',
  14248. 'size'
  14249. ]);
  14250. });
  14251. });
  14252. };
  14253. const addStrikeFilter = (domParser, schema, styles) => {
  14254. domParser.addNodeFilter('strike', nodes => {
  14255. const convertToSTag = schema.type !== 'html4';
  14256. each$e(nodes, node => {
  14257. if (convertToSTag) {
  14258. node.name = 's';
  14259. } else {
  14260. const props = styles.parse(node.attr('style'));
  14261. props['text-decoration'] = 'line-through';
  14262. node.name = 'span';
  14263. node.attr('style', styles.serialize(props));
  14264. }
  14265. });
  14266. });
  14267. };
  14268. const addFilters = (domParser, settings, schema) => {
  14269. var _a;
  14270. const styles = Styles();
  14271. if (settings.convert_fonts_to_spans) {
  14272. addFontToSpansFilter(domParser, styles, Tools.explode((_a = settings.font_size_legacy_values) !== null && _a !== void 0 ? _a : ''));
  14273. }
  14274. addStrikeFilter(domParser, schema, styles);
  14275. };
  14276. const register$5 = (domParser, settings, schema) => {
  14277. if (settings.inline_styles) {
  14278. addFilters(domParser, settings, schema);
  14279. }
  14280. };
  14281. const blobUriToBlob = url => fetch(url).then(res => res.ok ? res.blob() : Promise.reject()).catch(() => Promise.reject({
  14282. message: `Cannot convert ${ url } to Blob. Resource might not exist or is inaccessible.`,
  14283. uriType: 'blob'
  14284. }));
  14285. const extractBase64Data = data => {
  14286. const matches = /([a-z0-9+\/=\s]+)/i.exec(data);
  14287. return matches ? matches[1] : '';
  14288. };
  14289. const parseDataUri = uri => {
  14290. const [type, ...rest] = uri.split(',');
  14291. const data = rest.join(',');
  14292. const matches = /data:([^/]+\/[^;]+)(;.+)?/.exec(type);
  14293. if (matches) {
  14294. const base64Encoded = matches[2] === ';base64';
  14295. const extractedData = base64Encoded ? extractBase64Data(data) : decodeURIComponent(data);
  14296. return Optional.some({
  14297. type: matches[1],
  14298. data: extractedData,
  14299. base64Encoded
  14300. });
  14301. } else {
  14302. return Optional.none();
  14303. }
  14304. };
  14305. const buildBlob = (type, data, base64Encoded = true) => {
  14306. let str = data;
  14307. if (base64Encoded) {
  14308. try {
  14309. str = atob(data);
  14310. } catch (e) {
  14311. return Optional.none();
  14312. }
  14313. }
  14314. const arr = new Uint8Array(str.length);
  14315. for (let i = 0; i < arr.length; i++) {
  14316. arr[i] = str.charCodeAt(i);
  14317. }
  14318. return Optional.some(new Blob([arr], { type }));
  14319. };
  14320. const dataUriToBlob = uri => {
  14321. return new Promise((resolve, reject) => {
  14322. parseDataUri(uri).bind(({type, data, base64Encoded}) => buildBlob(type, data, base64Encoded)).fold(() => reject('Invalid data URI'), resolve);
  14323. });
  14324. };
  14325. const uriToBlob = url => {
  14326. if (startsWith(url, 'blob:')) {
  14327. return blobUriToBlob(url);
  14328. } else if (startsWith(url, 'data:')) {
  14329. return dataUriToBlob(url);
  14330. } else {
  14331. return Promise.reject('Unknown URI format');
  14332. }
  14333. };
  14334. const blobToDataUri = blob => {
  14335. return new Promise((resolve, reject) => {
  14336. const reader = new FileReader();
  14337. reader.onloadend = () => {
  14338. resolve(reader.result);
  14339. };
  14340. reader.onerror = () => {
  14341. var _a;
  14342. reject((_a = reader.error) === null || _a === void 0 ? void 0 : _a.message);
  14343. };
  14344. reader.readAsDataURL(blob);
  14345. });
  14346. };
  14347. let count$1 = 0;
  14348. const uniqueId$1 = prefix => {
  14349. return (prefix || 'blobid') + count$1++;
  14350. };
  14351. const processDataUri = (dataUri, base64Only, generateBlobInfo) => {
  14352. return parseDataUri(dataUri).bind(({data, type, base64Encoded}) => {
  14353. if (base64Only && !base64Encoded) {
  14354. return Optional.none();
  14355. } else {
  14356. const base64 = base64Encoded ? data : btoa(data);
  14357. return generateBlobInfo(base64, type);
  14358. }
  14359. });
  14360. };
  14361. const createBlobInfo$1 = (blobCache, blob, base64) => {
  14362. const blobInfo = blobCache.create(uniqueId$1(), blob, base64);
  14363. blobCache.add(blobInfo);
  14364. return blobInfo;
  14365. };
  14366. const dataUriToBlobInfo = (blobCache, dataUri, base64Only = false) => {
  14367. return processDataUri(dataUri, base64Only, (base64, type) => Optional.from(blobCache.getByData(base64, type)).orThunk(() => buildBlob(type, base64).map(blob => createBlobInfo$1(blobCache, blob, base64))));
  14368. };
  14369. const imageToBlobInfo = (blobCache, imageSrc) => {
  14370. const invalidDataUri = () => Promise.reject('Invalid data URI');
  14371. if (startsWith(imageSrc, 'blob:')) {
  14372. const blobInfo = blobCache.getByUri(imageSrc);
  14373. if (isNonNullable(blobInfo)) {
  14374. return Promise.resolve(blobInfo);
  14375. } else {
  14376. return uriToBlob(imageSrc).then(blob => {
  14377. return blobToDataUri(blob).then(dataUri => {
  14378. return processDataUri(dataUri, false, base64 => {
  14379. return Optional.some(createBlobInfo$1(blobCache, blob, base64));
  14380. }).getOrThunk(invalidDataUri);
  14381. });
  14382. });
  14383. }
  14384. } else if (startsWith(imageSrc, 'data:')) {
  14385. return dataUriToBlobInfo(blobCache, imageSrc).fold(invalidDataUri, blobInfo => Promise.resolve(blobInfo));
  14386. } else {
  14387. return Promise.reject('Unknown image data format');
  14388. }
  14389. };
  14390. const isBogusImage = img => isNonNullable(img.attr('data-mce-bogus'));
  14391. const isInternalImageSource = img => img.attr('src') === Env.transparentSrc || isNonNullable(img.attr('data-mce-placeholder'));
  14392. const registerBase64ImageFilter = (parser, settings) => {
  14393. const {blob_cache: blobCache} = settings;
  14394. if (blobCache) {
  14395. const processImage = img => {
  14396. const inputSrc = img.attr('src');
  14397. if (isInternalImageSource(img) || isBogusImage(img) || isNullable(inputSrc)) {
  14398. return;
  14399. }
  14400. dataUriToBlobInfo(blobCache, inputSrc, true).each(blobInfo => {
  14401. img.attr('src', blobInfo.blobUri());
  14402. });
  14403. };
  14404. parser.addAttributeFilter('src', nodes => each$e(nodes, processImage));
  14405. }
  14406. };
  14407. const register$4 = (parser, settings) => {
  14408. const schema = parser.schema;
  14409. if (settings.remove_trailing_brs) {
  14410. parser.addNodeFilter('br', (nodes, _, args) => {
  14411. const blockElements = Tools.extend({}, schema.getBlockElements());
  14412. const nonEmptyElements = schema.getNonEmptyElements();
  14413. const whitespaceElements = schema.getWhitespaceElements();
  14414. blockElements.body = 1;
  14415. const isBlock = node => node.name in blockElements && isTransparentAstInline(schema, node);
  14416. for (let i = 0, l = nodes.length; i < l; i++) {
  14417. let node = nodes[i];
  14418. let parent = node.parent;
  14419. if (parent && blockElements[parent.name] && node === parent.lastChild) {
  14420. let prev = node.prev;
  14421. while (prev) {
  14422. const prevName = prev.name;
  14423. if (prevName !== 'span' || prev.attr('data-mce-type') !== 'bookmark') {
  14424. if (prevName === 'br') {
  14425. node = null;
  14426. }
  14427. break;
  14428. }
  14429. prev = prev.prev;
  14430. }
  14431. if (node) {
  14432. node.remove();
  14433. if (isEmpty(schema, nonEmptyElements, whitespaceElements, parent)) {
  14434. const elementRule = schema.getElementRule(parent.name);
  14435. if (elementRule) {
  14436. if (elementRule.removeEmpty) {
  14437. parent.remove();
  14438. } else if (elementRule.paddEmpty) {
  14439. paddEmptyNode(args, isBlock, parent);
  14440. }
  14441. }
  14442. }
  14443. }
  14444. } else {
  14445. let lastParent = node;
  14446. while (parent && parent.firstChild === lastParent && parent.lastChild === lastParent) {
  14447. lastParent = parent;
  14448. if (blockElements[parent.name]) {
  14449. break;
  14450. }
  14451. parent = parent.parent;
  14452. }
  14453. if (lastParent === parent) {
  14454. const textNode = new AstNode('#text', 3);
  14455. textNode.value = nbsp;
  14456. node.replace(textNode);
  14457. }
  14458. }
  14459. }
  14460. });
  14461. }
  14462. parser.addAttributeFilter('href', nodes => {
  14463. let i = nodes.length;
  14464. const appendRel = rel => {
  14465. const parts = rel.split(' ').filter(p => p.length > 0);
  14466. return parts.concat(['noopener']).sort().join(' ');
  14467. };
  14468. const addNoOpener = rel => {
  14469. const newRel = rel ? Tools.trim(rel) : '';
  14470. if (!/\b(noopener)\b/g.test(newRel)) {
  14471. return appendRel(newRel);
  14472. } else {
  14473. return newRel;
  14474. }
  14475. };
  14476. if (!settings.allow_unsafe_link_target) {
  14477. while (i--) {
  14478. const node = nodes[i];
  14479. if (node.name === 'a' && node.attr('target') === '_blank') {
  14480. node.attr('rel', addNoOpener(node.attr('rel')));
  14481. }
  14482. }
  14483. }
  14484. });
  14485. if (!settings.allow_html_in_named_anchor) {
  14486. parser.addAttributeFilter('id,name', nodes => {
  14487. let i = nodes.length, sibling, prevSibling, parent, node;
  14488. while (i--) {
  14489. node = nodes[i];
  14490. if (node.name === 'a' && node.firstChild && !node.attr('href')) {
  14491. parent = node.parent;
  14492. sibling = node.lastChild;
  14493. while (sibling && parent) {
  14494. prevSibling = sibling.prev;
  14495. parent.insert(sibling, node);
  14496. sibling = prevSibling;
  14497. }
  14498. }
  14499. }
  14500. });
  14501. }
  14502. if (settings.fix_list_elements) {
  14503. parser.addNodeFilter('ul,ol', nodes => {
  14504. let i = nodes.length, node, parentNode;
  14505. while (i--) {
  14506. node = nodes[i];
  14507. parentNode = node.parent;
  14508. if (parentNode && (parentNode.name === 'ul' || parentNode.name === 'ol')) {
  14509. if (node.prev && node.prev.name === 'li') {
  14510. node.prev.append(node);
  14511. } else {
  14512. const li = new AstNode('li', 1);
  14513. li.attr('style', 'list-style-type: none');
  14514. node.wrap(li);
  14515. }
  14516. }
  14517. }
  14518. });
  14519. }
  14520. const validClasses = schema.getValidClasses();
  14521. if (settings.validate && validClasses) {
  14522. parser.addAttributeFilter('class', nodes => {
  14523. var _a;
  14524. let i = nodes.length;
  14525. while (i--) {
  14526. const node = nodes[i];
  14527. const clazz = (_a = node.attr('class')) !== null && _a !== void 0 ? _a : '';
  14528. const classList = Tools.explode(clazz, ' ');
  14529. let classValue = '';
  14530. for (let ci = 0; ci < classList.length; ci++) {
  14531. const className = classList[ci];
  14532. let valid = false;
  14533. let validClassesMap = validClasses['*'];
  14534. if (validClassesMap && validClassesMap[className]) {
  14535. valid = true;
  14536. }
  14537. validClassesMap = validClasses[node.name];
  14538. if (!valid && validClassesMap && validClassesMap[className]) {
  14539. valid = true;
  14540. }
  14541. if (valid) {
  14542. if (classValue) {
  14543. classValue += ' ';
  14544. }
  14545. classValue += className;
  14546. }
  14547. }
  14548. if (!classValue.length) {
  14549. classValue = null;
  14550. }
  14551. node.attr('class', classValue);
  14552. }
  14553. });
  14554. }
  14555. registerBase64ImageFilter(parser, settings);
  14556. };
  14557. function _typeof(obj) {
  14558. '@babel/helpers - typeof';
  14559. return _typeof = 'function' == typeof Symbol && 'symbol' == typeof Symbol.iterator ? function (obj) {
  14560. return typeof obj;
  14561. } : function (obj) {
  14562. return obj && 'function' == typeof Symbol && obj.constructor === Symbol && obj !== Symbol.prototype ? 'symbol' : typeof obj;
  14563. }, _typeof(obj);
  14564. }
  14565. function _setPrototypeOf(o, p) {
  14566. _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) {
  14567. o.__proto__ = p;
  14568. return o;
  14569. };
  14570. return _setPrototypeOf(o, p);
  14571. }
  14572. function _isNativeReflectConstruct() {
  14573. if (typeof Reflect === 'undefined' || !Reflect.construct)
  14574. return false;
  14575. if (Reflect.construct.sham)
  14576. return false;
  14577. if (typeof Proxy === 'function')
  14578. return true;
  14579. try {
  14580. Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {
  14581. }));
  14582. return true;
  14583. } catch (e) {
  14584. return false;
  14585. }
  14586. }
  14587. function _construct(Parent, args, Class) {
  14588. if (_isNativeReflectConstruct()) {
  14589. _construct = Reflect.construct;
  14590. } else {
  14591. _construct = function _construct(Parent, args, Class) {
  14592. var a = [null];
  14593. a.push.apply(a, args);
  14594. var Constructor = Function.bind.apply(Parent, a);
  14595. var instance = new Constructor();
  14596. if (Class)
  14597. _setPrototypeOf(instance, Class.prototype);
  14598. return instance;
  14599. };
  14600. }
  14601. return _construct.apply(null, arguments);
  14602. }
  14603. function _toConsumableArray(arr) {
  14604. return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _unsupportedIterableToArray(arr) || _nonIterableSpread();
  14605. }
  14606. function _arrayWithoutHoles(arr) {
  14607. if (Array.isArray(arr))
  14608. return _arrayLikeToArray(arr);
  14609. }
  14610. function _iterableToArray(iter) {
  14611. if (typeof Symbol !== 'undefined' && iter[Symbol.iterator] != null || iter['@@iterator'] != null)
  14612. return Array.from(iter);
  14613. }
  14614. function _unsupportedIterableToArray(o, minLen) {
  14615. if (!o)
  14616. return;
  14617. if (typeof o === 'string')
  14618. return _arrayLikeToArray(o, minLen);
  14619. var n = Object.prototype.toString.call(o).slice(8, -1);
  14620. if (n === 'Object' && o.constructor)
  14621. n = o.constructor.name;
  14622. if (n === 'Map' || n === 'Set')
  14623. return Array.from(o);
  14624. if (n === 'Arguments' || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n))
  14625. return _arrayLikeToArray(o, minLen);
  14626. }
  14627. function _arrayLikeToArray(arr, len) {
  14628. if (len == null || len > arr.length)
  14629. len = arr.length;
  14630. for (var i = 0, arr2 = new Array(len); i < len; i++)
  14631. arr2[i] = arr[i];
  14632. return arr2;
  14633. }
  14634. function _nonIterableSpread() {
  14635. throw new TypeError('Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.');
  14636. }
  14637. var hasOwnProperty = Object.hasOwnProperty, setPrototypeOf = Object.setPrototypeOf, isFrozen = Object.isFrozen, getPrototypeOf = Object.getPrototypeOf, getOwnPropertyDescriptor = Object.getOwnPropertyDescriptor;
  14638. var freeze = Object.freeze, seal = Object.seal, create$7 = Object.create;
  14639. var _ref = typeof Reflect !== 'undefined' && Reflect, apply = _ref.apply, construct = _ref.construct;
  14640. if (!apply) {
  14641. apply = function apply(fun, thisValue, args) {
  14642. return fun.apply(thisValue, args);
  14643. };
  14644. }
  14645. if (!freeze) {
  14646. freeze = function freeze(x) {
  14647. return x;
  14648. };
  14649. }
  14650. if (!seal) {
  14651. seal = function seal(x) {
  14652. return x;
  14653. };
  14654. }
  14655. if (!construct) {
  14656. construct = function construct(Func, args) {
  14657. return _construct(Func, _toConsumableArray(args));
  14658. };
  14659. }
  14660. var arrayForEach = unapply(Array.prototype.forEach);
  14661. var arrayPop = unapply(Array.prototype.pop);
  14662. var arrayPush = unapply(Array.prototype.push);
  14663. var stringToLowerCase = unapply(String.prototype.toLowerCase);
  14664. var stringMatch = unapply(String.prototype.match);
  14665. var stringReplace = unapply(String.prototype.replace);
  14666. var stringIndexOf = unapply(String.prototype.indexOf);
  14667. var stringTrim = unapply(String.prototype.trim);
  14668. var regExpTest = unapply(RegExp.prototype.test);
  14669. var typeErrorCreate = unconstruct(TypeError);
  14670. function unapply(func) {
  14671. return function (thisArg) {
  14672. for (var _len = arguments.length, args = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
  14673. args[_key - 1] = arguments[_key];
  14674. }
  14675. return apply(func, thisArg, args);
  14676. };
  14677. }
  14678. function unconstruct(func) {
  14679. return function () {
  14680. for (var _len2 = arguments.length, args = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) {
  14681. args[_key2] = arguments[_key2];
  14682. }
  14683. return construct(func, args);
  14684. };
  14685. }
  14686. function addToSet(set, array) {
  14687. if (setPrototypeOf) {
  14688. setPrototypeOf(set, null);
  14689. }
  14690. var l = array.length;
  14691. while (l--) {
  14692. var element = array[l];
  14693. if (typeof element === 'string') {
  14694. var lcElement = stringToLowerCase(element);
  14695. if (lcElement !== element) {
  14696. if (!isFrozen(array)) {
  14697. array[l] = lcElement;
  14698. }
  14699. element = lcElement;
  14700. }
  14701. }
  14702. set[element] = true;
  14703. }
  14704. return set;
  14705. }
  14706. function clone(object) {
  14707. var newObject = create$7(null);
  14708. var property;
  14709. for (property in object) {
  14710. if (apply(hasOwnProperty, object, [property])) {
  14711. newObject[property] = object[property];
  14712. }
  14713. }
  14714. return newObject;
  14715. }
  14716. function lookupGetter(object, prop) {
  14717. while (object !== null) {
  14718. var desc = getOwnPropertyDescriptor(object, prop);
  14719. if (desc) {
  14720. if (desc.get) {
  14721. return unapply(desc.get);
  14722. }
  14723. if (typeof desc.value === 'function') {
  14724. return unapply(desc.value);
  14725. }
  14726. }
  14727. object = getPrototypeOf(object);
  14728. }
  14729. function fallbackValue(element) {
  14730. console.warn('fallback value for', element);
  14731. return null;
  14732. }
  14733. return fallbackValue;
  14734. }
  14735. var html$1 = freeze([
  14736. 'a',
  14737. 'abbr',
  14738. 'acronym',
  14739. 'address',
  14740. 'area',
  14741. 'article',
  14742. 'aside',
  14743. 'audio',
  14744. 'b',
  14745. 'bdi',
  14746. 'bdo',
  14747. 'big',
  14748. 'blink',
  14749. 'blockquote',
  14750. 'body',
  14751. 'br',
  14752. 'button',
  14753. 'canvas',
  14754. 'caption',
  14755. 'center',
  14756. 'cite',
  14757. 'code',
  14758. 'col',
  14759. 'colgroup',
  14760. 'content',
  14761. 'data',
  14762. 'datalist',
  14763. 'dd',
  14764. 'decorator',
  14765. 'del',
  14766. 'details',
  14767. 'dfn',
  14768. 'dialog',
  14769. 'dir',
  14770. 'div',
  14771. 'dl',
  14772. 'dt',
  14773. 'element',
  14774. 'em',
  14775. 'fieldset',
  14776. 'figcaption',
  14777. 'figure',
  14778. 'font',
  14779. 'footer',
  14780. 'form',
  14781. 'h1',
  14782. 'h2',
  14783. 'h3',
  14784. 'h4',
  14785. 'h5',
  14786. 'h6',
  14787. 'head',
  14788. 'header',
  14789. 'hgroup',
  14790. 'hr',
  14791. 'html',
  14792. 'i',
  14793. 'img',
  14794. 'input',
  14795. 'ins',
  14796. 'kbd',
  14797. 'label',
  14798. 'legend',
  14799. 'li',
  14800. 'main',
  14801. 'map',
  14802. 'mark',
  14803. 'marquee',
  14804. 'menu',
  14805. 'menuitem',
  14806. 'meter',
  14807. 'nav',
  14808. 'nobr',
  14809. 'ol',
  14810. 'optgroup',
  14811. 'option',
  14812. 'output',
  14813. 'p',
  14814. 'picture',
  14815. 'pre',
  14816. 'progress',
  14817. 'q',
  14818. 'rp',
  14819. 'rt',
  14820. 'ruby',
  14821. 's',
  14822. 'samp',
  14823. 'section',
  14824. 'select',
  14825. 'shadow',
  14826. 'small',
  14827. 'source',
  14828. 'spacer',
  14829. 'span',
  14830. 'strike',
  14831. 'strong',
  14832. 'style',
  14833. 'sub',
  14834. 'summary',
  14835. 'sup',
  14836. 'table',
  14837. 'tbody',
  14838. 'td',
  14839. 'template',
  14840. 'textarea',
  14841. 'tfoot',
  14842. 'th',
  14843. 'thead',
  14844. 'time',
  14845. 'tr',
  14846. 'track',
  14847. 'tt',
  14848. 'u',
  14849. 'ul',
  14850. 'var',
  14851. 'video',
  14852. 'wbr'
  14853. ]);
  14854. var svg$1 = freeze([
  14855. 'svg',
  14856. 'a',
  14857. 'altglyph',
  14858. 'altglyphdef',
  14859. 'altglyphitem',
  14860. 'animatecolor',
  14861. 'animatemotion',
  14862. 'animatetransform',
  14863. 'circle',
  14864. 'clippath',
  14865. 'defs',
  14866. 'desc',
  14867. 'ellipse',
  14868. 'filter',
  14869. 'font',
  14870. 'g',
  14871. 'glyph',
  14872. 'glyphref',
  14873. 'hkern',
  14874. 'image',
  14875. 'line',
  14876. 'lineargradient',
  14877. 'marker',
  14878. 'mask',
  14879. 'metadata',
  14880. 'mpath',
  14881. 'path',
  14882. 'pattern',
  14883. 'polygon',
  14884. 'polyline',
  14885. 'radialgradient',
  14886. 'rect',
  14887. 'stop',
  14888. 'style',
  14889. 'switch',
  14890. 'symbol',
  14891. 'text',
  14892. 'textpath',
  14893. 'title',
  14894. 'tref',
  14895. 'tspan',
  14896. 'view',
  14897. 'vkern'
  14898. ]);
  14899. var svgFilters = freeze([
  14900. 'feBlend',
  14901. 'feColorMatrix',
  14902. 'feComponentTransfer',
  14903. 'feComposite',
  14904. 'feConvolveMatrix',
  14905. 'feDiffuseLighting',
  14906. 'feDisplacementMap',
  14907. 'feDistantLight',
  14908. 'feFlood',
  14909. 'feFuncA',
  14910. 'feFuncB',
  14911. 'feFuncG',
  14912. 'feFuncR',
  14913. 'feGaussianBlur',
  14914. 'feImage',
  14915. 'feMerge',
  14916. 'feMergeNode',
  14917. 'feMorphology',
  14918. 'feOffset',
  14919. 'fePointLight',
  14920. 'feSpecularLighting',
  14921. 'feSpotLight',
  14922. 'feTile',
  14923. 'feTurbulence'
  14924. ]);
  14925. var svgDisallowed = freeze([
  14926. 'animate',
  14927. 'color-profile',
  14928. 'cursor',
  14929. 'discard',
  14930. 'fedropshadow',
  14931. 'font-face',
  14932. 'font-face-format',
  14933. 'font-face-name',
  14934. 'font-face-src',
  14935. 'font-face-uri',
  14936. 'foreignobject',
  14937. 'hatch',
  14938. 'hatchpath',
  14939. 'mesh',
  14940. 'meshgradient',
  14941. 'meshpatch',
  14942. 'meshrow',
  14943. 'missing-glyph',
  14944. 'script',
  14945. 'set',
  14946. 'solidcolor',
  14947. 'unknown',
  14948. 'use'
  14949. ]);
  14950. var mathMl$1 = freeze([
  14951. 'math',
  14952. 'menclose',
  14953. 'merror',
  14954. 'mfenced',
  14955. 'mfrac',
  14956. 'mglyph',
  14957. 'mi',
  14958. 'mlabeledtr',
  14959. 'mmultiscripts',
  14960. 'mn',
  14961. 'mo',
  14962. 'mover',
  14963. 'mpadded',
  14964. 'mphantom',
  14965. 'mroot',
  14966. 'mrow',
  14967. 'ms',
  14968. 'mspace',
  14969. 'msqrt',
  14970. 'mstyle',
  14971. 'msub',
  14972. 'msup',
  14973. 'msubsup',
  14974. 'mtable',
  14975. 'mtd',
  14976. 'mtext',
  14977. 'mtr',
  14978. 'munder',
  14979. 'munderover'
  14980. ]);
  14981. var mathMlDisallowed = freeze([
  14982. 'maction',
  14983. 'maligngroup',
  14984. 'malignmark',
  14985. 'mlongdiv',
  14986. 'mscarries',
  14987. 'mscarry',
  14988. 'msgroup',
  14989. 'mstack',
  14990. 'msline',
  14991. 'msrow',
  14992. 'semantics',
  14993. 'annotation',
  14994. 'annotation-xml',
  14995. 'mprescripts',
  14996. 'none'
  14997. ]);
  14998. var text = freeze(['#text']);
  14999. var html = freeze([
  15000. 'accept',
  15001. 'action',
  15002. 'align',
  15003. 'alt',
  15004. 'autocapitalize',
  15005. 'autocomplete',
  15006. 'autopictureinpicture',
  15007. 'autoplay',
  15008. 'background',
  15009. 'bgcolor',
  15010. 'border',
  15011. 'capture',
  15012. 'cellpadding',
  15013. 'cellspacing',
  15014. 'checked',
  15015. 'cite',
  15016. 'class',
  15017. 'clear',
  15018. 'color',
  15019. 'cols',
  15020. 'colspan',
  15021. 'controls',
  15022. 'controlslist',
  15023. 'coords',
  15024. 'crossorigin',
  15025. 'datetime',
  15026. 'decoding',
  15027. 'default',
  15028. 'dir',
  15029. 'disabled',
  15030. 'disablepictureinpicture',
  15031. 'disableremoteplayback',
  15032. 'download',
  15033. 'draggable',
  15034. 'enctype',
  15035. 'enterkeyhint',
  15036. 'face',
  15037. 'for',
  15038. 'headers',
  15039. 'height',
  15040. 'hidden',
  15041. 'high',
  15042. 'href',
  15043. 'hreflang',
  15044. 'id',
  15045. 'inputmode',
  15046. 'integrity',
  15047. 'ismap',
  15048. 'kind',
  15049. 'label',
  15050. 'lang',
  15051. 'list',
  15052. 'loading',
  15053. 'loop',
  15054. 'low',
  15055. 'max',
  15056. 'maxlength',
  15057. 'media',
  15058. 'method',
  15059. 'min',
  15060. 'minlength',
  15061. 'multiple',
  15062. 'muted',
  15063. 'name',
  15064. 'nonce',
  15065. 'noshade',
  15066. 'novalidate',
  15067. 'nowrap',
  15068. 'open',
  15069. 'optimum',
  15070. 'pattern',
  15071. 'placeholder',
  15072. 'playsinline',
  15073. 'poster',
  15074. 'preload',
  15075. 'pubdate',
  15076. 'radiogroup',
  15077. 'readonly',
  15078. 'rel',
  15079. 'required',
  15080. 'rev',
  15081. 'reversed',
  15082. 'role',
  15083. 'rows',
  15084. 'rowspan',
  15085. 'spellcheck',
  15086. 'scope',
  15087. 'selected',
  15088. 'shape',
  15089. 'size',
  15090. 'sizes',
  15091. 'span',
  15092. 'srclang',
  15093. 'start',
  15094. 'src',
  15095. 'srcset',
  15096. 'step',
  15097. 'style',
  15098. 'summary',
  15099. 'tabindex',
  15100. 'title',
  15101. 'translate',
  15102. 'type',
  15103. 'usemap',
  15104. 'valign',
  15105. 'value',
  15106. 'width',
  15107. 'xmlns',
  15108. 'slot'
  15109. ]);
  15110. var svg = freeze([
  15111. 'accent-height',
  15112. 'accumulate',
  15113. 'additive',
  15114. 'alignment-baseline',
  15115. 'ascent',
  15116. 'attributename',
  15117. 'attributetype',
  15118. 'azimuth',
  15119. 'basefrequency',
  15120. 'baseline-shift',
  15121. 'begin',
  15122. 'bias',
  15123. 'by',
  15124. 'class',
  15125. 'clip',
  15126. 'clippathunits',
  15127. 'clip-path',
  15128. 'clip-rule',
  15129. 'color',
  15130. 'color-interpolation',
  15131. 'color-interpolation-filters',
  15132. 'color-profile',
  15133. 'color-rendering',
  15134. 'cx',
  15135. 'cy',
  15136. 'd',
  15137. 'dx',
  15138. 'dy',
  15139. 'diffuseconstant',
  15140. 'direction',
  15141. 'display',
  15142. 'divisor',
  15143. 'dur',
  15144. 'edgemode',
  15145. 'elevation',
  15146. 'end',
  15147. 'fill',
  15148. 'fill-opacity',
  15149. 'fill-rule',
  15150. 'filter',
  15151. 'filterunits',
  15152. 'flood-color',
  15153. 'flood-opacity',
  15154. 'font-family',
  15155. 'font-size',
  15156. 'font-size-adjust',
  15157. 'font-stretch',
  15158. 'font-style',
  15159. 'font-variant',
  15160. 'font-weight',
  15161. 'fx',
  15162. 'fy',
  15163. 'g1',
  15164. 'g2',
  15165. 'glyph-name',
  15166. 'glyphref',
  15167. 'gradientunits',
  15168. 'gradienttransform',
  15169. 'height',
  15170. 'href',
  15171. 'id',
  15172. 'image-rendering',
  15173. 'in',
  15174. 'in2',
  15175. 'k',
  15176. 'k1',
  15177. 'k2',
  15178. 'k3',
  15179. 'k4',
  15180. 'kerning',
  15181. 'keypoints',
  15182. 'keysplines',
  15183. 'keytimes',
  15184. 'lang',
  15185. 'lengthadjust',
  15186. 'letter-spacing',
  15187. 'kernelmatrix',
  15188. 'kernelunitlength',
  15189. 'lighting-color',
  15190. 'local',
  15191. 'marker-end',
  15192. 'marker-mid',
  15193. 'marker-start',
  15194. 'markerheight',
  15195. 'markerunits',
  15196. 'markerwidth',
  15197. 'maskcontentunits',
  15198. 'maskunits',
  15199. 'max',
  15200. 'mask',
  15201. 'media',
  15202. 'method',
  15203. 'mode',
  15204. 'min',
  15205. 'name',
  15206. 'numoctaves',
  15207. 'offset',
  15208. 'operator',
  15209. 'opacity',
  15210. 'order',
  15211. 'orient',
  15212. 'orientation',
  15213. 'origin',
  15214. 'overflow',
  15215. 'paint-order',
  15216. 'path',
  15217. 'pathlength',
  15218. 'patterncontentunits',
  15219. 'patterntransform',
  15220. 'patternunits',
  15221. 'points',
  15222. 'preservealpha',
  15223. 'preserveaspectratio',
  15224. 'primitiveunits',
  15225. 'r',
  15226. 'rx',
  15227. 'ry',
  15228. 'radius',
  15229. 'refx',
  15230. 'refy',
  15231. 'repeatcount',
  15232. 'repeatdur',
  15233. 'restart',
  15234. 'result',
  15235. 'rotate',
  15236. 'scale',
  15237. 'seed',
  15238. 'shape-rendering',
  15239. 'specularconstant',
  15240. 'specularexponent',
  15241. 'spreadmethod',
  15242. 'startoffset',
  15243. 'stddeviation',
  15244. 'stitchtiles',
  15245. 'stop-color',
  15246. 'stop-opacity',
  15247. 'stroke-dasharray',
  15248. 'stroke-dashoffset',
  15249. 'stroke-linecap',
  15250. 'stroke-linejoin',
  15251. 'stroke-miterlimit',
  15252. 'stroke-opacity',
  15253. 'stroke',
  15254. 'stroke-width',
  15255. 'style',
  15256. 'surfacescale',
  15257. 'systemlanguage',
  15258. 'tabindex',
  15259. 'targetx',
  15260. 'targety',
  15261. 'transform',
  15262. 'transform-origin',
  15263. 'text-anchor',
  15264. 'text-decoration',
  15265. 'text-rendering',
  15266. 'textlength',
  15267. 'type',
  15268. 'u1',
  15269. 'u2',
  15270. 'unicode',
  15271. 'values',
  15272. 'viewbox',
  15273. 'visibility',
  15274. 'version',
  15275. 'vert-adv-y',
  15276. 'vert-origin-x',
  15277. 'vert-origin-y',
  15278. 'width',
  15279. 'word-spacing',
  15280. 'wrap',
  15281. 'writing-mode',
  15282. 'xchannelselector',
  15283. 'ychannelselector',
  15284. 'x',
  15285. 'x1',
  15286. 'x2',
  15287. 'xmlns',
  15288. 'y',
  15289. 'y1',
  15290. 'y2',
  15291. 'z',
  15292. 'zoomandpan'
  15293. ]);
  15294. var mathMl = freeze([
  15295. 'accent',
  15296. 'accentunder',
  15297. 'align',
  15298. 'bevelled',
  15299. 'close',
  15300. 'columnsalign',
  15301. 'columnlines',
  15302. 'columnspan',
  15303. 'denomalign',
  15304. 'depth',
  15305. 'dir',
  15306. 'display',
  15307. 'displaystyle',
  15308. 'encoding',
  15309. 'fence',
  15310. 'frame',
  15311. 'height',
  15312. 'href',
  15313. 'id',
  15314. 'largeop',
  15315. 'length',
  15316. 'linethickness',
  15317. 'lspace',
  15318. 'lquote',
  15319. 'mathbackground',
  15320. 'mathcolor',
  15321. 'mathsize',
  15322. 'mathvariant',
  15323. 'maxsize',
  15324. 'minsize',
  15325. 'movablelimits',
  15326. 'notation',
  15327. 'numalign',
  15328. 'open',
  15329. 'rowalign',
  15330. 'rowlines',
  15331. 'rowspacing',
  15332. 'rowspan',
  15333. 'rspace',
  15334. 'rquote',
  15335. 'scriptlevel',
  15336. 'scriptminsize',
  15337. 'scriptsizemultiplier',
  15338. 'selection',
  15339. 'separator',
  15340. 'separators',
  15341. 'stretchy',
  15342. 'subscriptshift',
  15343. 'supscriptshift',
  15344. 'symmetric',
  15345. 'voffset',
  15346. 'width',
  15347. 'xmlns'
  15348. ]);
  15349. var xml = freeze([
  15350. 'xlink:href',
  15351. 'xml:id',
  15352. 'xlink:title',
  15353. 'xml:space',
  15354. 'xmlns:xlink'
  15355. ]);
  15356. var MUSTACHE_EXPR = seal(/\{\{[\w\W]*|[\w\W]*\}\}/gm);
  15357. var ERB_EXPR = seal(/<%[\w\W]*|[\w\W]*%>/gm);
  15358. var DATA_ATTR = seal(/^data-[\-\w.\u00B7-\uFFFF]/);
  15359. var ARIA_ATTR = seal(/^aria-[\-\w]+$/);
  15360. var IS_ALLOWED_URI = seal(/^(?:(?:(?:f|ht)tps?|mailto|tel|callto|cid|xmpp):|[^a-z]|[a-z+.\-]+(?:[^a-z+.\-:]|$))/i);
  15361. var IS_SCRIPT_OR_DATA = seal(/^(?:\w+script|data):/i);
  15362. var ATTR_WHITESPACE = seal(/[\u0000-\u0020\u00A0\u1680\u180E\u2000-\u2029\u205F\u3000]/g);
  15363. var DOCTYPE_NAME = seal(/^html$/i);
  15364. var getGlobal = function getGlobal() {
  15365. return typeof window === 'undefined' ? null : window;
  15366. };
  15367. var _createTrustedTypesPolicy = function _createTrustedTypesPolicy(trustedTypes, document) {
  15368. if (_typeof(trustedTypes) !== 'object' || typeof trustedTypes.createPolicy !== 'function') {
  15369. return null;
  15370. }
  15371. var suffix = null;
  15372. var ATTR_NAME = 'data-tt-policy-suffix';
  15373. if (document.currentScript && document.currentScript.hasAttribute(ATTR_NAME)) {
  15374. suffix = document.currentScript.getAttribute(ATTR_NAME);
  15375. }
  15376. var policyName = 'dompurify' + (suffix ? '#' + suffix : '');
  15377. try {
  15378. return trustedTypes.createPolicy(policyName, {
  15379. createHTML: function createHTML(html) {
  15380. return html;
  15381. }
  15382. });
  15383. } catch (_) {
  15384. console.warn('TrustedTypes policy ' + policyName + ' could not be created.');
  15385. return null;
  15386. }
  15387. };
  15388. function createDOMPurify() {
  15389. var window = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : getGlobal();
  15390. var DOMPurify = function DOMPurify(root) {
  15391. return createDOMPurify(root);
  15392. };
  15393. DOMPurify.version = '2.3.8';
  15394. DOMPurify.removed = [];
  15395. if (!window || !window.document || window.document.nodeType !== 9) {
  15396. DOMPurify.isSupported = false;
  15397. return DOMPurify;
  15398. }
  15399. var originalDocument = window.document;
  15400. var document = window.document;
  15401. 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;
  15402. var ElementPrototype = Element.prototype;
  15403. var cloneNode = lookupGetter(ElementPrototype, 'cloneNode');
  15404. var getNextSibling = lookupGetter(ElementPrototype, 'nextSibling');
  15405. var getChildNodes = lookupGetter(ElementPrototype, 'childNodes');
  15406. var getParentNode = lookupGetter(ElementPrototype, 'parentNode');
  15407. if (typeof HTMLTemplateElement === 'function') {
  15408. var template = document.createElement('template');
  15409. if (template.content && template.content.ownerDocument) {
  15410. document = template.content.ownerDocument;
  15411. }
  15412. }
  15413. var trustedTypesPolicy = _createTrustedTypesPolicy(trustedTypes, originalDocument);
  15414. var emptyHTML = trustedTypesPolicy ? trustedTypesPolicy.createHTML('') : '';
  15415. var _document = document, implementation = _document.implementation, createNodeIterator = _document.createNodeIterator, createDocumentFragment = _document.createDocumentFragment, getElementsByTagName = _document.getElementsByTagName;
  15416. var importNode = originalDocument.importNode;
  15417. var documentMode = {};
  15418. try {
  15419. documentMode = clone(document).documentMode ? document.documentMode : {};
  15420. } catch (_) {
  15421. }
  15422. var hooks = {};
  15423. DOMPurify.isSupported = typeof getParentNode === 'function' && implementation && typeof implementation.createHTMLDocument !== 'undefined' && documentMode !== 9;
  15424. 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;
  15425. var IS_ALLOWED_URI$1 = IS_ALLOWED_URI;
  15426. var ALLOWED_TAGS = null;
  15427. var DEFAULT_ALLOWED_TAGS = addToSet({}, [].concat(_toConsumableArray(html$1), _toConsumableArray(svg$1), _toConsumableArray(svgFilters), _toConsumableArray(mathMl$1), _toConsumableArray(text)));
  15428. var ALLOWED_ATTR = null;
  15429. var DEFAULT_ALLOWED_ATTR = addToSet({}, [].concat(_toConsumableArray(html), _toConsumableArray(svg), _toConsumableArray(mathMl), _toConsumableArray(xml)));
  15430. var CUSTOM_ELEMENT_HANDLING = Object.seal(Object.create(null, {
  15431. tagNameCheck: {
  15432. writable: true,
  15433. configurable: false,
  15434. enumerable: true,
  15435. value: null
  15436. },
  15437. attributeNameCheck: {
  15438. writable: true,
  15439. configurable: false,
  15440. enumerable: true,
  15441. value: null
  15442. },
  15443. allowCustomizedBuiltInElements: {
  15444. writable: true,
  15445. configurable: false,
  15446. enumerable: true,
  15447. value: false
  15448. }
  15449. }));
  15450. var FORBID_TAGS = null;
  15451. var FORBID_ATTR = null;
  15452. var ALLOW_ARIA_ATTR = true;
  15453. var ALLOW_DATA_ATTR = true;
  15454. var ALLOW_UNKNOWN_PROTOCOLS = false;
  15455. var SAFE_FOR_TEMPLATES = false;
  15456. var WHOLE_DOCUMENT = false;
  15457. var SET_CONFIG = false;
  15458. var FORCE_BODY = false;
  15459. var RETURN_DOM = false;
  15460. var RETURN_DOM_FRAGMENT = false;
  15461. var RETURN_TRUSTED_TYPE = false;
  15462. var SANITIZE_DOM = true;
  15463. var KEEP_CONTENT = true;
  15464. var IN_PLACE = false;
  15465. var USE_PROFILES = {};
  15466. var FORBID_CONTENTS = null;
  15467. var DEFAULT_FORBID_CONTENTS = addToSet({}, [
  15468. 'annotation-xml',
  15469. 'audio',
  15470. 'colgroup',
  15471. 'desc',
  15472. 'foreignobject',
  15473. 'head',
  15474. 'iframe',
  15475. 'math',
  15476. 'mi',
  15477. 'mn',
  15478. 'mo',
  15479. 'ms',
  15480. 'mtext',
  15481. 'noembed',
  15482. 'noframes',
  15483. 'noscript',
  15484. 'plaintext',
  15485. 'script',
  15486. 'style',
  15487. 'svg',
  15488. 'template',
  15489. 'thead',
  15490. 'title',
  15491. 'video',
  15492. 'xmp'
  15493. ]);
  15494. var DATA_URI_TAGS = null;
  15495. var DEFAULT_DATA_URI_TAGS = addToSet({}, [
  15496. 'audio',
  15497. 'video',
  15498. 'img',
  15499. 'source',
  15500. 'image',
  15501. 'track'
  15502. ]);
  15503. var URI_SAFE_ATTRIBUTES = null;
  15504. var DEFAULT_URI_SAFE_ATTRIBUTES = addToSet({}, [
  15505. 'alt',
  15506. 'class',
  15507. 'for',
  15508. 'id',
  15509. 'label',
  15510. 'name',
  15511. 'pattern',
  15512. 'placeholder',
  15513. 'role',
  15514. 'summary',
  15515. 'title',
  15516. 'value',
  15517. 'style',
  15518. 'xmlns'
  15519. ]);
  15520. var MATHML_NAMESPACE = 'http://www.w3.org/1998/Math/MathML';
  15521. var SVG_NAMESPACE = 'http://www.w3.org/2000/svg';
  15522. var HTML_NAMESPACE = 'http://www.w3.org/1999/xhtml';
  15523. var NAMESPACE = HTML_NAMESPACE;
  15524. var IS_EMPTY_INPUT = false;
  15525. var PARSER_MEDIA_TYPE;
  15526. var SUPPORTED_PARSER_MEDIA_TYPES = [
  15527. 'application/xhtml+xml',
  15528. 'text/html'
  15529. ];
  15530. var DEFAULT_PARSER_MEDIA_TYPE = 'text/html';
  15531. var transformCaseFunc;
  15532. var CONFIG = null;
  15533. var formElement = document.createElement('form');
  15534. var isRegexOrFunction = function isRegexOrFunction(testValue) {
  15535. return testValue instanceof RegExp || testValue instanceof Function;
  15536. };
  15537. var _parseConfig = function _parseConfig(cfg) {
  15538. if (CONFIG && CONFIG === cfg) {
  15539. return;
  15540. }
  15541. if (!cfg || _typeof(cfg) !== 'object') {
  15542. cfg = {};
  15543. }
  15544. cfg = clone(cfg);
  15545. ALLOWED_TAGS = 'ALLOWED_TAGS' in cfg ? addToSet({}, cfg.ALLOWED_TAGS) : DEFAULT_ALLOWED_TAGS;
  15546. ALLOWED_ATTR = 'ALLOWED_ATTR' in cfg ? addToSet({}, cfg.ALLOWED_ATTR) : DEFAULT_ALLOWED_ATTR;
  15547. URI_SAFE_ATTRIBUTES = 'ADD_URI_SAFE_ATTR' in cfg ? addToSet(clone(DEFAULT_URI_SAFE_ATTRIBUTES), cfg.ADD_URI_SAFE_ATTR) : DEFAULT_URI_SAFE_ATTRIBUTES;
  15548. DATA_URI_TAGS = 'ADD_DATA_URI_TAGS' in cfg ? addToSet(clone(DEFAULT_DATA_URI_TAGS), cfg.ADD_DATA_URI_TAGS) : DEFAULT_DATA_URI_TAGS;
  15549. FORBID_CONTENTS = 'FORBID_CONTENTS' in cfg ? addToSet({}, cfg.FORBID_CONTENTS) : DEFAULT_FORBID_CONTENTS;
  15550. FORBID_TAGS = 'FORBID_TAGS' in cfg ? addToSet({}, cfg.FORBID_TAGS) : {};
  15551. FORBID_ATTR = 'FORBID_ATTR' in cfg ? addToSet({}, cfg.FORBID_ATTR) : {};
  15552. USE_PROFILES = 'USE_PROFILES' in cfg ? cfg.USE_PROFILES : false;
  15553. ALLOW_ARIA_ATTR = cfg.ALLOW_ARIA_ATTR !== false;
  15554. ALLOW_DATA_ATTR = cfg.ALLOW_DATA_ATTR !== false;
  15555. ALLOW_UNKNOWN_PROTOCOLS = cfg.ALLOW_UNKNOWN_PROTOCOLS || false;
  15556. SAFE_FOR_TEMPLATES = cfg.SAFE_FOR_TEMPLATES || false;
  15557. WHOLE_DOCUMENT = cfg.WHOLE_DOCUMENT || false;
  15558. RETURN_DOM = cfg.RETURN_DOM || false;
  15559. RETURN_DOM_FRAGMENT = cfg.RETURN_DOM_FRAGMENT || false;
  15560. RETURN_TRUSTED_TYPE = cfg.RETURN_TRUSTED_TYPE || false;
  15561. FORCE_BODY = cfg.FORCE_BODY || false;
  15562. SANITIZE_DOM = cfg.SANITIZE_DOM !== false;
  15563. KEEP_CONTENT = cfg.KEEP_CONTENT !== false;
  15564. IN_PLACE = cfg.IN_PLACE || false;
  15565. IS_ALLOWED_URI$1 = cfg.ALLOWED_URI_REGEXP || IS_ALLOWED_URI$1;
  15566. NAMESPACE = cfg.NAMESPACE || HTML_NAMESPACE;
  15567. if (cfg.CUSTOM_ELEMENT_HANDLING && isRegexOrFunction(cfg.CUSTOM_ELEMENT_HANDLING.tagNameCheck)) {
  15568. CUSTOM_ELEMENT_HANDLING.tagNameCheck = cfg.CUSTOM_ELEMENT_HANDLING.tagNameCheck;
  15569. }
  15570. if (cfg.CUSTOM_ELEMENT_HANDLING && isRegexOrFunction(cfg.CUSTOM_ELEMENT_HANDLING.attributeNameCheck)) {
  15571. CUSTOM_ELEMENT_HANDLING.attributeNameCheck = cfg.CUSTOM_ELEMENT_HANDLING.attributeNameCheck;
  15572. }
  15573. if (cfg.CUSTOM_ELEMENT_HANDLING && typeof cfg.CUSTOM_ELEMENT_HANDLING.allowCustomizedBuiltInElements === 'boolean') {
  15574. CUSTOM_ELEMENT_HANDLING.allowCustomizedBuiltInElements = cfg.CUSTOM_ELEMENT_HANDLING.allowCustomizedBuiltInElements;
  15575. }
  15576. 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;
  15577. transformCaseFunc = PARSER_MEDIA_TYPE === 'application/xhtml+xml' ? function (x) {
  15578. return x;
  15579. } : stringToLowerCase;
  15580. if (SAFE_FOR_TEMPLATES) {
  15581. ALLOW_DATA_ATTR = false;
  15582. }
  15583. if (RETURN_DOM_FRAGMENT) {
  15584. RETURN_DOM = true;
  15585. }
  15586. if (USE_PROFILES) {
  15587. ALLOWED_TAGS = addToSet({}, _toConsumableArray(text));
  15588. ALLOWED_ATTR = [];
  15589. if (USE_PROFILES.html === true) {
  15590. addToSet(ALLOWED_TAGS, html$1);
  15591. addToSet(ALLOWED_ATTR, html);
  15592. }
  15593. if (USE_PROFILES.svg === true) {
  15594. addToSet(ALLOWED_TAGS, svg$1);
  15595. addToSet(ALLOWED_ATTR, svg);
  15596. addToSet(ALLOWED_ATTR, xml);
  15597. }
  15598. if (USE_PROFILES.svgFilters === true) {
  15599. addToSet(ALLOWED_TAGS, svgFilters);
  15600. addToSet(ALLOWED_ATTR, svg);
  15601. addToSet(ALLOWED_ATTR, xml);
  15602. }
  15603. if (USE_PROFILES.mathMl === true) {
  15604. addToSet(ALLOWED_TAGS, mathMl$1);
  15605. addToSet(ALLOWED_ATTR, mathMl);
  15606. addToSet(ALLOWED_ATTR, xml);
  15607. }
  15608. }
  15609. if (cfg.ADD_TAGS) {
  15610. if (ALLOWED_TAGS === DEFAULT_ALLOWED_TAGS) {
  15611. ALLOWED_TAGS = clone(ALLOWED_TAGS);
  15612. }
  15613. addToSet(ALLOWED_TAGS, cfg.ADD_TAGS);
  15614. }
  15615. if (cfg.ADD_ATTR) {
  15616. if (ALLOWED_ATTR === DEFAULT_ALLOWED_ATTR) {
  15617. ALLOWED_ATTR = clone(ALLOWED_ATTR);
  15618. }
  15619. addToSet(ALLOWED_ATTR, cfg.ADD_ATTR);
  15620. }
  15621. if (cfg.ADD_URI_SAFE_ATTR) {
  15622. addToSet(URI_SAFE_ATTRIBUTES, cfg.ADD_URI_SAFE_ATTR);
  15623. }
  15624. if (cfg.FORBID_CONTENTS) {
  15625. if (FORBID_CONTENTS === DEFAULT_FORBID_CONTENTS) {
  15626. FORBID_CONTENTS = clone(FORBID_CONTENTS);
  15627. }
  15628. addToSet(FORBID_CONTENTS, cfg.FORBID_CONTENTS);
  15629. }
  15630. if (KEEP_CONTENT) {
  15631. ALLOWED_TAGS['#text'] = true;
  15632. }
  15633. if (WHOLE_DOCUMENT) {
  15634. addToSet(ALLOWED_TAGS, [
  15635. 'html',
  15636. 'head',
  15637. 'body'
  15638. ]);
  15639. }
  15640. if (ALLOWED_TAGS.table) {
  15641. addToSet(ALLOWED_TAGS, ['tbody']);
  15642. delete FORBID_TAGS.tbody;
  15643. }
  15644. if (freeze) {
  15645. freeze(cfg);
  15646. }
  15647. CONFIG = cfg;
  15648. };
  15649. var MATHML_TEXT_INTEGRATION_POINTS = addToSet({}, [
  15650. 'mi',
  15651. 'mo',
  15652. 'mn',
  15653. 'ms',
  15654. 'mtext'
  15655. ]);
  15656. var HTML_INTEGRATION_POINTS = addToSet({}, [
  15657. 'foreignobject',
  15658. 'desc',
  15659. 'title',
  15660. 'annotation-xml'
  15661. ]);
  15662. var COMMON_SVG_AND_HTML_ELEMENTS = addToSet({}, [
  15663. 'title',
  15664. 'style',
  15665. 'font',
  15666. 'a',
  15667. 'script'
  15668. ]);
  15669. var ALL_SVG_TAGS = addToSet({}, svg$1);
  15670. addToSet(ALL_SVG_TAGS, svgFilters);
  15671. addToSet(ALL_SVG_TAGS, svgDisallowed);
  15672. var ALL_MATHML_TAGS = addToSet({}, mathMl$1);
  15673. addToSet(ALL_MATHML_TAGS, mathMlDisallowed);
  15674. var _checkValidNamespace = function _checkValidNamespace(element) {
  15675. var parent = getParentNode(element);
  15676. if (!parent || !parent.tagName) {
  15677. parent = {
  15678. namespaceURI: HTML_NAMESPACE,
  15679. tagName: 'template'
  15680. };
  15681. }
  15682. var tagName = stringToLowerCase(element.tagName);
  15683. var parentTagName = stringToLowerCase(parent.tagName);
  15684. if (element.namespaceURI === SVG_NAMESPACE) {
  15685. if (parent.namespaceURI === HTML_NAMESPACE) {
  15686. return tagName === 'svg';
  15687. }
  15688. if (parent.namespaceURI === MATHML_NAMESPACE) {
  15689. return tagName === 'svg' && (parentTagName === 'annotation-xml' || MATHML_TEXT_INTEGRATION_POINTS[parentTagName]);
  15690. }
  15691. return Boolean(ALL_SVG_TAGS[tagName]);
  15692. }
  15693. if (element.namespaceURI === MATHML_NAMESPACE) {
  15694. if (parent.namespaceURI === HTML_NAMESPACE) {
  15695. return tagName === 'math';
  15696. }
  15697. if (parent.namespaceURI === SVG_NAMESPACE) {
  15698. return tagName === 'math' && HTML_INTEGRATION_POINTS[parentTagName];
  15699. }
  15700. return Boolean(ALL_MATHML_TAGS[tagName]);
  15701. }
  15702. if (element.namespaceURI === HTML_NAMESPACE) {
  15703. if (parent.namespaceURI === SVG_NAMESPACE && !HTML_INTEGRATION_POINTS[parentTagName]) {
  15704. return false;
  15705. }
  15706. if (parent.namespaceURI === MATHML_NAMESPACE && !MATHML_TEXT_INTEGRATION_POINTS[parentTagName]) {
  15707. return false;
  15708. }
  15709. return !ALL_MATHML_TAGS[tagName] && (COMMON_SVG_AND_HTML_ELEMENTS[tagName] || !ALL_SVG_TAGS[tagName]);
  15710. }
  15711. return false;
  15712. };
  15713. var _forceRemove = function _forceRemove(node) {
  15714. arrayPush(DOMPurify.removed, { element: node });
  15715. try {
  15716. node.parentNode.removeChild(node);
  15717. } catch (_) {
  15718. try {
  15719. node.outerHTML = emptyHTML;
  15720. } catch (_) {
  15721. node.remove();
  15722. }
  15723. }
  15724. };
  15725. var _removeAttribute = function _removeAttribute(name, node) {
  15726. try {
  15727. arrayPush(DOMPurify.removed, {
  15728. attribute: node.getAttributeNode(name),
  15729. from: node
  15730. });
  15731. } catch (_) {
  15732. arrayPush(DOMPurify.removed, {
  15733. attribute: null,
  15734. from: node
  15735. });
  15736. }
  15737. node.removeAttribute(name);
  15738. if (name === 'is' && !ALLOWED_ATTR[name]) {
  15739. if (RETURN_DOM || RETURN_DOM_FRAGMENT) {
  15740. try {
  15741. _forceRemove(node);
  15742. } catch (_) {
  15743. }
  15744. } else {
  15745. try {
  15746. node.setAttribute(name, '');
  15747. } catch (_) {
  15748. }
  15749. }
  15750. }
  15751. };
  15752. var _initDocument = function _initDocument(dirty) {
  15753. var doc;
  15754. var leadingWhitespace;
  15755. if (FORCE_BODY) {
  15756. dirty = '<remove></remove>' + dirty;
  15757. } else {
  15758. var matches = stringMatch(dirty, /^[\r\n\t ]+/);
  15759. leadingWhitespace = matches && matches[0];
  15760. }
  15761. if (PARSER_MEDIA_TYPE === 'application/xhtml+xml') {
  15762. dirty = '<html xmlns="http://www.w3.org/1999/xhtml"><head></head><body>' + dirty + '</body></html>';
  15763. }
  15764. var dirtyPayload = trustedTypesPolicy ? trustedTypesPolicy.createHTML(dirty) : dirty;
  15765. if (NAMESPACE === HTML_NAMESPACE) {
  15766. try {
  15767. doc = new DOMParser().parseFromString(dirtyPayload, PARSER_MEDIA_TYPE);
  15768. } catch (_) {
  15769. }
  15770. }
  15771. if (!doc || !doc.documentElement) {
  15772. doc = implementation.createDocument(NAMESPACE, 'template', null);
  15773. try {
  15774. doc.documentElement.innerHTML = IS_EMPTY_INPUT ? '' : dirtyPayload;
  15775. } catch (_) {
  15776. }
  15777. }
  15778. var body = doc.body || doc.documentElement;
  15779. if (dirty && leadingWhitespace) {
  15780. body.insertBefore(document.createTextNode(leadingWhitespace), body.childNodes[0] || null);
  15781. }
  15782. if (NAMESPACE === HTML_NAMESPACE) {
  15783. return getElementsByTagName.call(doc, WHOLE_DOCUMENT ? 'html' : 'body')[0];
  15784. }
  15785. return WHOLE_DOCUMENT ? doc.documentElement : body;
  15786. };
  15787. var _createIterator = function _createIterator(root) {
  15788. return createNodeIterator.call(root.ownerDocument || root, root, NodeFilter.SHOW_ELEMENT | NodeFilter.SHOW_COMMENT | NodeFilter.SHOW_TEXT, null, false);
  15789. };
  15790. var _isClobbered = function _isClobbered(elm) {
  15791. 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');
  15792. };
  15793. var _isNode = function _isNode(object) {
  15794. return _typeof(Node) === 'object' ? object instanceof Node : object && _typeof(object) === 'object' && typeof object.nodeType === 'number' && typeof object.nodeName === 'string';
  15795. };
  15796. var _executeHook = function _executeHook(entryPoint, currentNode, data) {
  15797. if (!hooks[entryPoint]) {
  15798. return;
  15799. }
  15800. arrayForEach(hooks[entryPoint], function (hook) {
  15801. hook.call(DOMPurify, currentNode, data, CONFIG);
  15802. });
  15803. };
  15804. var _sanitizeElements = function _sanitizeElements(currentNode) {
  15805. var content;
  15806. _executeHook('beforeSanitizeElements', currentNode, null);
  15807. if (_isClobbered(currentNode)) {
  15808. _forceRemove(currentNode);
  15809. return true;
  15810. }
  15811. if (regExpTest(/[\u0080-\uFFFF]/, currentNode.nodeName)) {
  15812. _forceRemove(currentNode);
  15813. return true;
  15814. }
  15815. var tagName = transformCaseFunc(currentNode.nodeName);
  15816. _executeHook('uponSanitizeElement', currentNode, {
  15817. tagName: tagName,
  15818. allowedTags: ALLOWED_TAGS
  15819. });
  15820. if (currentNode.hasChildNodes() && !_isNode(currentNode.firstElementChild) && (!_isNode(currentNode.content) || !_isNode(currentNode.content.firstElementChild)) && regExpTest(/<[/\w]/g, currentNode.innerHTML) && regExpTest(/<[/\w]/g, currentNode.textContent)) {
  15821. _forceRemove(currentNode);
  15822. return true;
  15823. }
  15824. if (tagName === 'select' && regExpTest(/<template/i, currentNode.innerHTML)) {
  15825. _forceRemove(currentNode);
  15826. return true;
  15827. }
  15828. if (!ALLOWED_TAGS[tagName] || FORBID_TAGS[tagName]) {
  15829. if (!FORBID_TAGS[tagName] && _basicCustomElementTest(tagName)) {
  15830. if (CUSTOM_ELEMENT_HANDLING.tagNameCheck instanceof RegExp && regExpTest(CUSTOM_ELEMENT_HANDLING.tagNameCheck, tagName))
  15831. return false;
  15832. if (CUSTOM_ELEMENT_HANDLING.tagNameCheck instanceof Function && CUSTOM_ELEMENT_HANDLING.tagNameCheck(tagName))
  15833. return false;
  15834. }
  15835. if (KEEP_CONTENT && !FORBID_CONTENTS[tagName]) {
  15836. var parentNode = getParentNode(currentNode) || currentNode.parentNode;
  15837. var childNodes = getChildNodes(currentNode) || currentNode.childNodes;
  15838. if (childNodes && parentNode) {
  15839. var childCount = childNodes.length;
  15840. for (var i = childCount - 1; i >= 0; --i) {
  15841. parentNode.insertBefore(cloneNode(childNodes[i], true), getNextSibling(currentNode));
  15842. }
  15843. }
  15844. }
  15845. _forceRemove(currentNode);
  15846. return true;
  15847. }
  15848. if (currentNode instanceof Element && !_checkValidNamespace(currentNode)) {
  15849. _forceRemove(currentNode);
  15850. return true;
  15851. }
  15852. if ((tagName === 'noscript' || tagName === 'noembed') && regExpTest(/<\/no(script|embed)/i, currentNode.innerHTML)) {
  15853. _forceRemove(currentNode);
  15854. return true;
  15855. }
  15856. if (SAFE_FOR_TEMPLATES && currentNode.nodeType === 3) {
  15857. content = currentNode.textContent;
  15858. content = stringReplace(content, MUSTACHE_EXPR$1, ' ');
  15859. content = stringReplace(content, ERB_EXPR$1, ' ');
  15860. if (currentNode.textContent !== content) {
  15861. arrayPush(DOMPurify.removed, { element: currentNode.cloneNode() });
  15862. currentNode.textContent = content;
  15863. }
  15864. }
  15865. _executeHook('afterSanitizeElements', currentNode, null);
  15866. return false;
  15867. };
  15868. var _isValidAttribute = function _isValidAttribute(lcTag, lcName, value) {
  15869. if (SANITIZE_DOM && (lcName === 'id' || lcName === 'name') && (value in document || value in formElement)) {
  15870. return false;
  15871. }
  15872. if (ALLOW_DATA_ATTR && !FORBID_ATTR[lcName] && regExpTest(DATA_ATTR$1, lcName));
  15873. else if (ALLOW_ARIA_ATTR && regExpTest(ARIA_ATTR$1, lcName));
  15874. else if (!ALLOWED_ATTR[lcName] || FORBID_ATTR[lcName]) {
  15875. 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)));
  15876. else {
  15877. return false;
  15878. }
  15879. } else if (URI_SAFE_ATTRIBUTES[lcName]);
  15880. else if (regExpTest(IS_ALLOWED_URI$1, stringReplace(value, ATTR_WHITESPACE$1, '')));
  15881. else if ((lcName === 'src' || lcName === 'xlink:href' || lcName === 'href') && lcTag !== 'script' && stringIndexOf(value, 'data:') === 0 && DATA_URI_TAGS[lcTag]);
  15882. else if (ALLOW_UNKNOWN_PROTOCOLS && !regExpTest(IS_SCRIPT_OR_DATA$1, stringReplace(value, ATTR_WHITESPACE$1, '')));
  15883. else if (!value);
  15884. else {
  15885. return false;
  15886. }
  15887. return true;
  15888. };
  15889. var _basicCustomElementTest = function _basicCustomElementTest(tagName) {
  15890. return tagName.indexOf('-') > 0;
  15891. };
  15892. var _sanitizeAttributes = function _sanitizeAttributes(currentNode) {
  15893. var attr;
  15894. var value;
  15895. var lcName;
  15896. var l;
  15897. _executeHook('beforeSanitizeAttributes', currentNode, null);
  15898. var attributes = currentNode.attributes;
  15899. if (!attributes) {
  15900. return;
  15901. }
  15902. var hookEvent = {
  15903. attrName: '',
  15904. attrValue: '',
  15905. keepAttr: true,
  15906. allowedAttributes: ALLOWED_ATTR
  15907. };
  15908. l = attributes.length;
  15909. while (l--) {
  15910. attr = attributes[l];
  15911. var _attr = attr, name = _attr.name, namespaceURI = _attr.namespaceURI;
  15912. value = name === 'value' ? attr.value : stringTrim(attr.value);
  15913. lcName = transformCaseFunc(name);
  15914. var initValue = value;
  15915. hookEvent.attrName = lcName;
  15916. hookEvent.attrValue = value;
  15917. hookEvent.keepAttr = true;
  15918. hookEvent.forceKeepAttr = undefined;
  15919. _executeHook('uponSanitizeAttribute', currentNode, hookEvent);
  15920. value = hookEvent.attrValue;
  15921. if (hookEvent.forceKeepAttr) {
  15922. continue;
  15923. }
  15924. if (!hookEvent.keepAttr) {
  15925. _removeAttribute(name, currentNode);
  15926. continue;
  15927. }
  15928. if (regExpTest(/\/>/i, value)) {
  15929. _removeAttribute(name, currentNode);
  15930. continue;
  15931. }
  15932. if (SAFE_FOR_TEMPLATES) {
  15933. value = stringReplace(value, MUSTACHE_EXPR$1, ' ');
  15934. value = stringReplace(value, ERB_EXPR$1, ' ');
  15935. }
  15936. var lcTag = transformCaseFunc(currentNode.nodeName);
  15937. if (!_isValidAttribute(lcTag, lcName, value)) {
  15938. _removeAttribute(name, currentNode);
  15939. continue;
  15940. }
  15941. if (value !== initValue) {
  15942. try {
  15943. if (namespaceURI) {
  15944. currentNode.setAttributeNS(namespaceURI, name, value);
  15945. } else {
  15946. currentNode.setAttribute(name, value);
  15947. }
  15948. } catch (_) {
  15949. _removeAttribute(name, currentNode);
  15950. }
  15951. }
  15952. }
  15953. _executeHook('afterSanitizeAttributes', currentNode, null);
  15954. };
  15955. var _sanitizeShadowDOM = function _sanitizeShadowDOM(fragment) {
  15956. var shadowNode;
  15957. var shadowIterator = _createIterator(fragment);
  15958. _executeHook('beforeSanitizeShadowDOM', fragment, null);
  15959. while (shadowNode = shadowIterator.nextNode()) {
  15960. _executeHook('uponSanitizeShadowNode', shadowNode, null);
  15961. if (_sanitizeElements(shadowNode)) {
  15962. continue;
  15963. }
  15964. if (shadowNode.content instanceof DocumentFragment) {
  15965. _sanitizeShadowDOM(shadowNode.content);
  15966. }
  15967. _sanitizeAttributes(shadowNode);
  15968. }
  15969. _executeHook('afterSanitizeShadowDOM', fragment, null);
  15970. };
  15971. DOMPurify.sanitize = function (dirty, cfg) {
  15972. var body;
  15973. var importedNode;
  15974. var currentNode;
  15975. var oldNode;
  15976. var returnNode;
  15977. IS_EMPTY_INPUT = !dirty;
  15978. if (IS_EMPTY_INPUT) {
  15979. dirty = '<!-->';
  15980. }
  15981. if (typeof dirty !== 'string' && !_isNode(dirty)) {
  15982. if (typeof dirty.toString !== 'function') {
  15983. throw typeErrorCreate('toString is not a function');
  15984. } else {
  15985. dirty = dirty.toString();
  15986. if (typeof dirty !== 'string') {
  15987. throw typeErrorCreate('dirty is not a string, aborting');
  15988. }
  15989. }
  15990. }
  15991. if (!DOMPurify.isSupported) {
  15992. if (_typeof(window.toStaticHTML) === 'object' || typeof window.toStaticHTML === 'function') {
  15993. if (typeof dirty === 'string') {
  15994. return window.toStaticHTML(dirty);
  15995. }
  15996. if (_isNode(dirty)) {
  15997. return window.toStaticHTML(dirty.outerHTML);
  15998. }
  15999. }
  16000. return dirty;
  16001. }
  16002. if (!SET_CONFIG) {
  16003. _parseConfig(cfg);
  16004. }
  16005. DOMPurify.removed = [];
  16006. if (typeof dirty === 'string') {
  16007. IN_PLACE = false;
  16008. }
  16009. if (IN_PLACE) {
  16010. if (dirty.nodeName) {
  16011. var tagName = transformCaseFunc(dirty.nodeName);
  16012. if (!ALLOWED_TAGS[tagName] || FORBID_TAGS[tagName]) {
  16013. throw typeErrorCreate('root node is forbidden and cannot be sanitized in-place');
  16014. }
  16015. }
  16016. } else if (dirty instanceof Node) {
  16017. body = _initDocument('<!---->');
  16018. importedNode = body.ownerDocument.importNode(dirty, true);
  16019. if (importedNode.nodeType === 1 && importedNode.nodeName === 'BODY') {
  16020. body = importedNode;
  16021. } else if (importedNode.nodeName === 'HTML') {
  16022. body = importedNode;
  16023. } else {
  16024. body.appendChild(importedNode);
  16025. }
  16026. } else {
  16027. if (!RETURN_DOM && !SAFE_FOR_TEMPLATES && !WHOLE_DOCUMENT && dirty.indexOf('<') === -1) {
  16028. return trustedTypesPolicy && RETURN_TRUSTED_TYPE ? trustedTypesPolicy.createHTML(dirty) : dirty;
  16029. }
  16030. body = _initDocument(dirty);
  16031. if (!body) {
  16032. return RETURN_DOM ? null : RETURN_TRUSTED_TYPE ? emptyHTML : '';
  16033. }
  16034. }
  16035. if (body && FORCE_BODY) {
  16036. _forceRemove(body.firstChild);
  16037. }
  16038. var nodeIterator = _createIterator(IN_PLACE ? dirty : body);
  16039. while (currentNode = nodeIterator.nextNode()) {
  16040. if (currentNode.nodeType === 3 && currentNode === oldNode) {
  16041. continue;
  16042. }
  16043. if (_sanitizeElements(currentNode)) {
  16044. continue;
  16045. }
  16046. if (currentNode.content instanceof DocumentFragment) {
  16047. _sanitizeShadowDOM(currentNode.content);
  16048. }
  16049. _sanitizeAttributes(currentNode);
  16050. oldNode = currentNode;
  16051. }
  16052. oldNode = null;
  16053. if (IN_PLACE) {
  16054. return dirty;
  16055. }
  16056. if (RETURN_DOM) {
  16057. if (RETURN_DOM_FRAGMENT) {
  16058. returnNode = createDocumentFragment.call(body.ownerDocument);
  16059. while (body.firstChild) {
  16060. returnNode.appendChild(body.firstChild);
  16061. }
  16062. } else {
  16063. returnNode = body;
  16064. }
  16065. if (ALLOWED_ATTR.shadowroot) {
  16066. returnNode = importNode.call(originalDocument, returnNode, true);
  16067. }
  16068. return returnNode;
  16069. }
  16070. var serializedHTML = WHOLE_DOCUMENT ? body.outerHTML : body.innerHTML;
  16071. if (WHOLE_DOCUMENT && ALLOWED_TAGS['!doctype'] && body.ownerDocument && body.ownerDocument.doctype && body.ownerDocument.doctype.name && regExpTest(DOCTYPE_NAME, body.ownerDocument.doctype.name)) {
  16072. serializedHTML = '<!DOCTYPE ' + body.ownerDocument.doctype.name + '>\n' + serializedHTML;
  16073. }
  16074. if (SAFE_FOR_TEMPLATES) {
  16075. serializedHTML = stringReplace(serializedHTML, MUSTACHE_EXPR$1, ' ');
  16076. serializedHTML = stringReplace(serializedHTML, ERB_EXPR$1, ' ');
  16077. }
  16078. return trustedTypesPolicy && RETURN_TRUSTED_TYPE ? trustedTypesPolicy.createHTML(serializedHTML) : serializedHTML;
  16079. };
  16080. DOMPurify.setConfig = function (cfg) {
  16081. _parseConfig(cfg);
  16082. SET_CONFIG = true;
  16083. };
  16084. DOMPurify.clearConfig = function () {
  16085. CONFIG = null;
  16086. SET_CONFIG = false;
  16087. };
  16088. DOMPurify.isValidAttribute = function (tag, attr, value) {
  16089. if (!CONFIG) {
  16090. _parseConfig({});
  16091. }
  16092. var lcTag = transformCaseFunc(tag);
  16093. var lcName = transformCaseFunc(attr);
  16094. return _isValidAttribute(lcTag, lcName, value);
  16095. };
  16096. DOMPurify.addHook = function (entryPoint, hookFunction) {
  16097. if (typeof hookFunction !== 'function') {
  16098. return;
  16099. }
  16100. hooks[entryPoint] = hooks[entryPoint] || [];
  16101. arrayPush(hooks[entryPoint], hookFunction);
  16102. };
  16103. DOMPurify.removeHook = function (entryPoint) {
  16104. if (hooks[entryPoint]) {
  16105. return arrayPop(hooks[entryPoint]);
  16106. }
  16107. };
  16108. DOMPurify.removeHooks = function (entryPoint) {
  16109. if (hooks[entryPoint]) {
  16110. hooks[entryPoint] = [];
  16111. }
  16112. };
  16113. DOMPurify.removeAllHooks = function () {
  16114. hooks = {};
  16115. };
  16116. return DOMPurify;
  16117. }
  16118. var purify = createDOMPurify();
  16119. const each$4 = Tools.each, trim = Tools.trim;
  16120. const queryParts = [
  16121. 'source',
  16122. 'protocol',
  16123. 'authority',
  16124. 'userInfo',
  16125. 'user',
  16126. 'password',
  16127. 'host',
  16128. 'port',
  16129. 'relative',
  16130. 'path',
  16131. 'directory',
  16132. 'file',
  16133. 'query',
  16134. 'anchor'
  16135. ];
  16136. const DEFAULT_PORTS = {
  16137. ftp: 21,
  16138. http: 80,
  16139. https: 443,
  16140. mailto: 25
  16141. };
  16142. const safeSvgDataUrlElements = [
  16143. 'img',
  16144. 'video'
  16145. ];
  16146. const blockSvgDataUris = (allowSvgDataUrls, tagName) => {
  16147. if (isNonNullable(allowSvgDataUrls)) {
  16148. return !allowSvgDataUrls;
  16149. } else {
  16150. return isNonNullable(tagName) ? !contains$2(safeSvgDataUrlElements, tagName) : true;
  16151. }
  16152. };
  16153. const decodeUri = encodedUri => {
  16154. try {
  16155. return decodeURIComponent(encodedUri);
  16156. } catch (ex) {
  16157. return unescape(encodedUri);
  16158. }
  16159. };
  16160. const isInvalidUri = (settings, uri, tagName) => {
  16161. const decodedUri = decodeUri(uri).replace(/\s/g, '');
  16162. if (settings.allow_script_urls) {
  16163. return false;
  16164. } else if (/((java|vb)script|mhtml):/i.test(decodedUri)) {
  16165. return true;
  16166. } else if (settings.allow_html_data_urls) {
  16167. return false;
  16168. } else if (/^data:image\//i.test(decodedUri)) {
  16169. return blockSvgDataUris(settings.allow_svg_data_urls, tagName) && /^data:image\/svg\+xml/i.test(decodedUri);
  16170. } else {
  16171. return /^data:/i.test(decodedUri);
  16172. }
  16173. };
  16174. class URI {
  16175. constructor(url, settings = {}) {
  16176. this.path = '';
  16177. this.directory = '';
  16178. url = trim(url);
  16179. this.settings = settings;
  16180. const baseUri = settings.base_uri;
  16181. const self = this;
  16182. if (/^([\w\-]+):([^\/]{2})/i.test(url) || /^\s*#/.test(url)) {
  16183. self.source = url;
  16184. return;
  16185. }
  16186. const isProtocolRelative = url.indexOf('//') === 0;
  16187. if (url.indexOf('/') === 0 && !isProtocolRelative) {
  16188. url = (baseUri ? baseUri.protocol || 'http' : 'http') + '://mce_host' + url;
  16189. }
  16190. if (!/^[\w\-]*:?\/\//.test(url)) {
  16191. const baseUrl = baseUri ? baseUri.path : new URI(document.location.href).directory;
  16192. if ((baseUri === null || baseUri === void 0 ? void 0 : baseUri.protocol) === '') {
  16193. url = '//mce_host' + self.toAbsPath(baseUrl, url);
  16194. } else {
  16195. const match = /([^#?]*)([#?]?.*)/.exec(url);
  16196. if (match) {
  16197. url = (baseUri && baseUri.protocol || 'http') + '://mce_host' + self.toAbsPath(baseUrl, match[1]) + match[2];
  16198. }
  16199. }
  16200. }
  16201. url = url.replace(/@@/g, '(mce_at)');
  16202. const urlMatch = /^(?:(?![^:@]+:[^:@\/]*@)([^:\/?#.]+):)?(?:\/\/)?((?:(([^:@\/]*):?([^:@\/]*))?@)?(\[[a-zA-Z0-9:.%]+\]|[^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/.exec(url);
  16203. if (urlMatch) {
  16204. each$4(queryParts, (v, i) => {
  16205. let part = urlMatch[i];
  16206. if (part) {
  16207. part = part.replace(/\(mce_at\)/g, '@@');
  16208. }
  16209. self[v] = part;
  16210. });
  16211. }
  16212. if (baseUri) {
  16213. if (!self.protocol) {
  16214. self.protocol = baseUri.protocol;
  16215. }
  16216. if (!self.userInfo) {
  16217. self.userInfo = baseUri.userInfo;
  16218. }
  16219. if (!self.port && self.host === 'mce_host') {
  16220. self.port = baseUri.port;
  16221. }
  16222. if (!self.host || self.host === 'mce_host') {
  16223. self.host = baseUri.host;
  16224. }
  16225. self.source = '';
  16226. }
  16227. if (isProtocolRelative) {
  16228. self.protocol = '';
  16229. }
  16230. }
  16231. static parseDataUri(uri) {
  16232. let type;
  16233. const uriComponents = decodeURIComponent(uri).split(',');
  16234. const matches = /data:([^;]+)/.exec(uriComponents[0]);
  16235. if (matches) {
  16236. type = matches[1];
  16237. }
  16238. return {
  16239. type,
  16240. data: uriComponents[1]
  16241. };
  16242. }
  16243. static isDomSafe(uri, context, options = {}) {
  16244. if (options.allow_script_urls) {
  16245. return true;
  16246. } else {
  16247. const decodedUri = Entities.decode(uri).replace(/[\s\u0000-\u001F]+/g, '');
  16248. return !isInvalidUri(options, decodedUri, context);
  16249. }
  16250. }
  16251. static getDocumentBaseUrl(loc) {
  16252. var _a;
  16253. let baseUrl;
  16254. if (loc.protocol.indexOf('http') !== 0 && loc.protocol !== 'file:') {
  16255. baseUrl = (_a = loc.href) !== null && _a !== void 0 ? _a : '';
  16256. } else {
  16257. baseUrl = loc.protocol + '//' + loc.host + loc.pathname;
  16258. }
  16259. if (/^[^:]+:\/\/\/?[^\/]+\//.test(baseUrl)) {
  16260. baseUrl = baseUrl.replace(/[\?#].*$/, '').replace(/[\/\\][^\/]+$/, '');
  16261. if (!/[\/\\]$/.test(baseUrl)) {
  16262. baseUrl += '/';
  16263. }
  16264. }
  16265. return baseUrl;
  16266. }
  16267. setPath(path) {
  16268. const pathMatch = /^(.*?)\/?(\w+)?$/.exec(path);
  16269. if (pathMatch) {
  16270. this.path = pathMatch[0];
  16271. this.directory = pathMatch[1];
  16272. this.file = pathMatch[2];
  16273. }
  16274. this.source = '';
  16275. this.getURI();
  16276. }
  16277. toRelative(uri) {
  16278. if (uri === './') {
  16279. return uri;
  16280. }
  16281. const relativeUri = new URI(uri, { base_uri: this });
  16282. if (relativeUri.host !== 'mce_host' && this.host !== relativeUri.host && relativeUri.host || this.port !== relativeUri.port || this.protocol !== relativeUri.protocol && relativeUri.protocol !== '') {
  16283. return relativeUri.getURI();
  16284. }
  16285. const tu = this.getURI(), uu = relativeUri.getURI();
  16286. if (tu === uu || tu.charAt(tu.length - 1) === '/' && tu.substr(0, tu.length - 1) === uu) {
  16287. return tu;
  16288. }
  16289. let output = this.toRelPath(this.path, relativeUri.path);
  16290. if (relativeUri.query) {
  16291. output += '?' + relativeUri.query;
  16292. }
  16293. if (relativeUri.anchor) {
  16294. output += '#' + relativeUri.anchor;
  16295. }
  16296. return output;
  16297. }
  16298. toAbsolute(uri, noHost) {
  16299. const absoluteUri = new URI(uri, { base_uri: this });
  16300. return absoluteUri.getURI(noHost && this.isSameOrigin(absoluteUri));
  16301. }
  16302. isSameOrigin(uri) {
  16303. if (this.host == uri.host && this.protocol == uri.protocol) {
  16304. if (this.port == uri.port) {
  16305. return true;
  16306. }
  16307. const defaultPort = this.protocol ? DEFAULT_PORTS[this.protocol] : null;
  16308. if (defaultPort && (this.port || defaultPort) == (uri.port || defaultPort)) {
  16309. return true;
  16310. }
  16311. }
  16312. return false;
  16313. }
  16314. toRelPath(base, path) {
  16315. let breakPoint = 0, out = '', i, l;
  16316. const normalizedBase = base.substring(0, base.lastIndexOf('/')).split('/');
  16317. const items = path.split('/');
  16318. if (normalizedBase.length >= items.length) {
  16319. for (i = 0, l = normalizedBase.length; i < l; i++) {
  16320. if (i >= items.length || normalizedBase[i] !== items[i]) {
  16321. breakPoint = i + 1;
  16322. break;
  16323. }
  16324. }
  16325. }
  16326. if (normalizedBase.length < items.length) {
  16327. for (i = 0, l = items.length; i < l; i++) {
  16328. if (i >= normalizedBase.length || normalizedBase[i] !== items[i]) {
  16329. breakPoint = i + 1;
  16330. break;
  16331. }
  16332. }
  16333. }
  16334. if (breakPoint === 1) {
  16335. return path;
  16336. }
  16337. for (i = 0, l = normalizedBase.length - (breakPoint - 1); i < l; i++) {
  16338. out += '../';
  16339. }
  16340. for (i = breakPoint - 1, l = items.length; i < l; i++) {
  16341. if (i !== breakPoint - 1) {
  16342. out += '/' + items[i];
  16343. } else {
  16344. out += items[i];
  16345. }
  16346. }
  16347. return out;
  16348. }
  16349. toAbsPath(base, path) {
  16350. let nb = 0;
  16351. const tr = /\/$/.test(path) ? '/' : '';
  16352. const normalizedBase = base.split('/');
  16353. const normalizedPath = path.split('/');
  16354. const baseParts = [];
  16355. each$4(normalizedBase, k => {
  16356. if (k) {
  16357. baseParts.push(k);
  16358. }
  16359. });
  16360. const pathParts = [];
  16361. for (let i = normalizedPath.length - 1; i >= 0; i--) {
  16362. if (normalizedPath[i].length === 0 || normalizedPath[i] === '.') {
  16363. continue;
  16364. }
  16365. if (normalizedPath[i] === '..') {
  16366. nb++;
  16367. continue;
  16368. }
  16369. if (nb > 0) {
  16370. nb--;
  16371. continue;
  16372. }
  16373. pathParts.push(normalizedPath[i]);
  16374. }
  16375. const i = baseParts.length - nb;
  16376. let outPath;
  16377. if (i <= 0) {
  16378. outPath = reverse(pathParts).join('/');
  16379. } else {
  16380. outPath = baseParts.slice(0, i).join('/') + '/' + reverse(pathParts).join('/');
  16381. }
  16382. if (outPath.indexOf('/') !== 0) {
  16383. outPath = '/' + outPath;
  16384. }
  16385. if (tr && outPath.lastIndexOf('/') !== outPath.length - 1) {
  16386. outPath += tr;
  16387. }
  16388. return outPath;
  16389. }
  16390. getURI(noProtoHost = false) {
  16391. let s;
  16392. if (!this.source || noProtoHost) {
  16393. s = '';
  16394. if (!noProtoHost) {
  16395. if (this.protocol) {
  16396. s += this.protocol + '://';
  16397. } else {
  16398. s += '//';
  16399. }
  16400. if (this.userInfo) {
  16401. s += this.userInfo + '@';
  16402. }
  16403. if (this.host) {
  16404. s += this.host;
  16405. }
  16406. if (this.port) {
  16407. s += ':' + this.port;
  16408. }
  16409. }
  16410. if (this.path) {
  16411. s += this.path;
  16412. }
  16413. if (this.query) {
  16414. s += '?' + this.query;
  16415. }
  16416. if (this.anchor) {
  16417. s += '#' + this.anchor;
  16418. }
  16419. this.source = s;
  16420. }
  16421. return this.source;
  16422. }
  16423. }
  16424. const filteredUrlAttrs = Tools.makeMap('src,href,data,background,action,formaction,poster,xlink:href');
  16425. const internalElementAttr = 'data-mce-type';
  16426. let uid = 0;
  16427. const processNode = (node, settings, schema, evt) => {
  16428. var _a, _b, _c, _d;
  16429. const validate = settings.validate;
  16430. const specialElements = schema.getSpecialElements();
  16431. if (node.nodeType === COMMENT && !settings.allow_conditional_comments && /^\[if/i.test((_a = node.nodeValue) !== null && _a !== void 0 ? _a : '')) {
  16432. node.nodeValue = ' ' + node.nodeValue;
  16433. }
  16434. const lcTagName = (_b = evt === null || evt === void 0 ? void 0 : evt.tagName) !== null && _b !== void 0 ? _b : node.nodeName.toLowerCase();
  16435. if (node.nodeType !== ELEMENT || lcTagName === 'body') {
  16436. return;
  16437. }
  16438. const element = SugarElement.fromDom(node);
  16439. const isInternalElement = has$1(element, internalElementAttr);
  16440. const bogus = get$9(element, 'data-mce-bogus');
  16441. if (!isInternalElement && isString(bogus)) {
  16442. if (bogus === 'all') {
  16443. remove$6(element);
  16444. } else {
  16445. unwrap(element);
  16446. }
  16447. return;
  16448. }
  16449. const rule = schema.getElementRule(lcTagName);
  16450. if (validate && !rule) {
  16451. if (has$2(specialElements, lcTagName)) {
  16452. remove$6(element);
  16453. } else {
  16454. unwrap(element);
  16455. }
  16456. return;
  16457. } else {
  16458. if (isNonNullable(evt)) {
  16459. evt.allowedTags[lcTagName] = true;
  16460. }
  16461. }
  16462. if (validate && rule && !isInternalElement) {
  16463. each$e((_c = rule.attributesForced) !== null && _c !== void 0 ? _c : [], attr => {
  16464. set$3(element, attr.name, attr.value === '{$uid}' ? `mce_${ uid++ }` : attr.value);
  16465. });
  16466. each$e((_d = rule.attributesDefault) !== null && _d !== void 0 ? _d : [], attr => {
  16467. if (!has$1(element, attr.name)) {
  16468. set$3(element, attr.name, attr.value === '{$uid}' ? `mce_${ uid++ }` : attr.value);
  16469. }
  16470. });
  16471. if (rule.attributesRequired && !exists(rule.attributesRequired, attr => has$1(element, attr))) {
  16472. unwrap(element);
  16473. return;
  16474. }
  16475. if (rule.removeEmptyAttrs && hasNone(element)) {
  16476. unwrap(element);
  16477. return;
  16478. }
  16479. if (rule.outputName && rule.outputName !== lcTagName) {
  16480. mutate(element, rule.outputName);
  16481. }
  16482. }
  16483. };
  16484. const shouldKeepAttribute = (settings, schema, tagName, attrName, attrValue) => !(attrName in filteredUrlAttrs && isInvalidUri(settings, attrValue, tagName)) && (!settings.validate || schema.isValid(tagName, attrName) || startsWith(attrName, 'data-') || startsWith(attrName, 'aria-'));
  16485. const isRequiredAttributeOfInternalElement = (ele, attrName) => ele.hasAttribute(internalElementAttr) && (attrName === 'id' || attrName === 'class' || attrName === 'style');
  16486. const isBooleanAttribute = (attrName, schema) => attrName in schema.getBoolAttrs();
  16487. const filterAttributes = (ele, settings, schema) => {
  16488. const {attributes} = ele;
  16489. for (let i = attributes.length - 1; i >= 0; i--) {
  16490. const attr = attributes[i];
  16491. const attrName = attr.name;
  16492. const attrValue = attr.value;
  16493. if (!shouldKeepAttribute(settings, schema, ele.tagName.toLowerCase(), attrName, attrValue) && !isRequiredAttributeOfInternalElement(ele, attrName)) {
  16494. ele.removeAttribute(attrName);
  16495. } else if (isBooleanAttribute(attrName, schema)) {
  16496. ele.setAttribute(attrName, attrName);
  16497. }
  16498. }
  16499. };
  16500. const setupPurify = (settings, schema) => {
  16501. const purify$1 = purify();
  16502. purify$1.addHook('uponSanitizeElement', (ele, evt) => {
  16503. processNode(ele, settings, schema, evt);
  16504. });
  16505. purify$1.addHook('uponSanitizeAttribute', (ele, evt) => {
  16506. const tagName = ele.tagName.toLowerCase();
  16507. const {attrName, attrValue} = evt;
  16508. evt.keepAttr = shouldKeepAttribute(settings, schema, tagName, attrName, attrValue);
  16509. if (evt.keepAttr) {
  16510. evt.allowedAttributes[attrName] = true;
  16511. if (isBooleanAttribute(attrName, schema)) {
  16512. evt.attrValue = attrName;
  16513. }
  16514. if (settings.allow_svg_data_urls && startsWith(attrValue, 'data:image/svg+xml')) {
  16515. evt.forceKeepAttr = true;
  16516. }
  16517. } else if (isRequiredAttributeOfInternalElement(ele, attrName)) {
  16518. evt.forceKeepAttr = true;
  16519. }
  16520. });
  16521. return purify$1;
  16522. };
  16523. const getPurifyConfig = (settings, mimeType) => {
  16524. const basePurifyConfig = {
  16525. IN_PLACE: true,
  16526. ALLOW_UNKNOWN_PROTOCOLS: true,
  16527. ALLOWED_TAGS: [
  16528. '#comment',
  16529. '#cdata-section',
  16530. 'body'
  16531. ],
  16532. ALLOWED_ATTR: []
  16533. };
  16534. const config = { ...basePurifyConfig };
  16535. config.PARSER_MEDIA_TYPE = mimeType;
  16536. if (settings.allow_script_urls) {
  16537. config.ALLOWED_URI_REGEXP = /.*/;
  16538. } else if (settings.allow_html_data_urls) {
  16539. config.ALLOWED_URI_REGEXP = /^(?!(\w+script|mhtml):)/i;
  16540. }
  16541. return config;
  16542. };
  16543. const getSanitizer = (settings, schema) => {
  16544. if (settings.sanitize) {
  16545. const purify = setupPurify(settings, schema);
  16546. return (body, mimeType) => {
  16547. purify.sanitize(body, getPurifyConfig(settings, mimeType));
  16548. purify.removed = [];
  16549. };
  16550. } else {
  16551. return (body, _) => {
  16552. const nodeIterator = document.createNodeIterator(body, NodeFilter.SHOW_ELEMENT | NodeFilter.SHOW_COMMENT | NodeFilter.SHOW_TEXT);
  16553. let node;
  16554. while (node = nodeIterator.nextNode()) {
  16555. processNode(node, settings, schema);
  16556. if (isElement$6(node)) {
  16557. filterAttributes(node, settings, schema);
  16558. }
  16559. }
  16560. };
  16561. }
  16562. };
  16563. const makeMap = Tools.makeMap, extend$1 = Tools.extend;
  16564. const transferChildren = (parent, nativeParent, specialElements) => {
  16565. const parentName = parent.name;
  16566. const isSpecial = parentName in specialElements && parentName !== 'title' && parentName !== 'textarea';
  16567. const childNodes = nativeParent.childNodes;
  16568. for (let ni = 0, nl = childNodes.length; ni < nl; ni++) {
  16569. const nativeChild = childNodes[ni];
  16570. const child = new AstNode(nativeChild.nodeName.toLowerCase(), nativeChild.nodeType);
  16571. if (isElement$6(nativeChild)) {
  16572. const attributes = nativeChild.attributes;
  16573. for (let ai = 0, al = attributes.length; ai < al; ai++) {
  16574. const attr = attributes[ai];
  16575. child.attr(attr.name, attr.value);
  16576. }
  16577. } else if (isText$a(nativeChild)) {
  16578. child.value = nativeChild.data;
  16579. if (isSpecial) {
  16580. child.raw = true;
  16581. }
  16582. } else if (isComment(nativeChild) || isCData(nativeChild) || isPi(nativeChild)) {
  16583. child.value = nativeChild.data;
  16584. }
  16585. transferChildren(child, nativeChild, specialElements);
  16586. parent.append(child);
  16587. }
  16588. };
  16589. const walkTree = (root, preprocessors, postprocessors) => {
  16590. const traverseOrder = [];
  16591. for (let node = root, lastNode = node; node; lastNode = node, node = node.walk()) {
  16592. const tempNode = node;
  16593. each$e(preprocessors, preprocess => preprocess(tempNode));
  16594. if (isNullable(tempNode.parent) && tempNode !== root) {
  16595. node = lastNode;
  16596. } else {
  16597. traverseOrder.push(tempNode);
  16598. }
  16599. }
  16600. for (let i = traverseOrder.length - 1; i >= 0; i--) {
  16601. const node = traverseOrder[i];
  16602. each$e(postprocessors, postprocess => postprocess(node));
  16603. }
  16604. };
  16605. const whitespaceCleaner = (root, schema, settings, args) => {
  16606. const validate = settings.validate;
  16607. const nonEmptyElements = schema.getNonEmptyElements();
  16608. const whitespaceElements = schema.getWhitespaceElements();
  16609. const blockElements = extend$1(makeMap('script,style,head,html,body,title,meta,param'), schema.getBlockElements());
  16610. const textRootBlockElements = getTextRootBlockElements(schema);
  16611. const allWhiteSpaceRegExp = /[ \t\r\n]+/g;
  16612. const startWhiteSpaceRegExp = /^[ \t\r\n]+/;
  16613. const endWhiteSpaceRegExp = /[ \t\r\n]+$/;
  16614. const hasWhitespaceParent = node => {
  16615. let tempNode = node.parent;
  16616. while (isNonNullable(tempNode)) {
  16617. if (tempNode.name in whitespaceElements) {
  16618. return true;
  16619. } else {
  16620. tempNode = tempNode.parent;
  16621. }
  16622. }
  16623. return false;
  16624. };
  16625. const isTextRootBlockEmpty = node => {
  16626. let tempNode = node;
  16627. while (isNonNullable(tempNode)) {
  16628. if (tempNode.name in textRootBlockElements) {
  16629. return isEmpty(schema, nonEmptyElements, whitespaceElements, tempNode);
  16630. } else {
  16631. tempNode = tempNode.parent;
  16632. }
  16633. }
  16634. return false;
  16635. };
  16636. const isBlock = node => node.name in blockElements && !isTransparentAstInline(schema, node);
  16637. const isAtEdgeOfBlock = (node, start) => {
  16638. const neighbour = start ? node.prev : node.next;
  16639. if (isNonNullable(neighbour) || isNullable(node.parent)) {
  16640. return false;
  16641. }
  16642. return isBlock(node.parent) && (node.parent !== root || args.isRootContent === true);
  16643. };
  16644. const preprocess = node => {
  16645. var _a;
  16646. if (node.type === 3) {
  16647. if (!hasWhitespaceParent(node)) {
  16648. let text = (_a = node.value) !== null && _a !== void 0 ? _a : '';
  16649. text = text.replace(allWhiteSpaceRegExp, ' ');
  16650. if (isLineBreakNode(node.prev, isBlock) || isAtEdgeOfBlock(node, true)) {
  16651. text = text.replace(startWhiteSpaceRegExp, '');
  16652. }
  16653. if (text.length === 0) {
  16654. node.remove();
  16655. } else {
  16656. node.value = text;
  16657. }
  16658. }
  16659. }
  16660. };
  16661. const postprocess = node => {
  16662. var _a;
  16663. if (node.type === 1) {
  16664. const elementRule = schema.getElementRule(node.name);
  16665. if (validate && elementRule) {
  16666. const isNodeEmpty = isEmpty(schema, nonEmptyElements, whitespaceElements, node);
  16667. if (elementRule.paddInEmptyBlock && isNodeEmpty && isTextRootBlockEmpty(node)) {
  16668. paddEmptyNode(args, isBlock, node);
  16669. } else if (elementRule.removeEmpty && isNodeEmpty) {
  16670. if (isBlock(node)) {
  16671. node.remove();
  16672. } else {
  16673. node.unwrap();
  16674. }
  16675. } else if (elementRule.paddEmpty && (isNodeEmpty || isPaddedWithNbsp(node))) {
  16676. paddEmptyNode(args, isBlock, node);
  16677. }
  16678. }
  16679. } else if (node.type === 3) {
  16680. if (!hasWhitespaceParent(node)) {
  16681. let text = (_a = node.value) !== null && _a !== void 0 ? _a : '';
  16682. if (node.next && isBlock(node.next) || isAtEdgeOfBlock(node, false)) {
  16683. text = text.replace(endWhiteSpaceRegExp, '');
  16684. }
  16685. if (text.length === 0) {
  16686. node.remove();
  16687. } else {
  16688. node.value = text;
  16689. }
  16690. }
  16691. }
  16692. };
  16693. return [
  16694. preprocess,
  16695. postprocess
  16696. ];
  16697. };
  16698. const getRootBlockName = (settings, args) => {
  16699. var _a;
  16700. const name = (_a = args.forced_root_block) !== null && _a !== void 0 ? _a : settings.forced_root_block;
  16701. if (name === false) {
  16702. return '';
  16703. } else if (name === true) {
  16704. return 'p';
  16705. } else {
  16706. return name;
  16707. }
  16708. };
  16709. const DomParser = (settings = {}, schema = Schema()) => {
  16710. const nodeFilterRegistry = create$8();
  16711. const attributeFilterRegistry = create$8();
  16712. const defaultedSettings = {
  16713. validate: true,
  16714. root_name: 'body',
  16715. sanitize: true,
  16716. ...settings
  16717. };
  16718. const parser = new DOMParser();
  16719. const sanitize = getSanitizer(defaultedSettings, schema);
  16720. const parseAndSanitizeWithContext = (html, rootName, format = 'html') => {
  16721. const mimeType = format === 'xhtml' ? 'application/xhtml+xml' : 'text/html';
  16722. const isSpecialRoot = has$2(schema.getSpecialElements(), rootName.toLowerCase());
  16723. const content = isSpecialRoot ? `<${ rootName }>${ html }</${ rootName }>` : html;
  16724. const wrappedHtml = format === 'xhtml' ? `<html xmlns="http://www.w3.org/1999/xhtml"><head></head><body>${ content }</body></html>` : `<body>${ content }</body>`;
  16725. const body = parser.parseFromString(wrappedHtml, mimeType).body;
  16726. sanitize(body, mimeType);
  16727. return isSpecialRoot ? body.firstChild : body;
  16728. };
  16729. const addNodeFilter = nodeFilterRegistry.addFilter;
  16730. const getNodeFilters = nodeFilterRegistry.getFilters;
  16731. const removeNodeFilter = nodeFilterRegistry.removeFilter;
  16732. const addAttributeFilter = attributeFilterRegistry.addFilter;
  16733. const getAttributeFilters = attributeFilterRegistry.getFilters;
  16734. const removeAttributeFilter = attributeFilterRegistry.removeFilter;
  16735. const findInvalidChildren = (node, invalidChildren) => {
  16736. if (isInvalid(schema, node)) {
  16737. invalidChildren.push(node);
  16738. }
  16739. };
  16740. const isWrappableNode = (blockElements, node) => {
  16741. const isInternalElement = isString(node.attr(internalElementAttr));
  16742. const isInlineElement = node.type === 1 && (!has$2(blockElements, node.name) && !isTransparentAstBlock(schema, node));
  16743. return node.type === 3 || isInlineElement && !isInternalElement;
  16744. };
  16745. const addRootBlocks = (rootNode, rootBlockName) => {
  16746. const blockElements = extend$1(makeMap('script,style,head,html,body,title,meta,param'), schema.getBlockElements());
  16747. const startWhiteSpaceRegExp = /^[ \t\r\n]+/;
  16748. const endWhiteSpaceRegExp = /[ \t\r\n]+$/;
  16749. let node = rootNode.firstChild, rootBlockNode = null;
  16750. const trim = rootBlock => {
  16751. var _a, _b;
  16752. if (rootBlock) {
  16753. node = rootBlock.firstChild;
  16754. if (node && node.type === 3) {
  16755. node.value = (_a = node.value) === null || _a === void 0 ? void 0 : _a.replace(startWhiteSpaceRegExp, '');
  16756. }
  16757. node = rootBlock.lastChild;
  16758. if (node && node.type === 3) {
  16759. node.value = (_b = node.value) === null || _b === void 0 ? void 0 : _b.replace(endWhiteSpaceRegExp, '');
  16760. }
  16761. }
  16762. };
  16763. if (!schema.isValidChild(rootNode.name, rootBlockName.toLowerCase())) {
  16764. return;
  16765. }
  16766. while (node) {
  16767. const next = node.next;
  16768. if (isWrappableNode(blockElements, node)) {
  16769. if (!rootBlockNode) {
  16770. rootBlockNode = new AstNode(rootBlockName, 1);
  16771. rootBlockNode.attr(defaultedSettings.forced_root_block_attrs);
  16772. rootNode.insert(rootBlockNode, node);
  16773. rootBlockNode.append(node);
  16774. } else {
  16775. rootBlockNode.append(node);
  16776. }
  16777. } else {
  16778. trim(rootBlockNode);
  16779. rootBlockNode = null;
  16780. }
  16781. node = next;
  16782. }
  16783. trim(rootBlockNode);
  16784. };
  16785. const parse = (html, args = {}) => {
  16786. var _a;
  16787. const validate = defaultedSettings.validate;
  16788. const rootName = (_a = args.context) !== null && _a !== void 0 ? _a : defaultedSettings.root_name;
  16789. const element = parseAndSanitizeWithContext(html, rootName, args.format);
  16790. updateChildren(schema, element);
  16791. const rootNode = new AstNode(rootName, 11);
  16792. transferChildren(rootNode, element, schema.getSpecialElements());
  16793. element.innerHTML = '';
  16794. const [whitespacePre, whitespacePost] = whitespaceCleaner(rootNode, schema, defaultedSettings, args);
  16795. const invalidChildren = [];
  16796. const invalidFinder = validate ? node => findInvalidChildren(node, invalidChildren) : noop;
  16797. const matches = {
  16798. nodes: {},
  16799. attributes: {}
  16800. };
  16801. const matchFinder = node => matchNode$1(getNodeFilters(), getAttributeFilters(), node, matches);
  16802. walkTree(rootNode, [
  16803. whitespacePre,
  16804. matchFinder
  16805. ], [
  16806. whitespacePost,
  16807. invalidFinder
  16808. ]);
  16809. invalidChildren.reverse();
  16810. if (validate && invalidChildren.length > 0) {
  16811. if (args.context) {
  16812. const {
  16813. pass: topLevelChildren,
  16814. fail: otherChildren
  16815. } = partition$2(invalidChildren, child => child.parent === rootNode);
  16816. cleanInvalidNodes(otherChildren, schema, rootNode, matchFinder);
  16817. args.invalid = topLevelChildren.length > 0;
  16818. } else {
  16819. cleanInvalidNodes(invalidChildren, schema, rootNode, matchFinder);
  16820. }
  16821. }
  16822. const rootBlockName = getRootBlockName(defaultedSettings, args);
  16823. if (rootBlockName && (rootNode.name === 'body' || args.isRootContent)) {
  16824. addRootBlocks(rootNode, rootBlockName);
  16825. }
  16826. if (!args.invalid) {
  16827. runFilters(matches, args);
  16828. }
  16829. return rootNode;
  16830. };
  16831. const exports = {
  16832. schema,
  16833. addAttributeFilter,
  16834. getAttributeFilters,
  16835. removeAttributeFilter,
  16836. addNodeFilter,
  16837. getNodeFilters,
  16838. removeNodeFilter,
  16839. parse
  16840. };
  16841. register$4(exports, defaultedSettings);
  16842. register$5(exports, defaultedSettings, schema);
  16843. return exports;
  16844. };
  16845. const serializeContent = content => isTreeNode(content) ? HtmlSerializer({ validate: false }).serialize(content) : content;
  16846. const withSerializedContent = (content, fireEvent, sanitize) => {
  16847. const serializedContent = serializeContent(content);
  16848. const eventArgs = fireEvent(serializedContent);
  16849. if (eventArgs.isDefaultPrevented()) {
  16850. return eventArgs;
  16851. } else if (isTreeNode(content)) {
  16852. if (eventArgs.content !== serializedContent) {
  16853. const rootNode = DomParser({
  16854. validate: false,
  16855. forced_root_block: false,
  16856. sanitize
  16857. }).parse(eventArgs.content, { context: content.name });
  16858. return {
  16859. ...eventArgs,
  16860. content: rootNode
  16861. };
  16862. } else {
  16863. return {
  16864. ...eventArgs,
  16865. content
  16866. };
  16867. }
  16868. } else {
  16869. return eventArgs;
  16870. }
  16871. };
  16872. const preProcessGetContent = (editor, args) => {
  16873. if (args.no_events) {
  16874. return Result.value(args);
  16875. } else {
  16876. const eventArgs = fireBeforeGetContent(editor, args);
  16877. if (eventArgs.isDefaultPrevented()) {
  16878. return Result.error(fireGetContent(editor, {
  16879. content: '',
  16880. ...eventArgs
  16881. }).content);
  16882. } else {
  16883. return Result.value(eventArgs);
  16884. }
  16885. }
  16886. };
  16887. const postProcessGetContent = (editor, content, args) => {
  16888. if (args.no_events) {
  16889. return content;
  16890. } else {
  16891. const processedEventArgs = withSerializedContent(content, content => fireGetContent(editor, {
  16892. ...args,
  16893. content
  16894. }), shouldSanitizeXss(editor));
  16895. return processedEventArgs.content;
  16896. }
  16897. };
  16898. const preProcessSetContent = (editor, args) => {
  16899. if (args.no_events) {
  16900. return Result.value(args);
  16901. } else {
  16902. const processedEventArgs = withSerializedContent(args.content, content => fireBeforeSetContent(editor, {
  16903. ...args,
  16904. content
  16905. }), shouldSanitizeXss(editor));
  16906. if (processedEventArgs.isDefaultPrevented()) {
  16907. fireSetContent(editor, processedEventArgs);
  16908. return Result.error(undefined);
  16909. } else {
  16910. return Result.value(processedEventArgs);
  16911. }
  16912. }
  16913. };
  16914. const postProcessSetContent = (editor, content, args) => {
  16915. if (!args.no_events) {
  16916. fireSetContent(editor, {
  16917. ...args,
  16918. content
  16919. });
  16920. }
  16921. };
  16922. const tableModel = (element, width, rows) => ({
  16923. element,
  16924. width,
  16925. rows
  16926. });
  16927. const tableRow = (element, cells) => ({
  16928. element,
  16929. cells
  16930. });
  16931. const cellPosition = (x, y) => ({
  16932. x,
  16933. y
  16934. });
  16935. const getSpan = (td, key) => {
  16936. return getOpt(td, key).bind(toInt).getOr(1);
  16937. };
  16938. const fillout = (table, x, y, tr, td) => {
  16939. const rowspan = getSpan(td, 'rowspan');
  16940. const colspan = getSpan(td, 'colspan');
  16941. const rows = table.rows;
  16942. for (let y2 = y; y2 < y + rowspan; y2++) {
  16943. if (!rows[y2]) {
  16944. rows[y2] = tableRow(deep$1(tr), []);
  16945. }
  16946. for (let x2 = x; x2 < x + colspan; x2++) {
  16947. const cells = rows[y2].cells;
  16948. cells[x2] = y2 === y && x2 === x ? td : shallow$1(td);
  16949. }
  16950. }
  16951. };
  16952. const cellExists = (table, x, y) => {
  16953. const rows = table.rows;
  16954. const cells = rows[y] ? rows[y].cells : [];
  16955. return !!cells[x];
  16956. };
  16957. const skipCellsX = (table, x, y) => {
  16958. while (cellExists(table, x, y)) {
  16959. x++;
  16960. }
  16961. return x;
  16962. };
  16963. const getWidth = rows => {
  16964. return foldl(rows, (acc, row) => {
  16965. return row.cells.length > acc ? row.cells.length : acc;
  16966. }, 0);
  16967. };
  16968. const findElementPos = (table, element) => {
  16969. const rows = table.rows;
  16970. for (let y = 0; y < rows.length; y++) {
  16971. const cells = rows[y].cells;
  16972. for (let x = 0; x < cells.length; x++) {
  16973. if (eq(cells[x], element)) {
  16974. return Optional.some(cellPosition(x, y));
  16975. }
  16976. }
  16977. }
  16978. return Optional.none();
  16979. };
  16980. const extractRows = (table, sx, sy, ex, ey) => {
  16981. const newRows = [];
  16982. const rows = table.rows;
  16983. for (let y = sy; y <= ey; y++) {
  16984. const cells = rows[y].cells;
  16985. const slice = sx < ex ? cells.slice(sx, ex + 1) : cells.slice(ex, sx + 1);
  16986. newRows.push(tableRow(rows[y].element, slice));
  16987. }
  16988. return newRows;
  16989. };
  16990. const subTable = (table, startPos, endPos) => {
  16991. const sx = startPos.x, sy = startPos.y;
  16992. const ex = endPos.x, ey = endPos.y;
  16993. const newRows = sy < ey ? extractRows(table, sx, sy, ex, ey) : extractRows(table, sx, ey, ex, sy);
  16994. return tableModel(table.element, getWidth(newRows), newRows);
  16995. };
  16996. const createDomTable = (table, rows) => {
  16997. const tableElement = shallow$1(table.element);
  16998. const tableBody = SugarElement.fromTag('tbody');
  16999. append(tableBody, rows);
  17000. append$1(tableElement, tableBody);
  17001. return tableElement;
  17002. };
  17003. const modelRowsToDomRows = table => {
  17004. return map$3(table.rows, row => {
  17005. const cells = map$3(row.cells, cell => {
  17006. const td = deep$1(cell);
  17007. remove$b(td, 'colspan');
  17008. remove$b(td, 'rowspan');
  17009. return td;
  17010. });
  17011. const tr = shallow$1(row.element);
  17012. append(tr, cells);
  17013. return tr;
  17014. });
  17015. };
  17016. const fromDom = tableElm => {
  17017. const table = tableModel(shallow$1(tableElm), 0, []);
  17018. each$e(descendants(tableElm, 'tr'), (tr, y) => {
  17019. each$e(descendants(tr, 'td,th'), (td, x) => {
  17020. fillout(table, skipCellsX(table, x, y), y, tr, td);
  17021. });
  17022. });
  17023. return tableModel(table.element, getWidth(table.rows), table.rows);
  17024. };
  17025. const toDom = table => {
  17026. return createDomTable(table, modelRowsToDomRows(table));
  17027. };
  17028. const subsection = (table, startElement, endElement) => {
  17029. return findElementPos(table, startElement).bind(startPos => {
  17030. return findElementPos(table, endElement).map(endPos => {
  17031. return subTable(table, startPos, endPos);
  17032. });
  17033. });
  17034. };
  17035. const findParentListContainer = parents => find$2(parents, elm => name(elm) === 'ul' || name(elm) === 'ol');
  17036. const getFullySelectedListWrappers = (parents, rng) => find$2(parents, elm => name(elm) === 'li' && hasAllContentsSelected(elm, rng)).fold(constant([]), _li => findParentListContainer(parents).map(listCont => {
  17037. const listElm = SugarElement.fromTag(name(listCont));
  17038. const listStyles = filter$4(getAllRaw(listCont), (_style, name) => startsWith(name, 'list-style'));
  17039. setAll(listElm, listStyles);
  17040. return [
  17041. SugarElement.fromTag('li'),
  17042. listElm
  17043. ];
  17044. }).getOr([]));
  17045. const wrap = (innerElm, elms) => {
  17046. const wrapped = foldl(elms, (acc, elm) => {
  17047. append$1(elm, acc);
  17048. return elm;
  17049. }, innerElm);
  17050. return elms.length > 0 ? fromElements([wrapped]) : wrapped;
  17051. };
  17052. const directListWrappers = commonAnchorContainer => {
  17053. if (isListItem$1(commonAnchorContainer)) {
  17054. return parent(commonAnchorContainer).filter(isList).fold(constant([]), listElm => [
  17055. commonAnchorContainer,
  17056. listElm
  17057. ]);
  17058. } else {
  17059. return isList(commonAnchorContainer) ? [commonAnchorContainer] : [];
  17060. }
  17061. };
  17062. const getWrapElements = (rootNode, rng) => {
  17063. const commonAnchorContainer = SugarElement.fromDom(rng.commonAncestorContainer);
  17064. const parents = parentsAndSelf(commonAnchorContainer, rootNode);
  17065. const wrapElements = filter$5(parents, isWrapElement);
  17066. const listWrappers = getFullySelectedListWrappers(parents, rng);
  17067. const allWrappers = wrapElements.concat(listWrappers.length ? listWrappers : directListWrappers(commonAnchorContainer));
  17068. return map$3(allWrappers, shallow$1);
  17069. };
  17070. const emptyFragment = () => fromElements([]);
  17071. const getFragmentFromRange = (rootNode, rng) => wrap(SugarElement.fromDom(rng.cloneContents()), getWrapElements(rootNode, rng));
  17072. const getParentTable = (rootElm, cell) => ancestor$3(cell, 'table', curry(eq, rootElm));
  17073. const getTableFragment = (rootNode, selectedTableCells) => getParentTable(rootNode, selectedTableCells[0]).bind(tableElm => {
  17074. const firstCell = selectedTableCells[0];
  17075. const lastCell = selectedTableCells[selectedTableCells.length - 1];
  17076. const fullTableModel = fromDom(tableElm);
  17077. return subsection(fullTableModel, firstCell, lastCell).map(sectionedTableModel => fromElements([toDom(sectionedTableModel)]));
  17078. }).getOrThunk(emptyFragment);
  17079. const getSelectionFragment = (rootNode, ranges) => ranges.length > 0 && ranges[0].collapsed ? emptyFragment() : getFragmentFromRange(rootNode, ranges[0]);
  17080. const read$3 = (rootNode, ranges) => {
  17081. const selectedCells = getCellsFromElementOrRanges(ranges, rootNode);
  17082. return selectedCells.length > 0 ? getTableFragment(rootNode, selectedCells) : getSelectionFragment(rootNode, ranges);
  17083. };
  17084. const isCollapsibleWhitespace = (text, index) => index >= 0 && index < text.length && isWhiteSpace(text.charAt(index));
  17085. const getInnerText = bin => {
  17086. return trim$1(bin.innerText);
  17087. };
  17088. const getContextNodeName = parentBlockOpt => parentBlockOpt.map(block => block.nodeName).getOr('div').toLowerCase();
  17089. const getTextContent = editor => Optional.from(editor.selection.getRng()).map(rng => {
  17090. var _a;
  17091. const parentBlockOpt = Optional.from(editor.dom.getParent(rng.commonAncestorContainer, editor.dom.isBlock));
  17092. const body = editor.getBody();
  17093. const contextNodeName = getContextNodeName(parentBlockOpt);
  17094. const rangeContentClone = SugarElement.fromDom(rng.cloneContents());
  17095. cleanupBogusElements(rangeContentClone);
  17096. cleanupInputNames(rangeContentClone);
  17097. const bin = editor.dom.add(body, contextNodeName, {
  17098. 'data-mce-bogus': 'all',
  17099. 'style': 'overflow: hidden; opacity: 0;'
  17100. }, rangeContentClone.dom);
  17101. const text = getInnerText(bin);
  17102. const nonRenderedText = trim$1((_a = bin.textContent) !== null && _a !== void 0 ? _a : '');
  17103. editor.dom.remove(bin);
  17104. if (isCollapsibleWhitespace(nonRenderedText, 0) || isCollapsibleWhitespace(nonRenderedText, nonRenderedText.length - 1)) {
  17105. const parentBlock = parentBlockOpt.getOr(body);
  17106. const parentBlockText = getInnerText(parentBlock);
  17107. const textIndex = parentBlockText.indexOf(text);
  17108. if (textIndex === -1) {
  17109. return text;
  17110. } else {
  17111. const hasProceedingSpace = isCollapsibleWhitespace(parentBlockText, textIndex - 1);
  17112. const hasTrailingSpace = isCollapsibleWhitespace(parentBlockText, textIndex + text.length);
  17113. return (hasProceedingSpace ? ' ' : '') + text + (hasTrailingSpace ? ' ' : '');
  17114. }
  17115. } else {
  17116. return text;
  17117. }
  17118. }).getOr('');
  17119. const getSerializedContent = (editor, args) => {
  17120. const rng = editor.selection.getRng(), tmpElm = editor.dom.create('body');
  17121. const sel = editor.selection.getSel();
  17122. const ranges = processRanges(editor, getRanges$1(sel));
  17123. const fragment = args.contextual ? read$3(SugarElement.fromDom(editor.getBody()), ranges).dom : rng.cloneContents();
  17124. if (fragment) {
  17125. tmpElm.appendChild(fragment);
  17126. }
  17127. return editor.selection.serializer.serialize(tmpElm, args);
  17128. };
  17129. const extractSelectedContent = (editor, args) => {
  17130. if (args.format === 'text') {
  17131. return getTextContent(editor);
  17132. } else {
  17133. const content = getSerializedContent(editor, args);
  17134. if (args.format === 'tree') {
  17135. return content;
  17136. } else {
  17137. return editor.selection.isCollapsed() ? '' : content;
  17138. }
  17139. }
  17140. };
  17141. const setupArgs$3 = (args, format) => ({
  17142. ...args,
  17143. format,
  17144. get: true,
  17145. selection: true,
  17146. getInner: true
  17147. });
  17148. const getSelectedContentInternal = (editor, format, args = {}) => {
  17149. const defaultedArgs = setupArgs$3(args, format);
  17150. return preProcessGetContent(editor, defaultedArgs).fold(identity, updatedArgs => {
  17151. const content = extractSelectedContent(editor, updatedArgs);
  17152. return postProcessGetContent(editor, content, updatedArgs);
  17153. });
  17154. };
  17155. const KEEP = 0, INSERT = 1, DELETE = 2;
  17156. const diff = (left, right) => {
  17157. const size = left.length + right.length + 2;
  17158. const vDown = new Array(size);
  17159. const vUp = new Array(size);
  17160. const snake = (start, end, diag) => {
  17161. return {
  17162. start,
  17163. end,
  17164. diag
  17165. };
  17166. };
  17167. const buildScript = (start1, end1, start2, end2, script) => {
  17168. const middle = getMiddleSnake(start1, end1, start2, end2);
  17169. if (middle === null || middle.start === end1 && middle.diag === end1 - end2 || middle.end === start1 && middle.diag === start1 - start2) {
  17170. let i = start1;
  17171. let j = start2;
  17172. while (i < end1 || j < end2) {
  17173. if (i < end1 && j < end2 && left[i] === right[j]) {
  17174. script.push([
  17175. KEEP,
  17176. left[i]
  17177. ]);
  17178. ++i;
  17179. ++j;
  17180. } else {
  17181. if (end1 - start1 > end2 - start2) {
  17182. script.push([
  17183. DELETE,
  17184. left[i]
  17185. ]);
  17186. ++i;
  17187. } else {
  17188. script.push([
  17189. INSERT,
  17190. right[j]
  17191. ]);
  17192. ++j;
  17193. }
  17194. }
  17195. }
  17196. } else {
  17197. buildScript(start1, middle.start, start2, middle.start - middle.diag, script);
  17198. for (let i2 = middle.start; i2 < middle.end; ++i2) {
  17199. script.push([
  17200. KEEP,
  17201. left[i2]
  17202. ]);
  17203. }
  17204. buildScript(middle.end, end1, middle.end - middle.diag, end2, script);
  17205. }
  17206. };
  17207. const buildSnake = (start, diag, end1, end2) => {
  17208. let end = start;
  17209. while (end - diag < end2 && end < end1 && left[end] === right[end - diag]) {
  17210. ++end;
  17211. }
  17212. return snake(start, end, diag);
  17213. };
  17214. const getMiddleSnake = (start1, end1, start2, end2) => {
  17215. const m = end1 - start1;
  17216. const n = end2 - start2;
  17217. if (m === 0 || n === 0) {
  17218. return null;
  17219. }
  17220. const delta = m - n;
  17221. const sum = n + m;
  17222. const offset = (sum % 2 === 0 ? sum : sum + 1) / 2;
  17223. vDown[1 + offset] = start1;
  17224. vUp[1 + offset] = end1 + 1;
  17225. let d, k, i, x, y;
  17226. for (d = 0; d <= offset; ++d) {
  17227. for (k = -d; k <= d; k += 2) {
  17228. i = k + offset;
  17229. if (k === -d || k !== d && vDown[i - 1] < vDown[i + 1]) {
  17230. vDown[i] = vDown[i + 1];
  17231. } else {
  17232. vDown[i] = vDown[i - 1] + 1;
  17233. }
  17234. x = vDown[i];
  17235. y = x - start1 + start2 - k;
  17236. while (x < end1 && y < end2 && left[x] === right[y]) {
  17237. vDown[i] = ++x;
  17238. ++y;
  17239. }
  17240. if (delta % 2 !== 0 && delta - d <= k && k <= delta + d) {
  17241. if (vUp[i - delta] <= vDown[i]) {
  17242. return buildSnake(vUp[i - delta], k + start1 - start2, end1, end2);
  17243. }
  17244. }
  17245. }
  17246. for (k = delta - d; k <= delta + d; k += 2) {
  17247. i = k + offset - delta;
  17248. if (k === delta - d || k !== delta + d && vUp[i + 1] <= vUp[i - 1]) {
  17249. vUp[i] = vUp[i + 1] - 1;
  17250. } else {
  17251. vUp[i] = vUp[i - 1];
  17252. }
  17253. x = vUp[i] - 1;
  17254. y = x - start1 + start2 - k;
  17255. while (x >= start1 && y >= start2 && left[x] === right[y]) {
  17256. vUp[i] = x--;
  17257. y--;
  17258. }
  17259. if (delta % 2 === 0 && -d <= k && k <= d) {
  17260. if (vUp[i] <= vDown[i + delta]) {
  17261. return buildSnake(vUp[i], k + start1 - start2, end1, end2);
  17262. }
  17263. }
  17264. }
  17265. }
  17266. return null;
  17267. };
  17268. const script = [];
  17269. buildScript(0, left.length, 0, right.length, script);
  17270. return script;
  17271. };
  17272. const getOuterHtml = elm => {
  17273. if (isElement$6(elm)) {
  17274. return elm.outerHTML;
  17275. } else if (isText$a(elm)) {
  17276. return Entities.encodeRaw(elm.data, false);
  17277. } else if (isComment(elm)) {
  17278. return '<!--' + elm.data + '-->';
  17279. }
  17280. return '';
  17281. };
  17282. const createFragment = html => {
  17283. let node;
  17284. const container = document.createElement('div');
  17285. const frag = document.createDocumentFragment();
  17286. if (html) {
  17287. container.innerHTML = html;
  17288. }
  17289. while (node = container.firstChild) {
  17290. frag.appendChild(node);
  17291. }
  17292. return frag;
  17293. };
  17294. const insertAt = (elm, html, index) => {
  17295. const fragment = createFragment(html);
  17296. if (elm.hasChildNodes() && index < elm.childNodes.length) {
  17297. const target = elm.childNodes[index];
  17298. elm.insertBefore(fragment, target);
  17299. } else {
  17300. elm.appendChild(fragment);
  17301. }
  17302. };
  17303. const removeAt = (elm, index) => {
  17304. if (elm.hasChildNodes() && index < elm.childNodes.length) {
  17305. const target = elm.childNodes[index];
  17306. elm.removeChild(target);
  17307. }
  17308. };
  17309. const applyDiff = (diff, elm) => {
  17310. let index = 0;
  17311. each$e(diff, action => {
  17312. if (action[0] === KEEP) {
  17313. index++;
  17314. } else if (action[0] === INSERT) {
  17315. insertAt(elm, action[1], index);
  17316. index++;
  17317. } else if (action[0] === DELETE) {
  17318. removeAt(elm, index);
  17319. }
  17320. });
  17321. };
  17322. const read$2 = elm => {
  17323. return filter$5(map$3(from(elm.childNodes), getOuterHtml), item => {
  17324. return item.length > 0;
  17325. });
  17326. };
  17327. const write = (fragments, elm) => {
  17328. const currentFragments = map$3(from(elm.childNodes), getOuterHtml);
  17329. applyDiff(diff(currentFragments, fragments), elm);
  17330. return elm;
  17331. };
  17332. const lazyTempDocument = cached(() => document.implementation.createHTMLDocument('undo'));
  17333. const hasIframes = html => {
  17334. return html.indexOf('</iframe>') !== -1;
  17335. };
  17336. const createFragmentedLevel = fragments => {
  17337. return {
  17338. type: 'fragmented',
  17339. fragments,
  17340. content: '',
  17341. bookmark: null,
  17342. beforeBookmark: null
  17343. };
  17344. };
  17345. const createCompleteLevel = content => {
  17346. return {
  17347. type: 'complete',
  17348. fragments: null,
  17349. content,
  17350. bookmark: null,
  17351. beforeBookmark: null
  17352. };
  17353. };
  17354. const createFromEditor = editor => {
  17355. const fragments = read$2(editor.getBody());
  17356. const trimmedFragments = bind$3(fragments, html => {
  17357. const trimmed = trimInternal(editor.serializer, html);
  17358. return trimmed.length > 0 ? [trimmed] : [];
  17359. });
  17360. const content = trimmedFragments.join('');
  17361. return hasIframes(content) ? createFragmentedLevel(trimmedFragments) : createCompleteLevel(content);
  17362. };
  17363. const applyToEditor = (editor, level, before) => {
  17364. const bookmark = before ? level.beforeBookmark : level.bookmark;
  17365. if (level.type === 'fragmented') {
  17366. write(level.fragments, editor.getBody());
  17367. } else {
  17368. editor.setContent(level.content, {
  17369. format: 'raw',
  17370. no_selection: isNonNullable(bookmark) && isPathBookmark(bookmark) ? !bookmark.isFakeCaret : true
  17371. });
  17372. }
  17373. if (bookmark) {
  17374. editor.selection.moveToBookmark(bookmark);
  17375. editor.selection.scrollIntoView();
  17376. }
  17377. };
  17378. const getLevelContent = level => {
  17379. return level.type === 'fragmented' ? level.fragments.join('') : level.content;
  17380. };
  17381. const getCleanLevelContent = level => {
  17382. const elm = SugarElement.fromTag('body', lazyTempDocument());
  17383. set$1(elm, getLevelContent(level));
  17384. each$e(descendants(elm, '*[data-mce-bogus]'), unwrap);
  17385. return get$6(elm);
  17386. };
  17387. const hasEqualContent = (level1, level2) => getLevelContent(level1) === getLevelContent(level2);
  17388. const hasEqualCleanedContent = (level1, level2) => getCleanLevelContent(level1) === getCleanLevelContent(level2);
  17389. const isEq$1 = (level1, level2) => {
  17390. if (!level1 || !level2) {
  17391. return false;
  17392. } else if (hasEqualContent(level1, level2)) {
  17393. return true;
  17394. } else {
  17395. return hasEqualCleanedContent(level1, level2);
  17396. }
  17397. };
  17398. const isUnlocked = locks => locks.get() === 0;
  17399. const setTyping = (undoManager, typing, locks) => {
  17400. if (isUnlocked(locks)) {
  17401. undoManager.typing = typing;
  17402. }
  17403. };
  17404. const endTyping = (undoManager, locks) => {
  17405. if (undoManager.typing) {
  17406. setTyping(undoManager, false, locks);
  17407. undoManager.add();
  17408. }
  17409. };
  17410. const endTypingLevelIgnoreLocks = undoManager => {
  17411. if (undoManager.typing) {
  17412. undoManager.typing = false;
  17413. undoManager.add();
  17414. }
  17415. };
  17416. const beforeChange$1 = (editor, locks, beforeBookmark) => {
  17417. if (isUnlocked(locks)) {
  17418. beforeBookmark.set(getUndoBookmark(editor.selection));
  17419. }
  17420. };
  17421. const addUndoLevel$1 = (editor, undoManager, index, locks, beforeBookmark, level, event) => {
  17422. const currentLevel = createFromEditor(editor);
  17423. const newLevel = Tools.extend(level || {}, currentLevel);
  17424. if (!isUnlocked(locks) || editor.removed) {
  17425. return null;
  17426. }
  17427. const lastLevel = undoManager.data[index.get()];
  17428. if (editor.dispatch('BeforeAddUndo', {
  17429. level: newLevel,
  17430. lastLevel,
  17431. originalEvent: event
  17432. }).isDefaultPrevented()) {
  17433. return null;
  17434. }
  17435. if (lastLevel && isEq$1(lastLevel, newLevel)) {
  17436. return null;
  17437. }
  17438. if (undoManager.data[index.get()]) {
  17439. beforeBookmark.get().each(bm => {
  17440. undoManager.data[index.get()].beforeBookmark = bm;
  17441. });
  17442. }
  17443. const customUndoRedoLevels = getCustomUndoRedoLevels(editor);
  17444. if (customUndoRedoLevels) {
  17445. if (undoManager.data.length > customUndoRedoLevels) {
  17446. for (let i = 0; i < undoManager.data.length - 1; i++) {
  17447. undoManager.data[i] = undoManager.data[i + 1];
  17448. }
  17449. undoManager.data.length--;
  17450. index.set(undoManager.data.length);
  17451. }
  17452. }
  17453. newLevel.bookmark = getUndoBookmark(editor.selection);
  17454. if (index.get() < undoManager.data.length - 1) {
  17455. undoManager.data.length = index.get() + 1;
  17456. }
  17457. undoManager.data.push(newLevel);
  17458. index.set(undoManager.data.length - 1);
  17459. const args = {
  17460. level: newLevel,
  17461. lastLevel,
  17462. originalEvent: event
  17463. };
  17464. if (index.get() > 0) {
  17465. editor.setDirty(true);
  17466. editor.dispatch('AddUndo', args);
  17467. editor.dispatch('change', args);
  17468. } else {
  17469. editor.dispatch('AddUndo', args);
  17470. }
  17471. return newLevel;
  17472. };
  17473. const clear$1 = (editor, undoManager, index) => {
  17474. undoManager.data = [];
  17475. index.set(0);
  17476. undoManager.typing = false;
  17477. editor.dispatch('ClearUndos');
  17478. };
  17479. const extra$1 = (editor, undoManager, index, callback1, callback2) => {
  17480. if (undoManager.transact(callback1)) {
  17481. const bookmark = undoManager.data[index.get()].bookmark;
  17482. const lastLevel = undoManager.data[index.get() - 1];
  17483. applyToEditor(editor, lastLevel, true);
  17484. if (undoManager.transact(callback2)) {
  17485. undoManager.data[index.get() - 1].beforeBookmark = bookmark;
  17486. }
  17487. }
  17488. };
  17489. const redo$1 = (editor, index, data) => {
  17490. let level;
  17491. if (index.get() < data.length - 1) {
  17492. index.set(index.get() + 1);
  17493. level = data[index.get()];
  17494. applyToEditor(editor, level, false);
  17495. editor.setDirty(true);
  17496. editor.dispatch('Redo', { level });
  17497. }
  17498. return level;
  17499. };
  17500. const undo$1 = (editor, undoManager, locks, index) => {
  17501. let level;
  17502. if (undoManager.typing) {
  17503. undoManager.add();
  17504. undoManager.typing = false;
  17505. setTyping(undoManager, false, locks);
  17506. }
  17507. if (index.get() > 0) {
  17508. index.set(index.get() - 1);
  17509. level = undoManager.data[index.get()];
  17510. applyToEditor(editor, level, true);
  17511. editor.setDirty(true);
  17512. editor.dispatch('Undo', { level });
  17513. }
  17514. return level;
  17515. };
  17516. const reset$1 = undoManager => {
  17517. undoManager.clear();
  17518. undoManager.add();
  17519. };
  17520. const hasUndo$1 = (editor, undoManager, index) => index.get() > 0 || undoManager.typing && undoManager.data[0] && !isEq$1(createFromEditor(editor), undoManager.data[0]);
  17521. const hasRedo$1 = (undoManager, index) => index.get() < undoManager.data.length - 1 && !undoManager.typing;
  17522. const transact$1 = (undoManager, locks, callback) => {
  17523. endTyping(undoManager, locks);
  17524. undoManager.beforeChange();
  17525. undoManager.ignore(callback);
  17526. return undoManager.add();
  17527. };
  17528. const ignore$1 = (locks, callback) => {
  17529. try {
  17530. locks.set(locks.get() + 1);
  17531. callback();
  17532. } finally {
  17533. locks.set(locks.get() - 1);
  17534. }
  17535. };
  17536. const addVisualInternal = (editor, elm) => {
  17537. const dom = editor.dom;
  17538. const scope = isNonNullable(elm) ? elm : editor.getBody();
  17539. each$e(dom.select('table,a', scope), matchedElm => {
  17540. switch (matchedElm.nodeName) {
  17541. case 'TABLE':
  17542. const cls = getVisualAidsTableClass(editor);
  17543. const value = dom.getAttrib(matchedElm, 'border');
  17544. if ((!value || value === '0') && editor.hasVisual) {
  17545. dom.addClass(matchedElm, cls);
  17546. } else {
  17547. dom.removeClass(matchedElm, cls);
  17548. }
  17549. break;
  17550. case 'A':
  17551. if (!dom.getAttrib(matchedElm, 'href')) {
  17552. const value = dom.getAttrib(matchedElm, 'name') || matchedElm.id;
  17553. const cls = getVisualAidsAnchorClass(editor);
  17554. if (value && editor.hasVisual) {
  17555. dom.addClass(matchedElm, cls);
  17556. } else {
  17557. dom.removeClass(matchedElm, cls);
  17558. }
  17559. }
  17560. break;
  17561. }
  17562. });
  17563. editor.dispatch('VisualAid', {
  17564. element: elm,
  17565. hasVisual: editor.hasVisual
  17566. });
  17567. };
  17568. const makePlainAdaptor = editor => ({
  17569. init: { bindEvents: noop },
  17570. undoManager: {
  17571. beforeChange: (locks, beforeBookmark) => beforeChange$1(editor, locks, beforeBookmark),
  17572. add: (undoManager, index, locks, beforeBookmark, level, event) => addUndoLevel$1(editor, undoManager, index, locks, beforeBookmark, level, event),
  17573. undo: (undoManager, locks, index) => undo$1(editor, undoManager, locks, index),
  17574. redo: (index, data) => redo$1(editor, index, data),
  17575. clear: (undoManager, index) => clear$1(editor, undoManager, index),
  17576. reset: undoManager => reset$1(undoManager),
  17577. hasUndo: (undoManager, index) => hasUndo$1(editor, undoManager, index),
  17578. hasRedo: (undoManager, index) => hasRedo$1(undoManager, index),
  17579. transact: (undoManager, locks, callback) => transact$1(undoManager, locks, callback),
  17580. ignore: (locks, callback) => ignore$1(locks, callback),
  17581. extra: (undoManager, index, callback1, callback2) => extra$1(editor, undoManager, index, callback1, callback2)
  17582. },
  17583. formatter: {
  17584. match: (name, vars, node, similar) => match$2(editor, name, vars, node, similar),
  17585. matchAll: (names, vars) => matchAll(editor, names, vars),
  17586. matchNode: (node, name, vars, similar) => matchNode(editor, node, name, vars, similar),
  17587. canApply: name => canApply(editor, name),
  17588. closest: names => closest(editor, names),
  17589. apply: (name, vars, node) => applyFormat$1(editor, name, vars, node),
  17590. remove: (name, vars, node, similar) => remove$2(editor, name, vars, node, similar),
  17591. toggle: (name, vars, node) => toggle(editor, name, vars, node),
  17592. formatChanged: (registeredFormatListeners, formats, callback, similar, vars) => formatChangedInternal(editor, registeredFormatListeners, formats, callback, similar, vars)
  17593. },
  17594. editor: {
  17595. getContent: args => getContentInternal(editor, args),
  17596. setContent: (content, args) => setContentInternal(editor, content, args),
  17597. insertContent: (value, details) => insertHtmlAtCaret(editor, value, details),
  17598. addVisual: elm => addVisualInternal(editor, elm)
  17599. },
  17600. selection: { getContent: (format, args) => getSelectedContentInternal(editor, format, args) },
  17601. autocompleter: {
  17602. addDecoration: range => create$9(editor, range),
  17603. removeDecoration: () => remove$3(editor, SugarElement.fromDom(editor.getBody()))
  17604. },
  17605. raw: { getModel: () => Optional.none() }
  17606. });
  17607. const makeRtcAdaptor = rtcEditor => {
  17608. const defaultVars = vars => isObject(vars) ? vars : {};
  17609. const {init, undoManager, formatter, editor, selection, autocompleter, raw} = rtcEditor;
  17610. return {
  17611. init: { bindEvents: init.bindEvents },
  17612. undoManager: {
  17613. beforeChange: undoManager.beforeChange,
  17614. add: undoManager.add,
  17615. undo: undoManager.undo,
  17616. redo: undoManager.redo,
  17617. clear: undoManager.clear,
  17618. reset: undoManager.reset,
  17619. hasUndo: undoManager.hasUndo,
  17620. hasRedo: undoManager.hasRedo,
  17621. transact: (_undoManager, _locks, fn) => undoManager.transact(fn),
  17622. ignore: (_locks, callback) => undoManager.ignore(callback),
  17623. extra: (_undoManager, _index, callback1, callback2) => undoManager.extra(callback1, callback2)
  17624. },
  17625. formatter: {
  17626. match: (name, vars, _node, similar) => formatter.match(name, defaultVars(vars), similar),
  17627. matchAll: formatter.matchAll,
  17628. matchNode: formatter.matchNode,
  17629. canApply: name => formatter.canApply(name),
  17630. closest: names => formatter.closest(names),
  17631. apply: (name, vars, _node) => formatter.apply(name, defaultVars(vars)),
  17632. remove: (name, vars, _node, _similar) => formatter.remove(name, defaultVars(vars)),
  17633. toggle: (name, vars, _node) => formatter.toggle(name, defaultVars(vars)),
  17634. formatChanged: (_rfl, formats, callback, similar, vars) => formatter.formatChanged(formats, callback, similar, vars)
  17635. },
  17636. editor: {
  17637. getContent: args => editor.getContent(args),
  17638. setContent: (content, args) => {
  17639. return {
  17640. content: editor.setContent(content, args),
  17641. html: ''
  17642. };
  17643. },
  17644. insertContent: (content, _details) => {
  17645. editor.insertContent(content);
  17646. return '';
  17647. },
  17648. addVisual: editor.addVisual
  17649. },
  17650. selection: { getContent: (_format, args) => selection.getContent(args) },
  17651. autocompleter: {
  17652. addDecoration: autocompleter.addDecoration,
  17653. removeDecoration: autocompleter.removeDecoration
  17654. },
  17655. raw: { getModel: () => Optional.some(raw.getRawModel()) }
  17656. };
  17657. };
  17658. const makeNoopAdaptor = () => {
  17659. const nul = constant(null);
  17660. const empty = constant('');
  17661. return {
  17662. init: { bindEvents: noop },
  17663. undoManager: {
  17664. beforeChange: noop,
  17665. add: nul,
  17666. undo: nul,
  17667. redo: nul,
  17668. clear: noop,
  17669. reset: noop,
  17670. hasUndo: never,
  17671. hasRedo: never,
  17672. transact: nul,
  17673. ignore: noop,
  17674. extra: noop
  17675. },
  17676. formatter: {
  17677. match: never,
  17678. matchAll: constant([]),
  17679. matchNode: constant(undefined),
  17680. canApply: never,
  17681. closest: empty,
  17682. apply: noop,
  17683. remove: noop,
  17684. toggle: noop,
  17685. formatChanged: constant({ unbind: noop })
  17686. },
  17687. editor: {
  17688. getContent: empty,
  17689. setContent: constant({
  17690. content: '',
  17691. html: ''
  17692. }),
  17693. insertContent: constant(''),
  17694. addVisual: noop
  17695. },
  17696. selection: { getContent: empty },
  17697. autocompleter: {
  17698. addDecoration: noop,
  17699. removeDecoration: noop
  17700. },
  17701. raw: { getModel: constant(Optional.none()) }
  17702. };
  17703. };
  17704. const isRtc = editor => has$2(editor.plugins, 'rtc');
  17705. const getRtcSetup = editor => get$a(editor.plugins, 'rtc').bind(rtcPlugin => Optional.from(rtcPlugin.setup));
  17706. const setup$s = editor => {
  17707. const editorCast = editor;
  17708. return getRtcSetup(editor).fold(() => {
  17709. editorCast.rtcInstance = makePlainAdaptor(editor);
  17710. return Optional.none();
  17711. }, setup => {
  17712. editorCast.rtcInstance = makeNoopAdaptor();
  17713. return Optional.some(() => setup().then(rtcEditor => {
  17714. editorCast.rtcInstance = makeRtcAdaptor(rtcEditor);
  17715. return rtcEditor.rtc.isRemote;
  17716. }));
  17717. });
  17718. };
  17719. const getRtcInstanceWithFallback = editor => editor.rtcInstance ? editor.rtcInstance : makePlainAdaptor(editor);
  17720. const getRtcInstanceWithError = editor => {
  17721. const rtcInstance = editor.rtcInstance;
  17722. if (!rtcInstance) {
  17723. throw new Error('Failed to get RTC instance not yet initialized.');
  17724. } else {
  17725. return rtcInstance;
  17726. }
  17727. };
  17728. const beforeChange = (editor, locks, beforeBookmark) => {
  17729. getRtcInstanceWithError(editor).undoManager.beforeChange(locks, beforeBookmark);
  17730. };
  17731. const addUndoLevel = (editor, undoManager, index, locks, beforeBookmark, level, event) => getRtcInstanceWithError(editor).undoManager.add(undoManager, index, locks, beforeBookmark, level, event);
  17732. const undo = (editor, undoManager, locks, index) => getRtcInstanceWithError(editor).undoManager.undo(undoManager, locks, index);
  17733. const redo = (editor, index, data) => getRtcInstanceWithError(editor).undoManager.redo(index, data);
  17734. const clear = (editor, undoManager, index) => {
  17735. getRtcInstanceWithError(editor).undoManager.clear(undoManager, index);
  17736. };
  17737. const reset = (editor, undoManager) => {
  17738. getRtcInstanceWithError(editor).undoManager.reset(undoManager);
  17739. };
  17740. const hasUndo = (editor, undoManager, index) => getRtcInstanceWithError(editor).undoManager.hasUndo(undoManager, index);
  17741. const hasRedo = (editor, undoManager, index) => getRtcInstanceWithError(editor).undoManager.hasRedo(undoManager, index);
  17742. const transact = (editor, undoManager, locks, callback) => getRtcInstanceWithError(editor).undoManager.transact(undoManager, locks, callback);
  17743. const ignore = (editor, locks, callback) => {
  17744. getRtcInstanceWithError(editor).undoManager.ignore(locks, callback);
  17745. };
  17746. const extra = (editor, undoManager, index, callback1, callback2) => {
  17747. getRtcInstanceWithError(editor).undoManager.extra(undoManager, index, callback1, callback2);
  17748. };
  17749. const matchFormat = (editor, name, vars, node, similar) => getRtcInstanceWithError(editor).formatter.match(name, vars, node, similar);
  17750. const matchAllFormats = (editor, names, vars) => getRtcInstanceWithError(editor).formatter.matchAll(names, vars);
  17751. const matchNodeFormat = (editor, node, name, vars, similar) => getRtcInstanceWithError(editor).formatter.matchNode(node, name, vars, similar);
  17752. const canApplyFormat = (editor, name) => getRtcInstanceWithError(editor).formatter.canApply(name);
  17753. const closestFormat = (editor, names) => getRtcInstanceWithError(editor).formatter.closest(names);
  17754. const applyFormat = (editor, name, vars, node) => {
  17755. getRtcInstanceWithError(editor).formatter.apply(name, vars, node);
  17756. };
  17757. const removeFormat = (editor, name, vars, node, similar) => {
  17758. getRtcInstanceWithError(editor).formatter.remove(name, vars, node, similar);
  17759. };
  17760. const toggleFormat = (editor, name, vars, node) => {
  17761. getRtcInstanceWithError(editor).formatter.toggle(name, vars, node);
  17762. };
  17763. const formatChanged = (editor, registeredFormatListeners, formats, callback, similar, vars) => getRtcInstanceWithError(editor).formatter.formatChanged(registeredFormatListeners, formats, callback, similar, vars);
  17764. const getContent$2 = (editor, args) => getRtcInstanceWithFallback(editor).editor.getContent(args);
  17765. const setContent$2 = (editor, content, args) => getRtcInstanceWithFallback(editor).editor.setContent(content, args);
  17766. const insertContent$1 = (editor, value, details) => getRtcInstanceWithFallback(editor).editor.insertContent(value, details);
  17767. const getSelectedContent = (editor, format, args) => getRtcInstanceWithError(editor).selection.getContent(format, args);
  17768. const addVisual$1 = (editor, elm) => getRtcInstanceWithError(editor).editor.addVisual(elm);
  17769. const bindEvents = editor => getRtcInstanceWithError(editor).init.bindEvents();
  17770. const addAutocompleterDecoration = (editor, range) => getRtcInstanceWithError(editor).autocompleter.addDecoration(range);
  17771. const removeAutocompleterDecoration = editor => getRtcInstanceWithError(editor).autocompleter.removeDecoration();
  17772. const getContent$1 = (editor, args = {}) => {
  17773. const format = args.format ? args.format : 'html';
  17774. return getSelectedContent(editor, format, args);
  17775. };
  17776. const removeEmpty = text => {
  17777. if (text.dom.length === 0) {
  17778. remove$6(text);
  17779. return Optional.none();
  17780. } else {
  17781. return Optional.some(text);
  17782. }
  17783. };
  17784. const walkPastBookmark = (node, start) => node.filter(elm => BookmarkManager.isBookmarkNode(elm.dom)).bind(start ? nextSibling : prevSibling);
  17785. const merge$1 = (outer, inner, rng, start) => {
  17786. const outerElm = outer.dom;
  17787. const innerElm = inner.dom;
  17788. const oldLength = start ? outerElm.length : innerElm.length;
  17789. if (start) {
  17790. mergeTextNodes(outerElm, innerElm, false, !start);
  17791. rng.setStart(innerElm, oldLength);
  17792. } else {
  17793. mergeTextNodes(innerElm, outerElm, false, !start);
  17794. rng.setEnd(innerElm, oldLength);
  17795. }
  17796. };
  17797. const normalizeTextIfRequired = (inner, start) => {
  17798. parent(inner).each(root => {
  17799. const text = inner.dom;
  17800. if (start && needsToBeNbspLeft(root, CaretPosition(text, 0))) {
  17801. normalizeWhitespaceAfter(text, 0);
  17802. } else if (!start && needsToBeNbspRight(root, CaretPosition(text, text.length))) {
  17803. normalizeWhitespaceBefore(text, text.length);
  17804. }
  17805. });
  17806. };
  17807. const mergeAndNormalizeText = (outerNode, innerNode, rng, start) => {
  17808. outerNode.bind(outer => {
  17809. const normalizer = start ? normalizeWhitespaceBefore : normalizeWhitespaceAfter;
  17810. normalizer(outer.dom, start ? outer.dom.length : 0);
  17811. return innerNode.filter(isText$b).map(inner => merge$1(outer, inner, rng, start));
  17812. }).orThunk(() => {
  17813. const innerTextNode = walkPastBookmark(innerNode, start).or(innerNode).filter(isText$b);
  17814. return innerTextNode.map(inner => normalizeTextIfRequired(inner, start));
  17815. });
  17816. };
  17817. const rngSetContent = (rng, fragment) => {
  17818. const firstChild = Optional.from(fragment.firstChild).map(SugarElement.fromDom);
  17819. const lastChild = Optional.from(fragment.lastChild).map(SugarElement.fromDom);
  17820. rng.deleteContents();
  17821. rng.insertNode(fragment);
  17822. const prevText = firstChild.bind(prevSibling).filter(isText$b).bind(removeEmpty);
  17823. const nextText = lastChild.bind(nextSibling).filter(isText$b).bind(removeEmpty);
  17824. mergeAndNormalizeText(prevText, firstChild, rng, true);
  17825. mergeAndNormalizeText(nextText, lastChild, rng, false);
  17826. rng.collapse(false);
  17827. };
  17828. const setupArgs$2 = (args, content) => ({
  17829. format: 'html',
  17830. ...args,
  17831. set: true,
  17832. selection: true,
  17833. content
  17834. });
  17835. const cleanContent = (editor, args) => {
  17836. if (args.format !== 'raw') {
  17837. const rng = editor.selection.getRng();
  17838. const contextBlock = editor.dom.getParent(rng.commonAncestorContainer, editor.dom.isBlock);
  17839. const contextArgs = contextBlock ? { context: contextBlock.nodeName.toLowerCase() } : {};
  17840. const node = editor.parser.parse(args.content, {
  17841. forced_root_block: false,
  17842. ...contextArgs,
  17843. ...args
  17844. });
  17845. return HtmlSerializer({ validate: false }, editor.schema).serialize(node);
  17846. } else {
  17847. return args.content;
  17848. }
  17849. };
  17850. const setContent$1 = (editor, content, args = {}) => {
  17851. const defaultedArgs = setupArgs$2(args, content);
  17852. preProcessSetContent(editor, defaultedArgs).each(updatedArgs => {
  17853. const cleanedContent = cleanContent(editor, updatedArgs);
  17854. const rng = editor.selection.getRng();
  17855. rngSetContent(rng, rng.createContextualFragment(cleanedContent));
  17856. editor.selection.setRng(rng);
  17857. scrollRangeIntoView(editor, rng);
  17858. postProcessSetContent(editor, cleanedContent, updatedArgs);
  17859. });
  17860. };
  17861. const deleteFromCallbackMap = (callbackMap, selector, callback) => {
  17862. if (has$2(callbackMap, selector)) {
  17863. const newCallbacks = filter$5(callbackMap[selector], cb => cb !== callback);
  17864. if (newCallbacks.length === 0) {
  17865. delete callbackMap[selector];
  17866. } else {
  17867. callbackMap[selector] = newCallbacks;
  17868. }
  17869. }
  17870. };
  17871. var SelectorChanged = (dom, editor) => {
  17872. let selectorChangedData;
  17873. let currentSelectors;
  17874. const findMatchingNode = (selector, nodes) => find$2(nodes, node => dom.is(node, selector));
  17875. const getParents = elem => dom.getParents(elem, undefined, dom.getRoot());
  17876. const setup = () => {
  17877. selectorChangedData = {};
  17878. currentSelectors = {};
  17879. editor.on('NodeChange', e => {
  17880. const node = e.element;
  17881. const parents = getParents(node);
  17882. const matchedSelectors = {};
  17883. each$d(selectorChangedData, (callbacks, selector) => {
  17884. findMatchingNode(selector, parents).each(node => {
  17885. if (!currentSelectors[selector]) {
  17886. each$e(callbacks, callback => {
  17887. callback(true, {
  17888. node,
  17889. selector,
  17890. parents
  17891. });
  17892. });
  17893. currentSelectors[selector] = callbacks;
  17894. }
  17895. matchedSelectors[selector] = callbacks;
  17896. });
  17897. });
  17898. each$d(currentSelectors, (callbacks, selector) => {
  17899. if (!matchedSelectors[selector]) {
  17900. delete currentSelectors[selector];
  17901. each$e(callbacks, callback => {
  17902. callback(false, {
  17903. node,
  17904. selector,
  17905. parents
  17906. });
  17907. });
  17908. }
  17909. });
  17910. });
  17911. };
  17912. return {
  17913. selectorChangedWithUnbind: (selector, callback) => {
  17914. if (!selectorChangedData) {
  17915. setup();
  17916. }
  17917. if (!selectorChangedData[selector]) {
  17918. selectorChangedData[selector] = [];
  17919. }
  17920. selectorChangedData[selector].push(callback);
  17921. findMatchingNode(selector, getParents(editor.selection.getStart())).each(() => {
  17922. currentSelectors[selector] = selectorChangedData[selector];
  17923. });
  17924. return {
  17925. unbind: () => {
  17926. deleteFromCallbackMap(selectorChangedData, selector, callback);
  17927. deleteFromCallbackMap(currentSelectors, selector, callback);
  17928. }
  17929. };
  17930. }
  17931. };
  17932. };
  17933. const isAttachedToDom = node => {
  17934. return !!(node && node.ownerDocument) && contains(SugarElement.fromDom(node.ownerDocument), SugarElement.fromDom(node));
  17935. };
  17936. const isValidRange = rng => {
  17937. if (!rng) {
  17938. return false;
  17939. } else {
  17940. return isAttachedToDom(rng.startContainer) && isAttachedToDom(rng.endContainer);
  17941. }
  17942. };
  17943. const EditorSelection = (dom, win, serializer, editor) => {
  17944. let selectedRange;
  17945. let explicitRange;
  17946. const {selectorChangedWithUnbind} = SelectorChanged(dom, editor);
  17947. const setCursorLocation = (node, offset) => {
  17948. const rng = dom.createRng();
  17949. if (isNonNullable(node) && isNonNullable(offset)) {
  17950. rng.setStart(node, offset);
  17951. rng.setEnd(node, offset);
  17952. setRng(rng);
  17953. collapse(false);
  17954. } else {
  17955. moveEndPoint(dom, rng, editor.getBody(), true);
  17956. setRng(rng);
  17957. }
  17958. };
  17959. const getContent = args => getContent$1(editor, args);
  17960. const setContent = (content, args) => setContent$1(editor, content, args);
  17961. const getStart$1 = real => getStart(editor.getBody(), getRng$1(), real);
  17962. const getEnd = real => getEnd$1(editor.getBody(), getRng$1(), real);
  17963. const getBookmark = (type, normalized) => bookmarkManager.getBookmark(type, normalized);
  17964. const moveToBookmark = bookmark => bookmarkManager.moveToBookmark(bookmark);
  17965. const select$1 = (node, content) => {
  17966. select(dom, node, content).each(setRng);
  17967. return node;
  17968. };
  17969. const isCollapsed = () => {
  17970. const rng = getRng$1(), sel = getSel();
  17971. if (!rng || rng.item) {
  17972. return false;
  17973. }
  17974. if (rng.compareEndPoints) {
  17975. return rng.compareEndPoints('StartToEnd', rng) === 0;
  17976. }
  17977. return !sel || rng.collapsed;
  17978. };
  17979. const isEditable = () => {
  17980. const rng = getRng$1();
  17981. const fakeSelectedElements = editor.getBody().querySelectorAll('[data-mce-selected="1"]');
  17982. if (fakeSelectedElements.length > 0) {
  17983. return forall(fakeSelectedElements, el => dom.isEditable(el.parentElement));
  17984. } else if (rng.startContainer === rng.endContainer) {
  17985. return dom.isEditable(rng.startContainer);
  17986. } else {
  17987. return dom.isEditable(rng.startContainer) && dom.isEditable(rng.endContainer);
  17988. }
  17989. };
  17990. const collapse = toStart => {
  17991. const rng = getRng$1();
  17992. rng.collapse(!!toStart);
  17993. setRng(rng);
  17994. };
  17995. const getSel = () => win.getSelection ? win.getSelection() : win.document.selection;
  17996. const getRng$1 = () => {
  17997. let rng;
  17998. const tryCompareBoundaryPoints = (how, sourceRange, destinationRange) => {
  17999. try {
  18000. return sourceRange.compareBoundaryPoints(how, destinationRange);
  18001. } catch (ex) {
  18002. return -1;
  18003. }
  18004. };
  18005. const doc = win.document;
  18006. if (isNonNullable(editor.bookmark) && !hasFocus(editor)) {
  18007. const bookmark = getRng(editor);
  18008. if (bookmark.isSome()) {
  18009. return bookmark.map(r => processRanges(editor, [r])[0]).getOr(doc.createRange());
  18010. }
  18011. }
  18012. try {
  18013. const selection = getSel();
  18014. if (selection && !isRestrictedNode(selection.anchorNode)) {
  18015. if (selection.rangeCount > 0) {
  18016. rng = selection.getRangeAt(0);
  18017. } else {
  18018. rng = doc.createRange();
  18019. }
  18020. rng = processRanges(editor, [rng])[0];
  18021. }
  18022. } catch (ex) {
  18023. }
  18024. if (!rng) {
  18025. rng = doc.createRange();
  18026. }
  18027. if (isDocument$1(rng.startContainer) && rng.collapsed) {
  18028. const elm = dom.getRoot();
  18029. rng.setStart(elm, 0);
  18030. rng.setEnd(elm, 0);
  18031. }
  18032. if (selectedRange && explicitRange) {
  18033. if (tryCompareBoundaryPoints(rng.START_TO_START, rng, selectedRange) === 0 && tryCompareBoundaryPoints(rng.END_TO_END, rng, selectedRange) === 0) {
  18034. rng = explicitRange;
  18035. } else {
  18036. selectedRange = null;
  18037. explicitRange = null;
  18038. }
  18039. }
  18040. return rng;
  18041. };
  18042. const setRng = (rng, forward) => {
  18043. if (!isValidRange(rng)) {
  18044. return;
  18045. }
  18046. const sel = getSel();
  18047. const evt = editor.dispatch('SetSelectionRange', {
  18048. range: rng,
  18049. forward
  18050. });
  18051. rng = evt.range;
  18052. if (sel) {
  18053. explicitRange = rng;
  18054. try {
  18055. sel.removeAllRanges();
  18056. sel.addRange(rng);
  18057. } catch (ex) {
  18058. }
  18059. if (forward === false && sel.extend) {
  18060. sel.collapse(rng.endContainer, rng.endOffset);
  18061. sel.extend(rng.startContainer, rng.startOffset);
  18062. }
  18063. selectedRange = sel.rangeCount > 0 ? sel.getRangeAt(0) : null;
  18064. }
  18065. if (!rng.collapsed && rng.startContainer === rng.endContainer && (sel === null || sel === void 0 ? void 0 : sel.setBaseAndExtent)) {
  18066. if (rng.endOffset - rng.startOffset < 2) {
  18067. if (rng.startContainer.hasChildNodes()) {
  18068. const node = rng.startContainer.childNodes[rng.startOffset];
  18069. if (node && node.nodeName === 'IMG') {
  18070. sel.setBaseAndExtent(rng.startContainer, rng.startOffset, rng.endContainer, rng.endOffset);
  18071. if (sel.anchorNode !== rng.startContainer || sel.focusNode !== rng.endContainer) {
  18072. sel.setBaseAndExtent(node, 0, node, 1);
  18073. }
  18074. }
  18075. }
  18076. }
  18077. }
  18078. editor.dispatch('AfterSetSelectionRange', {
  18079. range: rng,
  18080. forward
  18081. });
  18082. };
  18083. const setNode = elm => {
  18084. setContent(dom.getOuterHTML(elm));
  18085. return elm;
  18086. };
  18087. const getNode$1 = () => getNode(editor.getBody(), getRng$1());
  18088. const getSelectedBlocks$1 = (startElm, endElm) => getSelectedBlocks(dom, getRng$1(), startElm, endElm);
  18089. const isForward = () => {
  18090. const sel = getSel();
  18091. const anchorNode = sel === null || sel === void 0 ? void 0 : sel.anchorNode;
  18092. const focusNode = sel === null || sel === void 0 ? void 0 : sel.focusNode;
  18093. if (!sel || !anchorNode || !focusNode || isRestrictedNode(anchorNode) || isRestrictedNode(focusNode)) {
  18094. return true;
  18095. }
  18096. const anchorRange = dom.createRng();
  18097. const focusRange = dom.createRng();
  18098. try {
  18099. anchorRange.setStart(anchorNode, sel.anchorOffset);
  18100. anchorRange.collapse(true);
  18101. focusRange.setStart(focusNode, sel.focusOffset);
  18102. focusRange.collapse(true);
  18103. } catch (e) {
  18104. return true;
  18105. }
  18106. return anchorRange.compareBoundaryPoints(anchorRange.START_TO_START, focusRange) <= 0;
  18107. };
  18108. const normalize = () => {
  18109. const rng = getRng$1();
  18110. const sel = getSel();
  18111. if (!hasMultipleRanges(sel) && hasAnyRanges(editor)) {
  18112. const normRng = normalize$2(dom, rng);
  18113. normRng.each(normRng => {
  18114. setRng(normRng, isForward());
  18115. });
  18116. return normRng.getOr(rng);
  18117. }
  18118. return rng;
  18119. };
  18120. const selectorChanged = (selector, callback) => {
  18121. selectorChangedWithUnbind(selector, callback);
  18122. return exports;
  18123. };
  18124. const getScrollContainer = () => {
  18125. let scrollContainer;
  18126. let node = dom.getRoot();
  18127. while (node && node.nodeName !== 'BODY') {
  18128. if (node.scrollHeight > node.clientHeight) {
  18129. scrollContainer = node;
  18130. break;
  18131. }
  18132. node = node.parentNode;
  18133. }
  18134. return scrollContainer;
  18135. };
  18136. const scrollIntoView = (elm, alignToTop) => {
  18137. if (isNonNullable(elm)) {
  18138. scrollElementIntoView(editor, elm, alignToTop);
  18139. } else {
  18140. scrollRangeIntoView(editor, getRng$1(), alignToTop);
  18141. }
  18142. };
  18143. const placeCaretAt = (clientX, clientY) => setRng(fromPoint(clientX, clientY, editor.getDoc()));
  18144. const getBoundingClientRect = () => {
  18145. const rng = getRng$1();
  18146. return rng.collapsed ? CaretPosition.fromRangeStart(rng).getClientRects()[0] : rng.getBoundingClientRect();
  18147. };
  18148. const destroy = () => {
  18149. win = selectedRange = explicitRange = null;
  18150. controlSelection.destroy();
  18151. };
  18152. const expand = (options = { type: 'word' }) => setRng(RangeUtils(dom).expand(getRng$1(), options));
  18153. const exports = {
  18154. dom,
  18155. win,
  18156. serializer,
  18157. editor,
  18158. expand,
  18159. collapse,
  18160. setCursorLocation,
  18161. getContent,
  18162. setContent,
  18163. getBookmark,
  18164. moveToBookmark,
  18165. select: select$1,
  18166. isCollapsed,
  18167. isEditable,
  18168. isForward,
  18169. setNode,
  18170. getNode: getNode$1,
  18171. getSel,
  18172. setRng,
  18173. getRng: getRng$1,
  18174. getStart: getStart$1,
  18175. getEnd,
  18176. getSelectedBlocks: getSelectedBlocks$1,
  18177. normalize,
  18178. selectorChanged,
  18179. selectorChangedWithUnbind,
  18180. getScrollContainer,
  18181. scrollIntoView,
  18182. placeCaretAt,
  18183. getBoundingClientRect,
  18184. destroy
  18185. };
  18186. const bookmarkManager = BookmarkManager(exports);
  18187. const controlSelection = ControlSelection(exports, editor);
  18188. exports.bookmarkManager = bookmarkManager;
  18189. exports.controlSelection = controlSelection;
  18190. return exports;
  18191. };
  18192. const register$3 = (htmlParser, settings, dom) => {
  18193. htmlParser.addAttributeFilter('data-mce-tabindex', (nodes, name) => {
  18194. let i = nodes.length;
  18195. while (i--) {
  18196. const node = nodes[i];
  18197. node.attr('tabindex', node.attr('data-mce-tabindex'));
  18198. node.attr(name, null);
  18199. }
  18200. });
  18201. htmlParser.addAttributeFilter('src,href,style', (nodes, name) => {
  18202. const internalName = 'data-mce-' + name;
  18203. const urlConverter = settings.url_converter;
  18204. const urlConverterScope = settings.url_converter_scope;
  18205. let i = nodes.length;
  18206. while (i--) {
  18207. const node = nodes[i];
  18208. let value = node.attr(internalName);
  18209. if (value !== undefined) {
  18210. node.attr(name, value.length > 0 ? value : null);
  18211. node.attr(internalName, null);
  18212. } else {
  18213. value = node.attr(name);
  18214. if (name === 'style') {
  18215. value = dom.serializeStyle(dom.parseStyle(value), node.name);
  18216. } else if (urlConverter) {
  18217. value = urlConverter.call(urlConverterScope, value, name, node.name);
  18218. }
  18219. node.attr(name, value.length > 0 ? value : null);
  18220. }
  18221. }
  18222. });
  18223. htmlParser.addAttributeFilter('class', nodes => {
  18224. let i = nodes.length;
  18225. while (i--) {
  18226. const node = nodes[i];
  18227. let value = node.attr('class');
  18228. if (value) {
  18229. value = value.replace(/(?:^|\s)mce-item-\w+(?!\S)/g, '');
  18230. node.attr('class', value.length > 0 ? value : null);
  18231. }
  18232. }
  18233. });
  18234. htmlParser.addAttributeFilter('data-mce-type', (nodes, name, args) => {
  18235. let i = nodes.length;
  18236. while (i--) {
  18237. const node = nodes[i];
  18238. if (node.attr('data-mce-type') === 'bookmark' && !args.cleanup) {
  18239. const hasChildren = Optional.from(node.firstChild).exists(firstChild => {
  18240. var _a;
  18241. return !isZwsp((_a = firstChild.value) !== null && _a !== void 0 ? _a : '');
  18242. });
  18243. if (hasChildren) {
  18244. node.unwrap();
  18245. } else {
  18246. node.remove();
  18247. }
  18248. }
  18249. }
  18250. });
  18251. htmlParser.addNodeFilter('noscript', nodes => {
  18252. var _a;
  18253. let i = nodes.length;
  18254. while (i--) {
  18255. const node = nodes[i].firstChild;
  18256. if (node) {
  18257. node.value = Entities.decode((_a = node.value) !== null && _a !== void 0 ? _a : '');
  18258. }
  18259. }
  18260. });
  18261. htmlParser.addNodeFilter('script,style', (nodes, name) => {
  18262. var _a;
  18263. const trim = value => {
  18264. 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, '');
  18265. };
  18266. let i = nodes.length;
  18267. while (i--) {
  18268. const node = nodes[i];
  18269. const firstChild = node.firstChild;
  18270. const value = (_a = firstChild === null || firstChild === void 0 ? void 0 : firstChild.value) !== null && _a !== void 0 ? _a : '';
  18271. if (name === 'script') {
  18272. const type = node.attr('type');
  18273. if (type) {
  18274. node.attr('type', type === 'mce-no/type' ? null : type.replace(/^mce\-/, ''));
  18275. }
  18276. if (settings.element_format === 'xhtml' && firstChild && value.length > 0) {
  18277. firstChild.value = '// <![CDATA[\n' + trim(value) + '\n// ]]>';
  18278. }
  18279. } else {
  18280. if (settings.element_format === 'xhtml' && firstChild && value.length > 0) {
  18281. firstChild.value = '<!--\n' + trim(value) + '\n-->';
  18282. }
  18283. }
  18284. }
  18285. });
  18286. htmlParser.addNodeFilter('#comment', nodes => {
  18287. let i = nodes.length;
  18288. while (i--) {
  18289. const node = nodes[i];
  18290. const value = node.value;
  18291. if (settings.preserve_cdata && (value === null || value === void 0 ? void 0 : value.indexOf('[CDATA[')) === 0) {
  18292. node.name = '#cdata';
  18293. node.type = 4;
  18294. node.value = dom.decode(value.replace(/^\[CDATA\[|\]\]$/g, ''));
  18295. } else if ((value === null || value === void 0 ? void 0 : value.indexOf('mce:protected ')) === 0) {
  18296. node.name = '#text';
  18297. node.type = 3;
  18298. node.raw = true;
  18299. node.value = unescape(value).substr(14);
  18300. }
  18301. }
  18302. });
  18303. htmlParser.addNodeFilter('xml:namespace,input', (nodes, name) => {
  18304. let i = nodes.length;
  18305. while (i--) {
  18306. const node = nodes[i];
  18307. if (node.type === 7) {
  18308. node.remove();
  18309. } else if (node.type === 1) {
  18310. if (name === 'input' && !node.attr('type')) {
  18311. node.attr('type', 'text');
  18312. }
  18313. }
  18314. }
  18315. });
  18316. htmlParser.addAttributeFilter('data-mce-type', nodes => {
  18317. each$e(nodes, node => {
  18318. if (node.attr('data-mce-type') === 'format-caret') {
  18319. if (node.isEmpty(htmlParser.schema.getNonEmptyElements())) {
  18320. node.remove();
  18321. } else {
  18322. node.unwrap();
  18323. }
  18324. }
  18325. });
  18326. });
  18327. htmlParser.addAttributeFilter('data-mce-src,data-mce-href,data-mce-style,' + 'data-mce-selected,data-mce-expando,data-mce-block,' + 'data-mce-type,data-mce-resize,data-mce-placeholder', (nodes, name) => {
  18328. let i = nodes.length;
  18329. while (i--) {
  18330. nodes[i].attr(name, null);
  18331. }
  18332. });
  18333. };
  18334. const trimTrailingBr = rootNode => {
  18335. const isBr = node => {
  18336. return (node === null || node === void 0 ? void 0 : node.name) === 'br';
  18337. };
  18338. const brNode1 = rootNode.lastChild;
  18339. if (isBr(brNode1)) {
  18340. const brNode2 = brNode1.prev;
  18341. if (isBr(brNode2)) {
  18342. brNode1.remove();
  18343. brNode2.remove();
  18344. }
  18345. }
  18346. };
  18347. const preProcess$1 = (editor, node, args) => {
  18348. let oldDoc;
  18349. const dom = editor.dom;
  18350. let clonedNode = node.cloneNode(true);
  18351. const impl = document.implementation;
  18352. if (impl.createHTMLDocument) {
  18353. const doc = impl.createHTMLDocument('');
  18354. Tools.each(clonedNode.nodeName === 'BODY' ? clonedNode.childNodes : [clonedNode], node => {
  18355. doc.body.appendChild(doc.importNode(node, true));
  18356. });
  18357. if (clonedNode.nodeName !== 'BODY') {
  18358. clonedNode = doc.body.firstChild;
  18359. } else {
  18360. clonedNode = doc.body;
  18361. }
  18362. oldDoc = dom.doc;
  18363. dom.doc = doc;
  18364. }
  18365. firePreProcess(editor, {
  18366. ...args,
  18367. node: clonedNode
  18368. });
  18369. if (oldDoc) {
  18370. dom.doc = oldDoc;
  18371. }
  18372. return clonedNode;
  18373. };
  18374. const shouldFireEvent = (editor, args) => {
  18375. return isNonNullable(editor) && editor.hasEventListeners('PreProcess') && !args.no_events;
  18376. };
  18377. const process$1 = (editor, node, args) => {
  18378. return shouldFireEvent(editor, args) ? preProcess$1(editor, node, args) : node;
  18379. };
  18380. const addTempAttr = (htmlParser, tempAttrs, name) => {
  18381. if (Tools.inArray(tempAttrs, name) === -1) {
  18382. htmlParser.addAttributeFilter(name, (nodes, name) => {
  18383. let i = nodes.length;
  18384. while (i--) {
  18385. nodes[i].attr(name, null);
  18386. }
  18387. });
  18388. tempAttrs.push(name);
  18389. }
  18390. };
  18391. const postProcess = (editor, args, content) => {
  18392. if (!args.no_events && editor) {
  18393. const outArgs = firePostProcess(editor, {
  18394. ...args,
  18395. content
  18396. });
  18397. return outArgs.content;
  18398. } else {
  18399. return content;
  18400. }
  18401. };
  18402. const getHtmlFromNode = (dom, node, args) => {
  18403. const html = trim$1(args.getInner ? node.innerHTML : dom.getOuterHTML(node));
  18404. return args.selection || isWsPreserveElement(SugarElement.fromDom(node)) ? html : Tools.trim(html);
  18405. };
  18406. const parseHtml = (htmlParser, html, args) => {
  18407. const parserArgs = args.selection ? {
  18408. forced_root_block: false,
  18409. ...args
  18410. } : args;
  18411. const rootNode = htmlParser.parse(html, parserArgs);
  18412. trimTrailingBr(rootNode);
  18413. return rootNode;
  18414. };
  18415. const serializeNode = (settings, schema, node) => {
  18416. const htmlSerializer = HtmlSerializer(settings, schema);
  18417. return htmlSerializer.serialize(node);
  18418. };
  18419. const toHtml = (editor, settings, schema, rootNode, args) => {
  18420. const content = serializeNode(settings, schema, rootNode);
  18421. return postProcess(editor, args, content);
  18422. };
  18423. const DomSerializerImpl = (settings, editor) => {
  18424. const tempAttrs = ['data-mce-selected'];
  18425. const dom = editor && editor.dom ? editor.dom : DOMUtils.DOM;
  18426. const schema = editor && editor.schema ? editor.schema : Schema(settings);
  18427. settings.entity_encoding = settings.entity_encoding || 'named';
  18428. settings.remove_trailing_brs = 'remove_trailing_brs' in settings ? settings.remove_trailing_brs : true;
  18429. const htmlParser = DomParser(settings, schema);
  18430. register$3(htmlParser, settings, dom);
  18431. const serialize = (node, parserArgs = {}) => {
  18432. const args = {
  18433. format: 'html',
  18434. ...parserArgs
  18435. };
  18436. const targetNode = process$1(editor, node, args);
  18437. const html = getHtmlFromNode(dom, targetNode, args);
  18438. const rootNode = parseHtml(htmlParser, html, args);
  18439. return args.format === 'tree' ? rootNode : toHtml(editor, settings, schema, rootNode, args);
  18440. };
  18441. return {
  18442. schema,
  18443. addNodeFilter: htmlParser.addNodeFilter,
  18444. addAttributeFilter: htmlParser.addAttributeFilter,
  18445. serialize: serialize,
  18446. addRules: schema.addValidElements,
  18447. setRules: schema.setValidElements,
  18448. addTempAttr: curry(addTempAttr, htmlParser, tempAttrs),
  18449. getTempAttrs: constant(tempAttrs),
  18450. getNodeFilters: htmlParser.getNodeFilters,
  18451. getAttributeFilters: htmlParser.getAttributeFilters,
  18452. removeNodeFilter: htmlParser.removeNodeFilter,
  18453. removeAttributeFilter: htmlParser.removeAttributeFilter
  18454. };
  18455. };
  18456. const DomSerializer = (settings, editor) => {
  18457. const domSerializer = DomSerializerImpl(settings, editor);
  18458. return {
  18459. schema: domSerializer.schema,
  18460. addNodeFilter: domSerializer.addNodeFilter,
  18461. addAttributeFilter: domSerializer.addAttributeFilter,
  18462. serialize: domSerializer.serialize,
  18463. addRules: domSerializer.addRules,
  18464. setRules: domSerializer.setRules,
  18465. addTempAttr: domSerializer.addTempAttr,
  18466. getTempAttrs: domSerializer.getTempAttrs,
  18467. getNodeFilters: domSerializer.getNodeFilters,
  18468. getAttributeFilters: domSerializer.getAttributeFilters,
  18469. removeNodeFilter: domSerializer.removeNodeFilter,
  18470. removeAttributeFilter: domSerializer.removeAttributeFilter
  18471. };
  18472. };
  18473. const defaultFormat$1 = 'html';
  18474. const setupArgs$1 = (args, format) => ({
  18475. ...args,
  18476. format,
  18477. get: true,
  18478. getInner: true
  18479. });
  18480. const getContent = (editor, args = {}) => {
  18481. const format = args.format ? args.format : defaultFormat$1;
  18482. const defaultedArgs = setupArgs$1(args, format);
  18483. return preProcessGetContent(editor, defaultedArgs).fold(identity, updatedArgs => {
  18484. const content = getContent$2(editor, updatedArgs);
  18485. return postProcessGetContent(editor, content, updatedArgs);
  18486. });
  18487. };
  18488. const defaultFormat = 'html';
  18489. const setupArgs = (args, content) => ({
  18490. format: defaultFormat,
  18491. ...args,
  18492. set: true,
  18493. content
  18494. });
  18495. const setContent = (editor, content, args = {}) => {
  18496. const defaultedArgs = setupArgs(args, content);
  18497. return preProcessSetContent(editor, defaultedArgs).map(updatedArgs => {
  18498. const result = setContent$2(editor, updatedArgs.content, updatedArgs);
  18499. postProcessSetContent(editor, result.html, updatedArgs);
  18500. return result.content;
  18501. }).getOr(content);
  18502. };
  18503. 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(',');
  18504. const deprecatedOptions = 'template_cdate_classes,template_mdate_classes,template_selected_content_classes,template_preview_replace_values,template_replace_values,templates,template_cdate_format,template_mdate_format'.split(',');
  18505. const removedPlugins = 'bbcode,colorpicker,contextmenu,fullpage,legacyoutput,spellchecker,textcolor'.split(',');
  18506. const deprecatedPlugins = [{
  18507. name: 'template',
  18508. replacedWith: 'Advanced Template'
  18509. }];
  18510. const getMatchingOptions = (options, searchingFor) => {
  18511. const settingNames = filter$5(searchingFor, setting => has$2(options, setting));
  18512. return sort(settingNames);
  18513. };
  18514. const getRemovedOptions = options => {
  18515. const settingNames = getMatchingOptions(options, removedOptions);
  18516. const forcedRootBlock = options.forced_root_block;
  18517. if (forcedRootBlock === false || forcedRootBlock === '') {
  18518. settingNames.push('forced_root_block (false only)');
  18519. }
  18520. return sort(settingNames);
  18521. };
  18522. const getDeprecatedOptions = options => getMatchingOptions(options, deprecatedOptions);
  18523. const getMatchingPlugins = (options, searchingFor) => {
  18524. const plugins = Tools.makeMap(options.plugins, ' ');
  18525. const hasPlugin = plugin => has$2(plugins, plugin);
  18526. const pluginNames = filter$5(searchingFor, hasPlugin);
  18527. return sort(pluginNames);
  18528. };
  18529. const getRemovedPlugins = options => getMatchingPlugins(options, removedPlugins);
  18530. const getDeprecatedPlugins = options => getMatchingPlugins(options, deprecatedPlugins.map(entry => entry.name));
  18531. const logRemovedWarnings = (rawOptions, normalizedOptions) => {
  18532. const removedOptions = getRemovedOptions(rawOptions);
  18533. const removedPlugins = getRemovedPlugins(normalizedOptions);
  18534. const hasRemovedPlugins = removedPlugins.length > 0;
  18535. const hasRemovedOptions = removedOptions.length > 0;
  18536. const isLegacyMobileTheme = normalizedOptions.theme === 'mobile';
  18537. if (hasRemovedPlugins || hasRemovedOptions || isLegacyMobileTheme) {
  18538. const listJoiner = '\n- ';
  18539. const themesMessage = isLegacyMobileTheme ? `\n\nThemes:${ listJoiner }mobile` : '';
  18540. const pluginsMessage = hasRemovedPlugins ? `\n\nPlugins:${ listJoiner }${ removedPlugins.join(listJoiner) }` : '';
  18541. const optionsMessage = hasRemovedOptions ? `\n\nOptions:${ listJoiner }${ removedOptions.join(listJoiner) }` : '';
  18542. 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);
  18543. }
  18544. };
  18545. const getPluginDescription = name => find$2(deprecatedPlugins, entry => entry.name === name).fold(() => name, entry => `${ name }, replaced by ${ entry.replacedWith }`);
  18546. const logDeprecatedWarnings = (rawOptions, normalizedOptions) => {
  18547. const deprecatedOptions = getDeprecatedOptions(rawOptions);
  18548. const deprecatedPlugins = getDeprecatedPlugins(normalizedOptions);
  18549. const hasDeprecatedPlugins = deprecatedPlugins.length > 0;
  18550. const hasDeprecatedOptions = deprecatedOptions.length > 0;
  18551. if (hasDeprecatedPlugins || hasDeprecatedOptions) {
  18552. const listJoiner = '\n- ';
  18553. const pluginsMessage = hasDeprecatedPlugins ? `\n\nPlugins:${ listJoiner }${ deprecatedPlugins.map(getPluginDescription).join(listJoiner) }` : '';
  18554. const optionsMessage = hasDeprecatedOptions ? `\n\nOptions:${ listJoiner }${ deprecatedOptions.join(listJoiner) }` : '';
  18555. console.warn('The following deprecated features are currently enabled but will be removed soon.' + pluginsMessage + optionsMessage);
  18556. }
  18557. };
  18558. const logWarnings = (rawOptions, normalizedOptions) => {
  18559. logRemovedWarnings(rawOptions, normalizedOptions);
  18560. logDeprecatedWarnings(rawOptions, normalizedOptions);
  18561. };
  18562. const DOM$8 = DOMUtils.DOM;
  18563. const restoreOriginalStyles = editor => {
  18564. DOM$8.setStyle(editor.id, 'display', editor.orgDisplay);
  18565. };
  18566. const safeDestroy = x => Optional.from(x).each(x => x.destroy());
  18567. const clearDomReferences = editor => {
  18568. const ed = editor;
  18569. ed.contentAreaContainer = ed.formElement = ed.container = ed.editorContainer = null;
  18570. ed.bodyElement = ed.contentDocument = ed.contentWindow = null;
  18571. ed.iframeElement = ed.targetElm = null;
  18572. const selection = editor.selection;
  18573. if (selection) {
  18574. const dom = selection.dom;
  18575. ed.selection = selection.win = selection.dom = dom.doc = null;
  18576. }
  18577. };
  18578. const restoreForm = editor => {
  18579. const form = editor.formElement;
  18580. if (form) {
  18581. if (form._mceOldSubmit) {
  18582. form.submit = form._mceOldSubmit;
  18583. delete form._mceOldSubmit;
  18584. }
  18585. DOM$8.unbind(form, 'submit reset', editor.formEventDelegate);
  18586. }
  18587. };
  18588. const remove$1 = editor => {
  18589. if (!editor.removed) {
  18590. const {_selectionOverrides, editorUpload} = editor;
  18591. const body = editor.getBody();
  18592. const element = editor.getElement();
  18593. if (body) {
  18594. editor.save({ is_removing: true });
  18595. }
  18596. editor.removed = true;
  18597. editor.unbindAllNativeEvents();
  18598. if (editor.hasHiddenInput && isNonNullable(element === null || element === void 0 ? void 0 : element.nextSibling)) {
  18599. DOM$8.remove(element.nextSibling);
  18600. }
  18601. fireRemove(editor);
  18602. editor.editorManager.remove(editor);
  18603. if (!editor.inline && body) {
  18604. restoreOriginalStyles(editor);
  18605. }
  18606. fireDetach(editor);
  18607. DOM$8.remove(editor.getContainer());
  18608. safeDestroy(_selectionOverrides);
  18609. safeDestroy(editorUpload);
  18610. editor.destroy();
  18611. }
  18612. };
  18613. const destroy = (editor, automatic) => {
  18614. const {selection, dom} = editor;
  18615. if (editor.destroyed) {
  18616. return;
  18617. }
  18618. if (!automatic && !editor.removed) {
  18619. editor.remove();
  18620. return;
  18621. }
  18622. if (!automatic) {
  18623. editor.editorManager.off('beforeunload', editor._beforeUnload);
  18624. if (editor.theme && editor.theme.destroy) {
  18625. editor.theme.destroy();
  18626. }
  18627. safeDestroy(selection);
  18628. safeDestroy(dom);
  18629. }
  18630. restoreForm(editor);
  18631. clearDomReferences(editor);
  18632. editor.destroyed = true;
  18633. };
  18634. const CreateIconManager = () => {
  18635. const lookup = {};
  18636. const add = (id, iconPack) => {
  18637. lookup[id] = iconPack;
  18638. };
  18639. const get = id => {
  18640. if (lookup[id]) {
  18641. return lookup[id];
  18642. } else {
  18643. return { icons: {} };
  18644. }
  18645. };
  18646. const has = id => has$2(lookup, id);
  18647. return {
  18648. add,
  18649. get,
  18650. has
  18651. };
  18652. };
  18653. const IconManager = CreateIconManager();
  18654. const ModelManager = AddOnManager.ModelManager;
  18655. const getProp = (propName, elm) => {
  18656. const rawElm = elm.dom;
  18657. return rawElm[propName];
  18658. };
  18659. const getComputedSizeProp = (propName, elm) => parseInt(get$7(elm, propName), 10);
  18660. const getClientWidth = curry(getProp, 'clientWidth');
  18661. const getClientHeight = curry(getProp, 'clientHeight');
  18662. const getMarginTop = curry(getComputedSizeProp, 'margin-top');
  18663. const getMarginLeft = curry(getComputedSizeProp, 'margin-left');
  18664. const getBoundingClientRect = elm => elm.dom.getBoundingClientRect();
  18665. const isInsideElementContentArea = (bodyElm, clientX, clientY) => {
  18666. const clientWidth = getClientWidth(bodyElm);
  18667. const clientHeight = getClientHeight(bodyElm);
  18668. return clientX >= 0 && clientY >= 0 && clientX <= clientWidth && clientY <= clientHeight;
  18669. };
  18670. const transpose = (inline, elm, clientX, clientY) => {
  18671. const clientRect = getBoundingClientRect(elm);
  18672. const deltaX = inline ? clientRect.left + elm.dom.clientLeft + getMarginLeft(elm) : 0;
  18673. const deltaY = inline ? clientRect.top + elm.dom.clientTop + getMarginTop(elm) : 0;
  18674. const x = clientX - deltaX;
  18675. const y = clientY - deltaY;
  18676. return {
  18677. x,
  18678. y
  18679. };
  18680. };
  18681. const isXYInContentArea = (editor, clientX, clientY) => {
  18682. const bodyElm = SugarElement.fromDom(editor.getBody());
  18683. const targetElm = editor.inline ? bodyElm : documentElement(bodyElm);
  18684. const transposedPoint = transpose(editor.inline, targetElm, clientX, clientY);
  18685. return isInsideElementContentArea(targetElm, transposedPoint.x, transposedPoint.y);
  18686. };
  18687. const fromDomSafe = node => Optional.from(node).map(SugarElement.fromDom);
  18688. const isEditorAttachedToDom = editor => {
  18689. const rawContainer = editor.inline ? editor.getBody() : editor.getContentAreaContainer();
  18690. return fromDomSafe(rawContainer).map(inBody).getOr(false);
  18691. };
  18692. var NotificationManagerImpl = () => {
  18693. const unimplemented = () => {
  18694. throw new Error('Theme did not provide a NotificationManager implementation.');
  18695. };
  18696. return {
  18697. open: unimplemented,
  18698. close: unimplemented,
  18699. getArgs: unimplemented
  18700. };
  18701. };
  18702. const NotificationManager = editor => {
  18703. const notifications = [];
  18704. const getImplementation = () => {
  18705. const theme = editor.theme;
  18706. return theme && theme.getNotificationManagerImpl ? theme.getNotificationManagerImpl() : NotificationManagerImpl();
  18707. };
  18708. const getTopNotification = () => {
  18709. return Optional.from(notifications[0]);
  18710. };
  18711. const isEqual = (a, b) => {
  18712. return a.type === b.type && a.text === b.text && !a.progressBar && !a.timeout && !b.progressBar && !b.timeout;
  18713. };
  18714. const reposition = () => {
  18715. each$e(notifications, notification => {
  18716. notification.reposition();
  18717. });
  18718. };
  18719. const addNotification = notification => {
  18720. notifications.push(notification);
  18721. };
  18722. const closeNotification = notification => {
  18723. findIndex$2(notifications, otherNotification => {
  18724. return otherNotification === notification;
  18725. }).each(index => {
  18726. notifications.splice(index, 1);
  18727. });
  18728. };
  18729. const open = (spec, fireEvent = true) => {
  18730. if (editor.removed || !isEditorAttachedToDom(editor)) {
  18731. return {};
  18732. }
  18733. if (fireEvent) {
  18734. editor.dispatch('BeforeOpenNotification', { notification: spec });
  18735. }
  18736. return find$2(notifications, notification => {
  18737. return isEqual(getImplementation().getArgs(notification), spec);
  18738. }).getOrThunk(() => {
  18739. editor.editorManager.setActive(editor);
  18740. const notification = getImplementation().open(spec, () => {
  18741. closeNotification(notification);
  18742. reposition();
  18743. getTopNotification().fold(() => editor.focus(), top => focus$1(SugarElement.fromDom(top.getEl())));
  18744. });
  18745. addNotification(notification);
  18746. reposition();
  18747. editor.dispatch('OpenNotification', { notification: { ...notification } });
  18748. return notification;
  18749. });
  18750. };
  18751. const close = () => {
  18752. getTopNotification().each(notification => {
  18753. getImplementation().close(notification);
  18754. closeNotification(notification);
  18755. reposition();
  18756. });
  18757. };
  18758. const getNotifications = constant(notifications);
  18759. const registerEvents = editor => {
  18760. editor.on('SkinLoaded', () => {
  18761. const serviceMessage = getServiceMessage(editor);
  18762. if (serviceMessage) {
  18763. open({
  18764. text: serviceMessage,
  18765. type: 'warning',
  18766. timeout: 0
  18767. }, false);
  18768. }
  18769. reposition();
  18770. });
  18771. editor.on('show ResizeEditor ResizeWindow NodeChange', () => {
  18772. requestAnimationFrame(reposition);
  18773. });
  18774. editor.on('remove', () => {
  18775. each$e(notifications.slice(), notification => {
  18776. getImplementation().close(notification);
  18777. });
  18778. });
  18779. };
  18780. registerEvents(editor);
  18781. return {
  18782. open,
  18783. close,
  18784. getNotifications
  18785. };
  18786. };
  18787. const PluginManager = AddOnManager.PluginManager;
  18788. const ThemeManager = AddOnManager.ThemeManager;
  18789. var WindowManagerImpl = () => {
  18790. const unimplemented = () => {
  18791. throw new Error('Theme did not provide a WindowManager implementation.');
  18792. };
  18793. return {
  18794. open: unimplemented,
  18795. openUrl: unimplemented,
  18796. alert: unimplemented,
  18797. confirm: unimplemented,
  18798. close: unimplemented
  18799. };
  18800. };
  18801. const WindowManager = editor => {
  18802. let dialogs = [];
  18803. const getImplementation = () => {
  18804. const theme = editor.theme;
  18805. return theme && theme.getWindowManagerImpl ? theme.getWindowManagerImpl() : WindowManagerImpl();
  18806. };
  18807. const funcBind = (scope, f) => {
  18808. return (...args) => {
  18809. return f ? f.apply(scope, args) : undefined;
  18810. };
  18811. };
  18812. const fireOpenEvent = dialog => {
  18813. editor.dispatch('OpenWindow', { dialog });
  18814. };
  18815. const fireCloseEvent = dialog => {
  18816. editor.dispatch('CloseWindow', { dialog });
  18817. };
  18818. const addDialog = dialog => {
  18819. dialogs.push(dialog);
  18820. fireOpenEvent(dialog);
  18821. };
  18822. const closeDialog = dialog => {
  18823. fireCloseEvent(dialog);
  18824. dialogs = filter$5(dialogs, otherDialog => {
  18825. return otherDialog !== dialog;
  18826. });
  18827. if (dialogs.length === 0) {
  18828. editor.focus();
  18829. }
  18830. };
  18831. const getTopDialog = () => {
  18832. return Optional.from(dialogs[dialogs.length - 1]);
  18833. };
  18834. const storeSelectionAndOpenDialog = openDialog => {
  18835. editor.editorManager.setActive(editor);
  18836. store(editor);
  18837. editor.ui.show();
  18838. const dialog = openDialog();
  18839. addDialog(dialog);
  18840. return dialog;
  18841. };
  18842. const open = (args, params) => {
  18843. return storeSelectionAndOpenDialog(() => getImplementation().open(args, params, closeDialog));
  18844. };
  18845. const openUrl = args => {
  18846. return storeSelectionAndOpenDialog(() => getImplementation().openUrl(args, closeDialog));
  18847. };
  18848. const alert = (message, callback, scope) => {
  18849. const windowManagerImpl = getImplementation();
  18850. windowManagerImpl.alert(message, funcBind(scope ? scope : windowManagerImpl, callback));
  18851. };
  18852. const confirm = (message, callback, scope) => {
  18853. const windowManagerImpl = getImplementation();
  18854. windowManagerImpl.confirm(message, funcBind(scope ? scope : windowManagerImpl, callback));
  18855. };
  18856. const close = () => {
  18857. getTopDialog().each(dialog => {
  18858. getImplementation().close(dialog);
  18859. closeDialog(dialog);
  18860. });
  18861. };
  18862. editor.on('remove', () => {
  18863. each$e(dialogs, dialog => {
  18864. getImplementation().close(dialog);
  18865. });
  18866. });
  18867. return {
  18868. open,
  18869. openUrl,
  18870. alert,
  18871. confirm,
  18872. close
  18873. };
  18874. };
  18875. const displayNotification = (editor, message) => {
  18876. editor.notificationManager.open({
  18877. type: 'error',
  18878. text: message
  18879. });
  18880. };
  18881. const displayError = (editor, message) => {
  18882. if (editor._skinLoaded) {
  18883. displayNotification(editor, message);
  18884. } else {
  18885. editor.on('SkinLoaded', () => {
  18886. displayNotification(editor, message);
  18887. });
  18888. }
  18889. };
  18890. const uploadError = (editor, message) => {
  18891. displayError(editor, I18n.translate([
  18892. 'Failed to upload image: {0}',
  18893. message
  18894. ]));
  18895. };
  18896. const logError = (editor, errorType, msg) => {
  18897. fireError(editor, errorType, { message: msg });
  18898. console.error(msg);
  18899. };
  18900. const createLoadError = (type, url, name) => name ? `Failed to load ${ type }: ${ name } from url ${ url }` : `Failed to load ${ type } url: ${ url }`;
  18901. const pluginLoadError = (editor, url, name) => {
  18902. logError(editor, 'PluginLoadError', createLoadError('plugin', url, name));
  18903. };
  18904. const iconsLoadError = (editor, url, name) => {
  18905. logError(editor, 'IconsLoadError', createLoadError('icons', url, name));
  18906. };
  18907. const languageLoadError = (editor, url, name) => {
  18908. logError(editor, 'LanguageLoadError', createLoadError('language', url, name));
  18909. };
  18910. const themeLoadError = (editor, url, name) => {
  18911. logError(editor, 'ThemeLoadError', createLoadError('theme', url, name));
  18912. };
  18913. const modelLoadError = (editor, url, name) => {
  18914. logError(editor, 'ModelLoadError', createLoadError('model', url, name));
  18915. };
  18916. const pluginInitError = (editor, name, err) => {
  18917. const message = I18n.translate([
  18918. 'Failed to initialize plugin: {0}',
  18919. name
  18920. ]);
  18921. fireError(editor, 'PluginLoadError', { message });
  18922. initError(message, err);
  18923. displayError(editor, message);
  18924. };
  18925. const initError = (message, ...x) => {
  18926. const console = window.console;
  18927. if (console) {
  18928. if (console.error) {
  18929. console.error(message, ...x);
  18930. } else {
  18931. console.log(message, ...x);
  18932. }
  18933. }
  18934. };
  18935. const isContentCssSkinName = url => /^[a-z0-9\-]+$/i.test(url);
  18936. const getContentCssUrls = editor => {
  18937. return transformToUrls(editor, getContentCss(editor));
  18938. };
  18939. const getFontCssUrls = editor => {
  18940. return transformToUrls(editor, getFontCss(editor));
  18941. };
  18942. const transformToUrls = (editor, cssLinks) => {
  18943. const skinUrl = editor.editorManager.baseURL + '/skins/content';
  18944. const suffix = editor.editorManager.suffix;
  18945. const contentCssFile = `content${ suffix }.css`;
  18946. return map$3(cssLinks, url => {
  18947. if (isContentCssSkinName(url) && !editor.inline) {
  18948. return `${ skinUrl }/${ url }/${ contentCssFile }`;
  18949. } else {
  18950. return editor.documentBaseURI.toAbsolute(url);
  18951. }
  18952. });
  18953. };
  18954. const appendContentCssFromSettings = editor => {
  18955. editor.contentCSS = editor.contentCSS.concat(getContentCssUrls(editor), getFontCssUrls(editor));
  18956. };
  18957. const getAllImages = elm => {
  18958. return elm ? from(elm.getElementsByTagName('img')) : [];
  18959. };
  18960. const ImageScanner = (uploadStatus, blobCache) => {
  18961. const cachedPromises = {};
  18962. const findAll = (elm, predicate = always) => {
  18963. const images = filter$5(getAllImages(elm), img => {
  18964. const src = img.src;
  18965. if (img.hasAttribute('data-mce-bogus')) {
  18966. return false;
  18967. }
  18968. if (img.hasAttribute('data-mce-placeholder')) {
  18969. return false;
  18970. }
  18971. if (!src || src === Env.transparentSrc) {
  18972. return false;
  18973. }
  18974. if (startsWith(src, 'blob:')) {
  18975. return !uploadStatus.isUploaded(src) && predicate(img);
  18976. }
  18977. if (startsWith(src, 'data:')) {
  18978. return predicate(img);
  18979. }
  18980. return false;
  18981. });
  18982. const promises = map$3(images, img => {
  18983. const imageSrc = img.src;
  18984. if (has$2(cachedPromises, imageSrc)) {
  18985. return cachedPromises[imageSrc].then(imageInfo => {
  18986. if (isString(imageInfo)) {
  18987. return imageInfo;
  18988. } else {
  18989. return {
  18990. image: img,
  18991. blobInfo: imageInfo.blobInfo
  18992. };
  18993. }
  18994. });
  18995. } else {
  18996. const newPromise = imageToBlobInfo(blobCache, imageSrc).then(blobInfo => {
  18997. delete cachedPromises[imageSrc];
  18998. return {
  18999. image: img,
  19000. blobInfo
  19001. };
  19002. }).catch(error => {
  19003. delete cachedPromises[imageSrc];
  19004. return error;
  19005. });
  19006. cachedPromises[imageSrc] = newPromise;
  19007. return newPromise;
  19008. }
  19009. });
  19010. return Promise.all(promises);
  19011. };
  19012. return { findAll };
  19013. };
  19014. const UploadStatus = () => {
  19015. const PENDING = 1, UPLOADED = 2;
  19016. let blobUriStatuses = {};
  19017. const createStatus = (status, resultUri) => {
  19018. return {
  19019. status,
  19020. resultUri
  19021. };
  19022. };
  19023. const hasBlobUri = blobUri => {
  19024. return blobUri in blobUriStatuses;
  19025. };
  19026. const getResultUri = blobUri => {
  19027. const result = blobUriStatuses[blobUri];
  19028. return result ? result.resultUri : null;
  19029. };
  19030. const isPending = blobUri => {
  19031. return hasBlobUri(blobUri) ? blobUriStatuses[blobUri].status === PENDING : false;
  19032. };
  19033. const isUploaded = blobUri => {
  19034. return hasBlobUri(blobUri) ? blobUriStatuses[blobUri].status === UPLOADED : false;
  19035. };
  19036. const markPending = blobUri => {
  19037. blobUriStatuses[blobUri] = createStatus(PENDING, null);
  19038. };
  19039. const markUploaded = (blobUri, resultUri) => {
  19040. blobUriStatuses[blobUri] = createStatus(UPLOADED, resultUri);
  19041. };
  19042. const removeFailed = blobUri => {
  19043. delete blobUriStatuses[blobUri];
  19044. };
  19045. const destroy = () => {
  19046. blobUriStatuses = {};
  19047. };
  19048. return {
  19049. hasBlobUri,
  19050. getResultUri,
  19051. isPending,
  19052. isUploaded,
  19053. markPending,
  19054. markUploaded,
  19055. removeFailed,
  19056. destroy
  19057. };
  19058. };
  19059. let count = 0;
  19060. const seed = () => {
  19061. const rnd = () => {
  19062. return Math.round(Math.random() * 4294967295).toString(36);
  19063. };
  19064. const now = new Date().getTime();
  19065. return 's' + now.toString(36) + rnd() + rnd() + rnd();
  19066. };
  19067. const uuid = prefix => {
  19068. return prefix + count++ + seed();
  19069. };
  19070. const BlobCache = () => {
  19071. let cache = [];
  19072. const mimeToExt = mime => {
  19073. const mimes = {
  19074. 'image/jpeg': 'jpg',
  19075. 'image/jpg': 'jpg',
  19076. 'image/gif': 'gif',
  19077. 'image/png': 'png',
  19078. 'image/apng': 'apng',
  19079. 'image/avif': 'avif',
  19080. 'image/svg+xml': 'svg',
  19081. 'image/webp': 'webp',
  19082. 'image/bmp': 'bmp',
  19083. 'image/tiff': 'tiff'
  19084. };
  19085. return mimes[mime.toLowerCase()] || 'dat';
  19086. };
  19087. const create = (o, blob, base64, name, filename) => {
  19088. if (isString(o)) {
  19089. const id = o;
  19090. return toBlobInfo({
  19091. id,
  19092. name,
  19093. filename,
  19094. blob: blob,
  19095. base64: base64
  19096. });
  19097. } else if (isObject(o)) {
  19098. return toBlobInfo(o);
  19099. } else {
  19100. throw new Error('Unknown input type');
  19101. }
  19102. };
  19103. const toBlobInfo = o => {
  19104. if (!o.blob || !o.base64) {
  19105. throw new Error('blob and base64 representations of the image are required for BlobInfo to be created');
  19106. }
  19107. const id = o.id || uuid('blobid');
  19108. const name = o.name || id;
  19109. const blob = o.blob;
  19110. return {
  19111. id: constant(id),
  19112. name: constant(name),
  19113. filename: constant(o.filename || name + '.' + mimeToExt(blob.type)),
  19114. blob: constant(blob),
  19115. base64: constant(o.base64),
  19116. blobUri: constant(o.blobUri || URL.createObjectURL(blob)),
  19117. uri: constant(o.uri)
  19118. };
  19119. };
  19120. const add = blobInfo => {
  19121. if (!get(blobInfo.id())) {
  19122. cache.push(blobInfo);
  19123. }
  19124. };
  19125. const findFirst = predicate => find$2(cache, predicate).getOrUndefined();
  19126. const get = id => findFirst(cachedBlobInfo => cachedBlobInfo.id() === id);
  19127. const getByUri = blobUri => findFirst(blobInfo => blobInfo.blobUri() === blobUri);
  19128. const getByData = (base64, type) => findFirst(blobInfo => blobInfo.base64() === base64 && blobInfo.blob().type === type);
  19129. const removeByUri = blobUri => {
  19130. cache = filter$5(cache, blobInfo => {
  19131. if (blobInfo.blobUri() === blobUri) {
  19132. URL.revokeObjectURL(blobInfo.blobUri());
  19133. return false;
  19134. }
  19135. return true;
  19136. });
  19137. };
  19138. const destroy = () => {
  19139. each$e(cache, cachedBlobInfo => {
  19140. URL.revokeObjectURL(cachedBlobInfo.blobUri());
  19141. });
  19142. cache = [];
  19143. };
  19144. return {
  19145. create,
  19146. add,
  19147. get,
  19148. getByUri,
  19149. getByData,
  19150. findFirst,
  19151. removeByUri,
  19152. destroy
  19153. };
  19154. };
  19155. const Uploader = (uploadStatus, settings) => {
  19156. const pendingPromises = {};
  19157. const pathJoin = (path1, path2) => {
  19158. if (path1) {
  19159. return path1.replace(/\/$/, '') + '/' + path2.replace(/^\//, '');
  19160. }
  19161. return path2;
  19162. };
  19163. const defaultHandler = (blobInfo, progress) => new Promise((success, failure) => {
  19164. const xhr = new XMLHttpRequest();
  19165. xhr.open('POST', settings.url);
  19166. xhr.withCredentials = settings.credentials;
  19167. xhr.upload.onprogress = e => {
  19168. progress(e.loaded / e.total * 100);
  19169. };
  19170. xhr.onerror = () => {
  19171. failure('Image upload failed due to a XHR Transport error. Code: ' + xhr.status);
  19172. };
  19173. xhr.onload = () => {
  19174. if (xhr.status < 200 || xhr.status >= 300) {
  19175. failure('HTTP Error: ' + xhr.status);
  19176. return;
  19177. }
  19178. const json = JSON.parse(xhr.responseText);
  19179. if (!json || !isString(json.location)) {
  19180. failure('Invalid JSON: ' + xhr.responseText);
  19181. return;
  19182. }
  19183. success(pathJoin(settings.basePath, json.location));
  19184. };
  19185. const formData = new FormData();
  19186. formData.append('file', blobInfo.blob(), blobInfo.filename());
  19187. xhr.send(formData);
  19188. });
  19189. const uploadHandler = isFunction(settings.handler) ? settings.handler : defaultHandler;
  19190. const noUpload = () => new Promise(resolve => {
  19191. resolve([]);
  19192. });
  19193. const handlerSuccess = (blobInfo, url) => ({
  19194. url,
  19195. blobInfo,
  19196. status: true
  19197. });
  19198. const handlerFailure = (blobInfo, error) => ({
  19199. url: '',
  19200. blobInfo,
  19201. status: false,
  19202. error
  19203. });
  19204. const resolvePending = (blobUri, result) => {
  19205. Tools.each(pendingPromises[blobUri], resolve => {
  19206. resolve(result);
  19207. });
  19208. delete pendingPromises[blobUri];
  19209. };
  19210. const uploadBlobInfo = (blobInfo, handler, openNotification) => {
  19211. uploadStatus.markPending(blobInfo.blobUri());
  19212. return new Promise(resolve => {
  19213. let notification;
  19214. let progress;
  19215. try {
  19216. const closeNotification = () => {
  19217. if (notification) {
  19218. notification.close();
  19219. progress = noop;
  19220. }
  19221. };
  19222. const success = url => {
  19223. closeNotification();
  19224. uploadStatus.markUploaded(blobInfo.blobUri(), url);
  19225. resolvePending(blobInfo.blobUri(), handlerSuccess(blobInfo, url));
  19226. resolve(handlerSuccess(blobInfo, url));
  19227. };
  19228. const failure = error => {
  19229. closeNotification();
  19230. uploadStatus.removeFailed(blobInfo.blobUri());
  19231. resolvePending(blobInfo.blobUri(), handlerFailure(blobInfo, error));
  19232. resolve(handlerFailure(blobInfo, error));
  19233. };
  19234. progress = percent => {
  19235. if (percent < 0 || percent > 100) {
  19236. return;
  19237. }
  19238. Optional.from(notification).orThunk(() => Optional.from(openNotification).map(apply$1)).each(n => {
  19239. notification = n;
  19240. n.progressBar.value(percent);
  19241. });
  19242. };
  19243. handler(blobInfo, progress).then(success, err => {
  19244. failure(isString(err) ? { message: err } : err);
  19245. });
  19246. } catch (ex) {
  19247. resolve(handlerFailure(blobInfo, ex));
  19248. }
  19249. });
  19250. };
  19251. const isDefaultHandler = handler => handler === defaultHandler;
  19252. const pendingUploadBlobInfo = blobInfo => {
  19253. const blobUri = blobInfo.blobUri();
  19254. return new Promise(resolve => {
  19255. pendingPromises[blobUri] = pendingPromises[blobUri] || [];
  19256. pendingPromises[blobUri].push(resolve);
  19257. });
  19258. };
  19259. const uploadBlobs = (blobInfos, openNotification) => {
  19260. blobInfos = Tools.grep(blobInfos, blobInfo => !uploadStatus.isUploaded(blobInfo.blobUri()));
  19261. return Promise.all(Tools.map(blobInfos, blobInfo => uploadStatus.isPending(blobInfo.blobUri()) ? pendingUploadBlobInfo(blobInfo) : uploadBlobInfo(blobInfo, uploadHandler, openNotification)));
  19262. };
  19263. const upload = (blobInfos, openNotification) => !settings.url && isDefaultHandler(uploadHandler) ? noUpload() : uploadBlobs(blobInfos, openNotification);
  19264. return { upload };
  19265. };
  19266. const openNotification = editor => () => editor.notificationManager.open({
  19267. text: editor.translate('Image uploading...'),
  19268. type: 'info',
  19269. timeout: -1,
  19270. progressBar: true
  19271. });
  19272. const createUploader = (editor, uploadStatus) => Uploader(uploadStatus, {
  19273. url: getImageUploadUrl(editor),
  19274. basePath: getImageUploadBasePath(editor),
  19275. credentials: getImagesUploadCredentials(editor),
  19276. handler: getImagesUploadHandler(editor)
  19277. });
  19278. const ImageUploader = editor => {
  19279. const uploadStatus = UploadStatus();
  19280. const uploader = createUploader(editor, uploadStatus);
  19281. return { upload: (blobInfos, showNotification = true) => uploader.upload(blobInfos, showNotification ? openNotification(editor) : undefined) };
  19282. };
  19283. const EditorUpload = editor => {
  19284. const blobCache = BlobCache();
  19285. let uploader, imageScanner;
  19286. const uploadStatus = UploadStatus();
  19287. const urlFilters = [];
  19288. const aliveGuard = callback => {
  19289. return result => {
  19290. if (editor.selection) {
  19291. return callback(result);
  19292. }
  19293. return [];
  19294. };
  19295. };
  19296. const cacheInvalidator = url => url + (url.indexOf('?') === -1 ? '?' : '&') + new Date().getTime();
  19297. const replaceString = (content, search, replace) => {
  19298. let index = 0;
  19299. do {
  19300. index = content.indexOf(search, index);
  19301. if (index !== -1) {
  19302. content = content.substring(0, index) + replace + content.substr(index + search.length);
  19303. index += replace.length - search.length + 1;
  19304. }
  19305. } while (index !== -1);
  19306. return content;
  19307. };
  19308. const replaceImageUrl = (content, targetUrl, replacementUrl) => {
  19309. const replacementString = `src="${ replacementUrl }"${ replacementUrl === Env.transparentSrc ? ' data-mce-placeholder="1"' : '' }`;
  19310. content = replaceString(content, `src="${ targetUrl }"`, replacementString);
  19311. content = replaceString(content, 'data-mce-src="' + targetUrl + '"', 'data-mce-src="' + replacementUrl + '"');
  19312. return content;
  19313. };
  19314. const replaceUrlInUndoStack = (targetUrl, replacementUrl) => {
  19315. each$e(editor.undoManager.data, level => {
  19316. if (level.type === 'fragmented') {
  19317. level.fragments = map$3(level.fragments, fragment => replaceImageUrl(fragment, targetUrl, replacementUrl));
  19318. } else {
  19319. level.content = replaceImageUrl(level.content, targetUrl, replacementUrl);
  19320. }
  19321. });
  19322. };
  19323. const replaceImageUriInView = (image, resultUri) => {
  19324. const src = editor.convertURL(resultUri, 'src');
  19325. replaceUrlInUndoStack(image.src, resultUri);
  19326. setAll$1(SugarElement.fromDom(image), {
  19327. 'src': shouldReuseFileName(editor) ? cacheInvalidator(resultUri) : resultUri,
  19328. 'data-mce-src': src
  19329. });
  19330. };
  19331. const uploadImages = () => {
  19332. if (!uploader) {
  19333. uploader = createUploader(editor, uploadStatus);
  19334. }
  19335. return scanForImages().then(aliveGuard(imageInfos => {
  19336. const blobInfos = map$3(imageInfos, imageInfo => imageInfo.blobInfo);
  19337. return uploader.upload(blobInfos, openNotification(editor)).then(aliveGuard(result => {
  19338. const imagesToRemove = [];
  19339. let shouldDispatchChange = false;
  19340. const filteredResult = map$3(result, (uploadInfo, index) => {
  19341. const {blobInfo, image} = imageInfos[index];
  19342. let removed = false;
  19343. if (uploadInfo.status && shouldReplaceBlobUris(editor)) {
  19344. if (uploadInfo.url && !contains$1(image.src, uploadInfo.url)) {
  19345. shouldDispatchChange = true;
  19346. }
  19347. blobCache.removeByUri(image.src);
  19348. if (isRtc(editor)) ; else {
  19349. replaceImageUriInView(image, uploadInfo.url);
  19350. }
  19351. } else if (uploadInfo.error) {
  19352. if (uploadInfo.error.remove) {
  19353. replaceUrlInUndoStack(image.src, Env.transparentSrc);
  19354. imagesToRemove.push(image);
  19355. removed = true;
  19356. }
  19357. uploadError(editor, uploadInfo.error.message);
  19358. }
  19359. return {
  19360. element: image,
  19361. status: uploadInfo.status,
  19362. uploadUri: uploadInfo.url,
  19363. blobInfo,
  19364. removed
  19365. };
  19366. });
  19367. if (imagesToRemove.length > 0 && !isRtc(editor)) {
  19368. editor.undoManager.transact(() => {
  19369. each$e(imagesToRemove, element => {
  19370. editor.dom.remove(element);
  19371. blobCache.removeByUri(element.src);
  19372. });
  19373. });
  19374. } else if (shouldDispatchChange) {
  19375. editor.undoManager.dispatchChange();
  19376. }
  19377. return filteredResult;
  19378. }));
  19379. }));
  19380. };
  19381. const uploadImagesAuto = () => isAutomaticUploadsEnabled(editor) ? uploadImages() : Promise.resolve([]);
  19382. const isValidDataUriImage = imgElm => forall(urlFilters, filter => filter(imgElm));
  19383. const addFilter = filter => {
  19384. urlFilters.push(filter);
  19385. };
  19386. const scanForImages = () => {
  19387. if (!imageScanner) {
  19388. imageScanner = ImageScanner(uploadStatus, blobCache);
  19389. }
  19390. return imageScanner.findAll(editor.getBody(), isValidDataUriImage).then(aliveGuard(result => {
  19391. const filteredResult = filter$5(result, resultItem => {
  19392. if (isString(resultItem)) {
  19393. displayError(editor, resultItem);
  19394. return false;
  19395. } else if (resultItem.uriType === 'blob') {
  19396. return false;
  19397. } else {
  19398. return true;
  19399. }
  19400. });
  19401. if (isRtc(editor)) ; else {
  19402. each$e(filteredResult, resultItem => {
  19403. replaceUrlInUndoStack(resultItem.image.src, resultItem.blobInfo.blobUri());
  19404. resultItem.image.src = resultItem.blobInfo.blobUri();
  19405. resultItem.image.removeAttribute('data-mce-src');
  19406. });
  19407. }
  19408. return filteredResult;
  19409. }));
  19410. };
  19411. const destroy = () => {
  19412. blobCache.destroy();
  19413. uploadStatus.destroy();
  19414. imageScanner = uploader = null;
  19415. };
  19416. const replaceBlobUris = content => {
  19417. return content.replace(/src="(blob:[^"]+)"/g, (match, blobUri) => {
  19418. const resultUri = uploadStatus.getResultUri(blobUri);
  19419. if (resultUri) {
  19420. return 'src="' + resultUri + '"';
  19421. }
  19422. let blobInfo = blobCache.getByUri(blobUri);
  19423. if (!blobInfo) {
  19424. blobInfo = foldl(editor.editorManager.get(), (result, editor) => {
  19425. return result || editor.editorUpload && editor.editorUpload.blobCache.getByUri(blobUri);
  19426. }, undefined);
  19427. }
  19428. if (blobInfo) {
  19429. const blob = blobInfo.blob();
  19430. return 'src="data:' + blob.type + ';base64,' + blobInfo.base64() + '"';
  19431. }
  19432. return match;
  19433. });
  19434. };
  19435. editor.on('SetContent', () => {
  19436. if (isAutomaticUploadsEnabled(editor)) {
  19437. uploadImagesAuto();
  19438. } else {
  19439. scanForImages();
  19440. }
  19441. });
  19442. editor.on('RawSaveContent', e => {
  19443. e.content = replaceBlobUris(e.content);
  19444. });
  19445. editor.on('GetContent', e => {
  19446. if (e.source_view || e.format === 'raw' || e.format === 'tree') {
  19447. return;
  19448. }
  19449. e.content = replaceBlobUris(e.content);
  19450. });
  19451. editor.on('PostRender', () => {
  19452. editor.parser.addNodeFilter('img', images => {
  19453. each$e(images, img => {
  19454. const src = img.attr('src');
  19455. if (!src || blobCache.getByUri(src)) {
  19456. return;
  19457. }
  19458. const resultUri = uploadStatus.getResultUri(src);
  19459. if (resultUri) {
  19460. img.attr('src', resultUri);
  19461. }
  19462. });
  19463. });
  19464. });
  19465. return {
  19466. blobCache,
  19467. addFilter,
  19468. uploadImages,
  19469. uploadImagesAuto,
  19470. scanForImages,
  19471. destroy
  19472. };
  19473. };
  19474. const get$1 = editor => {
  19475. const dom = editor.dom;
  19476. const schemaType = editor.schema.type;
  19477. const formats = {
  19478. valigntop: [{
  19479. selector: 'td,th',
  19480. styles: { verticalAlign: 'top' }
  19481. }],
  19482. valignmiddle: [{
  19483. selector: 'td,th',
  19484. styles: { verticalAlign: 'middle' }
  19485. }],
  19486. valignbottom: [{
  19487. selector: 'td,th',
  19488. styles: { verticalAlign: 'bottom' }
  19489. }],
  19490. alignleft: [
  19491. {
  19492. selector: 'figure.image',
  19493. collapsed: false,
  19494. classes: 'align-left',
  19495. ceFalseOverride: true,
  19496. preview: 'font-family font-size'
  19497. },
  19498. {
  19499. selector: 'figure,p,h1,h2,h3,h4,h5,h6,td,th,tr,div,ul,ol,li,pre',
  19500. styles: { textAlign: 'left' },
  19501. inherit: false,
  19502. preview: false
  19503. },
  19504. {
  19505. selector: 'img,audio,video',
  19506. collapsed: false,
  19507. styles: { float: 'left' },
  19508. preview: 'font-family font-size'
  19509. },
  19510. {
  19511. selector: 'table',
  19512. collapsed: false,
  19513. styles: {
  19514. marginLeft: '0px',
  19515. marginRight: 'auto'
  19516. },
  19517. onformat: table => {
  19518. dom.setStyle(table, 'float', null);
  19519. },
  19520. preview: 'font-family font-size'
  19521. },
  19522. {
  19523. selector: '.mce-preview-object,[data-ephox-embed-iri]',
  19524. ceFalseOverride: true,
  19525. styles: { float: 'left' }
  19526. }
  19527. ],
  19528. aligncenter: [
  19529. {
  19530. selector: 'figure,p,h1,h2,h3,h4,h5,h6,td,th,tr,div,ul,ol,li,pre',
  19531. styles: { textAlign: 'center' },
  19532. inherit: false,
  19533. preview: 'font-family font-size'
  19534. },
  19535. {
  19536. selector: 'figure.image',
  19537. collapsed: false,
  19538. classes: 'align-center',
  19539. ceFalseOverride: true,
  19540. preview: 'font-family font-size'
  19541. },
  19542. {
  19543. selector: 'img,audio,video',
  19544. collapsed: false,
  19545. styles: {
  19546. display: 'block',
  19547. marginLeft: 'auto',
  19548. marginRight: 'auto'
  19549. },
  19550. preview: false
  19551. },
  19552. {
  19553. selector: 'table',
  19554. collapsed: false,
  19555. styles: {
  19556. marginLeft: 'auto',
  19557. marginRight: 'auto'
  19558. },
  19559. preview: 'font-family font-size'
  19560. },
  19561. {
  19562. selector: '.mce-preview-object',
  19563. ceFalseOverride: true,
  19564. styles: {
  19565. display: 'table',
  19566. marginLeft: 'auto',
  19567. marginRight: 'auto'
  19568. },
  19569. preview: false
  19570. },
  19571. {
  19572. selector: '[data-ephox-embed-iri]',
  19573. ceFalseOverride: true,
  19574. styles: {
  19575. marginLeft: 'auto',
  19576. marginRight: 'auto'
  19577. },
  19578. preview: false
  19579. }
  19580. ],
  19581. alignright: [
  19582. {
  19583. selector: 'figure.image',
  19584. collapsed: false,
  19585. classes: 'align-right',
  19586. ceFalseOverride: true,
  19587. preview: 'font-family font-size'
  19588. },
  19589. {
  19590. selector: 'figure,p,h1,h2,h3,h4,h5,h6,td,th,tr,div,ul,ol,li,pre',
  19591. styles: { textAlign: 'right' },
  19592. inherit: false,
  19593. preview: 'font-family font-size'
  19594. },
  19595. {
  19596. selector: 'img,audio,video',
  19597. collapsed: false,
  19598. styles: { float: 'right' },
  19599. preview: 'font-family font-size'
  19600. },
  19601. {
  19602. selector: 'table',
  19603. collapsed: false,
  19604. styles: {
  19605. marginRight: '0px',
  19606. marginLeft: 'auto'
  19607. },
  19608. onformat: table => {
  19609. dom.setStyle(table, 'float', null);
  19610. },
  19611. preview: 'font-family font-size'
  19612. },
  19613. {
  19614. selector: '.mce-preview-object,[data-ephox-embed-iri]',
  19615. ceFalseOverride: true,
  19616. styles: { float: 'right' },
  19617. preview: false
  19618. }
  19619. ],
  19620. alignjustify: [{
  19621. selector: 'figure,p,h1,h2,h3,h4,h5,h6,td,th,tr,div,ul,ol,li,pre',
  19622. styles: { textAlign: 'justify' },
  19623. inherit: false,
  19624. preview: 'font-family font-size'
  19625. }],
  19626. bold: [
  19627. {
  19628. inline: 'strong',
  19629. remove: 'all',
  19630. preserve_attributes: [
  19631. 'class',
  19632. 'style'
  19633. ]
  19634. },
  19635. {
  19636. inline: 'span',
  19637. styles: { fontWeight: 'bold' }
  19638. },
  19639. {
  19640. inline: 'b',
  19641. remove: 'all',
  19642. preserve_attributes: [
  19643. 'class',
  19644. 'style'
  19645. ]
  19646. }
  19647. ],
  19648. italic: [
  19649. {
  19650. inline: 'em',
  19651. remove: 'all',
  19652. preserve_attributes: [
  19653. 'class',
  19654. 'style'
  19655. ]
  19656. },
  19657. {
  19658. inline: 'span',
  19659. styles: { fontStyle: 'italic' }
  19660. },
  19661. {
  19662. inline: 'i',
  19663. remove: 'all',
  19664. preserve_attributes: [
  19665. 'class',
  19666. 'style'
  19667. ]
  19668. }
  19669. ],
  19670. underline: [
  19671. {
  19672. inline: 'span',
  19673. styles: { textDecoration: 'underline' },
  19674. exact: true
  19675. },
  19676. {
  19677. inline: 'u',
  19678. remove: 'all',
  19679. preserve_attributes: [
  19680. 'class',
  19681. 'style'
  19682. ]
  19683. }
  19684. ],
  19685. strikethrough: (() => {
  19686. const span = {
  19687. inline: 'span',
  19688. styles: { textDecoration: 'line-through' },
  19689. exact: true
  19690. };
  19691. const strike = {
  19692. inline: 'strike',
  19693. remove: 'all',
  19694. preserve_attributes: [
  19695. 'class',
  19696. 'style'
  19697. ]
  19698. };
  19699. const s = {
  19700. inline: 's',
  19701. remove: 'all',
  19702. preserve_attributes: [
  19703. 'class',
  19704. 'style'
  19705. ]
  19706. };
  19707. return schemaType !== 'html4' ? [
  19708. s,
  19709. span,
  19710. strike
  19711. ] : [
  19712. span,
  19713. s,
  19714. strike
  19715. ];
  19716. })(),
  19717. forecolor: {
  19718. inline: 'span',
  19719. styles: { color: '%value' },
  19720. links: true,
  19721. remove_similar: true,
  19722. clear_child_styles: true
  19723. },
  19724. hilitecolor: {
  19725. inline: 'span',
  19726. styles: { backgroundColor: '%value' },
  19727. links: true,
  19728. remove_similar: true,
  19729. clear_child_styles: true
  19730. },
  19731. fontname: {
  19732. inline: 'span',
  19733. toggle: false,
  19734. styles: { fontFamily: '%value' },
  19735. clear_child_styles: true
  19736. },
  19737. fontsize: {
  19738. inline: 'span',
  19739. toggle: false,
  19740. styles: { fontSize: '%value' },
  19741. clear_child_styles: true
  19742. },
  19743. lineheight: {
  19744. selector: 'h1,h2,h3,h4,h5,h6,p,li,td,th,div',
  19745. styles: { lineHeight: '%value' }
  19746. },
  19747. fontsize_class: {
  19748. inline: 'span',
  19749. attributes: { class: '%value' }
  19750. },
  19751. blockquote: {
  19752. block: 'blockquote',
  19753. wrapper: true,
  19754. remove: 'all'
  19755. },
  19756. subscript: { inline: 'sub' },
  19757. superscript: { inline: 'sup' },
  19758. code: { inline: 'code' },
  19759. link: {
  19760. inline: 'a',
  19761. selector: 'a',
  19762. remove: 'all',
  19763. split: true,
  19764. deep: true,
  19765. onmatch: (node, _fmt, _itemName) => {
  19766. return isElement$6(node) && node.hasAttribute('href');
  19767. },
  19768. onformat: (elm, _fmt, vars) => {
  19769. Tools.each(vars, (value, key) => {
  19770. dom.setAttrib(elm, key, value);
  19771. });
  19772. }
  19773. },
  19774. lang: {
  19775. inline: 'span',
  19776. clear_child_styles: true,
  19777. remove_similar: true,
  19778. attributes: {
  19779. 'lang': '%value',
  19780. 'data-mce-lang': vars => {
  19781. var _a;
  19782. return (_a = vars === null || vars === void 0 ? void 0 : vars.customValue) !== null && _a !== void 0 ? _a : null;
  19783. }
  19784. }
  19785. },
  19786. removeformat: [
  19787. {
  19788. selector: 'b,strong,em,i,font,u,strike,s,sub,sup,dfn,code,samp,kbd,var,cite,mark,q,del,ins,small',
  19789. remove: 'all',
  19790. split: true,
  19791. expand: false,
  19792. block_expand: true,
  19793. deep: true
  19794. },
  19795. {
  19796. selector: 'span',
  19797. attributes: [
  19798. 'style',
  19799. 'class'
  19800. ],
  19801. remove: 'empty',
  19802. split: true,
  19803. expand: false,
  19804. deep: true
  19805. },
  19806. {
  19807. selector: '*',
  19808. attributes: [
  19809. 'style',
  19810. 'class'
  19811. ],
  19812. split: false,
  19813. expand: false,
  19814. deep: true
  19815. }
  19816. ]
  19817. };
  19818. Tools.each('p h1 h2 h3 h4 h5 h6 div address pre dt dd samp'.split(/\s/), name => {
  19819. formats[name] = {
  19820. block: name,
  19821. remove: 'all'
  19822. };
  19823. });
  19824. return formats;
  19825. };
  19826. const genericBase = {
  19827. remove_similar: true,
  19828. inherit: false
  19829. };
  19830. const cellBase = {
  19831. selector: 'td,th',
  19832. ...genericBase
  19833. };
  19834. const cellFormats = {
  19835. tablecellbackgroundcolor: {
  19836. styles: { backgroundColor: '%value' },
  19837. ...cellBase
  19838. },
  19839. tablecellverticalalign: {
  19840. styles: { 'vertical-align': '%value' },
  19841. ...cellBase
  19842. },
  19843. tablecellbordercolor: {
  19844. styles: { borderColor: '%value' },
  19845. ...cellBase
  19846. },
  19847. tablecellclass: {
  19848. classes: ['%value'],
  19849. ...cellBase
  19850. },
  19851. tableclass: {
  19852. selector: 'table',
  19853. classes: ['%value'],
  19854. ...genericBase
  19855. },
  19856. tablecellborderstyle: {
  19857. styles: { borderStyle: '%value' },
  19858. ...cellBase
  19859. },
  19860. tablecellborderwidth: {
  19861. styles: { borderWidth: '%value' },
  19862. ...cellBase
  19863. }
  19864. };
  19865. const get = constant(cellFormats);
  19866. const FormatRegistry = editor => {
  19867. const formats = {};
  19868. const get$2 = name => isNonNullable(name) ? formats[name] : formats;
  19869. const has = name => has$2(formats, name);
  19870. const register = (name, format) => {
  19871. if (name) {
  19872. if (!isString(name)) {
  19873. each$d(name, (format, name) => {
  19874. register(name, format);
  19875. });
  19876. } else {
  19877. if (!isArray$1(format)) {
  19878. format = [format];
  19879. }
  19880. each$e(format, format => {
  19881. if (isUndefined(format.deep)) {
  19882. format.deep = !isSelectorFormat(format);
  19883. }
  19884. if (isUndefined(format.split)) {
  19885. format.split = !isSelectorFormat(format) || isInlineFormat(format);
  19886. }
  19887. if (isUndefined(format.remove) && isSelectorFormat(format) && !isInlineFormat(format)) {
  19888. format.remove = 'none';
  19889. }
  19890. if (isSelectorFormat(format) && isInlineFormat(format)) {
  19891. format.mixed = true;
  19892. format.block_expand = true;
  19893. }
  19894. if (isString(format.classes)) {
  19895. format.classes = format.classes.split(/\s+/);
  19896. }
  19897. });
  19898. formats[name] = format;
  19899. }
  19900. }
  19901. };
  19902. const unregister = name => {
  19903. if (name && formats[name]) {
  19904. delete formats[name];
  19905. }
  19906. return formats;
  19907. };
  19908. register(get$1(editor));
  19909. register(get());
  19910. register(getFormats(editor));
  19911. return {
  19912. get: get$2,
  19913. has,
  19914. register,
  19915. unregister
  19916. };
  19917. };
  19918. const each$3 = Tools.each;
  19919. const dom = DOMUtils.DOM;
  19920. const isPreviewItem = item => isNonNullable(item) && isObject(item);
  19921. const parsedSelectorToHtml = (ancestry, editor) => {
  19922. const schema = editor && editor.schema || Schema({});
  19923. const decorate = (elm, item) => {
  19924. if (item.classes.length > 0) {
  19925. dom.addClass(elm, item.classes.join(' '));
  19926. }
  19927. dom.setAttribs(elm, item.attrs);
  19928. };
  19929. const createElement = sItem => {
  19930. const item = isString(sItem) ? {
  19931. name: sItem,
  19932. classes: [],
  19933. attrs: {}
  19934. } : sItem;
  19935. const elm = dom.create(item.name);
  19936. decorate(elm, item);
  19937. return elm;
  19938. };
  19939. const getRequiredParent = (elm, candidate) => {
  19940. const elmRule = schema.getElementRule(elm.nodeName.toLowerCase());
  19941. const parentsRequired = elmRule === null || elmRule === void 0 ? void 0 : elmRule.parentsRequired;
  19942. if (parentsRequired && parentsRequired.length) {
  19943. return candidate && contains$2(parentsRequired, candidate) ? candidate : parentsRequired[0];
  19944. } else {
  19945. return false;
  19946. }
  19947. };
  19948. const wrapInHtml = (elm, ancestors, siblings) => {
  19949. let parentCandidate;
  19950. const ancestor = ancestors[0];
  19951. const ancestorName = isPreviewItem(ancestor) ? ancestor.name : undefined;
  19952. const parentRequired = getRequiredParent(elm, ancestorName);
  19953. if (parentRequired) {
  19954. if (ancestorName === parentRequired) {
  19955. parentCandidate = ancestor;
  19956. ancestors = ancestors.slice(1);
  19957. } else {
  19958. parentCandidate = parentRequired;
  19959. }
  19960. } else if (ancestor) {
  19961. parentCandidate = ancestor;
  19962. ancestors = ancestors.slice(1);
  19963. } else if (!siblings) {
  19964. return elm;
  19965. }
  19966. const parent = parentCandidate ? createElement(parentCandidate) : dom.create('div');
  19967. parent.appendChild(elm);
  19968. if (siblings) {
  19969. Tools.each(siblings, sibling => {
  19970. const siblingElm = createElement(sibling);
  19971. parent.insertBefore(siblingElm, elm);
  19972. });
  19973. }
  19974. const parentSiblings = isPreviewItem(parentCandidate) ? parentCandidate.siblings : undefined;
  19975. return wrapInHtml(parent, ancestors, parentSiblings);
  19976. };
  19977. const fragment = dom.create('div');
  19978. if (ancestry.length > 0) {
  19979. const item = ancestry[0];
  19980. const elm = createElement(item);
  19981. const siblings = isPreviewItem(item) ? item.siblings : undefined;
  19982. fragment.appendChild(wrapInHtml(elm, ancestry.slice(1), siblings));
  19983. }
  19984. return fragment;
  19985. };
  19986. const parseSelectorItem = item => {
  19987. item = Tools.trim(item);
  19988. let tagName = 'div';
  19989. const obj = {
  19990. name: tagName,
  19991. classes: [],
  19992. attrs: {},
  19993. selector: item
  19994. };
  19995. if (item !== '*') {
  19996. tagName = item.replace(/(?:([#\.]|::?)([\w\-]+)|(\[)([^\]]+)\]?)/g, ($0, $1, $2, $3, $4) => {
  19997. switch ($1) {
  19998. case '#':
  19999. obj.attrs.id = $2;
  20000. break;
  20001. case '.':
  20002. obj.classes.push($2);
  20003. break;
  20004. case ':':
  20005. if (Tools.inArray('checked disabled enabled read-only required'.split(' '), $2) !== -1) {
  20006. obj.attrs[$2] = $2;
  20007. }
  20008. break;
  20009. }
  20010. if ($3 === '[') {
  20011. const m = $4.match(/([\w\-]+)(?:\=\"([^\"]+))?/);
  20012. if (m) {
  20013. obj.attrs[m[1]] = m[2];
  20014. }
  20015. }
  20016. return '';
  20017. });
  20018. }
  20019. obj.name = tagName || 'div';
  20020. return obj;
  20021. };
  20022. const parseSelector = selector => {
  20023. if (!isString(selector)) {
  20024. return [];
  20025. }
  20026. selector = selector.split(/\s*,\s*/)[0];
  20027. selector = selector.replace(/\s*(~\+|~|\+|>)\s*/g, '$1');
  20028. return Tools.map(selector.split(/(?:>|\s+(?![^\[\]]+\]))/), item => {
  20029. const siblings = Tools.map(item.split(/(?:~\+|~|\+)/), parseSelectorItem);
  20030. const obj = siblings.pop();
  20031. if (siblings.length) {
  20032. obj.siblings = siblings;
  20033. }
  20034. return obj;
  20035. }).reverse();
  20036. };
  20037. const getCssText = (editor, format) => {
  20038. let previewCss = '';
  20039. let previewStyles = getPreviewStyles(editor);
  20040. if (previewStyles === '') {
  20041. return '';
  20042. }
  20043. const removeVars = val => {
  20044. return isString(val) ? val.replace(/%(\w+)/g, '') : '';
  20045. };
  20046. const getComputedStyle = (name, elm) => {
  20047. return dom.getStyle(elm !== null && elm !== void 0 ? elm : editor.getBody(), name, true);
  20048. };
  20049. if (isString(format)) {
  20050. const formats = editor.formatter.get(format);
  20051. if (!formats) {
  20052. return '';
  20053. }
  20054. format = formats[0];
  20055. }
  20056. if ('preview' in format) {
  20057. const preview = format.preview;
  20058. if (preview === false) {
  20059. return '';
  20060. } else {
  20061. previewStyles = preview || previewStyles;
  20062. }
  20063. }
  20064. let name = format.block || format.inline || 'span';
  20065. let previewFrag;
  20066. const items = parseSelector(format.selector);
  20067. if (items.length > 0) {
  20068. if (!items[0].name) {
  20069. items[0].name = name;
  20070. }
  20071. name = format.selector;
  20072. previewFrag = parsedSelectorToHtml(items, editor);
  20073. } else {
  20074. previewFrag = parsedSelectorToHtml([name], editor);
  20075. }
  20076. const previewElm = dom.select(name, previewFrag)[0] || previewFrag.firstChild;
  20077. each$3(format.styles, (value, name) => {
  20078. const newValue = removeVars(value);
  20079. if (newValue) {
  20080. dom.setStyle(previewElm, name, newValue);
  20081. }
  20082. });
  20083. each$3(format.attributes, (value, name) => {
  20084. const newValue = removeVars(value);
  20085. if (newValue) {
  20086. dom.setAttrib(previewElm, name, newValue);
  20087. }
  20088. });
  20089. each$3(format.classes, value => {
  20090. const newValue = removeVars(value);
  20091. if (!dom.hasClass(previewElm, newValue)) {
  20092. dom.addClass(previewElm, newValue);
  20093. }
  20094. });
  20095. editor.dispatch('PreviewFormats');
  20096. dom.setStyles(previewFrag, {
  20097. position: 'absolute',
  20098. left: -65535
  20099. });
  20100. editor.getBody().appendChild(previewFrag);
  20101. const rawParentFontSize = getComputedStyle('fontSize');
  20102. const parentFontSize = /px$/.test(rawParentFontSize) ? parseInt(rawParentFontSize, 10) : 0;
  20103. each$3(previewStyles.split(' '), name => {
  20104. let value = getComputedStyle(name, previewElm);
  20105. if (name === 'background-color' && /transparent|rgba\s*\([^)]+,\s*0\)/.test(value)) {
  20106. value = getComputedStyle(name);
  20107. if (rgbaToHexString(value).toLowerCase() === '#ffffff') {
  20108. return;
  20109. }
  20110. }
  20111. if (name === 'color') {
  20112. if (rgbaToHexString(value).toLowerCase() === '#000000') {
  20113. return;
  20114. }
  20115. }
  20116. if (name === 'font-size') {
  20117. if (/em|%$/.test(value)) {
  20118. if (parentFontSize === 0) {
  20119. return;
  20120. }
  20121. const numValue = parseFloat(value) / (/%$/.test(value) ? 100 : 1);
  20122. value = numValue * parentFontSize + 'px';
  20123. }
  20124. }
  20125. if (name === 'border' && value) {
  20126. previewCss += 'padding:0 2px;';
  20127. }
  20128. previewCss += name + ':' + value + ';';
  20129. });
  20130. editor.dispatch('AfterPreviewFormats');
  20131. dom.remove(previewFrag);
  20132. return previewCss;
  20133. };
  20134. const setup$r = editor => {
  20135. editor.addShortcut('meta+b', '', 'Bold');
  20136. editor.addShortcut('meta+i', '', 'Italic');
  20137. editor.addShortcut('meta+u', '', 'Underline');
  20138. for (let i = 1; i <= 6; i++) {
  20139. editor.addShortcut('access+' + i, '', [
  20140. 'FormatBlock',
  20141. false,
  20142. 'h' + i
  20143. ]);
  20144. }
  20145. editor.addShortcut('access+7', '', [
  20146. 'FormatBlock',
  20147. false,
  20148. 'p'
  20149. ]);
  20150. editor.addShortcut('access+8', '', [
  20151. 'FormatBlock',
  20152. false,
  20153. 'div'
  20154. ]);
  20155. editor.addShortcut('access+9', '', [
  20156. 'FormatBlock',
  20157. false,
  20158. 'address'
  20159. ]);
  20160. };
  20161. const Formatter = editor => {
  20162. const formats = FormatRegistry(editor);
  20163. const formatChangeState = Cell({});
  20164. setup$r(editor);
  20165. setup$u(editor);
  20166. if (!isRtc(editor)) {
  20167. setup$t(formatChangeState, editor);
  20168. }
  20169. return {
  20170. get: formats.get,
  20171. has: formats.has,
  20172. register: formats.register,
  20173. unregister: formats.unregister,
  20174. apply: (name, vars, node) => {
  20175. applyFormat(editor, name, vars, node);
  20176. },
  20177. remove: (name, vars, node, similar) => {
  20178. removeFormat(editor, name, vars, node, similar);
  20179. },
  20180. toggle: (name, vars, node) => {
  20181. toggleFormat(editor, name, vars, node);
  20182. },
  20183. match: (name, vars, node, similar) => matchFormat(editor, name, vars, node, similar),
  20184. closest: names => closestFormat(editor, names),
  20185. matchAll: (names, vars) => matchAllFormats(editor, names, vars),
  20186. matchNode: (node, name, vars, similar) => matchNodeFormat(editor, node, name, vars, similar),
  20187. canApply: name => canApplyFormat(editor, name),
  20188. formatChanged: (formats, callback, similar, vars) => formatChanged(editor, formatChangeState, formats, callback, similar, vars),
  20189. getCssText: curry(getCssText, editor)
  20190. };
  20191. };
  20192. const shouldIgnoreCommand = cmd => {
  20193. switch (cmd.toLowerCase()) {
  20194. case 'undo':
  20195. case 'redo':
  20196. case 'mcefocus':
  20197. return true;
  20198. default:
  20199. return false;
  20200. }
  20201. };
  20202. const registerEvents = (editor, undoManager, locks) => {
  20203. const isFirstTypedCharacter = Cell(false);
  20204. const addNonTypingUndoLevel = e => {
  20205. setTyping(undoManager, false, locks);
  20206. undoManager.add({}, e);
  20207. };
  20208. editor.on('init', () => {
  20209. undoManager.add();
  20210. });
  20211. editor.on('BeforeExecCommand', e => {
  20212. const cmd = e.command;
  20213. if (!shouldIgnoreCommand(cmd)) {
  20214. endTyping(undoManager, locks);
  20215. undoManager.beforeChange();
  20216. }
  20217. });
  20218. editor.on('ExecCommand', e => {
  20219. const cmd = e.command;
  20220. if (!shouldIgnoreCommand(cmd)) {
  20221. addNonTypingUndoLevel(e);
  20222. }
  20223. });
  20224. editor.on('ObjectResizeStart cut', () => {
  20225. undoManager.beforeChange();
  20226. });
  20227. editor.on('SaveContent ObjectResized blur', addNonTypingUndoLevel);
  20228. editor.on('dragend', addNonTypingUndoLevel);
  20229. editor.on('keyup', e => {
  20230. const keyCode = e.keyCode;
  20231. if (e.isDefaultPrevented()) {
  20232. return;
  20233. }
  20234. if (keyCode >= 33 && keyCode <= 36 || keyCode >= 37 && keyCode <= 40 || keyCode === 45 || e.ctrlKey) {
  20235. addNonTypingUndoLevel();
  20236. editor.nodeChanged();
  20237. }
  20238. if (keyCode === 46 || keyCode === 8) {
  20239. editor.nodeChanged();
  20240. }
  20241. if (isFirstTypedCharacter.get() && undoManager.typing && !isEq$1(createFromEditor(editor), undoManager.data[0])) {
  20242. if (!editor.isDirty()) {
  20243. editor.setDirty(true);
  20244. }
  20245. editor.dispatch('TypingUndo');
  20246. isFirstTypedCharacter.set(false);
  20247. editor.nodeChanged();
  20248. }
  20249. });
  20250. editor.on('keydown', e => {
  20251. const keyCode = e.keyCode;
  20252. if (e.isDefaultPrevented()) {
  20253. return;
  20254. }
  20255. if (keyCode >= 33 && keyCode <= 36 || keyCode >= 37 && keyCode <= 40 || keyCode === 45) {
  20256. if (undoManager.typing) {
  20257. addNonTypingUndoLevel(e);
  20258. }
  20259. return;
  20260. }
  20261. const modKey = e.ctrlKey && !e.altKey || e.metaKey;
  20262. if ((keyCode < 16 || keyCode > 20) && keyCode !== 224 && keyCode !== 91 && !undoManager.typing && !modKey) {
  20263. undoManager.beforeChange();
  20264. setTyping(undoManager, true, locks);
  20265. undoManager.add({}, e);
  20266. isFirstTypedCharacter.set(true);
  20267. }
  20268. });
  20269. editor.on('mousedown', e => {
  20270. if (undoManager.typing) {
  20271. addNonTypingUndoLevel(e);
  20272. }
  20273. });
  20274. const isInsertReplacementText = event => event.inputType === 'insertReplacementText';
  20275. const isInsertTextDataNull = event => event.inputType === 'insertText' && event.data === null;
  20276. const isInsertFromPasteOrDrop = event => event.inputType === 'insertFromPaste' || event.inputType === 'insertFromDrop';
  20277. editor.on('input', e => {
  20278. if (e.inputType && (isInsertReplacementText(e) || isInsertTextDataNull(e) || isInsertFromPasteOrDrop(e))) {
  20279. addNonTypingUndoLevel(e);
  20280. }
  20281. });
  20282. editor.on('AddUndo Undo Redo ClearUndos', e => {
  20283. if (!e.isDefaultPrevented()) {
  20284. editor.nodeChanged();
  20285. }
  20286. });
  20287. };
  20288. const addKeyboardShortcuts = editor => {
  20289. editor.addShortcut('meta+z', '', 'Undo');
  20290. editor.addShortcut('meta+y,meta+shift+z', '', 'Redo');
  20291. };
  20292. const UndoManager = editor => {
  20293. const beforeBookmark = value$2();
  20294. const locks = Cell(0);
  20295. const index = Cell(0);
  20296. const undoManager = {
  20297. data: [],
  20298. typing: false,
  20299. beforeChange: () => {
  20300. beforeChange(editor, locks, beforeBookmark);
  20301. },
  20302. add: (level, event) => {
  20303. return addUndoLevel(editor, undoManager, index, locks, beforeBookmark, level, event);
  20304. },
  20305. dispatchChange: () => {
  20306. editor.setDirty(true);
  20307. const level = createFromEditor(editor);
  20308. level.bookmark = getUndoBookmark(editor.selection);
  20309. editor.dispatch('change', {
  20310. level,
  20311. lastLevel: get$b(undoManager.data, index.get()).getOrUndefined()
  20312. });
  20313. },
  20314. undo: () => {
  20315. return undo(editor, undoManager, locks, index);
  20316. },
  20317. redo: () => {
  20318. return redo(editor, index, undoManager.data);
  20319. },
  20320. clear: () => {
  20321. clear(editor, undoManager, index);
  20322. },
  20323. reset: () => {
  20324. reset(editor, undoManager);
  20325. },
  20326. hasUndo: () => {
  20327. return hasUndo(editor, undoManager, index);
  20328. },
  20329. hasRedo: () => {
  20330. return hasRedo(editor, undoManager, index);
  20331. },
  20332. transact: callback => {
  20333. return transact(editor, undoManager, locks, callback);
  20334. },
  20335. ignore: callback => {
  20336. ignore(editor, locks, callback);
  20337. },
  20338. extra: (callback1, callback2) => {
  20339. extra(editor, undoManager, index, callback1, callback2);
  20340. }
  20341. };
  20342. if (!isRtc(editor)) {
  20343. registerEvents(editor, undoManager, locks);
  20344. }
  20345. addKeyboardShortcuts(editor);
  20346. return undoManager;
  20347. };
  20348. const nonTypingKeycodes = [
  20349. 9,
  20350. 27,
  20351. VK.HOME,
  20352. VK.END,
  20353. 19,
  20354. 20,
  20355. 44,
  20356. 144,
  20357. 145,
  20358. 33,
  20359. 34,
  20360. 45,
  20361. 16,
  20362. 17,
  20363. 18,
  20364. 91,
  20365. 92,
  20366. 93,
  20367. VK.DOWN,
  20368. VK.UP,
  20369. VK.LEFT,
  20370. VK.RIGHT
  20371. ].concat(Env.browser.isFirefox() ? [224] : []);
  20372. const placeholderAttr = 'data-mce-placeholder';
  20373. const isKeyboardEvent = e => e.type === 'keydown' || e.type === 'keyup';
  20374. const isDeleteEvent = e => {
  20375. const keyCode = e.keyCode;
  20376. return keyCode === VK.BACKSPACE || keyCode === VK.DELETE;
  20377. };
  20378. const isNonTypingKeyboardEvent = e => {
  20379. if (isKeyboardEvent(e)) {
  20380. const keyCode = e.keyCode;
  20381. return !isDeleteEvent(e) && (VK.metaKeyPressed(e) || e.altKey || keyCode >= 112 && keyCode <= 123 || contains$2(nonTypingKeycodes, keyCode));
  20382. } else {
  20383. return false;
  20384. }
  20385. };
  20386. const isTypingKeyboardEvent = e => isKeyboardEvent(e) && !(isDeleteEvent(e) || e.type === 'keyup' && e.keyCode === 229);
  20387. const isVisuallyEmpty = (dom, rootElm, forcedRootBlock) => {
  20388. if (isEmpty$2(SugarElement.fromDom(rootElm), false)) {
  20389. const firstElement = rootElm.firstElementChild;
  20390. if (!firstElement) {
  20391. return true;
  20392. } else if (dom.getStyle(rootElm.firstElementChild, 'padding-left') || dom.getStyle(rootElm.firstElementChild, 'padding-right')) {
  20393. return false;
  20394. } else {
  20395. return forcedRootBlock === firstElement.nodeName.toLowerCase();
  20396. }
  20397. } else {
  20398. return false;
  20399. }
  20400. };
  20401. const setup$q = editor => {
  20402. var _a;
  20403. const dom = editor.dom;
  20404. const rootBlock = getForcedRootBlock(editor);
  20405. const placeholder = (_a = getPlaceholder(editor)) !== null && _a !== void 0 ? _a : '';
  20406. const updatePlaceholder = (e, initial) => {
  20407. if (isNonTypingKeyboardEvent(e)) {
  20408. return;
  20409. }
  20410. const body = editor.getBody();
  20411. const showPlaceholder = isTypingKeyboardEvent(e) ? false : isVisuallyEmpty(dom, body, rootBlock);
  20412. const isPlaceholderShown = dom.getAttrib(body, placeholderAttr) !== '';
  20413. if (isPlaceholderShown !== showPlaceholder || initial) {
  20414. dom.setAttrib(body, placeholderAttr, showPlaceholder ? placeholder : null);
  20415. dom.setAttrib(body, 'aria-placeholder', showPlaceholder ? placeholder : null);
  20416. firePlaceholderToggle(editor, showPlaceholder);
  20417. editor.on(showPlaceholder ? 'keydown' : 'keyup', updatePlaceholder);
  20418. editor.off(showPlaceholder ? 'keyup' : 'keydown', updatePlaceholder);
  20419. }
  20420. };
  20421. if (isNotEmpty(placeholder)) {
  20422. editor.on('init', e => {
  20423. updatePlaceholder(e, true);
  20424. editor.on('change SetContent ExecCommand', updatePlaceholder);
  20425. editor.on('paste', e => Delay.setEditorTimeout(editor, () => updatePlaceholder(e)));
  20426. });
  20427. }
  20428. };
  20429. const blockPosition = (block, position) => ({
  20430. block,
  20431. position
  20432. });
  20433. const blockBoundary = (from, to) => ({
  20434. from,
  20435. to
  20436. });
  20437. const getBlockPosition = (rootNode, pos) => {
  20438. const rootElm = SugarElement.fromDom(rootNode);
  20439. const containerElm = SugarElement.fromDom(pos.container());
  20440. return getParentBlock$2(rootElm, containerElm).map(block => blockPosition(block, pos));
  20441. };
  20442. const isDifferentBlocks = blockBoundary => !eq(blockBoundary.from.block, blockBoundary.to.block);
  20443. const getClosestHost = (root, scope) => {
  20444. const isRoot = node => eq(node, root);
  20445. const isHost = node => isTableCell$2(node) || isContentEditableTrue$3(node.dom);
  20446. return closest$4(scope, isHost, isRoot).filter(isElement$7).getOr(root);
  20447. };
  20448. const hasSameHost = (rootNode, blockBoundary) => {
  20449. const root = SugarElement.fromDom(rootNode);
  20450. return eq(getClosestHost(root, blockBoundary.from.block), getClosestHost(root, blockBoundary.to.block));
  20451. };
  20452. const isEditable$1 = blockBoundary => isContentEditableFalse$b(blockBoundary.from.block.dom) === false && isContentEditableFalse$b(blockBoundary.to.block.dom) === false;
  20453. const hasValidBlocks = blockBoundary => {
  20454. const isValidBlock = block => isTextBlock$2(block) || hasBlockAttr(block.dom);
  20455. return isValidBlock(blockBoundary.from.block) && isValidBlock(blockBoundary.to.block);
  20456. };
  20457. const skipLastBr = (rootNode, forward, blockPosition) => {
  20458. if (isBr$6(blockPosition.position.getNode()) && !isEmpty$2(blockPosition.block)) {
  20459. return positionIn(false, blockPosition.block.dom).bind(lastPositionInBlock => {
  20460. if (lastPositionInBlock.isEqual(blockPosition.position)) {
  20461. return fromPosition(forward, rootNode, lastPositionInBlock).bind(to => getBlockPosition(rootNode, to));
  20462. } else {
  20463. return Optional.some(blockPosition);
  20464. }
  20465. }).getOr(blockPosition);
  20466. } else {
  20467. return blockPosition;
  20468. }
  20469. };
  20470. const readFromRange = (rootNode, forward, rng) => {
  20471. const fromBlockPos = getBlockPosition(rootNode, CaretPosition.fromRangeStart(rng));
  20472. const toBlockPos = fromBlockPos.bind(blockPos => fromPosition(forward, rootNode, blockPos.position).bind(to => getBlockPosition(rootNode, to).map(blockPos => skipLastBr(rootNode, forward, blockPos))));
  20473. return lift2(fromBlockPos, toBlockPos, blockBoundary).filter(blockBoundary => isDifferentBlocks(blockBoundary) && hasSameHost(rootNode, blockBoundary) && isEditable$1(blockBoundary) && hasValidBlocks(blockBoundary));
  20474. };
  20475. const read$1 = (rootNode, forward, rng) => rng.collapsed ? readFromRange(rootNode, forward, rng) : Optional.none();
  20476. const getChildrenUntilBlockBoundary = block => {
  20477. const children = children$1(block);
  20478. return findIndex$2(children, isBlock$2).fold(constant(children), index => children.slice(0, index));
  20479. };
  20480. const extractChildren = block => {
  20481. const children = getChildrenUntilBlockBoundary(block);
  20482. each$e(children, remove$6);
  20483. return children;
  20484. };
  20485. const removeEmptyRoot = (rootNode, block) => {
  20486. const parents = parentsAndSelf(block, rootNode);
  20487. return find$2(parents.reverse(), element => isEmpty$2(element)).each(remove$6);
  20488. };
  20489. const isEmptyBefore = el => filter$5(prevSiblings(el), el => !isEmpty$2(el)).length === 0;
  20490. const nestedBlockMerge = (rootNode, fromBlock, toBlock, insertionPoint) => {
  20491. if (isEmpty$2(toBlock)) {
  20492. fillWithPaddingBr(toBlock);
  20493. return firstPositionIn(toBlock.dom);
  20494. }
  20495. if (isEmptyBefore(insertionPoint) && isEmpty$2(fromBlock)) {
  20496. before$3(insertionPoint, SugarElement.fromTag('br'));
  20497. }
  20498. const position = prevPosition(toBlock.dom, CaretPosition.before(insertionPoint.dom));
  20499. each$e(extractChildren(fromBlock), child => {
  20500. before$3(insertionPoint, child);
  20501. });
  20502. removeEmptyRoot(rootNode, fromBlock);
  20503. return position;
  20504. };
  20505. const sidelongBlockMerge = (rootNode, fromBlock, toBlock) => {
  20506. if (isEmpty$2(toBlock)) {
  20507. if (isEmpty$2(fromBlock)) {
  20508. const getInlineToBlockDescendants = el => {
  20509. const helper = (node, elements) => firstChild(node).fold(() => elements, child => isInline$1(child) ? helper(child, elements.concat(shallow$1(child))) : elements);
  20510. return helper(el, []);
  20511. };
  20512. const newFromBlockDescendants = foldr(getInlineToBlockDescendants(toBlock), (element, descendant) => {
  20513. wrap$2(element, descendant);
  20514. return descendant;
  20515. }, createPaddingBr());
  20516. empty(fromBlock);
  20517. append$1(fromBlock, newFromBlockDescendants);
  20518. }
  20519. remove$6(toBlock);
  20520. return firstPositionIn(fromBlock.dom);
  20521. }
  20522. const position = lastPositionIn(toBlock.dom);
  20523. each$e(extractChildren(fromBlock), child => {
  20524. append$1(toBlock, child);
  20525. });
  20526. removeEmptyRoot(rootNode, fromBlock);
  20527. return position;
  20528. };
  20529. const findInsertionPoint = (toBlock, block) => {
  20530. const parentsAndSelf$1 = parentsAndSelf(block, toBlock);
  20531. return Optional.from(parentsAndSelf$1[parentsAndSelf$1.length - 1]);
  20532. };
  20533. const getInsertionPoint = (fromBlock, toBlock) => contains(toBlock, fromBlock) ? findInsertionPoint(toBlock, fromBlock) : Optional.none();
  20534. const trimBr = (first, block) => {
  20535. positionIn(first, block.dom).bind(position => Optional.from(position.getNode())).map(SugarElement.fromDom).filter(isBr$5).each(remove$6);
  20536. };
  20537. const mergeBlockInto = (rootNode, fromBlock, toBlock) => {
  20538. trimBr(true, fromBlock);
  20539. trimBr(false, toBlock);
  20540. return getInsertionPoint(fromBlock, toBlock).fold(curry(sidelongBlockMerge, rootNode, fromBlock, toBlock), curry(nestedBlockMerge, rootNode, fromBlock, toBlock));
  20541. };
  20542. const mergeBlocks = (rootNode, forward, block1, block2) => forward ? mergeBlockInto(rootNode, block2, block1) : mergeBlockInto(rootNode, block1, block2);
  20543. const backspaceDelete$8 = (editor, forward) => {
  20544. const rootNode = SugarElement.fromDom(editor.getBody());
  20545. const position = read$1(rootNode.dom, forward, editor.selection.getRng()).map(blockBoundary => () => {
  20546. mergeBlocks(rootNode, forward, blockBoundary.from.block, blockBoundary.to.block).each(pos => {
  20547. editor.selection.setRng(pos.toRange());
  20548. });
  20549. });
  20550. return position;
  20551. };
  20552. const deleteRangeMergeBlocks = (rootNode, selection) => {
  20553. const rng = selection.getRng();
  20554. return lift2(getParentBlock$2(rootNode, SugarElement.fromDom(rng.startContainer)), getParentBlock$2(rootNode, SugarElement.fromDom(rng.endContainer)), (block1, block2) => {
  20555. if (!eq(block1, block2)) {
  20556. return Optional.some(() => {
  20557. rng.deleteContents();
  20558. mergeBlocks(rootNode, true, block1, block2).each(pos => {
  20559. selection.setRng(pos.toRange());
  20560. });
  20561. });
  20562. } else {
  20563. return Optional.none();
  20564. }
  20565. }).getOr(Optional.none());
  20566. };
  20567. const isRawNodeInTable = (root, rawNode) => {
  20568. const node = SugarElement.fromDom(rawNode);
  20569. const isRoot = curry(eq, root);
  20570. return ancestor$4(node, isTableCell$2, isRoot).isSome();
  20571. };
  20572. const isSelectionInTable = (root, rng) => isRawNodeInTable(root, rng.startContainer) || isRawNodeInTable(root, rng.endContainer);
  20573. const isEverythingSelected = (root, rng) => {
  20574. const noPrevious = prevPosition(root.dom, CaretPosition.fromRangeStart(rng)).isNone();
  20575. const noNext = nextPosition(root.dom, CaretPosition.fromRangeEnd(rng)).isNone();
  20576. return !isSelectionInTable(root, rng) && noPrevious && noNext;
  20577. };
  20578. const emptyEditor = editor => {
  20579. return Optional.some(() => {
  20580. editor.setContent('');
  20581. editor.selection.setCursorLocation();
  20582. });
  20583. };
  20584. const deleteRange$2 = editor => {
  20585. const rootNode = SugarElement.fromDom(editor.getBody());
  20586. const rng = editor.selection.getRng();
  20587. return isEverythingSelected(rootNode, rng) ? emptyEditor(editor) : deleteRangeMergeBlocks(rootNode, editor.selection);
  20588. };
  20589. const backspaceDelete$7 = (editor, _forward) => editor.selection.isCollapsed() ? Optional.none() : deleteRange$2(editor);
  20590. const showCaret = (direction, editor, node, before, scrollIntoView) => Optional.from(editor._selectionOverrides.showCaret(direction, node, before, scrollIntoView));
  20591. const getNodeRange = node => {
  20592. const rng = node.ownerDocument.createRange();
  20593. rng.selectNode(node);
  20594. return rng;
  20595. };
  20596. const selectNode = (editor, node) => {
  20597. const e = editor.dispatch('BeforeObjectSelected', { target: node });
  20598. if (e.isDefaultPrevented()) {
  20599. return Optional.none();
  20600. }
  20601. return Optional.some(getNodeRange(node));
  20602. };
  20603. const renderCaretAtRange = (editor, range, scrollIntoView) => {
  20604. const normalizedRange = normalizeRange(1, editor.getBody(), range);
  20605. const caretPosition = CaretPosition.fromRangeStart(normalizedRange);
  20606. const caretPositionNode = caretPosition.getNode();
  20607. if (isInlineFakeCaretTarget(caretPositionNode)) {
  20608. return showCaret(1, editor, caretPositionNode, !caretPosition.isAtEnd(), false);
  20609. }
  20610. const caretPositionBeforeNode = caretPosition.getNode(true);
  20611. if (isInlineFakeCaretTarget(caretPositionBeforeNode)) {
  20612. return showCaret(1, editor, caretPositionBeforeNode, false, false);
  20613. }
  20614. const ceRoot = getContentEditableRoot$1(editor.dom.getRoot(), caretPosition.getNode());
  20615. if (isInlineFakeCaretTarget(ceRoot)) {
  20616. return showCaret(1, editor, ceRoot, false, scrollIntoView);
  20617. }
  20618. return Optional.none();
  20619. };
  20620. const renderRangeCaret = (editor, range, scrollIntoView) => range.collapsed ? renderCaretAtRange(editor, range, scrollIntoView).getOr(range) : range;
  20621. const isBeforeBoundary = pos => isBeforeContentEditableFalse(pos) || isBeforeMedia(pos);
  20622. const isAfterBoundary = pos => isAfterContentEditableFalse(pos) || isAfterMedia(pos);
  20623. const trimEmptyTextNode = (dom, node) => {
  20624. if (isText$a(node) && node.data.length === 0) {
  20625. dom.remove(node);
  20626. }
  20627. };
  20628. const deleteContentAndShowCaret = (editor, range, node, direction, forward, peekCaretPosition) => {
  20629. showCaret(direction, editor, peekCaretPosition.getNode(!forward), forward, true).each(caretRange => {
  20630. if (range.collapsed) {
  20631. const deleteRange = range.cloneRange();
  20632. if (forward) {
  20633. deleteRange.setEnd(caretRange.startContainer, caretRange.startOffset);
  20634. } else {
  20635. deleteRange.setStart(caretRange.endContainer, caretRange.endOffset);
  20636. }
  20637. deleteRange.deleteContents();
  20638. } else {
  20639. range.deleteContents();
  20640. }
  20641. editor.selection.setRng(caretRange);
  20642. });
  20643. trimEmptyTextNode(editor.dom, node);
  20644. };
  20645. const deleteBoundaryText = (editor, forward) => {
  20646. const range = editor.selection.getRng();
  20647. if (!isText$a(range.commonAncestorContainer)) {
  20648. return Optional.none();
  20649. }
  20650. const direction = forward ? HDirection.Forwards : HDirection.Backwards;
  20651. const caretWalker = CaretWalker(editor.getBody());
  20652. const getNextPosFn = curry(getVisualCaretPosition, forward ? caretWalker.next : caretWalker.prev);
  20653. const isBeforeFn = forward ? isBeforeBoundary : isAfterBoundary;
  20654. const caretPosition = getNormalizedRangeEndPoint(direction, editor.getBody(), range);
  20655. const nextCaretPosition = getNextPosFn(caretPosition);
  20656. const normalizedNextCaretPosition = nextCaretPosition ? normalizePosition(forward, nextCaretPosition) : nextCaretPosition;
  20657. if (!normalizedNextCaretPosition || !isMoveInsideSameBlock(caretPosition, normalizedNextCaretPosition)) {
  20658. return Optional.none();
  20659. } else if (isBeforeFn(normalizedNextCaretPosition)) {
  20660. return Optional.some(() => deleteContentAndShowCaret(editor, range, caretPosition.getNode(), direction, forward, normalizedNextCaretPosition));
  20661. }
  20662. const peekCaretPosition = getNextPosFn(normalizedNextCaretPosition);
  20663. if (peekCaretPosition && isBeforeFn(peekCaretPosition)) {
  20664. if (isMoveInsideSameBlock(normalizedNextCaretPosition, peekCaretPosition)) {
  20665. return Optional.some(() => deleteContentAndShowCaret(editor, range, caretPosition.getNode(), direction, forward, peekCaretPosition));
  20666. }
  20667. }
  20668. return Optional.none();
  20669. };
  20670. const backspaceDelete$6 = (editor, forward) => deleteBoundaryText(editor, forward);
  20671. const getEdgeCefPosition = (editor, atStart) => {
  20672. const root = editor.getBody();
  20673. return atStart ? firstPositionIn(root).filter(isBeforeContentEditableFalse) : lastPositionIn(root).filter(isAfterContentEditableFalse);
  20674. };
  20675. const isCefAtEdgeSelected = editor => {
  20676. const rng = editor.selection.getRng();
  20677. return !rng.collapsed && (getEdgeCefPosition(editor, true).exists(pos => pos.isEqual(CaretPosition.fromRangeStart(rng))) || getEdgeCefPosition(editor, false).exists(pos => pos.isEqual(CaretPosition.fromRangeEnd(rng))));
  20678. };
  20679. const isCompoundElement = node => isNonNullable(node) && (isTableCell$2(SugarElement.fromDom(node)) || isListItem$1(SugarElement.fromDom(node)));
  20680. const DeleteAction = Adt.generate([
  20681. { remove: ['element'] },
  20682. { moveToElement: ['element'] },
  20683. { moveToPosition: ['position'] }
  20684. ]);
  20685. const isAtContentEditableBlockCaret = (forward, from) => {
  20686. const elm = from.getNode(!forward);
  20687. const caretLocation = forward ? 'after' : 'before';
  20688. return isElement$6(elm) && elm.getAttribute('data-mce-caret') === caretLocation;
  20689. };
  20690. const isDeleteFromCefDifferentBlocks = (root, forward, from, to) => {
  20691. const inSameBlock = elm => isInline$1(SugarElement.fromDom(elm)) && !isInSameBlock(from, to, root);
  20692. return getRelativeCefElm(!forward, from).fold(() => getRelativeCefElm(forward, to).fold(never, inSameBlock), inSameBlock);
  20693. };
  20694. const deleteEmptyBlockOrMoveToCef = (root, forward, from, to) => {
  20695. const toCefElm = to.getNode(!forward);
  20696. 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)));
  20697. };
  20698. const findCefPosition = (root, forward, from) => fromPosition(forward, root, from).bind(to => {
  20699. if (isCompoundElement(to.getNode())) {
  20700. return Optional.none();
  20701. } else if (isDeleteFromCefDifferentBlocks(root, forward, from, to)) {
  20702. return Optional.none();
  20703. } else if (forward && isContentEditableFalse$b(to.getNode())) {
  20704. return deleteEmptyBlockOrMoveToCef(root, forward, from, to);
  20705. } else if (!forward && isContentEditableFalse$b(to.getNode(true))) {
  20706. return deleteEmptyBlockOrMoveToCef(root, forward, from, to);
  20707. } else if (forward && isAfterContentEditableFalse(from)) {
  20708. return Optional.some(DeleteAction.moveToPosition(to));
  20709. } else if (!forward && isBeforeContentEditableFalse(from)) {
  20710. return Optional.some(DeleteAction.moveToPosition(to));
  20711. } else {
  20712. return Optional.none();
  20713. }
  20714. });
  20715. const getContentEditableBlockAction = (forward, elm) => {
  20716. if (isNullable(elm)) {
  20717. return Optional.none();
  20718. } else if (forward && isContentEditableFalse$b(elm.nextSibling)) {
  20719. return Optional.some(DeleteAction.moveToElement(elm.nextSibling));
  20720. } else if (!forward && isContentEditableFalse$b(elm.previousSibling)) {
  20721. return Optional.some(DeleteAction.moveToElement(elm.previousSibling));
  20722. } else {
  20723. return Optional.none();
  20724. }
  20725. };
  20726. const skipMoveToActionFromInlineCefToContent = (root, from, deleteAction) => deleteAction.fold(elm => Optional.some(DeleteAction.remove(elm)), elm => Optional.some(DeleteAction.moveToElement(elm)), to => {
  20727. if (isInSameBlock(from, to, root)) {
  20728. return Optional.none();
  20729. } else {
  20730. return Optional.some(DeleteAction.moveToPosition(to));
  20731. }
  20732. });
  20733. const getContentEditableAction = (root, forward, from) => {
  20734. if (isAtContentEditableBlockCaret(forward, from)) {
  20735. return getContentEditableBlockAction(forward, from.getNode(!forward)).orThunk(() => findCefPosition(root, forward, from));
  20736. } else {
  20737. return findCefPosition(root, forward, from).bind(deleteAction => skipMoveToActionFromInlineCefToContent(root, from, deleteAction));
  20738. }
  20739. };
  20740. const read = (root, forward, rng) => {
  20741. const normalizedRange = normalizeRange(forward ? 1 : -1, root, rng);
  20742. const from = CaretPosition.fromRangeStart(normalizedRange);
  20743. const rootElement = SugarElement.fromDom(root);
  20744. if (!forward && isAfterContentEditableFalse(from)) {
  20745. return Optional.some(DeleteAction.remove(from.getNode(true)));
  20746. } else if (forward && isBeforeContentEditableFalse(from)) {
  20747. return Optional.some(DeleteAction.remove(from.getNode()));
  20748. } else if (!forward && isBeforeContentEditableFalse(from) && isAfterBr(rootElement, from)) {
  20749. return findPreviousBr(rootElement, from).map(br => DeleteAction.remove(br.getNode()));
  20750. } else if (forward && isAfterContentEditableFalse(from) && isBeforeBr$1(rootElement, from)) {
  20751. return findNextBr(rootElement, from).map(br => DeleteAction.remove(br.getNode()));
  20752. } else {
  20753. return getContentEditableAction(root, forward, from);
  20754. }
  20755. };
  20756. const deleteElement$1 = (editor, forward) => element => {
  20757. editor._selectionOverrides.hideFakeCaret();
  20758. deleteElement$2(editor, forward, SugarElement.fromDom(element));
  20759. return true;
  20760. };
  20761. const moveToElement = (editor, forward) => element => {
  20762. const pos = forward ? CaretPosition.before(element) : CaretPosition.after(element);
  20763. editor.selection.setRng(pos.toRange());
  20764. return true;
  20765. };
  20766. const moveToPosition = editor => pos => {
  20767. editor.selection.setRng(pos.toRange());
  20768. return true;
  20769. };
  20770. const getAncestorCe = (editor, node) => Optional.from(getContentEditableRoot$1(editor.getBody(), node));
  20771. const backspaceDeleteCaret = (editor, forward) => {
  20772. const selectedNode = editor.selection.getNode();
  20773. 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));
  20774. };
  20775. const deleteOffscreenSelection = rootElement => {
  20776. each$e(descendants(rootElement, '.mce-offscreen-selection'), remove$6);
  20777. };
  20778. const backspaceDeleteRange = (editor, forward) => {
  20779. const selectedNode = editor.selection.getNode();
  20780. if (isContentEditableFalse$b(selectedNode) && !isTableCell$3(selectedNode)) {
  20781. const hasCefAncestor = getAncestorCe(editor, selectedNode.parentNode).filter(isContentEditableFalse$b);
  20782. return hasCefAncestor.fold(() => Optional.some(() => {
  20783. deleteOffscreenSelection(SugarElement.fromDom(editor.getBody()));
  20784. deleteElement$2(editor, forward, SugarElement.fromDom(editor.selection.getNode()));
  20785. paddEmptyBody(editor);
  20786. }), () => Optional.some(noop));
  20787. }
  20788. if (isCefAtEdgeSelected(editor)) {
  20789. return Optional.some(() => {
  20790. deleteRangeContents(editor, editor.selection.getRng(), SugarElement.fromDom(editor.getBody()));
  20791. });
  20792. }
  20793. return Optional.none();
  20794. };
  20795. const paddEmptyElement = editor => {
  20796. const dom = editor.dom, selection = editor.selection;
  20797. const ceRoot = getContentEditableRoot$1(editor.getBody(), selection.getNode());
  20798. if (isContentEditableTrue$3(ceRoot) && dom.isBlock(ceRoot) && dom.isEmpty(ceRoot)) {
  20799. const br = dom.create('br', { 'data-mce-bogus': '1' });
  20800. dom.setHTML(ceRoot, '');
  20801. ceRoot.appendChild(br);
  20802. selection.setRng(CaretPosition.before(br).toRange());
  20803. }
  20804. return true;
  20805. };
  20806. const backspaceDelete$5 = (editor, forward) => {
  20807. if (editor.selection.isCollapsed()) {
  20808. return backspaceDeleteCaret(editor, forward);
  20809. } else {
  20810. return backspaceDeleteRange(editor, forward);
  20811. }
  20812. };
  20813. const deleteCaret$2 = (editor, forward) => {
  20814. const fromPos = CaretPosition.fromRangeStart(editor.selection.getRng());
  20815. return fromPosition(forward, editor.getBody(), fromPos).filter(pos => forward ? isBeforeImageBlock(pos) : isAfterImageBlock(pos)).bind(pos => getChildNodeAtRelativeOffset(forward ? 0 : -1, pos)).map(elm => () => editor.selection.select(elm));
  20816. };
  20817. const backspaceDelete$4 = (editor, forward) => editor.selection.isCollapsed() ? deleteCaret$2(editor, forward) : Optional.none();
  20818. const isText$2 = isText$a;
  20819. const startsWithCaretContainer = node => isText$2(node) && node.data[0] === ZWSP$1;
  20820. const endsWithCaretContainer = node => isText$2(node) && node.data[node.data.length - 1] === ZWSP$1;
  20821. const createZwsp = node => {
  20822. var _a;
  20823. const doc = (_a = node.ownerDocument) !== null && _a !== void 0 ? _a : document;
  20824. return doc.createTextNode(ZWSP$1);
  20825. };
  20826. const insertBefore = node => {
  20827. var _a;
  20828. if (isText$2(node.previousSibling)) {
  20829. if (endsWithCaretContainer(node.previousSibling)) {
  20830. return node.previousSibling;
  20831. } else {
  20832. node.previousSibling.appendData(ZWSP$1);
  20833. return node.previousSibling;
  20834. }
  20835. } else if (isText$2(node)) {
  20836. if (startsWithCaretContainer(node)) {
  20837. return node;
  20838. } else {
  20839. node.insertData(0, ZWSP$1);
  20840. return node;
  20841. }
  20842. } else {
  20843. const newNode = createZwsp(node);
  20844. (_a = node.parentNode) === null || _a === void 0 ? void 0 : _a.insertBefore(newNode, node);
  20845. return newNode;
  20846. }
  20847. };
  20848. const insertAfter = node => {
  20849. var _a, _b;
  20850. if (isText$2(node.nextSibling)) {
  20851. if (startsWithCaretContainer(node.nextSibling)) {
  20852. return node.nextSibling;
  20853. } else {
  20854. node.nextSibling.insertData(0, ZWSP$1);
  20855. return node.nextSibling;
  20856. }
  20857. } else if (isText$2(node)) {
  20858. if (endsWithCaretContainer(node)) {
  20859. return node;
  20860. } else {
  20861. node.appendData(ZWSP$1);
  20862. return node;
  20863. }
  20864. } else {
  20865. const newNode = createZwsp(node);
  20866. if (node.nextSibling) {
  20867. (_a = node.parentNode) === null || _a === void 0 ? void 0 : _a.insertBefore(newNode, node.nextSibling);
  20868. } else {
  20869. (_b = node.parentNode) === null || _b === void 0 ? void 0 : _b.appendChild(newNode);
  20870. }
  20871. return newNode;
  20872. }
  20873. };
  20874. const insertInline = (before, node) => before ? insertBefore(node) : insertAfter(node);
  20875. const insertInlineBefore = curry(insertInline, true);
  20876. const insertInlineAfter = curry(insertInline, false);
  20877. const insertInlinePos = (pos, before) => {
  20878. if (isText$a(pos.container())) {
  20879. return insertInline(before, pos.container());
  20880. } else {
  20881. return insertInline(before, pos.getNode());
  20882. }
  20883. };
  20884. const isPosCaretContainer = (pos, caret) => {
  20885. const caretNode = caret.get();
  20886. return caretNode && pos.container() === caretNode && isCaretContainerInline(caretNode);
  20887. };
  20888. const renderCaret = (caret, location) => location.fold(element => {
  20889. remove$4(caret.get());
  20890. const text = insertInlineBefore(element);
  20891. caret.set(text);
  20892. return Optional.some(CaretPosition(text, text.length - 1));
  20893. }, element => firstPositionIn(element).map(pos => {
  20894. if (!isPosCaretContainer(pos, caret)) {
  20895. remove$4(caret.get());
  20896. const text = insertInlinePos(pos, true);
  20897. caret.set(text);
  20898. return CaretPosition(text, 1);
  20899. } else {
  20900. const node = caret.get();
  20901. return CaretPosition(node, 1);
  20902. }
  20903. }), element => lastPositionIn(element).map(pos => {
  20904. if (!isPosCaretContainer(pos, caret)) {
  20905. remove$4(caret.get());
  20906. const text = insertInlinePos(pos, false);
  20907. caret.set(text);
  20908. return CaretPosition(text, text.length - 1);
  20909. } else {
  20910. const node = caret.get();
  20911. return CaretPosition(node, node.length - 1);
  20912. }
  20913. }), element => {
  20914. remove$4(caret.get());
  20915. const text = insertInlineAfter(element);
  20916. caret.set(text);
  20917. return Optional.some(CaretPosition(text, 1));
  20918. });
  20919. const evaluateUntil = (fns, args) => {
  20920. for (let i = 0; i < fns.length; i++) {
  20921. const result = fns[i].apply(null, args);
  20922. if (result.isSome()) {
  20923. return result;
  20924. }
  20925. }
  20926. return Optional.none();
  20927. };
  20928. const Location = Adt.generate([
  20929. { before: ['element'] },
  20930. { start: ['element'] },
  20931. { end: ['element'] },
  20932. { after: ['element'] }
  20933. ]);
  20934. const rescope$1 = (rootNode, node) => {
  20935. const parentBlock = getParentBlock$3(node, rootNode);
  20936. return parentBlock ? parentBlock : rootNode;
  20937. };
  20938. const before = (isInlineTarget, rootNode, pos) => {
  20939. const nPos = normalizeForwards(pos);
  20940. const scope = rescope$1(rootNode, nPos.container());
  20941. return findRootInline(isInlineTarget, scope, nPos).fold(() => nextPosition(scope, nPos).bind(curry(findRootInline, isInlineTarget, scope)).map(inline => Location.before(inline)), Optional.none);
  20942. };
  20943. const isNotInsideFormatCaretContainer = (rootNode, elm) => getParentCaretContainer(rootNode, elm) === null;
  20944. const findInsideRootInline = (isInlineTarget, rootNode, pos) => findRootInline(isInlineTarget, rootNode, pos).filter(curry(isNotInsideFormatCaretContainer, rootNode));
  20945. const start$1 = (isInlineTarget, rootNode, pos) => {
  20946. const nPos = normalizeBackwards(pos);
  20947. return findInsideRootInline(isInlineTarget, rootNode, nPos).bind(inline => {
  20948. const prevPos = prevPosition(inline, nPos);
  20949. return prevPos.isNone() ? Optional.some(Location.start(inline)) : Optional.none();
  20950. });
  20951. };
  20952. const end = (isInlineTarget, rootNode, pos) => {
  20953. const nPos = normalizeForwards(pos);
  20954. return findInsideRootInline(isInlineTarget, rootNode, nPos).bind(inline => {
  20955. const nextPos = nextPosition(inline, nPos);
  20956. return nextPos.isNone() ? Optional.some(Location.end(inline)) : Optional.none();
  20957. });
  20958. };
  20959. const after = (isInlineTarget, rootNode, pos) => {
  20960. const nPos = normalizeBackwards(pos);
  20961. const scope = rescope$1(rootNode, nPos.container());
  20962. return findRootInline(isInlineTarget, scope, nPos).fold(() => prevPosition(scope, nPos).bind(curry(findRootInline, isInlineTarget, scope)).map(inline => Location.after(inline)), Optional.none);
  20963. };
  20964. const isValidLocation = location => !isRtl(getElement(location));
  20965. const readLocation = (isInlineTarget, rootNode, pos) => {
  20966. const location = evaluateUntil([
  20967. before,
  20968. start$1,
  20969. end,
  20970. after
  20971. ], [
  20972. isInlineTarget,
  20973. rootNode,
  20974. pos
  20975. ]);
  20976. return location.filter(isValidLocation);
  20977. };
  20978. const getElement = location => location.fold(identity, identity, identity, identity);
  20979. const getName = location => location.fold(constant('before'), constant('start'), constant('end'), constant('after'));
  20980. const outside = location => location.fold(Location.before, Location.before, Location.after, Location.after);
  20981. const inside = location => location.fold(Location.start, Location.start, Location.end, Location.end);
  20982. const isEq = (location1, location2) => getName(location1) === getName(location2) && getElement(location1) === getElement(location2);
  20983. const betweenInlines = (forward, isInlineTarget, rootNode, from, to, location) => lift2(findRootInline(isInlineTarget, rootNode, from), findRootInline(isInlineTarget, rootNode, to), (fromInline, toInline) => {
  20984. if (fromInline !== toInline && hasSameParentBlock(rootNode, fromInline, toInline)) {
  20985. return Location.after(forward ? fromInline : toInline);
  20986. } else {
  20987. return location;
  20988. }
  20989. }).getOr(location);
  20990. const skipNoMovement = (fromLocation, toLocation) => fromLocation.fold(always, fromLocation => !isEq(fromLocation, toLocation));
  20991. const findLocationTraverse = (forward, isInlineTarget, rootNode, fromLocation, pos) => {
  20992. const from = normalizePosition(forward, pos);
  20993. const to = fromPosition(forward, rootNode, from).map(curry(normalizePosition, forward));
  20994. const location = to.fold(() => fromLocation.map(outside), to => readLocation(isInlineTarget, rootNode, to).map(curry(betweenInlines, forward, isInlineTarget, rootNode, from, to)).filter(curry(skipNoMovement, fromLocation)));
  20995. return location.filter(isValidLocation);
  20996. };
  20997. const findLocationSimple = (forward, location) => {
  20998. if (forward) {
  20999. return location.fold(compose(Optional.some, Location.start), Optional.none, compose(Optional.some, Location.after), Optional.none);
  21000. } else {
  21001. return location.fold(Optional.none, compose(Optional.some, Location.before), Optional.none, compose(Optional.some, Location.end));
  21002. }
  21003. };
  21004. const findLocation$1 = (forward, isInlineTarget, rootNode, pos) => {
  21005. const from = normalizePosition(forward, pos);
  21006. const fromLocation = readLocation(isInlineTarget, rootNode, from);
  21007. return readLocation(isInlineTarget, rootNode, from).bind(curry(findLocationSimple, forward)).orThunk(() => findLocationTraverse(forward, isInlineTarget, rootNode, fromLocation, pos));
  21008. };
  21009. const hasSelectionModifyApi = editor => {
  21010. return isFunction(editor.selection.getSel().modify);
  21011. };
  21012. const moveRel = (forward, selection, pos) => {
  21013. const delta = forward ? 1 : -1;
  21014. selection.setRng(CaretPosition(pos.container(), pos.offset() + delta).toRange());
  21015. selection.getSel().modify('move', forward ? 'forward' : 'backward', 'word');
  21016. return true;
  21017. };
  21018. const moveByWord = (forward, editor) => {
  21019. const rng = editor.selection.getRng();
  21020. const pos = forward ? CaretPosition.fromRangeEnd(rng) : CaretPosition.fromRangeStart(rng);
  21021. if (!hasSelectionModifyApi(editor)) {
  21022. return false;
  21023. } else if (forward && isBeforeInline(pos)) {
  21024. return moveRel(true, editor.selection, pos);
  21025. } else if (!forward && isAfterInline(pos)) {
  21026. return moveRel(false, editor.selection, pos);
  21027. } else {
  21028. return false;
  21029. }
  21030. };
  21031. var BreakType;
  21032. (function (BreakType) {
  21033. BreakType[BreakType['Br'] = 0] = 'Br';
  21034. BreakType[BreakType['Block'] = 1] = 'Block';
  21035. BreakType[BreakType['Wrap'] = 2] = 'Wrap';
  21036. BreakType[BreakType['Eol'] = 3] = 'Eol';
  21037. }(BreakType || (BreakType = {})));
  21038. const flip = (direction, positions) => direction === HDirection.Backwards ? reverse(positions) : positions;
  21039. const walk$1 = (direction, caretWalker, pos) => direction === HDirection.Forwards ? caretWalker.next(pos) : caretWalker.prev(pos);
  21040. const getBreakType = (scope, direction, currentPos, nextPos) => {
  21041. if (isBr$6(nextPos.getNode(direction === HDirection.Forwards))) {
  21042. return BreakType.Br;
  21043. } else if (isInSameBlock(currentPos, nextPos) === false) {
  21044. return BreakType.Block;
  21045. } else {
  21046. return BreakType.Wrap;
  21047. }
  21048. };
  21049. const getPositionsUntil = (predicate, direction, scope, start) => {
  21050. const caretWalker = CaretWalker(scope);
  21051. let currentPos = start;
  21052. const positions = [];
  21053. while (currentPos) {
  21054. const nextPos = walk$1(direction, caretWalker, currentPos);
  21055. if (!nextPos) {
  21056. break;
  21057. }
  21058. if (isBr$6(nextPos.getNode(false))) {
  21059. if (direction === HDirection.Forwards) {
  21060. return {
  21061. positions: flip(direction, positions).concat([nextPos]),
  21062. breakType: BreakType.Br,
  21063. breakAt: Optional.some(nextPos)
  21064. };
  21065. } else {
  21066. return {
  21067. positions: flip(direction, positions),
  21068. breakType: BreakType.Br,
  21069. breakAt: Optional.some(nextPos)
  21070. };
  21071. }
  21072. }
  21073. if (!nextPos.isVisible()) {
  21074. currentPos = nextPos;
  21075. continue;
  21076. }
  21077. if (predicate(currentPos, nextPos)) {
  21078. const breakType = getBreakType(scope, direction, currentPos, nextPos);
  21079. return {
  21080. positions: flip(direction, positions),
  21081. breakType,
  21082. breakAt: Optional.some(nextPos)
  21083. };
  21084. }
  21085. positions.push(nextPos);
  21086. currentPos = nextPos;
  21087. }
  21088. return {
  21089. positions: flip(direction, positions),
  21090. breakType: BreakType.Eol,
  21091. breakAt: Optional.none()
  21092. };
  21093. };
  21094. const getAdjacentLinePositions = (direction, getPositionsUntilBreak, scope, start) => getPositionsUntilBreak(scope, start).breakAt.map(pos => {
  21095. const positions = getPositionsUntilBreak(scope, pos).positions;
  21096. return direction === HDirection.Backwards ? positions.concat(pos) : [pos].concat(positions);
  21097. }).getOr([]);
  21098. const findClosestHorizontalPositionFromPoint = (positions, x) => foldl(positions, (acc, newPos) => acc.fold(() => Optional.some(newPos), lastPos => lift2(head(lastPos.getClientRects()), head(newPos.getClientRects()), (lastRect, newRect) => {
  21099. const lastDist = Math.abs(x - lastRect.left);
  21100. const newDist = Math.abs(x - newRect.left);
  21101. return newDist <= lastDist ? newPos : lastPos;
  21102. }).or(acc)), Optional.none());
  21103. const findClosestHorizontalPosition = (positions, pos) => head(pos.getClientRects()).bind(targetRect => findClosestHorizontalPositionFromPoint(positions, targetRect.left));
  21104. const getPositionsUntilPreviousLine = curry(getPositionsUntil, CaretPosition.isAbove, -1);
  21105. const getPositionsUntilNextLine = curry(getPositionsUntil, CaretPosition.isBelow, 1);
  21106. const getPositionsAbove = curry(getAdjacentLinePositions, -1, getPositionsUntilPreviousLine);
  21107. const getPositionsBelow = curry(getAdjacentLinePositions, 1, getPositionsUntilNextLine);
  21108. const isAtFirstLine = (scope, pos) => getPositionsUntilPreviousLine(scope, pos).breakAt.isNone();
  21109. const isAtLastLine = (scope, pos) => getPositionsUntilNextLine(scope, pos).breakAt.isNone();
  21110. const getFirstLinePositions = scope => firstPositionIn(scope).map(pos => [pos].concat(getPositionsUntilNextLine(scope, pos).positions)).getOr([]);
  21111. const getLastLinePositions = scope => lastPositionIn(scope).map(pos => getPositionsUntilPreviousLine(scope, pos).positions.concat(pos)).getOr([]);
  21112. const getClosestPositionAbove = (scope, pos) => findClosestHorizontalPosition(getPositionsAbove(scope, pos), pos);
  21113. const getClosestPositionBelow = (scope, pos) => findClosestHorizontalPosition(getPositionsBelow(scope, pos), pos);
  21114. const isContentEditableFalse$4 = isContentEditableFalse$b;
  21115. const distanceToRectLeft$1 = (clientRect, clientX) => Math.abs(clientRect.left - clientX);
  21116. const distanceToRectRight$1 = (clientRect, clientX) => Math.abs(clientRect.right - clientX);
  21117. const isNodeClientRect = rect => hasNonNullableKey(rect, 'node');
  21118. const findClosestClientRect = (clientRects, clientX) => reduce(clientRects, (oldClientRect, clientRect) => {
  21119. const oldDistance = Math.min(distanceToRectLeft$1(oldClientRect, clientX), distanceToRectRight$1(oldClientRect, clientX));
  21120. const newDistance = Math.min(distanceToRectLeft$1(clientRect, clientX), distanceToRectRight$1(clientRect, clientX));
  21121. if (newDistance === oldDistance && isNodeClientRect(clientRect) && isContentEditableFalse$4(clientRect.node)) {
  21122. return clientRect;
  21123. }
  21124. if (newDistance < oldDistance) {
  21125. return clientRect;
  21126. }
  21127. return oldClientRect;
  21128. });
  21129. const getNodeClientRects = node => {
  21130. const toArrayWithNode = clientRects => {
  21131. return map$3(clientRects, rect => {
  21132. const clientRect = clone$1(rect);
  21133. clientRect.node = node;
  21134. return clientRect;
  21135. });
  21136. };
  21137. if (isElement$6(node)) {
  21138. return toArrayWithNode(node.getClientRects());
  21139. } else if (isText$a(node)) {
  21140. const rng = node.ownerDocument.createRange();
  21141. rng.setStart(node, 0);
  21142. rng.setEnd(node, node.data.length);
  21143. return toArrayWithNode(rng.getClientRects());
  21144. } else {
  21145. return [];
  21146. }
  21147. };
  21148. const getClientRects = nodes => bind$3(nodes, getNodeClientRects);
  21149. var VDirection;
  21150. (function (VDirection) {
  21151. VDirection[VDirection['Up'] = -1] = 'Up';
  21152. VDirection[VDirection['Down'] = 1] = 'Down';
  21153. }(VDirection || (VDirection = {})));
  21154. const findUntil = (direction, root, predicateFn, node) => {
  21155. let currentNode = node;
  21156. while (currentNode = findNode(currentNode, direction, isEditableCaretCandidate$1, root)) {
  21157. if (predicateFn(currentNode)) {
  21158. return;
  21159. }
  21160. }
  21161. };
  21162. const walkUntil = (direction, isAboveFn, isBeflowFn, root, predicateFn, caretPosition) => {
  21163. let line = 0;
  21164. const result = [];
  21165. const add = node => {
  21166. let clientRects = getClientRects([node]);
  21167. if (direction === -1) {
  21168. clientRects = clientRects.reverse();
  21169. }
  21170. for (let i = 0; i < clientRects.length; i++) {
  21171. const clientRect = clientRects[i];
  21172. if (isBeflowFn(clientRect, targetClientRect)) {
  21173. continue;
  21174. }
  21175. if (result.length > 0 && isAboveFn(clientRect, last$2(result))) {
  21176. line++;
  21177. }
  21178. clientRect.line = line;
  21179. if (predicateFn(clientRect)) {
  21180. return true;
  21181. }
  21182. result.push(clientRect);
  21183. }
  21184. return false;
  21185. };
  21186. const targetClientRect = last$2(caretPosition.getClientRects());
  21187. if (!targetClientRect) {
  21188. return result;
  21189. }
  21190. const node = caretPosition.getNode();
  21191. if (node) {
  21192. add(node);
  21193. findUntil(direction, root, add, node);
  21194. }
  21195. return result;
  21196. };
  21197. const aboveLineNumber = (lineNumber, clientRect) => clientRect.line > lineNumber;
  21198. const isLineNumber = (lineNumber, clientRect) => clientRect.line === lineNumber;
  21199. const upUntil = curry(walkUntil, VDirection.Up, isAbove$1, isBelow$1);
  21200. const downUntil = curry(walkUntil, VDirection.Down, isBelow$1, isAbove$1);
  21201. const getLastClientRect = caretPosition => {
  21202. return last$2(caretPosition.getClientRects());
  21203. };
  21204. const positionsUntil = (direction, root, predicateFn, node) => {
  21205. const caretWalker = CaretWalker(root);
  21206. let walkFn;
  21207. let isBelowFn;
  21208. let isAboveFn;
  21209. let caretPosition;
  21210. const result = [];
  21211. let line = 0;
  21212. if (direction === 1) {
  21213. walkFn = caretWalker.next;
  21214. isBelowFn = isBelow$1;
  21215. isAboveFn = isAbove$1;
  21216. caretPosition = CaretPosition.after(node);
  21217. } else {
  21218. walkFn = caretWalker.prev;
  21219. isBelowFn = isAbove$1;
  21220. isAboveFn = isBelow$1;
  21221. caretPosition = CaretPosition.before(node);
  21222. }
  21223. const targetClientRect = getLastClientRect(caretPosition);
  21224. do {
  21225. if (!caretPosition.isVisible()) {
  21226. continue;
  21227. }
  21228. const rect = getLastClientRect(caretPosition);
  21229. if (isAboveFn(rect, targetClientRect)) {
  21230. continue;
  21231. }
  21232. if (result.length > 0 && isBelowFn(rect, last$2(result))) {
  21233. line++;
  21234. }
  21235. const clientRect = clone$1(rect);
  21236. clientRect.position = caretPosition;
  21237. clientRect.line = line;
  21238. if (predicateFn(clientRect)) {
  21239. return result;
  21240. }
  21241. result.push(clientRect);
  21242. } while (caretPosition = walkFn(caretPosition));
  21243. return result;
  21244. };
  21245. const isAboveLine = lineNumber => clientRect => aboveLineNumber(lineNumber, clientRect);
  21246. const isLine = lineNumber => clientRect => isLineNumber(lineNumber, clientRect);
  21247. const moveToRange = (editor, rng) => {
  21248. editor.selection.setRng(rng);
  21249. scrollRangeIntoView(editor, editor.selection.getRng());
  21250. };
  21251. const renderRangeCaretOpt = (editor, range, scrollIntoView) => Optional.some(renderRangeCaret(editor, range, scrollIntoView));
  21252. const moveHorizontally = (editor, direction, range, isBefore, isAfter, isElement) => {
  21253. const forwards = direction === HDirection.Forwards;
  21254. const caretWalker = CaretWalker(editor.getBody());
  21255. const getNextPosFn = curry(getVisualCaretPosition, forwards ? caretWalker.next : caretWalker.prev);
  21256. const isBeforeFn = forwards ? isBefore : isAfter;
  21257. if (!range.collapsed) {
  21258. const node = getSelectedNode(range);
  21259. if (isElement(node)) {
  21260. return showCaret(direction, editor, node, direction === HDirection.Backwards, false);
  21261. } else if (isCefAtEdgeSelected(editor)) {
  21262. const newRange = range.cloneRange();
  21263. newRange.collapse(direction === HDirection.Backwards);
  21264. return Optional.from(newRange);
  21265. }
  21266. }
  21267. const caretPosition = getNormalizedRangeEndPoint(direction, editor.getBody(), range);
  21268. if (isBeforeFn(caretPosition)) {
  21269. return selectNode(editor, caretPosition.getNode(!forwards));
  21270. }
  21271. let nextCaretPosition = getNextPosFn(caretPosition);
  21272. const rangeIsInContainerBlock = isRangeInCaretContainerBlock(range);
  21273. if (!nextCaretPosition) {
  21274. return rangeIsInContainerBlock ? Optional.some(range) : Optional.none();
  21275. } else {
  21276. nextCaretPosition = normalizePosition(forwards, nextCaretPosition);
  21277. }
  21278. if (isBeforeFn(nextCaretPosition)) {
  21279. return showCaret(direction, editor, nextCaretPosition.getNode(!forwards), forwards, false);
  21280. }
  21281. const peekCaretPosition = getNextPosFn(nextCaretPosition);
  21282. if (peekCaretPosition && isBeforeFn(peekCaretPosition)) {
  21283. if (isMoveInsideSameBlock(nextCaretPosition, peekCaretPosition)) {
  21284. return showCaret(direction, editor, peekCaretPosition.getNode(!forwards), forwards, false);
  21285. }
  21286. }
  21287. if (rangeIsInContainerBlock) {
  21288. return renderRangeCaretOpt(editor, nextCaretPosition.toRange(), false);
  21289. }
  21290. return Optional.none();
  21291. };
  21292. const moveVertically = (editor, direction, range, isBefore, isAfter, isElement) => {
  21293. const caretPosition = getNormalizedRangeEndPoint(direction, editor.getBody(), range);
  21294. const caretClientRect = last$2(caretPosition.getClientRects());
  21295. const forwards = direction === VDirection.Down;
  21296. const root = editor.getBody();
  21297. if (!caretClientRect) {
  21298. return Optional.none();
  21299. }
  21300. if (isCefAtEdgeSelected(editor)) {
  21301. const caretPosition = forwards ? CaretPosition.fromRangeEnd(range) : CaretPosition.fromRangeStart(range);
  21302. const getClosestFn = !forwards ? getClosestPositionAbove : getClosestPositionBelow;
  21303. return getClosestFn(root, caretPosition).orThunk(() => Optional.from(caretPosition)).map(pos => pos.toRange());
  21304. }
  21305. const walkerFn = forwards ? downUntil : upUntil;
  21306. const linePositions = walkerFn(root, isAboveLine(1), caretPosition);
  21307. const nextLinePositions = filter$5(linePositions, isLine(1));
  21308. const clientX = caretClientRect.left;
  21309. const nextLineRect = findClosestClientRect(nextLinePositions, clientX);
  21310. if (nextLineRect && isElement(nextLineRect.node)) {
  21311. const dist1 = Math.abs(clientX - nextLineRect.left);
  21312. const dist2 = Math.abs(clientX - nextLineRect.right);
  21313. return showCaret(direction, editor, nextLineRect.node, dist1 < dist2, false);
  21314. }
  21315. let currentNode;
  21316. if (isBefore(caretPosition)) {
  21317. currentNode = caretPosition.getNode();
  21318. } else if (isAfter(caretPosition)) {
  21319. currentNode = caretPosition.getNode(true);
  21320. } else {
  21321. currentNode = getSelectedNode(range);
  21322. }
  21323. if (currentNode) {
  21324. const caretPositions = positionsUntil(direction, root, isAboveLine(1), currentNode);
  21325. let closestNextLineRect = findClosestClientRect(filter$5(caretPositions, isLine(1)), clientX);
  21326. if (closestNextLineRect) {
  21327. return renderRangeCaretOpt(editor, closestNextLineRect.position.toRange(), false);
  21328. }
  21329. closestNextLineRect = last$2(filter$5(caretPositions, isLine(0)));
  21330. if (closestNextLineRect) {
  21331. return renderRangeCaretOpt(editor, closestNextLineRect.position.toRange(), false);
  21332. }
  21333. }
  21334. if (nextLinePositions.length === 0) {
  21335. return getLineEndPoint(editor, forwards).filter(forwards ? isAfter : isBefore).map(pos => renderRangeCaret(editor, pos.toRange(), false));
  21336. }
  21337. return Optional.none();
  21338. };
  21339. const getLineEndPoint = (editor, forward) => {
  21340. const rng = editor.selection.getRng();
  21341. const from = forward ? CaretPosition.fromRangeEnd(rng) : CaretPosition.fromRangeStart(rng);
  21342. const host = getEditingHost(from.container(), editor.getBody());
  21343. if (forward) {
  21344. const lineInfo = getPositionsUntilNextLine(host, from);
  21345. return last$3(lineInfo.positions);
  21346. } else {
  21347. const lineInfo = getPositionsUntilPreviousLine(host, from);
  21348. return head(lineInfo.positions);
  21349. }
  21350. };
  21351. const moveToLineEndPoint$3 = (editor, forward, isElementPosition) => getLineEndPoint(editor, forward).filter(isElementPosition).exists(pos => {
  21352. editor.selection.setRng(pos.toRange());
  21353. return true;
  21354. });
  21355. const setCaretPosition = (editor, pos) => {
  21356. const rng = editor.dom.createRng();
  21357. rng.setStart(pos.container(), pos.offset());
  21358. rng.setEnd(pos.container(), pos.offset());
  21359. editor.selection.setRng(rng);
  21360. };
  21361. const setSelected = (state, elm) => {
  21362. if (state) {
  21363. elm.setAttribute('data-mce-selected', 'inline-boundary');
  21364. } else {
  21365. elm.removeAttribute('data-mce-selected');
  21366. }
  21367. };
  21368. const renderCaretLocation = (editor, caret, location) => renderCaret(caret, location).map(pos => {
  21369. setCaretPosition(editor, pos);
  21370. return location;
  21371. });
  21372. const getPositionFromRange = (range, root, forward) => {
  21373. const start = CaretPosition.fromRangeStart(range);
  21374. if (range.collapsed) {
  21375. return start;
  21376. } else {
  21377. const end = CaretPosition.fromRangeEnd(range);
  21378. return forward ? prevPosition(root, end).getOr(end) : nextPosition(root, start).getOr(start);
  21379. }
  21380. };
  21381. const findLocation = (editor, caret, forward) => {
  21382. const rootNode = editor.getBody();
  21383. const from = getPositionFromRange(editor.selection.getRng(), rootNode, forward);
  21384. const isInlineTarget$1 = curry(isInlineTarget, editor);
  21385. const location = findLocation$1(forward, isInlineTarget$1, rootNode, from);
  21386. return location.bind(location => renderCaretLocation(editor, caret, location));
  21387. };
  21388. const toggleInlines = (isInlineTarget, dom, elms) => {
  21389. const inlineBoundaries = map$3(descendants(SugarElement.fromDom(dom.getRoot()), '*[data-mce-selected="inline-boundary"]'), e => e.dom);
  21390. const selectedInlines = filter$5(inlineBoundaries, isInlineTarget);
  21391. const targetInlines = filter$5(elms, isInlineTarget);
  21392. each$e(difference(selectedInlines, targetInlines), curry(setSelected, false));
  21393. each$e(difference(targetInlines, selectedInlines), curry(setSelected, true));
  21394. };
  21395. const safeRemoveCaretContainer = (editor, caret) => {
  21396. const caretValue = caret.get();
  21397. if (editor.selection.isCollapsed() && !editor.composing && caretValue) {
  21398. const pos = CaretPosition.fromRangeStart(editor.selection.getRng());
  21399. if (CaretPosition.isTextPosition(pos) && !isAtZwsp(pos)) {
  21400. setCaretPosition(editor, removeAndReposition(caretValue, pos));
  21401. caret.set(null);
  21402. }
  21403. }
  21404. };
  21405. const renderInsideInlineCaret = (isInlineTarget, editor, caret, elms) => {
  21406. if (editor.selection.isCollapsed()) {
  21407. const inlines = filter$5(elms, isInlineTarget);
  21408. each$e(inlines, _inline => {
  21409. const pos = CaretPosition.fromRangeStart(editor.selection.getRng());
  21410. readLocation(isInlineTarget, editor.getBody(), pos).bind(location => renderCaretLocation(editor, caret, location));
  21411. });
  21412. }
  21413. };
  21414. const move$2 = (editor, caret, forward) => isInlineBoundariesEnabled(editor) ? findLocation(editor, caret, forward).isSome() : false;
  21415. const moveWord = (forward, editor, _caret) => isInlineBoundariesEnabled(editor) ? moveByWord(forward, editor) : false;
  21416. const setupSelectedState = editor => {
  21417. const caret = Cell(null);
  21418. const isInlineTarget$1 = curry(isInlineTarget, editor);
  21419. editor.on('NodeChange', e => {
  21420. if (isInlineBoundariesEnabled(editor)) {
  21421. toggleInlines(isInlineTarget$1, editor.dom, e.parents);
  21422. safeRemoveCaretContainer(editor, caret);
  21423. renderInsideInlineCaret(isInlineTarget$1, editor, caret, e.parents);
  21424. }
  21425. });
  21426. return caret;
  21427. };
  21428. const moveNextWord = curry(moveWord, true);
  21429. const movePrevWord = curry(moveWord, false);
  21430. const moveToLineEndPoint$2 = (editor, forward, caret) => {
  21431. if (isInlineBoundariesEnabled(editor)) {
  21432. const linePoint = getLineEndPoint(editor, forward).getOrThunk(() => {
  21433. const rng = editor.selection.getRng();
  21434. return forward ? CaretPosition.fromRangeEnd(rng) : CaretPosition.fromRangeStart(rng);
  21435. });
  21436. return readLocation(curry(isInlineTarget, editor), editor.getBody(), linePoint).exists(loc => {
  21437. const outsideLoc = outside(loc);
  21438. return renderCaret(caret, outsideLoc).exists(pos => {
  21439. setCaretPosition(editor, pos);
  21440. return true;
  21441. });
  21442. });
  21443. } else {
  21444. return false;
  21445. }
  21446. };
  21447. const rangeFromPositions = (from, to) => {
  21448. const range = document.createRange();
  21449. range.setStart(from.container(), from.offset());
  21450. range.setEnd(to.container(), to.offset());
  21451. return range;
  21452. };
  21453. const hasOnlyTwoOrLessPositionsLeft = elm => lift2(firstPositionIn(elm), lastPositionIn(elm), (firstPos, lastPos) => {
  21454. const normalizedFirstPos = normalizePosition(true, firstPos);
  21455. const normalizedLastPos = normalizePosition(false, lastPos);
  21456. return nextPosition(elm, normalizedFirstPos).forall(pos => pos.isEqual(normalizedLastPos));
  21457. }).getOr(true);
  21458. const setCaretLocation = (editor, caret) => location => renderCaret(caret, location).map(pos => () => setCaretPosition(editor, pos));
  21459. const deleteFromTo = (editor, caret, from, to) => {
  21460. const rootNode = editor.getBody();
  21461. const isInlineTarget$1 = curry(isInlineTarget, editor);
  21462. editor.undoManager.ignore(() => {
  21463. editor.selection.setRng(rangeFromPositions(from, to));
  21464. execNativeDeleteCommand(editor);
  21465. readLocation(isInlineTarget$1, rootNode, CaretPosition.fromRangeStart(editor.selection.getRng())).map(inside).bind(setCaretLocation(editor, caret)).each(call);
  21466. });
  21467. editor.nodeChanged();
  21468. };
  21469. const rescope = (rootNode, node) => {
  21470. const parentBlock = getParentBlock$3(node, rootNode);
  21471. return parentBlock ? parentBlock : rootNode;
  21472. };
  21473. const backspaceDeleteCollapsed = (editor, caret, forward, from) => {
  21474. const rootNode = rescope(editor.getBody(), from.container());
  21475. const isInlineTarget$1 = curry(isInlineTarget, editor);
  21476. const fromLocation = readLocation(isInlineTarget$1, rootNode, from);
  21477. const location = fromLocation.bind(location => {
  21478. if (forward) {
  21479. return location.fold(constant(Optional.some(inside(location))), Optional.none, constant(Optional.some(outside(location))), Optional.none);
  21480. } else {
  21481. return location.fold(Optional.none, constant(Optional.some(outside(location))), Optional.none, constant(Optional.some(inside(location))));
  21482. }
  21483. });
  21484. return location.map(setCaretLocation(editor, caret)).getOrThunk(() => {
  21485. const toPosition = navigate(forward, rootNode, from);
  21486. const toLocation = toPosition.bind(pos => readLocation(isInlineTarget$1, rootNode, pos));
  21487. return lift2(fromLocation, toLocation, () => findRootInline(isInlineTarget$1, rootNode, from).bind(elm => {
  21488. if (hasOnlyTwoOrLessPositionsLeft(elm)) {
  21489. return Optional.some(() => {
  21490. deleteElement$2(editor, forward, SugarElement.fromDom(elm));
  21491. });
  21492. } else {
  21493. return Optional.none();
  21494. }
  21495. })).getOrThunk(() => toLocation.bind(() => toPosition.map(to => {
  21496. return () => {
  21497. if (forward) {
  21498. deleteFromTo(editor, caret, from, to);
  21499. } else {
  21500. deleteFromTo(editor, caret, to, from);
  21501. }
  21502. };
  21503. })));
  21504. });
  21505. };
  21506. const backspaceDelete$3 = (editor, caret, forward) => {
  21507. if (editor.selection.isCollapsed() && isInlineBoundariesEnabled(editor)) {
  21508. const from = CaretPosition.fromRangeStart(editor.selection.getRng());
  21509. return backspaceDeleteCollapsed(editor, caret, forward, from);
  21510. }
  21511. return Optional.none();
  21512. };
  21513. const hasMultipleChildren = elm => childNodesCount(elm) > 1;
  21514. const getParentsUntil = (editor, pred) => {
  21515. const rootElm = SugarElement.fromDom(editor.getBody());
  21516. const startElm = SugarElement.fromDom(editor.selection.getStart());
  21517. const parents = parentsAndSelf(startElm, rootElm);
  21518. return findIndex$2(parents, pred).fold(constant(parents), index => parents.slice(0, index));
  21519. };
  21520. const getParentInlinesUntilMultichildInline = editor => getParentsUntil(editor, elm => isBlock$2(elm) || hasMultipleChildren(elm));
  21521. const getParentInlines = editor => getParentsUntil(editor, isBlock$2);
  21522. const getFormatNodes = (editor, parentInlines) => {
  21523. const isFormatElement$1 = curry(isFormatElement, editor);
  21524. return bind$3(parentInlines, elm => isFormatElement$1(elm) ? [elm.dom] : []);
  21525. };
  21526. const getFormatNodesAtStart = editor => {
  21527. const parentInlines = getParentInlines(editor);
  21528. return getFormatNodes(editor, parentInlines);
  21529. };
  21530. const deleteLastPosition = (forward, editor, target, parentInlines) => {
  21531. const formatNodes = getFormatNodes(editor, parentInlines);
  21532. if (formatNodes.length === 0) {
  21533. deleteElement$2(editor, forward, target);
  21534. } else {
  21535. const pos = replaceWithCaretFormat(target.dom, formatNodes);
  21536. editor.selection.setRng(pos.toRange());
  21537. }
  21538. };
  21539. const deleteCaret$1 = (editor, forward) => {
  21540. const parentInlines = getParentInlinesUntilMultichildInline(editor);
  21541. return last$3(parentInlines).bind(target => {
  21542. const fromPos = CaretPosition.fromRangeStart(editor.selection.getRng());
  21543. if (willDeleteLastPositionInElement(forward, fromPos, target.dom) && !isEmptyCaretFormatElement(target)) {
  21544. return Optional.some(() => deleteLastPosition(forward, editor, target, parentInlines));
  21545. } else {
  21546. return Optional.none();
  21547. }
  21548. });
  21549. };
  21550. const isBrInEmptyElement = (editor, elm) => {
  21551. const parentElm = elm.parentElement;
  21552. return isBr$6(elm) && !isNull(parentElm) && editor.dom.isEmpty(parentElm);
  21553. };
  21554. const isEmptyCaret = elm => isEmptyCaretFormatElement(SugarElement.fromDom(elm));
  21555. const createCaretFormatAtStart = (editor, formatNodes) => {
  21556. const startElm = editor.selection.getStart();
  21557. const pos = isBrInEmptyElement(editor, startElm) || isEmptyCaret(startElm) ? replaceWithCaretFormat(startElm, formatNodes) : createCaretFormatAtStart$1(editor, formatNodes);
  21558. editor.selection.setRng(pos.toRange());
  21559. };
  21560. const updateCaretFormat = (editor, updateFormats) => {
  21561. const missingFormats = difference(updateFormats, getFormatNodesAtStart(editor));
  21562. if (missingFormats.length > 0) {
  21563. createCaretFormatAtStart(editor, missingFormats);
  21564. }
  21565. };
  21566. const rangeStartsAtTextContainer = rng => isText$a(rng.startContainer);
  21567. const rangeStartsAtStartOfTextContainer = rng => rng.startOffset === 0 && rangeStartsAtTextContainer(rng);
  21568. const rangeStartParentIsFormatElement = (editor, rng) => {
  21569. const startParent = rng.startContainer.parentElement;
  21570. return !isNull(startParent) && isFormatElement(editor, SugarElement.fromDom(startParent));
  21571. };
  21572. const rangeStartAndEndHaveSameParent = rng => {
  21573. const startParent = rng.startContainer.parentNode;
  21574. const endParent = rng.endContainer.parentNode;
  21575. return !isNull(startParent) && !isNull(endParent) && startParent.isEqualNode(endParent);
  21576. };
  21577. const rangeEndsAtEndOfEndContainer = rng => {
  21578. const endContainer = rng.endContainer;
  21579. return rng.endOffset === (isText$a(endContainer) ? endContainer.length : endContainer.childNodes.length);
  21580. };
  21581. const rangeEndsAtEndOfStartContainer = rng => rangeStartAndEndHaveSameParent(rng) && rangeEndsAtEndOfEndContainer(rng);
  21582. const rangeEndsAfterEndOfStartContainer = rng => !rng.endContainer.isEqualNode(rng.commonAncestorContainer);
  21583. const rangeEndsAtOrAfterEndOfStartContainer = rng => rangeEndsAtEndOfStartContainer(rng) || rangeEndsAfterEndOfStartContainer(rng);
  21584. const requiresDeleteRangeOverride = editor => {
  21585. const rng = editor.selection.getRng();
  21586. return rangeStartsAtStartOfTextContainer(rng) && rangeStartParentIsFormatElement(editor, rng) && rangeEndsAtOrAfterEndOfStartContainer(rng);
  21587. };
  21588. const deleteRange$1 = editor => {
  21589. if (requiresDeleteRangeOverride(editor)) {
  21590. const formatNodes = getFormatNodesAtStart(editor);
  21591. return Optional.some(() => {
  21592. execNativeDeleteCommand(editor);
  21593. updateCaretFormat(editor, formatNodes);
  21594. });
  21595. } else {
  21596. return Optional.none();
  21597. }
  21598. };
  21599. const backspaceDelete$2 = (editor, forward) => editor.selection.isCollapsed() ? deleteCaret$1(editor, forward) : deleteRange$1(editor);
  21600. const hasAncestorInlineCaret = elm => ancestor$1(elm, node => isCaretNode(node.dom), isBlock$2);
  21601. const hasAncestorInlineCaretAtStart = editor => hasAncestorInlineCaret(SugarElement.fromDom(editor.selection.getStart()));
  21602. const requiresRefreshCaretOverride = editor => {
  21603. const rng = editor.selection.getRng();
  21604. return rng.collapsed && (rangeStartsAtTextContainer(rng) || editor.dom.isEmpty(rng.startContainer)) && !hasAncestorInlineCaretAtStart(editor);
  21605. };
  21606. const refreshCaret = editor => {
  21607. if (requiresRefreshCaretOverride(editor)) {
  21608. createCaretFormatAtStart(editor, []);
  21609. }
  21610. return true;
  21611. };
  21612. const deleteElement = (editor, forward, element) => {
  21613. if (isNonNullable(element)) {
  21614. return Optional.some(() => {
  21615. editor._selectionOverrides.hideFakeCaret();
  21616. deleteElement$2(editor, forward, SugarElement.fromDom(element));
  21617. });
  21618. } else {
  21619. return Optional.none();
  21620. }
  21621. };
  21622. const deleteCaret = (editor, forward) => {
  21623. const isNearMedia = forward ? isBeforeMedia : isAfterMedia;
  21624. const direction = forward ? HDirection.Forwards : HDirection.Backwards;
  21625. const fromPos = getNormalizedRangeEndPoint(direction, editor.getBody(), editor.selection.getRng());
  21626. if (isNearMedia(fromPos)) {
  21627. return deleteElement(editor, forward, fromPos.getNode(!forward));
  21628. } else {
  21629. return Optional.from(normalizePosition(forward, fromPos)).filter(pos => isNearMedia(pos) && isMoveInsideSameBlock(fromPos, pos)).bind(pos => deleteElement(editor, forward, pos.getNode(!forward)));
  21630. }
  21631. };
  21632. const deleteRange = (editor, forward) => {
  21633. const selectedNode = editor.selection.getNode();
  21634. return isMedia$2(selectedNode) ? deleteElement(editor, forward, selectedNode) : Optional.none();
  21635. };
  21636. const backspaceDelete$1 = (editor, forward) => editor.selection.isCollapsed() ? deleteCaret(editor, forward) : deleteRange(editor, forward);
  21637. const isEditable = target => closest$4(target, elm => isContentEditableTrue$3(elm.dom) || isContentEditableFalse$b(elm.dom)).exists(elm => isContentEditableTrue$3(elm.dom));
  21638. const parseIndentValue = value => toInt(value !== null && value !== void 0 ? value : '').getOr(0);
  21639. const getIndentStyleName = (useMargin, element) => {
  21640. const indentStyleName = useMargin || isTable$1(element) ? 'margin' : 'padding';
  21641. const suffix = get$7(element, 'direction') === 'rtl' ? '-right' : '-left';
  21642. return indentStyleName + suffix;
  21643. };
  21644. const indentElement = (dom, command, useMargin, value, unit, element) => {
  21645. const indentStyleName = getIndentStyleName(useMargin, SugarElement.fromDom(element));
  21646. const parsedValue = parseIndentValue(dom.getStyle(element, indentStyleName));
  21647. if (command === 'outdent') {
  21648. const styleValue = Math.max(0, parsedValue - value);
  21649. dom.setStyle(element, indentStyleName, styleValue ? styleValue + unit : '');
  21650. } else {
  21651. const styleValue = parsedValue + value + unit;
  21652. dom.setStyle(element, indentStyleName, styleValue);
  21653. }
  21654. };
  21655. const validateBlocks = (editor, blocks) => forall(blocks, block => {
  21656. const indentStyleName = getIndentStyleName(shouldIndentUseMargin(editor), block);
  21657. const intentValue = getRaw(block, indentStyleName).map(parseIndentValue).getOr(0);
  21658. const contentEditable = editor.dom.getContentEditable(block.dom);
  21659. return contentEditable !== 'false' && intentValue > 0;
  21660. });
  21661. const canOutdent = editor => {
  21662. const blocks = getBlocksToIndent(editor);
  21663. return !editor.mode.isReadOnly() && (blocks.length > 1 || validateBlocks(editor, blocks));
  21664. };
  21665. const isListComponent = el => isList(el) || isListItem$1(el);
  21666. const parentIsListComponent = el => parent(el).exists(isListComponent);
  21667. const getBlocksToIndent = editor => filter$5(fromDom$1(editor.selection.getSelectedBlocks()), el => !isListComponent(el) && !parentIsListComponent(el) && isEditable(el));
  21668. const handle = (editor, command) => {
  21669. var _a, _b;
  21670. const {dom} = editor;
  21671. const indentation = getIndentation(editor);
  21672. const indentUnit = (_b = (_a = /[a-z%]+$/i.exec(indentation)) === null || _a === void 0 ? void 0 : _a[0]) !== null && _b !== void 0 ? _b : 'px';
  21673. const indentValue = parseIndentValue(indentation);
  21674. const useMargin = shouldIndentUseMargin(editor);
  21675. each$e(getBlocksToIndent(editor), block => {
  21676. indentElement(dom, command, useMargin, indentValue, indentUnit, block.dom);
  21677. });
  21678. };
  21679. const indent = editor => handle(editor, 'indent');
  21680. const outdent = editor => handle(editor, 'outdent');
  21681. const backspaceDelete = editor => {
  21682. if (editor.selection.isCollapsed() && canOutdent(editor)) {
  21683. const dom = editor.dom;
  21684. const rng = editor.selection.getRng();
  21685. const pos = CaretPosition.fromRangeStart(rng);
  21686. const block = dom.getParent(rng.startContainer, dom.isBlock);
  21687. if (block !== null && isAtStartOfBlock(SugarElement.fromDom(block), pos)) {
  21688. return Optional.some(() => outdent(editor));
  21689. }
  21690. }
  21691. return Optional.none();
  21692. };
  21693. const findAction = (editor, caret, forward) => findMap([
  21694. backspaceDelete,
  21695. backspaceDelete$5,
  21696. backspaceDelete$6,
  21697. (editor, forward) => backspaceDelete$3(editor, caret, forward),
  21698. backspaceDelete$8,
  21699. backspaceDelete$9,
  21700. backspaceDelete$4,
  21701. backspaceDelete$1,
  21702. backspaceDelete$7,
  21703. backspaceDelete$2
  21704. ], item => item(editor, forward)).filter(_ => editor.selection.isEditable());
  21705. const deleteCommand = (editor, caret) => {
  21706. const result = findAction(editor, caret, false);
  21707. result.fold(() => {
  21708. execNativeDeleteCommand(editor);
  21709. paddEmptyBody(editor);
  21710. }, call);
  21711. };
  21712. const forwardDeleteCommand = (editor, caret) => {
  21713. const result = findAction(editor, caret, true);
  21714. result.fold(() => execNativeForwardDeleteCommand(editor), call);
  21715. };
  21716. const setup$p = (editor, caret) => {
  21717. editor.addCommand('delete', () => {
  21718. deleteCommand(editor, caret);
  21719. });
  21720. editor.addCommand('forwardDelete', () => {
  21721. forwardDeleteCommand(editor, caret);
  21722. });
  21723. };
  21724. const SIGNIFICANT_MOVE = 5;
  21725. const LONGPRESS_DELAY = 400;
  21726. const getTouch = event => {
  21727. if (event.touches === undefined || event.touches.length !== 1) {
  21728. return Optional.none();
  21729. }
  21730. return Optional.some(event.touches[0]);
  21731. };
  21732. const isFarEnough = (touch, data) => {
  21733. const distX = Math.abs(touch.clientX - data.x);
  21734. const distY = Math.abs(touch.clientY - data.y);
  21735. return distX > SIGNIFICANT_MOVE || distY > SIGNIFICANT_MOVE;
  21736. };
  21737. const setup$o = editor => {
  21738. const startData = value$2();
  21739. const longpressFired = Cell(false);
  21740. const debounceLongpress = last$1(e => {
  21741. editor.dispatch('longpress', {
  21742. ...e,
  21743. type: 'longpress'
  21744. });
  21745. longpressFired.set(true);
  21746. }, LONGPRESS_DELAY);
  21747. editor.on('touchstart', e => {
  21748. getTouch(e).each(touch => {
  21749. debounceLongpress.cancel();
  21750. const data = {
  21751. x: touch.clientX,
  21752. y: touch.clientY,
  21753. target: e.target
  21754. };
  21755. debounceLongpress.throttle(e);
  21756. longpressFired.set(false);
  21757. startData.set(data);
  21758. });
  21759. }, true);
  21760. editor.on('touchmove', e => {
  21761. debounceLongpress.cancel();
  21762. getTouch(e).each(touch => {
  21763. startData.on(data => {
  21764. if (isFarEnough(touch, data)) {
  21765. startData.clear();
  21766. longpressFired.set(false);
  21767. editor.dispatch('longpresscancel');
  21768. }
  21769. });
  21770. });
  21771. }, true);
  21772. editor.on('touchend touchcancel', e => {
  21773. debounceLongpress.cancel();
  21774. if (e.type === 'touchcancel') {
  21775. return;
  21776. }
  21777. startData.get().filter(data => data.target.isEqualNode(e.target)).each(() => {
  21778. if (longpressFired.get()) {
  21779. e.preventDefault();
  21780. } else {
  21781. editor.dispatch('tap', {
  21782. ...e,
  21783. type: 'tap'
  21784. });
  21785. }
  21786. });
  21787. }, true);
  21788. };
  21789. const isBlockElement = (blockElements, node) => has$2(blockElements, node.nodeName);
  21790. const isValidTarget = (schema, node) => {
  21791. if (isText$a(node)) {
  21792. return true;
  21793. } else if (isElement$6(node)) {
  21794. return !isBlockElement(schema.getBlockElements(), node) && !isBookmarkNode$1(node) && !isTransparentBlock(schema, node);
  21795. } else {
  21796. return false;
  21797. }
  21798. };
  21799. const hasBlockParent = (blockElements, root, node) => {
  21800. return exists(parents(SugarElement.fromDom(node), SugarElement.fromDom(root)), elm => {
  21801. return isBlockElement(blockElements, elm.dom);
  21802. });
  21803. };
  21804. const shouldRemoveTextNode = (blockElements, node) => {
  21805. if (isText$a(node)) {
  21806. if (node.data.length === 0) {
  21807. return true;
  21808. } else if (/^\s+$/.test(node.data) && (!node.nextSibling || isBlockElement(blockElements, node.nextSibling))) {
  21809. return true;
  21810. }
  21811. }
  21812. return false;
  21813. };
  21814. const createRootBlock = editor => editor.dom.create(getForcedRootBlock(editor), getForcedRootBlockAttrs(editor));
  21815. const addRootBlocks = editor => {
  21816. const dom = editor.dom, selection = editor.selection;
  21817. const schema = editor.schema;
  21818. const blockElements = schema.getBlockElements();
  21819. const startNode = selection.getStart();
  21820. const rootNode = editor.getBody();
  21821. let rootBlockNode;
  21822. let tempNode;
  21823. let wrapped = false;
  21824. const forcedRootBlock = getForcedRootBlock(editor);
  21825. if (!startNode || !isElement$6(startNode)) {
  21826. return;
  21827. }
  21828. const rootNodeName = rootNode.nodeName.toLowerCase();
  21829. if (!schema.isValidChild(rootNodeName, forcedRootBlock.toLowerCase()) || hasBlockParent(blockElements, rootNode, startNode)) {
  21830. return;
  21831. }
  21832. const rng = selection.getRng();
  21833. const {startContainer, startOffset, endContainer, endOffset} = rng;
  21834. const restoreSelection = hasFocus(editor);
  21835. let node = rootNode.firstChild;
  21836. while (node) {
  21837. if (isElement$6(node)) {
  21838. updateElement(schema, node);
  21839. }
  21840. if (isValidTarget(schema, node)) {
  21841. if (shouldRemoveTextNode(blockElements, node)) {
  21842. tempNode = node;
  21843. node = node.nextSibling;
  21844. dom.remove(tempNode);
  21845. continue;
  21846. }
  21847. if (!rootBlockNode) {
  21848. rootBlockNode = createRootBlock(editor);
  21849. rootNode.insertBefore(rootBlockNode, node);
  21850. wrapped = true;
  21851. }
  21852. tempNode = node;
  21853. node = node.nextSibling;
  21854. rootBlockNode.appendChild(tempNode);
  21855. } else {
  21856. rootBlockNode = null;
  21857. node = node.nextSibling;
  21858. }
  21859. }
  21860. if (wrapped && restoreSelection) {
  21861. rng.setStart(startContainer, startOffset);
  21862. rng.setEnd(endContainer, endOffset);
  21863. selection.setRng(rng);
  21864. editor.nodeChanged();
  21865. }
  21866. };
  21867. const insertEmptyLine = (editor, root, insertBlock) => {
  21868. const block = SugarElement.fromDom(createRootBlock(editor));
  21869. const br = createPaddingBr();
  21870. append$1(block, br);
  21871. insertBlock(root, block);
  21872. const rng = document.createRange();
  21873. rng.setStartBefore(br.dom);
  21874. rng.setEndBefore(br.dom);
  21875. return rng;
  21876. };
  21877. const setup$n = editor => {
  21878. editor.on('NodeChange', curry(addRootBlocks, editor));
  21879. };
  21880. const hasClass = checkClassName => node => (' ' + node.attr('class') + ' ').indexOf(checkClassName) !== -1;
  21881. const replaceMatchWithSpan = (editor, content, cls) => {
  21882. return function (match) {
  21883. const args = arguments, index = args[args.length - 2];
  21884. const prevChar = index > 0 ? content.charAt(index - 1) : '';
  21885. if (prevChar === '"') {
  21886. return match;
  21887. }
  21888. if (prevChar === '>') {
  21889. const findStartTagIndex = content.lastIndexOf('<', index);
  21890. if (findStartTagIndex !== -1) {
  21891. const tagHtml = content.substring(findStartTagIndex, index);
  21892. if (tagHtml.indexOf('contenteditable="false"') !== -1) {
  21893. return match;
  21894. }
  21895. }
  21896. }
  21897. return '<span class="' + cls + '" data-mce-content="' + editor.dom.encode(args[0]) + '">' + editor.dom.encode(typeof args[1] === 'string' ? args[1] : args[0]) + '</span>';
  21898. };
  21899. };
  21900. const convertRegExpsToNonEditable = (editor, nonEditableRegExps, e) => {
  21901. let i = nonEditableRegExps.length, content = e.content;
  21902. if (e.format === 'raw') {
  21903. return;
  21904. }
  21905. while (i--) {
  21906. content = content.replace(nonEditableRegExps[i], replaceMatchWithSpan(editor, content, getNonEditableClass(editor)));
  21907. }
  21908. e.content = content;
  21909. };
  21910. const setup$m = editor => {
  21911. const contentEditableAttrName = 'contenteditable';
  21912. const editClass = ' ' + Tools.trim(getEditableClass(editor)) + ' ';
  21913. const nonEditClass = ' ' + Tools.trim(getNonEditableClass(editor)) + ' ';
  21914. const hasEditClass = hasClass(editClass);
  21915. const hasNonEditClass = hasClass(nonEditClass);
  21916. const nonEditableRegExps = getNonEditableRegExps(editor);
  21917. if (nonEditableRegExps.length > 0) {
  21918. editor.on('BeforeSetContent', e => {
  21919. convertRegExpsToNonEditable(editor, nonEditableRegExps, e);
  21920. });
  21921. }
  21922. editor.parser.addAttributeFilter('class', nodes => {
  21923. let i = nodes.length;
  21924. while (i--) {
  21925. const node = nodes[i];
  21926. if (hasEditClass(node)) {
  21927. node.attr(contentEditableAttrName, 'true');
  21928. } else if (hasNonEditClass(node)) {
  21929. node.attr(contentEditableAttrName, 'false');
  21930. }
  21931. }
  21932. });
  21933. editor.serializer.addAttributeFilter(contentEditableAttrName, nodes => {
  21934. let i = nodes.length;
  21935. while (i--) {
  21936. const node = nodes[i];
  21937. if (!hasEditClass(node) && !hasNonEditClass(node)) {
  21938. continue;
  21939. }
  21940. if (nonEditableRegExps.length > 0 && node.attr('data-mce-content')) {
  21941. node.name = '#text';
  21942. node.type = 3;
  21943. node.raw = true;
  21944. node.value = node.attr('data-mce-content');
  21945. } else {
  21946. node.attr(contentEditableAttrName, null);
  21947. }
  21948. }
  21949. });
  21950. };
  21951. const findBlockCaretContainer = editor => descendant(SugarElement.fromDom(editor.getBody()), '*[data-mce-caret]').map(elm => elm.dom).getOrNull();
  21952. const showBlockCaretContainer = (editor, blockCaretContainer) => {
  21953. if (blockCaretContainer.hasAttribute('data-mce-caret')) {
  21954. showCaretContainerBlock(blockCaretContainer);
  21955. editor.selection.setRng(editor.selection.getRng());
  21956. editor.selection.scrollIntoView(blockCaretContainer);
  21957. }
  21958. };
  21959. const handleBlockContainer = (editor, e) => {
  21960. const blockCaretContainer = findBlockCaretContainer(editor);
  21961. if (!blockCaretContainer) {
  21962. return;
  21963. }
  21964. if (e.type === 'compositionstart') {
  21965. e.preventDefault();
  21966. e.stopPropagation();
  21967. showBlockCaretContainer(editor, blockCaretContainer);
  21968. return;
  21969. }
  21970. if (hasContent(blockCaretContainer)) {
  21971. showBlockCaretContainer(editor, blockCaretContainer);
  21972. editor.undoManager.add();
  21973. }
  21974. };
  21975. const setup$l = editor => {
  21976. editor.on('keyup compositionstart', curry(handleBlockContainer, editor));
  21977. };
  21978. const isContentEditableFalse$3 = isContentEditableFalse$b;
  21979. const moveToCeFalseHorizontally = (direction, editor, range) => moveHorizontally(editor, direction, range, isBeforeContentEditableFalse, isAfterContentEditableFalse, isContentEditableFalse$3);
  21980. const moveToCeFalseVertically = (direction, editor, range) => {
  21981. const isBefore = caretPosition => isBeforeContentEditableFalse(caretPosition) || isBeforeTable(caretPosition);
  21982. const isAfter = caretPosition => isAfterContentEditableFalse(caretPosition) || isAfterTable(caretPosition);
  21983. return moveVertically(editor, direction, range, isBefore, isAfter, isContentEditableFalse$3);
  21984. };
  21985. const createTextBlock = editor => {
  21986. const textBlock = editor.dom.create(getForcedRootBlock(editor));
  21987. textBlock.innerHTML = '<br data-mce-bogus="1">';
  21988. return textBlock;
  21989. };
  21990. const exitPreBlock = (editor, direction, range) => {
  21991. const caretWalker = CaretWalker(editor.getBody());
  21992. const getVisualCaretPosition$1 = curry(getVisualCaretPosition, direction === 1 ? caretWalker.next : caretWalker.prev);
  21993. if (range.collapsed) {
  21994. const pre = editor.dom.getParent(range.startContainer, 'PRE');
  21995. if (!pre) {
  21996. return;
  21997. }
  21998. const caretPos = getVisualCaretPosition$1(CaretPosition.fromRangeStart(range));
  21999. if (!caretPos) {
  22000. const newBlock = SugarElement.fromDom(createTextBlock(editor));
  22001. if (direction === 1) {
  22002. after$4(SugarElement.fromDom(pre), newBlock);
  22003. } else {
  22004. before$3(SugarElement.fromDom(pre), newBlock);
  22005. }
  22006. editor.selection.select(newBlock.dom, true);
  22007. editor.selection.collapse();
  22008. }
  22009. }
  22010. };
  22011. const getHorizontalRange = (editor, forward) => {
  22012. const direction = forward ? HDirection.Forwards : HDirection.Backwards;
  22013. const range = editor.selection.getRng();
  22014. return moveToCeFalseHorizontally(direction, editor, range).orThunk(() => {
  22015. exitPreBlock(editor, direction, range);
  22016. return Optional.none();
  22017. });
  22018. };
  22019. const getVerticalRange = (editor, down) => {
  22020. const direction = down ? 1 : -1;
  22021. const range = editor.selection.getRng();
  22022. return moveToCeFalseVertically(direction, editor, range).orThunk(() => {
  22023. exitPreBlock(editor, direction, range);
  22024. return Optional.none();
  22025. });
  22026. };
  22027. const moveH$2 = (editor, forward) => getHorizontalRange(editor, forward).exists(newRange => {
  22028. moveToRange(editor, newRange);
  22029. return true;
  22030. });
  22031. const moveV$3 = (editor, down) => getVerticalRange(editor, down).exists(newRange => {
  22032. moveToRange(editor, newRange);
  22033. return true;
  22034. });
  22035. const moveToLineEndPoint$1 = (editor, forward) => {
  22036. const isCefPosition = forward ? isAfterContentEditableFalse : isBeforeContentEditableFalse;
  22037. return moveToLineEndPoint$3(editor, forward, isCefPosition);
  22038. };
  22039. const selectToEndPoint = (editor, forward) => getEdgeCefPosition(editor, !forward).map(pos => {
  22040. const rng = pos.toRange();
  22041. const curRng = editor.selection.getRng();
  22042. if (forward) {
  22043. rng.setStart(curRng.startContainer, curRng.startOffset);
  22044. } else {
  22045. rng.setEnd(curRng.endContainer, curRng.endOffset);
  22046. }
  22047. return rng;
  22048. }).exists(rng => {
  22049. moveToRange(editor, rng);
  22050. return true;
  22051. });
  22052. const isTarget = node => contains$2(['figcaption'], name(node));
  22053. const getClosestTargetBlock = (pos, root) => {
  22054. const isRoot = curry(eq, root);
  22055. return closest$4(SugarElement.fromDom(pos.container()), isBlock$2, isRoot).filter(isTarget);
  22056. };
  22057. const isAtFirstOrLastLine = (root, forward, pos) => forward ? isAtLastLine(root.dom, pos) : isAtFirstLine(root.dom, pos);
  22058. const moveCaretToNewEmptyLine = (editor, forward) => {
  22059. const root = SugarElement.fromDom(editor.getBody());
  22060. const pos = CaretPosition.fromRangeStart(editor.selection.getRng());
  22061. return getClosestTargetBlock(pos, root).exists(() => {
  22062. if (isAtFirstOrLastLine(root, forward, pos)) {
  22063. const insertFn = forward ? append$1 : prepend;
  22064. const rng = insertEmptyLine(editor, root, insertFn);
  22065. editor.selection.setRng(rng);
  22066. return true;
  22067. } else {
  22068. return false;
  22069. }
  22070. });
  22071. };
  22072. const moveV$2 = (editor, forward) => {
  22073. if (editor.selection.isCollapsed()) {
  22074. return moveCaretToNewEmptyLine(editor, forward);
  22075. } else {
  22076. return false;
  22077. }
  22078. };
  22079. const baseKeyPattern = {
  22080. shiftKey: false,
  22081. altKey: false,
  22082. ctrlKey: false,
  22083. metaKey: false,
  22084. keyCode: 0
  22085. };
  22086. const defaultPatterns = patterns => map$3(patterns, pattern => ({
  22087. ...baseKeyPattern,
  22088. ...pattern
  22089. }));
  22090. const defaultDelayedPatterns = patterns => map$3(patterns, pattern => ({
  22091. ...baseKeyPattern,
  22092. ...pattern
  22093. }));
  22094. const matchesEvent = (pattern, evt) => evt.keyCode === pattern.keyCode && evt.shiftKey === pattern.shiftKey && evt.altKey === pattern.altKey && evt.ctrlKey === pattern.ctrlKey && evt.metaKey === pattern.metaKey;
  22095. const match$1 = (patterns, evt) => bind$3(defaultPatterns(patterns), pattern => matchesEvent(pattern, evt) ? [pattern] : []);
  22096. const matchDelayed = (patterns, evt) => bind$3(defaultDelayedPatterns(patterns), pattern => matchesEvent(pattern, evt) ? [pattern] : []);
  22097. const action = (f, ...x) => () => f.apply(null, x);
  22098. const execute = (patterns, evt) => find$2(match$1(patterns, evt), pattern => pattern.action());
  22099. const executeWithDelayedAction = (patterns, evt) => findMap(matchDelayed(patterns, evt), pattern => pattern.action());
  22100. const moveH$1 = (editor, forward) => {
  22101. const direction = forward ? HDirection.Forwards : HDirection.Backwards;
  22102. const range = editor.selection.getRng();
  22103. return moveHorizontally(editor, direction, range, isBeforeMedia, isAfterMedia, isMedia$2).exists(newRange => {
  22104. moveToRange(editor, newRange);
  22105. return true;
  22106. });
  22107. };
  22108. const moveV$1 = (editor, down) => {
  22109. const direction = down ? 1 : -1;
  22110. const range = editor.selection.getRng();
  22111. return moveVertically(editor, direction, range, isBeforeMedia, isAfterMedia, isMedia$2).exists(newRange => {
  22112. moveToRange(editor, newRange);
  22113. return true;
  22114. });
  22115. };
  22116. const moveToLineEndPoint = (editor, forward) => {
  22117. const isNearMedia = forward ? isAfterMedia : isBeforeMedia;
  22118. return moveToLineEndPoint$3(editor, forward, isNearMedia);
  22119. };
  22120. const adt = Adt.generate([
  22121. { none: ['current'] },
  22122. { first: ['current'] },
  22123. {
  22124. middle: [
  22125. 'current',
  22126. 'target'
  22127. ]
  22128. },
  22129. { last: ['current'] }
  22130. ]);
  22131. const none = current => adt.none(current);
  22132. const CellLocation = {
  22133. ...adt,
  22134. none
  22135. };
  22136. const firstLayer = (scope, selector) => {
  22137. return filterFirstLayer(scope, selector, always);
  22138. };
  22139. const filterFirstLayer = (scope, selector, predicate) => {
  22140. return bind$3(children$1(scope), x => {
  22141. if (is$1(x, selector)) {
  22142. return predicate(x) ? [x] : [];
  22143. } else {
  22144. return filterFirstLayer(x, selector, predicate);
  22145. }
  22146. });
  22147. };
  22148. const lookup$1 = (tags, element, isRoot = never) => {
  22149. if (isRoot(element)) {
  22150. return Optional.none();
  22151. }
  22152. if (contains$2(tags, name(element))) {
  22153. return Optional.some(element);
  22154. }
  22155. const isRootOrUpperTable = elm => is$1(elm, 'table') || isRoot(elm);
  22156. return ancestor$3(element, tags.join(','), isRootOrUpperTable);
  22157. };
  22158. const cell = (element, isRoot) => lookup$1([
  22159. 'td',
  22160. 'th'
  22161. ], element, isRoot);
  22162. const cells = ancestor => firstLayer(ancestor, 'th,td');
  22163. const table = (element, isRoot) => closest$3(element, 'table', isRoot);
  22164. const walk = (all, current, index, direction, isEligible = always) => {
  22165. const forwards = direction === 1;
  22166. if (!forwards && index <= 0) {
  22167. return CellLocation.first(all[0]);
  22168. } else if (forwards && index >= all.length - 1) {
  22169. return CellLocation.last(all[all.length - 1]);
  22170. } else {
  22171. const newIndex = index + direction;
  22172. const elem = all[newIndex];
  22173. return isEligible(elem) ? CellLocation.middle(current, elem) : walk(all, current, newIndex, direction, isEligible);
  22174. }
  22175. };
  22176. const detect = (current, isRoot) => {
  22177. return table(current, isRoot).bind(table => {
  22178. const all = cells(table);
  22179. const index = findIndex$2(all, x => eq(current, x));
  22180. return index.map(index => ({
  22181. index,
  22182. all
  22183. }));
  22184. });
  22185. };
  22186. const next = (current, isEligible, isRoot) => {
  22187. const detection = detect(current, isRoot);
  22188. return detection.fold(() => {
  22189. return CellLocation.none(current);
  22190. }, info => {
  22191. return walk(info.all, current, info.index, 1, isEligible);
  22192. });
  22193. };
  22194. const prev = (current, isEligible, isRoot) => {
  22195. const detection = detect(current, isRoot);
  22196. return detection.fold(() => {
  22197. return CellLocation.none();
  22198. }, info => {
  22199. return walk(info.all, current, info.index, -1, isEligible);
  22200. });
  22201. };
  22202. const deflate = (rect, delta) => ({
  22203. left: rect.left - delta,
  22204. top: rect.top - delta,
  22205. right: rect.right + delta * 2,
  22206. bottom: rect.bottom + delta * 2,
  22207. width: rect.width + delta,
  22208. height: rect.height + delta
  22209. });
  22210. const getCorners = (getYAxisValue, tds) => bind$3(tds, td => {
  22211. const rect = deflate(clone$1(td.getBoundingClientRect()), -1);
  22212. return [
  22213. {
  22214. x: rect.left,
  22215. y: getYAxisValue(rect),
  22216. cell: td
  22217. },
  22218. {
  22219. x: rect.right,
  22220. y: getYAxisValue(rect),
  22221. cell: td
  22222. }
  22223. ];
  22224. });
  22225. const findClosestCorner = (corners, x, y) => foldl(corners, (acc, newCorner) => acc.fold(() => Optional.some(newCorner), oldCorner => {
  22226. const oldDist = Math.sqrt(Math.abs(oldCorner.x - x) + Math.abs(oldCorner.y - y));
  22227. const newDist = Math.sqrt(Math.abs(newCorner.x - x) + Math.abs(newCorner.y - y));
  22228. return Optional.some(newDist < oldDist ? newCorner : oldCorner);
  22229. }), Optional.none());
  22230. const getClosestCell = (getYAxisValue, isTargetCorner, table, x, y) => {
  22231. const cells = descendants(SugarElement.fromDom(table), 'td,th,caption').map(e => e.dom);
  22232. const corners = filter$5(getCorners(getYAxisValue, cells), corner => isTargetCorner(corner, y));
  22233. return findClosestCorner(corners, x, y).map(corner => corner.cell);
  22234. };
  22235. const getBottomValue = rect => rect.bottom;
  22236. const getTopValue = rect => rect.top;
  22237. const isAbove = (corner, y) => corner.y < y;
  22238. const isBelow = (corner, y) => corner.y > y;
  22239. const getClosestCellAbove = curry(getClosestCell, getBottomValue, isAbove);
  22240. const getClosestCellBelow = curry(getClosestCell, getTopValue, isBelow);
  22241. const findClosestPositionInAboveCell = (table, pos) => head(pos.getClientRects()).bind(rect => getClosestCellAbove(table, rect.left, rect.top)).bind(cell => findClosestHorizontalPosition(getLastLinePositions(cell), pos));
  22242. const findClosestPositionInBelowCell = (table, pos) => last$3(pos.getClientRects()).bind(rect => getClosestCellBelow(table, rect.left, rect.top)).bind(cell => findClosestHorizontalPosition(getFirstLinePositions(cell), pos));
  22243. const hasNextBreak = (getPositionsUntil, scope, lineInfo) => lineInfo.breakAt.exists(breakPos => getPositionsUntil(scope, breakPos).breakAt.isSome());
  22244. const startsWithWrapBreak = lineInfo => lineInfo.breakType === BreakType.Wrap && lineInfo.positions.length === 0;
  22245. const startsWithBrBreak = lineInfo => lineInfo.breakType === BreakType.Br && lineInfo.positions.length === 1;
  22246. const isAtTableCellLine = (getPositionsUntil, scope, pos) => {
  22247. const lineInfo = getPositionsUntil(scope, pos);
  22248. if (startsWithWrapBreak(lineInfo) || !isBr$6(pos.getNode()) && startsWithBrBreak(lineInfo)) {
  22249. return !hasNextBreak(getPositionsUntil, scope, lineInfo);
  22250. } else {
  22251. return lineInfo.breakAt.isNone();
  22252. }
  22253. };
  22254. const isAtFirstTableCellLine = curry(isAtTableCellLine, getPositionsUntilPreviousLine);
  22255. const isAtLastTableCellLine = curry(isAtTableCellLine, getPositionsUntilNextLine);
  22256. const isCaretAtStartOrEndOfTable = (forward, rng, table) => {
  22257. const caretPos = CaretPosition.fromRangeStart(rng);
  22258. return positionIn(!forward, table).exists(pos => pos.isEqual(caretPos));
  22259. };
  22260. const navigateHorizontally = (editor, forward, table, _td) => {
  22261. const rng = editor.selection.getRng();
  22262. const direction = forward ? 1 : -1;
  22263. if (isFakeCaretTableBrowser() && isCaretAtStartOrEndOfTable(forward, rng, table)) {
  22264. showCaret(direction, editor, table, !forward, false).each(newRng => {
  22265. moveToRange(editor, newRng);
  22266. });
  22267. return true;
  22268. }
  22269. return false;
  22270. };
  22271. 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));
  22272. 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));
  22273. const getTable = (previous, pos) => {
  22274. const node = pos.getNode(previous);
  22275. return isTable$2(node) ? Optional.some(node) : Optional.none();
  22276. };
  22277. const renderBlock = (down, editor, table) => {
  22278. editor.undoManager.transact(() => {
  22279. const insertFn = down ? after$4 : before$3;
  22280. const rng = insertEmptyLine(editor, SugarElement.fromDom(table), insertFn);
  22281. moveToRange(editor, rng);
  22282. });
  22283. };
  22284. const moveCaret = (editor, down, pos) => {
  22285. const table = down ? getTable(true, pos) : getTable(false, pos);
  22286. const last = down === false;
  22287. 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)));
  22288. };
  22289. const navigateVertically = (editor, down, table, td) => {
  22290. const rng = editor.selection.getRng();
  22291. const pos = CaretPosition.fromRangeStart(rng);
  22292. const root = editor.getBody();
  22293. if (!down && isAtFirstTableCellLine(td, pos)) {
  22294. const newPos = getClosestAbovePosition(root, table, pos);
  22295. moveCaret(editor, down, newPos);
  22296. return true;
  22297. } else if (down && isAtLastTableCellLine(td, pos)) {
  22298. const newPos = getClosestBelowPosition(root, table, pos);
  22299. moveCaret(editor, down, newPos);
  22300. return true;
  22301. } else {
  22302. return false;
  22303. }
  22304. };
  22305. 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);
  22306. const moveH = (editor, forward) => move$1(editor, forward, navigateHorizontally);
  22307. const moveV = (editor, forward) => move$1(editor, forward, navigateVertically);
  22308. const getCellFirstCursorPosition = cell => {
  22309. const selection = SimSelection.exact(cell, 0, cell, 0);
  22310. return toNative(selection);
  22311. };
  22312. const tabGo = (editor, isRoot, cell) => {
  22313. return cell.fold(Optional.none, Optional.none, (_current, next) => {
  22314. return first(next).map(cell => {
  22315. return getCellFirstCursorPosition(cell);
  22316. });
  22317. }, current => {
  22318. editor.execCommand('mceTableInsertRowAfter');
  22319. return tabForward(editor, isRoot, current);
  22320. });
  22321. };
  22322. const tabForward = (editor, isRoot, cell) => tabGo(editor, isRoot, next(cell, isEditable$3));
  22323. const tabBackward = (editor, isRoot, cell) => tabGo(editor, isRoot, prev(cell, isEditable$3));
  22324. const handleTab = (editor, forward) => {
  22325. const rootElements = [
  22326. 'table',
  22327. 'li',
  22328. 'dl'
  22329. ];
  22330. const body = SugarElement.fromDom(editor.getBody());
  22331. const isRoot = element => {
  22332. const name$1 = name(element);
  22333. return eq(element, body) || contains$2(rootElements, name$1);
  22334. };
  22335. const rng = editor.selection.getRng();
  22336. const container = SugarElement.fromDom(!forward ? rng.startContainer : rng.endContainer);
  22337. return cell(container, isRoot).map(cell => {
  22338. table(cell, isRoot).each(table => {
  22339. editor.model.table.clearSelectedCells(table.dom);
  22340. });
  22341. editor.selection.collapse(!forward);
  22342. const navigation = !forward ? tabBackward : tabForward;
  22343. const rng = navigation(editor, isRoot, cell);
  22344. rng.each(range => {
  22345. editor.selection.setRng(range);
  22346. });
  22347. return true;
  22348. }).getOr(false);
  22349. };
  22350. const executeKeydownOverride$4 = (editor, caret, evt) => {
  22351. const isMac = Env.os.isMacOS() || Env.os.isiOS();
  22352. execute([
  22353. {
  22354. keyCode: VK.RIGHT,
  22355. action: action(moveH$2, editor, true)
  22356. },
  22357. {
  22358. keyCode: VK.LEFT,
  22359. action: action(moveH$2, editor, false)
  22360. },
  22361. {
  22362. keyCode: VK.UP,
  22363. action: action(moveV$3, editor, false)
  22364. },
  22365. {
  22366. keyCode: VK.DOWN,
  22367. action: action(moveV$3, editor, true)
  22368. },
  22369. ...isMac ? [
  22370. {
  22371. keyCode: VK.UP,
  22372. action: action(selectToEndPoint, editor, false),
  22373. metaKey: true,
  22374. shiftKey: true
  22375. },
  22376. {
  22377. keyCode: VK.DOWN,
  22378. action: action(selectToEndPoint, editor, true),
  22379. metaKey: true,
  22380. shiftKey: true
  22381. }
  22382. ] : [],
  22383. {
  22384. keyCode: VK.RIGHT,
  22385. action: action(moveH, editor, true)
  22386. },
  22387. {
  22388. keyCode: VK.LEFT,
  22389. action: action(moveH, editor, false)
  22390. },
  22391. {
  22392. keyCode: VK.UP,
  22393. action: action(moveV, editor, false)
  22394. },
  22395. {
  22396. keyCode: VK.DOWN,
  22397. action: action(moveV, editor, true)
  22398. },
  22399. {
  22400. keyCode: VK.RIGHT,
  22401. action: action(moveH$1, editor, true)
  22402. },
  22403. {
  22404. keyCode: VK.LEFT,
  22405. action: action(moveH$1, editor, false)
  22406. },
  22407. {
  22408. keyCode: VK.UP,
  22409. action: action(moveV$1, editor, false)
  22410. },
  22411. {
  22412. keyCode: VK.DOWN,
  22413. action: action(moveV$1, editor, true)
  22414. },
  22415. {
  22416. keyCode: VK.RIGHT,
  22417. action: action(move$2, editor, caret, true)
  22418. },
  22419. {
  22420. keyCode: VK.LEFT,
  22421. action: action(move$2, editor, caret, false)
  22422. },
  22423. {
  22424. keyCode: VK.RIGHT,
  22425. ctrlKey: !isMac,
  22426. altKey: isMac,
  22427. action: action(moveNextWord, editor, caret)
  22428. },
  22429. {
  22430. keyCode: VK.LEFT,
  22431. ctrlKey: !isMac,
  22432. altKey: isMac,
  22433. action: action(movePrevWord, editor, caret)
  22434. },
  22435. {
  22436. keyCode: VK.UP,
  22437. action: action(moveV$2, editor, false)
  22438. },
  22439. {
  22440. keyCode: VK.DOWN,
  22441. action: action(moveV$2, editor, true)
  22442. }
  22443. ], evt).each(_ => {
  22444. evt.preventDefault();
  22445. });
  22446. };
  22447. const setup$k = (editor, caret) => {
  22448. editor.on('keydown', evt => {
  22449. if (!evt.isDefaultPrevented()) {
  22450. executeKeydownOverride$4(editor, caret, evt);
  22451. }
  22452. });
  22453. };
  22454. const point = (container, offset) => ({
  22455. container,
  22456. offset
  22457. });
  22458. const DOM$7 = DOMUtils.DOM;
  22459. const alwaysNext = startNode => node => startNode === node ? -1 : 0;
  22460. const isBoundary = dom => node => dom.isBlock(node) || contains$2([
  22461. 'BR',
  22462. 'IMG',
  22463. 'HR',
  22464. 'INPUT'
  22465. ], node.nodeName) || dom.getContentEditable(node) === 'false';
  22466. const textBefore = (node, offset, rootNode) => {
  22467. if (isText$a(node) && offset >= 0) {
  22468. return Optional.some(point(node, offset));
  22469. } else {
  22470. const textSeeker = TextSeeker(DOM$7);
  22471. return Optional.from(textSeeker.backwards(node, offset, alwaysNext(node), rootNode)).map(prev => point(prev.container, prev.container.data.length));
  22472. }
  22473. };
  22474. const textAfter = (node, offset, rootNode) => {
  22475. if (isText$a(node) && offset >= node.length) {
  22476. return Optional.some(point(node, offset));
  22477. } else {
  22478. const textSeeker = TextSeeker(DOM$7);
  22479. return Optional.from(textSeeker.forwards(node, offset, alwaysNext(node), rootNode)).map(prev => point(prev.container, 0));
  22480. }
  22481. };
  22482. const scanLeft = (node, offset, rootNode) => {
  22483. if (!isText$a(node)) {
  22484. return Optional.none();
  22485. }
  22486. const text = node.data;
  22487. if (offset >= 0 && offset <= text.length) {
  22488. return Optional.some(point(node, offset));
  22489. } else {
  22490. const textSeeker = TextSeeker(DOM$7);
  22491. return Optional.from(textSeeker.backwards(node, offset, alwaysNext(node), rootNode)).bind(prev => {
  22492. const prevText = prev.container.data;
  22493. return scanLeft(prev.container, offset + prevText.length, rootNode);
  22494. });
  22495. }
  22496. };
  22497. const scanRight = (node, offset, rootNode) => {
  22498. if (!isText$a(node)) {
  22499. return Optional.none();
  22500. }
  22501. const text = node.data;
  22502. if (offset <= text.length) {
  22503. return Optional.some(point(node, offset));
  22504. } else {
  22505. const textSeeker = TextSeeker(DOM$7);
  22506. return Optional.from(textSeeker.forwards(node, offset, alwaysNext(node), rootNode)).bind(next => scanRight(next.container, offset - text.length, rootNode));
  22507. }
  22508. };
  22509. const repeatLeft = (dom, node, offset, process, rootNode) => {
  22510. const search = TextSeeker(dom, isBoundary(dom));
  22511. return Optional.from(search.backwards(node, offset, process, rootNode));
  22512. };
  22513. const isValidTextRange = rng => rng.collapsed && isText$a(rng.startContainer);
  22514. const getText = rng => trim$1(rng.toString().replace(/\u00A0/g, ' '));
  22515. const isWhitespace = chr => chr !== '' && ' \xA0\f\n\r\t\x0B'.indexOf(chr) !== -1;
  22516. const stripTrigger = (text, trigger) => text.substring(trigger.length);
  22517. const findTrigger = (text, index, trigger) => {
  22518. let i;
  22519. const firstChar = trigger.charAt(0);
  22520. for (i = index - 1; i >= 0; i--) {
  22521. const char = text.charAt(i);
  22522. if (isWhitespace(char)) {
  22523. return Optional.none();
  22524. }
  22525. if (firstChar === char && contains$1(text, trigger, i, index)) {
  22526. break;
  22527. }
  22528. }
  22529. return Optional.some(i);
  22530. };
  22531. const findStart = (dom, initRange, trigger, minChars = 0) => {
  22532. if (!isValidTextRange(initRange)) {
  22533. return Optional.none();
  22534. }
  22535. const buffer = {
  22536. text: '',
  22537. offset: 0
  22538. };
  22539. const findTriggerIndex = (element, offset, text) => {
  22540. buffer.text = text + buffer.text;
  22541. buffer.offset += offset;
  22542. return findTrigger(buffer.text, buffer.offset, trigger).getOr(offset);
  22543. };
  22544. const root = dom.getParent(initRange.startContainer, dom.isBlock) || dom.getRoot();
  22545. return repeatLeft(dom, initRange.startContainer, initRange.startOffset, findTriggerIndex, root).bind(spot => {
  22546. const range = initRange.cloneRange();
  22547. range.setStart(spot.container, spot.offset);
  22548. range.setEnd(initRange.endContainer, initRange.endOffset);
  22549. if (range.collapsed) {
  22550. return Optional.none();
  22551. }
  22552. const text = getText(range);
  22553. const triggerIndex = text.lastIndexOf(trigger);
  22554. if (triggerIndex !== 0 || stripTrigger(text, trigger).length < minChars) {
  22555. return Optional.none();
  22556. } else {
  22557. return Optional.some({
  22558. text: stripTrigger(text, trigger),
  22559. range,
  22560. trigger
  22561. });
  22562. }
  22563. });
  22564. };
  22565. const getContext = (dom, initRange, trigger, minChars = 0) => detect$1(SugarElement.fromDom(initRange.startContainer)).fold(() => findStart(dom, initRange, trigger, minChars), elm => {
  22566. const range = dom.createRng();
  22567. range.selectNode(elm.dom);
  22568. const text = getText(range);
  22569. return Optional.some({
  22570. range,
  22571. text: stripTrigger(text, trigger),
  22572. trigger
  22573. });
  22574. });
  22575. const isText$1 = node => node.nodeType === TEXT;
  22576. const isElement = node => node.nodeType === ELEMENT;
  22577. const toLast = node => {
  22578. if (isText$1(node)) {
  22579. return point(node, node.data.length);
  22580. } else {
  22581. const children = node.childNodes;
  22582. return children.length > 0 ? toLast(children[children.length - 1]) : point(node, children.length);
  22583. }
  22584. };
  22585. const toLeaf = (node, offset) => {
  22586. const children = node.childNodes;
  22587. if (children.length > 0 && offset < children.length) {
  22588. return toLeaf(children[offset], 0);
  22589. } else if (children.length > 0 && isElement(node) && children.length === offset) {
  22590. return toLast(children[children.length - 1]);
  22591. } else {
  22592. return point(node, offset);
  22593. }
  22594. };
  22595. const isPreviousCharContent = (dom, leaf) => {
  22596. var _a;
  22597. const root = (_a = dom.getParent(leaf.container, dom.isBlock)) !== null && _a !== void 0 ? _a : dom.getRoot();
  22598. return repeatLeft(dom, leaf.container, leaf.offset, (_element, offset) => offset === 0 ? -1 : offset, root).filter(spot => {
  22599. const char = spot.container.data.charAt(spot.offset - 1);
  22600. return !isWhitespace(char);
  22601. }).isSome();
  22602. };
  22603. const isStartOfWord = dom => rng => {
  22604. const leaf = toLeaf(rng.startContainer, rng.startOffset);
  22605. return !isPreviousCharContent(dom, leaf);
  22606. };
  22607. const getTriggerContext = (dom, initRange, database) => findMap(database.triggers, trigger => getContext(dom, initRange, trigger));
  22608. const lookup = (editor, getDatabase) => {
  22609. const database = getDatabase();
  22610. const rng = editor.selection.getRng();
  22611. return getTriggerContext(editor.dom, rng, database).bind(context => lookupWithContext(editor, getDatabase, context));
  22612. };
  22613. const lookupWithContext = (editor, getDatabase, context, fetchOptions = {}) => {
  22614. var _a;
  22615. const database = getDatabase();
  22616. const rng = editor.selection.getRng();
  22617. const startText = (_a = rng.startContainer.nodeValue) !== null && _a !== void 0 ? _a : '';
  22618. const autocompleters = filter$5(database.lookupByTrigger(context.trigger), autocompleter => context.text.length >= autocompleter.minChars && autocompleter.matches.getOrThunk(() => isStartOfWord(editor.dom))(context.range, startText, context.text));
  22619. if (autocompleters.length === 0) {
  22620. return Optional.none();
  22621. }
  22622. const lookupData = Promise.all(map$3(autocompleters, ac => {
  22623. const fetchResult = ac.fetch(context.text, ac.maxResults, fetchOptions);
  22624. return fetchResult.then(results => ({
  22625. matchText: context.text,
  22626. items: results,
  22627. columns: ac.columns,
  22628. onAction: ac.onAction,
  22629. highlightOn: ac.highlightOn
  22630. }));
  22631. }));
  22632. return Optional.some({
  22633. lookupData,
  22634. context
  22635. });
  22636. };
  22637. var SimpleResultType;
  22638. (function (SimpleResultType) {
  22639. SimpleResultType[SimpleResultType['Error'] = 0] = 'Error';
  22640. SimpleResultType[SimpleResultType['Value'] = 1] = 'Value';
  22641. }(SimpleResultType || (SimpleResultType = {})));
  22642. const fold$1 = (res, onError, onValue) => res.stype === SimpleResultType.Error ? onError(res.serror) : onValue(res.svalue);
  22643. const partition = results => {
  22644. const values = [];
  22645. const errors = [];
  22646. each$e(results, obj => {
  22647. fold$1(obj, err => errors.push(err), val => values.push(val));
  22648. });
  22649. return {
  22650. values,
  22651. errors
  22652. };
  22653. };
  22654. const mapError = (res, f) => {
  22655. if (res.stype === SimpleResultType.Error) {
  22656. return {
  22657. stype: SimpleResultType.Error,
  22658. serror: f(res.serror)
  22659. };
  22660. } else {
  22661. return res;
  22662. }
  22663. };
  22664. const map = (res, f) => {
  22665. if (res.stype === SimpleResultType.Value) {
  22666. return {
  22667. stype: SimpleResultType.Value,
  22668. svalue: f(res.svalue)
  22669. };
  22670. } else {
  22671. return res;
  22672. }
  22673. };
  22674. const bind$1 = (res, f) => {
  22675. if (res.stype === SimpleResultType.Value) {
  22676. return f(res.svalue);
  22677. } else {
  22678. return res;
  22679. }
  22680. };
  22681. const bindError = (res, f) => {
  22682. if (res.stype === SimpleResultType.Error) {
  22683. return f(res.serror);
  22684. } else {
  22685. return res;
  22686. }
  22687. };
  22688. const svalue = v => ({
  22689. stype: SimpleResultType.Value,
  22690. svalue: v
  22691. });
  22692. const serror = e => ({
  22693. stype: SimpleResultType.Error,
  22694. serror: e
  22695. });
  22696. const toResult = res => fold$1(res, Result.error, Result.value);
  22697. const fromResult = res => res.fold(serror, svalue);
  22698. const SimpleResult = {
  22699. fromResult,
  22700. toResult,
  22701. svalue,
  22702. partition,
  22703. serror,
  22704. bind: bind$1,
  22705. bindError,
  22706. map,
  22707. mapError,
  22708. fold: fold$1
  22709. };
  22710. const formatObj = input => {
  22711. return isObject(input) && keys(input).length > 100 ? ' removed due to size' : JSON.stringify(input, null, 2);
  22712. };
  22713. const formatErrors = errors => {
  22714. const es = errors.length > 10 ? errors.slice(0, 10).concat([{
  22715. path: [],
  22716. getErrorInfo: constant('... (only showing first ten failures)')
  22717. }]) : errors;
  22718. return map$3(es, e => {
  22719. return 'Failed path: (' + e.path.join(' > ') + ')\n' + e.getErrorInfo();
  22720. });
  22721. };
  22722. const nu = (path, getErrorInfo) => {
  22723. return SimpleResult.serror([{
  22724. path,
  22725. getErrorInfo
  22726. }]);
  22727. };
  22728. const missingRequired = (path, key, obj) => nu(path, () => 'Could not find valid *required* value for "' + key + '" in ' + formatObj(obj));
  22729. const missingKey = (path, key) => nu(path, () => 'Choice schema did not contain choice key: "' + key + '"');
  22730. const missingBranch = (path, branches, branch) => nu(path, () => 'The chosen schema: "' + branch + '" did not exist in branches: ' + formatObj(branches));
  22731. const custom = (path, err) => nu(path, constant(err));
  22732. const chooseFrom = (path, input, branches, ch) => {
  22733. const fields = get$a(branches, ch);
  22734. return fields.fold(() => missingBranch(path, branches, ch), vp => vp.extract(path.concat(['branch: ' + ch]), input));
  22735. };
  22736. const choose$1 = (key, branches) => {
  22737. const extract = (path, input) => {
  22738. const choice = get$a(input, key);
  22739. return choice.fold(() => missingKey(path, key), chosen => chooseFrom(path, input, branches, chosen));
  22740. };
  22741. const toString = () => 'chooseOn(' + key + '). Possible values: ' + keys(branches);
  22742. return {
  22743. extract,
  22744. toString
  22745. };
  22746. };
  22747. const shallow = (old, nu) => {
  22748. return nu;
  22749. };
  22750. const deep = (old, nu) => {
  22751. const bothObjects = isPlainObject(old) && isPlainObject(nu);
  22752. return bothObjects ? deepMerge(old, nu) : nu;
  22753. };
  22754. const baseMerge = merger => {
  22755. return (...objects) => {
  22756. if (objects.length === 0) {
  22757. throw new Error(`Can't merge zero objects`);
  22758. }
  22759. const ret = {};
  22760. for (let j = 0; j < objects.length; j++) {
  22761. const curObject = objects[j];
  22762. for (const key in curObject) {
  22763. if (has$2(curObject, key)) {
  22764. ret[key] = merger(ret[key], curObject[key]);
  22765. }
  22766. }
  22767. }
  22768. return ret;
  22769. };
  22770. };
  22771. const deepMerge = baseMerge(deep);
  22772. const merge = baseMerge(shallow);
  22773. const required = () => ({
  22774. tag: 'required',
  22775. process: {}
  22776. });
  22777. const defaultedThunk = fallbackThunk => ({
  22778. tag: 'defaultedThunk',
  22779. process: fallbackThunk
  22780. });
  22781. const defaulted$1 = fallback => defaultedThunk(constant(fallback));
  22782. const asOption = () => ({
  22783. tag: 'option',
  22784. process: {}
  22785. });
  22786. const mergeValues = (values, base) => values.length > 0 ? SimpleResult.svalue(deepMerge(base, merge.apply(undefined, values))) : SimpleResult.svalue(base);
  22787. const mergeErrors = errors => compose(SimpleResult.serror, flatten)(errors);
  22788. const consolidateObj = (objects, base) => {
  22789. const partition = SimpleResult.partition(objects);
  22790. return partition.errors.length > 0 ? mergeErrors(partition.errors) : mergeValues(partition.values, base);
  22791. };
  22792. const consolidateArr = objects => {
  22793. const partitions = SimpleResult.partition(objects);
  22794. return partitions.errors.length > 0 ? mergeErrors(partitions.errors) : SimpleResult.svalue(partitions.values);
  22795. };
  22796. const ResultCombine = {
  22797. consolidateObj,
  22798. consolidateArr
  22799. };
  22800. const field$1 = (key, newKey, presence, prop) => ({
  22801. tag: 'field',
  22802. key,
  22803. newKey,
  22804. presence,
  22805. prop
  22806. });
  22807. const customField$1 = (newKey, instantiator) => ({
  22808. tag: 'custom',
  22809. newKey,
  22810. instantiator
  22811. });
  22812. const fold = (value, ifField, ifCustom) => {
  22813. switch (value.tag) {
  22814. case 'field':
  22815. return ifField(value.key, value.newKey, value.presence, value.prop);
  22816. case 'custom':
  22817. return ifCustom(value.newKey, value.instantiator);
  22818. }
  22819. };
  22820. const value = validator => {
  22821. const extract = (path, val) => {
  22822. return SimpleResult.bindError(validator(val), err => custom(path, err));
  22823. };
  22824. const toString = constant('val');
  22825. return {
  22826. extract,
  22827. toString
  22828. };
  22829. };
  22830. const anyValue$1 = value(SimpleResult.svalue);
  22831. const requiredAccess = (path, obj, key, bundle) => get$a(obj, key).fold(() => missingRequired(path, key, obj), bundle);
  22832. const fallbackAccess = (obj, key, fallback, bundle) => {
  22833. const v = get$a(obj, key).getOrThunk(() => fallback(obj));
  22834. return bundle(v);
  22835. };
  22836. const optionAccess = (obj, key, bundle) => bundle(get$a(obj, key));
  22837. const optionDefaultedAccess = (obj, key, fallback, bundle) => {
  22838. const opt = get$a(obj, key).map(val => val === true ? fallback(obj) : val);
  22839. return bundle(opt);
  22840. };
  22841. const extractField = (field, path, obj, key, prop) => {
  22842. const bundle = av => prop.extract(path.concat([key]), av);
  22843. const bundleAsOption = optValue => optValue.fold(() => SimpleResult.svalue(Optional.none()), ov => {
  22844. const result = prop.extract(path.concat([key]), ov);
  22845. return SimpleResult.map(result, Optional.some);
  22846. });
  22847. switch (field.tag) {
  22848. case 'required':
  22849. return requiredAccess(path, obj, key, bundle);
  22850. case 'defaultedThunk':
  22851. return fallbackAccess(obj, key, field.process, bundle);
  22852. case 'option':
  22853. return optionAccess(obj, key, bundleAsOption);
  22854. case 'defaultedOptionThunk':
  22855. return optionDefaultedAccess(obj, key, field.process, bundleAsOption);
  22856. case 'mergeWithThunk': {
  22857. return fallbackAccess(obj, key, constant({}), v => {
  22858. const result = deepMerge(field.process(obj), v);
  22859. return bundle(result);
  22860. });
  22861. }
  22862. }
  22863. };
  22864. const extractFields = (path, obj, fields) => {
  22865. const success = {};
  22866. const errors = [];
  22867. for (const field of fields) {
  22868. fold(field, (key, newKey, presence, prop) => {
  22869. const result = extractField(presence, path, obj, key, prop);
  22870. SimpleResult.fold(result, err => {
  22871. errors.push(...err);
  22872. }, res => {
  22873. success[newKey] = res;
  22874. });
  22875. }, (newKey, instantiator) => {
  22876. success[newKey] = instantiator(obj);
  22877. });
  22878. }
  22879. return errors.length > 0 ? SimpleResult.serror(errors) : SimpleResult.svalue(success);
  22880. };
  22881. const objOf = values => {
  22882. const extract = (path, o) => extractFields(path, o, values);
  22883. const toString = () => {
  22884. const fieldStrings = map$3(values, value => fold(value, (key, _okey, _presence, prop) => key + ' -> ' + prop.toString(), (newKey, _instantiator) => 'state(' + newKey + ')'));
  22885. return 'obj{\n' + fieldStrings.join('\n') + '}';
  22886. };
  22887. return {
  22888. extract,
  22889. toString
  22890. };
  22891. };
  22892. const arrOf = prop => {
  22893. const extract = (path, array) => {
  22894. const results = map$3(array, (a, i) => prop.extract(path.concat(['[' + i + ']']), a));
  22895. return ResultCombine.consolidateArr(results);
  22896. };
  22897. const toString = () => 'array(' + prop.toString() + ')';
  22898. return {
  22899. extract,
  22900. toString
  22901. };
  22902. };
  22903. const valueOf = validator => value(v => validator(v).fold(SimpleResult.serror, SimpleResult.svalue));
  22904. const extractValue = (label, prop, obj) => {
  22905. const res = prop.extract([label], obj);
  22906. return SimpleResult.mapError(res, errs => ({
  22907. input: obj,
  22908. errors: errs
  22909. }));
  22910. };
  22911. const asRaw = (label, prop, obj) => SimpleResult.toResult(extractValue(label, prop, obj));
  22912. const formatError = errInfo => {
  22913. return 'Errors: \n' + formatErrors(errInfo.errors).join('\n') + '\n\nInput object: ' + formatObj(errInfo.input);
  22914. };
  22915. const choose = (key, branches) => choose$1(key, map$2(branches, objOf));
  22916. const anyValue = constant(anyValue$1);
  22917. const typedValue = (validator, expectedType) => value(a => {
  22918. const actualType = typeof a;
  22919. return validator(a) ? SimpleResult.svalue(a) : SimpleResult.serror(`Expected type: ${ expectedType } but got: ${ actualType }`);
  22920. });
  22921. const number = typedValue(isNumber, 'number');
  22922. const string = typedValue(isString, 'string');
  22923. const boolean = typedValue(isBoolean, 'boolean');
  22924. const functionProcessor = typedValue(isFunction, 'function');
  22925. const field = field$1;
  22926. const customField = customField$1;
  22927. const validateEnum = values => valueOf(value => contains$2(values, value) ? Result.value(value) : Result.error(`Unsupported value: "${ value }", choose one of "${ values.join(', ') }".`));
  22928. const requiredOf = (key, schema) => field(key, key, required(), schema);
  22929. const requiredString = key => requiredOf(key, string);
  22930. const requiredFunction = key => requiredOf(key, functionProcessor);
  22931. const requiredArrayOf = (key, schema) => field(key, key, required(), arrOf(schema));
  22932. const optionOf = (key, schema) => field(key, key, asOption(), schema);
  22933. const optionString = key => optionOf(key, string);
  22934. const optionFunction = key => optionOf(key, functionProcessor);
  22935. const defaulted = (key, fallback) => field(key, key, defaulted$1(fallback), anyValue());
  22936. const defaultedOf = (key, fallback, schema) => field(key, key, defaulted$1(fallback), schema);
  22937. const defaultedNumber = (key, fallback) => defaultedOf(key, fallback, number);
  22938. const defaultedString = (key, fallback) => defaultedOf(key, fallback, string);
  22939. const defaultedStringEnum = (key, fallback, values) => defaultedOf(key, fallback, validateEnum(values));
  22940. const defaultedBoolean = (key, fallback) => defaultedOf(key, fallback, boolean);
  22941. const defaultedFunction = (key, fallback) => defaultedOf(key, fallback, functionProcessor);
  22942. const defaultedArrayOf = (key, fallback, schema) => defaultedOf(key, fallback, arrOf(schema));
  22943. const type = requiredString('type');
  22944. const fetch$1 = requiredFunction('fetch');
  22945. const onAction = requiredFunction('onAction');
  22946. const onSetup = defaultedFunction('onSetup', () => noop);
  22947. const optionalText = optionString('text');
  22948. const optionalIcon = optionString('icon');
  22949. const optionalTooltip = optionString('tooltip');
  22950. const optionalLabel = optionString('label');
  22951. const active = defaultedBoolean('active', false);
  22952. const enabled = defaultedBoolean('enabled', true);
  22953. const primary = defaultedBoolean('primary', false);
  22954. const defaultedColumns = num => defaulted('columns', num);
  22955. const defaultedType = type => defaultedString('type', type);
  22956. const autocompleterSchema = objOf([
  22957. type,
  22958. requiredString('trigger'),
  22959. defaultedNumber('minChars', 1),
  22960. defaultedColumns(1),
  22961. defaultedNumber('maxResults', 10),
  22962. optionFunction('matches'),
  22963. fetch$1,
  22964. onAction,
  22965. defaultedArrayOf('highlightOn', [], string)
  22966. ]);
  22967. const createAutocompleter = spec => asRaw('Autocompleter', autocompleterSchema, {
  22968. trigger: spec.ch,
  22969. ...spec
  22970. });
  22971. const baseToolbarButtonFields = [
  22972. enabled,
  22973. optionalTooltip,
  22974. optionalIcon,
  22975. optionalText,
  22976. onSetup
  22977. ];
  22978. const baseToolbarToggleButtonFields = [active].concat(baseToolbarButtonFields);
  22979. const contextBarFields = [
  22980. defaultedFunction('predicate', never),
  22981. defaultedStringEnum('scope', 'node', [
  22982. 'node',
  22983. 'editor'
  22984. ]),
  22985. defaultedStringEnum('position', 'selection', [
  22986. 'node',
  22987. 'selection',
  22988. 'line'
  22989. ])
  22990. ];
  22991. const contextButtonFields = baseToolbarButtonFields.concat([
  22992. defaultedType('contextformbutton'),
  22993. primary,
  22994. onAction,
  22995. customField('original', identity)
  22996. ]);
  22997. const contextToggleButtonFields = baseToolbarToggleButtonFields.concat([
  22998. defaultedType('contextformbutton'),
  22999. primary,
  23000. onAction,
  23001. customField('original', identity)
  23002. ]);
  23003. const launchButtonFields = baseToolbarButtonFields.concat([defaultedType('contextformbutton')]);
  23004. const launchToggleButtonFields = baseToolbarToggleButtonFields.concat([defaultedType('contextformtogglebutton')]);
  23005. const toggleOrNormal = choose('type', {
  23006. contextformbutton: contextButtonFields,
  23007. contextformtogglebutton: contextToggleButtonFields
  23008. });
  23009. objOf([
  23010. defaultedType('contextform'),
  23011. defaultedFunction('initValue', constant('')),
  23012. optionalLabel,
  23013. requiredArrayOf('commands', toggleOrNormal),
  23014. optionOf('launch', choose('type', {
  23015. contextformbutton: launchButtonFields,
  23016. contextformtogglebutton: launchToggleButtonFields
  23017. }))
  23018. ].concat(contextBarFields));
  23019. const register$2 = editor => {
  23020. const popups = editor.ui.registry.getAll().popups;
  23021. const dataset = map$2(popups, popup => createAutocompleter(popup).fold(err => {
  23022. throw new Error(formatError(err));
  23023. }, identity));
  23024. const triggers = stringArray(mapToArray(dataset, v => v.trigger));
  23025. const datasetValues = values(dataset);
  23026. const lookupByTrigger = trigger => filter$5(datasetValues, dv => dv.trigger === trigger);
  23027. return {
  23028. dataset,
  23029. triggers,
  23030. lookupByTrigger
  23031. };
  23032. };
  23033. const setupEditorInput = (editor, api) => {
  23034. const update = last$1(api.load, 50);
  23035. editor.on('keypress compositionend', e => {
  23036. if (e.which === 27) {
  23037. return;
  23038. }
  23039. update.throttle();
  23040. });
  23041. editor.on('keydown', e => {
  23042. const keyCode = e.which;
  23043. if (keyCode === 8) {
  23044. update.throttle();
  23045. } else if (keyCode === 27) {
  23046. api.cancelIfNecessary();
  23047. }
  23048. });
  23049. editor.on('remove', update.cancel);
  23050. };
  23051. const setup$j = editor => {
  23052. const activeAutocompleter = value$2();
  23053. const uiActive = Cell(false);
  23054. const isActive = activeAutocompleter.isSet;
  23055. const cancelIfNecessary = () => {
  23056. if (isActive()) {
  23057. removeAutocompleterDecoration(editor);
  23058. fireAutocompleterEnd(editor);
  23059. uiActive.set(false);
  23060. activeAutocompleter.clear();
  23061. }
  23062. };
  23063. const commenceIfNecessary = context => {
  23064. if (!isActive()) {
  23065. addAutocompleterDecoration(editor, context.range);
  23066. activeAutocompleter.set({
  23067. trigger: context.trigger,
  23068. matchLength: context.text.length
  23069. });
  23070. }
  23071. };
  23072. const getAutocompleters = cached(() => register$2(editor));
  23073. const doLookup = fetchOptions => activeAutocompleter.get().map(ac => getContext(editor.dom, editor.selection.getRng(), ac.trigger).bind(newContext => lookupWithContext(editor, getAutocompleters, newContext, fetchOptions))).getOrThunk(() => lookup(editor, getAutocompleters));
  23074. const load = fetchOptions => {
  23075. doLookup(fetchOptions).fold(cancelIfNecessary, lookupInfo => {
  23076. commenceIfNecessary(lookupInfo.context);
  23077. lookupInfo.lookupData.then(lookupData => {
  23078. activeAutocompleter.get().map(ac => {
  23079. const context = lookupInfo.context;
  23080. if (ac.trigger === context.trigger) {
  23081. if (context.text.length - ac.matchLength >= 10) {
  23082. cancelIfNecessary();
  23083. } else {
  23084. activeAutocompleter.set({
  23085. ...ac,
  23086. matchLength: context.text.length
  23087. });
  23088. if (uiActive.get()) {
  23089. fireAutocompleterUpdate(editor, { lookupData });
  23090. } else {
  23091. uiActive.set(true);
  23092. fireAutocompleterStart(editor, { lookupData });
  23093. }
  23094. }
  23095. }
  23096. });
  23097. });
  23098. });
  23099. };
  23100. editor.addCommand('mceAutocompleterReload', (_ui, value) => {
  23101. const fetchOptions = isObject(value) ? value.fetchOptions : {};
  23102. load(fetchOptions);
  23103. });
  23104. editor.addCommand('mceAutocompleterClose', cancelIfNecessary);
  23105. setupEditorInput(editor, {
  23106. cancelIfNecessary,
  23107. load
  23108. });
  23109. };
  23110. const createAndFireInputEvent = eventType => (editor, inputType, specifics = {}) => {
  23111. const target = editor.getBody();
  23112. const overrides = {
  23113. bubbles: true,
  23114. composed: true,
  23115. data: null,
  23116. isComposing: false,
  23117. detail: 0,
  23118. view: null,
  23119. target,
  23120. currentTarget: target,
  23121. eventPhase: Event.AT_TARGET,
  23122. originalTarget: target,
  23123. explicitOriginalTarget: target,
  23124. isTrusted: false,
  23125. srcElement: target,
  23126. cancelable: false,
  23127. preventDefault: noop,
  23128. inputType
  23129. };
  23130. const input = clone$3(new InputEvent(eventType));
  23131. return editor.dispatch(eventType, {
  23132. ...input,
  23133. ...overrides,
  23134. ...specifics
  23135. });
  23136. };
  23137. const fireFakeInputEvent = createAndFireInputEvent('input');
  23138. const fireFakeBeforeInputEvent = createAndFireInputEvent('beforeinput');
  23139. const executeKeydownOverride$3 = (editor, caret, evt) => {
  23140. const inputType = evt.keyCode === VK.BACKSPACE ? 'deleteContentBackward' : 'deleteContentForward';
  23141. executeWithDelayedAction([
  23142. {
  23143. keyCode: VK.BACKSPACE,
  23144. action: action(backspaceDelete, editor)
  23145. },
  23146. {
  23147. keyCode: VK.BACKSPACE,
  23148. action: action(backspaceDelete$5, editor, false)
  23149. },
  23150. {
  23151. keyCode: VK.DELETE,
  23152. action: action(backspaceDelete$5, editor, true)
  23153. },
  23154. {
  23155. keyCode: VK.BACKSPACE,
  23156. action: action(backspaceDelete$6, editor, false)
  23157. },
  23158. {
  23159. keyCode: VK.DELETE,
  23160. action: action(backspaceDelete$6, editor, true)
  23161. },
  23162. {
  23163. keyCode: VK.BACKSPACE,
  23164. action: action(backspaceDelete$3, editor, caret, false)
  23165. },
  23166. {
  23167. keyCode: VK.DELETE,
  23168. action: action(backspaceDelete$3, editor, caret, true)
  23169. },
  23170. {
  23171. keyCode: VK.BACKSPACE,
  23172. action: action(backspaceDelete$9, editor, false)
  23173. },
  23174. {
  23175. keyCode: VK.DELETE,
  23176. action: action(backspaceDelete$9, editor, true)
  23177. },
  23178. {
  23179. keyCode: VK.BACKSPACE,
  23180. action: action(backspaceDelete$4, editor, false)
  23181. },
  23182. {
  23183. keyCode: VK.DELETE,
  23184. action: action(backspaceDelete$4, editor, true)
  23185. },
  23186. {
  23187. keyCode: VK.BACKSPACE,
  23188. action: action(backspaceDelete$1, editor, false)
  23189. },
  23190. {
  23191. keyCode: VK.DELETE,
  23192. action: action(backspaceDelete$1, editor, true)
  23193. },
  23194. {
  23195. keyCode: VK.BACKSPACE,
  23196. action: action(backspaceDelete$7, editor, false)
  23197. },
  23198. {
  23199. keyCode: VK.DELETE,
  23200. action: action(backspaceDelete$7, editor, true)
  23201. },
  23202. {
  23203. keyCode: VK.BACKSPACE,
  23204. action: action(backspaceDelete$8, editor, false)
  23205. },
  23206. {
  23207. keyCode: VK.DELETE,
  23208. action: action(backspaceDelete$8, editor, true)
  23209. },
  23210. {
  23211. keyCode: VK.BACKSPACE,
  23212. action: action(backspaceDelete$2, editor, false)
  23213. },
  23214. {
  23215. keyCode: VK.DELETE,
  23216. action: action(backspaceDelete$2, editor, true)
  23217. }
  23218. ], evt).filter(_ => editor.selection.isEditable()).each(applyAction => {
  23219. evt.preventDefault();
  23220. const beforeInput = fireFakeBeforeInputEvent(editor, inputType);
  23221. if (!beforeInput.isDefaultPrevented()) {
  23222. applyAction();
  23223. fireFakeInputEvent(editor, inputType);
  23224. }
  23225. });
  23226. };
  23227. const executeKeyupOverride = (editor, evt, isBackspaceKeydown) => {
  23228. const platform = detect$2();
  23229. const os = platform.os;
  23230. const browser = platform.browser;
  23231. const multiDeleteKeyPatterns = os.isMacOS() ? [
  23232. {
  23233. keyCode: VK.BACKSPACE,
  23234. altKey: true,
  23235. action: action(refreshCaret, editor)
  23236. },
  23237. {
  23238. keyCode: VK.DELETE,
  23239. altKey: true,
  23240. action: action(refreshCaret, editor)
  23241. }
  23242. ] : [
  23243. {
  23244. keyCode: VK.BACKSPACE,
  23245. ctrlKey: true,
  23246. action: action(refreshCaret, editor)
  23247. },
  23248. {
  23249. keyCode: VK.DELETE,
  23250. ctrlKey: true,
  23251. action: action(refreshCaret, editor)
  23252. }
  23253. ];
  23254. if (os.isMacOS() && isBackspaceKeydown) {
  23255. multiDeleteKeyPatterns.push({
  23256. keyCode: browser.isFirefox() ? 224 : 91,
  23257. action: action(refreshCaret, editor)
  23258. });
  23259. }
  23260. execute([
  23261. {
  23262. keyCode: VK.BACKSPACE,
  23263. action: action(paddEmptyElement, editor)
  23264. },
  23265. {
  23266. keyCode: VK.DELETE,
  23267. action: action(paddEmptyElement, editor)
  23268. },
  23269. ...multiDeleteKeyPatterns
  23270. ], evt);
  23271. };
  23272. const setup$i = (editor, caret) => {
  23273. let isBackspaceKeydown = false;
  23274. editor.on('keydown', evt => {
  23275. isBackspaceKeydown = evt.keyCode === VK.BACKSPACE;
  23276. if (!evt.isDefaultPrevented()) {
  23277. executeKeydownOverride$3(editor, caret, evt);
  23278. }
  23279. });
  23280. editor.on('keyup', evt => {
  23281. if (!evt.isDefaultPrevented()) {
  23282. executeKeyupOverride(editor, evt, isBackspaceKeydown);
  23283. }
  23284. isBackspaceKeydown = false;
  23285. });
  23286. };
  23287. const firstNonWhiteSpaceNodeSibling = node => {
  23288. while (node) {
  23289. if (isElement$6(node) || isText$a(node) && node.data && /[\r\n\s]/.test(node.data)) {
  23290. return node;
  23291. }
  23292. node = node.nextSibling;
  23293. }
  23294. return null;
  23295. };
  23296. const moveToCaretPosition = (editor, root) => {
  23297. const dom = editor.dom;
  23298. const moveCaretBeforeOnEnterElementsMap = editor.schema.getMoveCaretBeforeOnEnterElements();
  23299. if (!root) {
  23300. return;
  23301. }
  23302. if (/^(LI|DT|DD)$/.test(root.nodeName)) {
  23303. const firstChild = firstNonWhiteSpaceNodeSibling(root.firstChild);
  23304. if (firstChild && /^(UL|OL|DL)$/.test(firstChild.nodeName)) {
  23305. root.insertBefore(dom.doc.createTextNode(nbsp), root.firstChild);
  23306. }
  23307. }
  23308. const rng = dom.createRng();
  23309. root.normalize();
  23310. if (root.hasChildNodes()) {
  23311. const walker = new DomTreeWalker(root, root);
  23312. let lastNode = root;
  23313. let node;
  23314. while (node = walker.current()) {
  23315. if (isText$a(node)) {
  23316. rng.setStart(node, 0);
  23317. rng.setEnd(node, 0);
  23318. break;
  23319. }
  23320. if (moveCaretBeforeOnEnterElementsMap[node.nodeName.toLowerCase()]) {
  23321. rng.setStartBefore(node);
  23322. rng.setEndBefore(node);
  23323. break;
  23324. }
  23325. lastNode = node;
  23326. node = walker.next();
  23327. }
  23328. if (!node) {
  23329. rng.setStart(lastNode, 0);
  23330. rng.setEnd(lastNode, 0);
  23331. }
  23332. } else {
  23333. if (isBr$6(root)) {
  23334. if (root.nextSibling && dom.isBlock(root.nextSibling)) {
  23335. rng.setStartBefore(root);
  23336. rng.setEndBefore(root);
  23337. } else {
  23338. rng.setStartAfter(root);
  23339. rng.setEndAfter(root);
  23340. }
  23341. } else {
  23342. rng.setStart(root, 0);
  23343. rng.setEnd(root, 0);
  23344. }
  23345. }
  23346. editor.selection.setRng(rng);
  23347. scrollRangeIntoView(editor, rng);
  23348. };
  23349. const getEditableRoot = (dom, node) => {
  23350. const root = dom.getRoot();
  23351. let editableRoot;
  23352. let parent = node;
  23353. while (parent !== root && parent && dom.getContentEditable(parent) !== 'false') {
  23354. if (dom.getContentEditable(parent) === 'true') {
  23355. editableRoot = parent;
  23356. }
  23357. parent = parent.parentNode;
  23358. }
  23359. return parent !== root ? editableRoot : root;
  23360. };
  23361. const getParentBlock$1 = editor => {
  23362. return Optional.from(editor.dom.getParent(editor.selection.getStart(true), editor.dom.isBlock));
  23363. };
  23364. const getParentBlockName = editor => {
  23365. return getParentBlock$1(editor).fold(constant(''), parentBlock => {
  23366. return parentBlock.nodeName.toUpperCase();
  23367. });
  23368. };
  23369. const isListItemParentBlock = editor => {
  23370. return getParentBlock$1(editor).filter(elm => {
  23371. return isListItem$1(SugarElement.fromDom(elm));
  23372. }).isSome();
  23373. };
  23374. const hasFirstChild = (elm, name) => {
  23375. return elm.firstChild && elm.firstChild.nodeName === name;
  23376. };
  23377. const isFirstChild = elm => {
  23378. var _a;
  23379. return ((_a = elm.parentNode) === null || _a === void 0 ? void 0 : _a.firstChild) === elm;
  23380. };
  23381. const hasParent = (elm, parentName) => {
  23382. const parentNode = elm === null || elm === void 0 ? void 0 : elm.parentNode;
  23383. return isNonNullable(parentNode) && parentNode.nodeName === parentName;
  23384. };
  23385. const isListBlock = elm => {
  23386. return isNonNullable(elm) && /^(OL|UL|LI)$/.test(elm.nodeName);
  23387. };
  23388. const isListItem = elm => {
  23389. return isNonNullable(elm) && /^(LI|DT|DD)$/.test(elm.nodeName);
  23390. };
  23391. const isNestedList = elm => {
  23392. return isListBlock(elm) && isListBlock(elm.parentNode);
  23393. };
  23394. const getContainerBlock = containerBlock => {
  23395. const containerBlockParent = containerBlock.parentNode;
  23396. return isListItem(containerBlockParent) ? containerBlockParent : containerBlock;
  23397. };
  23398. const isFirstOrLastLi = (containerBlock, parentBlock, first) => {
  23399. let node = containerBlock[first ? 'firstChild' : 'lastChild'];
  23400. while (node) {
  23401. if (isElement$6(node)) {
  23402. break;
  23403. }
  23404. node = node[first ? 'nextSibling' : 'previousSibling'];
  23405. }
  23406. return node === parentBlock;
  23407. };
  23408. const insert$3 = (editor, createNewBlock, containerBlock, parentBlock, newBlockName) => {
  23409. const dom = editor.dom;
  23410. const rng = editor.selection.getRng();
  23411. const containerParent = containerBlock.parentNode;
  23412. if (containerBlock === editor.getBody() || !containerParent) {
  23413. return;
  23414. }
  23415. if (isNestedList(containerBlock)) {
  23416. newBlockName = 'LI';
  23417. }
  23418. let newBlock = createNewBlock(newBlockName);
  23419. if (isFirstOrLastLi(containerBlock, parentBlock, true) && isFirstOrLastLi(containerBlock, parentBlock, false)) {
  23420. if (hasParent(containerBlock, 'LI')) {
  23421. const containerBlockParent = getContainerBlock(containerBlock);
  23422. dom.insertAfter(newBlock, containerBlockParent);
  23423. if (isFirstChild(containerBlock)) {
  23424. dom.remove(containerBlockParent);
  23425. } else {
  23426. dom.remove(containerBlock);
  23427. }
  23428. } else {
  23429. dom.replace(newBlock, containerBlock);
  23430. }
  23431. } else if (isFirstOrLastLi(containerBlock, parentBlock, true)) {
  23432. if (hasParent(containerBlock, 'LI')) {
  23433. dom.insertAfter(newBlock, getContainerBlock(containerBlock));
  23434. newBlock.appendChild(dom.doc.createTextNode(' '));
  23435. newBlock.appendChild(containerBlock);
  23436. } else {
  23437. containerParent.insertBefore(newBlock, containerBlock);
  23438. }
  23439. dom.remove(parentBlock);
  23440. } else if (isFirstOrLastLi(containerBlock, parentBlock, false)) {
  23441. dom.insertAfter(newBlock, getContainerBlock(containerBlock));
  23442. dom.remove(parentBlock);
  23443. } else {
  23444. containerBlock = getContainerBlock(containerBlock);
  23445. const tmpRng = rng.cloneRange();
  23446. tmpRng.setStartAfter(parentBlock);
  23447. tmpRng.setEndAfter(containerBlock);
  23448. const fragment = tmpRng.extractContents();
  23449. if (newBlockName === 'LI' && hasFirstChild(fragment, 'LI')) {
  23450. newBlock = fragment.firstChild;
  23451. dom.insertAfter(fragment, containerBlock);
  23452. } else {
  23453. dom.insertAfter(fragment, containerBlock);
  23454. dom.insertAfter(newBlock, containerBlock);
  23455. }
  23456. dom.remove(parentBlock);
  23457. }
  23458. moveToCaretPosition(editor, newBlock);
  23459. };
  23460. const trimZwsp = fragment => {
  23461. each$e(descendants$1(SugarElement.fromDom(fragment), isText$b), text => {
  23462. const rawNode = text.dom;
  23463. rawNode.nodeValue = trim$1(rawNode.data);
  23464. });
  23465. };
  23466. const isWithinNonEditableList = (editor, node) => {
  23467. const parentList = editor.dom.getParent(node, 'ol,ul,dl');
  23468. return parentList !== null && editor.dom.getContentEditableParent(parentList) === 'false';
  23469. };
  23470. const isEmptyAnchor = (dom, elm) => {
  23471. return elm && elm.nodeName === 'A' && dom.isEmpty(elm);
  23472. };
  23473. const emptyBlock = elm => {
  23474. elm.innerHTML = '<br data-mce-bogus="1">';
  23475. };
  23476. const containerAndSiblingName = (container, nodeName) => {
  23477. return container.nodeName === nodeName || container.previousSibling && container.previousSibling.nodeName === nodeName;
  23478. };
  23479. const canSplitBlock = (dom, node) => {
  23480. return isNonNullable(node) && dom.isBlock(node) && !/^(TD|TH|CAPTION|FORM)$/.test(node.nodeName) && !/^(fixed|absolute)/i.test(node.style.position) && dom.isEditable(node.parentNode) && dom.getContentEditable(node) !== 'false';
  23481. };
  23482. const trimInlineElementsOnLeftSideOfBlock = (dom, nonEmptyElementsMap, block) => {
  23483. var _a;
  23484. const firstChilds = [];
  23485. if (!block) {
  23486. return;
  23487. }
  23488. let currentNode = block;
  23489. while (currentNode = currentNode.firstChild) {
  23490. if (dom.isBlock(currentNode)) {
  23491. return;
  23492. }
  23493. if (isElement$6(currentNode) && !nonEmptyElementsMap[currentNode.nodeName.toLowerCase()]) {
  23494. firstChilds.push(currentNode);
  23495. }
  23496. }
  23497. let i = firstChilds.length;
  23498. while (i--) {
  23499. currentNode = firstChilds[i];
  23500. if (!currentNode.hasChildNodes() || currentNode.firstChild === currentNode.lastChild && ((_a = currentNode.firstChild) === null || _a === void 0 ? void 0 : _a.nodeValue) === '') {
  23501. dom.remove(currentNode);
  23502. } else {
  23503. if (isEmptyAnchor(dom, currentNode)) {
  23504. dom.remove(currentNode);
  23505. }
  23506. }
  23507. }
  23508. };
  23509. const normalizeZwspOffset = (start, container, offset) => {
  23510. if (!isText$a(container)) {
  23511. return offset;
  23512. } else if (start) {
  23513. return offset === 1 && container.data.charAt(offset - 1) === ZWSP$1 ? 0 : offset;
  23514. } else {
  23515. return offset === container.data.length - 1 && container.data.charAt(offset) === ZWSP$1 ? container.data.length : offset;
  23516. }
  23517. };
  23518. const includeZwspInRange = rng => {
  23519. const newRng = rng.cloneRange();
  23520. newRng.setStart(rng.startContainer, normalizeZwspOffset(true, rng.startContainer, rng.startOffset));
  23521. newRng.setEnd(rng.endContainer, normalizeZwspOffset(false, rng.endContainer, rng.endOffset));
  23522. return newRng;
  23523. };
  23524. const trimLeadingLineBreaks = node => {
  23525. let currentNode = node;
  23526. do {
  23527. if (isText$a(currentNode)) {
  23528. currentNode.data = currentNode.data.replace(/^[\r\n]+/, '');
  23529. }
  23530. currentNode = currentNode.firstChild;
  23531. } while (currentNode);
  23532. };
  23533. const applyAttributes = (editor, node, forcedRootBlockAttrs) => {
  23534. const dom = editor.dom;
  23535. Optional.from(forcedRootBlockAttrs.style).map(dom.parseStyle).each(attrStyles => {
  23536. const currentStyles = getAllRaw(SugarElement.fromDom(node));
  23537. const newStyles = {
  23538. ...currentStyles,
  23539. ...attrStyles
  23540. };
  23541. dom.setStyles(node, newStyles);
  23542. });
  23543. const attrClassesOpt = Optional.from(forcedRootBlockAttrs.class).map(attrClasses => attrClasses.split(/\s+/));
  23544. const currentClassesOpt = Optional.from(node.className).map(currentClasses => filter$5(currentClasses.split(/\s+/), clazz => clazz !== ''));
  23545. lift2(attrClassesOpt, currentClassesOpt, (attrClasses, currentClasses) => {
  23546. const filteredClasses = filter$5(currentClasses, clazz => !contains$2(attrClasses, clazz));
  23547. const newClasses = [
  23548. ...attrClasses,
  23549. ...filteredClasses
  23550. ];
  23551. dom.setAttrib(node, 'class', newClasses.join(' '));
  23552. });
  23553. const appliedAttrs = [
  23554. 'style',
  23555. 'class'
  23556. ];
  23557. const remainingAttrs = filter$4(forcedRootBlockAttrs, (_, attrs) => !contains$2(appliedAttrs, attrs));
  23558. dom.setAttribs(node, remainingAttrs);
  23559. };
  23560. const setForcedBlockAttrs = (editor, node) => {
  23561. const forcedRootBlockName = getForcedRootBlock(editor);
  23562. if (forcedRootBlockName.toLowerCase() === node.tagName.toLowerCase()) {
  23563. const forcedRootBlockAttrs = getForcedRootBlockAttrs(editor);
  23564. applyAttributes(editor, node, forcedRootBlockAttrs);
  23565. }
  23566. };
  23567. const wrapSelfAndSiblingsInDefaultBlock = (editor, newBlockName, rng, container, offset) => {
  23568. var _a, _b;
  23569. const dom = editor.dom;
  23570. const editableRoot = (_a = getEditableRoot(dom, container)) !== null && _a !== void 0 ? _a : dom.getRoot();
  23571. let parentBlock = dom.getParent(container, dom.isBlock);
  23572. if (!parentBlock || !canSplitBlock(dom, parentBlock)) {
  23573. parentBlock = parentBlock || editableRoot;
  23574. if (!parentBlock.hasChildNodes()) {
  23575. const newBlock = dom.create(newBlockName);
  23576. setForcedBlockAttrs(editor, newBlock);
  23577. parentBlock.appendChild(newBlock);
  23578. rng.setStart(newBlock, 0);
  23579. rng.setEnd(newBlock, 0);
  23580. return newBlock;
  23581. }
  23582. let node = container;
  23583. while (node && node.parentNode !== parentBlock) {
  23584. node = node.parentNode;
  23585. }
  23586. let startNode;
  23587. while (node && !dom.isBlock(node)) {
  23588. startNode = node;
  23589. node = node.previousSibling;
  23590. }
  23591. const startNodeName = (_b = startNode === null || startNode === void 0 ? void 0 : startNode.parentElement) === null || _b === void 0 ? void 0 : _b.nodeName;
  23592. if (startNode && startNodeName && editor.schema.isValidChild(startNodeName, newBlockName.toLowerCase())) {
  23593. const startNodeParent = startNode.parentNode;
  23594. const newBlock = dom.create(newBlockName);
  23595. setForcedBlockAttrs(editor, newBlock);
  23596. startNodeParent.insertBefore(newBlock, startNode);
  23597. node = startNode;
  23598. while (node && !dom.isBlock(node)) {
  23599. const next = node.nextSibling;
  23600. newBlock.appendChild(node);
  23601. node = next;
  23602. }
  23603. rng.setStart(container, offset);
  23604. rng.setEnd(container, offset);
  23605. }
  23606. }
  23607. return container;
  23608. };
  23609. const addBrToBlockIfNeeded = (dom, block) => {
  23610. block.normalize();
  23611. const lastChild = block.lastChild;
  23612. if (!lastChild || isElement$6(lastChild) && /^(left|right)$/gi.test(dom.getStyle(lastChild, 'float', true))) {
  23613. dom.add(block, 'br');
  23614. }
  23615. };
  23616. const shouldEndContainer = (editor, container) => {
  23617. const optionValue = shouldEndContainerOnEmptyBlock(editor);
  23618. if (isNullable(container)) {
  23619. return false;
  23620. } else if (isString(optionValue)) {
  23621. return contains$2(Tools.explode(optionValue), container.nodeName.toLowerCase());
  23622. } else {
  23623. return optionValue;
  23624. }
  23625. };
  23626. const insert$2 = (editor, evt) => {
  23627. let container;
  23628. let offset;
  23629. let parentBlockName;
  23630. let containerBlock;
  23631. let isAfterLastNodeInContainer = false;
  23632. const dom = editor.dom;
  23633. const schema = editor.schema, nonEmptyElementsMap = schema.getNonEmptyElements();
  23634. const rng = editor.selection.getRng();
  23635. const newBlockName = getForcedRootBlock(editor);
  23636. const createNewBlock = name => {
  23637. let node = container;
  23638. const textInlineElements = schema.getTextInlineElements();
  23639. let block;
  23640. if (name || parentBlockName === 'TABLE' || parentBlockName === 'HR') {
  23641. block = dom.create(name || newBlockName);
  23642. } else {
  23643. block = parentBlock.cloneNode(false);
  23644. }
  23645. let caretNode = block;
  23646. if (shouldKeepStyles(editor) === false) {
  23647. dom.setAttrib(block, 'style', null);
  23648. dom.setAttrib(block, 'class', null);
  23649. } else {
  23650. do {
  23651. if (textInlineElements[node.nodeName]) {
  23652. if (isCaretNode(node) || isBookmarkNode$1(node)) {
  23653. continue;
  23654. }
  23655. const clonedNode = node.cloneNode(false);
  23656. dom.setAttrib(clonedNode, 'id', '');
  23657. if (block.hasChildNodes()) {
  23658. clonedNode.appendChild(block.firstChild);
  23659. block.appendChild(clonedNode);
  23660. } else {
  23661. caretNode = clonedNode;
  23662. block.appendChild(clonedNode);
  23663. }
  23664. }
  23665. } while ((node = node.parentNode) && node !== editableRoot);
  23666. }
  23667. setForcedBlockAttrs(editor, block);
  23668. emptyBlock(caretNode);
  23669. return block;
  23670. };
  23671. const isCaretAtStartOrEndOfBlock = start => {
  23672. const normalizedOffset = normalizeZwspOffset(start, container, offset);
  23673. if (isText$a(container) && (start ? normalizedOffset > 0 : normalizedOffset < container.data.length)) {
  23674. return false;
  23675. }
  23676. if (container.parentNode === parentBlock && isAfterLastNodeInContainer && !start) {
  23677. return true;
  23678. }
  23679. if (start && isElement$6(container) && container === parentBlock.firstChild) {
  23680. return true;
  23681. }
  23682. if (containerAndSiblingName(container, 'TABLE') || containerAndSiblingName(container, 'HR')) {
  23683. return isAfterLastNodeInContainer && !start || !isAfterLastNodeInContainer && start;
  23684. }
  23685. const walker = new DomTreeWalker(container, parentBlock);
  23686. if (isText$a(container)) {
  23687. if (start && normalizedOffset === 0) {
  23688. walker.prev();
  23689. } else if (!start && normalizedOffset === container.data.length) {
  23690. walker.next();
  23691. }
  23692. }
  23693. let node;
  23694. while (node = walker.current()) {
  23695. if (isElement$6(node)) {
  23696. if (!node.getAttribute('data-mce-bogus')) {
  23697. const name = node.nodeName.toLowerCase();
  23698. if (nonEmptyElementsMap[name] && name !== 'br') {
  23699. return false;
  23700. }
  23701. }
  23702. } else if (isText$a(node) && !isWhitespaceText(node.data)) {
  23703. return false;
  23704. }
  23705. if (start) {
  23706. walker.prev();
  23707. } else {
  23708. walker.next();
  23709. }
  23710. }
  23711. return true;
  23712. };
  23713. const insertNewBlockAfter = () => {
  23714. let block;
  23715. if (/^(H[1-6]|PRE|FIGURE)$/.test(parentBlockName) && containerBlockName !== 'HGROUP') {
  23716. block = createNewBlock(newBlockName);
  23717. } else {
  23718. block = createNewBlock();
  23719. }
  23720. if (shouldEndContainer(editor, containerBlock) && canSplitBlock(dom, containerBlock) && dom.isEmpty(parentBlock)) {
  23721. block = dom.split(containerBlock, parentBlock);
  23722. } else {
  23723. dom.insertAfter(block, parentBlock);
  23724. }
  23725. moveToCaretPosition(editor, block);
  23726. return block;
  23727. };
  23728. normalize$2(dom, rng).each(normRng => {
  23729. rng.setStart(normRng.startContainer, normRng.startOffset);
  23730. rng.setEnd(normRng.endContainer, normRng.endOffset);
  23731. });
  23732. container = rng.startContainer;
  23733. offset = rng.startOffset;
  23734. const shiftKey = !!(evt && evt.shiftKey);
  23735. const ctrlKey = !!(evt && evt.ctrlKey);
  23736. if (isElement$6(container) && container.hasChildNodes()) {
  23737. isAfterLastNodeInContainer = offset > container.childNodes.length - 1;
  23738. container = container.childNodes[Math.min(offset, container.childNodes.length - 1)] || container;
  23739. if (isAfterLastNodeInContainer && isText$a(container)) {
  23740. offset = container.data.length;
  23741. } else {
  23742. offset = 0;
  23743. }
  23744. }
  23745. const editableRoot = getEditableRoot(dom, container);
  23746. if (!editableRoot || isWithinNonEditableList(editor, container)) {
  23747. return;
  23748. }
  23749. if (!shiftKey) {
  23750. container = wrapSelfAndSiblingsInDefaultBlock(editor, newBlockName, rng, container, offset);
  23751. }
  23752. let parentBlock = dom.getParent(container, dom.isBlock) || dom.getRoot();
  23753. containerBlock = isNonNullable(parentBlock === null || parentBlock === void 0 ? void 0 : parentBlock.parentNode) ? dom.getParent(parentBlock.parentNode, dom.isBlock) : null;
  23754. parentBlockName = parentBlock ? parentBlock.nodeName.toUpperCase() : '';
  23755. const containerBlockName = containerBlock ? containerBlock.nodeName.toUpperCase() : '';
  23756. if (containerBlockName === 'LI' && !ctrlKey) {
  23757. const liBlock = containerBlock;
  23758. parentBlock = liBlock;
  23759. containerBlock = liBlock.parentNode;
  23760. parentBlockName = containerBlockName;
  23761. }
  23762. if (/^(LI|DT|DD)$/.test(parentBlockName) && isElement$6(containerBlock)) {
  23763. if (dom.isEmpty(parentBlock)) {
  23764. insert$3(editor, createNewBlock, containerBlock, parentBlock, newBlockName);
  23765. return;
  23766. }
  23767. }
  23768. if (parentBlock === editor.getBody() || !canSplitBlock(dom, parentBlock)) {
  23769. return;
  23770. }
  23771. const parentBlockParent = parentBlock.parentNode;
  23772. let newBlock;
  23773. if (isCaretContainerBlock$1(parentBlock)) {
  23774. newBlock = showCaretContainerBlock(parentBlock);
  23775. if (dom.isEmpty(parentBlock)) {
  23776. emptyBlock(parentBlock);
  23777. }
  23778. setForcedBlockAttrs(editor, newBlock);
  23779. moveToCaretPosition(editor, newBlock);
  23780. } else if (isCaretAtStartOrEndOfBlock(false)) {
  23781. newBlock = insertNewBlockAfter();
  23782. } else if (isCaretAtStartOrEndOfBlock(true) && parentBlockParent) {
  23783. newBlock = parentBlockParent.insertBefore(createNewBlock(), parentBlock);
  23784. moveToCaretPosition(editor, containerAndSiblingName(parentBlock, 'HR') ? newBlock : parentBlock);
  23785. } else {
  23786. const tmpRng = includeZwspInRange(rng).cloneRange();
  23787. tmpRng.setEndAfter(parentBlock);
  23788. const fragment = tmpRng.extractContents();
  23789. trimZwsp(fragment);
  23790. trimLeadingLineBreaks(fragment);
  23791. newBlock = fragment.firstChild;
  23792. dom.insertAfter(fragment, parentBlock);
  23793. trimInlineElementsOnLeftSideOfBlock(dom, nonEmptyElementsMap, newBlock);
  23794. addBrToBlockIfNeeded(dom, parentBlock);
  23795. if (dom.isEmpty(parentBlock)) {
  23796. emptyBlock(parentBlock);
  23797. }
  23798. newBlock.normalize();
  23799. if (dom.isEmpty(newBlock)) {
  23800. dom.remove(newBlock);
  23801. insertNewBlockAfter();
  23802. } else {
  23803. setForcedBlockAttrs(editor, newBlock);
  23804. moveToCaretPosition(editor, newBlock);
  23805. }
  23806. }
  23807. dom.setAttrib(newBlock, 'id', '');
  23808. editor.dispatch('NewBlock', { newBlock });
  23809. };
  23810. const fakeEventName$1 = 'insertParagraph';
  23811. const blockbreak = {
  23812. insert: insert$2,
  23813. fakeEventName: fakeEventName$1
  23814. };
  23815. const hasRightSideContent = (schema, container, parentBlock) => {
  23816. const walker = new DomTreeWalker(container, parentBlock);
  23817. let node;
  23818. const nonEmptyElementsMap = schema.getNonEmptyElements();
  23819. while (node = walker.next()) {
  23820. if (nonEmptyElementsMap[node.nodeName.toLowerCase()] || isText$a(node) && node.length > 0) {
  23821. return true;
  23822. }
  23823. }
  23824. return false;
  23825. };
  23826. const moveSelectionToBr = (editor, brElm, extraBr) => {
  23827. const rng = editor.dom.createRng();
  23828. if (!extraBr) {
  23829. rng.setStartAfter(brElm);
  23830. rng.setEndAfter(brElm);
  23831. } else {
  23832. rng.setStartBefore(brElm);
  23833. rng.setEndBefore(brElm);
  23834. }
  23835. editor.selection.setRng(rng);
  23836. scrollRangeIntoView(editor, rng);
  23837. };
  23838. const insertBrAtCaret = (editor, evt) => {
  23839. const selection = editor.selection;
  23840. const dom = editor.dom;
  23841. const rng = selection.getRng();
  23842. let brElm;
  23843. let extraBr = false;
  23844. normalize$2(dom, rng).each(normRng => {
  23845. rng.setStart(normRng.startContainer, normRng.startOffset);
  23846. rng.setEnd(normRng.endContainer, normRng.endOffset);
  23847. });
  23848. let offset = rng.startOffset;
  23849. let container = rng.startContainer;
  23850. if (isElement$6(container) && container.hasChildNodes()) {
  23851. const isAfterLastNodeInContainer = offset > container.childNodes.length - 1;
  23852. container = container.childNodes[Math.min(offset, container.childNodes.length - 1)] || container;
  23853. if (isAfterLastNodeInContainer && isText$a(container)) {
  23854. offset = container.data.length;
  23855. } else {
  23856. offset = 0;
  23857. }
  23858. }
  23859. let parentBlock = dom.getParent(container, dom.isBlock);
  23860. const containerBlock = parentBlock && parentBlock.parentNode ? dom.getParent(parentBlock.parentNode, dom.isBlock) : null;
  23861. const containerBlockName = containerBlock ? containerBlock.nodeName.toUpperCase() : '';
  23862. const isControlKey = !!(evt && evt.ctrlKey);
  23863. if (containerBlockName === 'LI' && !isControlKey) {
  23864. parentBlock = containerBlock;
  23865. }
  23866. if (isText$a(container) && offset >= container.data.length) {
  23867. if (!hasRightSideContent(editor.schema, container, parentBlock || dom.getRoot())) {
  23868. brElm = dom.create('br');
  23869. rng.insertNode(brElm);
  23870. rng.setStartAfter(brElm);
  23871. rng.setEndAfter(brElm);
  23872. extraBr = true;
  23873. }
  23874. }
  23875. brElm = dom.create('br');
  23876. rangeInsertNode(dom, rng, brElm);
  23877. moveSelectionToBr(editor, brElm, extraBr);
  23878. editor.undoManager.add();
  23879. };
  23880. const insertBrBefore = (editor, inline) => {
  23881. const br = SugarElement.fromTag('br');
  23882. before$3(SugarElement.fromDom(inline), br);
  23883. editor.undoManager.add();
  23884. };
  23885. const insertBrAfter = (editor, inline) => {
  23886. if (!hasBrAfter(editor.getBody(), inline)) {
  23887. after$4(SugarElement.fromDom(inline), SugarElement.fromTag('br'));
  23888. }
  23889. const br = SugarElement.fromTag('br');
  23890. after$4(SugarElement.fromDom(inline), br);
  23891. moveSelectionToBr(editor, br.dom, false);
  23892. editor.undoManager.add();
  23893. };
  23894. const isBeforeBr = pos => {
  23895. return isBr$6(pos.getNode());
  23896. };
  23897. const hasBrAfter = (rootNode, startNode) => {
  23898. if (isBeforeBr(CaretPosition.after(startNode))) {
  23899. return true;
  23900. } else {
  23901. return nextPosition(rootNode, CaretPosition.after(startNode)).map(pos => {
  23902. return isBr$6(pos.getNode());
  23903. }).getOr(false);
  23904. }
  23905. };
  23906. const isAnchorLink = elm => {
  23907. return elm && elm.nodeName === 'A' && 'href' in elm;
  23908. };
  23909. const isInsideAnchor = location => {
  23910. return location.fold(never, isAnchorLink, isAnchorLink, never);
  23911. };
  23912. const readInlineAnchorLocation = editor => {
  23913. const isInlineTarget$1 = curry(isInlineTarget, editor);
  23914. const position = CaretPosition.fromRangeStart(editor.selection.getRng());
  23915. return readLocation(isInlineTarget$1, editor.getBody(), position).filter(isInsideAnchor);
  23916. };
  23917. const insertBrOutsideAnchor = (editor, location) => {
  23918. location.fold(noop, curry(insertBrBefore, editor), curry(insertBrAfter, editor), noop);
  23919. };
  23920. const insert$1 = (editor, evt) => {
  23921. const anchorLocation = readInlineAnchorLocation(editor);
  23922. if (anchorLocation.isSome()) {
  23923. anchorLocation.each(curry(insertBrOutsideAnchor, editor));
  23924. } else {
  23925. insertBrAtCaret(editor, evt);
  23926. }
  23927. };
  23928. const fakeEventName = 'insertLineBreak';
  23929. const linebreak = {
  23930. insert: insert$1,
  23931. fakeEventName
  23932. };
  23933. const matchesSelector = (editor, selector) => {
  23934. return getParentBlock$1(editor).filter(parentBlock => {
  23935. return selector.length > 0 && is$1(SugarElement.fromDom(parentBlock), selector);
  23936. }).isSome();
  23937. };
  23938. const shouldInsertBr = editor => {
  23939. return matchesSelector(editor, getBrNewLineSelector(editor));
  23940. };
  23941. const shouldBlockNewLine$1 = editor => {
  23942. return matchesSelector(editor, getNoNewLineSelector(editor));
  23943. };
  23944. const newLineAction = Adt.generate([
  23945. { br: [] },
  23946. { block: [] },
  23947. { none: [] }
  23948. ]);
  23949. const shouldBlockNewLine = (editor, _shiftKey) => {
  23950. return shouldBlockNewLine$1(editor);
  23951. };
  23952. const inListBlock = requiredState => {
  23953. return (editor, _shiftKey) => {
  23954. return isListItemParentBlock(editor) === requiredState;
  23955. };
  23956. };
  23957. const inBlock = (blockName, requiredState) => (editor, _shiftKey) => {
  23958. const state = getParentBlockName(editor) === blockName.toUpperCase();
  23959. return state === requiredState;
  23960. };
  23961. const inCefBlock = editor => {
  23962. const editableRoot = getEditableRoot(editor.dom, editor.selection.getStart());
  23963. return isNullable(editableRoot);
  23964. };
  23965. const inPreBlock = requiredState => inBlock('pre', requiredState);
  23966. const inSummaryBlock = () => inBlock('summary', true);
  23967. const shouldPutBrInPre = requiredState => {
  23968. return (editor, _shiftKey) => {
  23969. return shouldPutBrInPre$1(editor) === requiredState;
  23970. };
  23971. };
  23972. const inBrContext = (editor, _shiftKey) => {
  23973. return shouldInsertBr(editor);
  23974. };
  23975. const hasShiftKey = (_editor, shiftKey) => {
  23976. return shiftKey;
  23977. };
  23978. const canInsertIntoEditableRoot = editor => {
  23979. const forcedRootBlock = getForcedRootBlock(editor);
  23980. const rootEditable = getEditableRoot(editor.dom, editor.selection.getStart());
  23981. return isNonNullable(rootEditable) && editor.schema.isValidChild(rootEditable.nodeName, forcedRootBlock);
  23982. };
  23983. const match = (predicates, action) => {
  23984. return (editor, shiftKey) => {
  23985. const isMatch = foldl(predicates, (res, p) => {
  23986. return res && p(editor, shiftKey);
  23987. }, true);
  23988. return isMatch ? Optional.some(action) : Optional.none();
  23989. };
  23990. };
  23991. const getAction = (editor, evt) => {
  23992. return evaluateUntil([
  23993. match([shouldBlockNewLine], newLineAction.none()),
  23994. match([
  23995. inPreBlock(true),
  23996. inCefBlock
  23997. ], newLineAction.none()),
  23998. match([inSummaryBlock()], newLineAction.br()),
  23999. match([
  24000. inPreBlock(true),
  24001. shouldPutBrInPre(false),
  24002. hasShiftKey
  24003. ], newLineAction.br()),
  24004. match([
  24005. inPreBlock(true),
  24006. shouldPutBrInPre(false)
  24007. ], newLineAction.block()),
  24008. match([
  24009. inPreBlock(true),
  24010. shouldPutBrInPre(true),
  24011. hasShiftKey
  24012. ], newLineAction.block()),
  24013. match([
  24014. inPreBlock(true),
  24015. shouldPutBrInPre(true)
  24016. ], newLineAction.br()),
  24017. match([
  24018. inListBlock(true),
  24019. hasShiftKey
  24020. ], newLineAction.br()),
  24021. match([inListBlock(true)], newLineAction.block()),
  24022. match([inBrContext], newLineAction.br()),
  24023. match([hasShiftKey], newLineAction.br()),
  24024. match([canInsertIntoEditableRoot], newLineAction.block())
  24025. ], [
  24026. editor,
  24027. !!(evt && evt.shiftKey)
  24028. ]).getOr(newLineAction.none());
  24029. };
  24030. const insertBreak = (breakType, editor, evt) => {
  24031. if (!editor.selection.isCollapsed()) {
  24032. execEditorDeleteCommand(editor);
  24033. }
  24034. if (isNonNullable(evt)) {
  24035. const event = fireFakeBeforeInputEvent(editor, breakType.fakeEventName);
  24036. if (event.isDefaultPrevented()) {
  24037. return;
  24038. }
  24039. }
  24040. breakType.insert(editor, evt);
  24041. if (isNonNullable(evt)) {
  24042. fireFakeInputEvent(editor, breakType.fakeEventName);
  24043. }
  24044. };
  24045. const insert = (editor, evt) => {
  24046. const br = () => insertBreak(linebreak, editor, evt);
  24047. const block = () => insertBreak(blockbreak, editor, evt);
  24048. const logicalAction = getAction(editor, evt);
  24049. switch (getNewlineBehavior(editor)) {
  24050. case 'linebreak':
  24051. logicalAction.fold(br, br, noop);
  24052. break;
  24053. case 'block':
  24054. logicalAction.fold(block, block, noop);
  24055. break;
  24056. case 'invert':
  24057. logicalAction.fold(block, br, noop);
  24058. break;
  24059. default:
  24060. logicalAction.fold(br, block, noop);
  24061. break;
  24062. }
  24063. };
  24064. const handleEnterKeyEvent = (editor, event) => {
  24065. if (event.isDefaultPrevented()) {
  24066. return;
  24067. }
  24068. event.preventDefault();
  24069. endTypingLevelIgnoreLocks(editor.undoManager);
  24070. editor.undoManager.transact(() => {
  24071. insert(editor, event);
  24072. });
  24073. };
  24074. const setup$h = editor => {
  24075. editor.on('keydown', event => {
  24076. if (event.keyCode === VK.ENTER) {
  24077. handleEnterKeyEvent(editor, event);
  24078. }
  24079. });
  24080. };
  24081. const executeKeydownOverride$2 = (editor, caret, evt) => {
  24082. const isMac = Env.os.isMacOS() || Env.os.isiOS();
  24083. execute([
  24084. {
  24085. keyCode: VK.END,
  24086. action: action(moveToLineEndPoint$1, editor, true)
  24087. },
  24088. {
  24089. keyCode: VK.HOME,
  24090. action: action(moveToLineEndPoint$1, editor, false)
  24091. },
  24092. ...!isMac ? [
  24093. {
  24094. keyCode: VK.HOME,
  24095. action: action(selectToEndPoint, editor, false),
  24096. ctrlKey: true,
  24097. shiftKey: true
  24098. },
  24099. {
  24100. keyCode: VK.END,
  24101. action: action(selectToEndPoint, editor, true),
  24102. ctrlKey: true,
  24103. shiftKey: true
  24104. }
  24105. ] : [],
  24106. {
  24107. keyCode: VK.END,
  24108. action: action(moveToLineEndPoint, editor, true)
  24109. },
  24110. {
  24111. keyCode: VK.HOME,
  24112. action: action(moveToLineEndPoint, editor, false)
  24113. },
  24114. {
  24115. keyCode: VK.END,
  24116. action: action(moveToLineEndPoint$2, editor, true, caret)
  24117. },
  24118. {
  24119. keyCode: VK.HOME,
  24120. action: action(moveToLineEndPoint$2, editor, false, caret)
  24121. }
  24122. ], evt).each(_ => {
  24123. evt.preventDefault();
  24124. });
  24125. };
  24126. const setup$g = (editor, caret) => {
  24127. editor.on('keydown', evt => {
  24128. if (!evt.isDefaultPrevented()) {
  24129. executeKeydownOverride$2(editor, caret, evt);
  24130. }
  24131. });
  24132. };
  24133. const setup$f = editor => {
  24134. editor.on('input', e => {
  24135. if (!e.isComposing) {
  24136. normalizeNbspsInEditor(editor);
  24137. }
  24138. });
  24139. };
  24140. const platform = detect$2();
  24141. const executeKeyupAction = (editor, caret, evt) => {
  24142. execute([
  24143. {
  24144. keyCode: VK.PAGE_UP,
  24145. action: action(moveToLineEndPoint$2, editor, false, caret)
  24146. },
  24147. {
  24148. keyCode: VK.PAGE_DOWN,
  24149. action: action(moveToLineEndPoint$2, editor, true, caret)
  24150. }
  24151. ], evt);
  24152. };
  24153. const stopImmediatePropagation = e => e.stopImmediatePropagation();
  24154. const isPageUpDown = evt => evt.keyCode === VK.PAGE_UP || evt.keyCode === VK.PAGE_DOWN;
  24155. const setNodeChangeBlocker = (blocked, editor, block) => {
  24156. if (block && !blocked.get()) {
  24157. editor.on('NodeChange', stopImmediatePropagation, true);
  24158. } else if (!block && blocked.get()) {
  24159. editor.off('NodeChange', stopImmediatePropagation);
  24160. }
  24161. blocked.set(block);
  24162. };
  24163. const setup$e = (editor, caret) => {
  24164. if (platform.os.isMacOS()) {
  24165. return;
  24166. }
  24167. const blocked = Cell(false);
  24168. editor.on('keydown', evt => {
  24169. if (isPageUpDown(evt)) {
  24170. setNodeChangeBlocker(blocked, editor, true);
  24171. }
  24172. });
  24173. editor.on('keyup', evt => {
  24174. if (!evt.isDefaultPrevented()) {
  24175. executeKeyupAction(editor, caret, evt);
  24176. }
  24177. if (isPageUpDown(evt) && blocked.get()) {
  24178. setNodeChangeBlocker(blocked, editor, false);
  24179. editor.nodeChanged();
  24180. }
  24181. });
  24182. };
  24183. const insertTextAtPosition = (text, pos) => {
  24184. const container = pos.container();
  24185. const offset = pos.offset();
  24186. if (isText$a(container)) {
  24187. container.insertData(offset, text);
  24188. return Optional.some(CaretPosition(container, offset + text.length));
  24189. } else {
  24190. return getElementFromPosition(pos).map(elm => {
  24191. const textNode = SugarElement.fromText(text);
  24192. if (pos.isAtEnd()) {
  24193. after$4(elm, textNode);
  24194. } else {
  24195. before$3(elm, textNode);
  24196. }
  24197. return CaretPosition(textNode.dom, text.length);
  24198. });
  24199. }
  24200. };
  24201. const insertNbspAtPosition = curry(insertTextAtPosition, nbsp);
  24202. const insertSpaceAtPosition = curry(insertTextAtPosition, ' ');
  24203. 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)));
  24204. const insertInlineBoundarySpaceOrNbsp = (root, pos) => checkPos => needsToHaveNbsp(root, checkPos) ? insertNbspAtPosition(pos) : insertSpaceAtPosition(pos);
  24205. const setSelection = editor => pos => {
  24206. editor.selection.setRng(pos.toRange());
  24207. editor.nodeChanged();
  24208. return true;
  24209. };
  24210. const insertSpaceOrNbspAtSelection = editor => {
  24211. const pos = CaretPosition.fromRangeStart(editor.selection.getRng());
  24212. const root = SugarElement.fromDom(editor.getBody());
  24213. if (editor.selection.isCollapsed()) {
  24214. const isInlineTarget$1 = curry(isInlineTarget, editor);
  24215. const caretPosition = CaretPosition.fromRangeStart(editor.selection.getRng());
  24216. return readLocation(isInlineTarget$1, editor.getBody(), caretPosition).bind(locationToCaretPosition(root)).map(checkPos => () => insertInlineBoundarySpaceOrNbsp(root, pos)(checkPos).each(setSelection(editor)));
  24217. } else {
  24218. return Optional.none();
  24219. }
  24220. };
  24221. const executeKeydownOverride$1 = (editor, evt) => {
  24222. executeWithDelayedAction([{
  24223. keyCode: VK.SPACEBAR,
  24224. action: action(insertSpaceOrNbspAtSelection, editor)
  24225. }], evt).each(applyAction => {
  24226. evt.preventDefault();
  24227. const event = fireFakeBeforeInputEvent(editor, 'insertText', { data: ' ' });
  24228. if (!event.isDefaultPrevented()) {
  24229. applyAction();
  24230. fireFakeInputEvent(editor, 'insertText', { data: ' ' });
  24231. }
  24232. });
  24233. };
  24234. const setup$d = editor => {
  24235. editor.on('keydown', evt => {
  24236. if (!evt.isDefaultPrevented()) {
  24237. executeKeydownOverride$1(editor, evt);
  24238. }
  24239. });
  24240. };
  24241. const tableTabNavigation = editor => {
  24242. if (hasTableTabNavigation(editor)) {
  24243. return [
  24244. {
  24245. keyCode: VK.TAB,
  24246. action: action(handleTab, editor, true)
  24247. },
  24248. {
  24249. keyCode: VK.TAB,
  24250. shiftKey: true,
  24251. action: action(handleTab, editor, false)
  24252. }
  24253. ];
  24254. } else {
  24255. return [];
  24256. }
  24257. };
  24258. const executeKeydownOverride = (editor, evt) => {
  24259. execute([...tableTabNavigation(editor)], evt).each(_ => {
  24260. evt.preventDefault();
  24261. });
  24262. };
  24263. const setup$c = editor => {
  24264. editor.on('keydown', evt => {
  24265. if (!evt.isDefaultPrevented()) {
  24266. executeKeydownOverride(editor, evt);
  24267. }
  24268. });
  24269. };
  24270. const setup$b = editor => {
  24271. editor.addShortcut('Meta+P', '', 'mcePrint');
  24272. setup$j(editor);
  24273. if (isRtc(editor)) {
  24274. return Cell(null);
  24275. } else {
  24276. const caret = setupSelectedState(editor);
  24277. setup$l(editor);
  24278. setup$k(editor, caret);
  24279. setup$i(editor, caret);
  24280. setup$h(editor);
  24281. setup$d(editor);
  24282. setup$f(editor);
  24283. setup$c(editor);
  24284. setup$g(editor, caret);
  24285. setup$e(editor, caret);
  24286. return caret;
  24287. }
  24288. };
  24289. class NodeChange {
  24290. constructor(editor) {
  24291. this.lastPath = [];
  24292. this.editor = editor;
  24293. let lastRng;
  24294. const self = this;
  24295. if (!('onselectionchange' in editor.getDoc())) {
  24296. editor.on('NodeChange click mouseup keyup focus', e => {
  24297. const nativeRng = editor.selection.getRng();
  24298. const fakeRng = {
  24299. startContainer: nativeRng.startContainer,
  24300. startOffset: nativeRng.startOffset,
  24301. endContainer: nativeRng.endContainer,
  24302. endOffset: nativeRng.endOffset
  24303. };
  24304. if (e.type === 'nodechange' || !isEq$4(fakeRng, lastRng)) {
  24305. editor.dispatch('SelectionChange');
  24306. }
  24307. lastRng = fakeRng;
  24308. });
  24309. }
  24310. editor.on('contextmenu', () => {
  24311. editor.dispatch('SelectionChange');
  24312. });
  24313. editor.on('SelectionChange', () => {
  24314. const startElm = editor.selection.getStart(true);
  24315. if (!startElm) {
  24316. return;
  24317. }
  24318. if (hasAnyRanges(editor) && !self.isSameElementPath(startElm) && editor.dom.isChildOf(startElm, editor.getBody())) {
  24319. editor.nodeChanged({ selectionChange: true });
  24320. }
  24321. });
  24322. editor.on('mouseup', e => {
  24323. if (!e.isDefaultPrevented() && hasAnyRanges(editor)) {
  24324. if (editor.selection.getNode().nodeName === 'IMG') {
  24325. Delay.setEditorTimeout(editor, () => {
  24326. editor.nodeChanged();
  24327. });
  24328. } else {
  24329. editor.nodeChanged();
  24330. }
  24331. }
  24332. });
  24333. }
  24334. nodeChanged(args = {}) {
  24335. const selection = this.editor.selection;
  24336. let node;
  24337. if (this.editor.initialized && selection && !shouldDisableNodeChange(this.editor) && !this.editor.mode.isReadOnly()) {
  24338. const root = this.editor.getBody();
  24339. node = selection.getStart(true) || root;
  24340. if (node.ownerDocument !== this.editor.getDoc() || !this.editor.dom.isChildOf(node, root)) {
  24341. node = root;
  24342. }
  24343. const parents = [];
  24344. this.editor.dom.getParent(node, node => {
  24345. if (node === root) {
  24346. return true;
  24347. } else {
  24348. parents.push(node);
  24349. return false;
  24350. }
  24351. });
  24352. this.editor.dispatch('NodeChange', {
  24353. ...args,
  24354. element: node,
  24355. parents
  24356. });
  24357. }
  24358. }
  24359. isSameElementPath(startElm) {
  24360. let i;
  24361. const editor = this.editor;
  24362. const currentPath = reverse(editor.dom.getParents(startElm, always, editor.getBody()));
  24363. if (currentPath.length === this.lastPath.length) {
  24364. for (i = currentPath.length; i >= 0; i--) {
  24365. if (currentPath[i] !== this.lastPath[i]) {
  24366. break;
  24367. }
  24368. }
  24369. if (i === -1) {
  24370. this.lastPath = currentPath;
  24371. return true;
  24372. }
  24373. }
  24374. this.lastPath = currentPath;
  24375. return false;
  24376. }
  24377. }
  24378. const internalMimeType = 'x-tinymce/html';
  24379. const internalHtmlMime = constant(internalMimeType);
  24380. const internalMark = '<!-- ' + internalMimeType + ' -->';
  24381. const mark = html => internalMark + html;
  24382. const unmark = html => html.replace(internalMark, '');
  24383. const isMarked = html => html.indexOf(internalMark) !== -1;
  24384. const isPlainText = text => {
  24385. return !/<(?:\/?(?!(?:div|p|br|span)>)\w+|(?:(?!(?:span style="white-space:\s?pre;?">)|br\s?\/>))\w+\s[^>]+)>/i.test(text);
  24386. };
  24387. const openContainer = (rootTag, rootAttrs) => {
  24388. let tag = '<' + rootTag;
  24389. const attrs = mapToArray(rootAttrs, (value, key) => key + '="' + Entities.encodeAllRaw(value) + '"');
  24390. if (attrs.length) {
  24391. tag += ' ' + attrs.join(' ');
  24392. }
  24393. return tag + '>';
  24394. };
  24395. const toBlockElements = (text, rootTag, rootAttrs) => {
  24396. const blocks = text.split(/\n\n/);
  24397. const tagOpen = openContainer(rootTag, rootAttrs);
  24398. const tagClose = '</' + rootTag + '>';
  24399. const paragraphs = map$3(blocks, p => {
  24400. return p.split(/\n/).join('<br />');
  24401. });
  24402. const stitch = p => {
  24403. return tagOpen + p + tagClose;
  24404. };
  24405. return paragraphs.length === 1 ? paragraphs[0] : map$3(paragraphs, stitch).join('');
  24406. };
  24407. const pasteBinDefaultContent = '%MCEPASTEBIN%';
  24408. const create$6 = (editor, lastRngCell) => {
  24409. const {dom, selection} = editor;
  24410. const body = editor.getBody();
  24411. lastRngCell.set(selection.getRng());
  24412. const pasteBinElm = dom.add(editor.getBody(), 'div', {
  24413. 'id': 'mcepastebin',
  24414. 'class': 'mce-pastebin',
  24415. 'contentEditable': true,
  24416. 'data-mce-bogus': 'all',
  24417. 'style': 'position: fixed; top: 50%; width: 10px; height: 10px; overflow: hidden; opacity: 0'
  24418. }, pasteBinDefaultContent);
  24419. if (Env.browser.isFirefox()) {
  24420. dom.setStyle(pasteBinElm, 'left', dom.getStyle(body, 'direction', true) === 'rtl' ? 65535 : -65535);
  24421. }
  24422. dom.bind(pasteBinElm, 'beforedeactivate focusin focusout', e => {
  24423. e.stopPropagation();
  24424. });
  24425. pasteBinElm.focus();
  24426. selection.select(pasteBinElm, true);
  24427. };
  24428. const remove = (editor, lastRngCell) => {
  24429. const dom = editor.dom;
  24430. if (getEl(editor)) {
  24431. let pasteBinClone;
  24432. const lastRng = lastRngCell.get();
  24433. while (pasteBinClone = getEl(editor)) {
  24434. dom.remove(pasteBinClone);
  24435. dom.unbind(pasteBinClone);
  24436. }
  24437. if (lastRng) {
  24438. editor.selection.setRng(lastRng);
  24439. }
  24440. }
  24441. lastRngCell.set(null);
  24442. };
  24443. const getEl = editor => editor.dom.get('mcepastebin');
  24444. const isPasteBin = elm => isNonNullable(elm) && elm.id === 'mcepastebin';
  24445. const getHtml = editor => {
  24446. const dom = editor.dom;
  24447. const copyAndRemove = (toElm, fromElm) => {
  24448. toElm.appendChild(fromElm);
  24449. dom.remove(fromElm, true);
  24450. };
  24451. const [pasteBinElm, ...pasteBinClones] = filter$5(editor.getBody().childNodes, isPasteBin);
  24452. each$e(pasteBinClones, pasteBinClone => {
  24453. copyAndRemove(pasteBinElm, pasteBinClone);
  24454. });
  24455. const dirtyWrappers = dom.select('div[id=mcepastebin]', pasteBinElm);
  24456. for (let i = dirtyWrappers.length - 1; i >= 0; i--) {
  24457. const cleanWrapper = dom.create('div');
  24458. pasteBinElm.insertBefore(cleanWrapper, dirtyWrappers[i]);
  24459. copyAndRemove(cleanWrapper, dirtyWrappers[i]);
  24460. }
  24461. return pasteBinElm ? pasteBinElm.innerHTML : '';
  24462. };
  24463. const isDefaultPasteBinContent = content => content === pasteBinDefaultContent;
  24464. const PasteBin = editor => {
  24465. const lastRng = Cell(null);
  24466. return {
  24467. create: () => create$6(editor, lastRng),
  24468. remove: () => remove(editor, lastRng),
  24469. getEl: () => getEl(editor),
  24470. getHtml: () => getHtml(editor),
  24471. getLastRng: lastRng.get
  24472. };
  24473. };
  24474. const filter$1 = (content, items) => {
  24475. Tools.each(items, v => {
  24476. if (is$4(v, RegExp)) {
  24477. content = content.replace(v, '');
  24478. } else {
  24479. content = content.replace(v[0], v[1]);
  24480. }
  24481. });
  24482. return content;
  24483. };
  24484. const innerText = html => {
  24485. const schema = Schema();
  24486. const domParser = DomParser({}, schema);
  24487. let text = '';
  24488. const voidElements = schema.getVoidElements();
  24489. const ignoreElements = Tools.makeMap('script noscript style textarea video audio iframe object', ' ');
  24490. const blockElements = schema.getBlockElements();
  24491. const walk = node => {
  24492. const name = node.name, currentNode = node;
  24493. if (name === 'br') {
  24494. text += '\n';
  24495. return;
  24496. }
  24497. if (name === 'wbr') {
  24498. return;
  24499. }
  24500. if (voidElements[name]) {
  24501. text += ' ';
  24502. }
  24503. if (ignoreElements[name]) {
  24504. text += ' ';
  24505. return;
  24506. }
  24507. if (node.type === 3) {
  24508. text += node.value;
  24509. }
  24510. if (!(node.name in schema.getVoidElements())) {
  24511. let currentNode = node.firstChild;
  24512. if (currentNode) {
  24513. do {
  24514. walk(currentNode);
  24515. } while (currentNode = currentNode.next);
  24516. }
  24517. }
  24518. if (blockElements[name] && currentNode.next) {
  24519. text += '\n';
  24520. if (name === 'p') {
  24521. text += '\n';
  24522. }
  24523. }
  24524. };
  24525. html = filter$1(html, [/<!\[[^\]]+\]>/g]);
  24526. walk(domParser.parse(html));
  24527. return text;
  24528. };
  24529. const trimHtml = html => {
  24530. const trimSpaces = (all, s1, s2) => {
  24531. if (!s1 && !s2) {
  24532. return ' ';
  24533. }
  24534. return nbsp;
  24535. };
  24536. html = filter$1(html, [
  24537. /^[\s\S]*<body[^>]*>\s*|\s*<\/body[^>]*>[\s\S]*$/ig,
  24538. /<!--StartFragment-->|<!--EndFragment-->/g,
  24539. [
  24540. /( ?)<span class="Apple-converted-space">\u00a0<\/span>( ?)/g,
  24541. trimSpaces
  24542. ],
  24543. /<br class="Apple-interchange-newline">/g,
  24544. /<br>$/i
  24545. ]);
  24546. return html;
  24547. };
  24548. const createIdGenerator = prefix => {
  24549. let count = 0;
  24550. return () => {
  24551. return prefix + count++;
  24552. };
  24553. };
  24554. const getImageMimeType = ext => {
  24555. const lowerExt = ext.toLowerCase();
  24556. const mimeOverrides = {
  24557. jpg: 'jpeg',
  24558. jpe: 'jpeg',
  24559. jfi: 'jpeg',
  24560. jif: 'jpeg',
  24561. jfif: 'jpeg',
  24562. pjpeg: 'jpeg',
  24563. pjp: 'jpeg',
  24564. svg: 'svg+xml'
  24565. };
  24566. return Tools.hasOwn(mimeOverrides, lowerExt) ? 'image/' + mimeOverrides[lowerExt] : 'image/' + lowerExt;
  24567. };
  24568. const preProcess = (editor, html) => {
  24569. const parser = DomParser({ sanitize: shouldSanitizeXss(editor) }, editor.schema);
  24570. parser.addNodeFilter('meta', nodes => {
  24571. Tools.each(nodes, node => {
  24572. node.remove();
  24573. });
  24574. });
  24575. const fragment = parser.parse(html, {
  24576. forced_root_block: false,
  24577. isRootContent: true
  24578. });
  24579. return HtmlSerializer({ validate: true }, editor.schema).serialize(fragment);
  24580. };
  24581. const processResult = (content, cancelled) => ({
  24582. content,
  24583. cancelled
  24584. });
  24585. const postProcessFilter = (editor, html, internal) => {
  24586. const tempBody = editor.dom.create('div', { style: 'display:none' }, html);
  24587. const postProcessArgs = firePastePostProcess(editor, tempBody, internal);
  24588. return processResult(postProcessArgs.node.innerHTML, postProcessArgs.isDefaultPrevented());
  24589. };
  24590. const filterContent = (editor, content, internal) => {
  24591. const preProcessArgs = firePastePreProcess(editor, content, internal);
  24592. const filteredContent = preProcess(editor, preProcessArgs.content);
  24593. if (editor.hasEventListeners('PastePostProcess') && !preProcessArgs.isDefaultPrevented()) {
  24594. return postProcessFilter(editor, filteredContent, internal);
  24595. } else {
  24596. return processResult(filteredContent, preProcessArgs.isDefaultPrevented());
  24597. }
  24598. };
  24599. const process = (editor, html, internal) => {
  24600. return filterContent(editor, html, internal);
  24601. };
  24602. const pasteHtml$1 = (editor, html) => {
  24603. editor.insertContent(html, {
  24604. merge: shouldPasteMergeFormats(editor),
  24605. paste: true
  24606. });
  24607. return true;
  24608. };
  24609. const isAbsoluteUrl = url => /^https?:\/\/[\w\-\/+=.,!;:&%@^~(){}?#]+$/i.test(url);
  24610. const isImageUrl = (editor, url) => {
  24611. return isAbsoluteUrl(url) && exists(getAllowedImageFileTypes(editor), type => endsWith(url.toLowerCase(), `.${ type.toLowerCase() }`));
  24612. };
  24613. const createImage = (editor, url, pasteHtmlFn) => {
  24614. editor.undoManager.extra(() => {
  24615. pasteHtmlFn(editor, url);
  24616. }, () => {
  24617. editor.insertContent('<img src="' + url + '">');
  24618. });
  24619. return true;
  24620. };
  24621. const createLink = (editor, url, pasteHtmlFn) => {
  24622. editor.undoManager.extra(() => {
  24623. pasteHtmlFn(editor, url);
  24624. }, () => {
  24625. editor.execCommand('mceInsertLink', false, url);
  24626. });
  24627. return true;
  24628. };
  24629. const linkSelection = (editor, html, pasteHtmlFn) => !editor.selection.isCollapsed() && isAbsoluteUrl(html) ? createLink(editor, html, pasteHtmlFn) : false;
  24630. const insertImage = (editor, html, pasteHtmlFn) => isImageUrl(editor, html) ? createImage(editor, html, pasteHtmlFn) : false;
  24631. const smartInsertContent = (editor, html) => {
  24632. Tools.each([
  24633. linkSelection,
  24634. insertImage,
  24635. pasteHtml$1
  24636. ], action => {
  24637. return !action(editor, html, pasteHtml$1);
  24638. });
  24639. };
  24640. const insertContent = (editor, html, pasteAsText) => {
  24641. if (pasteAsText || !isSmartPasteEnabled(editor)) {
  24642. pasteHtml$1(editor, html);
  24643. } else {
  24644. smartInsertContent(editor, html);
  24645. }
  24646. };
  24647. const uniqueId = createIdGenerator('mceclip');
  24648. const doPaste = (editor, content, internal, pasteAsText) => {
  24649. const args = process(editor, content, internal);
  24650. if (!args.cancelled) {
  24651. insertContent(editor, args.content, pasteAsText);
  24652. }
  24653. };
  24654. const pasteHtml = (editor, html, internalFlag) => {
  24655. const internal = internalFlag ? internalFlag : isMarked(html);
  24656. doPaste(editor, unmark(html), internal, false);
  24657. };
  24658. const pasteText = (editor, text) => {
  24659. const encodedText = editor.dom.encode(text).replace(/\r\n/g, '\n');
  24660. const normalizedText = normalize$4(encodedText, getPasteTabSpaces(editor));
  24661. const html = toBlockElements(normalizedText, getForcedRootBlock(editor), getForcedRootBlockAttrs(editor));
  24662. doPaste(editor, html, false, true);
  24663. };
  24664. const getDataTransferItems = dataTransfer => {
  24665. const items = {};
  24666. if (dataTransfer && dataTransfer.types) {
  24667. for (let i = 0; i < dataTransfer.types.length; i++) {
  24668. const contentType = dataTransfer.types[i];
  24669. try {
  24670. items[contentType] = dataTransfer.getData(contentType);
  24671. } catch (ex) {
  24672. items[contentType] = '';
  24673. }
  24674. }
  24675. }
  24676. return items;
  24677. };
  24678. const hasContentType = (clipboardContent, mimeType) => mimeType in clipboardContent && clipboardContent[mimeType].length > 0;
  24679. const hasHtmlOrText = content => hasContentType(content, 'text/html') || hasContentType(content, 'text/plain');
  24680. const extractFilename = (editor, str) => {
  24681. const m = str.match(/([\s\S]+?)(?:\.[a-z0-9.]+)$/i);
  24682. return isNonNullable(m) ? editor.dom.encode(m[1]) : undefined;
  24683. };
  24684. const createBlobInfo = (editor, blobCache, file, base64) => {
  24685. const id = uniqueId();
  24686. const useFileName = shouldReuseFileName(editor) && isNonNullable(file.name);
  24687. const name = useFileName ? extractFilename(editor, file.name) : id;
  24688. const filename = useFileName ? file.name : undefined;
  24689. const blobInfo = blobCache.create(id, file, base64, name, filename);
  24690. blobCache.add(blobInfo);
  24691. return blobInfo;
  24692. };
  24693. const pasteImage = (editor, imageItem) => {
  24694. parseDataUri(imageItem.uri).each(({data, type, base64Encoded}) => {
  24695. const base64 = base64Encoded ? data : btoa(data);
  24696. const file = imageItem.file;
  24697. const blobCache = editor.editorUpload.blobCache;
  24698. const existingBlobInfo = blobCache.getByData(base64, type);
  24699. const blobInfo = existingBlobInfo !== null && existingBlobInfo !== void 0 ? existingBlobInfo : createBlobInfo(editor, blobCache, file, base64);
  24700. pasteHtml(editor, `<img src="${ blobInfo.blobUri() }">`, false);
  24701. });
  24702. };
  24703. const isClipboardEvent = event => event.type === 'paste';
  24704. const readFilesAsDataUris = items => Promise.all(map$3(items, file => {
  24705. return blobToDataUri(file).then(uri => ({
  24706. file,
  24707. uri
  24708. }));
  24709. }));
  24710. const isImage = editor => {
  24711. const allowedExtensions = getAllowedImageFileTypes(editor);
  24712. return file => startsWith(file.type, 'image/') && exists(allowedExtensions, extension => {
  24713. return getImageMimeType(extension) === file.type;
  24714. });
  24715. };
  24716. const getImagesFromDataTransfer = (editor, dataTransfer) => {
  24717. const items = dataTransfer.items ? bind$3(from(dataTransfer.items), item => {
  24718. return item.kind === 'file' ? [item.getAsFile()] : [];
  24719. }) : [];
  24720. const files = dataTransfer.files ? from(dataTransfer.files) : [];
  24721. return filter$5(items.length > 0 ? items : files, isImage(editor));
  24722. };
  24723. const pasteImageData = (editor, e, rng) => {
  24724. const dataTransfer = isClipboardEvent(e) ? e.clipboardData : e.dataTransfer;
  24725. if (shouldPasteDataImages(editor) && dataTransfer) {
  24726. const images = getImagesFromDataTransfer(editor, dataTransfer);
  24727. if (images.length > 0) {
  24728. e.preventDefault();
  24729. readFilesAsDataUris(images).then(fileResults => {
  24730. if (rng) {
  24731. editor.selection.setRng(rng);
  24732. }
  24733. each$e(fileResults, result => {
  24734. pasteImage(editor, result);
  24735. });
  24736. });
  24737. return true;
  24738. }
  24739. }
  24740. return false;
  24741. };
  24742. const isBrokenAndroidClipboardEvent = e => {
  24743. var _a, _b;
  24744. 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;
  24745. };
  24746. const isKeyboardPasteEvent = e => VK.metaKeyPressed(e) && e.keyCode === 86 || e.shiftKey && e.keyCode === 45;
  24747. const insertClipboardContent = (editor, clipboardContent, html, plainTextMode) => {
  24748. let content = trimHtml(html);
  24749. const isInternal = hasContentType(clipboardContent, internalHtmlMime()) || isMarked(html);
  24750. const isPlainTextHtml = !isInternal && isPlainText(content);
  24751. const isAbsoluteUrl$1 = isAbsoluteUrl(content);
  24752. if (isDefaultPasteBinContent(content) || !content.length || isPlainTextHtml && !isAbsoluteUrl$1) {
  24753. plainTextMode = true;
  24754. }
  24755. if (plainTextMode || isAbsoluteUrl$1) {
  24756. if (hasContentType(clipboardContent, 'text/plain') && isPlainTextHtml) {
  24757. content = clipboardContent['text/plain'];
  24758. } else {
  24759. content = innerText(content);
  24760. }
  24761. }
  24762. if (isDefaultPasteBinContent(content)) {
  24763. return;
  24764. }
  24765. if (plainTextMode) {
  24766. pasteText(editor, content);
  24767. } else {
  24768. pasteHtml(editor, content, isInternal);
  24769. }
  24770. };
  24771. const registerEventHandlers = (editor, pasteBin, pasteFormat) => {
  24772. let keyboardPastePlainTextState;
  24773. const getLastRng = () => pasteBin.getLastRng() || editor.selection.getRng();
  24774. editor.on('keydown', e => {
  24775. if (isKeyboardPasteEvent(e) && !e.isDefaultPrevented()) {
  24776. keyboardPastePlainTextState = e.shiftKey && e.keyCode === 86;
  24777. }
  24778. });
  24779. editor.on('paste', e => {
  24780. if (e.isDefaultPrevented() || isBrokenAndroidClipboardEvent(e)) {
  24781. return;
  24782. }
  24783. const plainTextMode = pasteFormat.get() === 'text' || keyboardPastePlainTextState;
  24784. keyboardPastePlainTextState = false;
  24785. const clipboardContent = getDataTransferItems(e.clipboardData);
  24786. if (!hasHtmlOrText(clipboardContent) && pasteImageData(editor, e, getLastRng())) {
  24787. return;
  24788. }
  24789. if (hasContentType(clipboardContent, 'text/html')) {
  24790. e.preventDefault();
  24791. insertClipboardContent(editor, clipboardContent, clipboardContent['text/html'], plainTextMode);
  24792. } else if (hasContentType(clipboardContent, 'text/plain') && hasContentType(clipboardContent, 'text/uri-list')) {
  24793. e.preventDefault();
  24794. insertClipboardContent(editor, clipboardContent, clipboardContent['text/plain'], plainTextMode);
  24795. } else {
  24796. pasteBin.create();
  24797. Delay.setEditorTimeout(editor, () => {
  24798. const html = pasteBin.getHtml();
  24799. pasteBin.remove();
  24800. insertClipboardContent(editor, clipboardContent, html, plainTextMode);
  24801. }, 0);
  24802. }
  24803. });
  24804. };
  24805. const registerDataImageFilter = editor => {
  24806. const isWebKitFakeUrl = src => startsWith(src, 'webkit-fake-url');
  24807. const isDataUri = src => startsWith(src, 'data:');
  24808. const isPasteInsert = args => {
  24809. var _a;
  24810. return ((_a = args.data) === null || _a === void 0 ? void 0 : _a.paste) === true;
  24811. };
  24812. editor.parser.addNodeFilter('img', (nodes, name, args) => {
  24813. if (!shouldPasteDataImages(editor) && isPasteInsert(args)) {
  24814. for (const node of nodes) {
  24815. const src = node.attr('src');
  24816. if (isString(src) && !node.attr('data-mce-object') && src !== Env.transparentSrc) {
  24817. if (isWebKitFakeUrl(src)) {
  24818. node.remove();
  24819. } else if (!shouldAllowHtmlDataUrls(editor) && isDataUri(src)) {
  24820. node.remove();
  24821. }
  24822. }
  24823. }
  24824. }
  24825. });
  24826. };
  24827. const registerEventsAndFilters = (editor, pasteBin, pasteFormat) => {
  24828. registerEventHandlers(editor, pasteBin, pasteFormat);
  24829. registerDataImageFilter(editor);
  24830. };
  24831. const togglePlainTextPaste = (editor, pasteFormat) => {
  24832. if (pasteFormat.get() === 'text') {
  24833. pasteFormat.set('html');
  24834. firePastePlainTextToggle(editor, false);
  24835. } else {
  24836. pasteFormat.set('text');
  24837. firePastePlainTextToggle(editor, true);
  24838. }
  24839. editor.focus();
  24840. };
  24841. const register$1 = (editor, pasteFormat) => {
  24842. editor.addCommand('mceTogglePlainTextPaste', () => {
  24843. togglePlainTextPaste(editor, pasteFormat);
  24844. });
  24845. editor.addCommand('mceInsertClipboardContent', (ui, value) => {
  24846. if (value.html) {
  24847. pasteHtml(editor, value.html, value.internal);
  24848. }
  24849. if (value.text) {
  24850. pasteText(editor, value.text);
  24851. }
  24852. });
  24853. };
  24854. const setHtml5Clipboard = (clipboardData, html, text) => {
  24855. if (clipboardData) {
  24856. try {
  24857. clipboardData.clearData();
  24858. clipboardData.setData('text/html', html);
  24859. clipboardData.setData('text/plain', text);
  24860. clipboardData.setData(internalHtmlMime(), html);
  24861. return true;
  24862. } catch (e) {
  24863. return false;
  24864. }
  24865. } else {
  24866. return false;
  24867. }
  24868. };
  24869. const setClipboardData = (evt, data, fallback, done) => {
  24870. if (setHtml5Clipboard(evt.clipboardData, data.html, data.text)) {
  24871. evt.preventDefault();
  24872. done();
  24873. } else {
  24874. fallback(data.html, done);
  24875. }
  24876. };
  24877. const fallback$1 = editor => (html, done) => {
  24878. const {dom, selection} = editor;
  24879. const outer = dom.create('div', {
  24880. 'contenteditable': 'false',
  24881. 'data-mce-bogus': 'all'
  24882. });
  24883. const inner = dom.create('div', { contenteditable: 'true' }, html);
  24884. dom.setStyles(outer, {
  24885. position: 'fixed',
  24886. top: '0',
  24887. left: '-3000px',
  24888. width: '1000px',
  24889. overflow: 'hidden'
  24890. });
  24891. outer.appendChild(inner);
  24892. dom.add(editor.getBody(), outer);
  24893. const range = selection.getRng();
  24894. inner.focus();
  24895. const offscreenRange = dom.createRng();
  24896. offscreenRange.selectNodeContents(inner);
  24897. selection.setRng(offscreenRange);
  24898. Delay.setEditorTimeout(editor, () => {
  24899. selection.setRng(range);
  24900. dom.remove(outer);
  24901. done();
  24902. }, 0);
  24903. };
  24904. const getData = editor => ({
  24905. html: mark(editor.selection.getContent({ contextual: true })),
  24906. text: editor.selection.getContent({ format: 'text' })
  24907. });
  24908. const isTableSelection = editor => !!editor.dom.getParent(editor.selection.getStart(), 'td[data-mce-selected],th[data-mce-selected]', editor.getBody());
  24909. const hasSelectedContent = editor => !editor.selection.isCollapsed() || isTableSelection(editor);
  24910. const cut = editor => evt => {
  24911. if (!evt.isDefaultPrevented() && hasSelectedContent(editor)) {
  24912. setClipboardData(evt, getData(editor), fallback$1(editor), () => {
  24913. if (Env.browser.isChromium() || Env.browser.isFirefox()) {
  24914. const rng = editor.selection.getRng();
  24915. Delay.setEditorTimeout(editor, () => {
  24916. editor.selection.setRng(rng);
  24917. editor.execCommand('Delete');
  24918. }, 0);
  24919. } else {
  24920. editor.execCommand('Delete');
  24921. }
  24922. });
  24923. }
  24924. };
  24925. const copy = editor => evt => {
  24926. if (!evt.isDefaultPrevented() && hasSelectedContent(editor)) {
  24927. setClipboardData(evt, getData(editor), fallback$1(editor), noop);
  24928. }
  24929. };
  24930. const register = editor => {
  24931. editor.on('cut', cut(editor));
  24932. editor.on('copy', copy(editor));
  24933. };
  24934. const getCaretRangeFromEvent = (editor, e) => {
  24935. var _a, _b;
  24936. return RangeUtils.getCaretRangeFromPoint((_a = e.clientX) !== null && _a !== void 0 ? _a : 0, (_b = e.clientY) !== null && _b !== void 0 ? _b : 0, editor.getDoc());
  24937. };
  24938. const isPlainTextFileUrl = content => {
  24939. const plainTextContent = content['text/plain'];
  24940. return plainTextContent ? plainTextContent.indexOf('file://') === 0 : false;
  24941. };
  24942. const setFocusedRange = (editor, rng) => {
  24943. editor.focus();
  24944. if (rng) {
  24945. editor.selection.setRng(rng);
  24946. }
  24947. };
  24948. const hasImage = dataTransfer => exists(dataTransfer.files, file => /^image\//.test(file.type));
  24949. const isTransparentBlockDrop = (dom, schema, target, dropContent) => {
  24950. const parentTransparent = dom.getParent(target, node => isTransparentBlock(schema, node));
  24951. if (parentTransparent && has$2(dropContent, 'text/html')) {
  24952. const fragment = new DOMParser().parseFromString(dropContent['text/html'], 'text/html').body;
  24953. return !isNull(fragment.querySelector(parentTransparent.nodeName.toLowerCase()));
  24954. } else {
  24955. return false;
  24956. }
  24957. };
  24958. const setup$a = (editor, draggingInternallyState) => {
  24959. if (shouldPasteBlockDrop(editor)) {
  24960. editor.on('dragend dragover draggesture dragdrop drop drag', e => {
  24961. e.preventDefault();
  24962. e.stopPropagation();
  24963. });
  24964. }
  24965. if (!shouldPasteDataImages(editor)) {
  24966. editor.on('drop', e => {
  24967. const dataTransfer = e.dataTransfer;
  24968. if (dataTransfer && hasImage(dataTransfer)) {
  24969. e.preventDefault();
  24970. }
  24971. });
  24972. }
  24973. editor.on('drop', e => {
  24974. if (e.isDefaultPrevented()) {
  24975. return;
  24976. }
  24977. const rng = getCaretRangeFromEvent(editor, e);
  24978. if (isNullable(rng)) {
  24979. return;
  24980. }
  24981. const dropContent = getDataTransferItems(e.dataTransfer);
  24982. const internal = hasContentType(dropContent, internalHtmlMime());
  24983. if ((!hasHtmlOrText(dropContent) || isPlainTextFileUrl(dropContent)) && pasteImageData(editor, e, rng)) {
  24984. return;
  24985. }
  24986. const internalContent = dropContent[internalHtmlMime()];
  24987. const content = internalContent || dropContent['text/html'] || dropContent['text/plain'];
  24988. const transparentElementDrop = isTransparentBlockDrop(editor.dom, editor.schema, rng.startContainer, dropContent);
  24989. if (draggingInternallyState.get() && !transparentElementDrop) {
  24990. return;
  24991. }
  24992. if (content) {
  24993. e.preventDefault();
  24994. Delay.setEditorTimeout(editor, () => {
  24995. editor.undoManager.transact(() => {
  24996. if (internalContent) {
  24997. editor.execCommand('Delete');
  24998. }
  24999. setFocusedRange(editor, rng);
  25000. const trimmedContent = trimHtml(content);
  25001. if (dropContent['text/html']) {
  25002. pasteHtml(editor, trimmedContent, internal);
  25003. } else {
  25004. pasteText(editor, trimmedContent);
  25005. }
  25006. });
  25007. });
  25008. }
  25009. });
  25010. editor.on('dragstart', _e => {
  25011. draggingInternallyState.set(true);
  25012. });
  25013. editor.on('dragover dragend', e => {
  25014. if (shouldPasteDataImages(editor) && !draggingInternallyState.get()) {
  25015. e.preventDefault();
  25016. setFocusedRange(editor, getCaretRangeFromEvent(editor, e));
  25017. }
  25018. if (e.type === 'dragend') {
  25019. draggingInternallyState.set(false);
  25020. }
  25021. });
  25022. };
  25023. const setup$9 = editor => {
  25024. const processEvent = f => e => {
  25025. f(editor, e);
  25026. };
  25027. const preProcess = getPastePreProcess(editor);
  25028. if (isFunction(preProcess)) {
  25029. editor.on('PastePreProcess', processEvent(preProcess));
  25030. }
  25031. const postProcess = getPastePostProcess(editor);
  25032. if (isFunction(postProcess)) {
  25033. editor.on('PastePostProcess', processEvent(postProcess));
  25034. }
  25035. };
  25036. const addPreProcessFilter = (editor, filterFunc) => {
  25037. editor.on('PastePreProcess', e => {
  25038. e.content = filterFunc(editor, e.content, e.internal);
  25039. });
  25040. };
  25041. const rgbRegExp = /rgb\s*\(\s*([0-9]+)\s*,\s*([0-9]+)\s*,\s*([0-9]+)\s*\)/gi;
  25042. const rgbToHex = value => Tools.trim(value).replace(rgbRegExp, rgbaToHexString).toLowerCase();
  25043. const removeWebKitStyles = (editor, content, internal) => {
  25044. const webKitStylesOption = getPasteWebkitStyles(editor);
  25045. if (internal || webKitStylesOption === 'all' || !shouldPasteRemoveWebKitStyles(editor)) {
  25046. return content;
  25047. }
  25048. const webKitStyles = webKitStylesOption ? webKitStylesOption.split(/[, ]/) : [];
  25049. if (webKitStyles && webKitStylesOption !== 'none') {
  25050. const dom = editor.dom, node = editor.selection.getNode();
  25051. content = content.replace(/(<[^>]+) style="([^"]*)"([^>]*>)/gi, (all, before, value, after) => {
  25052. const inputStyles = dom.parseStyle(dom.decode(value));
  25053. const outputStyles = {};
  25054. for (let i = 0; i < webKitStyles.length; i++) {
  25055. const inputValue = inputStyles[webKitStyles[i]];
  25056. let compareInput = inputValue;
  25057. let currentValue = dom.getStyle(node, webKitStyles[i], true);
  25058. if (/color/.test(webKitStyles[i])) {
  25059. compareInput = rgbToHex(compareInput);
  25060. currentValue = rgbToHex(currentValue);
  25061. }
  25062. if (currentValue !== compareInput) {
  25063. outputStyles[webKitStyles[i]] = inputValue;
  25064. }
  25065. }
  25066. const outputStyle = dom.serializeStyle(outputStyles, 'span');
  25067. if (outputStyle) {
  25068. return before + ' style="' + outputStyle + '"' + after;
  25069. }
  25070. return before + after;
  25071. });
  25072. } else {
  25073. content = content.replace(/(<[^>]+) style="([^"]*)"([^>]*>)/gi, '$1$3');
  25074. }
  25075. content = content.replace(/(<[^>]+) data-mce-style="([^"]+)"([^>]*>)/gi, (all, before, value, after) => {
  25076. return before + ' style="' + value + '"' + after;
  25077. });
  25078. return content;
  25079. };
  25080. const setup$8 = editor => {
  25081. if (Env.browser.isChromium() || Env.browser.isSafari()) {
  25082. addPreProcessFilter(editor, removeWebKitStyles);
  25083. }
  25084. };
  25085. const setup$7 = editor => {
  25086. const draggingInternallyState = Cell(false);
  25087. const pasteFormat = Cell(isPasteAsTextEnabled(editor) ? 'text' : 'html');
  25088. const pasteBin = PasteBin(editor);
  25089. setup$8(editor);
  25090. register$1(editor, pasteFormat);
  25091. setup$9(editor);
  25092. editor.on('PreInit', () => {
  25093. register(editor);
  25094. setup$a(editor, draggingInternallyState);
  25095. registerEventsAndFilters(editor, pasteBin, pasteFormat);
  25096. });
  25097. };
  25098. const preventSummaryToggle = editor => {
  25099. editor.on('click', e => {
  25100. if (editor.dom.getParent(e.target, 'details')) {
  25101. e.preventDefault();
  25102. }
  25103. });
  25104. };
  25105. const filterDetails = editor => {
  25106. editor.parser.addNodeFilter('details', elms => {
  25107. each$e(elms, details => {
  25108. details.attr('data-mce-open', details.attr('open'));
  25109. details.attr('open', 'open');
  25110. });
  25111. });
  25112. editor.serializer.addNodeFilter('details', elms => {
  25113. each$e(elms, details => {
  25114. const open = details.attr('data-mce-open');
  25115. details.attr('open', isString(open) ? open : null);
  25116. details.attr('data-mce-open', null);
  25117. });
  25118. });
  25119. };
  25120. const setup$6 = editor => {
  25121. preventSummaryToggle(editor);
  25122. filterDetails(editor);
  25123. };
  25124. const isBr = isBr$6;
  25125. const isText = isText$a;
  25126. const isContentEditableFalse$2 = elm => isContentEditableFalse$b(elm.dom);
  25127. const isContentEditableTrue = elm => isContentEditableTrue$3(elm.dom);
  25128. const isRoot = rootNode => elm => eq(SugarElement.fromDom(rootNode), elm);
  25129. const getClosestScope = (node, rootNode) => closest$4(SugarElement.fromDom(node), elm => isContentEditableTrue(elm) || isBlock$2(elm), isRoot(rootNode)).getOr(SugarElement.fromDom(rootNode)).dom;
  25130. const getClosestCef = (node, rootNode) => closest$4(SugarElement.fromDom(node), isContentEditableFalse$2, isRoot(rootNode));
  25131. const findEdgeCaretCandidate = (startNode, scope, forward) => {
  25132. const walker = new DomTreeWalker(startNode, scope);
  25133. const next = forward ? walker.next.bind(walker) : walker.prev.bind(walker);
  25134. let result = startNode;
  25135. for (let current = forward ? startNode : next(); current && !isBr(current); current = next()) {
  25136. if (isCaretCandidate$3(current)) {
  25137. result = current;
  25138. }
  25139. }
  25140. return result;
  25141. };
  25142. const findClosestBlockRange = (startRng, rootNode) => {
  25143. const startPos = CaretPosition.fromRangeStart(startRng);
  25144. const clickNode = startPos.getNode();
  25145. const scope = getClosestScope(clickNode, rootNode);
  25146. const startNode = findEdgeCaretCandidate(clickNode, scope, false);
  25147. const endNode = findEdgeCaretCandidate(clickNode, scope, true);
  25148. const rng = document.createRange();
  25149. getClosestCef(startNode, scope).fold(() => {
  25150. if (isText(startNode)) {
  25151. rng.setStart(startNode, 0);
  25152. } else {
  25153. rng.setStartBefore(startNode);
  25154. }
  25155. }, cef => rng.setStartBefore(cef.dom));
  25156. getClosestCef(endNode, scope).fold(() => {
  25157. if (isText(endNode)) {
  25158. rng.setEnd(endNode, endNode.data.length);
  25159. } else {
  25160. rng.setEndAfter(endNode);
  25161. }
  25162. }, cef => rng.setEndAfter(cef.dom));
  25163. return rng;
  25164. };
  25165. const onTripleClickSelect = editor => {
  25166. const rng = findClosestBlockRange(editor.selection.getRng(), editor.getBody());
  25167. editor.selection.setRng(normalize(rng));
  25168. };
  25169. const setup$5 = editor => {
  25170. editor.on('mousedown', e => {
  25171. if (e.detail >= 3) {
  25172. e.preventDefault();
  25173. onTripleClickSelect(editor);
  25174. }
  25175. });
  25176. };
  25177. var FakeCaretPosition;
  25178. (function (FakeCaretPosition) {
  25179. FakeCaretPosition['Before'] = 'before';
  25180. FakeCaretPosition['After'] = 'after';
  25181. }(FakeCaretPosition || (FakeCaretPosition = {})));
  25182. const distanceToRectLeft = (clientRect, clientX) => Math.abs(clientRect.left - clientX);
  25183. const distanceToRectRight = (clientRect, clientX) => Math.abs(clientRect.right - clientX);
  25184. const isInsideY = (clientY, clientRect) => clientY >= clientRect.top && clientY <= clientRect.bottom;
  25185. const collidesY = (r1, r2) => r1.top < r2.bottom && r1.bottom > r2.top;
  25186. const isOverlapping = (r1, r2) => {
  25187. const overlap = overlapY(r1, r2) / Math.min(r1.height, r2.height);
  25188. return collidesY(r1, r2) && overlap > 0.5;
  25189. };
  25190. const splitRectsPerAxis = (rects, y) => {
  25191. const intersectingRects = filter$5(rects, rect => isInsideY(y, rect));
  25192. return boundingClientRectFromRects(intersectingRects).fold(() => [
  25193. [],
  25194. rects
  25195. ], boundingRect => {
  25196. const {
  25197. pass: horizontal,
  25198. fail: vertical
  25199. } = partition$2(rects, rect => isOverlapping(rect, boundingRect));
  25200. return [
  25201. horizontal,
  25202. vertical
  25203. ];
  25204. });
  25205. };
  25206. const clientInfo = (rect, clientX) => {
  25207. return {
  25208. node: rect.node,
  25209. position: distanceToRectLeft(rect, clientX) < distanceToRectRight(rect, clientX) ? FakeCaretPosition.Before : FakeCaretPosition.After
  25210. };
  25211. };
  25212. const horizontalDistance = (rect, x, _y) => x > rect.left && x < rect.right ? 0 : Math.min(Math.abs(rect.left - x), Math.abs(rect.right - x));
  25213. const closestChildCaretCandidateNodeRect = (children, clientX, clientY) => {
  25214. const caretCandidateRect = rect => {
  25215. if (isCaretCandidate$3(rect.node)) {
  25216. return Optional.some(rect);
  25217. } else if (isElement$6(rect.node)) {
  25218. return closestChildCaretCandidateNodeRect(from(rect.node.childNodes), clientX, clientY);
  25219. } else {
  25220. return Optional.none();
  25221. }
  25222. };
  25223. const getClosestTextNode = (rects, distance) => {
  25224. if (rects.length >= 2) {
  25225. const r1 = caretCandidateRect(rects[0]).getOr(rects[0]);
  25226. const r2 = caretCandidateRect(rects[1]).getOr(rects[1]);
  25227. const deltaDistance = Math.abs(distance(r1, clientX, clientY) - distance(r2, clientX, clientY));
  25228. if (deltaDistance < 2) {
  25229. if (isText$a(r1.node)) {
  25230. return Optional.some(r1);
  25231. } else if (isText$a(r2.node)) {
  25232. return Optional.some(r2);
  25233. }
  25234. }
  25235. }
  25236. return Optional.none();
  25237. };
  25238. const findClosestCaretCandidateNodeRect = (rects, distance) => {
  25239. const sortedRects = sort(rects, (r1, r2) => distance(r1, clientX, clientY) - distance(r2, clientX, clientY));
  25240. return getClosestTextNode(sortedRects, distance).orThunk(() => findMap(sortedRects, caretCandidateRect));
  25241. };
  25242. const [horizontalRects, verticalRects] = splitRectsPerAxis(getClientRects(children), clientY);
  25243. const {
  25244. pass: above,
  25245. fail: below
  25246. } = partition$2(verticalRects, rect => rect.top < clientY);
  25247. return findClosestCaretCandidateNodeRect(horizontalRects, horizontalDistance).orThunk(() => findClosestCaretCandidateNodeRect(below, distanceToRectEdgeFromXY)).orThunk(() => findClosestCaretCandidateNodeRect(above, distanceToRectEdgeFromXY));
  25248. };
  25249. const traverseUp = (rootElm, scope, clientX, clientY) => {
  25250. const helper = (scope, prevScope) => {
  25251. const isDragGhostContainer = node => isElement$6(node) && node.classList.contains('mce-drag-container');
  25252. const childNodesWithoutGhost = filter$5(scope.dom.childNodes, not(isDragGhostContainer));
  25253. return prevScope.fold(() => closestChildCaretCandidateNodeRect(childNodesWithoutGhost, clientX, clientY), prevScope => {
  25254. const uncheckedChildren = filter$5(childNodesWithoutGhost, node => node !== prevScope.dom);
  25255. return closestChildCaretCandidateNodeRect(uncheckedChildren, clientX, clientY);
  25256. }).orThunk(() => {
  25257. const parent = eq(scope, rootElm) ? Optional.none() : parentElement(scope);
  25258. return parent.bind(newScope => helper(newScope, Optional.some(scope)));
  25259. });
  25260. };
  25261. return helper(scope, Optional.none());
  25262. };
  25263. const closestCaretCandidateNodeRect = (root, clientX, clientY) => {
  25264. const rootElm = SugarElement.fromDom(root);
  25265. const ownerDoc = documentOrOwner(rootElm);
  25266. const elementAtPoint = SugarElement.fromPoint(ownerDoc, clientX, clientY).filter(elm => contains(rootElm, elm));
  25267. const element = elementAtPoint.getOr(rootElm);
  25268. return traverseUp(rootElm, element, clientX, clientY);
  25269. };
  25270. const closestFakeCaretCandidate = (root, clientX, clientY) => closestCaretCandidateNodeRect(root, clientX, clientY).filter(rect => isFakeCaretTarget(rect.node)).map(rect => clientInfo(rect, clientX));
  25271. const getAbsolutePosition = elm => {
  25272. var _a, _b;
  25273. const clientRect = elm.getBoundingClientRect();
  25274. const doc = elm.ownerDocument;
  25275. const docElem = doc.documentElement;
  25276. const win = doc.defaultView;
  25277. return {
  25278. top: clientRect.top + ((_a = win === null || win === void 0 ? void 0 : win.scrollY) !== null && _a !== void 0 ? _a : 0) - docElem.clientTop,
  25279. left: clientRect.left + ((_b = win === null || win === void 0 ? void 0 : win.scrollX) !== null && _b !== void 0 ? _b : 0) - docElem.clientLeft
  25280. };
  25281. };
  25282. const getBodyPosition = editor => editor.inline ? getAbsolutePosition(editor.getBody()) : {
  25283. left: 0,
  25284. top: 0
  25285. };
  25286. const getScrollPosition = editor => {
  25287. const body = editor.getBody();
  25288. return editor.inline ? {
  25289. left: body.scrollLeft,
  25290. top: body.scrollTop
  25291. } : {
  25292. left: 0,
  25293. top: 0
  25294. };
  25295. };
  25296. const getBodyScroll = editor => {
  25297. const body = editor.getBody(), docElm = editor.getDoc().documentElement;
  25298. const inlineScroll = {
  25299. left: body.scrollLeft,
  25300. top: body.scrollTop
  25301. };
  25302. const iframeScroll = {
  25303. left: body.scrollLeft || docElm.scrollLeft,
  25304. top: body.scrollTop || docElm.scrollTop
  25305. };
  25306. return editor.inline ? inlineScroll : iframeScroll;
  25307. };
  25308. const getMousePosition = (editor, event) => {
  25309. if (event.target.ownerDocument !== editor.getDoc()) {
  25310. const iframePosition = getAbsolutePosition(editor.getContentAreaContainer());
  25311. const scrollPosition = getBodyScroll(editor);
  25312. return {
  25313. left: event.pageX - iframePosition.left + scrollPosition.left,
  25314. top: event.pageY - iframePosition.top + scrollPosition.top
  25315. };
  25316. }
  25317. return {
  25318. left: event.pageX,
  25319. top: event.pageY
  25320. };
  25321. };
  25322. const calculatePosition = (bodyPosition, scrollPosition, mousePosition) => ({
  25323. pageX: mousePosition.left - bodyPosition.left + scrollPosition.left,
  25324. pageY: mousePosition.top - bodyPosition.top + scrollPosition.top
  25325. });
  25326. const calc = (editor, event) => calculatePosition(getBodyPosition(editor), getScrollPosition(editor), getMousePosition(editor, event));
  25327. const makeDndEventFromMouseEvent = (type, mouseEvent, extra) => ({
  25328. ...mouseEvent,
  25329. dataTransfer: null,
  25330. type,
  25331. ...extra
  25332. });
  25333. const makeDndEvent = (type, props) => {
  25334. const fail = die('Function not supported on simulated event.');
  25335. const event = {
  25336. bubbles: true,
  25337. cancelBubble: false,
  25338. cancelable: true,
  25339. composed: false,
  25340. currentTarget: null,
  25341. defaultPrevented: false,
  25342. eventPhase: 0,
  25343. isTrusted: true,
  25344. returnValue: false,
  25345. srcElement: null,
  25346. target: null,
  25347. timeStamp: 0,
  25348. type,
  25349. composedPath: fail,
  25350. initEvent: fail,
  25351. preventDefault: noop,
  25352. stopImmediatePropagation: noop,
  25353. stopPropagation: noop,
  25354. AT_TARGET: window.Event.AT_TARGET,
  25355. BUBBLING_PHASE: window.Event.BUBBLING_PHASE,
  25356. CAPTURING_PHASE: window.Event.CAPTURING_PHASE,
  25357. NONE: window.Event.NONE,
  25358. altKey: false,
  25359. button: 0,
  25360. buttons: 0,
  25361. clientX: 0,
  25362. clientY: 0,
  25363. ctrlKey: false,
  25364. metaKey: false,
  25365. movementX: 0,
  25366. movementY: 0,
  25367. offsetX: 0,
  25368. offsetY: 0,
  25369. pageX: 0,
  25370. pageY: 0,
  25371. relatedTarget: null,
  25372. screenX: 0,
  25373. screenY: 0,
  25374. shiftKey: false,
  25375. x: 0,
  25376. y: 0,
  25377. detail: 0,
  25378. view: null,
  25379. which: 0,
  25380. initUIEvent: fail,
  25381. initMouseEvent: fail,
  25382. getModifierState: fail,
  25383. dataTransfer: null,
  25384. ...props
  25385. };
  25386. return event;
  25387. };
  25388. const fallback = target => ({
  25389. target,
  25390. srcElement: target
  25391. });
  25392. const dndEvent = type => target => makeDndEvent(type, fallback(target));
  25393. const dndEventFromMouseEvent = type => (mouseEvent, target) => makeDndEventFromMouseEvent(type, mouseEvent, fallback(target));
  25394. const makeDragstartEventFromMouseEvent = dndEventFromMouseEvent('dragstart');
  25395. const makeDropEventFromMouseEvent = dndEventFromMouseEvent('drop');
  25396. const makeDragendEvent = dndEvent('dragend');
  25397. const makeDragendEventFromMouseEvent = dndEventFromMouseEvent('dragend');
  25398. const scrollPixelsPerInterval = 32;
  25399. const scrollIntervalValue = 100;
  25400. const mouseRangeToTriggerScrollInsideEditor = 8;
  25401. const mouseRangeToTriggerScrollOutsideEditor = 16;
  25402. const isContentEditableFalse$1 = isContentEditableFalse$b;
  25403. const isContentEditable = or(isContentEditableFalse$1, isContentEditableTrue$3);
  25404. const isDraggable = (dom, rootElm, elm) => isContentEditableFalse$1(elm) && elm !== rootElm && dom.isEditable(elm.parentElement);
  25405. const isValidDropTarget = (editor, targetElement, dragElement) => {
  25406. if (isNullable(targetElement)) {
  25407. return false;
  25408. } else if (targetElement === dragElement || editor.dom.isChildOf(targetElement, dragElement)) {
  25409. return false;
  25410. } else {
  25411. return editor.dom.isEditable(targetElement);
  25412. }
  25413. };
  25414. const cloneElement = elm => {
  25415. const cloneElm = elm.cloneNode(true);
  25416. cloneElm.removeAttribute('data-mce-selected');
  25417. return cloneElm;
  25418. };
  25419. const createGhost = (editor, elm, width, height) => {
  25420. const dom = editor.dom;
  25421. const clonedElm = elm.cloneNode(true);
  25422. dom.setStyles(clonedElm, {
  25423. width,
  25424. height
  25425. });
  25426. dom.setAttrib(clonedElm, 'data-mce-selected', null);
  25427. const ghostElm = dom.create('div', {
  25428. 'class': 'mce-drag-container',
  25429. 'data-mce-bogus': 'all',
  25430. 'unselectable': 'on',
  25431. 'contenteditable': 'false'
  25432. });
  25433. dom.setStyles(ghostElm, {
  25434. position: 'absolute',
  25435. opacity: 0.5,
  25436. overflow: 'hidden',
  25437. border: 0,
  25438. padding: 0,
  25439. margin: 0,
  25440. width,
  25441. height
  25442. });
  25443. dom.setStyles(clonedElm, {
  25444. margin: 0,
  25445. boxSizing: 'border-box'
  25446. });
  25447. ghostElm.appendChild(clonedElm);
  25448. return ghostElm;
  25449. };
  25450. const appendGhostToBody = (ghostElm, bodyElm) => {
  25451. if (ghostElm.parentNode !== bodyElm) {
  25452. bodyElm.appendChild(ghostElm);
  25453. }
  25454. };
  25455. const scrollEditor = (direction, amount) => win => () => {
  25456. const current = direction === 'left' ? win.scrollX : win.scrollY;
  25457. win.scroll({
  25458. [direction]: current + amount,
  25459. behavior: 'smooth'
  25460. });
  25461. };
  25462. const scrollLeft = scrollEditor('left', -scrollPixelsPerInterval);
  25463. const scrollRight = scrollEditor('left', scrollPixelsPerInterval);
  25464. const scrollUp = scrollEditor('top', -scrollPixelsPerInterval);
  25465. const scrollDown = scrollEditor('top', scrollPixelsPerInterval);
  25466. const moveGhost = (ghostElm, position, width, height, maxX, maxY, mouseY, mouseX, contentAreaContainer, win, state, mouseEventOriginatedFromWithinTheEditor) => {
  25467. let overflowX = 0, overflowY = 0;
  25468. ghostElm.style.left = position.pageX + 'px';
  25469. ghostElm.style.top = position.pageY + 'px';
  25470. if (position.pageX + width > maxX) {
  25471. overflowX = position.pageX + width - maxX;
  25472. }
  25473. if (position.pageY + height > maxY) {
  25474. overflowY = position.pageY + height - maxY;
  25475. }
  25476. ghostElm.style.width = width - overflowX + 'px';
  25477. ghostElm.style.height = height - overflowY + 'px';
  25478. const clientHeight = contentAreaContainer.clientHeight;
  25479. const clientWidth = contentAreaContainer.clientWidth;
  25480. const outerMouseY = mouseY + contentAreaContainer.getBoundingClientRect().top;
  25481. const outerMouseX = mouseX + contentAreaContainer.getBoundingClientRect().left;
  25482. state.on(state => {
  25483. state.intervalId.clear();
  25484. if (state.dragging && mouseEventOriginatedFromWithinTheEditor) {
  25485. if (mouseY + mouseRangeToTriggerScrollInsideEditor >= clientHeight) {
  25486. state.intervalId.set(scrollDown(win));
  25487. } else if (mouseY - mouseRangeToTriggerScrollInsideEditor <= 0) {
  25488. state.intervalId.set(scrollUp(win));
  25489. } else if (mouseX + mouseRangeToTriggerScrollInsideEditor >= clientWidth) {
  25490. state.intervalId.set(scrollRight(win));
  25491. } else if (mouseX - mouseRangeToTriggerScrollInsideEditor <= 0) {
  25492. state.intervalId.set(scrollLeft(win));
  25493. } else if (outerMouseY + mouseRangeToTriggerScrollOutsideEditor >= window.innerHeight) {
  25494. state.intervalId.set(scrollDown(window));
  25495. } else if (outerMouseY - mouseRangeToTriggerScrollOutsideEditor <= 0) {
  25496. state.intervalId.set(scrollUp(window));
  25497. } else if (outerMouseX + mouseRangeToTriggerScrollOutsideEditor >= window.innerWidth) {
  25498. state.intervalId.set(scrollRight(window));
  25499. } else if (outerMouseX - mouseRangeToTriggerScrollOutsideEditor <= 0) {
  25500. state.intervalId.set(scrollLeft(window));
  25501. }
  25502. }
  25503. });
  25504. };
  25505. const removeElement = elm => {
  25506. if (elm && elm.parentNode) {
  25507. elm.parentNode.removeChild(elm);
  25508. }
  25509. };
  25510. const removeElementWithPadding = (dom, elm) => {
  25511. const parentBlock = dom.getParent(elm.parentNode, dom.isBlock);
  25512. removeElement(elm);
  25513. if (parentBlock && parentBlock !== dom.getRoot() && dom.isEmpty(parentBlock)) {
  25514. fillWithPaddingBr(SugarElement.fromDom(parentBlock));
  25515. }
  25516. };
  25517. const isLeftMouseButtonPressed = e => e.button === 0;
  25518. const applyRelPos = (state, position) => ({
  25519. pageX: position.pageX - state.relX,
  25520. pageY: position.pageY + 5
  25521. });
  25522. const start = (state, editor) => e => {
  25523. if (isLeftMouseButtonPressed(e)) {
  25524. const ceElm = find$2(editor.dom.getParents(e.target), isContentEditable).getOr(null);
  25525. if (isNonNullable(ceElm) && isDraggable(editor.dom, editor.getBody(), ceElm)) {
  25526. const elmPos = editor.dom.getPos(ceElm);
  25527. const bodyElm = editor.getBody();
  25528. const docElm = editor.getDoc().documentElement;
  25529. state.set({
  25530. element: ceElm,
  25531. dragging: false,
  25532. screenX: e.screenX,
  25533. screenY: e.screenY,
  25534. maxX: (editor.inline ? bodyElm.scrollWidth : docElm.offsetWidth) - 2,
  25535. maxY: (editor.inline ? bodyElm.scrollHeight : docElm.offsetHeight) - 2,
  25536. relX: e.pageX - elmPos.x,
  25537. relY: e.pageY - elmPos.y,
  25538. width: ceElm.offsetWidth,
  25539. height: ceElm.offsetHeight,
  25540. ghost: createGhost(editor, ceElm, ceElm.offsetWidth, ceElm.offsetHeight),
  25541. intervalId: repeatable(scrollIntervalValue)
  25542. });
  25543. }
  25544. }
  25545. };
  25546. const placeCaretAt = (editor, clientX, clientY) => {
  25547. editor._selectionOverrides.hideFakeCaret();
  25548. closestFakeCaretCandidate(editor.getBody(), clientX, clientY).fold(() => editor.selection.placeCaretAt(clientX, clientY), caretInfo => {
  25549. const range = editor._selectionOverrides.showCaret(1, caretInfo.node, caretInfo.position === FakeCaretPosition.Before, false);
  25550. if (range) {
  25551. editor.selection.setRng(range);
  25552. } else {
  25553. editor.selection.placeCaretAt(clientX, clientY);
  25554. }
  25555. });
  25556. };
  25557. const move = (state, editor) => {
  25558. const throttledPlaceCaretAt = first$1((clientX, clientY) => placeCaretAt(editor, clientX, clientY), 0);
  25559. editor.on('remove', throttledPlaceCaretAt.cancel);
  25560. const state_ = state;
  25561. return e => state.on(state => {
  25562. const movement = Math.max(Math.abs(e.screenX - state.screenX), Math.abs(e.screenY - state.screenY));
  25563. if (!state.dragging && movement > 10) {
  25564. const args = editor.dispatch('dragstart', makeDragstartEventFromMouseEvent(e, state.element));
  25565. if (args.isDefaultPrevented()) {
  25566. return;
  25567. }
  25568. state.dragging = true;
  25569. editor.focus();
  25570. }
  25571. if (state.dragging) {
  25572. const mouseEventOriginatedFromWithinTheEditor = e.currentTarget === editor.getDoc().documentElement;
  25573. const targetPos = applyRelPos(state, calc(editor, e));
  25574. appendGhostToBody(state.ghost, editor.getBody());
  25575. moveGhost(state.ghost, targetPos, state.width, state.height, state.maxX, state.maxY, e.clientY, e.clientX, editor.getContentAreaContainer(), editor.getWin(), state_, mouseEventOriginatedFromWithinTheEditor);
  25576. throttledPlaceCaretAt.throttle(e.clientX, e.clientY);
  25577. }
  25578. });
  25579. };
  25580. const getRawTarget = selection => {
  25581. const sel = selection.getSel();
  25582. if (isNonNullable(sel)) {
  25583. const rng = sel.getRangeAt(0);
  25584. const startContainer = rng.startContainer;
  25585. return isText$a(startContainer) ? startContainer.parentNode : startContainer;
  25586. } else {
  25587. return null;
  25588. }
  25589. };
  25590. const drop = (state, editor) => e => {
  25591. state.on(state => {
  25592. var _a;
  25593. state.intervalId.clear();
  25594. if (state.dragging) {
  25595. if (isValidDropTarget(editor, getRawTarget(editor.selection), state.element)) {
  25596. const targetClone = cloneElement(state.element);
  25597. const dropTarget = (_a = editor.getDoc().elementFromPoint(e.clientX, e.clientY)) !== null && _a !== void 0 ? _a : editor.getBody();
  25598. const args = editor.dispatch('drop', makeDropEventFromMouseEvent(e, dropTarget));
  25599. if (!args.isDefaultPrevented()) {
  25600. editor.undoManager.transact(() => {
  25601. removeElementWithPadding(editor.dom, state.element);
  25602. editor.insertContent(editor.dom.getOuterHTML(targetClone));
  25603. editor._selectionOverrides.hideFakeCaret();
  25604. });
  25605. }
  25606. }
  25607. editor.dispatch('dragend', makeDragendEventFromMouseEvent(e, editor.getBody()));
  25608. }
  25609. });
  25610. removeDragState(state);
  25611. };
  25612. const stopDragging = (state, editor, e) => {
  25613. state.on(state => {
  25614. state.intervalId.clear();
  25615. if (state.dragging) {
  25616. const event = e.fold(() => makeDragendEvent(state.element), mouseEvent => makeDragendEventFromMouseEvent(mouseEvent, state.element));
  25617. editor.dispatch('dragend', event);
  25618. }
  25619. });
  25620. removeDragState(state);
  25621. };
  25622. const stop = (state, editor) => e => stopDragging(state, editor, Optional.some(e));
  25623. const removeDragState = state => {
  25624. state.on(state => {
  25625. state.intervalId.clear();
  25626. removeElement(state.ghost);
  25627. });
  25628. state.clear();
  25629. };
  25630. const bindFakeDragEvents = editor => {
  25631. const state = value$2();
  25632. const pageDom = DOMUtils.DOM;
  25633. const rootDocument = document;
  25634. const dragStartHandler = start(state, editor);
  25635. const dragHandler = move(state, editor);
  25636. const dropHandler = drop(state, editor);
  25637. const dragEndHandler = stop(state, editor);
  25638. editor.on('mousedown', dragStartHandler);
  25639. editor.on('mousemove', dragHandler);
  25640. editor.on('mouseup', dropHandler);
  25641. pageDom.bind(rootDocument, 'mousemove', dragHandler);
  25642. pageDom.bind(rootDocument, 'mouseup', dragEndHandler);
  25643. editor.on('remove', () => {
  25644. pageDom.unbind(rootDocument, 'mousemove', dragHandler);
  25645. pageDom.unbind(rootDocument, 'mouseup', dragEndHandler);
  25646. });
  25647. editor.on('keydown', e => {
  25648. if (e.keyCode === VK.ESC) {
  25649. stopDragging(state, editor, Optional.none());
  25650. }
  25651. });
  25652. };
  25653. const blockUnsupportedFileDrop = editor => {
  25654. const preventFileDrop = e => {
  25655. if (!e.isDefaultPrevented()) {
  25656. const dataTransfer = e.dataTransfer;
  25657. if (dataTransfer && (contains$2(dataTransfer.types, 'Files') || dataTransfer.files.length > 0)) {
  25658. e.preventDefault();
  25659. if (e.type === 'drop') {
  25660. displayError(editor, 'Dropped file type is not supported');
  25661. }
  25662. }
  25663. }
  25664. };
  25665. const preventFileDropIfUIElement = e => {
  25666. if (isUIElement(editor, e.target)) {
  25667. preventFileDrop(e);
  25668. }
  25669. };
  25670. const setup = () => {
  25671. const pageDom = DOMUtils.DOM;
  25672. const dom = editor.dom;
  25673. const doc = document;
  25674. const editorRoot = editor.inline ? editor.getBody() : editor.getDoc();
  25675. const eventNames = [
  25676. 'drop',
  25677. 'dragover'
  25678. ];
  25679. each$e(eventNames, name => {
  25680. pageDom.bind(doc, name, preventFileDropIfUIElement);
  25681. dom.bind(editorRoot, name, preventFileDrop);
  25682. });
  25683. editor.on('remove', () => {
  25684. each$e(eventNames, name => {
  25685. pageDom.unbind(doc, name, preventFileDropIfUIElement);
  25686. dom.unbind(editorRoot, name, preventFileDrop);
  25687. });
  25688. });
  25689. };
  25690. editor.on('init', () => {
  25691. Delay.setEditorTimeout(editor, setup, 0);
  25692. });
  25693. };
  25694. const init$2 = editor => {
  25695. bindFakeDragEvents(editor);
  25696. if (shouldBlockUnsupportedDrop(editor)) {
  25697. blockUnsupportedFileDrop(editor);
  25698. }
  25699. };
  25700. const setup$4 = editor => {
  25701. const renderFocusCaret = first$1(() => {
  25702. if (!editor.removed && editor.getBody().contains(document.activeElement)) {
  25703. const rng = editor.selection.getRng();
  25704. if (rng.collapsed) {
  25705. const caretRange = renderRangeCaret(editor, rng, false);
  25706. editor.selection.setRng(caretRange);
  25707. }
  25708. }
  25709. }, 0);
  25710. editor.on('focus', () => {
  25711. renderFocusCaret.throttle();
  25712. });
  25713. editor.on('blur', () => {
  25714. renderFocusCaret.cancel();
  25715. });
  25716. };
  25717. const setup$3 = editor => {
  25718. editor.on('init', () => {
  25719. editor.on('focusin', e => {
  25720. const target = e.target;
  25721. if (isMedia$2(target)) {
  25722. const ceRoot = getContentEditableRoot$1(editor.getBody(), target);
  25723. const node = isContentEditableFalse$b(ceRoot) ? ceRoot : target;
  25724. if (editor.selection.getNode() !== node) {
  25725. selectNode(editor, node).each(rng => editor.selection.setRng(rng));
  25726. }
  25727. }
  25728. });
  25729. });
  25730. };
  25731. const isContentEditableFalse = isContentEditableFalse$b;
  25732. const getContentEditableRoot = (editor, node) => getContentEditableRoot$1(editor.getBody(), node);
  25733. const SelectionOverrides = editor => {
  25734. const selection = editor.selection, dom = editor.dom;
  25735. const rootNode = editor.getBody();
  25736. const fakeCaret = FakeCaret(editor, rootNode, dom.isBlock, () => hasFocus(editor));
  25737. const realSelectionId = 'sel-' + dom.uniqueId();
  25738. const elementSelectionAttr = 'data-mce-selected';
  25739. let selectedElement;
  25740. const isFakeSelectionElement = node => isNonNullable(node) && dom.hasClass(node, 'mce-offscreen-selection');
  25741. const isFakeSelectionTargetElement = node => node !== rootNode && (isContentEditableFalse(node) || isMedia$2(node)) && dom.isChildOf(node, rootNode) && dom.isEditable(node.parentNode);
  25742. const setRange = range => {
  25743. if (range) {
  25744. selection.setRng(range);
  25745. }
  25746. };
  25747. const showCaret = (direction, node, before, scrollIntoView = true) => {
  25748. const e = editor.dispatch('ShowCaret', {
  25749. target: node,
  25750. direction,
  25751. before
  25752. });
  25753. if (e.isDefaultPrevented()) {
  25754. return null;
  25755. }
  25756. if (scrollIntoView) {
  25757. selection.scrollIntoView(node, direction === -1);
  25758. }
  25759. return fakeCaret.show(before, node);
  25760. };
  25761. const showBlockCaretContainer = blockCaretContainer => {
  25762. if (blockCaretContainer.hasAttribute('data-mce-caret')) {
  25763. showCaretContainerBlock(blockCaretContainer);
  25764. selection.scrollIntoView(blockCaretContainer);
  25765. }
  25766. };
  25767. const registerEvents = () => {
  25768. editor.on('click', e => {
  25769. if (!dom.isEditable(e.target)) {
  25770. e.preventDefault();
  25771. editor.focus();
  25772. }
  25773. });
  25774. editor.on('blur NewBlock', removeElementSelection);
  25775. editor.on('ResizeWindow FullscreenStateChanged', fakeCaret.reposition);
  25776. editor.on('tap', e => {
  25777. const targetElm = e.target;
  25778. const contentEditableRoot = getContentEditableRoot(editor, targetElm);
  25779. if (isContentEditableFalse(contentEditableRoot)) {
  25780. e.preventDefault();
  25781. selectNode(editor, contentEditableRoot).each(setElementSelection);
  25782. } else if (isFakeSelectionTargetElement(targetElm)) {
  25783. selectNode(editor, targetElm).each(setElementSelection);
  25784. }
  25785. }, true);
  25786. editor.on('mousedown', e => {
  25787. const targetElm = e.target;
  25788. if (targetElm !== rootNode && targetElm.nodeName !== 'HTML' && !dom.isChildOf(targetElm, rootNode)) {
  25789. return;
  25790. }
  25791. if (!isXYInContentArea(editor, e.clientX, e.clientY)) {
  25792. return;
  25793. }
  25794. removeElementSelection();
  25795. hideFakeCaret();
  25796. const closestContentEditable = getContentEditableRoot(editor, targetElm);
  25797. if (isContentEditableFalse(closestContentEditable)) {
  25798. e.preventDefault();
  25799. selectNode(editor, closestContentEditable).each(setElementSelection);
  25800. } else {
  25801. closestFakeCaretCandidate(rootNode, e.clientX, e.clientY).each(caretInfo => {
  25802. e.preventDefault();
  25803. const range = showCaret(1, caretInfo.node, caretInfo.position === FakeCaretPosition.Before, false);
  25804. setRange(range);
  25805. if (isElement$6(closestContentEditable)) {
  25806. closestContentEditable.focus();
  25807. } else {
  25808. editor.getBody().focus();
  25809. }
  25810. });
  25811. }
  25812. });
  25813. editor.on('keypress', e => {
  25814. if (VK.modifierPressed(e)) {
  25815. return;
  25816. }
  25817. if (isContentEditableFalse(selection.getNode())) {
  25818. e.preventDefault();
  25819. }
  25820. });
  25821. editor.on('GetSelectionRange', e => {
  25822. let rng = e.range;
  25823. if (selectedElement) {
  25824. if (!selectedElement.parentNode) {
  25825. selectedElement = null;
  25826. return;
  25827. }
  25828. rng = rng.cloneRange();
  25829. rng.selectNode(selectedElement);
  25830. e.range = rng;
  25831. }
  25832. });
  25833. editor.on('SetSelectionRange', e => {
  25834. e.range = normalizeVoidElementSelection(e.range);
  25835. const rng = setElementSelection(e.range, e.forward);
  25836. if (rng) {
  25837. e.range = rng;
  25838. }
  25839. });
  25840. const isPasteBin = node => isElement$6(node) && node.id === 'mcepastebin';
  25841. editor.on('AfterSetSelectionRange', e => {
  25842. const rng = e.range;
  25843. const parent = rng.startContainer.parentElement;
  25844. if (!isRangeInCaretContainer(rng) && !isPasteBin(parent)) {
  25845. hideFakeCaret();
  25846. }
  25847. if (!isFakeSelectionElement(parent)) {
  25848. removeElementSelection();
  25849. }
  25850. });
  25851. init$2(editor);
  25852. setup$4(editor);
  25853. setup$3(editor);
  25854. };
  25855. const isWithinCaretContainer = node => isCaretContainer$2(node) || startsWithCaretContainer$1(node) || endsWithCaretContainer$1(node);
  25856. const isRangeInCaretContainer = rng => isWithinCaretContainer(rng.startContainer) || isWithinCaretContainer(rng.endContainer);
  25857. const normalizeVoidElementSelection = rng => {
  25858. const voidElements = editor.schema.getVoidElements();
  25859. const newRng = dom.createRng();
  25860. const startContainer = rng.startContainer;
  25861. const startOffset = rng.startOffset;
  25862. const endContainer = rng.endContainer;
  25863. const endOffset = rng.endOffset;
  25864. if (has$2(voidElements, startContainer.nodeName.toLowerCase())) {
  25865. if (startOffset === 0) {
  25866. newRng.setStartBefore(startContainer);
  25867. } else {
  25868. newRng.setStartAfter(startContainer);
  25869. }
  25870. } else {
  25871. newRng.setStart(startContainer, startOffset);
  25872. }
  25873. if (has$2(voidElements, endContainer.nodeName.toLowerCase())) {
  25874. if (endOffset === 0) {
  25875. newRng.setEndBefore(endContainer);
  25876. } else {
  25877. newRng.setEndAfter(endContainer);
  25878. }
  25879. } else {
  25880. newRng.setEnd(endContainer, endOffset);
  25881. }
  25882. return newRng;
  25883. };
  25884. const setupOffscreenSelection = (node, targetClone) => {
  25885. const body = SugarElement.fromDom(editor.getBody());
  25886. const doc = editor.getDoc();
  25887. const realSelectionContainer = descendant(body, '#' + realSelectionId).getOrThunk(() => {
  25888. const newContainer = SugarElement.fromHtml('<div data-mce-bogus="all" class="mce-offscreen-selection"></div>', doc);
  25889. set$3(newContainer, 'id', realSelectionId);
  25890. append$1(body, newContainer);
  25891. return newContainer;
  25892. });
  25893. const newRange = dom.createRng();
  25894. empty(realSelectionContainer);
  25895. append(realSelectionContainer, [
  25896. SugarElement.fromText(nbsp, doc),
  25897. SugarElement.fromDom(targetClone),
  25898. SugarElement.fromText(nbsp, doc)
  25899. ]);
  25900. newRange.setStart(realSelectionContainer.dom.firstChild, 1);
  25901. newRange.setEnd(realSelectionContainer.dom.lastChild, 0);
  25902. setAll(realSelectionContainer, { top: dom.getPos(node, editor.getBody()).y + 'px' });
  25903. focus$1(realSelectionContainer);
  25904. const sel = selection.getSel();
  25905. if (sel) {
  25906. sel.removeAllRanges();
  25907. sel.addRange(newRange);
  25908. }
  25909. return newRange;
  25910. };
  25911. const selectElement = elm => {
  25912. const targetClone = elm.cloneNode(true);
  25913. const e = editor.dispatch('ObjectSelected', {
  25914. target: elm,
  25915. targetClone
  25916. });
  25917. if (e.isDefaultPrevented()) {
  25918. return null;
  25919. }
  25920. const range = setupOffscreenSelection(elm, e.targetClone);
  25921. const nodeElm = SugarElement.fromDom(elm);
  25922. each$e(descendants(SugarElement.fromDom(editor.getBody()), `*[${ elementSelectionAttr }]`), elm => {
  25923. if (!eq(nodeElm, elm)) {
  25924. remove$b(elm, elementSelectionAttr);
  25925. }
  25926. });
  25927. if (!dom.getAttrib(elm, elementSelectionAttr)) {
  25928. elm.setAttribute(elementSelectionAttr, '1');
  25929. }
  25930. selectedElement = elm;
  25931. hideFakeCaret();
  25932. return range;
  25933. };
  25934. const setElementSelection = (range, forward) => {
  25935. if (!range) {
  25936. return null;
  25937. }
  25938. if (range.collapsed) {
  25939. if (!isRangeInCaretContainer(range)) {
  25940. const dir = forward ? 1 : -1;
  25941. const caretPosition = getNormalizedRangeEndPoint(dir, rootNode, range);
  25942. const beforeNode = caretPosition.getNode(!forward);
  25943. if (isNonNullable(beforeNode)) {
  25944. if (isFakeCaretTarget(beforeNode)) {
  25945. return showCaret(dir, beforeNode, forward ? !caretPosition.isAtEnd() : false, false);
  25946. }
  25947. if (isCaretContainerInline(beforeNode) && isContentEditableFalse$b(beforeNode.nextSibling)) {
  25948. const rng = dom.createRng();
  25949. rng.setStart(beforeNode, 0);
  25950. rng.setEnd(beforeNode, 0);
  25951. return rng;
  25952. }
  25953. }
  25954. const afterNode = caretPosition.getNode(forward);
  25955. if (isNonNullable(afterNode)) {
  25956. if (isFakeCaretTarget(afterNode)) {
  25957. return showCaret(dir, afterNode, forward ? false : !caretPosition.isAtEnd(), false);
  25958. }
  25959. if (isCaretContainerInline(afterNode) && isContentEditableFalse$b(afterNode.previousSibling)) {
  25960. const rng = dom.createRng();
  25961. rng.setStart(afterNode, 1);
  25962. rng.setEnd(afterNode, 1);
  25963. return rng;
  25964. }
  25965. }
  25966. }
  25967. return null;
  25968. }
  25969. let startContainer = range.startContainer;
  25970. let startOffset = range.startOffset;
  25971. const endOffset = range.endOffset;
  25972. if (isText$a(startContainer) && startOffset === 0 && isContentEditableFalse(startContainer.parentNode)) {
  25973. startContainer = startContainer.parentNode;
  25974. startOffset = dom.nodeIndex(startContainer);
  25975. startContainer = startContainer.parentNode;
  25976. }
  25977. if (!isElement$6(startContainer)) {
  25978. return null;
  25979. }
  25980. if (endOffset === startOffset + 1 && startContainer === range.endContainer) {
  25981. const node = startContainer.childNodes[startOffset];
  25982. if (isFakeSelectionTargetElement(node)) {
  25983. return selectElement(node);
  25984. }
  25985. }
  25986. return null;
  25987. };
  25988. const removeElementSelection = () => {
  25989. if (selectedElement) {
  25990. selectedElement.removeAttribute(elementSelectionAttr);
  25991. }
  25992. descendant(SugarElement.fromDom(editor.getBody()), '#' + realSelectionId).each(remove$6);
  25993. selectedElement = null;
  25994. };
  25995. const destroy = () => {
  25996. fakeCaret.destroy();
  25997. selectedElement = null;
  25998. };
  25999. const hideFakeCaret = () => {
  26000. fakeCaret.hide();
  26001. };
  26002. if (!isRtc(editor)) {
  26003. registerEvents();
  26004. }
  26005. return {
  26006. showCaret,
  26007. showBlockCaretContainer,
  26008. hideFakeCaret,
  26009. destroy
  26010. };
  26011. };
  26012. const getNormalizedTextOffset = (container, offset) => {
  26013. let normalizedOffset = offset;
  26014. for (let node = container.previousSibling; isText$a(node); node = node.previousSibling) {
  26015. normalizedOffset += node.data.length;
  26016. }
  26017. return normalizedOffset;
  26018. };
  26019. const generatePath = (dom, root, node, offset, normalized) => {
  26020. if (isText$a(node) && (offset < 0 || offset > node.data.length)) {
  26021. return [];
  26022. }
  26023. const p = normalized && isText$a(node) ? [getNormalizedTextOffset(node, offset)] : [offset];
  26024. let current = node;
  26025. while (current !== root && current.parentNode) {
  26026. p.push(dom.nodeIndex(current, normalized));
  26027. current = current.parentNode;
  26028. }
  26029. return current === root ? p.reverse() : [];
  26030. };
  26031. const generatePathRange = (dom, root, startNode, startOffset, endNode, endOffset, normalized = false) => {
  26032. const start = generatePath(dom, root, startNode, startOffset, normalized);
  26033. const end = generatePath(dom, root, endNode, endOffset, normalized);
  26034. return {
  26035. start,
  26036. end
  26037. };
  26038. };
  26039. const resolvePath = (root, path) => {
  26040. const nodePath = path.slice();
  26041. const offset = nodePath.pop();
  26042. if (!isNumber(offset)) {
  26043. return Optional.none();
  26044. } else {
  26045. const resolvedNode = foldl(nodePath, (optNode, index) => optNode.bind(node => Optional.from(node.childNodes[index])), Optional.some(root));
  26046. return resolvedNode.bind(node => {
  26047. if (isText$a(node) && (offset < 0 || offset > node.data.length)) {
  26048. return Optional.none();
  26049. } else {
  26050. return Optional.some({
  26051. node,
  26052. offset
  26053. });
  26054. }
  26055. });
  26056. }
  26057. };
  26058. const resolvePathRange = (root, range) => resolvePath(root, range.start).bind(({
  26059. node: startNode,
  26060. offset: startOffset
  26061. }) => resolvePath(root, range.end).map(({
  26062. node: endNode,
  26063. offset: endOffset
  26064. }) => {
  26065. const rng = document.createRange();
  26066. rng.setStart(startNode, startOffset);
  26067. rng.setEnd(endNode, endOffset);
  26068. return rng;
  26069. }));
  26070. const generatePathRangeFromRange = (dom, root, range, normalized = false) => generatePathRange(dom, root, range.startContainer, range.startOffset, range.endContainer, range.endOffset, normalized);
  26071. const cleanEmptyNodes = (dom, node, isRoot) => {
  26072. if (node && dom.isEmpty(node) && !isRoot(node)) {
  26073. const parent = node.parentNode;
  26074. dom.remove(node);
  26075. cleanEmptyNodes(dom, parent, isRoot);
  26076. }
  26077. };
  26078. const deleteRng = (dom, rng, isRoot, clean = true) => {
  26079. const startParent = rng.startContainer.parentNode;
  26080. const endParent = rng.endContainer.parentNode;
  26081. rng.deleteContents();
  26082. if (clean && !isRoot(rng.startContainer)) {
  26083. if (isText$a(rng.startContainer) && rng.startContainer.data.length === 0) {
  26084. dom.remove(rng.startContainer);
  26085. }
  26086. if (isText$a(rng.endContainer) && rng.endContainer.data.length === 0) {
  26087. dom.remove(rng.endContainer);
  26088. }
  26089. cleanEmptyNodes(dom, startParent, isRoot);
  26090. if (startParent !== endParent) {
  26091. cleanEmptyNodes(dom, endParent, isRoot);
  26092. }
  26093. }
  26094. };
  26095. const getParentBlock = (editor, rng) => Optional.from(editor.dom.getParent(rng.startContainer, editor.dom.isBlock));
  26096. const resolveFromDynamicPatterns = (patternSet, block, beforeText) => {
  26097. const dynamicPatterns = patternSet.dynamicPatternsLookup({
  26098. text: beforeText,
  26099. block
  26100. });
  26101. return {
  26102. ...patternSet,
  26103. blockPatterns: getBlockPatterns(dynamicPatterns).concat(patternSet.blockPatterns),
  26104. inlinePatterns: getInlinePatterns(dynamicPatterns).concat(patternSet.inlinePatterns)
  26105. };
  26106. };
  26107. const getBeforeText = (dom, block, node, offset) => {
  26108. const rng = dom.createRng();
  26109. rng.setStart(block, 0);
  26110. rng.setEnd(node, offset);
  26111. return rng.toString();
  26112. };
  26113. const startsWithSingleSpace = s => /^\s[^\s]/.test(s);
  26114. const stripPattern = (dom, block, pattern) => {
  26115. const firstTextNode = textAfter(block, 0, block);
  26116. firstTextNode.each(spot => {
  26117. const node = spot.container;
  26118. scanRight(node, pattern.start.length, block).each(end => {
  26119. const rng = dom.createRng();
  26120. rng.setStart(node, 0);
  26121. rng.setEnd(end.container, end.offset);
  26122. deleteRng(dom, rng, e => e === block);
  26123. });
  26124. const text = SugarElement.fromDom(node);
  26125. const textContent = get$3(text);
  26126. if (startsWithSingleSpace(textContent)) {
  26127. set(text, textContent.slice(1));
  26128. }
  26129. });
  26130. };
  26131. const applyPattern$1 = (editor, match) => {
  26132. const dom = editor.dom;
  26133. const pattern = match.pattern;
  26134. const rng = resolvePathRange(dom.getRoot(), match.range).getOrDie('Unable to resolve path range');
  26135. const isBlockFormatName = (name, formatter) => {
  26136. const formatSet = formatter.get(name);
  26137. return isArray$1(formatSet) && head(formatSet).exists(format => has$2(format, 'block'));
  26138. };
  26139. getParentBlock(editor, rng).each(block => {
  26140. if (pattern.type === 'block-format') {
  26141. if (isBlockFormatName(pattern.format, editor.formatter)) {
  26142. editor.undoManager.transact(() => {
  26143. stripPattern(editor.dom, block, pattern);
  26144. editor.formatter.apply(pattern.format);
  26145. });
  26146. }
  26147. } else if (pattern.type === 'block-command') {
  26148. editor.undoManager.transact(() => {
  26149. stripPattern(editor.dom, block, pattern);
  26150. editor.execCommand(pattern.cmd, false, pattern.value);
  26151. });
  26152. }
  26153. });
  26154. return true;
  26155. };
  26156. const sortPatterns$1 = patterns => sort(patterns, (a, b) => b.start.length - a.start.length);
  26157. const findPattern$1 = (patterns, text) => {
  26158. const sortedPatterns = sortPatterns$1(patterns);
  26159. const nuText = text.replace(nbsp, ' ');
  26160. return find$2(sortedPatterns, pattern => text.indexOf(pattern.start) === 0 || nuText.indexOf(pattern.start) === 0);
  26161. };
  26162. const findPatterns$1 = (editor, block, patternSet, normalizedMatches) => {
  26163. var _a;
  26164. const dom = editor.dom;
  26165. const forcedRootBlock = getForcedRootBlock(editor);
  26166. if (!dom.is(block, forcedRootBlock)) {
  26167. return [];
  26168. }
  26169. const blockText = (_a = block.textContent) !== null && _a !== void 0 ? _a : '';
  26170. return findPattern$1(patternSet.blockPatterns, blockText).map(pattern => {
  26171. if (Tools.trim(blockText).length === pattern.start.length) {
  26172. return [];
  26173. }
  26174. return [{
  26175. pattern,
  26176. range: generatePathRange(dom, dom.getRoot(), block, 0, block, 0, normalizedMatches)
  26177. }];
  26178. }).getOr([]);
  26179. };
  26180. const applyMatches$1 = (editor, matches) => {
  26181. if (matches.length === 0) {
  26182. return;
  26183. }
  26184. const bookmark = editor.selection.getBookmark();
  26185. each$e(matches, match => applyPattern$1(editor, match));
  26186. editor.selection.moveToBookmark(bookmark);
  26187. };
  26188. const newMarker = (dom, id) => dom.create('span', {
  26189. 'data-mce-type': 'bookmark',
  26190. id
  26191. });
  26192. const rangeFromMarker = (dom, marker) => {
  26193. const rng = dom.createRng();
  26194. rng.setStartAfter(marker.start);
  26195. rng.setEndBefore(marker.end);
  26196. return rng;
  26197. };
  26198. const createMarker = (dom, markerPrefix, pathRange) => {
  26199. const rng = resolvePathRange(dom.getRoot(), pathRange).getOrDie('Unable to resolve path range');
  26200. const startNode = rng.startContainer;
  26201. const endNode = rng.endContainer;
  26202. const textEnd = rng.endOffset === 0 ? endNode : endNode.splitText(rng.endOffset);
  26203. const textStart = rng.startOffset === 0 ? startNode : startNode.splitText(rng.startOffset);
  26204. const startParentNode = textStart.parentNode;
  26205. const endParentNode = textEnd.parentNode;
  26206. return {
  26207. prefix: markerPrefix,
  26208. end: endParentNode.insertBefore(newMarker(dom, markerPrefix + '-end'), textEnd),
  26209. start: startParentNode.insertBefore(newMarker(dom, markerPrefix + '-start'), textStart)
  26210. };
  26211. };
  26212. const removeMarker = (dom, marker, isRoot) => {
  26213. cleanEmptyNodes(dom, dom.get(marker.prefix + '-end'), isRoot);
  26214. cleanEmptyNodes(dom, dom.get(marker.prefix + '-start'), isRoot);
  26215. };
  26216. const isReplacementPattern = pattern => pattern.start.length === 0;
  26217. const matchesPattern = patternContent => (element, offset) => {
  26218. const text = element.data;
  26219. const searchText = text.substring(0, offset);
  26220. const startEndIndex = searchText.lastIndexOf(patternContent.charAt(patternContent.length - 1));
  26221. const startIndex = searchText.lastIndexOf(patternContent);
  26222. if (startIndex !== -1) {
  26223. return startIndex + patternContent.length;
  26224. } else if (startEndIndex !== -1) {
  26225. return startEndIndex + 1;
  26226. } else {
  26227. return -1;
  26228. }
  26229. };
  26230. const findPatternStartFromSpot = (dom, pattern, block, spot) => {
  26231. const startPattern = pattern.start;
  26232. const startSpot = repeatLeft(dom, spot.container, spot.offset, matchesPattern(startPattern), block);
  26233. return startSpot.bind(spot => {
  26234. var _a, _b;
  26235. const startPatternIndex = (_b = (_a = block.textContent) === null || _a === void 0 ? void 0 : _a.indexOf(startPattern)) !== null && _b !== void 0 ? _b : -1;
  26236. const isCompleteMatch = startPatternIndex !== -1 && spot.offset >= startPatternIndex + startPattern.length;
  26237. if (isCompleteMatch) {
  26238. const rng = dom.createRng();
  26239. rng.setStart(spot.container, spot.offset - startPattern.length);
  26240. rng.setEnd(spot.container, spot.offset);
  26241. return Optional.some(rng);
  26242. } else {
  26243. const offset = spot.offset - startPattern.length;
  26244. return scanLeft(spot.container, offset, block).map(nextSpot => {
  26245. const rng = dom.createRng();
  26246. rng.setStart(nextSpot.container, nextSpot.offset);
  26247. rng.setEnd(spot.container, spot.offset);
  26248. return rng;
  26249. }).filter(rng => rng.toString() === startPattern).orThunk(() => findPatternStartFromSpot(dom, pattern, block, point(spot.container, 0)));
  26250. }
  26251. });
  26252. };
  26253. const findPatternStart = (dom, pattern, node, offset, block, requireGap = false) => {
  26254. if (pattern.start.length === 0 && !requireGap) {
  26255. const rng = dom.createRng();
  26256. rng.setStart(node, offset);
  26257. rng.setEnd(node, offset);
  26258. return Optional.some(rng);
  26259. }
  26260. return textBefore(node, offset, block).bind(spot => {
  26261. const start = findPatternStartFromSpot(dom, pattern, block, spot);
  26262. return start.bind(startRange => {
  26263. var _a;
  26264. if (requireGap) {
  26265. if (startRange.endContainer === spot.container && startRange.endOffset === spot.offset) {
  26266. return Optional.none();
  26267. } else if (spot.offset === 0 && ((_a = startRange.endContainer.textContent) === null || _a === void 0 ? void 0 : _a.length) === startRange.endOffset) {
  26268. return Optional.none();
  26269. }
  26270. }
  26271. return Optional.some(startRange);
  26272. });
  26273. });
  26274. };
  26275. const findPattern = (editor, block, details, normalizedMatches) => {
  26276. const dom = editor.dom;
  26277. const root = dom.getRoot();
  26278. const pattern = details.pattern;
  26279. const endNode = details.position.container;
  26280. const endOffset = details.position.offset;
  26281. return scanLeft(endNode, endOffset - details.pattern.end.length, block).bind(spot => {
  26282. const endPathRng = generatePathRange(dom, root, spot.container, spot.offset, endNode, endOffset, normalizedMatches);
  26283. if (isReplacementPattern(pattern)) {
  26284. return Optional.some({
  26285. matches: [{
  26286. pattern,
  26287. startRng: endPathRng,
  26288. endRng: endPathRng
  26289. }],
  26290. position: spot
  26291. });
  26292. } else {
  26293. const resultsOpt = findPatternsRec(editor, details.remainingPatterns, spot.container, spot.offset, block, normalizedMatches);
  26294. const results = resultsOpt.getOr({
  26295. matches: [],
  26296. position: spot
  26297. });
  26298. const pos = results.position;
  26299. const start = findPatternStart(dom, pattern, pos.container, pos.offset, block, resultsOpt.isNone());
  26300. return start.map(startRng => {
  26301. const startPathRng = generatePathRangeFromRange(dom, root, startRng, normalizedMatches);
  26302. return {
  26303. matches: results.matches.concat([{
  26304. pattern,
  26305. startRng: startPathRng,
  26306. endRng: endPathRng
  26307. }]),
  26308. position: point(startRng.startContainer, startRng.startOffset)
  26309. };
  26310. });
  26311. }
  26312. });
  26313. };
  26314. const findPatternsRec = (editor, patterns, node, offset, block, normalizedMatches) => {
  26315. const dom = editor.dom;
  26316. return textBefore(node, offset, dom.getRoot()).bind(endSpot => {
  26317. const text = getBeforeText(dom, block, node, offset);
  26318. for (let i = 0; i < patterns.length; i++) {
  26319. const pattern = patterns[i];
  26320. if (!endsWith(text, pattern.end)) {
  26321. continue;
  26322. }
  26323. const patternsWithoutCurrent = patterns.slice();
  26324. patternsWithoutCurrent.splice(i, 1);
  26325. const result = findPattern(editor, block, {
  26326. pattern,
  26327. remainingPatterns: patternsWithoutCurrent,
  26328. position: endSpot
  26329. }, normalizedMatches);
  26330. if (result.isNone() && offset > 0) {
  26331. return findPatternsRec(editor, patterns, node, offset - 1, block, normalizedMatches);
  26332. }
  26333. if (result.isSome()) {
  26334. return result;
  26335. }
  26336. }
  26337. return Optional.none();
  26338. });
  26339. };
  26340. const applyPattern = (editor, pattern, patternRange) => {
  26341. editor.selection.setRng(patternRange);
  26342. if (pattern.type === 'inline-format') {
  26343. each$e(pattern.format, format => {
  26344. editor.formatter.apply(format);
  26345. });
  26346. } else {
  26347. editor.execCommand(pattern.cmd, false, pattern.value);
  26348. }
  26349. };
  26350. const applyReplacementPattern = (editor, pattern, marker, isRoot) => {
  26351. const markerRange = rangeFromMarker(editor.dom, marker);
  26352. deleteRng(editor.dom, markerRange, isRoot);
  26353. applyPattern(editor, pattern, markerRange);
  26354. };
  26355. const applyPatternWithContent = (editor, pattern, startMarker, endMarker, isRoot) => {
  26356. const dom = editor.dom;
  26357. const markerEndRange = rangeFromMarker(dom, endMarker);
  26358. const markerStartRange = rangeFromMarker(dom, startMarker);
  26359. deleteRng(dom, markerStartRange, isRoot);
  26360. deleteRng(dom, markerEndRange, isRoot);
  26361. const patternMarker = {
  26362. prefix: startMarker.prefix,
  26363. start: startMarker.end,
  26364. end: endMarker.start
  26365. };
  26366. const patternRange = rangeFromMarker(dom, patternMarker);
  26367. applyPattern(editor, pattern, patternRange);
  26368. };
  26369. const addMarkers = (dom, matches) => {
  26370. const markerPrefix = generate$1('mce_textpattern');
  26371. const matchesWithEnds = foldr(matches, (acc, match) => {
  26372. const endMarker = createMarker(dom, markerPrefix + `_end${ acc.length }`, match.endRng);
  26373. return acc.concat([{
  26374. ...match,
  26375. endMarker
  26376. }]);
  26377. }, []);
  26378. return foldr(matchesWithEnds, (acc, match) => {
  26379. const idx = matchesWithEnds.length - acc.length - 1;
  26380. const startMarker = isReplacementPattern(match.pattern) ? match.endMarker : createMarker(dom, markerPrefix + `_start${ idx }`, match.startRng);
  26381. return acc.concat([{
  26382. ...match,
  26383. startMarker
  26384. }]);
  26385. }, []);
  26386. };
  26387. const sortPatterns = patterns => sort(patterns, (a, b) => b.end.length - a.end.length);
  26388. const getBestMatches = (matches, matchesWithSortedPatterns) => {
  26389. const hasSameMatches = forall(matches, match => exists(matchesWithSortedPatterns, sortedMatch => match.pattern.start === sortedMatch.pattern.start && match.pattern.end === sortedMatch.pattern.end));
  26390. if (matches.length === matchesWithSortedPatterns.length) {
  26391. if (hasSameMatches) {
  26392. return matches;
  26393. } else {
  26394. return matchesWithSortedPatterns;
  26395. }
  26396. }
  26397. return matches.length > matchesWithSortedPatterns.length ? matches : matchesWithSortedPatterns;
  26398. };
  26399. const findPatterns = (editor, block, node, offset, patternSet, normalizedMatches) => {
  26400. const matches = findPatternsRec(editor, patternSet.inlinePatterns, node, offset, block, normalizedMatches).fold(() => [], result => result.matches);
  26401. const matchesWithSortedPatterns = findPatternsRec(editor, sortPatterns(patternSet.inlinePatterns), node, offset, block, normalizedMatches).fold(() => [], result => result.matches);
  26402. return getBestMatches(matches, matchesWithSortedPatterns);
  26403. };
  26404. const applyMatches = (editor, matches) => {
  26405. if (matches.length === 0) {
  26406. return;
  26407. }
  26408. const dom = editor.dom;
  26409. const bookmark = editor.selection.getBookmark();
  26410. const matchesWithMarkers = addMarkers(dom, matches);
  26411. each$e(matchesWithMarkers, match => {
  26412. const block = dom.getParent(match.startMarker.start, dom.isBlock);
  26413. const isRoot = node => node === block;
  26414. if (isReplacementPattern(match.pattern)) {
  26415. applyReplacementPattern(editor, match.pattern, match.endMarker, isRoot);
  26416. } else {
  26417. applyPatternWithContent(editor, match.pattern, match.startMarker, match.endMarker, isRoot);
  26418. }
  26419. removeMarker(dom, match.endMarker, isRoot);
  26420. removeMarker(dom, match.startMarker, isRoot);
  26421. });
  26422. editor.selection.moveToBookmark(bookmark);
  26423. };
  26424. const handleEnter = (editor, patternSet) => {
  26425. const rng = editor.selection.getRng();
  26426. return getParentBlock(editor, rng).map(block => {
  26427. var _a;
  26428. const offset = Math.max(0, rng.startOffset);
  26429. const dynamicPatternSet = resolveFromDynamicPatterns(patternSet, block, (_a = block.textContent) !== null && _a !== void 0 ? _a : '');
  26430. const inlineMatches = findPatterns(editor, block, rng.startContainer, offset, dynamicPatternSet, true);
  26431. const blockMatches = findPatterns$1(editor, block, dynamicPatternSet, true);
  26432. if (blockMatches.length > 0 || inlineMatches.length > 0) {
  26433. editor.undoManager.add();
  26434. editor.undoManager.extra(() => {
  26435. editor.execCommand('mceInsertNewLine');
  26436. }, () => {
  26437. editor.insertContent(zeroWidth);
  26438. applyMatches(editor, inlineMatches);
  26439. applyMatches$1(editor, blockMatches);
  26440. const range = editor.selection.getRng();
  26441. const spot = textBefore(range.startContainer, range.startOffset, editor.dom.getRoot());
  26442. editor.execCommand('mceInsertNewLine');
  26443. spot.each(s => {
  26444. const node = s.container;
  26445. if (node.data.charAt(s.offset - 1) === zeroWidth) {
  26446. node.deleteData(s.offset - 1, 1);
  26447. cleanEmptyNodes(editor.dom, node.parentNode, e => e === editor.dom.getRoot());
  26448. }
  26449. });
  26450. });
  26451. return true;
  26452. }
  26453. return false;
  26454. }).getOr(false);
  26455. };
  26456. const handleInlineKey = (editor, patternSet) => {
  26457. const rng = editor.selection.getRng();
  26458. getParentBlock(editor, rng).map(block => {
  26459. const offset = Math.max(0, rng.startOffset - 1);
  26460. const beforeText = getBeforeText(editor.dom, block, rng.startContainer, offset);
  26461. const dynamicPatternSet = resolveFromDynamicPatterns(patternSet, block, beforeText);
  26462. const inlineMatches = findPatterns(editor, block, rng.startContainer, offset, dynamicPatternSet, false);
  26463. if (inlineMatches.length > 0) {
  26464. editor.undoManager.transact(() => {
  26465. applyMatches(editor, inlineMatches);
  26466. });
  26467. }
  26468. });
  26469. };
  26470. const checkKeyEvent = (codes, event, predicate) => {
  26471. for (let i = 0; i < codes.length; i++) {
  26472. if (predicate(codes[i], event)) {
  26473. return true;
  26474. }
  26475. }
  26476. return false;
  26477. };
  26478. const checkKeyCode = (codes, event) => checkKeyEvent(codes, event, (code, event) => {
  26479. return code === event.keyCode && !VK.modifierPressed(event);
  26480. });
  26481. const checkCharCode = (chars, event) => checkKeyEvent(chars, event, (chr, event) => {
  26482. return chr.charCodeAt(0) === event.charCode;
  26483. });
  26484. const setup$2 = editor => {
  26485. const charCodes = [
  26486. ',',
  26487. '.',
  26488. ';',
  26489. ':',
  26490. '!',
  26491. '?'
  26492. ];
  26493. const keyCodes = [32];
  26494. const getPatternSet = () => createPatternSet(getTextPatterns(editor), getTextPatternsLookup(editor));
  26495. const hasDynamicPatterns = () => hasTextPatternsLookup(editor);
  26496. editor.on('keydown', e => {
  26497. if (e.keyCode === 13 && !VK.modifierPressed(e) && editor.selection.isCollapsed()) {
  26498. const patternSet = getPatternSet();
  26499. const hasPatterns = patternSet.inlinePatterns.length > 0 || patternSet.blockPatterns.length > 0 || hasDynamicPatterns();
  26500. if (hasPatterns && handleEnter(editor, patternSet)) {
  26501. e.preventDefault();
  26502. }
  26503. }
  26504. }, true);
  26505. const handleInlineTrigger = () => {
  26506. if (editor.selection.isCollapsed()) {
  26507. const patternSet = getPatternSet();
  26508. const hasPatterns = patternSet.inlinePatterns.length > 0 || hasDynamicPatterns();
  26509. if (hasPatterns) {
  26510. handleInlineKey(editor, patternSet);
  26511. }
  26512. }
  26513. };
  26514. editor.on('keyup', e => {
  26515. if (checkKeyCode(keyCodes, e)) {
  26516. handleInlineTrigger();
  26517. }
  26518. });
  26519. editor.on('keypress', e => {
  26520. if (checkCharCode(charCodes, e)) {
  26521. Delay.setEditorTimeout(editor, handleInlineTrigger);
  26522. }
  26523. });
  26524. };
  26525. const setup$1 = editor => {
  26526. setup$2(editor);
  26527. };
  26528. const Quirks = editor => {
  26529. const each = Tools.each;
  26530. const BACKSPACE = VK.BACKSPACE, DELETE = VK.DELETE, dom = editor.dom, selection = editor.selection, parser = editor.parser;
  26531. const browser = Env.browser;
  26532. const isGecko = browser.isFirefox();
  26533. const isWebKit = browser.isChromium() || browser.isSafari();
  26534. const isiOS = Env.deviceType.isiPhone() || Env.deviceType.isiPad();
  26535. const isMac = Env.os.isMacOS() || Env.os.isiOS();
  26536. const setEditorCommandState = (cmd, state) => {
  26537. try {
  26538. editor.getDoc().execCommand(cmd, false, String(state));
  26539. } catch (ex) {
  26540. }
  26541. };
  26542. const isDefaultPrevented = e => {
  26543. return e.isDefaultPrevented();
  26544. };
  26545. const emptyEditorWhenDeleting = () => {
  26546. const serializeRng = rng => {
  26547. const body = dom.create('body');
  26548. const contents = rng.cloneContents();
  26549. body.appendChild(contents);
  26550. return selection.serializer.serialize(body, { format: 'html' });
  26551. };
  26552. const allContentsSelected = rng => {
  26553. const selection = serializeRng(rng);
  26554. const allRng = dom.createRng();
  26555. allRng.selectNode(editor.getBody());
  26556. const allSelection = serializeRng(allRng);
  26557. return selection === allSelection;
  26558. };
  26559. editor.on('keydown', e => {
  26560. const keyCode = e.keyCode;
  26561. if (!isDefaultPrevented(e) && (keyCode === DELETE || keyCode === BACKSPACE) && editor.selection.isEditable()) {
  26562. const isCollapsed = editor.selection.isCollapsed();
  26563. const body = editor.getBody();
  26564. if (isCollapsed && !dom.isEmpty(body)) {
  26565. return;
  26566. }
  26567. if (!isCollapsed && !allContentsSelected(editor.selection.getRng())) {
  26568. return;
  26569. }
  26570. e.preventDefault();
  26571. editor.setContent('');
  26572. if (body.firstChild && dom.isBlock(body.firstChild)) {
  26573. editor.selection.setCursorLocation(body.firstChild, 0);
  26574. } else {
  26575. editor.selection.setCursorLocation(body, 0);
  26576. }
  26577. editor.nodeChanged();
  26578. }
  26579. });
  26580. };
  26581. const selectAll = () => {
  26582. editor.shortcuts.add('meta+a', null, 'SelectAll');
  26583. };
  26584. const documentElementEditingFocus = () => {
  26585. if (!editor.inline) {
  26586. dom.bind(editor.getDoc(), 'mousedown mouseup', e => {
  26587. let rng;
  26588. if (e.target === editor.getDoc().documentElement) {
  26589. rng = selection.getRng();
  26590. editor.getBody().focus();
  26591. if (e.type === 'mousedown') {
  26592. if (isCaretContainer$2(rng.startContainer)) {
  26593. return;
  26594. }
  26595. selection.placeCaretAt(e.clientX, e.clientY);
  26596. } else {
  26597. selection.setRng(rng);
  26598. }
  26599. }
  26600. });
  26601. }
  26602. };
  26603. const removeHrOnBackspace = () => {
  26604. editor.on('keydown', e => {
  26605. if (!isDefaultPrevented(e) && e.keyCode === BACKSPACE) {
  26606. if (!editor.getBody().getElementsByTagName('hr').length) {
  26607. return;
  26608. }
  26609. if (selection.isCollapsed() && selection.getRng().startOffset === 0) {
  26610. const node = selection.getNode();
  26611. const previousSibling = node.previousSibling;
  26612. if (node.nodeName === 'HR') {
  26613. dom.remove(node);
  26614. e.preventDefault();
  26615. return;
  26616. }
  26617. if (previousSibling && previousSibling.nodeName && previousSibling.nodeName.toLowerCase() === 'hr') {
  26618. dom.remove(previousSibling);
  26619. e.preventDefault();
  26620. }
  26621. }
  26622. }
  26623. });
  26624. };
  26625. const focusBody = () => {
  26626. if (!Range.prototype.getClientRects) {
  26627. editor.on('mousedown', e => {
  26628. if (!isDefaultPrevented(e) && e.target.nodeName === 'HTML') {
  26629. const body = editor.getBody();
  26630. body.blur();
  26631. Delay.setEditorTimeout(editor, () => {
  26632. body.focus();
  26633. });
  26634. }
  26635. });
  26636. }
  26637. };
  26638. const selectControlElements = () => {
  26639. const visualAidsAnchorClass = getVisualAidsAnchorClass(editor);
  26640. editor.on('click', e => {
  26641. const target = e.target;
  26642. if (/^(IMG|HR)$/.test(target.nodeName) && dom.isEditable(target.parentNode)) {
  26643. e.preventDefault();
  26644. editor.selection.select(target);
  26645. editor.nodeChanged();
  26646. }
  26647. if (target.nodeName === 'A' && dom.hasClass(target, visualAidsAnchorClass) && target.childNodes.length === 0 && dom.isEditable(target.parentNode)) {
  26648. e.preventDefault();
  26649. selection.select(target);
  26650. }
  26651. });
  26652. };
  26653. const removeStylesWhenDeletingAcrossBlockElements = () => {
  26654. const getAttributeApplyFunction = () => {
  26655. const template = dom.getAttribs(selection.getStart().cloneNode(false));
  26656. return () => {
  26657. const target = selection.getStart();
  26658. if (target !== editor.getBody()) {
  26659. dom.setAttrib(target, 'style', null);
  26660. each(template, attr => {
  26661. target.setAttributeNode(attr.cloneNode(true));
  26662. });
  26663. }
  26664. };
  26665. };
  26666. const isSelectionAcrossElements = () => {
  26667. return !selection.isCollapsed() && dom.getParent(selection.getStart(), dom.isBlock) !== dom.getParent(selection.getEnd(), dom.isBlock);
  26668. };
  26669. editor.on('keypress', e => {
  26670. let applyAttributes;
  26671. if (!isDefaultPrevented(e) && (e.keyCode === 8 || e.keyCode === 46) && isSelectionAcrossElements()) {
  26672. applyAttributes = getAttributeApplyFunction();
  26673. editor.getDoc().execCommand('delete', false);
  26674. applyAttributes();
  26675. e.preventDefault();
  26676. return false;
  26677. } else {
  26678. return true;
  26679. }
  26680. });
  26681. dom.bind(editor.getDoc(), 'cut', e => {
  26682. if (!isDefaultPrevented(e) && isSelectionAcrossElements()) {
  26683. const applyAttributes = getAttributeApplyFunction();
  26684. Delay.setEditorTimeout(editor, () => {
  26685. applyAttributes();
  26686. });
  26687. }
  26688. });
  26689. };
  26690. const disableBackspaceIntoATable = () => {
  26691. editor.on('keydown', e => {
  26692. if (!isDefaultPrevented(e) && e.keyCode === BACKSPACE) {
  26693. if (selection.isCollapsed() && selection.getRng().startOffset === 0) {
  26694. const previousSibling = selection.getNode().previousSibling;
  26695. if (previousSibling && previousSibling.nodeName && previousSibling.nodeName.toLowerCase() === 'table') {
  26696. e.preventDefault();
  26697. return false;
  26698. }
  26699. }
  26700. }
  26701. return true;
  26702. });
  26703. };
  26704. const removeBlockQuoteOnBackSpace = () => {
  26705. editor.on('keydown', e => {
  26706. if (isDefaultPrevented(e) || e.keyCode !== VK.BACKSPACE) {
  26707. return;
  26708. }
  26709. let rng = selection.getRng();
  26710. const container = rng.startContainer;
  26711. const offset = rng.startOffset;
  26712. const root = dom.getRoot();
  26713. let parent = container;
  26714. if (!rng.collapsed || offset !== 0) {
  26715. return;
  26716. }
  26717. while (parent.parentNode && parent.parentNode.firstChild === parent && parent.parentNode !== root) {
  26718. parent = parent.parentNode;
  26719. }
  26720. if (parent.nodeName === 'BLOCKQUOTE') {
  26721. editor.formatter.toggle('blockquote', undefined, parent);
  26722. rng = dom.createRng();
  26723. rng.setStart(container, 0);
  26724. rng.setEnd(container, 0);
  26725. selection.setRng(rng);
  26726. }
  26727. });
  26728. };
  26729. const setGeckoEditingOptions = () => {
  26730. const setOpts = () => {
  26731. setEditorCommandState('StyleWithCSS', false);
  26732. setEditorCommandState('enableInlineTableEditing', false);
  26733. if (!getObjectResizing(editor)) {
  26734. setEditorCommandState('enableObjectResizing', false);
  26735. }
  26736. };
  26737. if (!isReadOnly$1(editor)) {
  26738. editor.on('BeforeExecCommand mousedown', setOpts);
  26739. }
  26740. };
  26741. const addBrAfterLastLinks = () => {
  26742. const fixLinks = () => {
  26743. each(dom.select('a:not([data-mce-block])'), node => {
  26744. var _a;
  26745. let parentNode = node.parentNode;
  26746. const root = dom.getRoot();
  26747. if ((parentNode === null || parentNode === void 0 ? void 0 : parentNode.lastChild) === node) {
  26748. while (parentNode && !dom.isBlock(parentNode)) {
  26749. if (((_a = parentNode.parentNode) === null || _a === void 0 ? void 0 : _a.lastChild) !== parentNode || parentNode === root) {
  26750. return;
  26751. }
  26752. parentNode = parentNode.parentNode;
  26753. }
  26754. dom.add(parentNode, 'br', { 'data-mce-bogus': 1 });
  26755. }
  26756. });
  26757. };
  26758. editor.on('SetContent ExecCommand', e => {
  26759. if (e.type === 'setcontent' || e.command === 'mceInsertLink') {
  26760. fixLinks();
  26761. }
  26762. });
  26763. };
  26764. const setDefaultBlockType = () => {
  26765. editor.on('init', () => {
  26766. setEditorCommandState('DefaultParagraphSeparator', getForcedRootBlock(editor));
  26767. });
  26768. };
  26769. const isAllContentSelected = editor => {
  26770. const body = editor.getBody();
  26771. const rng = editor.selection.getRng();
  26772. return rng.startContainer === rng.endContainer && rng.startContainer === body && rng.startOffset === 0 && rng.endOffset === body.childNodes.length;
  26773. };
  26774. const normalizeSelection = () => {
  26775. editor.on('keyup focusin mouseup', e => {
  26776. if (!VK.modifierPressed(e) && !isAllContentSelected(editor)) {
  26777. selection.normalize();
  26778. }
  26779. }, true);
  26780. };
  26781. const showBrokenImageIcon = () => {
  26782. editor.contentStyles.push('img:-moz-broken {' + '-moz-force-broken-image-icon:1;' + 'min-width:24px;' + 'min-height:24px' + '}');
  26783. };
  26784. const restoreFocusOnKeyDown = () => {
  26785. if (!editor.inline) {
  26786. editor.on('keydown', () => {
  26787. if (document.activeElement === document.body) {
  26788. editor.getWin().focus();
  26789. }
  26790. });
  26791. }
  26792. };
  26793. const bodyHeight = () => {
  26794. if (!editor.inline) {
  26795. editor.contentStyles.push('body {min-height: 150px}');
  26796. editor.on('click', e => {
  26797. let rng;
  26798. if (e.target.nodeName === 'HTML') {
  26799. rng = editor.selection.getRng();
  26800. editor.getBody().focus();
  26801. editor.selection.setRng(rng);
  26802. editor.selection.normalize();
  26803. editor.nodeChanged();
  26804. }
  26805. });
  26806. }
  26807. };
  26808. const blockCmdArrowNavigation = () => {
  26809. if (isMac) {
  26810. editor.on('keydown', e => {
  26811. if (VK.metaKeyPressed(e) && !e.shiftKey && (e.keyCode === 37 || e.keyCode === 39)) {
  26812. e.preventDefault();
  26813. const selection = editor.selection.getSel();
  26814. selection.modify('move', e.keyCode === 37 ? 'backward' : 'forward', 'lineboundary');
  26815. }
  26816. });
  26817. }
  26818. };
  26819. const tapLinksAndImages = () => {
  26820. editor.on('click', e => {
  26821. let elm = e.target;
  26822. do {
  26823. if (elm.tagName === 'A') {
  26824. e.preventDefault();
  26825. return;
  26826. }
  26827. } while (elm = elm.parentNode);
  26828. });
  26829. editor.contentStyles.push('.mce-content-body {-webkit-touch-callout: none}');
  26830. };
  26831. const blockFormSubmitInsideEditor = () => {
  26832. editor.on('init', () => {
  26833. editor.dom.bind(editor.getBody(), 'submit', e => {
  26834. e.preventDefault();
  26835. });
  26836. });
  26837. };
  26838. const removeAppleInterchangeBrs = () => {
  26839. parser.addNodeFilter('br', nodes => {
  26840. let i = nodes.length;
  26841. while (i--) {
  26842. if (nodes[i].attr('class') === 'Apple-interchange-newline') {
  26843. nodes[i].remove();
  26844. }
  26845. }
  26846. });
  26847. };
  26848. const refreshContentEditable = noop;
  26849. const isHidden = () => {
  26850. if (!isGecko || editor.removed) {
  26851. return false;
  26852. }
  26853. const sel = editor.selection.getSel();
  26854. return !sel || !sel.rangeCount || sel.rangeCount === 0;
  26855. };
  26856. const setupRtc = () => {
  26857. if (isWebKit) {
  26858. documentElementEditingFocus();
  26859. selectControlElements();
  26860. blockFormSubmitInsideEditor();
  26861. selectAll();
  26862. if (isiOS) {
  26863. restoreFocusOnKeyDown();
  26864. bodyHeight();
  26865. tapLinksAndImages();
  26866. }
  26867. }
  26868. if (isGecko) {
  26869. focusBody();
  26870. setGeckoEditingOptions();
  26871. showBrokenImageIcon();
  26872. blockCmdArrowNavigation();
  26873. }
  26874. };
  26875. const setup = () => {
  26876. removeBlockQuoteOnBackSpace();
  26877. emptyEditorWhenDeleting();
  26878. if (!Env.windowsPhone) {
  26879. normalizeSelection();
  26880. }
  26881. if (isWebKit) {
  26882. documentElementEditingFocus();
  26883. selectControlElements();
  26884. setDefaultBlockType();
  26885. blockFormSubmitInsideEditor();
  26886. disableBackspaceIntoATable();
  26887. removeAppleInterchangeBrs();
  26888. if (isiOS) {
  26889. restoreFocusOnKeyDown();
  26890. bodyHeight();
  26891. tapLinksAndImages();
  26892. } else {
  26893. selectAll();
  26894. }
  26895. }
  26896. if (isGecko) {
  26897. removeHrOnBackspace();
  26898. focusBody();
  26899. removeStylesWhenDeletingAcrossBlockElements();
  26900. setGeckoEditingOptions();
  26901. addBrAfterLastLinks();
  26902. showBrokenImageIcon();
  26903. blockCmdArrowNavigation();
  26904. disableBackspaceIntoATable();
  26905. }
  26906. };
  26907. if (isRtc(editor)) {
  26908. setupRtc();
  26909. } else {
  26910. setup();
  26911. }
  26912. return {
  26913. refreshContentEditable,
  26914. isHidden
  26915. };
  26916. };
  26917. const DOM$6 = DOMUtils.DOM;
  26918. const appendStyle = (editor, text) => {
  26919. const body = SugarElement.fromDom(editor.getBody());
  26920. const container = getStyleContainer(getRootNode(body));
  26921. const style = SugarElement.fromTag('style');
  26922. set$3(style, 'type', 'text/css');
  26923. append$1(style, SugarElement.fromText(text));
  26924. append$1(container, style);
  26925. editor.on('remove', () => {
  26926. remove$6(style);
  26927. });
  26928. };
  26929. const getRootName = editor => editor.inline ? editor.getElement().nodeName.toLowerCase() : undefined;
  26930. const removeUndefined = obj => filter$4(obj, v => isUndefined(v) === false);
  26931. const mkParserSettings = editor => {
  26932. const getOption = editor.options.get;
  26933. const blobCache = editor.editorUpload.blobCache;
  26934. return removeUndefined({
  26935. allow_conditional_comments: getOption('allow_conditional_comments'),
  26936. allow_html_data_urls: getOption('allow_html_data_urls'),
  26937. allow_svg_data_urls: getOption('allow_svg_data_urls'),
  26938. allow_html_in_named_anchor: getOption('allow_html_in_named_anchor'),
  26939. allow_script_urls: getOption('allow_script_urls'),
  26940. allow_unsafe_link_target: getOption('allow_unsafe_link_target'),
  26941. convert_fonts_to_spans: getOption('convert_fonts_to_spans'),
  26942. fix_list_elements: getOption('fix_list_elements'),
  26943. font_size_legacy_values: getOption('font_size_legacy_values'),
  26944. forced_root_block: getOption('forced_root_block'),
  26945. forced_root_block_attrs: getOption('forced_root_block_attrs'),
  26946. preserve_cdata: getOption('preserve_cdata'),
  26947. remove_trailing_brs: getOption('remove_trailing_brs'),
  26948. inline_styles: getOption('inline_styles'),
  26949. root_name: getRootName(editor),
  26950. sanitize: getOption('xss_sanitization'),
  26951. validate: true,
  26952. blob_cache: blobCache,
  26953. document: editor.getDoc()
  26954. });
  26955. };
  26956. const mkSchemaSettings = editor => {
  26957. const getOption = editor.options.get;
  26958. return removeUndefined({
  26959. custom_elements: getOption('custom_elements'),
  26960. extended_valid_elements: getOption('extended_valid_elements'),
  26961. invalid_elements: getOption('invalid_elements'),
  26962. invalid_styles: getOption('invalid_styles'),
  26963. schema: getOption('schema'),
  26964. valid_children: getOption('valid_children'),
  26965. valid_classes: getOption('valid_classes'),
  26966. valid_elements: getOption('valid_elements'),
  26967. valid_styles: getOption('valid_styles'),
  26968. verify_html: getOption('verify_html'),
  26969. padd_empty_block_inline_children: getOption('format_empty_lines')
  26970. });
  26971. };
  26972. const mkSerializerSettings = editor => {
  26973. const getOption = editor.options.get;
  26974. return {
  26975. ...mkParserSettings(editor),
  26976. ...mkSchemaSettings(editor),
  26977. ...removeUndefined({
  26978. url_converter: getOption('url_converter'),
  26979. url_converter_scope: getOption('url_converter_scope'),
  26980. element_format: getOption('element_format'),
  26981. entities: getOption('entities'),
  26982. entity_encoding: getOption('entity_encoding'),
  26983. indent: getOption('indent'),
  26984. indent_after: getOption('indent_after'),
  26985. indent_before: getOption('indent_before')
  26986. })
  26987. };
  26988. };
  26989. const createParser = editor => {
  26990. const parser = DomParser(mkParserSettings(editor), editor.schema);
  26991. parser.addAttributeFilter('src,href,style,tabindex', (nodes, name) => {
  26992. const dom = editor.dom;
  26993. const internalName = 'data-mce-' + name;
  26994. let i = nodes.length;
  26995. while (i--) {
  26996. const node = nodes[i];
  26997. let value = node.attr(name);
  26998. if (value && !node.attr(internalName)) {
  26999. if (value.indexOf('data:') === 0 || value.indexOf('blob:') === 0) {
  27000. continue;
  27001. }
  27002. if (name === 'style') {
  27003. value = dom.serializeStyle(dom.parseStyle(value), node.name);
  27004. if (!value.length) {
  27005. value = null;
  27006. }
  27007. node.attr(internalName, value);
  27008. node.attr(name, value);
  27009. } else if (name === 'tabindex') {
  27010. node.attr(internalName, value);
  27011. node.attr(name, null);
  27012. } else {
  27013. node.attr(internalName, editor.convertURL(value, name, node.name));
  27014. }
  27015. }
  27016. }
  27017. });
  27018. parser.addNodeFilter('script', nodes => {
  27019. let i = nodes.length;
  27020. while (i--) {
  27021. const node = nodes[i];
  27022. const type = node.attr('type') || 'no/type';
  27023. if (type.indexOf('mce-') !== 0) {
  27024. node.attr('type', 'mce-' + type);
  27025. }
  27026. }
  27027. });
  27028. if (shouldPreserveCData(editor)) {
  27029. parser.addNodeFilter('#cdata', nodes => {
  27030. var _a;
  27031. let i = nodes.length;
  27032. while (i--) {
  27033. const node = nodes[i];
  27034. node.type = 8;
  27035. node.name = '#comment';
  27036. node.value = '[CDATA[' + editor.dom.encode((_a = node.value) !== null && _a !== void 0 ? _a : '') + ']]';
  27037. }
  27038. });
  27039. }
  27040. parser.addNodeFilter('p,h1,h2,h3,h4,h5,h6,div', nodes => {
  27041. let i = nodes.length;
  27042. const nonEmptyElements = editor.schema.getNonEmptyElements();
  27043. while (i--) {
  27044. const node = nodes[i];
  27045. if (node.isEmpty(nonEmptyElements) && node.getAll('br').length === 0) {
  27046. node.append(new AstNode('br', 1));
  27047. }
  27048. }
  27049. });
  27050. return parser;
  27051. };
  27052. const autoFocus = editor => {
  27053. const autoFocus = getAutoFocus(editor);
  27054. if (autoFocus) {
  27055. Delay.setEditorTimeout(editor, () => {
  27056. let focusEditor;
  27057. if (autoFocus === true) {
  27058. focusEditor = editor;
  27059. } else {
  27060. focusEditor = editor.editorManager.get(autoFocus);
  27061. }
  27062. if (focusEditor && !focusEditor.destroyed) {
  27063. focusEditor.focus();
  27064. focusEditor.selection.scrollIntoView();
  27065. }
  27066. }, 100);
  27067. }
  27068. };
  27069. const moveSelectionToFirstCaretPosition = editor => {
  27070. const root = editor.dom.getRoot();
  27071. if (!editor.inline && (!hasAnyRanges(editor) || editor.selection.getStart(true) === root)) {
  27072. firstPositionIn(root).each(pos => {
  27073. const node = pos.getNode();
  27074. const caretPos = isTable$2(node) ? firstPositionIn(node).getOr(pos) : pos;
  27075. editor.selection.setRng(caretPos.toRange());
  27076. });
  27077. }
  27078. };
  27079. const initEditor = editor => {
  27080. editor.bindPendingEventDelegates();
  27081. editor.initialized = true;
  27082. fireInit(editor);
  27083. editor.focus(true);
  27084. moveSelectionToFirstCaretPosition(editor);
  27085. editor.nodeChanged({ initial: true });
  27086. const initInstanceCallback = getInitInstanceCallback(editor);
  27087. if (isFunction(initInstanceCallback)) {
  27088. initInstanceCallback.call(editor, editor);
  27089. }
  27090. autoFocus(editor);
  27091. };
  27092. const getStyleSheetLoader$1 = editor => editor.inline ? editor.ui.styleSheetLoader : editor.dom.styleSheetLoader;
  27093. const makeStylesheetLoadingPromises = (editor, css, framedFonts) => {
  27094. const promises = [getStyleSheetLoader$1(editor).loadAll(css)];
  27095. if (editor.inline) {
  27096. return promises;
  27097. } else {
  27098. return promises.concat([editor.ui.styleSheetLoader.loadAll(framedFonts)]);
  27099. }
  27100. };
  27101. const loadContentCss = editor => {
  27102. const styleSheetLoader = getStyleSheetLoader$1(editor);
  27103. const fontCss = getFontCss(editor);
  27104. const css = editor.contentCSS;
  27105. const removeCss = () => {
  27106. styleSheetLoader.unloadAll(css);
  27107. if (!editor.inline) {
  27108. editor.ui.styleSheetLoader.unloadAll(fontCss);
  27109. }
  27110. };
  27111. const loaded = () => {
  27112. if (editor.removed) {
  27113. removeCss();
  27114. } else {
  27115. editor.on('remove', removeCss);
  27116. }
  27117. };
  27118. if (editor.contentStyles.length > 0) {
  27119. let contentCssText = '';
  27120. Tools.each(editor.contentStyles, style => {
  27121. contentCssText += style + '\r\n';
  27122. });
  27123. editor.dom.addStyle(contentCssText);
  27124. }
  27125. const allStylesheets = Promise.all(makeStylesheetLoadingPromises(editor, css, fontCss)).then(loaded).catch(loaded);
  27126. const contentStyle = getContentStyle(editor);
  27127. if (contentStyle) {
  27128. appendStyle(editor, contentStyle);
  27129. }
  27130. return allStylesheets;
  27131. };
  27132. const preInit = editor => {
  27133. const doc = editor.getDoc(), body = editor.getBody();
  27134. firePreInit(editor);
  27135. if (!shouldBrowserSpellcheck(editor)) {
  27136. doc.body.spellcheck = false;
  27137. DOM$6.setAttrib(body, 'spellcheck', 'false');
  27138. }
  27139. editor.quirks = Quirks(editor);
  27140. firePostRender(editor);
  27141. const directionality = getDirectionality(editor);
  27142. if (directionality !== undefined) {
  27143. body.dir = directionality;
  27144. }
  27145. const protect = getProtect(editor);
  27146. if (protect) {
  27147. editor.on('BeforeSetContent', e => {
  27148. Tools.each(protect, pattern => {
  27149. e.content = e.content.replace(pattern, str => {
  27150. return '<!--mce:protected ' + escape(str) + '-->';
  27151. });
  27152. });
  27153. });
  27154. }
  27155. editor.on('SetContent', () => {
  27156. editor.addVisual(editor.getBody());
  27157. });
  27158. editor.on('compositionstart compositionend', e => {
  27159. editor.composing = e.type === 'compositionstart';
  27160. });
  27161. };
  27162. const loadInitialContent = editor => {
  27163. if (!isRtc(editor)) {
  27164. editor.load({
  27165. initial: true,
  27166. format: 'html'
  27167. });
  27168. }
  27169. editor.startContent = editor.getContent({ format: 'raw' });
  27170. };
  27171. const initEditorWithInitialContent = editor => {
  27172. if (editor.removed !== true) {
  27173. loadInitialContent(editor);
  27174. initEditor(editor);
  27175. }
  27176. };
  27177. const contentBodyLoaded = editor => {
  27178. const targetElm = editor.getElement();
  27179. let doc = editor.getDoc();
  27180. if (editor.inline) {
  27181. DOM$6.addClass(targetElm, 'mce-content-body');
  27182. editor.contentDocument = doc = document;
  27183. editor.contentWindow = window;
  27184. editor.bodyElement = targetElm;
  27185. editor.contentAreaContainer = targetElm;
  27186. }
  27187. const body = editor.getBody();
  27188. body.disabled = true;
  27189. editor.readonly = isReadOnly$1(editor);
  27190. if (!editor.readonly) {
  27191. if (editor.inline && DOM$6.getStyle(body, 'position', true) === 'static') {
  27192. body.style.position = 'relative';
  27193. }
  27194. body.contentEditable = 'true';
  27195. }
  27196. body.disabled = false;
  27197. editor.editorUpload = EditorUpload(editor);
  27198. editor.schema = Schema(mkSchemaSettings(editor));
  27199. editor.dom = DOMUtils(doc, {
  27200. keep_values: true,
  27201. url_converter: editor.convertURL,
  27202. url_converter_scope: editor,
  27203. update_styles: true,
  27204. root_element: editor.inline ? editor.getBody() : null,
  27205. collect: editor.inline,
  27206. schema: editor.schema,
  27207. contentCssCors: shouldUseContentCssCors(editor),
  27208. referrerPolicy: getReferrerPolicy(editor),
  27209. onSetAttrib: e => {
  27210. editor.dispatch('SetAttrib', e);
  27211. }
  27212. });
  27213. editor.parser = createParser(editor);
  27214. editor.serializer = DomSerializer(mkSerializerSettings(editor), editor);
  27215. editor.selection = EditorSelection(editor.dom, editor.getWin(), editor.serializer, editor);
  27216. editor.annotator = Annotator(editor);
  27217. editor.formatter = Formatter(editor);
  27218. editor.undoManager = UndoManager(editor);
  27219. editor._nodeChangeDispatcher = new NodeChange(editor);
  27220. editor._selectionOverrides = SelectionOverrides(editor);
  27221. setup$o(editor);
  27222. setup$6(editor);
  27223. setup$m(editor);
  27224. if (!isRtc(editor)) {
  27225. setup$5(editor);
  27226. setup$1(editor);
  27227. }
  27228. const caret = setup$b(editor);
  27229. setup$p(editor, caret);
  27230. setup$n(editor);
  27231. setup$q(editor);
  27232. setup$7(editor);
  27233. const setupRtcThunk = setup$s(editor);
  27234. preInit(editor);
  27235. setupRtcThunk.fold(() => {
  27236. loadContentCss(editor).then(() => initEditorWithInitialContent(editor));
  27237. }, setupRtc => {
  27238. editor.setProgressState(true);
  27239. loadContentCss(editor).then(() => {
  27240. setupRtc().then(_rtcMode => {
  27241. editor.setProgressState(false);
  27242. initEditorWithInitialContent(editor);
  27243. bindEvents(editor);
  27244. }, err => {
  27245. editor.notificationManager.open({
  27246. type: 'error',
  27247. text: String(err)
  27248. });
  27249. initEditorWithInitialContent(editor);
  27250. bindEvents(editor);
  27251. });
  27252. });
  27253. });
  27254. };
  27255. const filter = always;
  27256. const bind = (element, event, handler) => bind$2(element, event, filter, handler);
  27257. const DOM$5 = DOMUtils.DOM;
  27258. const createIframeElement = (id, title, customAttrs, tabindex) => {
  27259. const iframe = SugarElement.fromTag('iframe');
  27260. tabindex.each(t => set$3(iframe, 'tabindex', t));
  27261. setAll$1(iframe, customAttrs);
  27262. setAll$1(iframe, {
  27263. id: id + '_ifr',
  27264. frameBorder: '0',
  27265. allowTransparency: 'true',
  27266. title
  27267. });
  27268. add$2(iframe, 'tox-edit-area__iframe');
  27269. return iframe;
  27270. };
  27271. const getIframeHtml = editor => {
  27272. let iframeHTML = getDocType(editor) + '<html><head>';
  27273. if (getDocumentBaseUrl(editor) !== editor.documentBaseUrl) {
  27274. iframeHTML += '<base href="' + editor.documentBaseURI.getURI() + '" />';
  27275. }
  27276. iframeHTML += '<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />';
  27277. const bodyId = getBodyId(editor);
  27278. const bodyClass = getBodyClass(editor);
  27279. const translatedAriaText = editor.translate(getIframeAriaText(editor));
  27280. if (getContentSecurityPolicy(editor)) {
  27281. iframeHTML += '<meta http-equiv="Content-Security-Policy" content="' + getContentSecurityPolicy(editor) + '" />';
  27282. }
  27283. iframeHTML += '</head>' + `<body id="${ bodyId }" class="mce-content-body ${ bodyClass }" data-id="${ editor.id }" aria-label="${ translatedAriaText }">` + '<br>' + '</body></html>';
  27284. return iframeHTML;
  27285. };
  27286. const createIframe = (editor, boxInfo) => {
  27287. const iframeTitle = editor.translate('Rich Text Area');
  27288. const tabindex = getOpt(SugarElement.fromDom(editor.getElement()), 'tabindex').bind(toInt);
  27289. const ifr = createIframeElement(editor.id, iframeTitle, getIframeAttrs(editor), tabindex).dom;
  27290. ifr.onload = () => {
  27291. ifr.onload = null;
  27292. editor.dispatch('load');
  27293. };
  27294. editor.contentAreaContainer = boxInfo.iframeContainer;
  27295. editor.iframeElement = ifr;
  27296. editor.iframeHTML = getIframeHtml(editor);
  27297. DOM$5.add(boxInfo.iframeContainer, ifr);
  27298. };
  27299. const setupIframeBody = editor => {
  27300. const iframe = editor.iframeElement;
  27301. const binder = bind(SugarElement.fromDom(iframe), 'load', () => {
  27302. binder.unbind();
  27303. editor.contentDocument = iframe.contentDocument;
  27304. contentBodyLoaded(editor);
  27305. });
  27306. if (Env.browser.isFirefox()) {
  27307. const doc = editor.getDoc();
  27308. doc.open();
  27309. doc.write(editor.iframeHTML);
  27310. doc.close();
  27311. } else {
  27312. iframe.srcdoc = editor.iframeHTML;
  27313. }
  27314. };
  27315. const init$1 = (editor, boxInfo) => {
  27316. createIframe(editor, boxInfo);
  27317. if (boxInfo.editorContainer) {
  27318. boxInfo.editorContainer.style.display = editor.orgDisplay;
  27319. editor.hidden = DOM$5.isHidden(boxInfo.editorContainer);
  27320. }
  27321. editor.getElement().style.display = 'none';
  27322. DOM$5.setAttrib(editor.id, 'aria-hidden', 'true');
  27323. editor.getElement().style.visibility = editor.orgVisibility;
  27324. setupIframeBody(editor);
  27325. };
  27326. const DOM$4 = DOMUtils.DOM;
  27327. const initPlugin = (editor, initializedPlugins, plugin) => {
  27328. const Plugin = PluginManager.get(plugin);
  27329. const pluginUrl = PluginManager.urls[plugin] || editor.documentBaseUrl.replace(/\/$/, '');
  27330. plugin = Tools.trim(plugin);
  27331. if (Plugin && Tools.inArray(initializedPlugins, plugin) === -1) {
  27332. if (editor.plugins[plugin]) {
  27333. return;
  27334. }
  27335. try {
  27336. const pluginInstance = Plugin(editor, pluginUrl) || {};
  27337. editor.plugins[plugin] = pluginInstance;
  27338. if (isFunction(pluginInstance.init)) {
  27339. pluginInstance.init(editor, pluginUrl);
  27340. initializedPlugins.push(plugin);
  27341. }
  27342. } catch (e) {
  27343. pluginInitError(editor, plugin, e);
  27344. }
  27345. }
  27346. };
  27347. const trimLegacyPrefix = name => {
  27348. return name.replace(/^\-/, '');
  27349. };
  27350. const initPlugins = editor => {
  27351. const initializedPlugins = [];
  27352. each$e(getPlugins(editor), name => {
  27353. initPlugin(editor, initializedPlugins, trimLegacyPrefix(name));
  27354. });
  27355. };
  27356. const initIcons = editor => {
  27357. const iconPackName = Tools.trim(getIconPackName(editor));
  27358. const currentIcons = editor.ui.registry.getAll().icons;
  27359. const loadIcons = {
  27360. ...IconManager.get('default').icons,
  27361. ...IconManager.get(iconPackName).icons
  27362. };
  27363. each$d(loadIcons, (svgData, icon) => {
  27364. if (!has$2(currentIcons, icon)) {
  27365. editor.ui.registry.addIcon(icon, svgData);
  27366. }
  27367. });
  27368. };
  27369. const initTheme = editor => {
  27370. const theme = getTheme(editor);
  27371. if (isString(theme)) {
  27372. const Theme = ThemeManager.get(theme);
  27373. editor.theme = Theme(editor, ThemeManager.urls[theme]) || {};
  27374. if (isFunction(editor.theme.init)) {
  27375. editor.theme.init(editor, ThemeManager.urls[theme] || editor.documentBaseUrl.replace(/\/$/, ''));
  27376. }
  27377. } else {
  27378. editor.theme = {};
  27379. }
  27380. };
  27381. const initModel = editor => {
  27382. const model = getModel(editor);
  27383. const Model = ModelManager.get(model);
  27384. editor.model = Model(editor, ModelManager.urls[model]);
  27385. };
  27386. const renderFromLoadedTheme = editor => {
  27387. const render = editor.theme.renderUI;
  27388. return render ? render() : renderThemeFalse(editor);
  27389. };
  27390. const renderFromThemeFunc = editor => {
  27391. const elm = editor.getElement();
  27392. const theme = getTheme(editor);
  27393. const info = theme(editor, elm);
  27394. if (info.editorContainer.nodeType) {
  27395. info.editorContainer.id = info.editorContainer.id || editor.id + '_parent';
  27396. }
  27397. if (info.iframeContainer && info.iframeContainer.nodeType) {
  27398. info.iframeContainer.id = info.iframeContainer.id || editor.id + '_iframecontainer';
  27399. }
  27400. info.height = info.iframeHeight ? info.iframeHeight : elm.offsetHeight;
  27401. return info;
  27402. };
  27403. const createThemeFalseResult = (element, iframe) => {
  27404. return {
  27405. editorContainer: element,
  27406. iframeContainer: iframe,
  27407. api: {}
  27408. };
  27409. };
  27410. const renderThemeFalseIframe = targetElement => {
  27411. const iframeContainer = DOM$4.create('div');
  27412. DOM$4.insertAfter(iframeContainer, targetElement);
  27413. return createThemeFalseResult(iframeContainer, iframeContainer);
  27414. };
  27415. const renderThemeFalse = editor => {
  27416. const targetElement = editor.getElement();
  27417. return editor.inline ? createThemeFalseResult(null) : renderThemeFalseIframe(targetElement);
  27418. };
  27419. const renderThemeUi = editor => {
  27420. const elm = editor.getElement();
  27421. editor.orgDisplay = elm.style.display;
  27422. if (isString(getTheme(editor))) {
  27423. return renderFromLoadedTheme(editor);
  27424. } else if (isFunction(getTheme(editor))) {
  27425. return renderFromThemeFunc(editor);
  27426. } else {
  27427. return renderThemeFalse(editor);
  27428. }
  27429. };
  27430. const augmentEditorUiApi = (editor, api) => {
  27431. const uiApiFacade = {
  27432. show: Optional.from(api.show).getOr(noop),
  27433. hide: Optional.from(api.hide).getOr(noop),
  27434. isEnabled: Optional.from(api.isEnabled).getOr(always),
  27435. setEnabled: state => {
  27436. if (!editor.mode.isReadOnly()) {
  27437. Optional.from(api.setEnabled).each(f => f(state));
  27438. }
  27439. }
  27440. };
  27441. editor.ui = {
  27442. ...editor.ui,
  27443. ...uiApiFacade
  27444. };
  27445. };
  27446. const init = async editor => {
  27447. editor.dispatch('ScriptsLoaded');
  27448. initIcons(editor);
  27449. initTheme(editor);
  27450. initModel(editor);
  27451. initPlugins(editor);
  27452. const renderInfo = await renderThemeUi(editor);
  27453. augmentEditorUiApi(editor, Optional.from(renderInfo.api).getOr({}));
  27454. editor.editorContainer = renderInfo.editorContainer;
  27455. appendContentCssFromSettings(editor);
  27456. if (editor.inline) {
  27457. contentBodyLoaded(editor);
  27458. } else {
  27459. init$1(editor, {
  27460. editorContainer: renderInfo.editorContainer,
  27461. iframeContainer: renderInfo.iframeContainer
  27462. });
  27463. }
  27464. };
  27465. const DOM$3 = DOMUtils.DOM;
  27466. const hasSkipLoadPrefix = name => name.charAt(0) === '-';
  27467. const loadLanguage = (scriptLoader, editor) => {
  27468. const languageCode = getLanguageCode(editor);
  27469. const languageUrl = getLanguageUrl(editor);
  27470. if (!I18n.hasCode(languageCode) && languageCode !== 'en') {
  27471. const url = isNotEmpty(languageUrl) ? languageUrl : `${ editor.editorManager.baseURL }/langs/${ languageCode }.js`;
  27472. scriptLoader.add(url).catch(() => {
  27473. languageLoadError(editor, url, languageCode);
  27474. });
  27475. }
  27476. };
  27477. const loadTheme = (editor, suffix) => {
  27478. const theme = getTheme(editor);
  27479. if (isString(theme) && !hasSkipLoadPrefix(theme) && !has$2(ThemeManager.urls, theme)) {
  27480. const themeUrl = getThemeUrl(editor);
  27481. const url = themeUrl ? editor.documentBaseURI.toAbsolute(themeUrl) : `themes/${ theme }/theme${ suffix }.js`;
  27482. ThemeManager.load(theme, url).catch(() => {
  27483. themeLoadError(editor, url, theme);
  27484. });
  27485. }
  27486. };
  27487. const loadModel = (editor, suffix) => {
  27488. const model = getModel(editor);
  27489. if (model !== 'plugin' && !has$2(ModelManager.urls, model)) {
  27490. const modelUrl = getModelUrl(editor);
  27491. const url = isString(modelUrl) ? editor.documentBaseURI.toAbsolute(modelUrl) : `models/${ model }/model${ suffix }.js`;
  27492. ModelManager.load(model, url).catch(() => {
  27493. modelLoadError(editor, url, model);
  27494. });
  27495. }
  27496. };
  27497. const getIconsUrlMetaFromUrl = editor => Optional.from(getIconsUrl(editor)).filter(isNotEmpty).map(url => ({
  27498. url,
  27499. name: Optional.none()
  27500. }));
  27501. const getIconsUrlMetaFromName = (editor, name, suffix) => Optional.from(name).filter(name => isNotEmpty(name) && !IconManager.has(name)).map(name => ({
  27502. url: `${ editor.editorManager.baseURL }/icons/${ name }/icons${ suffix }.js`,
  27503. name: Optional.some(name)
  27504. }));
  27505. const loadIcons = (scriptLoader, editor, suffix) => {
  27506. const defaultIconsUrl = getIconsUrlMetaFromName(editor, 'default', suffix);
  27507. const customIconsUrl = getIconsUrlMetaFromUrl(editor).orThunk(() => getIconsUrlMetaFromName(editor, getIconPackName(editor), ''));
  27508. each$e(cat([
  27509. defaultIconsUrl,
  27510. customIconsUrl
  27511. ]), urlMeta => {
  27512. scriptLoader.add(urlMeta.url).catch(() => {
  27513. iconsLoadError(editor, urlMeta.url, urlMeta.name.getOrUndefined());
  27514. });
  27515. });
  27516. };
  27517. const loadPlugins = (editor, suffix) => {
  27518. const loadPlugin = (name, url) => {
  27519. PluginManager.load(name, url).catch(() => {
  27520. pluginLoadError(editor, url, name);
  27521. });
  27522. };
  27523. each$d(getExternalPlugins$1(editor), (url, name) => {
  27524. loadPlugin(name, url);
  27525. editor.options.set('plugins', getPlugins(editor).concat(name));
  27526. });
  27527. each$e(getPlugins(editor), plugin => {
  27528. plugin = Tools.trim(plugin);
  27529. if (plugin && !PluginManager.urls[plugin] && !hasSkipLoadPrefix(plugin)) {
  27530. loadPlugin(plugin, `plugins/${ plugin }/plugin${ suffix }.js`);
  27531. }
  27532. });
  27533. };
  27534. const isThemeLoaded = editor => {
  27535. const theme = getTheme(editor);
  27536. return !isString(theme) || isNonNullable(ThemeManager.get(theme));
  27537. };
  27538. const isModelLoaded = editor => {
  27539. const model = getModel(editor);
  27540. return isNonNullable(ModelManager.get(model));
  27541. };
  27542. const loadScripts = (editor, suffix) => {
  27543. const scriptLoader = ScriptLoader.ScriptLoader;
  27544. const initEditor = () => {
  27545. if (!editor.removed && isThemeLoaded(editor) && isModelLoaded(editor)) {
  27546. init(editor);
  27547. }
  27548. };
  27549. loadTheme(editor, suffix);
  27550. loadModel(editor, suffix);
  27551. loadLanguage(scriptLoader, editor);
  27552. loadIcons(scriptLoader, editor, suffix);
  27553. loadPlugins(editor, suffix);
  27554. scriptLoader.loadQueue().then(initEditor, initEditor);
  27555. };
  27556. const getStyleSheetLoader = (element, editor) => instance.forElement(element, {
  27557. contentCssCors: hasContentCssCors(editor),
  27558. referrerPolicy: getReferrerPolicy(editor)
  27559. });
  27560. const render = editor => {
  27561. const id = editor.id;
  27562. I18n.setCode(getLanguageCode(editor));
  27563. const readyHandler = () => {
  27564. DOM$3.unbind(window, 'ready', readyHandler);
  27565. editor.render();
  27566. };
  27567. if (!EventUtils.Event.domLoaded) {
  27568. DOM$3.bind(window, 'ready', readyHandler);
  27569. return;
  27570. }
  27571. if (!editor.getElement()) {
  27572. return;
  27573. }
  27574. const element = SugarElement.fromDom(editor.getElement());
  27575. const snapshot = clone$4(element);
  27576. editor.on('remove', () => {
  27577. eachr(element.dom.attributes, attr => remove$b(element, attr.name));
  27578. setAll$1(element, snapshot);
  27579. });
  27580. editor.ui.styleSheetLoader = getStyleSheetLoader(element, editor);
  27581. if (!isInline(editor)) {
  27582. editor.orgVisibility = editor.getElement().style.visibility;
  27583. editor.getElement().style.visibility = 'hidden';
  27584. } else {
  27585. editor.inline = true;
  27586. }
  27587. const form = editor.getElement().form || DOM$3.getParent(id, 'form');
  27588. if (form) {
  27589. editor.formElement = form;
  27590. if (hasHiddenInput(editor) && !isTextareaOrInput(editor.getElement())) {
  27591. DOM$3.insertAfter(DOM$3.create('input', {
  27592. type: 'hidden',
  27593. name: id
  27594. }), id);
  27595. editor.hasHiddenInput = true;
  27596. }
  27597. editor.formEventDelegate = e => {
  27598. editor.dispatch(e.type, e);
  27599. };
  27600. DOM$3.bind(form, 'submit reset', editor.formEventDelegate);
  27601. editor.on('reset', () => {
  27602. editor.resetContent();
  27603. });
  27604. if (shouldPatchSubmit(editor) && !form.submit.nodeType && !form.submit.length && !form._mceOldSubmit) {
  27605. form._mceOldSubmit = form.submit;
  27606. form.submit = () => {
  27607. editor.editorManager.triggerSave();
  27608. editor.setDirty(false);
  27609. return form._mceOldSubmit(form);
  27610. };
  27611. }
  27612. }
  27613. editor.windowManager = WindowManager(editor);
  27614. editor.notificationManager = NotificationManager(editor);
  27615. if (isEncodingXml(editor)) {
  27616. editor.on('GetContent', e => {
  27617. if (e.save) {
  27618. e.content = DOM$3.encode(e.content);
  27619. }
  27620. });
  27621. }
  27622. if (shouldAddFormSubmitTrigger(editor)) {
  27623. editor.on('submit', () => {
  27624. if (editor.initialized) {
  27625. editor.save();
  27626. }
  27627. });
  27628. }
  27629. if (shouldAddUnloadTrigger(editor)) {
  27630. editor._beforeUnload = () => {
  27631. if (editor.initialized && !editor.destroyed && !editor.isHidden()) {
  27632. editor.save({
  27633. format: 'raw',
  27634. no_events: true,
  27635. set_dirty: false
  27636. });
  27637. }
  27638. };
  27639. editor.editorManager.on('BeforeUnload', editor._beforeUnload);
  27640. }
  27641. editor.editorManager.add(editor);
  27642. loadScripts(editor, editor.suffix);
  27643. };
  27644. const sectionResult = (sections, settings) => ({
  27645. sections: constant(sections),
  27646. options: constant(settings)
  27647. });
  27648. const deviceDetection = detect$2().deviceType;
  27649. const isPhone = deviceDetection.isPhone();
  27650. const isTablet = deviceDetection.isTablet();
  27651. const normalizePlugins = plugins => {
  27652. if (isNullable(plugins)) {
  27653. return [];
  27654. } else {
  27655. const pluginNames = isArray$1(plugins) ? plugins : plugins.split(/[ ,]/);
  27656. const trimmedPlugins = map$3(pluginNames, trim$3);
  27657. return filter$5(trimmedPlugins, isNotEmpty);
  27658. }
  27659. };
  27660. const extractSections = (keys, options) => {
  27661. const result = bifilter(options, (value, key) => {
  27662. return contains$2(keys, key);
  27663. });
  27664. return sectionResult(result.t, result.f);
  27665. };
  27666. const getSection = (sectionResult, name, defaults = {}) => {
  27667. const sections = sectionResult.sections();
  27668. const sectionOptions = get$a(sections, name).getOr({});
  27669. return Tools.extend({}, defaults, sectionOptions);
  27670. };
  27671. const hasSection = (sectionResult, name) => {
  27672. return has$2(sectionResult.sections(), name);
  27673. };
  27674. const getSectionConfig = (sectionResult, name) => {
  27675. return hasSection(sectionResult, name) ? sectionResult.sections()[name] : {};
  27676. };
  27677. const getMobileOverrideOptions = (mobileOptions, isPhone) => {
  27678. const defaultMobileOptions = {
  27679. table_grid: false,
  27680. object_resizing: false,
  27681. resize: false,
  27682. toolbar_mode: get$a(mobileOptions, 'toolbar_mode').getOr('scrolling'),
  27683. toolbar_sticky: false
  27684. };
  27685. const defaultPhoneOptions = { menubar: false };
  27686. return {
  27687. ...defaultMobileOptions,
  27688. ...isPhone ? defaultPhoneOptions : {}
  27689. };
  27690. };
  27691. const getExternalPlugins = (overrideOptions, options) => {
  27692. var _a;
  27693. const userDefinedExternalPlugins = (_a = options.external_plugins) !== null && _a !== void 0 ? _a : {};
  27694. if (overrideOptions && overrideOptions.external_plugins) {
  27695. return Tools.extend({}, overrideOptions.external_plugins, userDefinedExternalPlugins);
  27696. } else {
  27697. return userDefinedExternalPlugins;
  27698. }
  27699. };
  27700. const combinePlugins = (forcedPlugins, plugins) => [
  27701. ...normalizePlugins(forcedPlugins),
  27702. ...normalizePlugins(plugins)
  27703. ];
  27704. const getPlatformPlugins = (isMobileDevice, sectionResult, desktopPlugins, mobilePlugins) => {
  27705. if (isMobileDevice && hasSection(sectionResult, 'mobile')) {
  27706. return mobilePlugins;
  27707. } else {
  27708. return desktopPlugins;
  27709. }
  27710. };
  27711. const processPlugins = (isMobileDevice, sectionResult, defaultOverrideOptions, options) => {
  27712. const forcedPlugins = normalizePlugins(defaultOverrideOptions.forced_plugins);
  27713. const desktopPlugins = normalizePlugins(options.plugins);
  27714. const mobileConfig = getSectionConfig(sectionResult, 'mobile');
  27715. const mobilePlugins = mobileConfig.plugins ? normalizePlugins(mobileConfig.plugins) : desktopPlugins;
  27716. const platformPlugins = getPlatformPlugins(isMobileDevice, sectionResult, desktopPlugins, mobilePlugins);
  27717. const combinedPlugins = combinePlugins(forcedPlugins, platformPlugins);
  27718. return Tools.extend(options, {
  27719. forced_plugins: forcedPlugins,
  27720. plugins: combinedPlugins
  27721. });
  27722. };
  27723. const isOnMobile = (isMobileDevice, sectionResult) => {
  27724. return isMobileDevice && hasSection(sectionResult, 'mobile');
  27725. };
  27726. const combineOptions = (isMobileDevice, isPhone, defaultOptions, defaultOverrideOptions, options) => {
  27727. var _a;
  27728. const deviceOverrideOptions = isMobileDevice ? { mobile: getMobileOverrideOptions((_a = options.mobile) !== null && _a !== void 0 ? _a : {}, isPhone) } : {};
  27729. const sectionResult = extractSections(['mobile'], deepMerge(deviceOverrideOptions, options));
  27730. const extendedOptions = Tools.extend(defaultOptions, defaultOverrideOptions, sectionResult.options(), isOnMobile(isMobileDevice, sectionResult) ? getSection(sectionResult, 'mobile') : {}, { external_plugins: getExternalPlugins(defaultOverrideOptions, sectionResult.options()) });
  27731. return processPlugins(isMobileDevice, sectionResult, defaultOverrideOptions, extendedOptions);
  27732. };
  27733. const normalizeOptions = (defaultOverrideOptions, options) => combineOptions(isPhone || isTablet, isPhone, options, defaultOverrideOptions, options);
  27734. const addVisual = (editor, elm) => addVisual$1(editor, elm);
  27735. const registerExecCommands$3 = editor => {
  27736. const toggleFormat = (name, value) => {
  27737. editor.formatter.toggle(name, value);
  27738. editor.nodeChanged();
  27739. };
  27740. const toggleAlign = align => () => {
  27741. each$e('left,center,right,justify'.split(','), name => {
  27742. if (align !== name) {
  27743. editor.formatter.remove('align' + name);
  27744. }
  27745. });
  27746. if (align !== 'none') {
  27747. toggleFormat('align' + align);
  27748. }
  27749. };
  27750. editor.editorCommands.addCommands({
  27751. JustifyLeft: toggleAlign('left'),
  27752. JustifyCenter: toggleAlign('center'),
  27753. JustifyRight: toggleAlign('right'),
  27754. JustifyFull: toggleAlign('justify'),
  27755. JustifyNone: toggleAlign('none')
  27756. });
  27757. };
  27758. const registerQueryStateCommands$1 = editor => {
  27759. const alignStates = name => () => {
  27760. const selection = editor.selection;
  27761. const nodes = selection.isCollapsed() ? [editor.dom.getParent(selection.getNode(), editor.dom.isBlock)] : selection.getSelectedBlocks();
  27762. return exists(nodes, node => isNonNullable(editor.formatter.matchNode(node, name)));
  27763. };
  27764. editor.editorCommands.addCommands({
  27765. JustifyLeft: alignStates('alignleft'),
  27766. JustifyCenter: alignStates('aligncenter'),
  27767. JustifyRight: alignStates('alignright'),
  27768. JustifyFull: alignStates('alignjustify')
  27769. }, 'state');
  27770. };
  27771. const registerCommands$a = editor => {
  27772. registerExecCommands$3(editor);
  27773. registerQueryStateCommands$1(editor);
  27774. };
  27775. const registerCommands$9 = editor => {
  27776. editor.editorCommands.addCommands({
  27777. 'Cut,Copy,Paste': command => {
  27778. const doc = editor.getDoc();
  27779. let failed;
  27780. try {
  27781. doc.execCommand(command);
  27782. } catch (ex) {
  27783. failed = true;
  27784. }
  27785. if (command === 'paste' && !doc.queryCommandEnabled(command)) {
  27786. failed = true;
  27787. }
  27788. if (failed || !doc.queryCommandSupported(command)) {
  27789. let msg = editor.translate(`Your browser doesn't support direct access to the clipboard. ` + 'Please use the Ctrl+X/C/V keyboard shortcuts instead.');
  27790. if (Env.os.isMacOS() || Env.os.isiOS()) {
  27791. msg = msg.replace(/Ctrl\+/g, '\u2318+');
  27792. }
  27793. editor.notificationManager.open({
  27794. text: msg,
  27795. type: 'error'
  27796. });
  27797. }
  27798. }
  27799. });
  27800. };
  27801. const trimOrPadLeftRight = (dom, rng, html) => {
  27802. const root = SugarElement.fromDom(dom.getRoot());
  27803. if (needsToBeNbspLeft(root, CaretPosition.fromRangeStart(rng))) {
  27804. html = html.replace(/^ /, '&nbsp;');
  27805. } else {
  27806. html = html.replace(/^&nbsp;/, ' ');
  27807. }
  27808. if (needsToBeNbspRight(root, CaretPosition.fromRangeEnd(rng))) {
  27809. html = html.replace(/(&nbsp;| )(<br( \/)>)?$/, '&nbsp;');
  27810. } else {
  27811. html = html.replace(/&nbsp;(<br( \/)?>)?$/, ' ');
  27812. }
  27813. return html;
  27814. };
  27815. const processValue$1 = value => {
  27816. if (typeof value !== 'string') {
  27817. const details = Tools.extend({
  27818. paste: value.paste,
  27819. data: { paste: value.paste }
  27820. }, value);
  27821. return {
  27822. content: value.content,
  27823. details
  27824. };
  27825. }
  27826. return {
  27827. content: value,
  27828. details: {}
  27829. };
  27830. };
  27831. const trimOrPad = (editor, value) => {
  27832. const selection = editor.selection;
  27833. const dom = editor.dom;
  27834. if (/^ | $/.test(value)) {
  27835. return trimOrPadLeftRight(dom, selection.getRng(), value);
  27836. } else {
  27837. return value;
  27838. }
  27839. };
  27840. const insertAtCaret = (editor, value) => {
  27841. if (editor.selection.isEditable()) {
  27842. const {content, details} = processValue$1(value);
  27843. preProcessSetContent(editor, {
  27844. ...details,
  27845. content: trimOrPad(editor, content),
  27846. format: 'html',
  27847. set: false,
  27848. selection: true
  27849. }).each(args => {
  27850. const insertedContent = insertContent$1(editor, args.content, details);
  27851. postProcessSetContent(editor, insertedContent, args);
  27852. editor.addVisual();
  27853. });
  27854. }
  27855. };
  27856. const registerCommands$8 = editor => {
  27857. editor.editorCommands.addCommands({
  27858. mceCleanup: () => {
  27859. const bm = editor.selection.getBookmark();
  27860. editor.setContent(editor.getContent());
  27861. editor.selection.moveToBookmark(bm);
  27862. },
  27863. insertImage: (_command, _ui, value) => {
  27864. insertAtCaret(editor, editor.dom.createHTML('img', { src: value }));
  27865. },
  27866. insertHorizontalRule: () => {
  27867. editor.execCommand('mceInsertContent', false, '<hr>');
  27868. },
  27869. insertText: (_command, _ui, value) => {
  27870. insertAtCaret(editor, editor.dom.encode(value));
  27871. },
  27872. insertHTML: (_command, _ui, value) => {
  27873. insertAtCaret(editor, value);
  27874. },
  27875. mceInsertContent: (_command, _ui, value) => {
  27876. insertAtCaret(editor, value);
  27877. },
  27878. mceSetContent: (_command, _ui, value) => {
  27879. editor.setContent(value);
  27880. },
  27881. mceReplaceContent: (_command, _ui, value) => {
  27882. editor.execCommand('mceInsertContent', false, value.replace(/\{\$selection\}/g, editor.selection.getContent({ format: 'text' })));
  27883. },
  27884. mceNewDocument: () => {
  27885. editor.setContent('');
  27886. }
  27887. });
  27888. };
  27889. const legacyPropNames = {
  27890. 'font-size': 'size',
  27891. 'font-family': 'face'
  27892. };
  27893. const isFont = isTag('font');
  27894. const getSpecifiedFontProp = (propName, rootElm, elm) => {
  27895. const getProperty = elm => getRaw(elm, propName).orThunk(() => {
  27896. if (isFont(elm)) {
  27897. return get$a(legacyPropNames, propName).bind(legacyPropName => getOpt(elm, legacyPropName));
  27898. } else {
  27899. return Optional.none();
  27900. }
  27901. });
  27902. const isRoot = elm => eq(SugarElement.fromDom(rootElm), elm);
  27903. return closest$1(SugarElement.fromDom(elm), elm => getProperty(elm), isRoot);
  27904. };
  27905. const normalizeFontFamily = fontFamily => fontFamily.replace(/[\'\"\\]/g, '').replace(/,\s+/g, ',');
  27906. const getComputedFontProp = (propName, elm) => Optional.from(DOMUtils.DOM.getStyle(elm, propName, true));
  27907. 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('');
  27908. const getFontSize = getFontProp('font-size');
  27909. const getFontFamily = compose(normalizeFontFamily, getFontProp('font-family'));
  27910. const findFirstCaretElement = editor => firstPositionIn(editor.getBody()).bind(caret => {
  27911. const container = caret.container();
  27912. return Optional.from(isText$a(container) ? container.parentNode : container);
  27913. });
  27914. const getCaretElement = editor => Optional.from(editor.selection.getRng()).bind(rng => {
  27915. const root = editor.getBody();
  27916. const atStartOfNode = rng.startContainer === root && rng.startOffset === 0;
  27917. return atStartOfNode ? Optional.none() : Optional.from(editor.selection.getStart(true));
  27918. });
  27919. const bindRange = (editor, binder) => getCaretElement(editor).orThunk(curry(findFirstCaretElement, editor)).map(SugarElement.fromDom).filter(isElement$7).bind(binder);
  27920. const mapRange = (editor, mapper) => bindRange(editor, compose1(Optional.some, mapper));
  27921. const fromFontSizeNumber = (editor, value) => {
  27922. if (/^[0-9.]+$/.test(value)) {
  27923. const fontSizeNumber = parseInt(value, 10);
  27924. if (fontSizeNumber >= 1 && fontSizeNumber <= 7) {
  27925. const fontSizes = getFontStyleValues(editor);
  27926. const fontClasses = getFontSizeClasses(editor);
  27927. if (fontClasses.length > 0) {
  27928. return fontClasses[fontSizeNumber - 1] || value;
  27929. } else {
  27930. return fontSizes[fontSizeNumber - 1] || value;
  27931. }
  27932. } else {
  27933. return value;
  27934. }
  27935. } else {
  27936. return value;
  27937. }
  27938. };
  27939. const normalizeFontNames = font => {
  27940. const fonts = font.split(/\s*,\s*/);
  27941. return map$3(fonts, font => {
  27942. if (font.indexOf(' ') !== -1 && !(startsWith(font, '"') || startsWith(font, `'`))) {
  27943. return `'${ font }'`;
  27944. } else {
  27945. return font;
  27946. }
  27947. }).join(',');
  27948. };
  27949. const fontNameAction = (editor, value) => {
  27950. const font = fromFontSizeNumber(editor, value);
  27951. editor.formatter.toggle('fontname', { value: normalizeFontNames(font) });
  27952. editor.nodeChanged();
  27953. };
  27954. const fontNameQuery = editor => mapRange(editor, elm => getFontFamily(editor.getBody(), elm.dom)).getOr('');
  27955. const fontSizeAction = (editor, value) => {
  27956. editor.formatter.toggle('fontsize', { value: fromFontSizeNumber(editor, value) });
  27957. editor.nodeChanged();
  27958. };
  27959. const fontSizeQuery = editor => mapRange(editor, elm => getFontSize(editor.getBody(), elm.dom)).getOr('');
  27960. const lineHeightQuery = editor => mapRange(editor, elm => {
  27961. const root = SugarElement.fromDom(editor.getBody());
  27962. const specifiedStyle = closest$1(elm, elm => getRaw(elm, 'line-height'), curry(eq, root));
  27963. const computedStyle = () => {
  27964. const lineHeight = parseFloat(get$7(elm, 'line-height'));
  27965. const fontSize = parseFloat(get$7(elm, 'font-size'));
  27966. return String(lineHeight / fontSize);
  27967. };
  27968. return specifiedStyle.getOrThunk(computedStyle);
  27969. }).getOr('');
  27970. const lineHeightAction = (editor, lineHeight) => {
  27971. editor.formatter.toggle('lineheight', { value: String(lineHeight) });
  27972. editor.nodeChanged();
  27973. };
  27974. const registerExecCommands$2 = editor => {
  27975. const toggleFormat = (name, value) => {
  27976. editor.formatter.toggle(name, value);
  27977. editor.nodeChanged();
  27978. };
  27979. editor.editorCommands.addCommands({
  27980. 'Bold,Italic,Underline,Strikethrough,Superscript,Subscript': command => {
  27981. toggleFormat(command);
  27982. },
  27983. 'ForeColor,HiliteColor': (command, _ui, value) => {
  27984. toggleFormat(command, { value });
  27985. },
  27986. 'BackColor': (_command, _ui, value) => {
  27987. toggleFormat('hilitecolor', { value });
  27988. },
  27989. 'FontName': (_command, _ui, value) => {
  27990. fontNameAction(editor, value);
  27991. },
  27992. 'FontSize': (_command, _ui, value) => {
  27993. fontSizeAction(editor, value);
  27994. },
  27995. 'LineHeight': (_command, _ui, value) => {
  27996. lineHeightAction(editor, value);
  27997. },
  27998. 'Lang': (command, _ui, lang) => {
  27999. var _a;
  28000. toggleFormat(command, {
  28001. value: lang.code,
  28002. customValue: (_a = lang.customCode) !== null && _a !== void 0 ? _a : null
  28003. });
  28004. },
  28005. 'RemoveFormat': command => {
  28006. editor.formatter.remove(command);
  28007. },
  28008. 'mceBlockQuote': () => {
  28009. toggleFormat('blockquote');
  28010. },
  28011. 'FormatBlock': (_command, _ui, value) => {
  28012. toggleFormat(isString(value) ? value : 'p');
  28013. },
  28014. 'mceToggleFormat': (_command, _ui, value) => {
  28015. toggleFormat(value);
  28016. }
  28017. });
  28018. };
  28019. const registerQueryValueCommands = editor => {
  28020. const isFormatMatch = name => editor.formatter.match(name);
  28021. editor.editorCommands.addCommands({
  28022. 'Bold,Italic,Underline,Strikethrough,Superscript,Subscript': command => isFormatMatch(command),
  28023. 'mceBlockQuote': () => isFormatMatch('blockquote')
  28024. }, 'state');
  28025. editor.editorCommands.addQueryValueHandler('FontName', () => fontNameQuery(editor));
  28026. editor.editorCommands.addQueryValueHandler('FontSize', () => fontSizeQuery(editor));
  28027. editor.editorCommands.addQueryValueHandler('LineHeight', () => lineHeightQuery(editor));
  28028. };
  28029. const registerCommands$7 = editor => {
  28030. registerExecCommands$2(editor);
  28031. registerQueryValueCommands(editor);
  28032. };
  28033. const registerCommands$6 = editor => {
  28034. editor.editorCommands.addCommands({
  28035. mceAddUndoLevel: () => {
  28036. editor.undoManager.add();
  28037. },
  28038. mceEndUndoLevel: () => {
  28039. editor.undoManager.add();
  28040. },
  28041. Undo: () => {
  28042. editor.undoManager.undo();
  28043. },
  28044. Redo: () => {
  28045. editor.undoManager.redo();
  28046. }
  28047. });
  28048. };
  28049. const registerCommands$5 = editor => {
  28050. editor.editorCommands.addCommands({
  28051. Indent: () => {
  28052. indent(editor);
  28053. },
  28054. Outdent: () => {
  28055. outdent(editor);
  28056. }
  28057. });
  28058. editor.editorCommands.addCommands({ Outdent: () => canOutdent(editor) }, 'state');
  28059. };
  28060. const registerCommands$4 = editor => {
  28061. const applyLinkToSelection = (_command, _ui, value) => {
  28062. const linkDetails = isString(value) ? { href: value } : value;
  28063. const anchor = editor.dom.getParent(editor.selection.getNode(), 'a');
  28064. if (isObject(linkDetails) && isString(linkDetails.href)) {
  28065. linkDetails.href = linkDetails.href.replace(/ /g, '%20');
  28066. if (!anchor || !linkDetails.href) {
  28067. editor.formatter.remove('link');
  28068. }
  28069. if (linkDetails.href) {
  28070. editor.formatter.apply('link', linkDetails, anchor);
  28071. }
  28072. }
  28073. };
  28074. editor.editorCommands.addCommands({
  28075. unlink: () => {
  28076. if (editor.selection.isCollapsed()) {
  28077. const elm = editor.dom.getParent(editor.selection.getStart(), 'a');
  28078. if (elm) {
  28079. editor.dom.remove(elm, true);
  28080. }
  28081. return;
  28082. }
  28083. editor.formatter.remove('link');
  28084. },
  28085. mceInsertLink: applyLinkToSelection,
  28086. createLink: applyLinkToSelection
  28087. });
  28088. };
  28089. const registerExecCommands$1 = editor => {
  28090. editor.editorCommands.addCommands({
  28091. 'InsertUnorderedList,InsertOrderedList': command => {
  28092. editor.getDoc().execCommand(command);
  28093. const listElm = editor.dom.getParent(editor.selection.getNode(), 'ol,ul');
  28094. if (listElm) {
  28095. const listParent = listElm.parentNode;
  28096. if (listParent && /^(H[1-6]|P|ADDRESS|PRE)$/.test(listParent.nodeName)) {
  28097. const bm = editor.selection.getBookmark();
  28098. editor.dom.split(listParent, listElm);
  28099. editor.selection.moveToBookmark(bm);
  28100. }
  28101. }
  28102. }
  28103. });
  28104. };
  28105. const registerQueryStateCommands = editor => {
  28106. editor.editorCommands.addCommands({
  28107. 'InsertUnorderedList,InsertOrderedList': command => {
  28108. const list = editor.dom.getParent(editor.selection.getNode(), 'ul,ol');
  28109. return list && (command === 'insertunorderedlist' && list.tagName === 'UL' || command === 'insertorderedlist' && list.tagName === 'OL');
  28110. }
  28111. }, 'state');
  28112. };
  28113. const registerCommands$3 = editor => {
  28114. registerExecCommands$1(editor);
  28115. registerQueryStateCommands(editor);
  28116. };
  28117. const registerCommands$2 = editor => {
  28118. editor.editorCommands.addCommands({
  28119. insertParagraph: () => {
  28120. insertBreak(blockbreak, editor);
  28121. },
  28122. mceInsertNewLine: (_command, _ui, value) => {
  28123. insert(editor, value);
  28124. },
  28125. InsertLineBreak: (_command, _ui, _value) => {
  28126. insertBreak(linebreak, editor);
  28127. }
  28128. });
  28129. };
  28130. const registerCommands$1 = editor => {
  28131. editor.editorCommands.addCommands({
  28132. mceSelectNodeDepth: (_command, _ui, value) => {
  28133. let counter = 0;
  28134. editor.dom.getParent(editor.selection.getNode(), node => {
  28135. if (isElement$6(node) && counter++ === value) {
  28136. editor.selection.select(node);
  28137. return false;
  28138. } else {
  28139. return true;
  28140. }
  28141. }, editor.getBody());
  28142. },
  28143. mceSelectNode: (_command, _ui, value) => {
  28144. editor.selection.select(value);
  28145. },
  28146. selectAll: () => {
  28147. const editingHost = editor.dom.getParent(editor.selection.getStart(), isContentEditableTrue$3);
  28148. if (editingHost) {
  28149. const rng = editor.dom.createRng();
  28150. rng.selectNodeContents(editingHost);
  28151. editor.selection.setRng(rng);
  28152. }
  28153. }
  28154. });
  28155. };
  28156. const registerExecCommands = editor => {
  28157. editor.editorCommands.addCommands({
  28158. mceRemoveNode: (_command, _ui, value) => {
  28159. const node = value !== null && value !== void 0 ? value : editor.selection.getNode();
  28160. if (node !== editor.getBody()) {
  28161. const bm = editor.selection.getBookmark();
  28162. editor.dom.remove(node, true);
  28163. editor.selection.moveToBookmark(bm);
  28164. }
  28165. },
  28166. mcePrint: () => {
  28167. editor.getWin().print();
  28168. },
  28169. mceFocus: (_command, _ui, value) => {
  28170. focus(editor, value === true);
  28171. },
  28172. mceToggleVisualAid: () => {
  28173. editor.hasVisual = !editor.hasVisual;
  28174. editor.addVisual();
  28175. }
  28176. });
  28177. };
  28178. const registerCommands = editor => {
  28179. registerCommands$a(editor);
  28180. registerCommands$9(editor);
  28181. registerCommands$6(editor);
  28182. registerCommands$1(editor);
  28183. registerCommands$8(editor);
  28184. registerCommands$4(editor);
  28185. registerCommands$5(editor);
  28186. registerCommands$2(editor);
  28187. registerCommands$3(editor);
  28188. registerCommands$7(editor);
  28189. registerExecCommands(editor);
  28190. };
  28191. const selectionSafeCommands = ['toggleview'];
  28192. const isSelectionSafeCommand = command => contains$2(selectionSafeCommands, command.toLowerCase());
  28193. class EditorCommands {
  28194. constructor(editor) {
  28195. this.commands = {
  28196. state: {},
  28197. exec: {},
  28198. value: {}
  28199. };
  28200. this.editor = editor;
  28201. }
  28202. execCommand(command, ui = false, value, args) {
  28203. const editor = this.editor;
  28204. const lowerCaseCommand = command.toLowerCase();
  28205. const skipFocus = args === null || args === void 0 ? void 0 : args.skip_focus;
  28206. if (editor.removed) {
  28207. return false;
  28208. }
  28209. if (lowerCaseCommand !== 'mcefocus') {
  28210. if (!/^(mceAddUndoLevel|mceEndUndoLevel)$/i.test(lowerCaseCommand) && !skipFocus) {
  28211. editor.focus();
  28212. } else {
  28213. restore(editor);
  28214. }
  28215. }
  28216. const eventArgs = editor.dispatch('BeforeExecCommand', {
  28217. command,
  28218. ui,
  28219. value
  28220. });
  28221. if (eventArgs.isDefaultPrevented()) {
  28222. return false;
  28223. }
  28224. const func = this.commands.exec[lowerCaseCommand];
  28225. if (isFunction(func)) {
  28226. func(lowerCaseCommand, ui, value);
  28227. editor.dispatch('ExecCommand', {
  28228. command,
  28229. ui,
  28230. value
  28231. });
  28232. return true;
  28233. }
  28234. return false;
  28235. }
  28236. queryCommandState(command) {
  28237. if (!isSelectionSafeCommand(command) && this.editor.quirks.isHidden() || this.editor.removed) {
  28238. return false;
  28239. }
  28240. const lowerCaseCommand = command.toLowerCase();
  28241. const func = this.commands.state[lowerCaseCommand];
  28242. if (isFunction(func)) {
  28243. return func(lowerCaseCommand);
  28244. }
  28245. return false;
  28246. }
  28247. queryCommandValue(command) {
  28248. if (!isSelectionSafeCommand(command) && this.editor.quirks.isHidden() || this.editor.removed) {
  28249. return '';
  28250. }
  28251. const lowerCaseCommand = command.toLowerCase();
  28252. const func = this.commands.value[lowerCaseCommand];
  28253. if (isFunction(func)) {
  28254. return func(lowerCaseCommand);
  28255. }
  28256. return '';
  28257. }
  28258. addCommands(commandList, type = 'exec') {
  28259. const commands = this.commands;
  28260. each$d(commandList, (callback, command) => {
  28261. each$e(command.toLowerCase().split(','), command => {
  28262. commands[type][command] = callback;
  28263. });
  28264. });
  28265. }
  28266. addCommand(command, callback, scope) {
  28267. const lowerCaseCommand = command.toLowerCase();
  28268. this.commands.exec[lowerCaseCommand] = (_command, ui, value) => callback.call(scope !== null && scope !== void 0 ? scope : this.editor, ui, value);
  28269. }
  28270. queryCommandSupported(command) {
  28271. const lowerCaseCommand = command.toLowerCase();
  28272. if (this.commands.exec[lowerCaseCommand]) {
  28273. return true;
  28274. } else {
  28275. return false;
  28276. }
  28277. }
  28278. addQueryStateHandler(command, callback, scope) {
  28279. this.commands.state[command.toLowerCase()] = () => callback.call(scope !== null && scope !== void 0 ? scope : this.editor);
  28280. }
  28281. addQueryValueHandler(command, callback, scope) {
  28282. this.commands.value[command.toLowerCase()] = () => callback.call(scope !== null && scope !== void 0 ? scope : this.editor);
  28283. }
  28284. }
  28285. const internalContentEditableAttr = 'data-mce-contenteditable';
  28286. const toggleClass = (elm, cls, state) => {
  28287. if (has(elm, cls) && !state) {
  28288. remove$8(elm, cls);
  28289. } else if (state) {
  28290. add$2(elm, cls);
  28291. }
  28292. };
  28293. const setEditorCommandState = (editor, cmd, state) => {
  28294. try {
  28295. editor.getDoc().execCommand(cmd, false, String(state));
  28296. } catch (ex) {
  28297. }
  28298. };
  28299. const setContentEditable = (elm, state) => {
  28300. elm.dom.contentEditable = state ? 'true' : 'false';
  28301. };
  28302. const switchOffContentEditableTrue = elm => {
  28303. each$e(descendants(elm, '*[contenteditable="true"]'), elm => {
  28304. set$3(elm, internalContentEditableAttr, 'true');
  28305. setContentEditable(elm, false);
  28306. });
  28307. };
  28308. const switchOnContentEditableTrue = elm => {
  28309. each$e(descendants(elm, `*[${ internalContentEditableAttr }="true"]`), elm => {
  28310. remove$b(elm, internalContentEditableAttr);
  28311. setContentEditable(elm, true);
  28312. });
  28313. };
  28314. const removeFakeSelection = editor => {
  28315. Optional.from(editor.selection.getNode()).each(elm => {
  28316. elm.removeAttribute('data-mce-selected');
  28317. });
  28318. };
  28319. const restoreFakeSelection = editor => {
  28320. editor.selection.setRng(editor.selection.getRng());
  28321. };
  28322. const toggleReadOnly = (editor, state) => {
  28323. const body = SugarElement.fromDom(editor.getBody());
  28324. toggleClass(body, 'mce-content-readonly', state);
  28325. if (state) {
  28326. editor.selection.controlSelection.hideResizeRect();
  28327. editor._selectionOverrides.hideFakeCaret();
  28328. removeFakeSelection(editor);
  28329. editor.readonly = true;
  28330. setContentEditable(body, false);
  28331. switchOffContentEditableTrue(body);
  28332. } else {
  28333. editor.readonly = false;
  28334. setContentEditable(body, true);
  28335. switchOnContentEditableTrue(body);
  28336. setEditorCommandState(editor, 'StyleWithCSS', false);
  28337. setEditorCommandState(editor, 'enableInlineTableEditing', false);
  28338. setEditorCommandState(editor, 'enableObjectResizing', false);
  28339. if (hasEditorOrUiFocus(editor)) {
  28340. editor.focus();
  28341. }
  28342. restoreFakeSelection(editor);
  28343. editor.nodeChanged();
  28344. }
  28345. };
  28346. const isReadOnly = editor => editor.readonly;
  28347. const registerFilters = editor => {
  28348. editor.parser.addAttributeFilter('contenteditable', nodes => {
  28349. if (isReadOnly(editor)) {
  28350. each$e(nodes, node => {
  28351. node.attr(internalContentEditableAttr, node.attr('contenteditable'));
  28352. node.attr('contenteditable', 'false');
  28353. });
  28354. }
  28355. });
  28356. editor.serializer.addAttributeFilter(internalContentEditableAttr, nodes => {
  28357. if (isReadOnly(editor)) {
  28358. each$e(nodes, node => {
  28359. node.attr('contenteditable', node.attr(internalContentEditableAttr));
  28360. });
  28361. }
  28362. });
  28363. editor.serializer.addTempAttr(internalContentEditableAttr);
  28364. };
  28365. const registerReadOnlyContentFilters = editor => {
  28366. if (editor.serializer) {
  28367. registerFilters(editor);
  28368. } else {
  28369. editor.on('PreInit', () => {
  28370. registerFilters(editor);
  28371. });
  28372. }
  28373. };
  28374. const isClickEvent = e => e.type === 'click';
  28375. const allowedEvents = ['copy'];
  28376. const isReadOnlyAllowedEvent = e => contains$2(allowedEvents, e.type);
  28377. const getAnchorHrefOpt = (editor, elm) => {
  28378. const isRoot = elm => eq(elm, SugarElement.fromDom(editor.getBody()));
  28379. return closest$3(elm, 'a', isRoot).bind(a => getOpt(a, 'href'));
  28380. };
  28381. const processReadonlyEvents = (editor, e) => {
  28382. if (isClickEvent(e) && !VK.metaKeyPressed(e)) {
  28383. const elm = SugarElement.fromDom(e.target);
  28384. getAnchorHrefOpt(editor, elm).each(href => {
  28385. e.preventDefault();
  28386. if (/^#/.test(href)) {
  28387. const targetEl = editor.dom.select(`${ href },[name="${ removeLeading(href, '#') }"]`);
  28388. if (targetEl.length) {
  28389. editor.selection.scrollIntoView(targetEl[0], true);
  28390. }
  28391. } else {
  28392. window.open(href, '_blank', 'rel=noopener noreferrer,menubar=yes,toolbar=yes,location=yes,status=yes,resizable=yes,scrollbars=yes');
  28393. }
  28394. });
  28395. } else if (isReadOnlyAllowedEvent(e)) {
  28396. editor.dispatch(e.type, e);
  28397. }
  28398. };
  28399. const registerReadOnlySelectionBlockers = editor => {
  28400. editor.on('ShowCaret', e => {
  28401. if (isReadOnly(editor)) {
  28402. e.preventDefault();
  28403. }
  28404. });
  28405. editor.on('ObjectSelected', e => {
  28406. if (isReadOnly(editor)) {
  28407. e.preventDefault();
  28408. }
  28409. });
  28410. };
  28411. 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', ' ');
  28412. class EventDispatcher {
  28413. constructor(settings) {
  28414. this.bindings = {};
  28415. this.settings = settings || {};
  28416. this.scope = this.settings.scope || this;
  28417. this.toggleEvent = this.settings.toggleEvent || never;
  28418. }
  28419. static isNative(name) {
  28420. return !!nativeEvents[name.toLowerCase()];
  28421. }
  28422. fire(name, args) {
  28423. return this.dispatch(name, args);
  28424. }
  28425. dispatch(name, args) {
  28426. const lcName = name.toLowerCase();
  28427. const event = normalize$3(lcName, args !== null && args !== void 0 ? args : {}, this.scope);
  28428. if (this.settings.beforeFire) {
  28429. this.settings.beforeFire(event);
  28430. }
  28431. const handlers = this.bindings[lcName];
  28432. if (handlers) {
  28433. for (let i = 0, l = handlers.length; i < l; i++) {
  28434. const callback = handlers[i];
  28435. if (callback.removed) {
  28436. continue;
  28437. }
  28438. if (callback.once) {
  28439. this.off(lcName, callback.func);
  28440. }
  28441. if (event.isImmediatePropagationStopped()) {
  28442. return event;
  28443. }
  28444. if (callback.func.call(this.scope, event) === false) {
  28445. event.preventDefault();
  28446. return event;
  28447. }
  28448. }
  28449. }
  28450. return event;
  28451. }
  28452. on(name, callback, prepend, extra) {
  28453. if (callback === false) {
  28454. callback = never;
  28455. }
  28456. if (callback) {
  28457. const wrappedCallback = {
  28458. func: callback,
  28459. removed: false
  28460. };
  28461. if (extra) {
  28462. Tools.extend(wrappedCallback, extra);
  28463. }
  28464. const names = name.toLowerCase().split(' ');
  28465. let i = names.length;
  28466. while (i--) {
  28467. const currentName = names[i];
  28468. let handlers = this.bindings[currentName];
  28469. if (!handlers) {
  28470. handlers = [];
  28471. this.toggleEvent(currentName, true);
  28472. }
  28473. if (prepend) {
  28474. handlers = [
  28475. wrappedCallback,
  28476. ...handlers
  28477. ];
  28478. } else {
  28479. handlers = [
  28480. ...handlers,
  28481. wrappedCallback
  28482. ];
  28483. }
  28484. this.bindings[currentName] = handlers;
  28485. }
  28486. }
  28487. return this;
  28488. }
  28489. off(name, callback) {
  28490. if (name) {
  28491. const names = name.toLowerCase().split(' ');
  28492. let i = names.length;
  28493. while (i--) {
  28494. const currentName = names[i];
  28495. let handlers = this.bindings[currentName];
  28496. if (!currentName) {
  28497. each$d(this.bindings, (_value, bindingName) => {
  28498. this.toggleEvent(bindingName, false);
  28499. delete this.bindings[bindingName];
  28500. });
  28501. return this;
  28502. }
  28503. if (handlers) {
  28504. if (!callback) {
  28505. handlers.length = 0;
  28506. } else {
  28507. const filteredHandlers = partition$2(handlers, handler => handler.func === callback);
  28508. handlers = filteredHandlers.fail;
  28509. this.bindings[currentName] = handlers;
  28510. each$e(filteredHandlers.pass, handler => {
  28511. handler.removed = true;
  28512. });
  28513. }
  28514. if (!handlers.length) {
  28515. this.toggleEvent(name, false);
  28516. delete this.bindings[currentName];
  28517. }
  28518. }
  28519. }
  28520. } else {
  28521. each$d(this.bindings, (_value, name) => {
  28522. this.toggleEvent(name, false);
  28523. });
  28524. this.bindings = {};
  28525. }
  28526. return this;
  28527. }
  28528. once(name, callback, prepend) {
  28529. return this.on(name, callback, prepend, { once: true });
  28530. }
  28531. has(name) {
  28532. name = name.toLowerCase();
  28533. const binding = this.bindings[name];
  28534. return !(!binding || binding.length === 0);
  28535. }
  28536. }
  28537. const getEventDispatcher = obj => {
  28538. if (!obj._eventDispatcher) {
  28539. obj._eventDispatcher = new EventDispatcher({
  28540. scope: obj,
  28541. toggleEvent: (name, state) => {
  28542. if (EventDispatcher.isNative(name) && obj.toggleNativeEvent) {
  28543. obj.toggleNativeEvent(name, state);
  28544. }
  28545. }
  28546. });
  28547. }
  28548. return obj._eventDispatcher;
  28549. };
  28550. const Observable = {
  28551. fire(name, args, bubble) {
  28552. return this.dispatch(name, args, bubble);
  28553. },
  28554. dispatch(name, args, bubble) {
  28555. const self = this;
  28556. if (self.removed && name !== 'remove' && name !== 'detach') {
  28557. return normalize$3(name.toLowerCase(), args !== null && args !== void 0 ? args : {}, self);
  28558. }
  28559. const dispatcherArgs = getEventDispatcher(self).dispatch(name, args);
  28560. if (bubble !== false && self.parent) {
  28561. let parent = self.parent();
  28562. while (parent && !dispatcherArgs.isPropagationStopped()) {
  28563. parent.dispatch(name, dispatcherArgs, false);
  28564. parent = parent.parent ? parent.parent() : undefined;
  28565. }
  28566. }
  28567. return dispatcherArgs;
  28568. },
  28569. on(name, callback, prepend) {
  28570. return getEventDispatcher(this).on(name, callback, prepend);
  28571. },
  28572. off(name, callback) {
  28573. return getEventDispatcher(this).off(name, callback);
  28574. },
  28575. once(name, callback) {
  28576. return getEventDispatcher(this).once(name, callback);
  28577. },
  28578. hasEventListeners(name) {
  28579. return getEventDispatcher(this).has(name);
  28580. }
  28581. };
  28582. const DOM$2 = DOMUtils.DOM;
  28583. let customEventRootDelegates;
  28584. const getEventTarget = (editor, eventName) => {
  28585. if (eventName === 'selectionchange') {
  28586. return editor.getDoc();
  28587. }
  28588. if (!editor.inline && /^(?:mouse|touch|click|contextmenu|drop|dragover|dragend)/.test(eventName)) {
  28589. return editor.getDoc().documentElement;
  28590. }
  28591. const eventRoot = getEventRoot(editor);
  28592. if (eventRoot) {
  28593. if (!editor.eventRoot) {
  28594. editor.eventRoot = DOM$2.select(eventRoot)[0];
  28595. }
  28596. return editor.eventRoot;
  28597. }
  28598. return editor.getBody();
  28599. };
  28600. const isListening = editor => !editor.hidden && !isReadOnly(editor);
  28601. const fireEvent = (editor, eventName, e) => {
  28602. if (isListening(editor)) {
  28603. editor.dispatch(eventName, e);
  28604. } else if (isReadOnly(editor)) {
  28605. processReadonlyEvents(editor, e);
  28606. }
  28607. };
  28608. const bindEventDelegate = (editor, eventName) => {
  28609. if (!editor.delegates) {
  28610. editor.delegates = {};
  28611. }
  28612. if (editor.delegates[eventName] || editor.removed) {
  28613. return;
  28614. }
  28615. const eventRootElm = getEventTarget(editor, eventName);
  28616. if (getEventRoot(editor)) {
  28617. if (!customEventRootDelegates) {
  28618. customEventRootDelegates = {};
  28619. editor.editorManager.on('removeEditor', () => {
  28620. if (!editor.editorManager.activeEditor) {
  28621. if (customEventRootDelegates) {
  28622. each$d(customEventRootDelegates, (_value, name) => {
  28623. editor.dom.unbind(getEventTarget(editor, name));
  28624. });
  28625. customEventRootDelegates = null;
  28626. }
  28627. }
  28628. });
  28629. }
  28630. if (customEventRootDelegates[eventName]) {
  28631. return;
  28632. }
  28633. const delegate = e => {
  28634. const target = e.target;
  28635. const editors = editor.editorManager.get();
  28636. let i = editors.length;
  28637. while (i--) {
  28638. const body = editors[i].getBody();
  28639. if (body === target || DOM$2.isChildOf(target, body)) {
  28640. fireEvent(editors[i], eventName, e);
  28641. }
  28642. }
  28643. };
  28644. customEventRootDelegates[eventName] = delegate;
  28645. DOM$2.bind(eventRootElm, eventName, delegate);
  28646. } else {
  28647. const delegate = e => {
  28648. fireEvent(editor, eventName, e);
  28649. };
  28650. DOM$2.bind(eventRootElm, eventName, delegate);
  28651. editor.delegates[eventName] = delegate;
  28652. }
  28653. };
  28654. const EditorObservable = {
  28655. ...Observable,
  28656. bindPendingEventDelegates() {
  28657. const self = this;
  28658. Tools.each(self._pendingNativeEvents, name => {
  28659. bindEventDelegate(self, name);
  28660. });
  28661. },
  28662. toggleNativeEvent(name, state) {
  28663. const self = this;
  28664. if (name === 'focus' || name === 'blur') {
  28665. return;
  28666. }
  28667. if (self.removed) {
  28668. return;
  28669. }
  28670. if (state) {
  28671. if (self.initialized) {
  28672. bindEventDelegate(self, name);
  28673. } else {
  28674. if (!self._pendingNativeEvents) {
  28675. self._pendingNativeEvents = [name];
  28676. } else {
  28677. self._pendingNativeEvents.push(name);
  28678. }
  28679. }
  28680. } else if (self.initialized && self.delegates) {
  28681. self.dom.unbind(getEventTarget(self, name), name, self.delegates[name]);
  28682. delete self.delegates[name];
  28683. }
  28684. },
  28685. unbindAllNativeEvents() {
  28686. const self = this;
  28687. const body = self.getBody();
  28688. const dom = self.dom;
  28689. if (self.delegates) {
  28690. each$d(self.delegates, (value, name) => {
  28691. self.dom.unbind(getEventTarget(self, name), name, value);
  28692. });
  28693. delete self.delegates;
  28694. }
  28695. if (!self.inline && body && dom) {
  28696. body.onload = null;
  28697. dom.unbind(self.getWin());
  28698. dom.unbind(self.getDoc());
  28699. }
  28700. if (dom) {
  28701. dom.unbind(body);
  28702. dom.unbind(self.getContainer());
  28703. }
  28704. }
  28705. };
  28706. const stringListProcessor = value => {
  28707. if (isString(value)) {
  28708. return {
  28709. value: value.split(/[ ,]/),
  28710. valid: true
  28711. };
  28712. } else if (isArrayOf(value, isString)) {
  28713. return {
  28714. value,
  28715. valid: true
  28716. };
  28717. } else {
  28718. return {
  28719. valid: false,
  28720. message: `The value must be a string[] or a comma/space separated string.`
  28721. };
  28722. }
  28723. };
  28724. const getBuiltInProcessor = type => {
  28725. const validator = (() => {
  28726. switch (type) {
  28727. case 'array':
  28728. return isArray$1;
  28729. case 'boolean':
  28730. return isBoolean;
  28731. case 'function':
  28732. return isFunction;
  28733. case 'number':
  28734. return isNumber;
  28735. case 'object':
  28736. return isObject;
  28737. case 'string':
  28738. return isString;
  28739. case 'string[]':
  28740. return stringListProcessor;
  28741. case 'object[]':
  28742. return val => isArrayOf(val, isObject);
  28743. case 'regexp':
  28744. return val => is$4(val, RegExp);
  28745. default:
  28746. return always;
  28747. }
  28748. })();
  28749. return value => processValue(value, validator, `The value must be a ${ type }.`);
  28750. };
  28751. const isBuiltInSpec = spec => isString(spec.processor);
  28752. const getErrorMessage = (message, result) => {
  28753. const additionalText = isEmpty$3(result.message) ? '' : `. ${ result.message }`;
  28754. return message + additionalText;
  28755. };
  28756. const isValidResult = result => result.valid;
  28757. const processValue = (value, processor, message = '') => {
  28758. const result = processor(value);
  28759. if (isBoolean(result)) {
  28760. return result ? {
  28761. value: value,
  28762. valid: true
  28763. } : {
  28764. valid: false,
  28765. message
  28766. };
  28767. } else {
  28768. return result;
  28769. }
  28770. };
  28771. const processDefaultValue = (name, defaultValue, processor) => {
  28772. if (!isUndefined(defaultValue)) {
  28773. const result = processValue(defaultValue, processor);
  28774. if (isValidResult(result)) {
  28775. return result.value;
  28776. } else {
  28777. console.error(getErrorMessage(`Invalid default value passed for the "${ name }" option`, result));
  28778. }
  28779. }
  28780. return undefined;
  28781. };
  28782. const create$5 = (editor, initialOptions) => {
  28783. const registry = {};
  28784. const values = {};
  28785. const setValue = (name, value, processor) => {
  28786. const result = processValue(value, processor);
  28787. if (isValidResult(result)) {
  28788. values[name] = result.value;
  28789. return true;
  28790. } else {
  28791. console.warn(getErrorMessage(`Invalid value passed for the ${ name } option`, result));
  28792. return false;
  28793. }
  28794. };
  28795. const register = (name, spec) => {
  28796. const processor = isBuiltInSpec(spec) ? getBuiltInProcessor(spec.processor) : spec.processor;
  28797. const defaultValue = processDefaultValue(name, spec.default, processor);
  28798. registry[name] = {
  28799. ...spec,
  28800. default: defaultValue,
  28801. processor
  28802. };
  28803. const initValue = get$a(values, name).orThunk(() => get$a(initialOptions, name));
  28804. initValue.each(value => setValue(name, value, processor));
  28805. };
  28806. const isRegistered = name => has$2(registry, name);
  28807. const get = name => get$a(values, name).orThunk(() => get$a(registry, name).map(spec => spec.default)).getOrUndefined();
  28808. const set = (name, value) => {
  28809. if (!isRegistered(name)) {
  28810. console.warn(`"${ name }" is not a registered option. Ensure the option has been registered before setting a value.`);
  28811. return false;
  28812. } else {
  28813. const spec = registry[name];
  28814. if (spec.immutable) {
  28815. console.error(`"${ name }" is an immutable option and cannot be updated`);
  28816. return false;
  28817. } else {
  28818. return setValue(name, value, spec.processor);
  28819. }
  28820. }
  28821. };
  28822. const unset = name => {
  28823. const registered = isRegistered(name);
  28824. if (registered) {
  28825. delete values[name];
  28826. }
  28827. return registered;
  28828. };
  28829. const isSet = name => has$2(values, name);
  28830. return {
  28831. register,
  28832. isRegistered,
  28833. get,
  28834. set,
  28835. unset,
  28836. isSet
  28837. };
  28838. };
  28839. const defaultModes = [
  28840. 'design',
  28841. 'readonly'
  28842. ];
  28843. const switchToMode = (editor, activeMode, availableModes, mode) => {
  28844. const oldMode = availableModes[activeMode.get()];
  28845. const newMode = availableModes[mode];
  28846. try {
  28847. newMode.activate();
  28848. } catch (e) {
  28849. console.error(`problem while activating editor mode ${ mode }:`, e);
  28850. return;
  28851. }
  28852. oldMode.deactivate();
  28853. if (oldMode.editorReadOnly !== newMode.editorReadOnly) {
  28854. toggleReadOnly(editor, newMode.editorReadOnly);
  28855. }
  28856. activeMode.set(mode);
  28857. fireSwitchMode(editor, mode);
  28858. };
  28859. const setMode = (editor, availableModes, activeMode, mode) => {
  28860. if (mode === activeMode.get()) {
  28861. return;
  28862. } else if (!has$2(availableModes, mode)) {
  28863. throw new Error(`Editor mode '${ mode }' is invalid`);
  28864. }
  28865. if (editor.initialized) {
  28866. switchToMode(editor, activeMode, availableModes, mode);
  28867. } else {
  28868. editor.on('init', () => switchToMode(editor, activeMode, availableModes, mode));
  28869. }
  28870. };
  28871. const registerMode = (availableModes, mode, api) => {
  28872. if (contains$2(defaultModes, mode)) {
  28873. throw new Error(`Cannot override default mode ${ mode }`);
  28874. }
  28875. return {
  28876. ...availableModes,
  28877. [mode]: {
  28878. ...api,
  28879. deactivate: () => {
  28880. try {
  28881. api.deactivate();
  28882. } catch (e) {
  28883. console.error(`problem while deactivating editor mode ${ mode }:`, e);
  28884. }
  28885. }
  28886. }
  28887. };
  28888. };
  28889. const create$4 = editor => {
  28890. const activeMode = Cell('design');
  28891. const availableModes = Cell({
  28892. design: {
  28893. activate: noop,
  28894. deactivate: noop,
  28895. editorReadOnly: false
  28896. },
  28897. readonly: {
  28898. activate: noop,
  28899. deactivate: noop,
  28900. editorReadOnly: true
  28901. }
  28902. });
  28903. registerReadOnlyContentFilters(editor);
  28904. registerReadOnlySelectionBlockers(editor);
  28905. return {
  28906. isReadOnly: () => isReadOnly(editor),
  28907. set: mode => setMode(editor, availableModes.get(), activeMode, mode),
  28908. get: () => activeMode.get(),
  28909. register: (mode, api) => {
  28910. availableModes.set(registerMode(availableModes.get(), mode, api));
  28911. }
  28912. };
  28913. };
  28914. const each$2 = Tools.each, explode = Tools.explode;
  28915. const keyCodeLookup = {
  28916. f1: 112,
  28917. f2: 113,
  28918. f3: 114,
  28919. f4: 115,
  28920. f5: 116,
  28921. f6: 117,
  28922. f7: 118,
  28923. f8: 119,
  28924. f9: 120,
  28925. f10: 121,
  28926. f11: 122,
  28927. f12: 123
  28928. };
  28929. const modifierNames = Tools.makeMap('alt,ctrl,shift,meta,access');
  28930. const isModifier = key => key in modifierNames;
  28931. const parseShortcut = pattern => {
  28932. const shortcut = {};
  28933. const isMac = Env.os.isMacOS() || Env.os.isiOS();
  28934. each$2(explode(pattern.toLowerCase(), '+'), value => {
  28935. if (isModifier(value)) {
  28936. shortcut[value] = true;
  28937. } else {
  28938. if (/^[0-9]{2,}$/.test(value)) {
  28939. shortcut.keyCode = parseInt(value, 10);
  28940. } else {
  28941. shortcut.charCode = value.charCodeAt(0);
  28942. shortcut.keyCode = keyCodeLookup[value] || value.toUpperCase().charCodeAt(0);
  28943. }
  28944. }
  28945. });
  28946. const id = [shortcut.keyCode];
  28947. let key;
  28948. for (key in modifierNames) {
  28949. if (shortcut[key]) {
  28950. id.push(key);
  28951. } else {
  28952. shortcut[key] = false;
  28953. }
  28954. }
  28955. shortcut.id = id.join(',');
  28956. if (shortcut.access) {
  28957. shortcut.alt = true;
  28958. if (isMac) {
  28959. shortcut.ctrl = true;
  28960. } else {
  28961. shortcut.shift = true;
  28962. }
  28963. }
  28964. if (shortcut.meta) {
  28965. if (isMac) {
  28966. shortcut.meta = true;
  28967. } else {
  28968. shortcut.ctrl = true;
  28969. shortcut.meta = false;
  28970. }
  28971. }
  28972. return shortcut;
  28973. };
  28974. class Shortcuts {
  28975. constructor(editor) {
  28976. this.shortcuts = {};
  28977. this.pendingPatterns = [];
  28978. this.editor = editor;
  28979. const self = this;
  28980. editor.on('keyup keypress keydown', e => {
  28981. if ((self.hasModifier(e) || self.isFunctionKey(e)) && !e.isDefaultPrevented()) {
  28982. each$2(self.shortcuts, shortcut => {
  28983. if (self.matchShortcut(e, shortcut)) {
  28984. self.pendingPatterns = shortcut.subpatterns.slice(0);
  28985. if (e.type === 'keydown') {
  28986. self.executeShortcutAction(shortcut);
  28987. }
  28988. }
  28989. });
  28990. if (self.matchShortcut(e, self.pendingPatterns[0])) {
  28991. if (self.pendingPatterns.length === 1) {
  28992. if (e.type === 'keydown') {
  28993. self.executeShortcutAction(self.pendingPatterns[0]);
  28994. }
  28995. }
  28996. self.pendingPatterns.shift();
  28997. }
  28998. }
  28999. });
  29000. }
  29001. add(pattern, desc, cmdFunc, scope) {
  29002. const self = this;
  29003. const func = self.normalizeCommandFunc(cmdFunc);
  29004. each$2(explode(Tools.trim(pattern)), pattern => {
  29005. const shortcut = self.createShortcut(pattern, desc, func, scope);
  29006. self.shortcuts[shortcut.id] = shortcut;
  29007. });
  29008. return true;
  29009. }
  29010. remove(pattern) {
  29011. const shortcut = this.createShortcut(pattern);
  29012. if (this.shortcuts[shortcut.id]) {
  29013. delete this.shortcuts[shortcut.id];
  29014. return true;
  29015. }
  29016. return false;
  29017. }
  29018. normalizeCommandFunc(cmdFunc) {
  29019. const self = this;
  29020. const cmd = cmdFunc;
  29021. if (typeof cmd === 'string') {
  29022. return () => {
  29023. self.editor.execCommand(cmd, false, null);
  29024. };
  29025. } else if (Tools.isArray(cmd)) {
  29026. return () => {
  29027. self.editor.execCommand(cmd[0], cmd[1], cmd[2]);
  29028. };
  29029. } else {
  29030. return cmd;
  29031. }
  29032. }
  29033. createShortcut(pattern, desc, cmdFunc, scope) {
  29034. const shortcuts = Tools.map(explode(pattern, '>'), parseShortcut);
  29035. shortcuts[shortcuts.length - 1] = Tools.extend(shortcuts[shortcuts.length - 1], {
  29036. func: cmdFunc,
  29037. scope: scope || this.editor
  29038. });
  29039. return Tools.extend(shortcuts[0], {
  29040. desc: this.editor.translate(desc),
  29041. subpatterns: shortcuts.slice(1)
  29042. });
  29043. }
  29044. hasModifier(e) {
  29045. return e.altKey || e.ctrlKey || e.metaKey;
  29046. }
  29047. isFunctionKey(e) {
  29048. return e.type === 'keydown' && e.keyCode >= 112 && e.keyCode <= 123;
  29049. }
  29050. matchShortcut(e, shortcut) {
  29051. if (!shortcut) {
  29052. return false;
  29053. }
  29054. if (shortcut.ctrl !== e.ctrlKey || shortcut.meta !== e.metaKey) {
  29055. return false;
  29056. }
  29057. if (shortcut.alt !== e.altKey || shortcut.shift !== e.shiftKey) {
  29058. return false;
  29059. }
  29060. if (e.keyCode === shortcut.keyCode || e.charCode && e.charCode === shortcut.charCode) {
  29061. e.preventDefault();
  29062. return true;
  29063. }
  29064. return false;
  29065. }
  29066. executeShortcutAction(shortcut) {
  29067. return shortcut.func ? shortcut.func.call(shortcut.scope) : null;
  29068. }
  29069. }
  29070. const create$3 = () => {
  29071. const buttons = {};
  29072. const menuItems = {};
  29073. const popups = {};
  29074. const icons = {};
  29075. const contextMenus = {};
  29076. const contextToolbars = {};
  29077. const sidebars = {};
  29078. const views = {};
  29079. const add = (collection, type) => (name, spec) => {
  29080. collection[name.toLowerCase()] = {
  29081. ...spec,
  29082. type
  29083. };
  29084. };
  29085. const addIcon = (name, svgData) => icons[name.toLowerCase()] = svgData;
  29086. return {
  29087. addButton: add(buttons, 'button'),
  29088. addGroupToolbarButton: add(buttons, 'grouptoolbarbutton'),
  29089. addToggleButton: add(buttons, 'togglebutton'),
  29090. addMenuButton: add(buttons, 'menubutton'),
  29091. addSplitButton: add(buttons, 'splitbutton'),
  29092. addMenuItem: add(menuItems, 'menuitem'),
  29093. addNestedMenuItem: add(menuItems, 'nestedmenuitem'),
  29094. addToggleMenuItem: add(menuItems, 'togglemenuitem'),
  29095. addAutocompleter: add(popups, 'autocompleter'),
  29096. addContextMenu: add(contextMenus, 'contextmenu'),
  29097. addContextToolbar: add(contextToolbars, 'contexttoolbar'),
  29098. addContextForm: add(contextToolbars, 'contextform'),
  29099. addSidebar: add(sidebars, 'sidebar'),
  29100. addView: add(views, 'views'),
  29101. addIcon,
  29102. getAll: () => ({
  29103. buttons,
  29104. menuItems,
  29105. icons,
  29106. popups,
  29107. contextMenus,
  29108. contextToolbars,
  29109. sidebars,
  29110. views
  29111. })
  29112. };
  29113. };
  29114. const registry = () => {
  29115. const bridge = create$3();
  29116. return {
  29117. addAutocompleter: bridge.addAutocompleter,
  29118. addButton: bridge.addButton,
  29119. addContextForm: bridge.addContextForm,
  29120. addContextMenu: bridge.addContextMenu,
  29121. addContextToolbar: bridge.addContextToolbar,
  29122. addIcon: bridge.addIcon,
  29123. addMenuButton: bridge.addMenuButton,
  29124. addMenuItem: bridge.addMenuItem,
  29125. addNestedMenuItem: bridge.addNestedMenuItem,
  29126. addSidebar: bridge.addSidebar,
  29127. addSplitButton: bridge.addSplitButton,
  29128. addToggleButton: bridge.addToggleButton,
  29129. addGroupToolbarButton: bridge.addGroupToolbarButton,
  29130. addToggleMenuItem: bridge.addToggleMenuItem,
  29131. addView: bridge.addView,
  29132. getAll: bridge.getAll
  29133. };
  29134. };
  29135. const DOM$1 = DOMUtils.DOM;
  29136. const extend = Tools.extend, each$1 = Tools.each;
  29137. class Editor {
  29138. constructor(id, options, editorManager) {
  29139. this.plugins = {};
  29140. this.contentCSS = [];
  29141. this.contentStyles = [];
  29142. this.loadedCSS = {};
  29143. this.isNotDirty = false;
  29144. this.composing = false;
  29145. this.destroyed = false;
  29146. this.hasHiddenInput = false;
  29147. this.iframeElement = null;
  29148. this.initialized = false;
  29149. this.readonly = false;
  29150. this.removed = false;
  29151. this.startContent = '';
  29152. this._pendingNativeEvents = [];
  29153. this._skinLoaded = false;
  29154. this.editorManager = editorManager;
  29155. this.documentBaseUrl = editorManager.documentBaseURL;
  29156. extend(this, EditorObservable);
  29157. const self = this;
  29158. this.id = id;
  29159. this.hidden = false;
  29160. const normalizedOptions = normalizeOptions(editorManager.defaultOptions, options);
  29161. this.options = create$5(self, normalizedOptions);
  29162. register$7(self);
  29163. const getOption = this.options.get;
  29164. if (getOption('deprecation_warnings')) {
  29165. logWarnings(options, normalizedOptions);
  29166. }
  29167. const suffix = getOption('suffix');
  29168. if (suffix) {
  29169. editorManager.suffix = suffix;
  29170. }
  29171. this.suffix = editorManager.suffix;
  29172. const baseUrl = getOption('base_url');
  29173. if (baseUrl) {
  29174. editorManager._setBaseUrl(baseUrl);
  29175. }
  29176. this.baseUri = editorManager.baseURI;
  29177. const referrerPolicy = getReferrerPolicy(self);
  29178. if (referrerPolicy) {
  29179. ScriptLoader.ScriptLoader._setReferrerPolicy(referrerPolicy);
  29180. DOMUtils.DOM.styleSheetLoader._setReferrerPolicy(referrerPolicy);
  29181. }
  29182. const contentCssCors = hasContentCssCors(self);
  29183. if (isNonNullable(contentCssCors)) {
  29184. DOMUtils.DOM.styleSheetLoader._setContentCssCors(contentCssCors);
  29185. }
  29186. AddOnManager.languageLoad = getOption('language_load');
  29187. AddOnManager.baseURL = editorManager.baseURL;
  29188. this.setDirty(false);
  29189. this.documentBaseURI = new URI(getDocumentBaseUrl(self), { base_uri: this.baseUri });
  29190. this.baseURI = this.baseUri;
  29191. this.inline = isInline(self);
  29192. this.hasVisual = isVisualAidsEnabled(self);
  29193. this.shortcuts = new Shortcuts(this);
  29194. this.editorCommands = new EditorCommands(this);
  29195. registerCommands(this);
  29196. const cacheSuffix = getOption('cache_suffix');
  29197. if (cacheSuffix) {
  29198. Env.cacheSuffix = cacheSuffix.replace(/^[\?\&]+/, '');
  29199. }
  29200. this.ui = {
  29201. registry: registry(),
  29202. styleSheetLoader: undefined,
  29203. show: noop,
  29204. hide: noop,
  29205. setEnabled: noop,
  29206. isEnabled: always
  29207. };
  29208. this.mode = create$4(self);
  29209. editorManager.dispatch('SetupEditor', { editor: this });
  29210. const setupCallback = getSetupCallback(self);
  29211. if (isFunction(setupCallback)) {
  29212. setupCallback.call(self, self);
  29213. }
  29214. }
  29215. render() {
  29216. render(this);
  29217. }
  29218. focus(skipFocus) {
  29219. this.execCommand('mceFocus', false, skipFocus);
  29220. }
  29221. hasFocus() {
  29222. return hasFocus(this);
  29223. }
  29224. translate(text) {
  29225. return I18n.translate(text);
  29226. }
  29227. getParam(name, defaultVal, type) {
  29228. const options = this.options;
  29229. if (!options.isRegistered(name)) {
  29230. if (isNonNullable(type)) {
  29231. options.register(name, {
  29232. processor: type,
  29233. default: defaultVal
  29234. });
  29235. } else {
  29236. options.register(name, {
  29237. processor: always,
  29238. default: defaultVal
  29239. });
  29240. }
  29241. }
  29242. return !options.isSet(name) && !isUndefined(defaultVal) ? defaultVal : options.get(name);
  29243. }
  29244. hasPlugin(name, loaded) {
  29245. const hasPlugin = contains$2(getPlugins(this), name);
  29246. if (hasPlugin) {
  29247. return loaded ? PluginManager.get(name) !== undefined : true;
  29248. } else {
  29249. return false;
  29250. }
  29251. }
  29252. nodeChanged(args) {
  29253. this._nodeChangeDispatcher.nodeChanged(args);
  29254. }
  29255. addCommand(name, callback, scope) {
  29256. this.editorCommands.addCommand(name, callback, scope);
  29257. }
  29258. addQueryStateHandler(name, callback, scope) {
  29259. this.editorCommands.addQueryStateHandler(name, callback, scope);
  29260. }
  29261. addQueryValueHandler(name, callback, scope) {
  29262. this.editorCommands.addQueryValueHandler(name, callback, scope);
  29263. }
  29264. addShortcut(pattern, desc, cmdFunc, scope) {
  29265. this.shortcuts.add(pattern, desc, cmdFunc, scope);
  29266. }
  29267. execCommand(cmd, ui, value, args) {
  29268. return this.editorCommands.execCommand(cmd, ui, value, args);
  29269. }
  29270. queryCommandState(cmd) {
  29271. return this.editorCommands.queryCommandState(cmd);
  29272. }
  29273. queryCommandValue(cmd) {
  29274. return this.editorCommands.queryCommandValue(cmd);
  29275. }
  29276. queryCommandSupported(cmd) {
  29277. return this.editorCommands.queryCommandSupported(cmd);
  29278. }
  29279. show() {
  29280. const self = this;
  29281. if (self.hidden) {
  29282. self.hidden = false;
  29283. if (self.inline) {
  29284. self.getBody().contentEditable = 'true';
  29285. } else {
  29286. DOM$1.show(self.getContainer());
  29287. DOM$1.hide(self.id);
  29288. }
  29289. self.load();
  29290. self.dispatch('show');
  29291. }
  29292. }
  29293. hide() {
  29294. const self = this;
  29295. if (!self.hidden) {
  29296. self.save();
  29297. if (self.inline) {
  29298. self.getBody().contentEditable = 'false';
  29299. if (self === self.editorManager.focusedEditor) {
  29300. self.editorManager.focusedEditor = null;
  29301. }
  29302. } else {
  29303. DOM$1.hide(self.getContainer());
  29304. DOM$1.setStyle(self.id, 'display', self.orgDisplay);
  29305. }
  29306. self.hidden = true;
  29307. self.dispatch('hide');
  29308. }
  29309. }
  29310. isHidden() {
  29311. return this.hidden;
  29312. }
  29313. setProgressState(state, time) {
  29314. this.dispatch('ProgressState', {
  29315. state,
  29316. time
  29317. });
  29318. }
  29319. load(args = {}) {
  29320. const self = this;
  29321. const elm = self.getElement();
  29322. if (self.removed) {
  29323. return '';
  29324. }
  29325. if (elm) {
  29326. const loadArgs = {
  29327. ...args,
  29328. load: true
  29329. };
  29330. const value = isTextareaOrInput(elm) ? elm.value : elm.innerHTML;
  29331. const html = self.setContent(value, loadArgs);
  29332. if (!loadArgs.no_events) {
  29333. self.dispatch('LoadContent', {
  29334. ...loadArgs,
  29335. element: elm
  29336. });
  29337. }
  29338. return html;
  29339. } else {
  29340. return '';
  29341. }
  29342. }
  29343. save(args = {}) {
  29344. const self = this;
  29345. let elm = self.getElement();
  29346. if (!elm || !self.initialized || self.removed) {
  29347. return '';
  29348. }
  29349. const getArgs = {
  29350. ...args,
  29351. save: true,
  29352. element: elm
  29353. };
  29354. let html = self.getContent(getArgs);
  29355. const saveArgs = {
  29356. ...getArgs,
  29357. content: html
  29358. };
  29359. if (!saveArgs.no_events) {
  29360. self.dispatch('SaveContent', saveArgs);
  29361. }
  29362. if (saveArgs.format === 'raw') {
  29363. self.dispatch('RawSaveContent', saveArgs);
  29364. }
  29365. html = saveArgs.content;
  29366. if (!isTextareaOrInput(elm)) {
  29367. if (args.is_removing || !self.inline) {
  29368. elm.innerHTML = html;
  29369. }
  29370. const form = DOM$1.getParent(self.id, 'form');
  29371. if (form) {
  29372. each$1(form.elements, elm => {
  29373. if (elm.name === self.id) {
  29374. elm.value = html;
  29375. return false;
  29376. } else {
  29377. return true;
  29378. }
  29379. });
  29380. }
  29381. } else {
  29382. elm.value = html;
  29383. }
  29384. saveArgs.element = getArgs.element = elm = null;
  29385. if (saveArgs.set_dirty !== false) {
  29386. self.setDirty(false);
  29387. }
  29388. return html;
  29389. }
  29390. setContent(content, args) {
  29391. return setContent(this, content, args);
  29392. }
  29393. getContent(args) {
  29394. return getContent(this, args);
  29395. }
  29396. insertContent(content, args) {
  29397. if (args) {
  29398. content = extend({ content }, args);
  29399. }
  29400. this.execCommand('mceInsertContent', false, content);
  29401. }
  29402. resetContent(initialContent) {
  29403. if (initialContent === undefined) {
  29404. setContent(this, this.startContent, { format: 'raw' });
  29405. } else {
  29406. setContent(this, initialContent);
  29407. }
  29408. this.undoManager.reset();
  29409. this.setDirty(false);
  29410. this.nodeChanged();
  29411. }
  29412. isDirty() {
  29413. return !this.isNotDirty;
  29414. }
  29415. setDirty(state) {
  29416. const oldState = !this.isNotDirty;
  29417. this.isNotDirty = !state;
  29418. if (state && state !== oldState) {
  29419. this.dispatch('dirty');
  29420. }
  29421. }
  29422. getContainer() {
  29423. const self = this;
  29424. if (!self.container) {
  29425. self.container = self.editorContainer || DOM$1.get(self.id + '_parent');
  29426. }
  29427. return self.container;
  29428. }
  29429. getContentAreaContainer() {
  29430. return this.contentAreaContainer;
  29431. }
  29432. getElement() {
  29433. if (!this.targetElm) {
  29434. this.targetElm = DOM$1.get(this.id);
  29435. }
  29436. return this.targetElm;
  29437. }
  29438. getWin() {
  29439. const self = this;
  29440. if (!self.contentWindow) {
  29441. const elm = self.iframeElement;
  29442. if (elm) {
  29443. self.contentWindow = elm.contentWindow;
  29444. }
  29445. }
  29446. return self.contentWindow;
  29447. }
  29448. getDoc() {
  29449. const self = this;
  29450. if (!self.contentDocument) {
  29451. const win = self.getWin();
  29452. if (win) {
  29453. self.contentDocument = win.document;
  29454. }
  29455. }
  29456. return self.contentDocument;
  29457. }
  29458. getBody() {
  29459. var _a, _b;
  29460. const doc = this.getDoc();
  29461. return (_b = (_a = this.bodyElement) !== null && _a !== void 0 ? _a : doc === null || doc === void 0 ? void 0 : doc.body) !== null && _b !== void 0 ? _b : null;
  29462. }
  29463. convertURL(url, name, elm) {
  29464. const self = this, getOption = self.options.get;
  29465. const urlConverterCallback = getUrlConverterCallback(self);
  29466. if (isFunction(urlConverterCallback)) {
  29467. return urlConverterCallback.call(self, url, elm, true, name);
  29468. }
  29469. if (!getOption('convert_urls') || elm === 'link' || isObject(elm) && elm.nodeName === 'LINK' || url.indexOf('file:') === 0 || url.length === 0) {
  29470. return url;
  29471. }
  29472. if (getOption('relative_urls')) {
  29473. return self.documentBaseURI.toRelative(url);
  29474. }
  29475. url = self.documentBaseURI.toAbsolute(url, getOption('remove_script_host'));
  29476. return url;
  29477. }
  29478. addVisual(elm) {
  29479. addVisual(this, elm);
  29480. }
  29481. remove() {
  29482. remove$1(this);
  29483. }
  29484. destroy(automatic) {
  29485. destroy(this, automatic);
  29486. }
  29487. uploadImages() {
  29488. return this.editorUpload.uploadImages();
  29489. }
  29490. _scanForImages() {
  29491. return this.editorUpload.scanForImages();
  29492. }
  29493. }
  29494. const DOM = DOMUtils.DOM;
  29495. const each = Tools.each;
  29496. let boundGlobalEvents = false;
  29497. let beforeUnloadDelegate;
  29498. let editors = [];
  29499. const globalEventDelegate = e => {
  29500. const type = e.type;
  29501. each(EditorManager.get(), editor => {
  29502. switch (type) {
  29503. case 'scroll':
  29504. editor.dispatch('ScrollWindow', e);
  29505. break;
  29506. case 'resize':
  29507. editor.dispatch('ResizeWindow', e);
  29508. break;
  29509. }
  29510. });
  29511. };
  29512. const toggleGlobalEvents = state => {
  29513. if (state !== boundGlobalEvents) {
  29514. const DOM = DOMUtils.DOM;
  29515. if (state) {
  29516. DOM.bind(window, 'resize', globalEventDelegate);
  29517. DOM.bind(window, 'scroll', globalEventDelegate);
  29518. } else {
  29519. DOM.unbind(window, 'resize', globalEventDelegate);
  29520. DOM.unbind(window, 'scroll', globalEventDelegate);
  29521. }
  29522. boundGlobalEvents = state;
  29523. }
  29524. };
  29525. const removeEditorFromList = targetEditor => {
  29526. const oldEditors = editors;
  29527. editors = filter$5(editors, editor => {
  29528. return targetEditor !== editor;
  29529. });
  29530. if (EditorManager.activeEditor === targetEditor) {
  29531. EditorManager.activeEditor = editors.length > 0 ? editors[0] : null;
  29532. }
  29533. if (EditorManager.focusedEditor === targetEditor) {
  29534. EditorManager.focusedEditor = null;
  29535. }
  29536. return oldEditors.length !== editors.length;
  29537. };
  29538. const purgeDestroyedEditor = editor => {
  29539. if (editor && editor.initialized && !(editor.getContainer() || editor.getBody()).parentNode) {
  29540. removeEditorFromList(editor);
  29541. editor.unbindAllNativeEvents();
  29542. editor.destroy(true);
  29543. editor.removed = true;
  29544. }
  29545. };
  29546. const isQuirksMode = document.compatMode !== 'CSS1Compat';
  29547. const EditorManager = {
  29548. ...Observable,
  29549. baseURI: null,
  29550. baseURL: null,
  29551. defaultOptions: {},
  29552. documentBaseURL: null,
  29553. suffix: null,
  29554. majorVersion: '6',
  29555. minorVersion: '4.2',
  29556. releaseDate: '2023-04-26',
  29557. i18n: I18n,
  29558. activeEditor: null,
  29559. focusedEditor: null,
  29560. setup() {
  29561. const self = this;
  29562. let baseURL = '';
  29563. let suffix = '';
  29564. let documentBaseURL = URI.getDocumentBaseUrl(document.location);
  29565. if (/^[^:]+:\/\/\/?[^\/]+\//.test(documentBaseURL)) {
  29566. documentBaseURL = documentBaseURL.replace(/[\?#].*$/, '').replace(/[\/\\][^\/]+$/, '');
  29567. if (!/[\/\\]$/.test(documentBaseURL)) {
  29568. documentBaseURL += '/';
  29569. }
  29570. }
  29571. const preInit = window.tinymce || window.tinyMCEPreInit;
  29572. if (preInit) {
  29573. baseURL = preInit.base || preInit.baseURL;
  29574. suffix = preInit.suffix;
  29575. } else {
  29576. const scripts = document.getElementsByTagName('script');
  29577. for (let i = 0; i < scripts.length; i++) {
  29578. const src = scripts[i].src || '';
  29579. if (src === '') {
  29580. continue;
  29581. }
  29582. const srcScript = src.substring(src.lastIndexOf('/'));
  29583. if (/tinymce(\.full|\.jquery|)(\.min|\.dev|)\.js/.test(src)) {
  29584. if (srcScript.indexOf('.min') !== -1) {
  29585. suffix = '.min';
  29586. }
  29587. baseURL = src.substring(0, src.lastIndexOf('/'));
  29588. break;
  29589. }
  29590. }
  29591. if (!baseURL && document.currentScript) {
  29592. const src = document.currentScript.src;
  29593. if (src.indexOf('.min') !== -1) {
  29594. suffix = '.min';
  29595. }
  29596. baseURL = src.substring(0, src.lastIndexOf('/'));
  29597. }
  29598. }
  29599. self.baseURL = new URI(documentBaseURL).toAbsolute(baseURL);
  29600. self.documentBaseURL = documentBaseURL;
  29601. self.baseURI = new URI(self.baseURL);
  29602. self.suffix = suffix;
  29603. setup$v(self);
  29604. },
  29605. overrideDefaults(defaultOptions) {
  29606. const baseUrl = defaultOptions.base_url;
  29607. if (baseUrl) {
  29608. this._setBaseUrl(baseUrl);
  29609. }
  29610. const suffix = defaultOptions.suffix;
  29611. if (suffix) {
  29612. this.suffix = suffix;
  29613. }
  29614. this.defaultOptions = defaultOptions;
  29615. const pluginBaseUrls = defaultOptions.plugin_base_urls;
  29616. if (pluginBaseUrls !== undefined) {
  29617. each$d(pluginBaseUrls, (pluginBaseUrl, pluginName) => {
  29618. AddOnManager.PluginManager.urls[pluginName] = pluginBaseUrl;
  29619. });
  29620. }
  29621. },
  29622. init(options) {
  29623. const self = this;
  29624. let result;
  29625. 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', ' ');
  29626. const isInvalidInlineTarget = (options, elm) => options.inline && elm.tagName.toLowerCase() in invalidInlineTargets;
  29627. const createId = elm => {
  29628. let id = elm.id;
  29629. if (!id) {
  29630. id = get$a(elm, 'name').filter(name => !DOM.get(name)).getOrThunk(DOM.uniqueId);
  29631. elm.setAttribute('id', id);
  29632. }
  29633. return id;
  29634. };
  29635. const execCallback = name => {
  29636. const callback = options[name];
  29637. if (!callback) {
  29638. return;
  29639. }
  29640. return callback.apply(self, []);
  29641. };
  29642. const findTargets = options => {
  29643. if (Env.browser.isIE() || Env.browser.isEdge()) {
  29644. 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');
  29645. return [];
  29646. } else if (isQuirksMode) {
  29647. initError('Failed to initialize the editor as the document is not in standards mode. ' + 'TinyMCE requires standards mode.');
  29648. return [];
  29649. } else if (isString(options.selector)) {
  29650. return DOM.select(options.selector);
  29651. } else if (isNonNullable(options.target)) {
  29652. return [options.target];
  29653. } else {
  29654. return [];
  29655. }
  29656. };
  29657. let provideResults = editors => {
  29658. result = editors;
  29659. };
  29660. const initEditors = () => {
  29661. let initCount = 0;
  29662. const editors = [];
  29663. let targets;
  29664. const createEditor = (id, options, targetElm) => {
  29665. const editor = new Editor(id, options, self);
  29666. editors.push(editor);
  29667. editor.on('init', () => {
  29668. if (++initCount === targets.length) {
  29669. provideResults(editors);
  29670. }
  29671. });
  29672. editor.targetElm = editor.targetElm || targetElm;
  29673. editor.render();
  29674. };
  29675. DOM.unbind(window, 'ready', initEditors);
  29676. execCallback('onpageload');
  29677. targets = unique$1(findTargets(options));
  29678. Tools.each(targets, elm => {
  29679. purgeDestroyedEditor(self.get(elm.id));
  29680. });
  29681. targets = Tools.grep(targets, elm => {
  29682. return !self.get(elm.id);
  29683. });
  29684. if (targets.length === 0) {
  29685. provideResults([]);
  29686. } else {
  29687. each(targets, elm => {
  29688. if (isInvalidInlineTarget(options, elm)) {
  29689. initError('Could not initialize inline editor on invalid inline target element', elm);
  29690. } else {
  29691. createEditor(createId(elm), options, elm);
  29692. }
  29693. });
  29694. }
  29695. };
  29696. DOM.bind(window, 'ready', initEditors);
  29697. return new Promise(resolve => {
  29698. if (result) {
  29699. resolve(result);
  29700. } else {
  29701. provideResults = editors => {
  29702. resolve(editors);
  29703. };
  29704. }
  29705. });
  29706. },
  29707. get(id) {
  29708. if (arguments.length === 0) {
  29709. return editors.slice(0);
  29710. } else if (isString(id)) {
  29711. return find$2(editors, editor => {
  29712. return editor.id === id;
  29713. }).getOr(null);
  29714. } else if (isNumber(id)) {
  29715. return editors[id] ? editors[id] : null;
  29716. } else {
  29717. return null;
  29718. }
  29719. },
  29720. add(editor) {
  29721. const self = this;
  29722. const existingEditor = self.get(editor.id);
  29723. if (existingEditor === editor) {
  29724. return editor;
  29725. }
  29726. if (existingEditor === null) {
  29727. editors.push(editor);
  29728. }
  29729. toggleGlobalEvents(true);
  29730. self.activeEditor = editor;
  29731. self.dispatch('AddEditor', { editor });
  29732. if (!beforeUnloadDelegate) {
  29733. beforeUnloadDelegate = e => {
  29734. const event = self.dispatch('BeforeUnload');
  29735. if (event.returnValue) {
  29736. e.preventDefault();
  29737. e.returnValue = event.returnValue;
  29738. return event.returnValue;
  29739. }
  29740. };
  29741. window.addEventListener('beforeunload', beforeUnloadDelegate);
  29742. }
  29743. return editor;
  29744. },
  29745. createEditor(id, options) {
  29746. return this.add(new Editor(id, options, this));
  29747. },
  29748. remove(selector) {
  29749. const self = this;
  29750. let editor;
  29751. if (!selector) {
  29752. for (let i = editors.length - 1; i >= 0; i--) {
  29753. self.remove(editors[i]);
  29754. }
  29755. return;
  29756. }
  29757. if (isString(selector)) {
  29758. each(DOM.select(selector), elm => {
  29759. editor = self.get(elm.id);
  29760. if (editor) {
  29761. self.remove(editor);
  29762. }
  29763. });
  29764. return;
  29765. }
  29766. editor = selector;
  29767. if (isNull(self.get(editor.id))) {
  29768. return null;
  29769. }
  29770. if (removeEditorFromList(editor)) {
  29771. self.dispatch('RemoveEditor', { editor });
  29772. }
  29773. if (editors.length === 0) {
  29774. window.removeEventListener('beforeunload', beforeUnloadDelegate);
  29775. }
  29776. editor.remove();
  29777. toggleGlobalEvents(editors.length > 0);
  29778. return editor;
  29779. },
  29780. execCommand(cmd, ui, value) {
  29781. var _a;
  29782. const self = this;
  29783. const editorId = isObject(value) ? (_a = value.id) !== null && _a !== void 0 ? _a : value.index : value;
  29784. switch (cmd) {
  29785. case 'mceAddEditor': {
  29786. if (!self.get(editorId)) {
  29787. const editorOptions = value.options;
  29788. new Editor(editorId, editorOptions, self).render();
  29789. }
  29790. return true;
  29791. }
  29792. case 'mceRemoveEditor': {
  29793. const editor = self.get(editorId);
  29794. if (editor) {
  29795. editor.remove();
  29796. }
  29797. return true;
  29798. }
  29799. case 'mceToggleEditor': {
  29800. const editor = self.get(editorId);
  29801. if (!editor) {
  29802. self.execCommand('mceAddEditor', false, value);
  29803. return true;
  29804. }
  29805. if (editor.isHidden()) {
  29806. editor.show();
  29807. } else {
  29808. editor.hide();
  29809. }
  29810. return true;
  29811. }
  29812. }
  29813. if (self.activeEditor) {
  29814. return self.activeEditor.execCommand(cmd, ui, value);
  29815. }
  29816. return false;
  29817. },
  29818. triggerSave: () => {
  29819. each(editors, editor => {
  29820. editor.save();
  29821. });
  29822. },
  29823. addI18n: (code, items) => {
  29824. I18n.add(code, items);
  29825. },
  29826. translate: text => {
  29827. return I18n.translate(text);
  29828. },
  29829. setActive(editor) {
  29830. const activeEditor = this.activeEditor;
  29831. if (this.activeEditor !== editor) {
  29832. if (activeEditor) {
  29833. activeEditor.dispatch('deactivate', { relatedTarget: editor });
  29834. }
  29835. editor.dispatch('activate', { relatedTarget: activeEditor });
  29836. }
  29837. this.activeEditor = editor;
  29838. },
  29839. _setBaseUrl(baseUrl) {
  29840. this.baseURL = new URI(this.documentBaseURL).toAbsolute(baseUrl.replace(/\/+$/, ''));
  29841. this.baseURI = new URI(this.baseURL);
  29842. }
  29843. };
  29844. EditorManager.setup();
  29845. const setup = () => {
  29846. const dataValue = value$2();
  29847. const FakeClipboardItem = items => ({
  29848. items,
  29849. types: keys(items),
  29850. getType: type => get$a(items, type).getOrUndefined()
  29851. });
  29852. const write = data => {
  29853. dataValue.set(data);
  29854. };
  29855. const read = () => dataValue.get().getOrUndefined();
  29856. const clear = dataValue.clear;
  29857. return {
  29858. FakeClipboardItem,
  29859. write,
  29860. read,
  29861. clear
  29862. };
  29863. };
  29864. const FakeClipboard = setup();
  29865. const min = Math.min, max = Math.max, round = Math.round;
  29866. const relativePosition = (rect, targetRect, rel) => {
  29867. let x = targetRect.x;
  29868. let y = targetRect.y;
  29869. const w = rect.w;
  29870. const h = rect.h;
  29871. const targetW = targetRect.w;
  29872. const targetH = targetRect.h;
  29873. const relChars = (rel || '').split('');
  29874. if (relChars[0] === 'b') {
  29875. y += targetH;
  29876. }
  29877. if (relChars[1] === 'r') {
  29878. x += targetW;
  29879. }
  29880. if (relChars[0] === 'c') {
  29881. y += round(targetH / 2);
  29882. }
  29883. if (relChars[1] === 'c') {
  29884. x += round(targetW / 2);
  29885. }
  29886. if (relChars[3] === 'b') {
  29887. y -= h;
  29888. }
  29889. if (relChars[4] === 'r') {
  29890. x -= w;
  29891. }
  29892. if (relChars[3] === 'c') {
  29893. y -= round(h / 2);
  29894. }
  29895. if (relChars[4] === 'c') {
  29896. x -= round(w / 2);
  29897. }
  29898. return create$2(x, y, w, h);
  29899. };
  29900. const findBestRelativePosition = (rect, targetRect, constrainRect, rels) => {
  29901. for (let i = 0; i < rels.length; i++) {
  29902. const pos = relativePosition(rect, targetRect, rels[i]);
  29903. 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) {
  29904. return rels[i];
  29905. }
  29906. }
  29907. return null;
  29908. };
  29909. const inflate = (rect, w, h) => {
  29910. return create$2(rect.x - w, rect.y - h, rect.w + w * 2, rect.h + h * 2);
  29911. };
  29912. const intersect = (rect, cropRect) => {
  29913. const x1 = max(rect.x, cropRect.x);
  29914. const y1 = max(rect.y, cropRect.y);
  29915. const x2 = min(rect.x + rect.w, cropRect.x + cropRect.w);
  29916. const y2 = min(rect.y + rect.h, cropRect.y + cropRect.h);
  29917. if (x2 - x1 < 0 || y2 - y1 < 0) {
  29918. return null;
  29919. }
  29920. return create$2(x1, y1, x2 - x1, y2 - y1);
  29921. };
  29922. const clamp = (rect, clampRect, fixedSize) => {
  29923. let x1 = rect.x;
  29924. let y1 = rect.y;
  29925. let x2 = rect.x + rect.w;
  29926. let y2 = rect.y + rect.h;
  29927. const cx2 = clampRect.x + clampRect.w;
  29928. const cy2 = clampRect.y + clampRect.h;
  29929. const underflowX1 = max(0, clampRect.x - x1);
  29930. const underflowY1 = max(0, clampRect.y - y1);
  29931. const overflowX2 = max(0, x2 - cx2);
  29932. const overflowY2 = max(0, y2 - cy2);
  29933. x1 += underflowX1;
  29934. y1 += underflowY1;
  29935. if (fixedSize) {
  29936. x2 += underflowX1;
  29937. y2 += underflowY1;
  29938. x1 -= overflowX2;
  29939. y1 -= overflowY2;
  29940. }
  29941. x2 -= overflowX2;
  29942. y2 -= overflowY2;
  29943. return create$2(x1, y1, x2 - x1, y2 - y1);
  29944. };
  29945. const create$2 = (x, y, w, h) => {
  29946. return {
  29947. x,
  29948. y,
  29949. w,
  29950. h
  29951. };
  29952. };
  29953. const fromClientRect = clientRect => {
  29954. return create$2(clientRect.left, clientRect.top, clientRect.width, clientRect.height);
  29955. };
  29956. const Rect = {
  29957. inflate,
  29958. relativePosition,
  29959. findBestRelativePosition,
  29960. intersect,
  29961. clamp,
  29962. create: create$2,
  29963. fromClientRect
  29964. };
  29965. const awaiter = (resolveCb, rejectCb, timeout = 1000) => {
  29966. let done = false;
  29967. let timer = null;
  29968. const complete = completer => (...args) => {
  29969. if (!done) {
  29970. done = true;
  29971. if (timer !== null) {
  29972. clearTimeout(timer);
  29973. timer = null;
  29974. }
  29975. completer.apply(null, args);
  29976. }
  29977. };
  29978. const resolve = complete(resolveCb);
  29979. const reject = complete(rejectCb);
  29980. const start = (...args) => {
  29981. if (!done && timer === null) {
  29982. timer = setTimeout(() => reject.apply(null, args), timeout);
  29983. }
  29984. };
  29985. return {
  29986. start,
  29987. resolve,
  29988. reject
  29989. };
  29990. };
  29991. const create$1 = () => {
  29992. const tasks = {};
  29993. const resultFns = {};
  29994. const load = (id, url) => {
  29995. const loadErrMsg = `Script at URL "${ url }" failed to load`;
  29996. const runErrMsg = `Script at URL "${ url }" did not call \`tinymce.Resource.add('${ id }', data)\` within 1 second`;
  29997. if (tasks[id] !== undefined) {
  29998. return tasks[id];
  29999. } else {
  30000. const task = new Promise((resolve, reject) => {
  30001. const waiter = awaiter(resolve, reject);
  30002. resultFns[id] = waiter.resolve;
  30003. ScriptLoader.ScriptLoader.loadScript(url).then(() => waiter.start(runErrMsg), () => waiter.reject(loadErrMsg));
  30004. });
  30005. tasks[id] = task;
  30006. return task;
  30007. }
  30008. };
  30009. const add = (id, data) => {
  30010. if (resultFns[id] !== undefined) {
  30011. resultFns[id](data);
  30012. delete resultFns[id];
  30013. }
  30014. tasks[id] = Promise.resolve(data);
  30015. };
  30016. const unload = id => {
  30017. delete tasks[id];
  30018. };
  30019. return {
  30020. load,
  30021. add,
  30022. unload
  30023. };
  30024. };
  30025. const Resource = create$1();
  30026. const create = () => (() => {
  30027. let data = {};
  30028. let keys = [];
  30029. const storage = {
  30030. getItem: key => {
  30031. const item = data[key];
  30032. return item ? item : null;
  30033. },
  30034. setItem: (key, value) => {
  30035. keys.push(key);
  30036. data[key] = String(value);
  30037. },
  30038. key: index => {
  30039. return keys[index];
  30040. },
  30041. removeItem: key => {
  30042. keys = keys.filter(k => k === key);
  30043. delete data[key];
  30044. },
  30045. clear: () => {
  30046. keys = [];
  30047. data = {};
  30048. },
  30049. length: 0
  30050. };
  30051. Object.defineProperty(storage, 'length', {
  30052. get: () => keys.length,
  30053. configurable: false,
  30054. enumerable: false
  30055. });
  30056. return storage;
  30057. })();
  30058. let localStorage;
  30059. try {
  30060. const test = '__storage_test__';
  30061. localStorage = window.localStorage;
  30062. localStorage.setItem(test, test);
  30063. localStorage.removeItem(test);
  30064. } catch (e) {
  30065. localStorage = create();
  30066. }
  30067. var LocalStorage = localStorage;
  30068. const publicApi = {
  30069. geom: { Rect },
  30070. util: {
  30071. Delay,
  30072. Tools,
  30073. VK,
  30074. URI,
  30075. EventDispatcher,
  30076. Observable,
  30077. I18n,
  30078. LocalStorage,
  30079. ImageUploader
  30080. },
  30081. dom: {
  30082. EventUtils,
  30083. TreeWalker: DomTreeWalker,
  30084. TextSeeker,
  30085. DOMUtils,
  30086. ScriptLoader,
  30087. RangeUtils,
  30088. Serializer: DomSerializer,
  30089. StyleSheetLoader,
  30090. ControlSelection,
  30091. BookmarkManager,
  30092. Selection: EditorSelection,
  30093. Event: EventUtils.Event
  30094. },
  30095. html: {
  30096. Styles,
  30097. Entities,
  30098. Node: AstNode,
  30099. Schema,
  30100. DomParser,
  30101. Writer,
  30102. Serializer: HtmlSerializer
  30103. },
  30104. Env,
  30105. AddOnManager,
  30106. Annotator,
  30107. Formatter,
  30108. UndoManager,
  30109. EditorCommands,
  30110. WindowManager,
  30111. NotificationManager,
  30112. EditorObservable,
  30113. Shortcuts,
  30114. Editor,
  30115. FocusManager,
  30116. EditorManager,
  30117. DOM: DOMUtils.DOM,
  30118. ScriptLoader: ScriptLoader.ScriptLoader,
  30119. PluginManager,
  30120. ThemeManager,
  30121. ModelManager,
  30122. IconManager,
  30123. Resource,
  30124. FakeClipboard,
  30125. trim: Tools.trim,
  30126. isArray: Tools.isArray,
  30127. is: Tools.is,
  30128. toArray: Tools.toArray,
  30129. makeMap: Tools.makeMap,
  30130. each: Tools.each,
  30131. map: Tools.map,
  30132. grep: Tools.grep,
  30133. inArray: Tools.inArray,
  30134. extend: Tools.extend,
  30135. walk: Tools.walk,
  30136. resolve: Tools.resolve,
  30137. explode: Tools.explode,
  30138. _addCacheSuffix: Tools._addCacheSuffix
  30139. };
  30140. const tinymce = Tools.extend(EditorManager, publicApi);
  30141. const exportToModuleLoaders = tinymce => {
  30142. if (typeof module === 'object') {
  30143. try {
  30144. module.exports = tinymce;
  30145. } catch (_) {
  30146. }
  30147. }
  30148. };
  30149. const exportToWindowGlobal = tinymce => {
  30150. window.tinymce = tinymce;
  30151. window.tinyMCE = tinymce;
  30152. };
  30153. exportToWindowGlobal(tinymce);
  30154. exportToModuleLoaders(tinymce);
  30155. })();