No Description

index.js 289KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254
  1. import { c as createCommonjsModule, u as unwrapExports, j as commonjsGlobal, i as _slicedToArray } from '../_commonjsHelpers-aeb41076.js';
  2. import React$1, { useMemo, useState } from 'react';
  3. import { r as require$$3 } from '../_react-dom_commonjs-external-d3012e04.js';
  4. import 'react-dom';
  5. /*!
  6. * isobject <https://github.com/jonschlinkert/isobject>
  7. *
  8. * Copyright (c) 2014-2017, Jon Schlinkert.
  9. * Released under the MIT License.
  10. */
  11. function isObject(val) {
  12. return val != null && typeof val === 'object' && Array.isArray(val) === false;
  13. }
  14. /*!
  15. * is-plain-object <https://github.com/jonschlinkert/is-plain-object>
  16. *
  17. * Copyright (c) 2014-2017, Jon Schlinkert.
  18. * Released under the MIT License.
  19. */
  20. function isObjectObject(o) {
  21. return isObject(o) === true
  22. && Object.prototype.toString.call(o) === '[object Object]';
  23. }
  24. function isPlainObject(o) {
  25. var ctor,prot;
  26. if (isObjectObject(o) === false) return false;
  27. // If has modified constructor
  28. ctor = o.constructor;
  29. if (typeof ctor !== 'function') return false;
  30. // If has modified prototype
  31. prot = ctor.prototype;
  32. if (isObjectObject(prot) === false) return false;
  33. // If constructor does not have an Object-specific method
  34. if (prot.hasOwnProperty('isPrototypeOf') === false) {
  35. return false;
  36. }
  37. // Most likely a plain Object
  38. return true;
  39. }
  40. var index_cjs = isPlainObject;
  41. var immer_1 = createCommonjsModule(function (module, exports) {
  42. Object.defineProperty(exports, '__esModule', { value: true });
  43. // Should be no imports here!
  44. var _a; // SOme things that should be evaluated before all else...
  45. var hasSymbol = typeof Symbol !== "undefined";
  46. var hasMap = typeof Map !== "undefined";
  47. var hasSet = typeof Set !== "undefined";
  48. /**
  49. * The sentinel value returned by producers to replace the draft with undefined.
  50. */
  51. var NOTHING = hasSymbol ? Symbol("immer-nothing") : (_a = {}, _a["immer-nothing"] = true, _a);
  52. /**
  53. * To let Immer treat your class instances as plain immutable objects
  54. * (albeit with a custom prototype), you must define either an instance property
  55. * or a static property on each of your custom classes.
  56. *
  57. * Otherwise, your class instance will never be drafted, which means it won't be
  58. * safe to mutate in a produce callback.
  59. */
  60. var DRAFTABLE = hasSymbol ? Symbol("immer-draftable") : "__$immer_draftable";
  61. var DRAFT_STATE = hasSymbol ? Symbol("immer-state") : "__$immer_state";
  62. var iteratorSymbol = hasSymbol ? Symbol.iterator : "@@iterator";
  63. /* istanbul ignore next */
  64. var extendStatics = function (d, b) {
  65. extendStatics = Object.setPrototypeOf || {
  66. __proto__: []
  67. } instanceof Array && function (d, b) {
  68. d.__proto__ = b;
  69. } || function (d, b) {
  70. for (var p in b) { if (b.hasOwnProperty(p)) { d[p] = b[p]; } }
  71. };
  72. return extendStatics(d, b);
  73. }; // Ugly hack to resolve #502 and inherit built in Map / Set
  74. function __extends(d, b) {
  75. extendStatics(d, b);
  76. function __() {
  77. this.constructor = d;
  78. }
  79. d.prototype = ( // @ts-ignore
  80. __.prototype = b.prototype, new __());
  81. }
  82. var Archtype;
  83. (function (Archtype) {
  84. Archtype[Archtype["Object"] = 0] = "Object";
  85. Archtype[Archtype["Array"] = 1] = "Array";
  86. Archtype[Archtype["Map"] = 2] = "Map";
  87. Archtype[Archtype["Set"] = 3] = "Set";
  88. })(Archtype || (Archtype = {}));
  89. var ProxyType;
  90. (function (ProxyType) {
  91. ProxyType[ProxyType["ProxyObject"] = 0] = "ProxyObject";
  92. ProxyType[ProxyType["ProxyArray"] = 1] = "ProxyArray";
  93. ProxyType[ProxyType["ES5Object"] = 2] = "ES5Object";
  94. ProxyType[ProxyType["ES5Array"] = 3] = "ES5Array";
  95. ProxyType[ProxyType["Map"] = 4] = "Map";
  96. ProxyType[ProxyType["Set"] = 5] = "Set";
  97. })(ProxyType || (ProxyType = {}));
  98. /** Returns true if the given value is an Immer draft */
  99. function isDraft(value) {
  100. return !!value && !!value[DRAFT_STATE];
  101. }
  102. /** Returns true if the given value can be drafted by Immer */
  103. function isDraftable(value) {
  104. if (!value) { return false; }
  105. return isPlainObject(value) || Array.isArray(value) || !!value[DRAFTABLE] || !!value.constructor[DRAFTABLE] || isMap(value) || isSet(value);
  106. }
  107. function isPlainObject(value) {
  108. if (!value || typeof value !== "object") { return false; }
  109. var proto = Object.getPrototypeOf(value);
  110. return !proto || proto === Object.prototype;
  111. }
  112. function original(value) {
  113. if (value && value[DRAFT_STATE]) {
  114. return value[DRAFT_STATE].base;
  115. } // otherwise return undefined
  116. }
  117. var ownKeys = typeof Reflect !== "undefined" && Reflect.ownKeys ? Reflect.ownKeys : typeof Object.getOwnPropertySymbols !== "undefined" ? function (obj) {
  118. return Object.getOwnPropertyNames(obj).concat(Object.getOwnPropertySymbols(obj));
  119. } :
  120. /* istanbul ignore next */
  121. Object.getOwnPropertyNames;
  122. function each(obj, iter) {
  123. if (getArchtype(obj) === Archtype.Object) {
  124. ownKeys(obj).forEach(function (key) {
  125. return iter(key, obj[key], obj);
  126. });
  127. } else {
  128. obj.forEach(function (entry, index) {
  129. return iter(index, entry, obj);
  130. });
  131. }
  132. }
  133. function isEnumerable(base, prop) {
  134. var desc = Object.getOwnPropertyDescriptor(base, prop);
  135. return desc && desc.enumerable ? true : false;
  136. }
  137. function getArchtype(thing) {
  138. /* istanbul ignore next */
  139. if (!thing) { die(); }
  140. if (thing[DRAFT_STATE]) {
  141. switch (thing[DRAFT_STATE].type) {
  142. case ProxyType.ES5Object:
  143. case ProxyType.ProxyObject:
  144. return Archtype.Object;
  145. case ProxyType.ES5Array:
  146. case ProxyType.ProxyArray:
  147. return Archtype.Array;
  148. case ProxyType.Map:
  149. return Archtype.Map;
  150. case ProxyType.Set:
  151. return Archtype.Set;
  152. }
  153. }
  154. return Array.isArray(thing) ? Archtype.Array : isMap(thing) ? Archtype.Map : isSet(thing) ? Archtype.Set : Archtype.Object;
  155. }
  156. function has(thing, prop) {
  157. return getArchtype(thing) === Archtype.Map ? thing.has(prop) : Object.prototype.hasOwnProperty.call(thing, prop);
  158. }
  159. function get(thing, prop) {
  160. // @ts-ignore
  161. return getArchtype(thing) === Archtype.Map ? thing.get(prop) : thing[prop];
  162. }
  163. function set(thing, propOrOldValue, value) {
  164. switch (getArchtype(thing)) {
  165. case Archtype.Map:
  166. thing.set(propOrOldValue, value);
  167. break;
  168. case Archtype.Set:
  169. thing.delete(propOrOldValue);
  170. thing.add(value);
  171. break;
  172. default:
  173. thing[propOrOldValue] = value;
  174. }
  175. }
  176. function is(x, y) {
  177. // From: https://github.com/facebook/fbjs/blob/c69904a511b900266935168223063dd8772dfc40/packages/fbjs/src/core/shallowEqual.js
  178. if (x === y) {
  179. return x !== 0 || 1 / x === 1 / y;
  180. } else {
  181. return x !== x && y !== y;
  182. }
  183. }
  184. function isMap(target) {
  185. return hasMap && target instanceof Map;
  186. }
  187. function isSet(target) {
  188. return hasSet && target instanceof Set;
  189. }
  190. function latest(state) {
  191. return state.copy || state.base;
  192. }
  193. function shallowCopy(base, invokeGetters) {
  194. if (invokeGetters === void 0) {
  195. invokeGetters = false;
  196. }
  197. if (Array.isArray(base)) { return base.slice(); }
  198. var clone = Object.create(Object.getPrototypeOf(base));
  199. ownKeys(base).forEach(function (key) {
  200. if (key === DRAFT_STATE) {
  201. return; // Never copy over draft state.
  202. }
  203. var desc = Object.getOwnPropertyDescriptor(base, key);
  204. var value = desc.value;
  205. if (desc.get) {
  206. if (!invokeGetters) {
  207. throw new Error("Immer drafts cannot have computed properties");
  208. }
  209. value = desc.get.call(base);
  210. }
  211. if (desc.enumerable) {
  212. clone[key] = value;
  213. } else {
  214. Object.defineProperty(clone, key, {
  215. value: value,
  216. writable: true,
  217. configurable: true
  218. });
  219. }
  220. });
  221. return clone;
  222. }
  223. function freeze(obj, deep) {
  224. if (!isDraftable(obj) || isDraft(obj) || Object.isFrozen(obj)) { return; }
  225. var type = getArchtype(obj);
  226. if (type === Archtype.Set) {
  227. obj.add = obj.clear = obj.delete = dontMutateFrozenCollections;
  228. } else if (type === Archtype.Map) {
  229. obj.set = obj.clear = obj.delete = dontMutateFrozenCollections;
  230. }
  231. Object.freeze(obj);
  232. if (deep) { each(obj, function (_, value) {
  233. return freeze(value, true);
  234. }); }
  235. }
  236. function dontMutateFrozenCollections() {
  237. throw new Error("This object has been frozen and should not be mutated");
  238. }
  239. function createHiddenProperty(target, prop, value) {
  240. Object.defineProperty(target, prop, {
  241. value: value,
  242. enumerable: false,
  243. writable: true
  244. });
  245. }
  246. /* istanbul ignore next */
  247. function die() {
  248. throw new Error("Illegal state, please file a bug");
  249. }
  250. /** Each scope represents a `produce` call. */
  251. var ImmerScope =
  252. /** @class */
  253. function () {
  254. function ImmerScope(parent, immer) {
  255. this.drafts = [];
  256. this.parent = parent;
  257. this.immer = immer; // Whenever the modified draft contains a draft from another scope, we
  258. // need to prevent auto-freezing so the unowned draft can be finalized.
  259. this.canAutoFreeze = true;
  260. }
  261. ImmerScope.prototype.usePatches = function (patchListener) {
  262. if (patchListener) {
  263. this.patches = [];
  264. this.inversePatches = [];
  265. this.patchListener = patchListener;
  266. }
  267. };
  268. ImmerScope.prototype.revoke = function () {
  269. this.leave();
  270. this.drafts.forEach(revoke); // @ts-ignore
  271. this.drafts = null;
  272. };
  273. ImmerScope.prototype.leave = function () {
  274. if (this === ImmerScope.current) {
  275. ImmerScope.current = this.parent;
  276. }
  277. };
  278. ImmerScope.enter = function (immer) {
  279. var scope = new ImmerScope(ImmerScope.current, immer);
  280. ImmerScope.current = scope;
  281. return scope;
  282. };
  283. return ImmerScope;
  284. }();
  285. function revoke(draft) {
  286. var state = draft[DRAFT_STATE];
  287. if (state.type === ProxyType.ProxyObject || state.type === ProxyType.ProxyArray) { state.revoke(); }else { state.revoked = true; }
  288. }
  289. function processResult(immer, result, scope) {
  290. var baseDraft = scope.drafts[0];
  291. var isReplaced = result !== undefined && result !== baseDraft;
  292. immer.willFinalize(scope, result, isReplaced);
  293. if (isReplaced) {
  294. if (baseDraft[DRAFT_STATE].modified) {
  295. scope.revoke();
  296. throw new Error("An immer producer returned a new value *and* modified its draft. Either return a new value *or* modify the draft."); // prettier-ignore
  297. }
  298. if (isDraftable(result)) {
  299. // Finalize the result in case it contains (or is) a subset of the draft.
  300. result = finalize(immer, result, scope);
  301. maybeFreeze(immer, result);
  302. }
  303. if (scope.patches) {
  304. scope.patches.push({
  305. op: "replace",
  306. path: [],
  307. value: result
  308. });
  309. scope.inversePatches.push({
  310. op: "replace",
  311. path: [],
  312. value: baseDraft[DRAFT_STATE].base
  313. });
  314. }
  315. } else {
  316. // Finalize the base draft.
  317. result = finalize(immer, baseDraft, scope, []);
  318. }
  319. scope.revoke();
  320. if (scope.patches) {
  321. scope.patchListener(scope.patches, scope.inversePatches);
  322. }
  323. return result !== NOTHING ? result : undefined;
  324. }
  325. function finalize(immer, draft, scope, path) {
  326. var state = draft[DRAFT_STATE];
  327. if (!state) {
  328. if (Object.isFrozen(draft)) { return draft; }
  329. return finalizeTree(immer, draft, scope);
  330. } // Never finalize drafts owned by another scope.
  331. if (state.scope !== scope) {
  332. return draft;
  333. }
  334. if (!state.modified) {
  335. maybeFreeze(immer, state.base, true);
  336. return state.base;
  337. }
  338. if (!state.finalized) {
  339. state.finalized = true;
  340. finalizeTree(immer, state.draft, scope, path); // We cannot really delete anything inside of a Set. We can only replace the whole Set.
  341. if (immer.onDelete && state.type !== ProxyType.Set) {
  342. // The `assigned` object is unreliable with ES5 drafts.
  343. if (immer.useProxies) {
  344. var assigned = state.assigned;
  345. each(assigned, function (prop, exists) {
  346. if (!exists) { immer.onDelete(state, prop); }
  347. });
  348. } else {
  349. var base = state.base,
  350. copy_1 = state.copy;
  351. each(base, function (prop) {
  352. if (!has(copy_1, prop)) { immer.onDelete(state, prop); }
  353. });
  354. }
  355. }
  356. if (immer.onCopy) {
  357. immer.onCopy(state);
  358. } // At this point, all descendants of `state.copy` have been finalized,
  359. // so we can be sure that `scope.canAutoFreeze` is accurate.
  360. if (immer.autoFreeze && scope.canAutoFreeze) {
  361. freeze(state.copy, false);
  362. }
  363. if (path && scope.patches) {
  364. generatePatches(state, path, scope.patches, scope.inversePatches);
  365. }
  366. }
  367. return state.copy;
  368. }
  369. function finalizeTree(immer, root, scope, rootPath) {
  370. var state = root[DRAFT_STATE];
  371. if (state) {
  372. if (state.type === ProxyType.ES5Object || state.type === ProxyType.ES5Array) {
  373. // Create the final copy, with added keys and without deleted keys.
  374. state.copy = shallowCopy(state.draft, true);
  375. }
  376. root = state.copy;
  377. }
  378. each(root, function (key, value) {
  379. return finalizeProperty(immer, scope, root, state, root, key, value, rootPath);
  380. });
  381. return root;
  382. }
  383. function finalizeProperty(immer, scope, root, rootState, parentValue, prop, childValue, rootPath) {
  384. if (childValue === parentValue) {
  385. throw Error("Immer forbids circular references");
  386. } // In the `finalizeTree` method, only the `root` object may be a draft.
  387. var isDraftProp = !!rootState && parentValue === root;
  388. var isSetMember = isSet(parentValue);
  389. if (isDraft(childValue)) {
  390. var path = rootPath && isDraftProp && !isSetMember && // Set objects are atomic since they have no keys.
  391. !has(rootState.assigned, prop) // Skip deep patches for assigned keys.
  392. ? rootPath.concat(prop) : undefined; // Drafts owned by `scope` are finalized here.
  393. childValue = finalize(immer, childValue, scope, path);
  394. set(parentValue, prop, childValue); // Drafts from another scope must prevent auto-freezing.
  395. if (isDraft(childValue)) {
  396. scope.canAutoFreeze = false;
  397. }
  398. } // Unchanged draft properties are ignored.
  399. else if (isDraftProp && is(childValue, get(rootState.base, prop))) {
  400. return;
  401. } // Search new objects for unfinalized drafts. Frozen objects should never contain drafts.
  402. // TODO: the recursion over here looks weird, shouldn't non-draft stuff have it's own recursion?
  403. // especially the passing on of root and rootState doesn't make sense...
  404. else if (isDraftable(childValue) && !Object.isFrozen(childValue)) {
  405. each(childValue, function (key, grandChild) {
  406. return finalizeProperty(immer, scope, root, rootState, childValue, key, grandChild, rootPath);
  407. });
  408. maybeFreeze(immer, childValue);
  409. }
  410. if (isDraftProp && immer.onAssign && !isSetMember) {
  411. immer.onAssign(rootState, prop, childValue);
  412. }
  413. }
  414. function maybeFreeze(immer, value, deep) {
  415. if (deep === void 0) {
  416. deep = false;
  417. }
  418. if (immer.autoFreeze && !isDraft(value)) {
  419. freeze(value, deep);
  420. }
  421. }
  422. /**
  423. * Returns a new draft of the `base` object.
  424. *
  425. * The second argument is the parent draft-state (used internally).
  426. */
  427. function createProxy(base, parent) {
  428. var isArray = Array.isArray(base);
  429. var state = {
  430. type: isArray ? ProxyType.ProxyArray : ProxyType.ProxyObject,
  431. // Track which produce call this is associated with.
  432. scope: parent ? parent.scope : ImmerScope.current,
  433. // True for both shallow and deep changes.
  434. modified: false,
  435. // Used during finalization.
  436. finalized: false,
  437. // Track which properties have been assigned (true) or deleted (false).
  438. assigned: {},
  439. // The parent draft state.
  440. parent: parent,
  441. // The base state.
  442. base: base,
  443. // The base proxy.
  444. draft: null,
  445. // Any property proxies.
  446. drafts: {},
  447. // The base copy with any updated values.
  448. copy: null,
  449. // Called by the `produce` function.
  450. revoke: null,
  451. isManual: false
  452. }; // the traps must target something, a bit like the 'real' base.
  453. // but also, we need to be able to determine from the target what the relevant state is
  454. // (to avoid creating traps per instance to capture the state in closure,
  455. // and to avoid creating weird hidden properties as well)
  456. // So the trick is to use 'state' as the actual 'target'! (and make sure we intercept everything)
  457. // Note that in the case of an array, we put the state in an array to have better Reflect defaults ootb
  458. var target = state;
  459. var traps = objectTraps;
  460. if (isArray) {
  461. target = [state];
  462. traps = arrayTraps;
  463. } // TODO: optimization: might be faster, cheaper if we created a non-revocable proxy
  464. // and administrate revoking ourselves
  465. var _a = Proxy.revocable(target, traps),
  466. revoke = _a.revoke,
  467. proxy = _a.proxy;
  468. state.draft = proxy;
  469. state.revoke = revoke;
  470. return proxy;
  471. }
  472. /**
  473. * Object drafts
  474. */
  475. var objectTraps = {
  476. get: function (state, prop) {
  477. if (prop === DRAFT_STATE) { return state; }
  478. var drafts = state.drafts; // Check for existing draft in unmodified state.
  479. if (!state.modified && has(drafts, prop)) {
  480. return drafts[prop];
  481. }
  482. var value = latest(state)[prop];
  483. if (state.finalized || !isDraftable(value)) {
  484. return value;
  485. } // Check for existing draft in modified state.
  486. if (state.modified) {
  487. // Assigned values are never drafted. This catches any drafts we created, too.
  488. if (value !== peek(state.base, prop)) { return value; } // Store drafts on the copy (when one exists).
  489. // @ts-ignore
  490. drafts = state.copy;
  491. }
  492. return drafts[prop] = state.scope.immer.createProxy(value, state);
  493. },
  494. has: function (state, prop) {
  495. return prop in latest(state);
  496. },
  497. ownKeys: function (state) {
  498. return Reflect.ownKeys(latest(state));
  499. },
  500. set: function (state, prop
  501. /* strictly not, but helps TS */
  502. , value) {
  503. if (!state.modified) {
  504. var baseValue = peek(state.base, prop); // Optimize based on value's truthiness. Truthy values are guaranteed to
  505. // never be undefined, so we can avoid the `in` operator. Lastly, truthy
  506. // values may be drafts, but falsy values are never drafts.
  507. var isUnchanged = value ? is(baseValue, value) || value === state.drafts[prop] : is(baseValue, value) && prop in state.base;
  508. if (isUnchanged) { return true; }
  509. prepareCopy(state);
  510. markChanged(state);
  511. }
  512. state.assigned[prop] = true; // @ts-ignore
  513. state.copy[prop] = value;
  514. return true;
  515. },
  516. deleteProperty: function (state, prop) {
  517. // The `undefined` check is a fast path for pre-existing keys.
  518. if (peek(state.base, prop) !== undefined || prop in state.base) {
  519. state.assigned[prop] = false;
  520. prepareCopy(state);
  521. markChanged(state);
  522. } else if (state.assigned[prop]) {
  523. // if an originally not assigned property was deleted
  524. delete state.assigned[prop];
  525. } // @ts-ignore
  526. if (state.copy) { delete state.copy[prop]; }
  527. return true;
  528. },
  529. // Note: We never coerce `desc.value` into an Immer draft, because we can't make
  530. // the same guarantee in ES5 mode.
  531. getOwnPropertyDescriptor: function (state, prop) {
  532. var owner = latest(state);
  533. var desc = Reflect.getOwnPropertyDescriptor(owner, prop);
  534. if (desc) {
  535. desc.writable = true;
  536. desc.configurable = state.type !== ProxyType.ProxyArray || prop !== "length";
  537. }
  538. return desc;
  539. },
  540. defineProperty: function () {
  541. throw new Error("Object.defineProperty() cannot be used on an Immer draft"); // prettier-ignore
  542. },
  543. getPrototypeOf: function (state) {
  544. return Object.getPrototypeOf(state.base);
  545. },
  546. setPrototypeOf: function () {
  547. throw new Error("Object.setPrototypeOf() cannot be used on an Immer draft"); // prettier-ignore
  548. }
  549. };
  550. /**
  551. * Array drafts
  552. */
  553. var arrayTraps = {};
  554. each(objectTraps, function (key, fn) {
  555. // @ts-ignore
  556. arrayTraps[key] = function () {
  557. arguments[0] = arguments[0][0];
  558. return fn.apply(this, arguments);
  559. };
  560. });
  561. arrayTraps.deleteProperty = function (state, prop) {
  562. if (isNaN(parseInt(prop))) {
  563. throw new Error("Immer only supports deleting array indices"); // prettier-ignore
  564. }
  565. return objectTraps.deleteProperty.call(this, state[0], prop);
  566. };
  567. arrayTraps.set = function (state, prop, value) {
  568. if (prop !== "length" && isNaN(parseInt(prop))) {
  569. throw new Error("Immer only supports setting array indices and the 'length' property"); // prettier-ignore
  570. }
  571. return objectTraps.set.call(this, state[0], prop, value, state[0]);
  572. };
  573. /**
  574. * Map drafts
  575. */
  576. // Access a property without creating an Immer draft.
  577. function peek(draft, prop) {
  578. var state = draft[DRAFT_STATE];
  579. var desc = Reflect.getOwnPropertyDescriptor(state ? latest(state) : draft, prop);
  580. return desc && desc.value;
  581. }
  582. function markChanged(state) {
  583. if (!state.modified) {
  584. state.modified = true;
  585. if (state.type === ProxyType.ProxyObject || state.type === ProxyType.ProxyArray) {
  586. var copy_1 = state.copy = shallowCopy(state.base);
  587. each(state.drafts, function (key, value) {
  588. // @ts-ignore
  589. copy_1[key] = value;
  590. });
  591. state.drafts = undefined;
  592. }
  593. if (state.parent) {
  594. markChanged(state.parent);
  595. }
  596. }
  597. }
  598. function prepareCopy(state) {
  599. if (!state.copy) {
  600. state.copy = shallowCopy(state.base);
  601. }
  602. }
  603. function willFinalizeES5(scope, result, isReplaced) {
  604. scope.drafts.forEach(function (draft) {
  605. draft[DRAFT_STATE].finalizing = true;
  606. });
  607. if (!isReplaced) {
  608. if (scope.patches) {
  609. markChangesRecursively(scope.drafts[0]);
  610. } // This is faster when we don't care about which attributes changed.
  611. markChangesSweep(scope.drafts);
  612. } // When a child draft is returned, look for changes.
  613. else if (isDraft(result) && result[DRAFT_STATE].scope === scope) {
  614. markChangesSweep(scope.drafts);
  615. }
  616. }
  617. function createES5Proxy(base, parent) {
  618. var isArray = Array.isArray(base);
  619. var draft = clonePotentialDraft(base);
  620. each(draft, function (prop) {
  621. proxyProperty(draft, prop, isArray || isEnumerable(base, prop));
  622. });
  623. var state = {
  624. type: isArray ? ProxyType.ES5Array : ProxyType.ES5Object,
  625. scope: parent ? parent.scope : ImmerScope.current,
  626. modified: false,
  627. finalizing: false,
  628. finalized: false,
  629. assigned: {},
  630. parent: parent,
  631. base: base,
  632. draft: draft,
  633. copy: null,
  634. revoked: false,
  635. isManual: false
  636. };
  637. createHiddenProperty(draft, DRAFT_STATE, state);
  638. return draft;
  639. } // Access a property without creating an Immer draft.
  640. function peek$1(draft, prop) {
  641. var state = draft[DRAFT_STATE];
  642. if (state && !state.finalizing) {
  643. state.finalizing = true;
  644. var value = draft[prop];
  645. state.finalizing = false;
  646. return value;
  647. }
  648. return draft[prop];
  649. }
  650. function get$1(state, prop) {
  651. assertUnrevoked(state);
  652. var value = peek$1(latest(state), prop);
  653. if (state.finalizing) { return value; } // Create a draft if the value is unmodified.
  654. if (value === peek$1(state.base, prop) && isDraftable(value)) {
  655. prepareCopy$1(state); // @ts-ignore
  656. return state.copy[prop] = state.scope.immer.createProxy(value, state);
  657. }
  658. return value;
  659. }
  660. function set$1(state, prop, value) {
  661. assertUnrevoked(state);
  662. state.assigned[prop] = true;
  663. if (!state.modified) {
  664. if (is(value, peek$1(latest(state), prop))) { return; }
  665. markChangedES5(state);
  666. prepareCopy$1(state);
  667. } // @ts-ignore
  668. state.copy[prop] = value;
  669. }
  670. function markChangedES5(state) {
  671. if (!state.modified) {
  672. state.modified = true;
  673. if (state.parent) { markChangedES5(state.parent); }
  674. }
  675. }
  676. function prepareCopy$1(state) {
  677. if (!state.copy) { state.copy = clonePotentialDraft(state.base); }
  678. }
  679. function clonePotentialDraft(base) {
  680. var state = base && base[DRAFT_STATE];
  681. if (state) {
  682. state.finalizing = true;
  683. var draft = shallowCopy(state.draft, true);
  684. state.finalizing = false;
  685. return draft;
  686. }
  687. return shallowCopy(base);
  688. } // property descriptors are recycled to make sure we don't create a get and set closure per property,
  689. // but share them all instead
  690. var descriptors = {};
  691. function proxyProperty(draft, prop, enumerable) {
  692. var desc = descriptors[prop];
  693. if (desc) {
  694. desc.enumerable = enumerable;
  695. } else {
  696. descriptors[prop] = desc = {
  697. configurable: true,
  698. enumerable: enumerable,
  699. get: function () {
  700. return get$1(this[DRAFT_STATE], prop);
  701. },
  702. set: function (value) {
  703. set$1(this[DRAFT_STATE], prop, value);
  704. }
  705. };
  706. }
  707. Object.defineProperty(draft, prop, desc);
  708. }
  709. function assertUnrevoked(state) {
  710. if (state.revoked === true) { throw new Error("Cannot use a proxy that has been revoked. Did you pass an object from inside an immer function to an async process? " + JSON.stringify(latest(state))); }
  711. } // This looks expensive, but only proxies are visited, and only objects without known changes are scanned.
  712. function markChangesSweep(drafts) {
  713. // The natural order of drafts in the `scope` array is based on when they
  714. // were accessed. By processing drafts in reverse natural order, we have a
  715. // better chance of processing leaf nodes first. When a leaf node is known to
  716. // have changed, we can avoid any traversal of its ancestor nodes.
  717. for (var i = drafts.length - 1; i >= 0; i--) {
  718. var state = drafts[i][DRAFT_STATE];
  719. if (!state.modified) {
  720. switch (state.type) {
  721. case ProxyType.ES5Array:
  722. if (hasArrayChanges(state)) { markChangedES5(state); }
  723. break;
  724. case ProxyType.ES5Object:
  725. if (hasObjectChanges(state)) { markChangedES5(state); }
  726. break;
  727. }
  728. }
  729. }
  730. }
  731. function markChangesRecursively(object) {
  732. if (!object || typeof object !== "object") { return; }
  733. var state = object[DRAFT_STATE];
  734. if (!state) { return; }
  735. var base = state.base,
  736. draft = state.draft,
  737. assigned = state.assigned,
  738. type = state.type;
  739. if (type === ProxyType.ES5Object) {
  740. // Look for added keys.
  741. // TODO: looks quite duplicate to hasObjectChanges,
  742. // probably there is a faster way to detect changes, as sweep + recurse seems to do some
  743. // unnecessary work.
  744. // also: probably we can store the information we detect here, to speed up tree finalization!
  745. each(draft, function (key) {
  746. if (key === DRAFT_STATE) { return; } // The `undefined` check is a fast path for pre-existing keys.
  747. if (base[key] === undefined && !has(base, key)) {
  748. assigned[key] = true;
  749. markChangedES5(state);
  750. } else if (!assigned[key]) {
  751. // Only untouched properties trigger recursion.
  752. markChangesRecursively(draft[key]);
  753. }
  754. }); // Look for removed keys.
  755. each(base, function (key) {
  756. // The `undefined` check is a fast path for pre-existing keys.
  757. if (draft[key] === undefined && !has(draft, key)) {
  758. assigned[key] = false;
  759. markChangedES5(state);
  760. }
  761. });
  762. } else if (type === ProxyType.ES5Array && hasArrayChanges(state)) {
  763. markChangedES5(state);
  764. assigned.length = true;
  765. if (draft.length < base.length) {
  766. for (var i = draft.length; i < base.length; i++) { assigned[i] = false; }
  767. } else {
  768. for (var i = base.length; i < draft.length; i++) { assigned[i] = true; }
  769. }
  770. for (var i = 0; i < draft.length; i++) {
  771. // Only untouched indices trigger recursion.
  772. if (assigned[i] === undefined) { markChangesRecursively(draft[i]); }
  773. }
  774. }
  775. }
  776. function hasObjectChanges(state) {
  777. var base = state.base,
  778. draft = state.draft; // Search for added keys and changed keys. Start at the back, because
  779. // non-numeric keys are ordered by time of definition on the object.
  780. var keys = Object.keys(draft);
  781. for (var i = keys.length - 1; i >= 0; i--) {
  782. var key = keys[i];
  783. var baseValue = base[key]; // The `undefined` check is a fast path for pre-existing keys.
  784. if (baseValue === undefined && !has(base, key)) {
  785. return true;
  786. } // Once a base key is deleted, future changes go undetected, because its
  787. // descriptor is erased. This branch detects any missed changes.
  788. else {
  789. var value = draft[key];
  790. var state_1 = value && value[DRAFT_STATE];
  791. if (state_1 ? state_1.base !== baseValue : !is(value, baseValue)) {
  792. return true;
  793. }
  794. }
  795. } // At this point, no keys were added or changed.
  796. // Compare key count to determine if keys were deleted.
  797. return keys.length !== Object.keys(base).length;
  798. }
  799. function hasArrayChanges(state) {
  800. var draft = state.draft;
  801. if (draft.length !== state.base.length) { return true; } // See #116
  802. // If we first shorten the length, our array interceptors will be removed.
  803. // If after that new items are added, result in the same original length,
  804. // those last items will have no intercepting property.
  805. // So if there is no own descriptor on the last position, we know that items were removed and added
  806. // N.B.: splice, unshift, etc only shift values around, but not prop descriptors, so we only have to check
  807. // the last one
  808. var descriptor = Object.getOwnPropertyDescriptor(draft, draft.length - 1); // descriptor can be null, but only for newly created sparse arrays, eg. new Array(10)
  809. if (descriptor && !descriptor.get) { return true; } // For all other cases, we don't have to compare, as they would have been picked up by the index setters
  810. return false;
  811. }
  812. var DraftMap = function (_super) {
  813. if (!_super) {
  814. /* istanbul ignore next */
  815. throw new Error("Map is not polyfilled");
  816. }
  817. __extends(DraftMap, _super); // Create class manually, cause #502
  818. function DraftMap(target, parent) {
  819. this[DRAFT_STATE] = {
  820. type: ProxyType.Map,
  821. parent: parent,
  822. scope: parent ? parent.scope : ImmerScope.current,
  823. modified: false,
  824. finalized: false,
  825. copy: undefined,
  826. assigned: undefined,
  827. base: target,
  828. draft: this,
  829. isManual: false,
  830. revoked: false
  831. };
  832. return this;
  833. }
  834. var p = DraftMap.prototype; // TODO: smaller build size if we create a util for Object.defineProperty
  835. Object.defineProperty(p, "size", {
  836. get: function () {
  837. return latest(this[DRAFT_STATE]).size;
  838. },
  839. enumerable: true,
  840. configurable: true
  841. });
  842. p.has = function (key) {
  843. return latest(this[DRAFT_STATE]).has(key);
  844. };
  845. p.set = function (key, value) {
  846. var state = this[DRAFT_STATE];
  847. assertUnrevoked(state);
  848. if (latest(state).get(key) !== value) {
  849. prepareCopy$2(state);
  850. state.scope.immer.markChanged(state);
  851. state.assigned.set(key, true);
  852. state.copy.set(key, value);
  853. state.assigned.set(key, true);
  854. }
  855. return this;
  856. };
  857. p.delete = function (key) {
  858. if (!this.has(key)) {
  859. return false;
  860. }
  861. var state = this[DRAFT_STATE];
  862. assertUnrevoked(state);
  863. prepareCopy$2(state);
  864. state.scope.immer.markChanged(state);
  865. state.assigned.set(key, false);
  866. state.copy.delete(key);
  867. return true;
  868. };
  869. p.clear = function () {
  870. var state = this[DRAFT_STATE];
  871. assertUnrevoked(state);
  872. prepareCopy$2(state);
  873. state.scope.immer.markChanged(state);
  874. state.assigned = new Map();
  875. return state.copy.clear();
  876. };
  877. p.forEach = function (cb, thisArg) {
  878. var _this = this;
  879. var state = this[DRAFT_STATE];
  880. latest(state).forEach(function (_value, key, _map) {
  881. cb.call(thisArg, _this.get(key), key, _this);
  882. });
  883. };
  884. p.get = function (key) {
  885. var state = this[DRAFT_STATE];
  886. assertUnrevoked(state);
  887. var value = latest(state).get(key);
  888. if (state.finalized || !isDraftable(value)) {
  889. return value;
  890. }
  891. if (value !== state.base.get(key)) {
  892. return value; // either already drafted or reassigned
  893. } // despite what it looks, this creates a draft only once, see above condition
  894. var draft = state.scope.immer.createProxy(value, state);
  895. prepareCopy$2(state);
  896. state.copy.set(key, draft);
  897. return draft;
  898. };
  899. p.keys = function () {
  900. return latest(this[DRAFT_STATE]).keys();
  901. };
  902. p.values = function () {
  903. var _a;
  904. var _this = this;
  905. var iterator = this.keys();
  906. return _a = {}, _a[iteratorSymbol] = function () {
  907. return _this.values();
  908. }, _a.next = function () {
  909. var r = iterator.next();
  910. /* istanbul ignore next */
  911. if (r.done) { return r; }
  912. var value = _this.get(r.value);
  913. return {
  914. done: false,
  915. value: value
  916. };
  917. }, _a;
  918. };
  919. p.entries = function () {
  920. var _a;
  921. var _this = this;
  922. var iterator = this.keys();
  923. return _a = {}, _a[iteratorSymbol] = function () {
  924. return _this.entries();
  925. }, _a.next = function () {
  926. var r = iterator.next();
  927. /* istanbul ignore next */
  928. if (r.done) { return r; }
  929. var value = _this.get(r.value);
  930. return {
  931. done: false,
  932. value: [r.value, value]
  933. };
  934. }, _a;
  935. };
  936. p[iteratorSymbol] = function () {
  937. return this.entries();
  938. };
  939. return DraftMap;
  940. }(Map);
  941. function proxyMap(target, parent) {
  942. // @ts-ignore
  943. return new DraftMap(target, parent);
  944. }
  945. function prepareCopy$2(state) {
  946. if (!state.copy) {
  947. state.assigned = new Map();
  948. state.copy = new Map(state.base);
  949. }
  950. }
  951. var DraftSet = function (_super) {
  952. if (!_super) {
  953. /* istanbul ignore next */
  954. throw new Error("Set is not polyfilled");
  955. }
  956. __extends(DraftSet, _super); // Create class manually, cause #502
  957. function DraftSet(target, parent) {
  958. this[DRAFT_STATE] = {
  959. type: ProxyType.Set,
  960. parent: parent,
  961. scope: parent ? parent.scope : ImmerScope.current,
  962. modified: false,
  963. finalized: false,
  964. copy: undefined,
  965. base: target,
  966. draft: this,
  967. drafts: new Map(),
  968. revoked: false,
  969. isManual: false
  970. };
  971. return this;
  972. }
  973. var p = DraftSet.prototype;
  974. Object.defineProperty(p, "size", {
  975. get: function () {
  976. return latest(this[DRAFT_STATE]).size;
  977. },
  978. enumerable: true,
  979. configurable: true
  980. });
  981. p.has = function (value) {
  982. var state = this[DRAFT_STATE];
  983. assertUnrevoked(state); // bit of trickery here, to be able to recognize both the value, and the draft of its value
  984. if (!state.copy) {
  985. return state.base.has(value);
  986. }
  987. if (state.copy.has(value)) { return true; }
  988. if (state.drafts.has(value) && state.copy.has(state.drafts.get(value))) { return true; }
  989. return false;
  990. };
  991. p.add = function (value) {
  992. var state = this[DRAFT_STATE];
  993. assertUnrevoked(state);
  994. if (state.copy) {
  995. state.copy.add(value);
  996. } else if (!state.base.has(value)) {
  997. prepareCopy$3(state);
  998. state.scope.immer.markChanged(state);
  999. state.copy.add(value);
  1000. }
  1001. return this;
  1002. };
  1003. p.delete = function (value) {
  1004. if (!this.has(value)) {
  1005. return false;
  1006. }
  1007. var state = this[DRAFT_STATE];
  1008. assertUnrevoked(state);
  1009. prepareCopy$3(state);
  1010. state.scope.immer.markChanged(state);
  1011. return state.copy.delete(value) || (state.drafts.has(value) ? state.copy.delete(state.drafts.get(value)) :
  1012. /* istanbul ignore next */
  1013. false);
  1014. };
  1015. p.clear = function () {
  1016. var state = this[DRAFT_STATE];
  1017. assertUnrevoked(state);
  1018. prepareCopy$3(state);
  1019. state.scope.immer.markChanged(state);
  1020. return state.copy.clear();
  1021. };
  1022. p.values = function () {
  1023. var state = this[DRAFT_STATE];
  1024. assertUnrevoked(state);
  1025. prepareCopy$3(state);
  1026. return state.copy.values();
  1027. };
  1028. p.entries = function entries() {
  1029. var state = this[DRAFT_STATE];
  1030. assertUnrevoked(state);
  1031. prepareCopy$3(state);
  1032. return state.copy.entries();
  1033. };
  1034. p.keys = function () {
  1035. return this.values();
  1036. };
  1037. p[iteratorSymbol] = function () {
  1038. return this.values();
  1039. };
  1040. p.forEach = function forEach(cb, thisArg) {
  1041. var iterator = this.values();
  1042. var result = iterator.next();
  1043. while (!result.done) {
  1044. cb.call(thisArg, result.value, result.value, this);
  1045. result = iterator.next();
  1046. }
  1047. };
  1048. return DraftSet;
  1049. }(Set);
  1050. function proxySet(target, parent) {
  1051. // @ts-ignore
  1052. return new DraftSet(target, parent);
  1053. }
  1054. function prepareCopy$3(state) {
  1055. if (!state.copy) {
  1056. // create drafts for all entries to preserve insertion order
  1057. state.copy = new Set();
  1058. state.base.forEach(function (value) {
  1059. if (isDraftable(value)) {
  1060. var draft = state.scope.immer.createProxy(value, state);
  1061. state.drafts.set(value, draft);
  1062. state.copy.add(draft);
  1063. } else {
  1064. state.copy.add(value);
  1065. }
  1066. });
  1067. }
  1068. }
  1069. function generatePatches(state, basePath, patches, inversePatches) {
  1070. switch (state.type) {
  1071. case ProxyType.ProxyObject:
  1072. case ProxyType.ES5Object:
  1073. case ProxyType.Map:
  1074. return generatePatchesFromAssigned(state, basePath, patches, inversePatches);
  1075. case ProxyType.ES5Array:
  1076. case ProxyType.ProxyArray:
  1077. return generateArrayPatches(state, basePath, patches, inversePatches);
  1078. case ProxyType.Set:
  1079. return generateSetPatches(state, basePath, patches, inversePatches);
  1080. }
  1081. }
  1082. function generateArrayPatches(state, basePath, patches, inversePatches) {
  1083. var _a, _b;
  1084. var base = state.base,
  1085. assigned = state.assigned,
  1086. copy = state.copy;
  1087. /* istanbul ignore next */
  1088. if (!copy) { die(); } // Reduce complexity by ensuring `base` is never longer.
  1089. if (copy.length < base.length) {
  1090. _a = [copy, base], base = _a[0], copy = _a[1];
  1091. _b = [inversePatches, patches], patches = _b[0], inversePatches = _b[1];
  1092. }
  1093. var delta = copy.length - base.length; // Find the first replaced index.
  1094. var start = 0;
  1095. while (base[start] === copy[start] && start < base.length) {
  1096. ++start;
  1097. } // Find the last replaced index. Search from the end to optimize splice patches.
  1098. var end = base.length;
  1099. while (end > start && base[end - 1] === copy[end + delta - 1]) {
  1100. --end;
  1101. } // Process replaced indices.
  1102. for (var i = start; i < end; ++i) {
  1103. if (assigned[i] && copy[i] !== base[i]) {
  1104. var path = basePath.concat([i]);
  1105. patches.push({
  1106. op: "replace",
  1107. path: path,
  1108. value: copy[i]
  1109. });
  1110. inversePatches.push({
  1111. op: "replace",
  1112. path: path,
  1113. value: base[i]
  1114. });
  1115. }
  1116. }
  1117. var replaceCount = patches.length; // Process added indices.
  1118. for (var i = end + delta - 1; i >= end; --i) {
  1119. var path = basePath.concat([i]);
  1120. patches[replaceCount + i - end] = {
  1121. op: "add",
  1122. path: path,
  1123. value: copy[i]
  1124. };
  1125. inversePatches.push({
  1126. op: "remove",
  1127. path: path
  1128. });
  1129. }
  1130. } // This is used for both Map objects and normal objects.
  1131. function generatePatchesFromAssigned(state, basePath, patches, inversePatches) {
  1132. var base = state.base,
  1133. copy = state.copy;
  1134. each(state.assigned, function (key, assignedValue) {
  1135. var origValue = get(base, key);
  1136. var value = get(copy, key);
  1137. var op = !assignedValue ? "remove" : has(base, key) ? "replace" : "add";
  1138. if (origValue === value && op === "replace") { return; }
  1139. var path = basePath.concat(key);
  1140. patches.push(op === "remove" ? {
  1141. op: op,
  1142. path: path
  1143. } : {
  1144. op: op,
  1145. path: path,
  1146. value: value
  1147. });
  1148. inversePatches.push(op === "add" ? {
  1149. op: "remove",
  1150. path: path
  1151. } : op === "remove" ? {
  1152. op: "add",
  1153. path: path,
  1154. value: origValue
  1155. } : {
  1156. op: "replace",
  1157. path: path,
  1158. value: origValue
  1159. });
  1160. });
  1161. }
  1162. function generateSetPatches(state, basePath, patches, inversePatches) {
  1163. var base = state.base,
  1164. copy = state.copy;
  1165. var i = 0;
  1166. base.forEach(function (value) {
  1167. if (!copy.has(value)) {
  1168. var path = basePath.concat([i]);
  1169. patches.push({
  1170. op: "remove",
  1171. path: path,
  1172. value: value
  1173. });
  1174. inversePatches.unshift({
  1175. op: "add",
  1176. path: path,
  1177. value: value
  1178. });
  1179. }
  1180. i++;
  1181. });
  1182. i = 0;
  1183. copy.forEach(function (value) {
  1184. if (!base.has(value)) {
  1185. var path = basePath.concat([i]);
  1186. patches.push({
  1187. op: "add",
  1188. path: path,
  1189. value: value
  1190. });
  1191. inversePatches.unshift({
  1192. op: "remove",
  1193. path: path,
  1194. value: value
  1195. });
  1196. }
  1197. i++;
  1198. });
  1199. }
  1200. function applyPatches(draft, patches) {
  1201. patches.forEach(function (patch) {
  1202. var path = patch.path,
  1203. op = patch.op;
  1204. /* istanbul ignore next */
  1205. if (!path.length) { die(); }
  1206. var base = draft;
  1207. for (var i = 0; i < path.length - 1; i++) {
  1208. base = get(base, path[i]);
  1209. if (!base || typeof base !== "object") { throw new Error("Cannot apply patch, path doesn't resolve: " + path.join("/")); } // prettier-ignore
  1210. }
  1211. var type = getArchtype(base);
  1212. var value = deepClonePatchValue(patch.value); // used to clone patch to ensure original patch is not modified, see #411
  1213. var key = path[path.length - 1];
  1214. switch (op) {
  1215. case "replace":
  1216. switch (type) {
  1217. case Archtype.Map:
  1218. return base.set(key, value);
  1219. /* istanbul ignore next */
  1220. case Archtype.Set:
  1221. throw new Error('Sets cannot have "replace" patches.');
  1222. default:
  1223. // if value is an object, then it's assigned by reference
  1224. // in the following add or remove ops, the value field inside the patch will also be modifyed
  1225. // so we use value from the cloned patch
  1226. // @ts-ignore
  1227. return base[key] = value;
  1228. }
  1229. case "add":
  1230. switch (type) {
  1231. case Archtype.Array:
  1232. return base.splice(key, 0, value);
  1233. case Archtype.Map:
  1234. return base.set(key, value);
  1235. case Archtype.Set:
  1236. return base.add(value);
  1237. default:
  1238. return base[key] = value;
  1239. }
  1240. case "remove":
  1241. switch (type) {
  1242. case Archtype.Array:
  1243. return base.splice(key, 1);
  1244. case Archtype.Map:
  1245. return base.delete(key);
  1246. case Archtype.Set:
  1247. return base.delete(patch.value);
  1248. default:
  1249. return delete base[key];
  1250. }
  1251. default:
  1252. throw new Error("Unsupported patch operation: " + op);
  1253. }
  1254. });
  1255. return draft;
  1256. }
  1257. function deepClonePatchValue(obj) {
  1258. if (!obj || typeof obj !== "object") { return obj; }
  1259. if (Array.isArray(obj)) { return obj.map(deepClonePatchValue); }
  1260. if (isMap(obj)) { return new Map(Array.from(obj.entries()).map(function (_a) {
  1261. var k = _a[0],
  1262. v = _a[1];
  1263. return [k, deepClonePatchValue(v)];
  1264. })); } // Not needed: if (isSet(obj)) return new Set(Array.from(obj.values()).map(deepClone))
  1265. var cloned = Object.create(Object.getPrototypeOf(obj));
  1266. for (var key in obj) { cloned[key] = deepClonePatchValue(obj[key]); }
  1267. return cloned;
  1268. }
  1269. /*! *****************************************************************************
  1270. Copyright (c) Microsoft Corporation. All rights reserved.
  1271. Licensed under the Apache License, Version 2.0 (the "License"); you may not use
  1272. this file except in compliance with the License. You may obtain a copy of the
  1273. License at http://www.apache.org/licenses/LICENSE-2.0
  1274. THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  1275. KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
  1276. WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
  1277. MERCHANTABLITY OR NON-INFRINGEMENT.
  1278. See the Apache Version 2.0 License for specific language governing permissions
  1279. and limitations under the License.
  1280. ***************************************************************************** */
  1281. function __spreadArrays() {
  1282. for (var s = 0, i = 0, il = arguments.length; i < il; i++) s += arguments[i].length;
  1283. for (var r = Array(s), k = 0, i = 0; i < il; i++)
  1284. for (var a = arguments[i], j = 0, jl = a.length; j < jl; j++, k++)
  1285. r[k] = a[j];
  1286. return r;
  1287. }
  1288. /* istanbul ignore next */
  1289. function verifyMinified() {}
  1290. var configDefaults = {
  1291. useProxies: typeof Proxy !== "undefined" && typeof Proxy.revocable !== "undefined" && typeof Reflect !== "undefined",
  1292. autoFreeze: typeof process !== "undefined" ? process.env.NODE_ENV !== "production" :
  1293. /* istanbul ignore next */
  1294. verifyMinified.name === "verifyMinified",
  1295. onAssign: null,
  1296. onDelete: null,
  1297. onCopy: null
  1298. };
  1299. var Immer =
  1300. /** @class */
  1301. function () {
  1302. function Immer(config) {
  1303. var _this = this;
  1304. this.useProxies = false;
  1305. this.autoFreeze = false;
  1306. each(configDefaults, function (key, value) {
  1307. var _a, _b; // @ts-ignore
  1308. _this[key] = (_b = (_a = config) === null || _a === void 0 ? void 0 : _a[key], _b !== null && _b !== void 0 ? _b : value);
  1309. });
  1310. this.setUseProxies(this.useProxies);
  1311. this.produce = this.produce.bind(this);
  1312. this.produceWithPatches = this.produceWithPatches.bind(this);
  1313. }
  1314. /**
  1315. * The `produce` function takes a value and a "recipe function" (whose
  1316. * return value often depends on the base state). The recipe function is
  1317. * free to mutate its first argument however it wants. All mutations are
  1318. * only ever applied to a __copy__ of the base state.
  1319. *
  1320. * Pass only a function to create a "curried producer" which relieves you
  1321. * from passing the recipe function every time.
  1322. *
  1323. * Only plain objects and arrays are made mutable. All other objects are
  1324. * considered uncopyable.
  1325. *
  1326. * Note: This function is __bound__ to its `Immer` instance.
  1327. *
  1328. * @param {any} base - the initial state
  1329. * @param {Function} producer - function that receives a proxy of the base state as first argument and which can be freely modified
  1330. * @param {Function} patchListener - optional function that will be called with all the patches produced here
  1331. * @returns {any} a new state, or the initial state if nothing was modified
  1332. */
  1333. Immer.prototype.produce = function (base, recipe, patchListener) {
  1334. var _this = this; // curried invocation
  1335. if (typeof base === "function" && typeof recipe !== "function") {
  1336. var defaultBase_1 = recipe;
  1337. recipe = base;
  1338. var self_1 = this;
  1339. return function curriedProduce(base) {
  1340. var arguments$1 = arguments;
  1341. var _this = this;
  1342. if (base === void 0) {
  1343. base = defaultBase_1;
  1344. }
  1345. var args = [];
  1346. for (var _i = 1; _i < arguments.length; _i++) {
  1347. args[_i - 1] = arguments$1[_i];
  1348. }
  1349. return self_1.produce(base, function (draft) {
  1350. return recipe.call.apply(recipe, __spreadArrays([_this, draft], args));
  1351. }); // prettier-ignore
  1352. };
  1353. } // prettier-ignore
  1354. {
  1355. if (typeof recipe !== "function") {
  1356. throw new Error("The first or second argument to `produce` must be a function");
  1357. }
  1358. if (patchListener !== undefined && typeof patchListener !== "function") {
  1359. throw new Error("The third argument to `produce` must be a function or undefined");
  1360. }
  1361. }
  1362. var result; // Only plain objects, arrays, and "immerable classes" are drafted.
  1363. if (isDraftable(base)) {
  1364. var scope_1 = ImmerScope.enter(this);
  1365. var proxy = this.createProxy(base, undefined);
  1366. var hasError = true;
  1367. try {
  1368. result = recipe(proxy);
  1369. hasError = false;
  1370. } finally {
  1371. // finally instead of catch + rethrow better preserves original stack
  1372. if (hasError) { scope_1.revoke(); }else { scope_1.leave(); }
  1373. }
  1374. if (typeof Promise !== "undefined" && result instanceof Promise) {
  1375. return result.then(function (result) {
  1376. scope_1.usePatches(patchListener);
  1377. return processResult(_this, result, scope_1);
  1378. }, function (error) {
  1379. scope_1.revoke();
  1380. throw error;
  1381. });
  1382. }
  1383. scope_1.usePatches(patchListener);
  1384. return processResult(this, result, scope_1);
  1385. } else {
  1386. result = recipe(base);
  1387. if (result === NOTHING) { return undefined; }
  1388. if (result === undefined) { result = base; }
  1389. maybeFreeze(this, result, true);
  1390. return result;
  1391. }
  1392. };
  1393. Immer.prototype.produceWithPatches = function (arg1, arg2, arg3) {
  1394. var _this = this;
  1395. if (typeof arg1 === "function") {
  1396. return function (state) {
  1397. var arguments$1 = arguments;
  1398. var args = [];
  1399. for (var _i = 1; _i < arguments.length; _i++) {
  1400. args[_i - 1] = arguments$1[_i];
  1401. }
  1402. return _this.produceWithPatches(state, function (draft) {
  1403. return arg1.apply(void 0, __spreadArrays([draft], args));
  1404. });
  1405. };
  1406. } // non-curried form
  1407. /* istanbul ignore next */
  1408. if (arg3) { die(); }
  1409. var patches, inversePatches;
  1410. var nextState = this.produce(arg1, arg2, function (p, ip) {
  1411. patches = p;
  1412. inversePatches = ip;
  1413. });
  1414. return [nextState, patches, inversePatches];
  1415. };
  1416. Immer.prototype.createDraft = function (base) {
  1417. if (!isDraftable(base)) {
  1418. throw new Error("First argument to `createDraft` must be a plain object, an array, or an immerable object"); // prettier-ignore
  1419. }
  1420. var scope = ImmerScope.enter(this);
  1421. var proxy = this.createProxy(base, undefined);
  1422. proxy[DRAFT_STATE].isManual = true;
  1423. scope.leave();
  1424. return proxy;
  1425. };
  1426. Immer.prototype.finishDraft = function (draft, patchListener) {
  1427. var state = draft && draft[DRAFT_STATE];
  1428. if (!state || !state.isManual) {
  1429. throw new Error("First argument to `finishDraft` must be a draft returned by `createDraft`"); // prettier-ignore
  1430. }
  1431. if (state.finalized) {
  1432. throw new Error("The given draft is already finalized"); // prettier-ignore
  1433. }
  1434. var scope = state.scope;
  1435. scope.usePatches(patchListener);
  1436. return processResult(this, undefined, scope);
  1437. };
  1438. /**
  1439. * Pass true to automatically freeze all copies created by Immer.
  1440. *
  1441. * By default, auto-freezing is disabled in production.
  1442. */
  1443. Immer.prototype.setAutoFreeze = function (value) {
  1444. this.autoFreeze = value;
  1445. };
  1446. /**
  1447. * Pass true to use the ES2015 `Proxy` class when creating drafts, which is
  1448. * always faster than using ES5 proxies.
  1449. *
  1450. * By default, feature detection is used, so calling this is rarely necessary.
  1451. */
  1452. Immer.prototype.setUseProxies = function (value) {
  1453. this.useProxies = value;
  1454. };
  1455. Immer.prototype.applyPatches = function (base, patches) {
  1456. // If a patch replaces the entire state, take that replacement as base
  1457. // before applying patches
  1458. var i;
  1459. for (i = patches.length - 1; i >= 0; i--) {
  1460. var patch = patches[i];
  1461. if (patch.path.length === 0 && patch.op === "replace") {
  1462. base = patch.value;
  1463. break;
  1464. }
  1465. }
  1466. if (isDraft(base)) {
  1467. // N.B: never hits if some patch a replacement, patches are never drafts
  1468. return applyPatches(base, patches);
  1469. } // Otherwise, produce a copy of the base state.
  1470. return this.produce(base, function (draft) {
  1471. return applyPatches(draft, patches.slice(i + 1));
  1472. });
  1473. };
  1474. Immer.prototype.createProxy = function (value, parent) {
  1475. // precondition: createProxy should be guarded by isDraftable, so we know we can safely draft
  1476. var draft = isMap(value) ? proxyMap(value, parent) : isSet(value) ? proxySet(value, parent) : this.useProxies ? createProxy(value, parent) : createES5Proxy(value, parent);
  1477. var scope = parent ? parent.scope : ImmerScope.current;
  1478. scope.drafts.push(draft);
  1479. return draft;
  1480. };
  1481. Immer.prototype.willFinalize = function (scope, thing, isReplaced) {
  1482. if (!this.useProxies) { willFinalizeES5(scope, thing, isReplaced); }
  1483. };
  1484. Immer.prototype.markChanged = function (state) {
  1485. if (this.useProxies) {
  1486. markChanged(state);
  1487. } else {
  1488. markChangedES5(state);
  1489. }
  1490. };
  1491. return Immer;
  1492. }();
  1493. var immer = new Immer();
  1494. /**
  1495. * The `produce` function takes a value and a "recipe function" (whose
  1496. * return value often depends on the base state). The recipe function is
  1497. * free to mutate its first argument however it wants. All mutations are
  1498. * only ever applied to a __copy__ of the base state.
  1499. *
  1500. * Pass only a function to create a "curried producer" which relieves you
  1501. * from passing the recipe function every time.
  1502. *
  1503. * Only plain objects and arrays are made mutable. All other objects are
  1504. * considered uncopyable.
  1505. *
  1506. * Note: This function is __bound__ to its `Immer` instance.
  1507. *
  1508. * @param {any} base - the initial state
  1509. * @param {Function} producer - function that receives a proxy of the base state as first argument and which can be freely modified
  1510. * @param {Function} patchListener - optional function that will be called with all the patches produced here
  1511. * @returns {any} a new state, or the initial state if nothing was modified
  1512. */
  1513. var produce = immer.produce;
  1514. /**
  1515. * Like `produce`, but `produceWithPatches` always returns a tuple
  1516. * [nextState, patches, inversePatches] (instead of just the next state)
  1517. */
  1518. var produceWithPatches = immer.produceWithPatches.bind(immer);
  1519. /**
  1520. * Pass true to automatically freeze all copies created by Immer.
  1521. *
  1522. * By default, auto-freezing is disabled in production.
  1523. */
  1524. var setAutoFreeze = immer.setAutoFreeze.bind(immer);
  1525. /**
  1526. * Pass true to use the ES2015 `Proxy` class when creating drafts, which is
  1527. * always faster than using ES5 proxies.
  1528. *
  1529. * By default, feature detection is used, so calling this is rarely necessary.
  1530. */
  1531. var setUseProxies = immer.setUseProxies.bind(immer);
  1532. /**
  1533. * Apply an array of Immer patches to the first argument.
  1534. *
  1535. * This function is a producer, which means copy-on-write is in effect.
  1536. */
  1537. var applyPatches$1 = immer.applyPatches.bind(immer);
  1538. /**
  1539. * Create an Immer draft from the given base state, which may be a draft itself.
  1540. * The draft can be modified until you finalize it with the `finishDraft` function.
  1541. */
  1542. var createDraft = immer.createDraft.bind(immer);
  1543. /**
  1544. * Finalize an Immer draft from a `createDraft` call, returning the base state
  1545. * (if no changes were made) or a modified copy. The draft must *not* be
  1546. * mutated afterwards.
  1547. *
  1548. * Pass a function as the 2nd argument to generate Immer patches based on the
  1549. * changes that were made.
  1550. */
  1551. var finishDraft = immer.finishDraft.bind(immer);
  1552. /**
  1553. * This function is actually a no-op, but can be used to cast an immutable type
  1554. * to an draft type and make TypeScript happy
  1555. *
  1556. * @param value
  1557. */
  1558. function castDraft(value) {
  1559. return value;
  1560. }
  1561. /**
  1562. * This function is actually a no-op, but can be used to cast a mutable type
  1563. * to an immutable type and make TypeScript happy
  1564. * @param value
  1565. */
  1566. function castImmutable(value) {
  1567. return value;
  1568. }
  1569. exports.Immer = Immer;
  1570. exports.applyPatches = applyPatches$1;
  1571. exports.castDraft = castDraft;
  1572. exports.castImmutable = castImmutable;
  1573. exports.createDraft = createDraft;
  1574. exports.default = produce;
  1575. exports.finishDraft = finishDraft;
  1576. exports.immerable = DRAFTABLE;
  1577. exports.isDraft = isDraft;
  1578. exports.isDraftable = isDraftable;
  1579. exports.nothing = NOTHING;
  1580. exports.original = original;
  1581. exports.produce = produce;
  1582. exports.produceWithPatches = produceWithPatches;
  1583. exports.setAutoFreeze = setAutoFreeze;
  1584. exports.setUseProxies = setUseProxies;
  1585. });
  1586. unwrapExports(immer_1);
  1587. var immer_2 = immer_1.Immer;
  1588. var immer_3 = immer_1.applyPatches;
  1589. var immer_4 = immer_1.castDraft;
  1590. var immer_5 = immer_1.castImmutable;
  1591. var immer_6 = immer_1.createDraft;
  1592. var immer_7 = immer_1.finishDraft;
  1593. var immer_8 = immer_1.immerable;
  1594. var immer_9 = immer_1.isDraft;
  1595. var immer_10 = immer_1.isDraftable;
  1596. var immer_11 = immer_1.nothing;
  1597. var immer_12 = immer_1.original;
  1598. var immer_13 = immer_1.produce;
  1599. var immer_14 = immer_1.produceWithPatches;
  1600. var immer_15 = immer_1.setAutoFreeze;
  1601. var immer_16 = immer_1.setUseProxies;
  1602. var esrever = createCommonjsModule(function (module, exports) {
  1603. (function(root) {
  1604. // Detect free variables `exports`
  1605. var freeExports = exports;
  1606. // Detect free variable `module`
  1607. var freeModule = module &&
  1608. module.exports == freeExports && module;
  1609. // Detect free variable `global`, from Node.js or Browserified code,
  1610. // and use it as `root`
  1611. var freeGlobal = typeof commonjsGlobal == 'object' && commonjsGlobal;
  1612. if (freeGlobal.global === freeGlobal || freeGlobal.window === freeGlobal) {
  1613. root = freeGlobal;
  1614. }
  1615. /*--------------------------------------------------------------------------*/
  1616. var regexSymbolWithCombiningMarks = /([\0-\u02FF\u0370-\u1AAF\u1B00-\u1DBF\u1E00-\u20CF\u2100-\uD7FF\uE000-\uFE1F\uFE30-\uFFFF]|[\uD800-\uDBFF][\uDC00-\uDFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF])([\u0300-\u036F\u1AB0-\u1AFF\u1DC0-\u1DFF\u20D0-\u20FF\uFE20-\uFE2F]+)/g;
  1617. var regexSurrogatePair = /([\uD800-\uDBFF])([\uDC00-\uDFFF])/g;
  1618. var reverse = function(string) {
  1619. // Step 1: deal with combining marks and astral symbols (surrogate pairs)
  1620. string = string
  1621. // Swap symbols with their combining marks so the combining marks go first
  1622. .replace(regexSymbolWithCombiningMarks, function($0, $1, $2) {
  1623. // Reverse the combining marks so they will end up in the same order
  1624. // later on (after another round of reversing)
  1625. return reverse($2) + $1;
  1626. })
  1627. // Swap high and low surrogates so the low surrogates go first
  1628. .replace(regexSurrogatePair, '$2$1');
  1629. // Step 2: reverse the code units in the string
  1630. var result = '';
  1631. var index = string.length;
  1632. while (index--) {
  1633. result += string.charAt(index);
  1634. }
  1635. return result;
  1636. };
  1637. /*--------------------------------------------------------------------------*/
  1638. var esrever = {
  1639. 'version': '0.2.0',
  1640. 'reverse': reverse
  1641. };
  1642. // Some AMD build optimizers, like r.js, check for specific condition patterns
  1643. // like the following:
  1644. if (freeExports && !freeExports.nodeType) {
  1645. if (freeModule) { // in Node.js, io.js, or RingoJS v0.8.0+
  1646. freeModule.exports = esrever;
  1647. } else { // in Narwhal or RingoJS v0.7.0-
  1648. for (var key in esrever) {
  1649. esrever.hasOwnProperty(key) && (freeExports[key] = esrever[key]);
  1650. }
  1651. }
  1652. } else { // in Rhino or a web browser
  1653. root.esrever = esrever;
  1654. }
  1655. }(commonjsGlobal));
  1656. });
  1657. var dist = createCommonjsModule(function (module, exports) {
  1658. Object.defineProperty(exports, '__esModule', { value: true });
  1659. function _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; }
  1660. var isPlainObject = _interopDefault(index_cjs);
  1661. function _defineProperty(obj, key, value) {
  1662. if (key in obj) {
  1663. Object.defineProperty(obj, key, {
  1664. value: value,
  1665. enumerable: true,
  1666. configurable: true,
  1667. writable: true
  1668. });
  1669. } else {
  1670. obj[key] = value;
  1671. }
  1672. return obj;
  1673. }
  1674. var DIRTY_PATHS = new WeakMap();
  1675. var FLUSHING = new WeakMap();
  1676. var NORMALIZING = new WeakMap();
  1677. var PATH_REFS = new WeakMap();
  1678. var POINT_REFS = new WeakMap();
  1679. var RANGE_REFS = new WeakMap();
  1680. function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); keys.push.apply(keys, symbols); } return keys; }
  1681. function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys(Object(source), true).forEach(function (key) { _defineProperty(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; }
  1682. /**
  1683. * Create a new Slate `Editor` object.
  1684. */
  1685. var createEditor = () => {
  1686. var editor = {
  1687. children: [],
  1688. operations: [],
  1689. selection: null,
  1690. marks: null,
  1691. isInline: () => false,
  1692. isVoid: () => false,
  1693. onChange: () => {},
  1694. apply: op => {
  1695. for (var ref of Editor.pathRefs(editor)) {
  1696. PathRef.transform(ref, op);
  1697. }
  1698. for (var _ref of Editor.pointRefs(editor)) {
  1699. PointRef.transform(_ref, op);
  1700. }
  1701. for (var _ref2 of Editor.rangeRefs(editor)) {
  1702. RangeRef.transform(_ref2, op);
  1703. }
  1704. var set = new Set();
  1705. var dirtyPaths = [];
  1706. var add = path => {
  1707. if (path) {
  1708. var key = path.join(',');
  1709. if (!set.has(key)) {
  1710. set.add(key);
  1711. dirtyPaths.push(path);
  1712. }
  1713. }
  1714. };
  1715. var oldDirtyPaths = DIRTY_PATHS.get(editor) || [];
  1716. var newDirtyPaths = getDirtyPaths(op);
  1717. for (var path of oldDirtyPaths) {
  1718. var newPath = Path.transform(path, op);
  1719. add(newPath);
  1720. }
  1721. for (var _path of newDirtyPaths) {
  1722. add(_path);
  1723. }
  1724. DIRTY_PATHS.set(editor, dirtyPaths);
  1725. Editor.transform(editor, op);
  1726. editor.operations.push(op);
  1727. Editor.normalize(editor); // Clear any formats applied to the cursor if the selection changes.
  1728. if (op.type === 'set_selection') {
  1729. editor.marks = null;
  1730. }
  1731. if (!FLUSHING.get(editor)) {
  1732. FLUSHING.set(editor, true);
  1733. Promise.resolve().then(() => {
  1734. FLUSHING.set(editor, false);
  1735. editor.onChange();
  1736. editor.operations = [];
  1737. });
  1738. }
  1739. },
  1740. addMark: (key, value) => {
  1741. var {
  1742. selection
  1743. } = editor;
  1744. if (selection) {
  1745. if (Range.isExpanded(selection)) {
  1746. Transforms.setNodes(editor, {
  1747. [key]: value
  1748. }, {
  1749. match: Text.isText,
  1750. split: true
  1751. });
  1752. } else {
  1753. var marks = _objectSpread({}, Editor.marks(editor) || {}, {
  1754. [key]: value
  1755. });
  1756. editor.marks = marks;
  1757. editor.onChange();
  1758. }
  1759. }
  1760. },
  1761. deleteBackward: unit => {
  1762. var {
  1763. selection
  1764. } = editor;
  1765. if (selection && Range.isCollapsed(selection)) {
  1766. Transforms.delete(editor, {
  1767. unit,
  1768. reverse: true
  1769. });
  1770. }
  1771. },
  1772. deleteForward: unit => {
  1773. var {
  1774. selection
  1775. } = editor;
  1776. if (selection && Range.isCollapsed(selection)) {
  1777. Transforms.delete(editor, {
  1778. unit
  1779. });
  1780. }
  1781. },
  1782. deleteFragment: () => {
  1783. var {
  1784. selection
  1785. } = editor;
  1786. if (selection && Range.isExpanded(selection)) {
  1787. Transforms.delete(editor);
  1788. }
  1789. },
  1790. insertBreak: () => {
  1791. Transforms.splitNodes(editor, {
  1792. always: true
  1793. });
  1794. },
  1795. insertFragment: fragment => {
  1796. Transforms.insertFragment(editor, fragment);
  1797. },
  1798. insertNode: node => {
  1799. Transforms.insertNodes(editor, node);
  1800. },
  1801. insertText: text => {
  1802. var {
  1803. selection,
  1804. marks
  1805. } = editor;
  1806. if (selection) {
  1807. // If the cursor is at the end of an inline, move it outside of
  1808. // the inline before inserting
  1809. if (Range.isCollapsed(selection)) {
  1810. var inline = Editor.above(editor, {
  1811. match: n => Editor.isInline(editor, n),
  1812. mode: 'highest'
  1813. });
  1814. if (inline) {
  1815. var [, inlinePath] = inline;
  1816. if (Editor.isEnd(editor, selection.anchor, inlinePath)) {
  1817. var point = Editor.after(editor, inlinePath);
  1818. Transforms.setSelection(editor, {
  1819. anchor: point,
  1820. focus: point
  1821. });
  1822. }
  1823. }
  1824. }
  1825. if (marks) {
  1826. var node = _objectSpread({
  1827. text
  1828. }, marks);
  1829. Transforms.insertNodes(editor, node);
  1830. } else {
  1831. Transforms.insertText(editor, text);
  1832. }
  1833. editor.marks = null;
  1834. }
  1835. },
  1836. normalizeNode: entry => {
  1837. var [node, path] = entry; // There are no core normalizations for text nodes.
  1838. if (Text.isText(node)) {
  1839. return;
  1840. } // Ensure that block and inline nodes have at least one text child.
  1841. if (Element.isElement(node) && node.children.length === 0) {
  1842. var child = {
  1843. text: ''
  1844. };
  1845. Transforms.insertNodes(editor, child, {
  1846. at: path.concat(0),
  1847. voids: true
  1848. });
  1849. return;
  1850. } // Determine whether the node should have block or inline children.
  1851. var shouldHaveInlines = Editor.isEditor(node) ? false : Element.isElement(node) && (editor.isInline(node) || node.children.length === 0 || Text.isText(node.children[0]) || editor.isInline(node.children[0])); // Since we'll be applying operations while iterating, keep track of an
  1852. // index that accounts for any added/removed nodes.
  1853. var n = 0;
  1854. for (var i = 0; i < node.children.length; i++, n++) {
  1855. var _child = node.children[i];
  1856. var prev = node.children[i - 1];
  1857. var isLast = i === node.children.length - 1;
  1858. var isInlineOrText = Text.isText(_child) || Element.isElement(_child) && editor.isInline(_child); // Only allow block nodes in the top-level children and parent blocks
  1859. // that only contain block nodes. Similarly, only allow inline nodes in
  1860. // other inline nodes, or parent blocks that only contain inlines and
  1861. // text.
  1862. if (isInlineOrText !== shouldHaveInlines) {
  1863. Transforms.removeNodes(editor, {
  1864. at: path.concat(n),
  1865. voids: true
  1866. });
  1867. n--;
  1868. } else if (Element.isElement(_child)) {
  1869. // Ensure that inline nodes are surrounded by text nodes.
  1870. if (editor.isInline(_child)) {
  1871. if (prev == null || !Text.isText(prev)) {
  1872. var newChild = {
  1873. text: ''
  1874. };
  1875. Transforms.insertNodes(editor, newChild, {
  1876. at: path.concat(n),
  1877. voids: true
  1878. });
  1879. n++;
  1880. } else if (isLast) {
  1881. var _newChild = {
  1882. text: ''
  1883. };
  1884. Transforms.insertNodes(editor, _newChild, {
  1885. at: path.concat(n + 1),
  1886. voids: true
  1887. });
  1888. n++;
  1889. }
  1890. }
  1891. } else {
  1892. // Merge adjacent text nodes that are empty or match.
  1893. if (prev != null && Text.isText(prev)) {
  1894. if (Text.equals(_child, prev, {
  1895. loose: true
  1896. })) {
  1897. Transforms.mergeNodes(editor, {
  1898. at: path.concat(n),
  1899. voids: true
  1900. });
  1901. n--;
  1902. } else if (prev.text === '') {
  1903. Transforms.removeNodes(editor, {
  1904. at: path.concat(n - 1),
  1905. voids: true
  1906. });
  1907. n--;
  1908. } else if (isLast && _child.text === '') {
  1909. Transforms.removeNodes(editor, {
  1910. at: path.concat(n),
  1911. voids: true
  1912. });
  1913. n--;
  1914. }
  1915. }
  1916. }
  1917. }
  1918. },
  1919. removeMark: key => {
  1920. var {
  1921. selection
  1922. } = editor;
  1923. if (selection) {
  1924. if (Range.isExpanded(selection)) {
  1925. Transforms.unsetNodes(editor, key, {
  1926. match: Text.isText,
  1927. split: true
  1928. });
  1929. } else {
  1930. var marks = _objectSpread({}, Editor.marks(editor) || {});
  1931. delete marks[key];
  1932. editor.marks = marks;
  1933. editor.onChange();
  1934. }
  1935. }
  1936. }
  1937. };
  1938. return editor;
  1939. };
  1940. /**
  1941. * Get the "dirty" paths generated from an operation.
  1942. */
  1943. var getDirtyPaths = op => {
  1944. switch (op.type) {
  1945. case 'insert_text':
  1946. case 'remove_text':
  1947. case 'set_node':
  1948. {
  1949. var {
  1950. path
  1951. } = op;
  1952. return Path.levels(path);
  1953. }
  1954. case 'insert_node':
  1955. {
  1956. var {
  1957. node,
  1958. path: _path2
  1959. } = op;
  1960. var levels = Path.levels(_path2);
  1961. var descendants = Text.isText(node) ? [] : Array.from(Node.nodes(node), (_ref3) => {
  1962. var [, p] = _ref3;
  1963. return _path2.concat(p);
  1964. });
  1965. return [...levels, ...descendants];
  1966. }
  1967. case 'merge_node':
  1968. {
  1969. var {
  1970. path: _path3
  1971. } = op;
  1972. var ancestors = Path.ancestors(_path3);
  1973. var previousPath = Path.previous(_path3);
  1974. return [...ancestors, previousPath];
  1975. }
  1976. case 'move_node':
  1977. {
  1978. var {
  1979. path: _path4,
  1980. newPath
  1981. } = op;
  1982. if (Path.equals(_path4, newPath)) {
  1983. return [];
  1984. }
  1985. var oldAncestors = [];
  1986. var newAncestors = [];
  1987. for (var ancestor of Path.ancestors(_path4)) {
  1988. var p = Path.transform(ancestor, op);
  1989. oldAncestors.push(p);
  1990. }
  1991. for (var _ancestor of Path.ancestors(newPath)) {
  1992. var _p = Path.transform(_ancestor, op);
  1993. newAncestors.push(_p);
  1994. }
  1995. return [...oldAncestors, ...newAncestors];
  1996. }
  1997. case 'remove_node':
  1998. {
  1999. var {
  2000. path: _path5
  2001. } = op;
  2002. var _ancestors = Path.ancestors(_path5);
  2003. return [..._ancestors];
  2004. }
  2005. case 'split_node':
  2006. {
  2007. var {
  2008. path: _path6
  2009. } = op;
  2010. var _levels = Path.levels(_path6);
  2011. var nextPath = Path.next(_path6);
  2012. return [..._levels, nextPath];
  2013. }
  2014. default:
  2015. {
  2016. return [];
  2017. }
  2018. }
  2019. };
  2020. function _objectWithoutPropertiesLoose(source, excluded) {
  2021. if (source == null) return {};
  2022. var target = {};
  2023. var sourceKeys = Object.keys(source);
  2024. var key, i;
  2025. for (i = 0; i < sourceKeys.length; i++) {
  2026. key = sourceKeys[i];
  2027. if (excluded.indexOf(key) >= 0) continue;
  2028. target[key] = source[key];
  2029. }
  2030. return target;
  2031. }
  2032. function _objectWithoutProperties(source, excluded) {
  2033. if (source == null) return {};
  2034. var target = _objectWithoutPropertiesLoose(source, excluded);
  2035. var key, i;
  2036. if (Object.getOwnPropertySymbols) {
  2037. var sourceSymbolKeys = Object.getOwnPropertySymbols(source);
  2038. for (i = 0; i < sourceSymbolKeys.length; i++) {
  2039. key = sourceSymbolKeys[i];
  2040. if (excluded.indexOf(key) >= 0) continue;
  2041. if (!Object.prototype.propertyIsEnumerable.call(source, key)) continue;
  2042. target[key] = source[key];
  2043. }
  2044. }
  2045. return target;
  2046. }
  2047. /**
  2048. * Constants for string distance checking.
  2049. */
  2050. var SPACE = /\s/;
  2051. var PUNCTUATION = /[\u0021-\u0023\u0025-\u002A\u002C-\u002F\u003A\u003B\u003F\u0040\u005B-\u005D\u005F\u007B\u007D\u00A1\u00A7\u00AB\u00B6\u00B7\u00BB\u00BF\u037E\u0387\u055A-\u055F\u0589\u058A\u05BE\u05C0\u05C3\u05C6\u05F3\u05F4\u0609\u060A\u060C\u060D\u061B\u061E\u061F\u066A-\u066D\u06D4\u0700-\u070D\u07F7-\u07F9\u0830-\u083E\u085E\u0964\u0965\u0970\u0AF0\u0DF4\u0E4F\u0E5A\u0E5B\u0F04-\u0F12\u0F14\u0F3A-\u0F3D\u0F85\u0FD0-\u0FD4\u0FD9\u0FDA\u104A-\u104F\u10FB\u1360-\u1368\u1400\u166D\u166E\u169B\u169C\u16EB-\u16ED\u1735\u1736\u17D4-\u17D6\u17D8-\u17DA\u1800-\u180A\u1944\u1945\u1A1E\u1A1F\u1AA0-\u1AA6\u1AA8-\u1AAD\u1B5A-\u1B60\u1BFC-\u1BFF\u1C3B-\u1C3F\u1C7E\u1C7F\u1CC0-\u1CC7\u1CD3\u2010-\u2027\u2030-\u2043\u2045-\u2051\u2053-\u205E\u207D\u207E\u208D\u208E\u2329\u232A\u2768-\u2775\u27C5\u27C6\u27E6-\u27EF\u2983-\u2998\u29D8-\u29DB\u29FC\u29FD\u2CF9-\u2CFC\u2CFE\u2CFF\u2D70\u2E00-\u2E2E\u2E30-\u2E3B\u3001-\u3003\u3008-\u3011\u3014-\u301F\u3030\u303D\u30A0\u30FB\uA4FE\uA4FF\uA60D-\uA60F\uA673\uA67E\uA6F2-\uA6F7\uA874-\uA877\uA8CE\uA8CF\uA8F8-\uA8FA\uA92E\uA92F\uA95F\uA9C1-\uA9CD\uA9DE\uA9DF\uAA5C-\uAA5F\uAADE\uAADF\uAAF0\uAAF1\uABEB\uFD3E\uFD3F\uFE10-\uFE19\uFE30-\uFE52\uFE54-\uFE61\uFE63\uFE68\uFE6A\uFE6B\uFF01-\uFF03\uFF05-\uFF0A\uFF0C-\uFF0F\uFF1A\uFF1B\uFF1F\uFF20\uFF3B-\uFF3D\uFF3F\uFF5B\uFF5D\uFF5F-\uFF65]/;
  2052. var CHAMELEON = /['\u2018\u2019]/;
  2053. var SURROGATE_START = 0xd800;
  2054. var SURROGATE_END = 0xdfff;
  2055. var ZERO_WIDTH_JOINER = 0x200d;
  2056. /**
  2057. * Get the distance to the end of the first character in a string of text.
  2058. */
  2059. var getCharacterDistance = text => {
  2060. var offset = 0; // prev types:
  2061. // SURR: surrogate pair
  2062. // MOD: modifier (technically also surrogate pair)
  2063. // ZWJ: zero width joiner
  2064. // VAR: variation selector
  2065. // BMP: sequenceable character from basic multilingual plane
  2066. var prev = null;
  2067. var charCode = text.charCodeAt(0);
  2068. while (charCode) {
  2069. if (isSurrogate(charCode)) {
  2070. var modifier = isModifier(charCode, text, offset); // Early returns are the heart of this function, where we decide if previous and current
  2071. // codepoints should form a single character (in terms of how many of them should selection
  2072. // jump over).
  2073. if (prev === 'SURR' || prev === 'BMP') {
  2074. break;
  2075. }
  2076. offset += 2;
  2077. prev = modifier ? 'MOD' : 'SURR';
  2078. charCode = text.charCodeAt(offset); // Absolutely fine to `continue` without any checks because if `charCode` is NaN (which
  2079. // is the case when out of `text` range), next `while` loop won"t execute and we"re done.
  2080. continue;
  2081. }
  2082. if (charCode === ZERO_WIDTH_JOINER) {
  2083. offset += 1;
  2084. prev = 'ZWJ';
  2085. charCode = text.charCodeAt(offset);
  2086. continue;
  2087. }
  2088. if (isBMPEmoji(charCode)) {
  2089. if (prev && prev !== 'ZWJ' && prev !== 'VAR') {
  2090. break;
  2091. }
  2092. offset += 1;
  2093. prev = 'BMP';
  2094. charCode = text.charCodeAt(offset);
  2095. continue;
  2096. }
  2097. if (isVariationSelector(charCode)) {
  2098. if (prev && prev !== 'ZWJ') {
  2099. break;
  2100. }
  2101. offset += 1;
  2102. prev = 'VAR';
  2103. charCode = text.charCodeAt(offset);
  2104. continue;
  2105. } // Modifier 'groups up' with what ever character is before that (even whitespace), need to
  2106. // look ahead.
  2107. if (prev === 'MOD') {
  2108. offset += 1;
  2109. break;
  2110. } // If while loop ever gets here, we're done (e.g latin chars).
  2111. break;
  2112. }
  2113. return offset || 1;
  2114. };
  2115. /**
  2116. * Get the distance to the end of the first word in a string of text.
  2117. */
  2118. var getWordDistance = text => {
  2119. var length = 0;
  2120. var i = 0;
  2121. var started = false;
  2122. var char;
  2123. while (char = text.charAt(i)) {
  2124. var l = getCharacterDistance(char);
  2125. char = text.slice(i, i + l);
  2126. var rest = text.slice(i + l);
  2127. if (isWordCharacter(char, rest)) {
  2128. started = true;
  2129. length += l;
  2130. } else if (!started) {
  2131. length += l;
  2132. } else {
  2133. break;
  2134. }
  2135. i += l;
  2136. }
  2137. return length;
  2138. };
  2139. /**
  2140. * Check if a character is a word character. The `remaining` argument is used
  2141. * because sometimes you must read subsequent characters to truly determine it.
  2142. */
  2143. var isWordCharacter = (char, remaining) => {
  2144. if (SPACE.test(char)) {
  2145. return false;
  2146. } // Chameleons count as word characters as long as they're in a word, so
  2147. // recurse to see if the next one is a word character or not.
  2148. if (CHAMELEON.test(char)) {
  2149. var next = remaining.charAt(0);
  2150. var length = getCharacterDistance(next);
  2151. next = remaining.slice(0, length);
  2152. var rest = remaining.slice(length);
  2153. if (isWordCharacter(next, rest)) {
  2154. return true;
  2155. }
  2156. }
  2157. if (PUNCTUATION.test(char)) {
  2158. return false;
  2159. }
  2160. return true;
  2161. };
  2162. /**
  2163. * Determines if `code` is a surrogate
  2164. */
  2165. var isSurrogate = code => SURROGATE_START <= code && code <= SURROGATE_END;
  2166. /**
  2167. * Does `code` form Modifier with next one.
  2168. *
  2169. * https://emojipedia.org/modifiers/
  2170. */
  2171. var isModifier = (code, text, offset) => {
  2172. if (code === 0xd83c) {
  2173. var next = text.charCodeAt(offset + 1);
  2174. return next <= 0xdfff && next >= 0xdffb;
  2175. }
  2176. return false;
  2177. };
  2178. /**
  2179. * Is `code` a Variation Selector.
  2180. *
  2181. * https://codepoints.net/variation_selectors
  2182. */
  2183. var isVariationSelector = code => {
  2184. return code <= 0xfe0f && code >= 0xfe00;
  2185. };
  2186. /**
  2187. * Is `code` one of the BMP codes used in emoji sequences.
  2188. *
  2189. * https://emojipedia.org/emoji-zwj-sequences/
  2190. */
  2191. var isBMPEmoji = code => {
  2192. // This requires tiny bit of maintanance, better ideas?
  2193. // Fortunately it only happens if new Unicode Standard
  2194. // is released. Fails gracefully if upkeep lags behind,
  2195. // same way Slate previously behaved with all emojis.
  2196. return code === 0x2764 || // heart (❤)
  2197. code === 0x2642 || // male (♂)
  2198. code === 0x2640 || // female (♀)
  2199. code === 0x2620 || // scull (☠)
  2200. code === 0x2695 || // medical (⚕)
  2201. code === 0x2708 || // plane (✈️)
  2202. code === 0x25ef // large circle (◯)
  2203. ;
  2204. };
  2205. function ownKeys$1(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); keys.push.apply(keys, symbols); } return keys; }
  2206. function _objectSpread$1(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys$1(Object(source), true).forEach(function (key) { _defineProperty(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys$1(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; }
  2207. var Editor = {
  2208. /**
  2209. * Get the ancestor above a location in the document.
  2210. */
  2211. above(editor) {
  2212. var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
  2213. var {
  2214. voids = false,
  2215. mode = 'lowest',
  2216. at = editor.selection,
  2217. match
  2218. } = options;
  2219. if (!at) {
  2220. return;
  2221. }
  2222. var path = Editor.path(editor, at);
  2223. var reverse = mode === 'lowest';
  2224. for (var [n, p] of Editor.levels(editor, {
  2225. at: path,
  2226. voids,
  2227. match,
  2228. reverse
  2229. })) {
  2230. if (!Text.isText(n) && !Path.equals(path, p)) {
  2231. return [n, p];
  2232. }
  2233. }
  2234. },
  2235. /**
  2236. * Add a custom property to the leaf text nodes in the current selection.
  2237. *
  2238. * If the selection is currently collapsed, the marks will be added to the
  2239. * `editor.marks` property instead, and applied when text is inserted next.
  2240. */
  2241. addMark(editor, key, value) {
  2242. editor.addMark(key, value);
  2243. },
  2244. /**
  2245. * Get the point after a location.
  2246. */
  2247. after(editor, at) {
  2248. var options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
  2249. var anchor = Editor.point(editor, at, {
  2250. edge: 'end'
  2251. });
  2252. var focus = Editor.end(editor, []);
  2253. var range = {
  2254. anchor,
  2255. focus
  2256. };
  2257. var {
  2258. distance = 1
  2259. } = options;
  2260. var d = 0;
  2261. var target;
  2262. for (var p of Editor.positions(editor, _objectSpread$1({}, options, {
  2263. at: range
  2264. }))) {
  2265. if (d > distance) {
  2266. break;
  2267. }
  2268. if (d !== 0) {
  2269. target = p;
  2270. }
  2271. d++;
  2272. }
  2273. return target;
  2274. },
  2275. /**
  2276. * Get the point before a location.
  2277. */
  2278. before(editor, at) {
  2279. var options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
  2280. var anchor = Editor.start(editor, []);
  2281. var focus = Editor.point(editor, at, {
  2282. edge: 'start'
  2283. });
  2284. var range = {
  2285. anchor,
  2286. focus
  2287. };
  2288. var {
  2289. distance = 1
  2290. } = options;
  2291. var d = 0;
  2292. var target;
  2293. for (var p of Editor.positions(editor, _objectSpread$1({}, options, {
  2294. at: range,
  2295. reverse: true
  2296. }))) {
  2297. if (d > distance) {
  2298. break;
  2299. }
  2300. if (d !== 0) {
  2301. target = p;
  2302. }
  2303. d++;
  2304. }
  2305. return target;
  2306. },
  2307. /**
  2308. * Delete content in the editor backward from the current selection.
  2309. */
  2310. deleteBackward(editor) {
  2311. var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
  2312. var {
  2313. unit = 'character'
  2314. } = options;
  2315. editor.deleteBackward(unit);
  2316. },
  2317. /**
  2318. * Delete content in the editor forward from the current selection.
  2319. */
  2320. deleteForward(editor) {
  2321. var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
  2322. var {
  2323. unit = 'character'
  2324. } = options;
  2325. editor.deleteForward(unit);
  2326. },
  2327. /**
  2328. * Delete the content in the current selection.
  2329. */
  2330. deleteFragment(editor) {
  2331. editor.deleteFragment();
  2332. },
  2333. /**
  2334. * Get the start and end points of a location.
  2335. */
  2336. edges(editor, at) {
  2337. return [Editor.start(editor, at), Editor.end(editor, at)];
  2338. },
  2339. /**
  2340. * Get the end point of a location.
  2341. */
  2342. end(editor, at) {
  2343. return Editor.point(editor, at, {
  2344. edge: 'end'
  2345. });
  2346. },
  2347. /**
  2348. * Get the first node at a location.
  2349. */
  2350. first(editor, at) {
  2351. var path = Editor.path(editor, at, {
  2352. edge: 'start'
  2353. });
  2354. return Editor.node(editor, path);
  2355. },
  2356. /**
  2357. * Get the fragment at a location.
  2358. */
  2359. fragment(editor, at) {
  2360. var range = Editor.range(editor, at);
  2361. var fragment = Node.fragment(editor, range);
  2362. return fragment;
  2363. },
  2364. /**
  2365. * Check if a node has block children.
  2366. */
  2367. hasBlocks(editor, element) {
  2368. return element.children.some(n => Editor.isBlock(editor, n));
  2369. },
  2370. /**
  2371. * Check if a node has inline and text children.
  2372. */
  2373. hasInlines(editor, element) {
  2374. return element.children.some(n => Text.isText(n) || Editor.isInline(editor, n));
  2375. },
  2376. /**
  2377. * Check if a node has text children.
  2378. */
  2379. hasTexts(editor, element) {
  2380. return element.children.every(n => Text.isText(n));
  2381. },
  2382. /**
  2383. * Insert a block break at the current selection.
  2384. *
  2385. * If the selection is currently expanded, it will be deleted first.
  2386. */
  2387. insertBreak(editor) {
  2388. editor.insertBreak();
  2389. },
  2390. /**
  2391. * Insert a fragment at the current selection.
  2392. *
  2393. * If the selection is currently expanded, it will be deleted first.
  2394. */
  2395. insertFragment(editor, fragment) {
  2396. editor.insertFragment(fragment);
  2397. },
  2398. /**
  2399. * Insert a node at the current selection.
  2400. *
  2401. * If the selection is currently expanded, it will be deleted first.
  2402. */
  2403. insertNode(editor, node) {
  2404. editor.insertNode(node);
  2405. },
  2406. /**
  2407. * Insert text at the current selection.
  2408. *
  2409. * If the selection is currently expanded, it will be deleted first.
  2410. */
  2411. insertText(editor, text) {
  2412. editor.insertText(text);
  2413. },
  2414. /**
  2415. * Check if a value is a block `Element` object.
  2416. */
  2417. isBlock(editor, value) {
  2418. return Element.isElement(value) && !editor.isInline(value);
  2419. },
  2420. /**
  2421. * Check if a value is an `Editor` object.
  2422. */
  2423. isEditor(value) {
  2424. return isPlainObject(value) && typeof value.addMark === 'function' && typeof value.apply === 'function' && typeof value.deleteBackward === 'function' && typeof value.deleteForward === 'function' && typeof value.deleteFragment === 'function' && typeof value.insertBreak === 'function' && typeof value.insertFragment === 'function' && typeof value.insertNode === 'function' && typeof value.insertText === 'function' && typeof value.isInline === 'function' && typeof value.isVoid === 'function' && typeof value.normalizeNode === 'function' && typeof value.onChange === 'function' && typeof value.removeMark === 'function' && (value.marks === null || isPlainObject(value.marks)) && (value.selection === null || Range.isRange(value.selection)) && Node.isNodeList(value.children) && Operation.isOperationList(value.operations);
  2425. },
  2426. /**
  2427. * Check if a point is the end point of a location.
  2428. */
  2429. isEnd(editor, point, at) {
  2430. var end = Editor.end(editor, at);
  2431. return Point.equals(point, end);
  2432. },
  2433. /**
  2434. * Check if a point is an edge of a location.
  2435. */
  2436. isEdge(editor, point, at) {
  2437. return Editor.isStart(editor, point, at) || Editor.isEnd(editor, point, at);
  2438. },
  2439. /**
  2440. * Check if an element is empty, accounting for void nodes.
  2441. */
  2442. isEmpty(editor, element) {
  2443. var {
  2444. children
  2445. } = element;
  2446. var [first] = children;
  2447. return children.length === 0 || children.length === 1 && Text.isText(first) && first.text === '' && !editor.isVoid(element);
  2448. },
  2449. /**
  2450. * Check if a value is an inline `Element` object.
  2451. */
  2452. isInline(editor, value) {
  2453. return Element.isElement(value) && editor.isInline(value);
  2454. },
  2455. /**
  2456. * Check if the editor is currently normalizing after each operation.
  2457. */
  2458. isNormalizing(editor) {
  2459. var isNormalizing = NORMALIZING.get(editor);
  2460. return isNormalizing === undefined ? true : isNormalizing;
  2461. },
  2462. /**
  2463. * Check if a point is the start point of a location.
  2464. */
  2465. isStart(editor, point, at) {
  2466. // PERF: If the offset isn't `0` we know it's not the start.
  2467. if (point.offset !== 0) {
  2468. return false;
  2469. }
  2470. var start = Editor.start(editor, at);
  2471. return Point.equals(point, start);
  2472. },
  2473. /**
  2474. * Check if a value is a void `Element` object.
  2475. */
  2476. isVoid(editor, value) {
  2477. return Element.isElement(value) && editor.isVoid(value);
  2478. },
  2479. /**
  2480. * Get the last node at a location.
  2481. */
  2482. last(editor, at) {
  2483. var path = Editor.path(editor, at, {
  2484. edge: 'end'
  2485. });
  2486. return Editor.node(editor, path);
  2487. },
  2488. /**
  2489. * Get the leaf text node at a location.
  2490. */
  2491. leaf(editor, at) {
  2492. var options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
  2493. var path = Editor.path(editor, at, options);
  2494. var node = Node.leaf(editor, path);
  2495. return [node, path];
  2496. },
  2497. /**
  2498. * Iterate through all of the levels at a location.
  2499. */
  2500. *levels(editor) {
  2501. var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
  2502. var {
  2503. at = editor.selection,
  2504. reverse = false,
  2505. voids = false
  2506. } = options;
  2507. var {
  2508. match
  2509. } = options;
  2510. if (match == null) {
  2511. match = () => true;
  2512. }
  2513. if (!at) {
  2514. return;
  2515. }
  2516. var levels = [];
  2517. var path = Editor.path(editor, at);
  2518. for (var [n, p] of Node.levels(editor, path)) {
  2519. if (!match(n)) {
  2520. continue;
  2521. }
  2522. levels.push([n, p]);
  2523. if (!voids && Editor.isVoid(editor, n)) {
  2524. break;
  2525. }
  2526. }
  2527. if (reverse) {
  2528. levels.reverse();
  2529. }
  2530. yield* levels;
  2531. },
  2532. /**
  2533. * Get the marks that would be added to text at the current selection.
  2534. */
  2535. marks(editor) {
  2536. var {
  2537. marks,
  2538. selection
  2539. } = editor;
  2540. if (!selection) {
  2541. return null;
  2542. }
  2543. if (marks) {
  2544. return marks;
  2545. }
  2546. if (Range.isExpanded(selection)) {
  2547. var [match] = Editor.nodes(editor, {
  2548. match: Text.isText
  2549. });
  2550. if (match) {
  2551. var [_node] = match;
  2552. var _rest = _objectWithoutProperties(_node, ["text"]);
  2553. return _rest;
  2554. } else {
  2555. return {};
  2556. }
  2557. }
  2558. var {
  2559. anchor
  2560. } = selection;
  2561. var {
  2562. path
  2563. } = anchor;
  2564. var [node] = Editor.leaf(editor, path);
  2565. if (anchor.offset === 0) {
  2566. var prev = Editor.previous(editor, {
  2567. at: path,
  2568. match: Text.isText
  2569. });
  2570. var block = Editor.above(editor, {
  2571. match: n => Editor.isBlock(editor, n)
  2572. });
  2573. if (prev && block) {
  2574. var [prevNode, prevPath] = prev;
  2575. var [, blockPath] = block;
  2576. if (Path.isAncestor(blockPath, prevPath)) {
  2577. node = prevNode;
  2578. }
  2579. }
  2580. }
  2581. var rest = _objectWithoutProperties(node, ["text"]);
  2582. return rest;
  2583. },
  2584. /**
  2585. * Get the matching node in the branch of the document after a location.
  2586. */
  2587. next(editor) {
  2588. var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
  2589. var {
  2590. mode = 'lowest',
  2591. voids = false
  2592. } = options;
  2593. var {
  2594. match,
  2595. at = editor.selection
  2596. } = options;
  2597. if (!at) {
  2598. return;
  2599. }
  2600. var [, from] = Editor.last(editor, at);
  2601. var [, to] = Editor.last(editor, []);
  2602. var span = [from, to];
  2603. if (Path.isPath(at) && at.length === 0) {
  2604. throw new Error("Cannot get the next node from the root node!");
  2605. }
  2606. if (match == null) {
  2607. if (Path.isPath(at)) {
  2608. var [parent] = Editor.parent(editor, at);
  2609. match = n => parent.children.includes(n);
  2610. } else {
  2611. match = () => true;
  2612. }
  2613. }
  2614. var [, next] = Editor.nodes(editor, {
  2615. at: span,
  2616. match,
  2617. mode,
  2618. voids
  2619. });
  2620. return next;
  2621. },
  2622. /**
  2623. * Get the node at a location.
  2624. */
  2625. node(editor, at) {
  2626. var options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
  2627. var path = Editor.path(editor, at, options);
  2628. var node = Node.get(editor, path);
  2629. return [node, path];
  2630. },
  2631. /**
  2632. * Iterate through all of the nodes in the Editor.
  2633. */
  2634. *nodes(editor) {
  2635. var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
  2636. var {
  2637. at = editor.selection,
  2638. mode = 'all',
  2639. universal = false,
  2640. reverse = false,
  2641. voids = false
  2642. } = options;
  2643. var {
  2644. match
  2645. } = options;
  2646. if (!match) {
  2647. match = () => true;
  2648. }
  2649. if (!at) {
  2650. return;
  2651. }
  2652. var from;
  2653. var to;
  2654. if (Span.isSpan(at)) {
  2655. from = at[0];
  2656. to = at[1];
  2657. } else {
  2658. var first = Editor.path(editor, at, {
  2659. edge: 'start'
  2660. });
  2661. var last = Editor.path(editor, at, {
  2662. edge: 'end'
  2663. });
  2664. from = reverse ? last : first;
  2665. to = reverse ? first : last;
  2666. }
  2667. var iterable = Node.nodes(editor, {
  2668. reverse,
  2669. from,
  2670. to,
  2671. pass: (_ref) => {
  2672. var [n] = _ref;
  2673. return voids ? false : Editor.isVoid(editor, n);
  2674. }
  2675. });
  2676. var matches = [];
  2677. var hit;
  2678. for (var [node, path] of iterable) {
  2679. var isLower = hit && Path.compare(path, hit[1]) === 0; // In highest mode any node lower than the last hit is not a match.
  2680. if (mode === 'highest' && isLower) {
  2681. continue;
  2682. }
  2683. if (!match(node)) {
  2684. // If we've arrived at a leaf text node that is not lower than the last
  2685. // hit, then we've found a branch that doesn't include a match, which
  2686. // means the match is not universal.
  2687. if (universal && !isLower && Text.isText(node)) {
  2688. return;
  2689. } else {
  2690. continue;
  2691. }
  2692. } // If there's a match and it's lower than the last, update the hit.
  2693. if (mode === 'lowest' && isLower) {
  2694. hit = [node, path];
  2695. continue;
  2696. } // In lowest mode we emit the last hit, once it's guaranteed lowest.
  2697. var emit = mode === 'lowest' ? hit : [node, path];
  2698. if (emit) {
  2699. if (universal) {
  2700. matches.push(emit);
  2701. } else {
  2702. yield emit;
  2703. }
  2704. }
  2705. hit = [node, path];
  2706. } // Since lowest is always emitting one behind, catch up at the end.
  2707. if (mode === 'lowest' && hit) {
  2708. if (universal) {
  2709. matches.push(hit);
  2710. } else {
  2711. yield hit;
  2712. }
  2713. } // Universal defers to ensure that the match occurs in every branch, so we
  2714. // yield all of the matches after iterating.
  2715. if (universal) {
  2716. yield* matches;
  2717. }
  2718. },
  2719. /**
  2720. * Normalize any dirty objects in the editor.
  2721. */
  2722. normalize(editor) {
  2723. var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
  2724. var {
  2725. force = false
  2726. } = options;
  2727. var getDirtyPaths = editor => {
  2728. return DIRTY_PATHS.get(editor) || [];
  2729. };
  2730. if (!Editor.isNormalizing(editor)) {
  2731. return;
  2732. }
  2733. if (force) {
  2734. var allPaths = Array.from(Node.nodes(editor), (_ref2) => {
  2735. var [, p] = _ref2;
  2736. return p;
  2737. });
  2738. DIRTY_PATHS.set(editor, allPaths);
  2739. }
  2740. if (getDirtyPaths(editor).length === 0) {
  2741. return;
  2742. }
  2743. Editor.withoutNormalizing(editor, () => {
  2744. var max = getDirtyPaths(editor).length * 42; // HACK: better way?
  2745. var m = 0;
  2746. while (getDirtyPaths(editor).length !== 0) {
  2747. if (m > max) {
  2748. throw new Error("\n Could not completely normalize the editor after ".concat(max, " iterations! This is usually due to incorrect normalization logic that leaves a node in an invalid state.\n "));
  2749. }
  2750. var path = getDirtyPaths(editor).pop();
  2751. var entry = Editor.node(editor, path);
  2752. editor.normalizeNode(entry);
  2753. m++;
  2754. }
  2755. });
  2756. },
  2757. /**
  2758. * Get the parent node of a location.
  2759. */
  2760. parent(editor, at) {
  2761. var options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
  2762. var path = Editor.path(editor, at, options);
  2763. var parentPath = Path.parent(path);
  2764. var entry = Editor.node(editor, parentPath);
  2765. return entry;
  2766. },
  2767. /**
  2768. * Get the path of a location.
  2769. */
  2770. path(editor, at) {
  2771. var options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
  2772. var {
  2773. depth,
  2774. edge
  2775. } = options;
  2776. if (Path.isPath(at)) {
  2777. if (edge === 'start') {
  2778. var [, firstPath] = Node.first(editor, at);
  2779. at = firstPath;
  2780. } else if (edge === 'end') {
  2781. var [, lastPath] = Node.last(editor, at);
  2782. at = lastPath;
  2783. }
  2784. }
  2785. if (Range.isRange(at)) {
  2786. if (edge === 'start') {
  2787. at = Range.start(at);
  2788. } else if (edge === 'end') {
  2789. at = Range.end(at);
  2790. } else {
  2791. at = Path.common(at.anchor.path, at.focus.path);
  2792. }
  2793. }
  2794. if (Point.isPoint(at)) {
  2795. at = at.path;
  2796. }
  2797. if (depth != null) {
  2798. at = at.slice(0, depth);
  2799. }
  2800. return at;
  2801. },
  2802. /**
  2803. * Create a mutable ref for a `Path` object, which will stay in sync as new
  2804. * operations are applied to the editor.
  2805. */
  2806. pathRef(editor, path) {
  2807. var options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
  2808. var {
  2809. affinity = 'forward'
  2810. } = options;
  2811. var ref = {
  2812. current: path,
  2813. affinity,
  2814. unref() {
  2815. var {
  2816. current
  2817. } = ref;
  2818. var pathRefs = Editor.pathRefs(editor);
  2819. pathRefs.delete(ref);
  2820. ref.current = null;
  2821. return current;
  2822. }
  2823. };
  2824. var refs = Editor.pathRefs(editor);
  2825. refs.add(ref);
  2826. return ref;
  2827. },
  2828. /**
  2829. * Get the set of currently tracked path refs of the editor.
  2830. */
  2831. pathRefs(editor) {
  2832. var refs = PATH_REFS.get(editor);
  2833. if (!refs) {
  2834. refs = new Set();
  2835. PATH_REFS.set(editor, refs);
  2836. }
  2837. return refs;
  2838. },
  2839. /**
  2840. * Get the start or end point of a location.
  2841. */
  2842. point(editor, at) {
  2843. var options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
  2844. var {
  2845. edge = 'start'
  2846. } = options;
  2847. if (Path.isPath(at)) {
  2848. var path;
  2849. if (edge === 'end') {
  2850. var [, lastPath] = Node.last(editor, at);
  2851. path = lastPath;
  2852. } else {
  2853. var [, firstPath] = Node.first(editor, at);
  2854. path = firstPath;
  2855. }
  2856. var node = Node.get(editor, path);
  2857. if (!Text.isText(node)) {
  2858. throw new Error("Cannot get the ".concat(edge, " point in the node at path [").concat(at, "] because it has no ").concat(edge, " text node."));
  2859. }
  2860. return {
  2861. path,
  2862. offset: edge === 'end' ? node.text.length : 0
  2863. };
  2864. }
  2865. if (Range.isRange(at)) {
  2866. var [start, end] = Range.edges(at);
  2867. return edge === 'start' ? start : end;
  2868. }
  2869. return at;
  2870. },
  2871. /**
  2872. * Create a mutable ref for a `Point` object, which will stay in sync as new
  2873. * operations are applied to the editor.
  2874. */
  2875. pointRef(editor, point) {
  2876. var options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
  2877. var {
  2878. affinity = 'forward'
  2879. } = options;
  2880. var ref = {
  2881. current: point,
  2882. affinity,
  2883. unref() {
  2884. var {
  2885. current
  2886. } = ref;
  2887. var pointRefs = Editor.pointRefs(editor);
  2888. pointRefs.delete(ref);
  2889. ref.current = null;
  2890. return current;
  2891. }
  2892. };
  2893. var refs = Editor.pointRefs(editor);
  2894. refs.add(ref);
  2895. return ref;
  2896. },
  2897. /**
  2898. * Get the set of currently tracked point refs of the editor.
  2899. */
  2900. pointRefs(editor) {
  2901. var refs = POINT_REFS.get(editor);
  2902. if (!refs) {
  2903. refs = new Set();
  2904. POINT_REFS.set(editor, refs);
  2905. }
  2906. return refs;
  2907. },
  2908. /**
  2909. * Iterate through all of the positions in the document where a `Point` can be
  2910. * placed.
  2911. *
  2912. * By default it will move forward by individual offsets at a time, but you
  2913. * can pass the `unit: 'character'` option to moved forward one character, word,
  2914. * or line at at time.
  2915. *
  2916. * Note: void nodes are treated as a single point, and iteration will not
  2917. * happen inside their content.
  2918. */
  2919. *positions(editor) {
  2920. var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
  2921. var {
  2922. at = editor.selection,
  2923. unit = 'offset',
  2924. reverse = false
  2925. } = options;
  2926. if (!at) {
  2927. return;
  2928. }
  2929. var range = Editor.range(editor, at);
  2930. var [start, end] = Range.edges(range);
  2931. var first = reverse ? end : start;
  2932. var string = '';
  2933. var available = 0;
  2934. var offset = 0;
  2935. var distance = null;
  2936. var isNewBlock = false;
  2937. var advance = () => {
  2938. if (distance == null) {
  2939. if (unit === 'character') {
  2940. distance = getCharacterDistance(string);
  2941. } else if (unit === 'word') {
  2942. distance = getWordDistance(string);
  2943. } else if (unit === 'line' || unit === 'block') {
  2944. distance = string.length;
  2945. } else {
  2946. distance = 1;
  2947. }
  2948. string = string.slice(distance);
  2949. } // Add or substract the offset.
  2950. offset = reverse ? offset - distance : offset + distance; // Subtract the distance traveled from the available text.
  2951. available = available - distance; // If the available had room to spare, reset the distance so that it will
  2952. // advance again next time. Otherwise, set it to the overflow amount.
  2953. distance = available >= 0 ? null : 0 - available;
  2954. };
  2955. for (var [node, path] of Editor.nodes(editor, {
  2956. at,
  2957. reverse
  2958. })) {
  2959. if (Element.isElement(node)) {
  2960. // Void nodes are a special case, since we don't want to iterate over
  2961. // their content. We instead always just yield their first point.
  2962. if (editor.isVoid(node)) {
  2963. yield Editor.start(editor, path);
  2964. continue;
  2965. }
  2966. if (editor.isInline(node)) {
  2967. continue;
  2968. }
  2969. if (Editor.hasInlines(editor, node)) {
  2970. var e = Path.isAncestor(path, end.path) ? end : Editor.end(editor, path);
  2971. var s = Path.isAncestor(path, start.path) ? start : Editor.start(editor, path);
  2972. var text = Editor.string(editor, {
  2973. anchor: s,
  2974. focus: e
  2975. });
  2976. string = reverse ? esrever.reverse(text) : text;
  2977. isNewBlock = true;
  2978. }
  2979. }
  2980. if (Text.isText(node)) {
  2981. var isFirst = Path.equals(path, first.path);
  2982. available = node.text.length;
  2983. offset = reverse ? available : 0;
  2984. if (isFirst) {
  2985. available = reverse ? first.offset : available - first.offset;
  2986. offset = first.offset;
  2987. }
  2988. if (isFirst || isNewBlock || unit === 'offset') {
  2989. yield {
  2990. path,
  2991. offset
  2992. };
  2993. }
  2994. while (true) {
  2995. // If there's no more string, continue to the next block.
  2996. if (string === '') {
  2997. break;
  2998. } else {
  2999. advance();
  3000. } // If the available space hasn't overflow, we have another point to
  3001. // yield in the current text node.
  3002. if (available >= 0) {
  3003. yield {
  3004. path,
  3005. offset
  3006. };
  3007. } else {
  3008. break;
  3009. }
  3010. }
  3011. isNewBlock = false;
  3012. }
  3013. }
  3014. },
  3015. /**
  3016. * Get the matching node in the branch of the document before a location.
  3017. */
  3018. previous(editor) {
  3019. var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
  3020. var {
  3021. mode = 'lowest',
  3022. voids = false
  3023. } = options;
  3024. var {
  3025. match,
  3026. at = editor.selection
  3027. } = options;
  3028. if (!at) {
  3029. return;
  3030. }
  3031. var [, from] = Editor.first(editor, at);
  3032. var [, to] = Editor.first(editor, []);
  3033. var span = [from, to];
  3034. if (Path.isPath(at) && at.length === 0) {
  3035. throw new Error("Cannot get the previous node from the root node!");
  3036. }
  3037. if (match == null) {
  3038. if (Path.isPath(at)) {
  3039. var [parent] = Editor.parent(editor, at);
  3040. match = n => parent.children.includes(n);
  3041. } else {
  3042. match = () => true;
  3043. }
  3044. }
  3045. var [, previous] = Editor.nodes(editor, {
  3046. reverse: true,
  3047. at: span,
  3048. match,
  3049. mode,
  3050. voids
  3051. });
  3052. return previous;
  3053. },
  3054. /**
  3055. * Get a range of a location.
  3056. */
  3057. range(editor, at, to) {
  3058. if (Range.isRange(at) && !to) {
  3059. return at;
  3060. }
  3061. var start = Editor.start(editor, at);
  3062. var end = Editor.end(editor, to || at);
  3063. return {
  3064. anchor: start,
  3065. focus: end
  3066. };
  3067. },
  3068. /**
  3069. * Create a mutable ref for a `Range` object, which will stay in sync as new
  3070. * operations are applied to the editor.
  3071. */
  3072. rangeRef(editor, range) {
  3073. var options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
  3074. var {
  3075. affinity = 'forward'
  3076. } = options;
  3077. var ref = {
  3078. current: range,
  3079. affinity,
  3080. unref() {
  3081. var {
  3082. current
  3083. } = ref;
  3084. var rangeRefs = Editor.rangeRefs(editor);
  3085. rangeRefs.delete(ref);
  3086. ref.current = null;
  3087. return current;
  3088. }
  3089. };
  3090. var refs = Editor.rangeRefs(editor);
  3091. refs.add(ref);
  3092. return ref;
  3093. },
  3094. /**
  3095. * Get the set of currently tracked range refs of the editor.
  3096. */
  3097. rangeRefs(editor) {
  3098. var refs = RANGE_REFS.get(editor);
  3099. if (!refs) {
  3100. refs = new Set();
  3101. RANGE_REFS.set(editor, refs);
  3102. }
  3103. return refs;
  3104. },
  3105. /**
  3106. * Remove a custom property from all of the leaf text nodes in the current
  3107. * selection.
  3108. *
  3109. * If the selection is currently collapsed, the removal will be stored on
  3110. * `editor.marks` and applied to the text inserted next.
  3111. */
  3112. removeMark(editor, key) {
  3113. editor.removeMark(key);
  3114. },
  3115. /**
  3116. * Get the start point of a location.
  3117. */
  3118. start(editor, at) {
  3119. return Editor.point(editor, at, {
  3120. edge: 'start'
  3121. });
  3122. },
  3123. /**
  3124. * Get the text string content of a location.
  3125. *
  3126. * Note: the text of void nodes is presumed to be an empty string, regardless
  3127. * of what their actual content is.
  3128. */
  3129. string(editor, at) {
  3130. var range = Editor.range(editor, at);
  3131. var [start, end] = Range.edges(range);
  3132. var text = '';
  3133. for (var [node, path] of Editor.nodes(editor, {
  3134. at: range,
  3135. match: Text.isText
  3136. })) {
  3137. var t = node.text;
  3138. if (Path.equals(path, end.path)) {
  3139. t = t.slice(0, end.offset);
  3140. }
  3141. if (Path.equals(path, start.path)) {
  3142. t = t.slice(start.offset);
  3143. }
  3144. text += t;
  3145. }
  3146. return text;
  3147. },
  3148. /**
  3149. * Transform the editor by an operation.
  3150. */
  3151. transform(editor, op) {
  3152. editor.children = immer_1.createDraft(editor.children);
  3153. var selection = editor.selection && immer_1.createDraft(editor.selection);
  3154. switch (op.type) {
  3155. case 'insert_node':
  3156. {
  3157. var {
  3158. path,
  3159. node
  3160. } = op;
  3161. var parent = Node.parent(editor, path);
  3162. var index = path[path.length - 1];
  3163. parent.children.splice(index, 0, node);
  3164. if (selection) {
  3165. for (var [point, key] of Range.points(selection)) {
  3166. selection[key] = Point.transform(point, op);
  3167. }
  3168. }
  3169. break;
  3170. }
  3171. case 'insert_text':
  3172. {
  3173. var {
  3174. path: _path,
  3175. offset,
  3176. text
  3177. } = op;
  3178. var _node2 = Node.leaf(editor, _path);
  3179. var before = _node2.text.slice(0, offset);
  3180. var after = _node2.text.slice(offset);
  3181. _node2.text = before + text + after;
  3182. if (selection) {
  3183. for (var [_point, _key] of Range.points(selection)) {
  3184. selection[_key] = Point.transform(_point, op);
  3185. }
  3186. }
  3187. break;
  3188. }
  3189. case 'merge_node':
  3190. {
  3191. var {
  3192. path: _path2
  3193. } = op;
  3194. var _node3 = Node.get(editor, _path2);
  3195. var prevPath = Path.previous(_path2);
  3196. var prev = Node.get(editor, prevPath);
  3197. var _parent = Node.parent(editor, _path2);
  3198. var _index = _path2[_path2.length - 1];
  3199. if (Text.isText(_node3) && Text.isText(prev)) {
  3200. prev.text += _node3.text;
  3201. } else if (!Text.isText(_node3) && !Text.isText(prev)) {
  3202. prev.children.push(..._node3.children);
  3203. } else {
  3204. throw new Error("Cannot apply a \"merge_node\" operation at path [".concat(_path2, "] to nodes of different interaces: ").concat(_node3, " ").concat(prev));
  3205. }
  3206. _parent.children.splice(_index, 1);
  3207. if (selection) {
  3208. for (var [_point2, _key2] of Range.points(selection)) {
  3209. selection[_key2] = Point.transform(_point2, op);
  3210. }
  3211. }
  3212. break;
  3213. }
  3214. case 'move_node':
  3215. {
  3216. var {
  3217. path: _path3,
  3218. newPath
  3219. } = op;
  3220. if (Path.isAncestor(_path3, newPath)) {
  3221. throw new Error("Cannot move a path [".concat(_path3, "] to new path [").concat(newPath, "] because the destination is inside itself."));
  3222. }
  3223. var _node4 = Node.get(editor, _path3);
  3224. var _parent2 = Node.parent(editor, _path3);
  3225. var _index2 = _path3[_path3.length - 1]; // This is tricky, but since the `path` and `newPath` both refer to
  3226. // the same snapshot in time, there's a mismatch. After either
  3227. // removing the original position, the second step's path can be out
  3228. // of date. So instead of using the `op.newPath` directly, we
  3229. // transform `op.path` to ascertain what the `newPath` would be after
  3230. // the operation was applied.
  3231. _parent2.children.splice(_index2, 1);
  3232. var truePath = Path.transform(_path3, op);
  3233. var newParent = Node.get(editor, Path.parent(truePath));
  3234. var newIndex = truePath[truePath.length - 1];
  3235. newParent.children.splice(newIndex, 0, _node4);
  3236. if (selection) {
  3237. for (var [_point3, _key3] of Range.points(selection)) {
  3238. selection[_key3] = Point.transform(_point3, op);
  3239. }
  3240. }
  3241. break;
  3242. }
  3243. case 'remove_node':
  3244. {
  3245. var {
  3246. path: _path4
  3247. } = op;
  3248. var _index3 = _path4[_path4.length - 1];
  3249. var _parent3 = Node.parent(editor, _path4);
  3250. _parent3.children.splice(_index3, 1); // Transform all of the points in the value, but if the point was in the
  3251. // node that was removed we need to update the range or remove it.
  3252. if (selection) {
  3253. for (var [_point4, _key4] of Range.points(selection)) {
  3254. var result = Point.transform(_point4, op);
  3255. if (selection != null && result != null) {
  3256. selection[_key4] = result;
  3257. } else {
  3258. var _prev = void 0;
  3259. var next = void 0;
  3260. for (var [n, p] of Node.texts(editor)) {
  3261. if (Path.compare(p, _path4) === -1) {
  3262. _prev = [n, p];
  3263. } else {
  3264. next = [n, p];
  3265. break;
  3266. }
  3267. }
  3268. if (_prev) {
  3269. _point4.path = _prev[1];
  3270. _point4.offset = _prev[0].text.length;
  3271. } else if (next) {
  3272. _point4.path = next[1];
  3273. _point4.offset = 0;
  3274. } else {
  3275. selection = null;
  3276. }
  3277. }
  3278. }
  3279. }
  3280. break;
  3281. }
  3282. case 'remove_text':
  3283. {
  3284. var {
  3285. path: _path5,
  3286. offset: _offset,
  3287. text: _text2
  3288. } = op;
  3289. var _node5 = Node.leaf(editor, _path5);
  3290. var _before = _node5.text.slice(0, _offset);
  3291. var _after = _node5.text.slice(_offset + _text2.length);
  3292. _node5.text = _before + _after;
  3293. if (selection) {
  3294. for (var [_point5, _key5] of Range.points(selection)) {
  3295. selection[_key5] = Point.transform(_point5, op);
  3296. }
  3297. }
  3298. break;
  3299. }
  3300. case 'set_node':
  3301. {
  3302. var {
  3303. path: _path6,
  3304. newProperties
  3305. } = op;
  3306. if (_path6.length === 0) {
  3307. throw new Error("Cannot set properties on the root node!");
  3308. }
  3309. var _node6 = Node.get(editor, _path6);
  3310. for (var _key6 in newProperties) {
  3311. if (_key6 === 'children' || _key6 === 'text') {
  3312. throw new Error("Cannot set the \"".concat(_key6, "\" property of nodes!"));
  3313. }
  3314. var value = newProperties[_key6];
  3315. if (value == null) {
  3316. delete _node6[_key6];
  3317. } else {
  3318. _node6[_key6] = value;
  3319. }
  3320. }
  3321. break;
  3322. }
  3323. case 'set_selection':
  3324. {
  3325. var {
  3326. newProperties: _newProperties
  3327. } = op;
  3328. if (_newProperties == null) {
  3329. selection = _newProperties;
  3330. } else if (selection == null) {
  3331. if (!Range.isRange(_newProperties)) {
  3332. throw new Error("Cannot apply an incomplete \"set_selection\" operation properties ".concat(JSON.stringify(_newProperties), " when there is no current selection."));
  3333. }
  3334. selection = _newProperties;
  3335. } else {
  3336. Object.assign(selection, _newProperties);
  3337. }
  3338. break;
  3339. }
  3340. case 'split_node':
  3341. {
  3342. var {
  3343. path: _path7,
  3344. position,
  3345. properties
  3346. } = op;
  3347. if (_path7.length === 0) {
  3348. throw new Error("Cannot apply a \"split_node\" operation at path [".concat(_path7, "] because the root node cannot be split."));
  3349. }
  3350. var _node7 = Node.get(editor, _path7);
  3351. var _parent4 = Node.parent(editor, _path7);
  3352. var _index4 = _path7[_path7.length - 1];
  3353. var newNode;
  3354. if (Text.isText(_node7)) {
  3355. var _before2 = _node7.text.slice(0, position);
  3356. var _after2 = _node7.text.slice(position);
  3357. _node7.text = _before2;
  3358. newNode = _objectSpread$1({}, _node7, {}, properties, {
  3359. text: _after2
  3360. });
  3361. } else {
  3362. var _before3 = _node7.children.slice(0, position);
  3363. var _after3 = _node7.children.slice(position);
  3364. _node7.children = _before3;
  3365. newNode = _objectSpread$1({}, _node7, {}, properties, {
  3366. children: _after3
  3367. });
  3368. }
  3369. _parent4.children.splice(_index4 + 1, 0, newNode);
  3370. if (selection) {
  3371. for (var [_point6, _key7] of Range.points(selection)) {
  3372. selection[_key7] = Point.transform(_point6, op);
  3373. }
  3374. }
  3375. break;
  3376. }
  3377. }
  3378. editor.children = immer_1.finishDraft(editor.children);
  3379. if (selection) {
  3380. editor.selection = immer_1.isDraft(selection) ? immer_1.finishDraft(selection) : selection;
  3381. } else {
  3382. editor.selection = null;
  3383. }
  3384. },
  3385. /**
  3386. * Convert a range into a non-hanging one.
  3387. */
  3388. unhangRange(editor, range) {
  3389. var options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
  3390. var {
  3391. voids = false
  3392. } = options;
  3393. var [start, end] = Range.edges(range); // PERF: exit early if we can guarantee that the range isn't hanging.
  3394. if (start.offset !== 0 || end.offset !== 0 || Range.isCollapsed(range)) {
  3395. return range;
  3396. }
  3397. var endBlock = Editor.above(editor, {
  3398. at: end,
  3399. match: n => Editor.isBlock(editor, n)
  3400. });
  3401. var blockPath = endBlock ? endBlock[1] : [];
  3402. var first = Editor.start(editor, []);
  3403. var before = {
  3404. anchor: first,
  3405. focus: end
  3406. };
  3407. var skip = true;
  3408. for (var [node, path] of Editor.nodes(editor, {
  3409. at: before,
  3410. match: Text.isText,
  3411. reverse: true,
  3412. voids
  3413. })) {
  3414. if (skip) {
  3415. skip = false;
  3416. continue;
  3417. }
  3418. if (node.text !== '' || Path.isBefore(path, blockPath)) {
  3419. end = {
  3420. path,
  3421. offset: node.text.length
  3422. };
  3423. break;
  3424. }
  3425. }
  3426. return {
  3427. anchor: start,
  3428. focus: end
  3429. };
  3430. },
  3431. /**
  3432. * Match a void node in the current branch of the editor.
  3433. */
  3434. void(editor) {
  3435. var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
  3436. return Editor.above(editor, _objectSpread$1({}, options, {
  3437. match: n => Editor.isVoid(editor, n)
  3438. }));
  3439. },
  3440. /**
  3441. * Call a function, deferring normalization until after it completes.
  3442. */
  3443. withoutNormalizing(editor, fn) {
  3444. var value = Editor.isNormalizing(editor);
  3445. NORMALIZING.set(editor, false);
  3446. fn();
  3447. NORMALIZING.set(editor, value);
  3448. Editor.normalize(editor);
  3449. }
  3450. };
  3451. var Element = {
  3452. /**
  3453. * Check if a value implements the `Element` interface.
  3454. */
  3455. isElement(value) {
  3456. return isPlainObject(value) && Node.isNodeList(value.children) && !Editor.isEditor(value);
  3457. },
  3458. /**
  3459. * Check if a value is an array of `Element` objects.
  3460. */
  3461. isElementList(value) {
  3462. return Array.isArray(value) && (value.length === 0 || Element.isElement(value[0]));
  3463. },
  3464. /**
  3465. * Check if an element matches set of properties.
  3466. *
  3467. * Note: this checks custom properties, and it does not ensure that any
  3468. * children are equivalent.
  3469. */
  3470. matches(element, props) {
  3471. for (var key in props) {
  3472. if (key === 'children') {
  3473. continue;
  3474. }
  3475. if (element[key] !== props[key]) {
  3476. return false;
  3477. }
  3478. }
  3479. return true;
  3480. }
  3481. };
  3482. var Location = {
  3483. /**
  3484. * Check if a value implements the `Location` interface.
  3485. */
  3486. isLocation(value) {
  3487. return Path.isPath(value) || Point.isPoint(value) || Range.isRange(value);
  3488. }
  3489. };
  3490. var Span = {
  3491. /**
  3492. * Check if a value implements the `Span` interface.
  3493. */
  3494. isSpan(value) {
  3495. return Array.isArray(value) && value.length === 2 && value.every(Path.isPath);
  3496. }
  3497. };
  3498. var Node = {
  3499. /**
  3500. * Get the node at a specific path, asserting that it's an ancestor node.
  3501. */
  3502. ancestor(root, path) {
  3503. var node = Node.get(root, path);
  3504. if (Text.isText(node)) {
  3505. throw new Error("Cannot get the ancestor node at path [".concat(path, "] because it refers to a text node instead: ").concat(node));
  3506. }
  3507. return node;
  3508. },
  3509. /**
  3510. * Return an iterable of all the ancestor nodes above a specific path.
  3511. *
  3512. * By default the order is bottom-up, from lowest to highest ancestor in
  3513. * the tree, but you can pass the `reverse: true` option to go top-down.
  3514. */
  3515. *ancestors(root, path) {
  3516. var options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
  3517. for (var p of Path.ancestors(path, options)) {
  3518. var n = Node.ancestor(root, p);
  3519. var entry = [n, p];
  3520. yield entry;
  3521. }
  3522. },
  3523. /**
  3524. * Get the child of a node at a specific index.
  3525. */
  3526. child(root, index) {
  3527. if (Text.isText(root)) {
  3528. throw new Error("Cannot get the child of a text node: ".concat(JSON.stringify(root)));
  3529. }
  3530. var c = root.children[index];
  3531. if (c == null) {
  3532. throw new Error("Cannot get child at index `".concat(index, "` in node: ").concat(JSON.stringify(root)));
  3533. }
  3534. return c;
  3535. },
  3536. /**
  3537. * Iterate over the children of a node at a specific path.
  3538. */
  3539. *children(root, path) {
  3540. var options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
  3541. var {
  3542. reverse = false
  3543. } = options;
  3544. var ancestor = Node.ancestor(root, path);
  3545. var {
  3546. children
  3547. } = ancestor;
  3548. var index = reverse ? children.length - 1 : 0;
  3549. while (reverse ? index >= 0 : index < children.length) {
  3550. var child = Node.child(ancestor, index);
  3551. var childPath = path.concat(index);
  3552. yield [child, childPath];
  3553. index = reverse ? index - 1 : index + 1;
  3554. }
  3555. },
  3556. /**
  3557. * Get an entry for the common ancesetor node of two paths.
  3558. */
  3559. common(root, path, another) {
  3560. var p = Path.common(path, another);
  3561. var n = Node.get(root, p);
  3562. return [n, p];
  3563. },
  3564. /**
  3565. * Get the node at a specific path, asserting that it's a descendant node.
  3566. */
  3567. descendant(root, path) {
  3568. var node = Node.get(root, path);
  3569. if (Editor.isEditor(node)) {
  3570. throw new Error("Cannot get the descendant node at path [".concat(path, "] because it refers to the root editor node instead: ").concat(node));
  3571. }
  3572. return node;
  3573. },
  3574. /**
  3575. * Return an iterable of all the descendant node entries inside a root node.
  3576. */
  3577. *descendants(root) {
  3578. var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
  3579. for (var [node, path] of Node.nodes(root, options)) {
  3580. if (path.length !== 0) {
  3581. // NOTE: we have to coerce here because checking the path's length does
  3582. // guarantee that `node` is not a `Editor`, but TypeScript doesn't know.
  3583. yield [node, path];
  3584. }
  3585. }
  3586. },
  3587. /**
  3588. * Return an iterable of all the element nodes inside a root node. Each iteration
  3589. * will return an `ElementEntry` tuple consisting of `[Element, Path]`. If the
  3590. * root node is an element it will be included in the iteration as well.
  3591. */
  3592. *elements(root) {
  3593. var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
  3594. for (var [node, path] of Node.nodes(root, options)) {
  3595. if (Element.isElement(node)) {
  3596. yield [node, path];
  3597. }
  3598. }
  3599. },
  3600. /**
  3601. * Get the first node entry in a root node from a path.
  3602. */
  3603. first(root, path) {
  3604. var p = path.slice();
  3605. var n = Node.get(root, p);
  3606. while (n) {
  3607. if (Text.isText(n) || n.children.length === 0) {
  3608. break;
  3609. } else {
  3610. n = n.children[0];
  3611. p.push(0);
  3612. }
  3613. }
  3614. return [n, p];
  3615. },
  3616. /**
  3617. * Get the sliced fragment represented by a range inside a root node.
  3618. */
  3619. fragment(root, range) {
  3620. if (Text.isText(root)) {
  3621. throw new Error("Cannot get a fragment starting from a root text node: ".concat(JSON.stringify(root)));
  3622. }
  3623. var newRoot = immer_1.produce(root, r => {
  3624. var [start, end] = Range.edges(range);
  3625. var iterable = Node.nodes(r, {
  3626. reverse: true,
  3627. pass: (_ref) => {
  3628. var [, path] = _ref;
  3629. return !Range.includes(range, path);
  3630. }
  3631. });
  3632. for (var [, path] of iterable) {
  3633. if (!Range.includes(range, path)) {
  3634. var parent = Node.parent(r, path);
  3635. var index = path[path.length - 1];
  3636. parent.children.splice(index, 1);
  3637. }
  3638. if (Path.equals(path, end.path)) {
  3639. var leaf = Node.leaf(r, path);
  3640. leaf.text = leaf.text.slice(0, end.offset);
  3641. }
  3642. if (Path.equals(path, start.path)) {
  3643. var _leaf = Node.leaf(r, path);
  3644. _leaf.text = _leaf.text.slice(start.offset);
  3645. }
  3646. }
  3647. delete r.selection;
  3648. });
  3649. return newRoot.children;
  3650. },
  3651. /**
  3652. * Get the descendant node referred to by a specific path. If the path is an
  3653. * empty array, it refers to the root node itself.
  3654. */
  3655. get(root, path) {
  3656. var node = root;
  3657. for (var i = 0; i < path.length; i++) {
  3658. var p = path[i];
  3659. if (Text.isText(node) || !node.children[p]) {
  3660. throw new Error("Cannot find a descendant at path [".concat(path, "] in node: ").concat(JSON.stringify(root)));
  3661. }
  3662. node = node.children[p];
  3663. }
  3664. return node;
  3665. },
  3666. /**
  3667. * Check if a descendant node exists at a specific path.
  3668. */
  3669. has(root, path) {
  3670. var node = root;
  3671. for (var i = 0; i < path.length; i++) {
  3672. var p = path[i];
  3673. if (Text.isText(node) || !node.children[p]) {
  3674. return false;
  3675. }
  3676. node = node.children[p];
  3677. }
  3678. return true;
  3679. },
  3680. /**
  3681. * Check if a value implements the `Node` interface.
  3682. */
  3683. isNode(value) {
  3684. return Text.isText(value) || Element.isElement(value) || Editor.isEditor(value);
  3685. },
  3686. /**
  3687. * Check if a value is a list of `Node` objects.
  3688. */
  3689. isNodeList(value) {
  3690. return Array.isArray(value) && (value.length === 0 || Node.isNode(value[0]));
  3691. },
  3692. /**
  3693. * Get the lash node entry in a root node from a path.
  3694. */
  3695. last(root, path) {
  3696. var p = path.slice();
  3697. var n = Node.get(root, p);
  3698. while (n) {
  3699. if (Text.isText(n) || n.children.length === 0) {
  3700. break;
  3701. } else {
  3702. var i = n.children.length - 1;
  3703. n = n.children[i];
  3704. p.push(i);
  3705. }
  3706. }
  3707. return [n, p];
  3708. },
  3709. /**
  3710. * Get the node at a specific path, ensuring it's a leaf text node.
  3711. */
  3712. leaf(root, path) {
  3713. var node = Node.get(root, path);
  3714. if (!Text.isText(node)) {
  3715. throw new Error("Cannot get the leaf node at path [".concat(path, "] because it refers to a non-leaf node: ").concat(node));
  3716. }
  3717. return node;
  3718. },
  3719. /**
  3720. * Return an iterable of the in a branch of the tree, from a specific path.
  3721. *
  3722. * By default the order is top-down, from lowest to highest node in the tree,
  3723. * but you can pass the `reverse: true` option to go bottom-up.
  3724. */
  3725. *levels(root, path) {
  3726. var options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
  3727. for (var p of Path.levels(path, options)) {
  3728. var n = Node.get(root, p);
  3729. yield [n, p];
  3730. }
  3731. },
  3732. /**
  3733. * Check if a node matches a set of props.
  3734. */
  3735. matches(node, props) {
  3736. return Element.isElement(node) && Element.matches(node, props) || Text.isText(node) && Text.matches(node, props);
  3737. },
  3738. /**
  3739. * Return an iterable of all the node entries of a root node. Each entry is
  3740. * returned as a `[Node, Path]` tuple, with the path referring to the node's
  3741. * position inside the root node.
  3742. */
  3743. *nodes(root) {
  3744. var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
  3745. var {
  3746. pass,
  3747. reverse = false
  3748. } = options;
  3749. var {
  3750. from = [],
  3751. to
  3752. } = options;
  3753. var visited = new Set();
  3754. var p = [];
  3755. var n = root;
  3756. while (true) {
  3757. if (to && (reverse ? Path.isBefore(p, to) : Path.isAfter(p, to))) {
  3758. break;
  3759. }
  3760. if (!visited.has(n)) {
  3761. yield [n, p];
  3762. } // If we're allowed to go downward and we haven't decsended yet, do.
  3763. if (!visited.has(n) && !Text.isText(n) && n.children.length !== 0 && (pass == null || pass([n, p]) === false)) {
  3764. visited.add(n);
  3765. var nextIndex = reverse ? n.children.length - 1 : 0;
  3766. if (Path.isAncestor(p, from)) {
  3767. nextIndex = from[p.length];
  3768. }
  3769. p = p.concat(nextIndex);
  3770. n = Node.get(root, p);
  3771. continue;
  3772. } // If we're at the root and we can't go down, we're done.
  3773. if (p.length === 0) {
  3774. break;
  3775. } // If we're going forward...
  3776. if (!reverse) {
  3777. var newPath = Path.next(p);
  3778. if (Node.has(root, newPath)) {
  3779. p = newPath;
  3780. n = Node.get(root, p);
  3781. continue;
  3782. }
  3783. } // If we're going backward...
  3784. if (reverse && p[p.length - 1] !== 0) {
  3785. var _newPath = Path.previous(p);
  3786. p = _newPath;
  3787. n = Node.get(root, p);
  3788. continue;
  3789. } // Otherwise we're going upward...
  3790. p = Path.parent(p);
  3791. n = Node.get(root, p);
  3792. visited.add(n);
  3793. }
  3794. },
  3795. /**
  3796. * Get the parent of a node at a specific path.
  3797. */
  3798. parent(root, path) {
  3799. var parentPath = Path.parent(path);
  3800. var p = Node.get(root, parentPath);
  3801. if (Text.isText(p)) {
  3802. throw new Error("Cannot get the parent of path [".concat(path, "] because it does not exist in the root."));
  3803. }
  3804. return p;
  3805. },
  3806. /**
  3807. * Get the concatenated text string of a node's content.
  3808. *
  3809. * Note that this will not include spaces or line breaks between block nodes.
  3810. * It is not a user-facing string, but a string for performing offset-related
  3811. * computations for a node.
  3812. */
  3813. string(node) {
  3814. if (Text.isText(node)) {
  3815. return node.text;
  3816. } else {
  3817. return node.children.map(Node.string).join('');
  3818. }
  3819. },
  3820. /**
  3821. * Return an iterable of all leaf text nodes in a root node.
  3822. */
  3823. *texts(root) {
  3824. var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
  3825. for (var [node, path] of Node.nodes(root, options)) {
  3826. if (Text.isText(node)) {
  3827. yield [node, path];
  3828. }
  3829. }
  3830. }
  3831. };
  3832. function ownKeys$2(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); keys.push.apply(keys, symbols); } return keys; }
  3833. function _objectSpread$2(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys$2(Object(source), true).forEach(function (key) { _defineProperty(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys$2(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; }
  3834. var Operation = {
  3835. /**
  3836. * Check of a value is a `NodeOperation` object.
  3837. */
  3838. isNodeOperation(value) {
  3839. return Operation.isOperation(value) && value.type.endsWith('_node');
  3840. },
  3841. /**
  3842. * Check of a value is an `Operation` object.
  3843. */
  3844. isOperation(value) {
  3845. if (!isPlainObject(value)) {
  3846. return false;
  3847. }
  3848. switch (value.type) {
  3849. case 'insert_node':
  3850. return Path.isPath(value.path) && Node.isNode(value.node);
  3851. case 'insert_text':
  3852. return typeof value.offset === 'number' && typeof value.text === 'string' && Path.isPath(value.path);
  3853. case 'merge_node':
  3854. return typeof value.position === 'number' && (typeof value.target === 'number' || value.target === null) && Path.isPath(value.path) && isPlainObject(value.properties);
  3855. case 'move_node':
  3856. return Path.isPath(value.path) && Path.isPath(value.newPath);
  3857. case 'remove_node':
  3858. return Path.isPath(value.path) && Node.isNode(value.node);
  3859. case 'remove_text':
  3860. return typeof value.offset === 'number' && typeof value.text === 'string' && Path.isPath(value.path);
  3861. case 'set_node':
  3862. return Path.isPath(value.path) && isPlainObject(value.properties) && isPlainObject(value.newProperties);
  3863. case 'set_selection':
  3864. return value.properties === null && Range.isRange(value.newProperties) || value.newProperties === null && Range.isRange(value.properties) || isPlainObject(value.properties) && isPlainObject(value.newProperties);
  3865. case 'split_node':
  3866. return Path.isPath(value.path) && typeof value.position === 'number' && (typeof value.target === 'number' || value.target === null) && isPlainObject(value.properties);
  3867. default:
  3868. return false;
  3869. }
  3870. },
  3871. /**
  3872. * Check if a value is a list of `Operation` objects.
  3873. */
  3874. isOperationList(value) {
  3875. return Array.isArray(value) && (value.length === 0 || Operation.isOperation(value[0]));
  3876. },
  3877. /**
  3878. * Check of a value is a `SelectionOperation` object.
  3879. */
  3880. isSelectionOperation(value) {
  3881. return Operation.isOperation(value) && value.type.endsWith('_selection');
  3882. },
  3883. /**
  3884. * Check of a value is a `TextOperation` object.
  3885. */
  3886. isTextOperation(value) {
  3887. return Operation.isOperation(value) && value.type.endsWith('_text');
  3888. },
  3889. /**
  3890. * Invert an operation, returning a new operation that will exactly undo the
  3891. * original when applied.
  3892. */
  3893. inverse(op) {
  3894. switch (op.type) {
  3895. case 'insert_node':
  3896. {
  3897. return _objectSpread$2({}, op, {
  3898. type: 'remove_node'
  3899. });
  3900. }
  3901. case 'insert_text':
  3902. {
  3903. return _objectSpread$2({}, op, {
  3904. type: 'remove_text'
  3905. });
  3906. }
  3907. case 'merge_node':
  3908. {
  3909. return _objectSpread$2({}, op, {
  3910. type: 'split_node',
  3911. path: Path.previous(op.path)
  3912. });
  3913. }
  3914. case 'move_node':
  3915. {
  3916. var {
  3917. newPath,
  3918. path
  3919. } = op; // PERF: in this case the move operation is a no-op anyways.
  3920. if (Path.equals(newPath, path)) {
  3921. return op;
  3922. } // We need to get the original path here, but sometimes the `newPath`
  3923. // is a younger sibling of (or ends before) the original, and this
  3924. // accounts for it.
  3925. var inversePath = Path.transform(path, op);
  3926. var inverseNewPath = Path.transform(Path.next(path), op);
  3927. return _objectSpread$2({}, op, {
  3928. path: inversePath,
  3929. newPath: inverseNewPath
  3930. });
  3931. }
  3932. case 'remove_node':
  3933. {
  3934. return _objectSpread$2({}, op, {
  3935. type: 'insert_node'
  3936. });
  3937. }
  3938. case 'remove_text':
  3939. {
  3940. return _objectSpread$2({}, op, {
  3941. type: 'insert_text'
  3942. });
  3943. }
  3944. case 'set_node':
  3945. {
  3946. var {
  3947. properties,
  3948. newProperties
  3949. } = op;
  3950. return _objectSpread$2({}, op, {
  3951. properties: newProperties,
  3952. newProperties: properties
  3953. });
  3954. }
  3955. case 'set_selection':
  3956. {
  3957. var {
  3958. properties: _properties,
  3959. newProperties: _newProperties
  3960. } = op;
  3961. if (_properties == null) {
  3962. return _objectSpread$2({}, op, {
  3963. properties: _newProperties,
  3964. newProperties: null
  3965. });
  3966. } else if (_newProperties == null) {
  3967. return _objectSpread$2({}, op, {
  3968. properties: null,
  3969. newProperties: _properties
  3970. });
  3971. } else {
  3972. return _objectSpread$2({}, op, {
  3973. properties: _newProperties,
  3974. newProperties: _properties
  3975. });
  3976. }
  3977. }
  3978. case 'split_node':
  3979. {
  3980. return _objectSpread$2({}, op, {
  3981. type: 'merge_node',
  3982. path: Path.next(op.path)
  3983. });
  3984. }
  3985. }
  3986. }
  3987. };
  3988. var Path = {
  3989. /**
  3990. * Get a list of ancestor paths for a given path.
  3991. *
  3992. * The paths are sorted from deepest to shallowest ancestor. However, if the
  3993. * `reverse: true` option is passed, they are reversed.
  3994. */
  3995. ancestors(path) {
  3996. var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
  3997. var {
  3998. reverse = false
  3999. } = options;
  4000. var paths = Path.levels(path, options);
  4001. if (reverse) {
  4002. paths = paths.slice(1);
  4003. } else {
  4004. paths = paths.slice(0, -1);
  4005. }
  4006. return paths;
  4007. },
  4008. /**
  4009. * Get the common ancestor path of two paths.
  4010. */
  4011. common(path, another) {
  4012. var common = [];
  4013. for (var i = 0; i < path.length && i < another.length; i++) {
  4014. var av = path[i];
  4015. var bv = another[i];
  4016. if (av !== bv) {
  4017. break;
  4018. }
  4019. common.push(av);
  4020. }
  4021. return common;
  4022. },
  4023. /**
  4024. * Compare a path to another, returning an integer indicating whether the path
  4025. * was before, at, or after the other.
  4026. *
  4027. * Note: Two paths of unequal length can still receive a `0` result if one is
  4028. * directly above or below the other. If you want exact matching, use
  4029. * [[Path.equals]] instead.
  4030. */
  4031. compare(path, another) {
  4032. var min = Math.min(path.length, another.length);
  4033. for (var i = 0; i < min; i++) {
  4034. if (path[i] < another[i]) return -1;
  4035. if (path[i] > another[i]) return 1;
  4036. }
  4037. return 0;
  4038. },
  4039. /**
  4040. * Check if a path ends after one of the indexes in another.
  4041. */
  4042. endsAfter(path, another) {
  4043. var i = path.length - 1;
  4044. var as = path.slice(0, i);
  4045. var bs = another.slice(0, i);
  4046. var av = path[i];
  4047. var bv = another[i];
  4048. return Path.equals(as, bs) && av > bv;
  4049. },
  4050. /**
  4051. * Check if a path ends at one of the indexes in another.
  4052. */
  4053. endsAt(path, another) {
  4054. var i = path.length;
  4055. var as = path.slice(0, i);
  4056. var bs = another.slice(0, i);
  4057. return Path.equals(as, bs);
  4058. },
  4059. /**
  4060. * Check if a path ends before one of the indexes in another.
  4061. */
  4062. endsBefore(path, another) {
  4063. var i = path.length - 1;
  4064. var as = path.slice(0, i);
  4065. var bs = another.slice(0, i);
  4066. var av = path[i];
  4067. var bv = another[i];
  4068. return Path.equals(as, bs) && av < bv;
  4069. },
  4070. /**
  4071. * Check if a path is exactly equal to another.
  4072. */
  4073. equals(path, another) {
  4074. return path.length === another.length && path.every((n, i) => n === another[i]);
  4075. },
  4076. /**
  4077. * Check if a path is after another.
  4078. */
  4079. isAfter(path, another) {
  4080. return Path.compare(path, another) === 1;
  4081. },
  4082. /**
  4083. * Check if a path is an ancestor of another.
  4084. */
  4085. isAncestor(path, another) {
  4086. return path.length < another.length && Path.compare(path, another) === 0;
  4087. },
  4088. /**
  4089. * Check if a path is before another.
  4090. */
  4091. isBefore(path, another) {
  4092. return Path.compare(path, another) === -1;
  4093. },
  4094. /**
  4095. * Check if a path is a child of another.
  4096. */
  4097. isChild(path, another) {
  4098. return path.length === another.length + 1 && Path.compare(path, another) === 0;
  4099. },
  4100. /**
  4101. * Check if a path is equal to or an ancestor of another.
  4102. */
  4103. isCommon(path, another) {
  4104. return path.length <= another.length && Path.compare(path, another) === 0;
  4105. },
  4106. /**
  4107. * Check if a path is a descendant of another.
  4108. */
  4109. isDescendant(path, another) {
  4110. return path.length > another.length && Path.compare(path, another) === 0;
  4111. },
  4112. /**
  4113. * Check if a path is the parent of another.
  4114. */
  4115. isParent(path, another) {
  4116. return path.length + 1 === another.length && Path.compare(path, another) === 0;
  4117. },
  4118. /**
  4119. * Check is a value implements the `Path` interface.
  4120. */
  4121. isPath(value) {
  4122. return Array.isArray(value) && (value.length === 0 || typeof value[0] === 'number');
  4123. },
  4124. /**
  4125. * Check if a path is a sibling of another.
  4126. */
  4127. isSibling(path, another) {
  4128. if (path.length !== another.length) {
  4129. return false;
  4130. }
  4131. var as = path.slice(0, -1);
  4132. var bs = another.slice(0, -1);
  4133. var al = path[path.length - 1];
  4134. var bl = another[another.length - 1];
  4135. return al !== bl && Path.equals(as, bs);
  4136. },
  4137. /**
  4138. * Get a list of paths at every level down to a path. Note: this is the same
  4139. * as `Path.ancestors`, but including the path itself.
  4140. *
  4141. * The paths are sorted from shallowest to deepest. However, if the `reverse:
  4142. * true` option is passed, they are reversed.
  4143. */
  4144. levels(path) {
  4145. var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
  4146. var {
  4147. reverse = false
  4148. } = options;
  4149. var list = [];
  4150. for (var i = 0; i <= path.length; i++) {
  4151. list.push(path.slice(0, i));
  4152. }
  4153. if (reverse) {
  4154. list.reverse();
  4155. }
  4156. return list;
  4157. },
  4158. /**
  4159. * Given a path, get the path to the next sibling node.
  4160. */
  4161. next(path) {
  4162. if (path.length === 0) {
  4163. throw new Error("Cannot get the next path of a root path [".concat(path, "], because it has no next index."));
  4164. }
  4165. var last = path[path.length - 1];
  4166. return path.slice(0, -1).concat(last + 1);
  4167. },
  4168. /**
  4169. * Given a path, return a new path referring to the parent node above it.
  4170. */
  4171. parent(path) {
  4172. if (path.length === 0) {
  4173. throw new Error("Cannot get the parent path of the root path [".concat(path, "]."));
  4174. }
  4175. return path.slice(0, -1);
  4176. },
  4177. /**
  4178. * Given a path, get the path to the previous sibling node.
  4179. */
  4180. previous(path) {
  4181. if (path.length === 0) {
  4182. throw new Error("Cannot get the previous path of a root path [".concat(path, "], because it has no previous index."));
  4183. }
  4184. var last = path[path.length - 1];
  4185. if (last <= 0) {
  4186. throw new Error("Cannot get the previous path of a first child path [".concat(path, "] because it would result in a negative index."));
  4187. }
  4188. return path.slice(0, -1).concat(last - 1);
  4189. },
  4190. /**
  4191. * Get a path relative to an ancestor.
  4192. */
  4193. relative(path, ancestor) {
  4194. if (!Path.isAncestor(ancestor, path) && !Path.equals(path, ancestor)) {
  4195. throw new Error("Cannot get the relative path of [".concat(path, "] inside ancestor [").concat(ancestor, "], because it is not above or equal to the path."));
  4196. }
  4197. return path.slice(ancestor.length);
  4198. },
  4199. /**
  4200. * Transform a path by an operation.
  4201. */
  4202. transform(path, operation) {
  4203. var options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
  4204. return immer_1.produce(path, p => {
  4205. var {
  4206. affinity = 'forward'
  4207. } = options; // PERF: Exit early if the operation is guaranteed not to have an effect.
  4208. if (path.length === 0) {
  4209. return;
  4210. }
  4211. switch (operation.type) {
  4212. case 'insert_node':
  4213. {
  4214. var {
  4215. path: op
  4216. } = operation;
  4217. if (Path.equals(op, p) || Path.endsBefore(op, p) || Path.isAncestor(op, p)) {
  4218. p[op.length - 1] += 1;
  4219. }
  4220. break;
  4221. }
  4222. case 'remove_node':
  4223. {
  4224. var {
  4225. path: _op
  4226. } = operation;
  4227. if (Path.equals(_op, p) || Path.isAncestor(_op, p)) {
  4228. return null;
  4229. } else if (Path.endsBefore(_op, p)) {
  4230. p[_op.length - 1] -= 1;
  4231. }
  4232. break;
  4233. }
  4234. case 'merge_node':
  4235. {
  4236. var {
  4237. path: _op2,
  4238. position
  4239. } = operation;
  4240. if (Path.equals(_op2, p) || Path.endsBefore(_op2, p)) {
  4241. p[_op2.length - 1] -= 1;
  4242. } else if (Path.isAncestor(_op2, p)) {
  4243. p[_op2.length - 1] -= 1;
  4244. p[_op2.length] += position;
  4245. }
  4246. break;
  4247. }
  4248. case 'split_node':
  4249. {
  4250. var {
  4251. path: _op3,
  4252. position: _position
  4253. } = operation;
  4254. if (Path.equals(_op3, p)) {
  4255. if (affinity === 'forward') {
  4256. p[p.length - 1] += 1;
  4257. } else if (affinity === 'backward') ; else {
  4258. return null;
  4259. }
  4260. } else if (Path.endsBefore(_op3, p)) {
  4261. p[_op3.length - 1] += 1;
  4262. } else if (Path.isAncestor(_op3, p) && path[_op3.length] >= _position) {
  4263. p[_op3.length - 1] += 1;
  4264. p[_op3.length] -= _position;
  4265. }
  4266. break;
  4267. }
  4268. case 'move_node':
  4269. {
  4270. var {
  4271. path: _op4,
  4272. newPath: onp
  4273. } = operation; // If the old and new path are the same, it's a no-op.
  4274. if (Path.equals(_op4, onp)) {
  4275. return;
  4276. }
  4277. if (Path.isAncestor(_op4, p) || Path.equals(_op4, p)) {
  4278. var copy = onp.slice();
  4279. if (Path.endsBefore(_op4, onp) && _op4.length < onp.length) {
  4280. var i = Math.min(onp.length, _op4.length) - 1;
  4281. copy[i] -= 1;
  4282. }
  4283. return copy.concat(p.slice(_op4.length));
  4284. } else if (Path.endsBefore(onp, p) || Path.equals(onp, p) || Path.isAncestor(onp, p)) {
  4285. if (Path.endsBefore(_op4, p)) {
  4286. p[_op4.length - 1] -= 1;
  4287. }
  4288. p[onp.length - 1] += 1;
  4289. } else if (Path.endsBefore(_op4, p)) {
  4290. if (Path.equals(onp, p)) {
  4291. p[onp.length - 1] += 1;
  4292. }
  4293. p[_op4.length - 1] -= 1;
  4294. }
  4295. break;
  4296. }
  4297. }
  4298. });
  4299. }
  4300. };
  4301. var PathRef = {
  4302. /**
  4303. * Transform the path ref's current value by an operation.
  4304. */
  4305. transform(ref, op) {
  4306. var {
  4307. current,
  4308. affinity
  4309. } = ref;
  4310. if (current == null) {
  4311. return;
  4312. }
  4313. var path = Path.transform(current, op, {
  4314. affinity
  4315. });
  4316. ref.current = path;
  4317. if (path == null) {
  4318. ref.unref();
  4319. }
  4320. }
  4321. };
  4322. function ownKeys$3(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); keys.push.apply(keys, symbols); } return keys; }
  4323. function _objectSpread$3(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys$3(Object(source), true).forEach(function (key) { _defineProperty(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys$3(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; }
  4324. var Point = {
  4325. /**
  4326. * Compare a point to another, returning an integer indicating whether the
  4327. * point was before, at, or after the other.
  4328. */
  4329. compare(point, another) {
  4330. var result = Path.compare(point.path, another.path);
  4331. if (result === 0) {
  4332. if (point.offset < another.offset) return -1;
  4333. if (point.offset > another.offset) return 1;
  4334. return 0;
  4335. }
  4336. return result;
  4337. },
  4338. /**
  4339. * Check if a point is after another.
  4340. */
  4341. isAfter(point, another) {
  4342. return Point.compare(point, another) === 1;
  4343. },
  4344. /**
  4345. * Check if a point is before another.
  4346. */
  4347. isBefore(point, another) {
  4348. return Point.compare(point, another) === -1;
  4349. },
  4350. /**
  4351. * Check if a point is exactly equal to another.
  4352. */
  4353. equals(point, another) {
  4354. // PERF: ensure the offsets are equal first since they are cheaper to check.
  4355. return point.offset === another.offset && Path.equals(point.path, another.path);
  4356. },
  4357. /**
  4358. * Check if a value implements the `Point` interface.
  4359. */
  4360. isPoint(value) {
  4361. return isPlainObject(value) && typeof value.offset === 'number' && Path.isPath(value.path);
  4362. },
  4363. /**
  4364. * Transform a point by an operation.
  4365. */
  4366. transform(point, op) {
  4367. var options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
  4368. return immer_1.produce(point, p => {
  4369. var {
  4370. affinity = 'forward'
  4371. } = options;
  4372. var {
  4373. path,
  4374. offset
  4375. } = p;
  4376. switch (op.type) {
  4377. case 'insert_node':
  4378. case 'move_node':
  4379. {
  4380. p.path = Path.transform(path, op, options);
  4381. break;
  4382. }
  4383. case 'insert_text':
  4384. {
  4385. if (Path.equals(op.path, path) && op.offset <= offset) {
  4386. p.offset += op.text.length;
  4387. }
  4388. break;
  4389. }
  4390. case 'merge_node':
  4391. {
  4392. if (Path.equals(op.path, path)) {
  4393. p.offset += op.position;
  4394. }
  4395. p.path = Path.transform(path, op, options);
  4396. break;
  4397. }
  4398. case 'remove_text':
  4399. {
  4400. if (Path.equals(op.path, path) && op.offset <= offset) {
  4401. p.offset -= Math.min(offset - op.offset, op.text.length);
  4402. }
  4403. break;
  4404. }
  4405. case 'remove_node':
  4406. {
  4407. if (Path.equals(op.path, path) || Path.isAncestor(op.path, path)) {
  4408. return null;
  4409. }
  4410. p.path = Path.transform(path, op, options);
  4411. break;
  4412. }
  4413. case 'split_node':
  4414. {
  4415. if (Path.equals(op.path, path)) {
  4416. if (op.position === offset && affinity == null) {
  4417. return null;
  4418. } else if (op.position < offset || op.position === offset && affinity === 'forward') {
  4419. p.offset -= op.position;
  4420. p.path = Path.transform(path, op, _objectSpread$3({}, options, {
  4421. affinity: 'forward'
  4422. }));
  4423. }
  4424. } else {
  4425. p.path = Path.transform(path, op, options);
  4426. }
  4427. break;
  4428. }
  4429. }
  4430. });
  4431. }
  4432. };
  4433. var PointRef = {
  4434. /**
  4435. * Transform the point ref's current value by an operation.
  4436. */
  4437. transform(ref, op) {
  4438. var {
  4439. current,
  4440. affinity
  4441. } = ref;
  4442. if (current == null) {
  4443. return;
  4444. }
  4445. var point = Point.transform(current, op, {
  4446. affinity
  4447. });
  4448. ref.current = point;
  4449. if (point == null) {
  4450. ref.unref();
  4451. }
  4452. }
  4453. };
  4454. function ownKeys$4(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); keys.push.apply(keys, symbols); } return keys; }
  4455. function _objectSpread$4(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys$4(Object(source), true).forEach(function (key) { _defineProperty(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys$4(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; }
  4456. var Range = {
  4457. /**
  4458. * Get the start and end points of a range, in the order in which they appear
  4459. * in the document.
  4460. */
  4461. edges(range) {
  4462. var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
  4463. var {
  4464. reverse = false
  4465. } = options;
  4466. var {
  4467. anchor,
  4468. focus
  4469. } = range;
  4470. return Range.isBackward(range) === reverse ? [anchor, focus] : [focus, anchor];
  4471. },
  4472. /**
  4473. * Get the end point of a range.
  4474. */
  4475. end(range) {
  4476. var [, end] = Range.edges(range);
  4477. return end;
  4478. },
  4479. /**
  4480. * Check if a range is exactly equal to another.
  4481. */
  4482. equals(range, another) {
  4483. return Point.equals(range.anchor, another.anchor) && Point.equals(range.focus, another.focus);
  4484. },
  4485. /**
  4486. * Check if a range includes a path, a point or part of another range.
  4487. */
  4488. includes(range, target) {
  4489. if (Range.isRange(target)) {
  4490. if (Range.includes(range, target.anchor) || Range.includes(range, target.focus)) {
  4491. return true;
  4492. }
  4493. var [rs, re] = Range.edges(range);
  4494. var [ts, te] = Range.edges(target);
  4495. return Point.isBefore(rs, ts) && Point.isAfter(re, te);
  4496. }
  4497. var [start, end] = Range.edges(range);
  4498. var isAfterStart = false;
  4499. var isBeforeEnd = false;
  4500. if (Point.isPoint(target)) {
  4501. isAfterStart = Point.compare(target, start) >= 0;
  4502. isBeforeEnd = Point.compare(target, end) <= 0;
  4503. } else {
  4504. isAfterStart = Path.compare(target, start.path) >= 0;
  4505. isBeforeEnd = Path.compare(target, end.path) <= 0;
  4506. }
  4507. return isAfterStart && isBeforeEnd;
  4508. },
  4509. /**
  4510. * Get the intersection of a range with another.
  4511. */
  4512. intersection(range, another) {
  4513. var rest = _objectWithoutProperties(range, ["anchor", "focus"]);
  4514. var [s1, e1] = Range.edges(range);
  4515. var [s2, e2] = Range.edges(another);
  4516. var start = Point.isBefore(s1, s2) ? s2 : s1;
  4517. var end = Point.isBefore(e1, e2) ? e1 : e2;
  4518. if (Point.isBefore(end, start)) {
  4519. return null;
  4520. } else {
  4521. return _objectSpread$4({
  4522. anchor: start,
  4523. focus: end
  4524. }, rest);
  4525. }
  4526. },
  4527. /**
  4528. * Check if a range is backward, meaning that its anchor point appears in the
  4529. * document _after_ its focus point.
  4530. */
  4531. isBackward(range) {
  4532. var {
  4533. anchor,
  4534. focus
  4535. } = range;
  4536. return Point.isAfter(anchor, focus);
  4537. },
  4538. /**
  4539. * Check if a range is collapsed, meaning that both its anchor and focus
  4540. * points refer to the exact same position in the document.
  4541. */
  4542. isCollapsed(range) {
  4543. var {
  4544. anchor,
  4545. focus
  4546. } = range;
  4547. return Point.equals(anchor, focus);
  4548. },
  4549. /**
  4550. * Check if a range is expanded.
  4551. *
  4552. * This is the opposite of [[Range.isCollapsed]] and is provided for legibility.
  4553. */
  4554. isExpanded(range) {
  4555. return !Range.isCollapsed(range);
  4556. },
  4557. /**
  4558. * Check if a range is forward.
  4559. *
  4560. * This is the opposite of [[Range.isBackward]] and is provided for legibility.
  4561. */
  4562. isForward(range) {
  4563. return !Range.isBackward(range);
  4564. },
  4565. /**
  4566. * Check if a value implements the [[Range]] interface.
  4567. */
  4568. isRange(value) {
  4569. return isPlainObject(value) && Point.isPoint(value.anchor) && Point.isPoint(value.focus);
  4570. },
  4571. /**
  4572. * Iterate through all of the point entries in a range.
  4573. */
  4574. *points(range) {
  4575. yield [range.anchor, 'anchor'];
  4576. yield [range.focus, 'focus'];
  4577. },
  4578. /**
  4579. * Get the start point of a range.
  4580. */
  4581. start(range) {
  4582. var [start] = Range.edges(range);
  4583. return start;
  4584. },
  4585. /**
  4586. * Transform a range by an operation.
  4587. */
  4588. transform(range, op, options) {
  4589. var {
  4590. affinity = 'inward'
  4591. } = options;
  4592. var affinityAnchor;
  4593. var affinityFocus;
  4594. if (affinity === 'inward') {
  4595. if (Range.isForward(range)) {
  4596. affinityAnchor = 'forward';
  4597. affinityFocus = 'backward';
  4598. } else {
  4599. affinityAnchor = 'backward';
  4600. affinityFocus = 'forward';
  4601. }
  4602. } else if (affinity === 'outward') {
  4603. if (Range.isForward(range)) {
  4604. affinityAnchor = 'backward';
  4605. affinityFocus = 'forward';
  4606. } else {
  4607. affinityAnchor = 'forward';
  4608. affinityFocus = 'backward';
  4609. }
  4610. } else {
  4611. affinityAnchor = affinity;
  4612. affinityFocus = affinity;
  4613. }
  4614. return immer_1.produce(range, r => {
  4615. var anchor = Point.transform(r.anchor, op, {
  4616. affinity: affinityAnchor
  4617. });
  4618. var focus = Point.transform(r.focus, op, {
  4619. affinity: affinityFocus
  4620. });
  4621. if (!anchor || !focus) {
  4622. return null;
  4623. }
  4624. r.anchor = anchor;
  4625. r.focus = focus;
  4626. });
  4627. }
  4628. };
  4629. var RangeRef = {
  4630. /**
  4631. * Transform the range ref's current value by an operation.
  4632. */
  4633. transform(ref, op) {
  4634. var {
  4635. current,
  4636. affinity
  4637. } = ref;
  4638. if (current == null) {
  4639. return;
  4640. }
  4641. var path = Range.transform(current, op, {
  4642. affinity
  4643. });
  4644. ref.current = path;
  4645. if (path == null) {
  4646. ref.unref();
  4647. }
  4648. }
  4649. };
  4650. function ownKeys$5(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); keys.push.apply(keys, symbols); } return keys; }
  4651. function _objectSpread$5(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys$5(Object(source), true).forEach(function (key) { _defineProperty(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys$5(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; }
  4652. var Text = {
  4653. /**
  4654. * Check if two text nodes are equal.
  4655. */
  4656. equals(text, another) {
  4657. var options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
  4658. var {
  4659. loose = false
  4660. } = options;
  4661. for (var key in text) {
  4662. if (loose && key === 'text') {
  4663. continue;
  4664. }
  4665. if (text[key] !== another[key]) {
  4666. return false;
  4667. }
  4668. }
  4669. for (var _key in another) {
  4670. if (loose && _key === 'text') {
  4671. continue;
  4672. }
  4673. if (text[_key] !== another[_key]) {
  4674. return false;
  4675. }
  4676. }
  4677. return true;
  4678. },
  4679. /**
  4680. * Check if a value implements the `Text` interface.
  4681. */
  4682. isText(value) {
  4683. return isPlainObject(value) && typeof value.text === 'string';
  4684. },
  4685. /**
  4686. * Check if a value is a list of `Text` objects.
  4687. */
  4688. isTextList(value) {
  4689. return Array.isArray(value) && (value.length === 0 || Text.isText(value[0]));
  4690. },
  4691. /**
  4692. * Check if an text matches set of properties.
  4693. *
  4694. * Note: this is for matching custom properties, and it does not ensure that
  4695. * the `text` property are two nodes equal.
  4696. */
  4697. matches(text, props) {
  4698. for (var key in props) {
  4699. if (key === 'text') {
  4700. continue;
  4701. }
  4702. if (text[key] !== props[key]) {
  4703. return false;
  4704. }
  4705. }
  4706. return true;
  4707. },
  4708. /**
  4709. * Get the leaves for a text node given decorations.
  4710. */
  4711. decorations(node, decorations) {
  4712. var leaves = [_objectSpread$5({}, node)];
  4713. for (var dec of decorations) {
  4714. var rest = _objectWithoutProperties(dec, ["anchor", "focus"]);
  4715. var [start, end] = Range.edges(dec);
  4716. var next = [];
  4717. var o = 0;
  4718. for (var leaf of leaves) {
  4719. var {
  4720. length
  4721. } = leaf.text;
  4722. var offset = o;
  4723. o += length; // If the range encompases the entire leaf, add the range.
  4724. if (start.offset <= offset && end.offset >= offset + length) {
  4725. Object.assign(leaf, rest);
  4726. next.push(leaf);
  4727. continue;
  4728. } // If the range starts after the leaf, or ends before it, continue.
  4729. if (start.offset > offset + length || end.offset < offset || end.offset === offset && offset !== 0) {
  4730. next.push(leaf);
  4731. continue;
  4732. } // Otherwise we need to split the leaf, at the start, end, or both,
  4733. // and add the range to the middle intersecting section. Do the end
  4734. // split first since we don't need to update the offset that way.
  4735. var middle = leaf;
  4736. var before = void 0;
  4737. var after = void 0;
  4738. if (end.offset < offset + length) {
  4739. var off = end.offset - offset;
  4740. after = _objectSpread$5({}, middle, {
  4741. text: middle.text.slice(off)
  4742. });
  4743. middle = _objectSpread$5({}, middle, {
  4744. text: middle.text.slice(0, off)
  4745. });
  4746. }
  4747. if (start.offset > offset) {
  4748. var _off = start.offset - offset;
  4749. before = _objectSpread$5({}, middle, {
  4750. text: middle.text.slice(0, _off)
  4751. });
  4752. middle = _objectSpread$5({}, middle, {
  4753. text: middle.text.slice(_off)
  4754. });
  4755. }
  4756. Object.assign(middle, rest);
  4757. if (before) {
  4758. next.push(before);
  4759. }
  4760. next.push(middle);
  4761. if (after) {
  4762. next.push(after);
  4763. }
  4764. }
  4765. leaves = next;
  4766. }
  4767. return leaves;
  4768. }
  4769. };
  4770. function ownKeys$6(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); keys.push.apply(keys, symbols); } return keys; }
  4771. function _objectSpread$6(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys$6(Object(source), true).forEach(function (key) { _defineProperty(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys$6(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; }
  4772. var GeneralTransforms = {
  4773. /**
  4774. * Transform the editor by an operation.
  4775. */
  4776. transform(editor, op) {
  4777. editor.children = immer_1.createDraft(editor.children);
  4778. var selection = editor.selection && immer_1.createDraft(editor.selection);
  4779. switch (op.type) {
  4780. case 'insert_node':
  4781. {
  4782. var {
  4783. path,
  4784. node
  4785. } = op;
  4786. var parent = Node.parent(editor, path);
  4787. var index = path[path.length - 1];
  4788. parent.children.splice(index, 0, node);
  4789. if (selection) {
  4790. for (var [point, key] of Range.points(selection)) {
  4791. selection[key] = Point.transform(point, op);
  4792. }
  4793. }
  4794. break;
  4795. }
  4796. case 'insert_text':
  4797. {
  4798. var {
  4799. path: _path,
  4800. offset,
  4801. text
  4802. } = op;
  4803. var _node = Node.leaf(editor, _path);
  4804. var before = _node.text.slice(0, offset);
  4805. var after = _node.text.slice(offset);
  4806. _node.text = before + text + after;
  4807. if (selection) {
  4808. for (var [_point, _key] of Range.points(selection)) {
  4809. selection[_key] = Point.transform(_point, op);
  4810. }
  4811. }
  4812. break;
  4813. }
  4814. case 'merge_node':
  4815. {
  4816. var {
  4817. path: _path2
  4818. } = op;
  4819. var _node2 = Node.get(editor, _path2);
  4820. var prevPath = Path.previous(_path2);
  4821. var prev = Node.get(editor, prevPath);
  4822. var _parent = Node.parent(editor, _path2);
  4823. var _index = _path2[_path2.length - 1];
  4824. if (Text.isText(_node2) && Text.isText(prev)) {
  4825. prev.text += _node2.text;
  4826. } else if (!Text.isText(_node2) && !Text.isText(prev)) {
  4827. prev.children.push(..._node2.children);
  4828. } else {
  4829. throw new Error("Cannot apply a \"merge_node\" operation at path [".concat(_path2, "] to nodes of different interaces: ").concat(_node2, " ").concat(prev));
  4830. }
  4831. _parent.children.splice(_index, 1);
  4832. if (selection) {
  4833. for (var [_point2, _key2] of Range.points(selection)) {
  4834. selection[_key2] = Point.transform(_point2, op);
  4835. }
  4836. }
  4837. break;
  4838. }
  4839. case 'move_node':
  4840. {
  4841. var {
  4842. path: _path3,
  4843. newPath
  4844. } = op;
  4845. if (Path.isAncestor(_path3, newPath)) {
  4846. throw new Error("Cannot move a path [".concat(_path3, "] to new path [").concat(newPath, "] because the destination is inside itself."));
  4847. }
  4848. var _node3 = Node.get(editor, _path3);
  4849. var _parent2 = Node.parent(editor, _path3);
  4850. var _index2 = _path3[_path3.length - 1]; // This is tricky, but since the `path` and `newPath` both refer to
  4851. // the same snapshot in time, there's a mismatch. After either
  4852. // removing the original position, the second step's path can be out
  4853. // of date. So instead of using the `op.newPath` directly, we
  4854. // transform `op.path` to ascertain what the `newPath` would be after
  4855. // the operation was applied.
  4856. _parent2.children.splice(_index2, 1);
  4857. var truePath = Path.transform(_path3, op);
  4858. var newParent = Node.get(editor, Path.parent(truePath));
  4859. var newIndex = truePath[truePath.length - 1];
  4860. newParent.children.splice(newIndex, 0, _node3);
  4861. if (selection) {
  4862. for (var [_point3, _key3] of Range.points(selection)) {
  4863. selection[_key3] = Point.transform(_point3, op);
  4864. }
  4865. }
  4866. break;
  4867. }
  4868. case 'remove_node':
  4869. {
  4870. var {
  4871. path: _path4
  4872. } = op;
  4873. var _index3 = _path4[_path4.length - 1];
  4874. var _parent3 = Node.parent(editor, _path4);
  4875. _parent3.children.splice(_index3, 1); // Transform all of the points in the value, but if the point was in the
  4876. // node that was removed we need to update the range or remove it.
  4877. if (selection) {
  4878. for (var [_point4, _key4] of Range.points(selection)) {
  4879. var result = Point.transform(_point4, op);
  4880. if (selection != null && result != null) {
  4881. selection[_key4] = result;
  4882. } else {
  4883. var _prev = void 0;
  4884. var next = void 0;
  4885. for (var [n, p] of Node.texts(editor)) {
  4886. if (Path.compare(p, _path4) === -1) {
  4887. _prev = [n, p];
  4888. } else {
  4889. next = [n, p];
  4890. break;
  4891. }
  4892. }
  4893. if (_prev) {
  4894. _point4.path = _prev[1];
  4895. _point4.offset = _prev[0].text.length;
  4896. } else if (next) {
  4897. _point4.path = next[1];
  4898. _point4.offset = 0;
  4899. } else {
  4900. selection = null;
  4901. }
  4902. }
  4903. }
  4904. }
  4905. break;
  4906. }
  4907. case 'remove_text':
  4908. {
  4909. var {
  4910. path: _path5,
  4911. offset: _offset,
  4912. text: _text
  4913. } = op;
  4914. var _node4 = Node.leaf(editor, _path5);
  4915. var _before = _node4.text.slice(0, _offset);
  4916. var _after = _node4.text.slice(_offset + _text.length);
  4917. _node4.text = _before + _after;
  4918. if (selection) {
  4919. for (var [_point5, _key5] of Range.points(selection)) {
  4920. selection[_key5] = Point.transform(_point5, op);
  4921. }
  4922. }
  4923. break;
  4924. }
  4925. case 'set_node':
  4926. {
  4927. var {
  4928. path: _path6,
  4929. newProperties
  4930. } = op;
  4931. if (_path6.length === 0) {
  4932. throw new Error("Cannot set properties on the root node!");
  4933. }
  4934. var _node5 = Node.get(editor, _path6);
  4935. for (var _key6 in newProperties) {
  4936. if (_key6 === 'children' || _key6 === 'text') {
  4937. throw new Error("Cannot set the \"".concat(_key6, "\" property of nodes!"));
  4938. }
  4939. var value = newProperties[_key6];
  4940. if (value == null) {
  4941. delete _node5[_key6];
  4942. } else {
  4943. _node5[_key6] = value;
  4944. }
  4945. }
  4946. break;
  4947. }
  4948. case 'set_selection':
  4949. {
  4950. var {
  4951. newProperties: _newProperties
  4952. } = op;
  4953. if (_newProperties == null) {
  4954. selection = _newProperties;
  4955. } else if (selection == null) {
  4956. if (!Range.isRange(_newProperties)) {
  4957. throw new Error("Cannot apply an incomplete \"set_selection\" operation properties ".concat(JSON.stringify(_newProperties), " when there is no current selection."));
  4958. }
  4959. selection = _newProperties;
  4960. } else {
  4961. Object.assign(selection, _newProperties);
  4962. }
  4963. break;
  4964. }
  4965. case 'split_node':
  4966. {
  4967. var {
  4968. path: _path7,
  4969. position,
  4970. properties
  4971. } = op;
  4972. if (_path7.length === 0) {
  4973. throw new Error("Cannot apply a \"split_node\" operation at path [".concat(_path7, "] because the root node cannot be split."));
  4974. }
  4975. var _node6 = Node.get(editor, _path7);
  4976. var _parent4 = Node.parent(editor, _path7);
  4977. var _index4 = _path7[_path7.length - 1];
  4978. var newNode;
  4979. if (Text.isText(_node6)) {
  4980. var _before2 = _node6.text.slice(0, position);
  4981. var _after2 = _node6.text.slice(position);
  4982. _node6.text = _before2;
  4983. newNode = _objectSpread$6({}, _node6, {}, properties, {
  4984. text: _after2
  4985. });
  4986. } else {
  4987. var _before3 = _node6.children.slice(0, position);
  4988. var _after3 = _node6.children.slice(position);
  4989. _node6.children = _before3;
  4990. newNode = _objectSpread$6({}, _node6, {}, properties, {
  4991. children: _after3
  4992. });
  4993. }
  4994. _parent4.children.splice(_index4 + 1, 0, newNode);
  4995. if (selection) {
  4996. for (var [_point6, _key7] of Range.points(selection)) {
  4997. selection[_key7] = Point.transform(_point6, op);
  4998. }
  4999. }
  5000. break;
  5001. }
  5002. }
  5003. editor.children = immer_1.finishDraft(editor.children);
  5004. if (selection) {
  5005. editor.selection = immer_1.isDraft(selection) ? immer_1.finishDraft(selection) : selection;
  5006. } else {
  5007. editor.selection = null;
  5008. }
  5009. }
  5010. };
  5011. function ownKeys$7(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); keys.push.apply(keys, symbols); } return keys; }
  5012. function _objectSpread$7(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys$7(Object(source), true).forEach(function (key) { _defineProperty(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys$7(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; }
  5013. var NodeTransforms = {
  5014. /**
  5015. * Insert nodes at a specific location in the Editor.
  5016. */
  5017. insertNodes(editor, nodes) {
  5018. var options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
  5019. Editor.withoutNormalizing(editor, () => {
  5020. var {
  5021. hanging = false,
  5022. voids = false,
  5023. mode = 'lowest'
  5024. } = options;
  5025. var {
  5026. at,
  5027. match,
  5028. select
  5029. } = options;
  5030. if (Node.isNode(nodes)) {
  5031. nodes = [nodes];
  5032. }
  5033. if (nodes.length === 0) {
  5034. return;
  5035. }
  5036. var [node] = nodes; // By default, use the selection as the target location. But if there is
  5037. // no selection, insert at the end of the document since that is such a
  5038. // common use case when inserting from a non-selected state.
  5039. if (!at) {
  5040. if (editor.selection) {
  5041. at = editor.selection;
  5042. } else if (editor.children.length > 0) {
  5043. at = Editor.end(editor, []);
  5044. } else {
  5045. at = [0];
  5046. }
  5047. select = true;
  5048. }
  5049. if (select == null) {
  5050. select = false;
  5051. }
  5052. if (Range.isRange(at)) {
  5053. if (!hanging) {
  5054. at = Editor.unhangRange(editor, at);
  5055. }
  5056. if (Range.isCollapsed(at)) {
  5057. at = at.anchor;
  5058. } else {
  5059. var [, end] = Range.edges(at);
  5060. var pointRef = Editor.pointRef(editor, end);
  5061. Transforms.delete(editor, {
  5062. at
  5063. });
  5064. at = pointRef.unref();
  5065. }
  5066. }
  5067. if (Point.isPoint(at)) {
  5068. if (match == null) {
  5069. if (Text.isText(node)) {
  5070. match = n => Text.isText(n);
  5071. } else if (editor.isInline(node)) {
  5072. match = n => Text.isText(n) || Editor.isInline(editor, n);
  5073. } else {
  5074. match = n => Editor.isBlock(editor, n);
  5075. }
  5076. }
  5077. var [entry] = Editor.nodes(editor, {
  5078. at: at.path,
  5079. match,
  5080. mode,
  5081. voids
  5082. });
  5083. if (entry) {
  5084. var [, _matchPath] = entry;
  5085. var pathRef = Editor.pathRef(editor, _matchPath);
  5086. var isAtEnd = Editor.isEnd(editor, at, _matchPath);
  5087. Transforms.splitNodes(editor, {
  5088. at,
  5089. match,
  5090. mode,
  5091. voids
  5092. });
  5093. var path = pathRef.unref();
  5094. at = isAtEnd ? Path.next(path) : path;
  5095. } else {
  5096. return;
  5097. }
  5098. }
  5099. var parentPath = Path.parent(at);
  5100. var index = at[at.length - 1];
  5101. if (!voids && Editor.void(editor, {
  5102. at: parentPath
  5103. })) {
  5104. return;
  5105. }
  5106. for (var _node of nodes) {
  5107. var _path = parentPath.concat(index);
  5108. index++;
  5109. editor.apply({
  5110. type: 'insert_node',
  5111. path: _path,
  5112. node: _node
  5113. });
  5114. }
  5115. if (select) {
  5116. var point = Editor.end(editor, at);
  5117. if (point) {
  5118. Transforms.select(editor, point);
  5119. }
  5120. }
  5121. });
  5122. },
  5123. /**
  5124. * Lift nodes at a specific location upwards in the document tree, splitting
  5125. * their parent in two if necessary.
  5126. */
  5127. liftNodes(editor) {
  5128. var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
  5129. Editor.withoutNormalizing(editor, () => {
  5130. var {
  5131. at = editor.selection,
  5132. mode = 'lowest',
  5133. voids = false
  5134. } = options;
  5135. var {
  5136. match
  5137. } = options;
  5138. if (match == null) {
  5139. match = Path.isPath(at) ? matchPath(editor, at) : n => Editor.isBlock(editor, n);
  5140. }
  5141. if (!at) {
  5142. return;
  5143. }
  5144. var matches = Editor.nodes(editor, {
  5145. at,
  5146. match,
  5147. mode,
  5148. voids
  5149. });
  5150. var pathRefs = Array.from(matches, (_ref) => {
  5151. var [, p] = _ref;
  5152. return Editor.pathRef(editor, p);
  5153. });
  5154. for (var pathRef of pathRefs) {
  5155. var path = pathRef.unref();
  5156. if (path.length < 2) {
  5157. throw new Error("Cannot lift node at a path [".concat(path, "] because it has a depth of less than `2`."));
  5158. }
  5159. var [parent, parentPath] = Editor.node(editor, Path.parent(path));
  5160. var index = path[path.length - 1];
  5161. var {
  5162. length
  5163. } = parent.children;
  5164. if (length === 1) {
  5165. var toPath = Path.next(parentPath);
  5166. Transforms.moveNodes(editor, {
  5167. at: path,
  5168. to: toPath,
  5169. voids
  5170. });
  5171. Transforms.removeNodes(editor, {
  5172. at: parentPath,
  5173. voids
  5174. });
  5175. } else if (index === 0) {
  5176. Transforms.moveNodes(editor, {
  5177. at: path,
  5178. to: parentPath,
  5179. voids
  5180. });
  5181. } else if (index === length - 1) {
  5182. var _toPath = Path.next(parentPath);
  5183. Transforms.moveNodes(editor, {
  5184. at: path,
  5185. to: _toPath,
  5186. voids
  5187. });
  5188. } else {
  5189. var splitPath = Path.next(path);
  5190. var _toPath2 = Path.next(parentPath);
  5191. Transforms.splitNodes(editor, {
  5192. at: splitPath,
  5193. voids
  5194. });
  5195. Transforms.moveNodes(editor, {
  5196. at: path,
  5197. to: _toPath2,
  5198. voids
  5199. });
  5200. }
  5201. }
  5202. });
  5203. },
  5204. /**
  5205. * Merge a node at a location with the previous node of the same depth,
  5206. * removing any empty containing nodes after the merge if necessary.
  5207. */
  5208. mergeNodes(editor) {
  5209. var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
  5210. Editor.withoutNormalizing(editor, () => {
  5211. var {
  5212. match,
  5213. at = editor.selection
  5214. } = options;
  5215. var {
  5216. hanging = false,
  5217. voids = false,
  5218. mode = 'lowest'
  5219. } = options;
  5220. if (!at) {
  5221. return;
  5222. }
  5223. if (match == null) {
  5224. if (Path.isPath(at)) {
  5225. var [parent] = Editor.parent(editor, at);
  5226. match = n => parent.children.includes(n);
  5227. } else {
  5228. match = n => Editor.isBlock(editor, n);
  5229. }
  5230. }
  5231. if (!hanging && Range.isRange(at)) {
  5232. at = Editor.unhangRange(editor, at);
  5233. }
  5234. if (Range.isRange(at)) {
  5235. if (Range.isCollapsed(at)) {
  5236. at = at.anchor;
  5237. } else {
  5238. var [, end] = Range.edges(at);
  5239. var pointRef = Editor.pointRef(editor, end);
  5240. Transforms.delete(editor, {
  5241. at
  5242. });
  5243. at = pointRef.unref();
  5244. if (options.at == null) {
  5245. Transforms.select(editor, at);
  5246. }
  5247. }
  5248. }
  5249. var [current] = Editor.nodes(editor, {
  5250. at,
  5251. match,
  5252. voids,
  5253. mode
  5254. });
  5255. var prev = Editor.previous(editor, {
  5256. at,
  5257. match,
  5258. voids,
  5259. mode
  5260. });
  5261. if (!current || !prev) {
  5262. return;
  5263. }
  5264. var [node, path] = current;
  5265. var [prevNode, prevPath] = prev;
  5266. if (path.length === 0 || prevPath.length === 0) {
  5267. return;
  5268. }
  5269. var newPath = Path.next(prevPath);
  5270. var commonPath = Path.common(path, prevPath);
  5271. var isPreviousSibling = Path.isSibling(path, prevPath);
  5272. var levels = Array.from(Editor.levels(editor, {
  5273. at: path
  5274. }), (_ref2) => {
  5275. var [n] = _ref2;
  5276. return n;
  5277. }).slice(commonPath.length).slice(0, -1); // Determine if the merge will leave an ancestor of the path empty as a
  5278. // result, in which case we'll want to remove it after merging.
  5279. var emptyAncestor = Editor.above(editor, {
  5280. at: path,
  5281. mode: 'highest',
  5282. match: n => levels.includes(n) && Element.isElement(n) && n.children.length === 1
  5283. });
  5284. var emptyRef = emptyAncestor && Editor.pathRef(editor, emptyAncestor[1]);
  5285. var properties;
  5286. var position; // Ensure that the nodes are equivalent, and figure out what the position
  5287. // and extra properties of the merge will be.
  5288. if (Text.isText(node) && Text.isText(prevNode)) {
  5289. var rest = _objectWithoutProperties(node, ["text"]);
  5290. position = prevNode.text.length;
  5291. properties = rest;
  5292. } else if (Element.isElement(node) && Element.isElement(prevNode)) {
  5293. var rest = _objectWithoutProperties(node, ["children"]);
  5294. position = prevNode.children.length;
  5295. properties = rest;
  5296. } else {
  5297. throw new Error("Cannot merge the node at path [".concat(path, "] with the previous sibling because it is not the same kind: ").concat(JSON.stringify(node), " ").concat(JSON.stringify(prevNode)));
  5298. } // If the node isn't already the next sibling of the previous node, move
  5299. // it so that it is before merging.
  5300. if (!isPreviousSibling) {
  5301. Transforms.moveNodes(editor, {
  5302. at: path,
  5303. to: newPath,
  5304. voids
  5305. });
  5306. } // If there was going to be an empty ancestor of the node that was merged,
  5307. // we remove it from the tree.
  5308. if (emptyRef) {
  5309. Transforms.removeNodes(editor, {
  5310. at: emptyRef.current,
  5311. voids
  5312. });
  5313. } // If the target node that we're merging with is empty, remove it instead
  5314. // of merging the two. This is a common rich text editor behavior to
  5315. // prevent losing formatting when deleting entire nodes when you have a
  5316. // hanging selection.
  5317. if (Element.isElement(prevNode) && Editor.isEmpty(editor, prevNode) || Text.isText(prevNode) && prevNode.text === '') {
  5318. Transforms.removeNodes(editor, {
  5319. at: prevPath,
  5320. voids
  5321. });
  5322. } else {
  5323. editor.apply({
  5324. type: 'merge_node',
  5325. path: newPath,
  5326. position,
  5327. target: null,
  5328. properties
  5329. });
  5330. }
  5331. if (emptyRef) {
  5332. emptyRef.unref();
  5333. }
  5334. });
  5335. },
  5336. /**
  5337. * Move the nodes at a location to a new location.
  5338. */
  5339. moveNodes(editor, options) {
  5340. Editor.withoutNormalizing(editor, () => {
  5341. var {
  5342. to,
  5343. at = editor.selection,
  5344. mode = 'lowest',
  5345. voids = false
  5346. } = options;
  5347. var {
  5348. match
  5349. } = options;
  5350. if (!at) {
  5351. return;
  5352. }
  5353. if (match == null) {
  5354. match = Path.isPath(at) ? matchPath(editor, at) : n => Editor.isBlock(editor, n);
  5355. }
  5356. var toRef = Editor.pathRef(editor, to);
  5357. var targets = Editor.nodes(editor, {
  5358. at,
  5359. match,
  5360. mode,
  5361. voids
  5362. });
  5363. var pathRefs = Array.from(targets, (_ref3) => {
  5364. var [, p] = _ref3;
  5365. return Editor.pathRef(editor, p);
  5366. });
  5367. for (var pathRef of pathRefs) {
  5368. var path = pathRef.unref();
  5369. var newPath = toRef.current;
  5370. if (path.length !== 0) {
  5371. editor.apply({
  5372. type: 'move_node',
  5373. path,
  5374. newPath
  5375. });
  5376. }
  5377. }
  5378. toRef.unref();
  5379. });
  5380. },
  5381. /**
  5382. * Remove the nodes at a specific location in the document.
  5383. */
  5384. removeNodes(editor) {
  5385. var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
  5386. Editor.withoutNormalizing(editor, () => {
  5387. var {
  5388. hanging = false,
  5389. voids = false,
  5390. mode = 'lowest'
  5391. } = options;
  5392. var {
  5393. at = editor.selection,
  5394. match
  5395. } = options;
  5396. if (!at) {
  5397. return;
  5398. }
  5399. if (match == null) {
  5400. match = Path.isPath(at) ? matchPath(editor, at) : n => Editor.isBlock(editor, n);
  5401. }
  5402. if (!hanging && Range.isRange(at)) {
  5403. at = Editor.unhangRange(editor, at);
  5404. }
  5405. var depths = Editor.nodes(editor, {
  5406. at,
  5407. match,
  5408. mode,
  5409. voids
  5410. });
  5411. var pathRefs = Array.from(depths, (_ref4) => {
  5412. var [, p] = _ref4;
  5413. return Editor.pathRef(editor, p);
  5414. });
  5415. for (var pathRef of pathRefs) {
  5416. var path = pathRef.unref();
  5417. if (path) {
  5418. var [node] = Editor.node(editor, path);
  5419. editor.apply({
  5420. type: 'remove_node',
  5421. path,
  5422. node
  5423. });
  5424. }
  5425. }
  5426. });
  5427. },
  5428. /**
  5429. * Set new properties on the nodes at a location.
  5430. */
  5431. setNodes(editor, props) {
  5432. var options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
  5433. Editor.withoutNormalizing(editor, () => {
  5434. var {
  5435. match,
  5436. at = editor.selection
  5437. } = options;
  5438. var {
  5439. hanging = false,
  5440. mode = 'lowest',
  5441. split = false,
  5442. voids = false
  5443. } = options;
  5444. if (!at) {
  5445. return;
  5446. }
  5447. if (match == null) {
  5448. match = Path.isPath(at) ? matchPath(editor, at) : n => Editor.isBlock(editor, n);
  5449. }
  5450. if (!hanging && Range.isRange(at)) {
  5451. at = Editor.unhangRange(editor, at);
  5452. }
  5453. if (split && Range.isRange(at)) {
  5454. var rangeRef = Editor.rangeRef(editor, at, {
  5455. affinity: 'inward'
  5456. });
  5457. var [start, end] = Range.edges(at);
  5458. var splitMode = mode === 'lowest' ? 'lowest' : 'highest';
  5459. Transforms.splitNodes(editor, {
  5460. at: end,
  5461. match,
  5462. mode: splitMode,
  5463. voids
  5464. });
  5465. Transforms.splitNodes(editor, {
  5466. at: start,
  5467. match,
  5468. mode: splitMode,
  5469. voids
  5470. });
  5471. at = rangeRef.unref();
  5472. if (options.at == null) {
  5473. Transforms.select(editor, at);
  5474. }
  5475. }
  5476. for (var [node, path] of Editor.nodes(editor, {
  5477. at,
  5478. match,
  5479. mode,
  5480. voids
  5481. })) {
  5482. var properties = {};
  5483. var newProperties = {}; // You can't set properties on the editor node.
  5484. if (path.length === 0) {
  5485. continue;
  5486. }
  5487. for (var k in props) {
  5488. if (k === 'children' || k === 'text') {
  5489. continue;
  5490. }
  5491. if (props[k] !== node[k]) {
  5492. properties[k] = node[k];
  5493. newProperties[k] = props[k];
  5494. }
  5495. }
  5496. if (Object.keys(newProperties).length !== 0) {
  5497. editor.apply({
  5498. type: 'set_node',
  5499. path,
  5500. properties,
  5501. newProperties
  5502. });
  5503. }
  5504. }
  5505. });
  5506. },
  5507. /**
  5508. * Split the nodes at a specific location.
  5509. */
  5510. splitNodes(editor) {
  5511. var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
  5512. Editor.withoutNormalizing(editor, () => {
  5513. var {
  5514. mode = 'lowest',
  5515. voids = false
  5516. } = options;
  5517. var {
  5518. match,
  5519. at = editor.selection,
  5520. height = 0,
  5521. always = false
  5522. } = options;
  5523. if (match == null) {
  5524. match = n => Editor.isBlock(editor, n);
  5525. }
  5526. if (Range.isRange(at)) {
  5527. at = deleteRange(editor, at);
  5528. } // If the target is a path, the default height-skipping and position
  5529. // counters need to account for us potentially splitting at a non-leaf.
  5530. if (Path.isPath(at)) {
  5531. var path = at;
  5532. var point = Editor.point(editor, path);
  5533. var [parent] = Editor.parent(editor, path);
  5534. match = n => n === parent;
  5535. height = point.path.length - path.length + 1;
  5536. at = point;
  5537. always = true;
  5538. }
  5539. if (!at) {
  5540. return;
  5541. }
  5542. var beforeRef = Editor.pointRef(editor, at, {
  5543. affinity: 'backward'
  5544. });
  5545. var [highest] = Editor.nodes(editor, {
  5546. at,
  5547. match,
  5548. mode,
  5549. voids
  5550. });
  5551. if (!highest) {
  5552. return;
  5553. }
  5554. var voidMatch = Editor.void(editor, {
  5555. at,
  5556. mode: 'highest'
  5557. });
  5558. var nudge = 0;
  5559. if (!voids && voidMatch) {
  5560. var [voidNode, voidPath] = voidMatch;
  5561. if (Element.isElement(voidNode) && editor.isInline(voidNode)) {
  5562. var after = Editor.after(editor, voidPath);
  5563. if (!after) {
  5564. var text = {
  5565. text: ''
  5566. };
  5567. var afterPath = Path.next(voidPath);
  5568. Transforms.insertNodes(editor, text, {
  5569. at: afterPath,
  5570. voids
  5571. });
  5572. after = Editor.point(editor, afterPath);
  5573. }
  5574. at = after;
  5575. always = true;
  5576. }
  5577. var siblingHeight = at.path.length - voidPath.length;
  5578. height = siblingHeight + 1;
  5579. always = true;
  5580. }
  5581. var afterRef = Editor.pointRef(editor, at);
  5582. var depth = at.path.length - height;
  5583. var [, highestPath] = highest;
  5584. var lowestPath = at.path.slice(0, depth);
  5585. var position = height === 0 ? at.offset : at.path[depth] + nudge;
  5586. var target = null;
  5587. for (var [node, _path2] of Editor.levels(editor, {
  5588. at: lowestPath,
  5589. reverse: true,
  5590. voids
  5591. })) {
  5592. var split = false;
  5593. if (_path2.length < highestPath.length || _path2.length === 0 || !voids && Editor.isVoid(editor, node)) {
  5594. break;
  5595. }
  5596. var _point = beforeRef.current;
  5597. var isEnd = Editor.isEnd(editor, _point, _path2);
  5598. if (always || !beforeRef || !Editor.isEdge(editor, _point, _path2)) {
  5599. split = true;
  5600. var properties = _objectWithoutProperties(node, ["text", "children"]);
  5601. editor.apply({
  5602. type: 'split_node',
  5603. path: _path2,
  5604. position,
  5605. target,
  5606. properties
  5607. });
  5608. }
  5609. target = position;
  5610. position = _path2[_path2.length - 1] + (split || isEnd ? 1 : 0);
  5611. }
  5612. if (options.at == null) {
  5613. var _point2 = afterRef.current || Editor.end(editor, []);
  5614. Transforms.select(editor, _point2);
  5615. }
  5616. beforeRef.unref();
  5617. afterRef.unref();
  5618. });
  5619. },
  5620. /**
  5621. * Unset properties on the nodes at a location.
  5622. */
  5623. unsetNodes(editor, props) {
  5624. var options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
  5625. if (!Array.isArray(props)) {
  5626. props = [props];
  5627. }
  5628. var obj = {};
  5629. for (var key of props) {
  5630. obj[key] = null;
  5631. }
  5632. Transforms.setNodes(editor, obj, options);
  5633. },
  5634. /**
  5635. * Unwrap the nodes at a location from a parent node, splitting the parent if
  5636. * necessary to ensure that only the content in the range is unwrapped.
  5637. */
  5638. unwrapNodes(editor, options) {
  5639. Editor.withoutNormalizing(editor, () => {
  5640. var {
  5641. mode = 'lowest',
  5642. split = false,
  5643. voids = false
  5644. } = options;
  5645. var {
  5646. at = editor.selection,
  5647. match
  5648. } = options;
  5649. if (!at) {
  5650. return;
  5651. }
  5652. if (match == null) {
  5653. match = Path.isPath(at) ? matchPath(editor, at) : n => Editor.isBlock(editor, n);
  5654. }
  5655. if (Path.isPath(at)) {
  5656. at = Editor.range(editor, at);
  5657. }
  5658. var rangeRef = Range.isRange(at) ? Editor.rangeRef(editor, at) : null;
  5659. var matches = Editor.nodes(editor, {
  5660. at,
  5661. match,
  5662. mode,
  5663. voids
  5664. });
  5665. var pathRefs = Array.from(matches, (_ref5) => {
  5666. var [, p] = _ref5;
  5667. return Editor.pathRef(editor, p);
  5668. });
  5669. var _loop = function _loop(pathRef) {
  5670. var path = pathRef.unref();
  5671. var [node] = Editor.node(editor, path);
  5672. var range = Editor.range(editor, path);
  5673. if (split && rangeRef) {
  5674. range = Range.intersection(rangeRef.current, range);
  5675. }
  5676. Transforms.liftNodes(editor, {
  5677. at: range,
  5678. match: n => node.children.includes(n),
  5679. voids
  5680. });
  5681. };
  5682. for (var pathRef of pathRefs) {
  5683. _loop(pathRef);
  5684. }
  5685. if (rangeRef) {
  5686. rangeRef.unref();
  5687. }
  5688. });
  5689. },
  5690. /**
  5691. * Wrap the nodes at a location in a new container node, splitting the edges
  5692. * of the range first to ensure that only the content in the range is wrapped.
  5693. */
  5694. wrapNodes(editor, element) {
  5695. var options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
  5696. Editor.withoutNormalizing(editor, () => {
  5697. var {
  5698. mode = 'lowest',
  5699. split = false,
  5700. voids = false
  5701. } = options;
  5702. var {
  5703. match,
  5704. at = editor.selection
  5705. } = options;
  5706. if (!at) {
  5707. return;
  5708. }
  5709. if (match == null) {
  5710. if (Path.isPath(at)) {
  5711. match = matchPath(editor, at);
  5712. } else if (editor.isInline(element)) {
  5713. match = n => Editor.isInline(editor, n) || Text.isText(n);
  5714. } else {
  5715. match = n => Editor.isBlock(editor, n);
  5716. }
  5717. }
  5718. if (split && Range.isRange(at)) {
  5719. var [start, end] = Range.edges(at);
  5720. var rangeRef = Editor.rangeRef(editor, at, {
  5721. affinity: 'inward'
  5722. });
  5723. Transforms.splitNodes(editor, {
  5724. at: end,
  5725. match,
  5726. voids
  5727. });
  5728. Transforms.splitNodes(editor, {
  5729. at: start,
  5730. match,
  5731. voids
  5732. });
  5733. at = rangeRef.unref();
  5734. if (options.at == null) {
  5735. Transforms.select(editor, at);
  5736. }
  5737. }
  5738. var roots = Array.from(Editor.nodes(editor, {
  5739. at,
  5740. match: editor.isInline(element) ? n => Editor.isBlock(editor, n) : n => Editor.isEditor(n),
  5741. mode: 'highest',
  5742. voids
  5743. }));
  5744. for (var [, rootPath] of roots) {
  5745. var a = Range.isRange(at) ? Range.intersection(at, Editor.range(editor, rootPath)) : at;
  5746. if (!a) {
  5747. continue;
  5748. }
  5749. var matches = Array.from(Editor.nodes(editor, {
  5750. at: a,
  5751. match,
  5752. mode,
  5753. voids
  5754. }));
  5755. if (matches.length > 0) {
  5756. (function () {
  5757. var [first] = matches;
  5758. var last = matches[matches.length - 1];
  5759. var [, firstPath] = first;
  5760. var [, lastPath] = last;
  5761. var commonPath = Path.equals(firstPath, lastPath) ? Path.parent(firstPath) : Path.common(firstPath, lastPath);
  5762. var range = Editor.range(editor, firstPath, lastPath);
  5763. var [commonNode] = Editor.node(editor, commonPath);
  5764. var depth = commonPath.length + 1;
  5765. var wrapperPath = Path.next(lastPath.slice(0, depth));
  5766. var wrapper = _objectSpread$7({}, element, {
  5767. children: []
  5768. });
  5769. Transforms.insertNodes(editor, wrapper, {
  5770. at: wrapperPath,
  5771. voids
  5772. });
  5773. Transforms.moveNodes(editor, {
  5774. at: range,
  5775. match: n => commonNode.children.includes(n),
  5776. to: wrapperPath.concat(0),
  5777. voids
  5778. });
  5779. })();
  5780. }
  5781. }
  5782. });
  5783. }
  5784. };
  5785. /**
  5786. * Convert a range into a point by deleting it's content.
  5787. */
  5788. var deleteRange = (editor, range) => {
  5789. if (Range.isCollapsed(range)) {
  5790. return range.anchor;
  5791. } else {
  5792. var [, end] = Range.edges(range);
  5793. var pointRef = Editor.pointRef(editor, end);
  5794. Transforms.delete(editor, {
  5795. at: range
  5796. });
  5797. return pointRef.unref();
  5798. }
  5799. };
  5800. var matchPath = (editor, path) => {
  5801. var [node] = Editor.node(editor, path);
  5802. return n => n === node;
  5803. };
  5804. var SelectionTransforms = {
  5805. /**
  5806. * Collapse the selection.
  5807. */
  5808. collapse(editor) {
  5809. var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
  5810. var {
  5811. edge = 'anchor'
  5812. } = options;
  5813. var {
  5814. selection
  5815. } = editor;
  5816. if (!selection) {
  5817. return;
  5818. } else if (edge === 'anchor') {
  5819. Transforms.select(editor, selection.anchor);
  5820. } else if (edge === 'focus') {
  5821. Transforms.select(editor, selection.focus);
  5822. } else if (edge === 'start') {
  5823. var [start] = Range.edges(selection);
  5824. Transforms.select(editor, start);
  5825. } else if (edge === 'end') {
  5826. var [, end] = Range.edges(selection);
  5827. Transforms.select(editor, end);
  5828. }
  5829. },
  5830. /**
  5831. * Unset the selection.
  5832. */
  5833. deselect(editor) {
  5834. var {
  5835. selection
  5836. } = editor;
  5837. if (selection) {
  5838. editor.apply({
  5839. type: 'set_selection',
  5840. properties: selection,
  5841. newProperties: null
  5842. });
  5843. }
  5844. },
  5845. /**
  5846. * Move the selection's point forward or backward.
  5847. */
  5848. move(editor) {
  5849. var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
  5850. var {
  5851. selection
  5852. } = editor;
  5853. var {
  5854. distance = 1,
  5855. unit = 'character',
  5856. reverse = false
  5857. } = options;
  5858. var {
  5859. edge = null
  5860. } = options;
  5861. if (!selection) {
  5862. return;
  5863. }
  5864. if (edge === 'start') {
  5865. edge = Range.isBackward(selection) ? 'focus' : 'anchor';
  5866. }
  5867. if (edge === 'end') {
  5868. edge = Range.isBackward(selection) ? 'anchor' : 'focus';
  5869. }
  5870. var {
  5871. anchor,
  5872. focus
  5873. } = selection;
  5874. var opts = {
  5875. distance,
  5876. unit
  5877. };
  5878. var props = {};
  5879. if (edge == null || edge === 'anchor') {
  5880. var point = reverse ? Editor.before(editor, anchor, opts) : Editor.after(editor, anchor, opts);
  5881. if (point) {
  5882. props.anchor = point;
  5883. }
  5884. }
  5885. if (edge == null || edge === 'focus') {
  5886. var _point = reverse ? Editor.before(editor, focus, opts) : Editor.after(editor, focus, opts);
  5887. if (_point) {
  5888. props.focus = _point;
  5889. }
  5890. }
  5891. Transforms.setSelection(editor, props);
  5892. },
  5893. /**
  5894. * Set the selection to a new value.
  5895. */
  5896. select(editor, target) {
  5897. var {
  5898. selection
  5899. } = editor;
  5900. target = Editor.range(editor, target);
  5901. if (selection) {
  5902. Transforms.setSelection(editor, target);
  5903. return;
  5904. }
  5905. if (!Range.isRange(target)) {
  5906. throw new Error("When setting the selection and the current selection is `null` you must provide at least an `anchor` and `focus`, but you passed: ".concat(JSON.stringify(target)));
  5907. }
  5908. editor.apply({
  5909. type: 'set_selection',
  5910. properties: selection,
  5911. newProperties: target
  5912. });
  5913. },
  5914. /**
  5915. * Set new properties on one of the selection's points.
  5916. */
  5917. setPoint(editor, props, options) {
  5918. var {
  5919. selection
  5920. } = editor;
  5921. var {
  5922. edge = 'both'
  5923. } = options;
  5924. if (!selection) {
  5925. return;
  5926. }
  5927. if (edge === 'start') {
  5928. edge = Range.isBackward(selection) ? 'focus' : 'anchor';
  5929. }
  5930. if (edge === 'end') {
  5931. edge = Range.isBackward(selection) ? 'anchor' : 'focus';
  5932. }
  5933. var {
  5934. anchor,
  5935. focus
  5936. } = selection;
  5937. var point = edge === 'anchor' ? anchor : focus;
  5938. var newPoint = Object.assign(point, props);
  5939. if (edge === 'anchor') {
  5940. Transforms.setSelection(editor, {
  5941. anchor: newPoint
  5942. });
  5943. } else {
  5944. Transforms.setSelection(editor, {
  5945. focus: newPoint
  5946. });
  5947. }
  5948. },
  5949. /**
  5950. * Set new properties on the selection.
  5951. */
  5952. setSelection(editor, props) {
  5953. var {
  5954. selection
  5955. } = editor;
  5956. var oldProps = {};
  5957. var newProps = {};
  5958. if (!selection) {
  5959. return;
  5960. }
  5961. for (var k in props) {
  5962. if (k === 'anchor' && props.anchor != null && !Point.equals(props.anchor, selection.anchor) || k === 'focus' && props.focus != null && !Point.equals(props.focus, selection.focus) || k !== 'anchor' && k !== 'focus' && props[k] !== selection[k]) {
  5963. oldProps[k] = selection[k];
  5964. newProps[k] = props[k];
  5965. }
  5966. }
  5967. if (Object.keys(oldProps).length > 0) {
  5968. editor.apply({
  5969. type: 'set_selection',
  5970. properties: oldProps,
  5971. newProperties: newProps
  5972. });
  5973. }
  5974. }
  5975. };
  5976. var TextTransforms = {
  5977. /**
  5978. * Delete content in the editor.
  5979. */
  5980. delete(editor) {
  5981. var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
  5982. Editor.withoutNormalizing(editor, () => {
  5983. var {
  5984. reverse = false,
  5985. unit = 'character',
  5986. distance = 1,
  5987. voids = false
  5988. } = options;
  5989. var {
  5990. at = editor.selection,
  5991. hanging = false
  5992. } = options;
  5993. if (!at) {
  5994. return;
  5995. }
  5996. if (Range.isRange(at) && Range.isCollapsed(at)) {
  5997. at = at.anchor;
  5998. }
  5999. if (Point.isPoint(at)) {
  6000. var furthestVoid = Editor.void(editor, {
  6001. at,
  6002. mode: 'highest'
  6003. });
  6004. if (!voids && furthestVoid) {
  6005. var [, voidPath] = furthestVoid;
  6006. at = voidPath;
  6007. } else {
  6008. var opts = {
  6009. unit,
  6010. distance
  6011. };
  6012. var target = reverse ? Editor.before(editor, at, opts) || Editor.start(editor, []) : Editor.after(editor, at, opts) || Editor.end(editor, []);
  6013. at = {
  6014. anchor: at,
  6015. focus: target
  6016. };
  6017. hanging = true;
  6018. }
  6019. }
  6020. if (Path.isPath(at)) {
  6021. Transforms.removeNodes(editor, {
  6022. at,
  6023. voids
  6024. });
  6025. return;
  6026. }
  6027. if (Range.isCollapsed(at)) {
  6028. return;
  6029. }
  6030. if (!hanging) {
  6031. at = Editor.unhangRange(editor, at, {
  6032. voids
  6033. });
  6034. }
  6035. var [start, end] = Range.edges(at);
  6036. var startBlock = Editor.above(editor, {
  6037. match: n => Editor.isBlock(editor, n),
  6038. at: start,
  6039. voids
  6040. });
  6041. var endBlock = Editor.above(editor, {
  6042. match: n => Editor.isBlock(editor, n),
  6043. at: end,
  6044. voids
  6045. });
  6046. var isAcrossBlocks = startBlock && endBlock && !Path.equals(startBlock[1], endBlock[1]);
  6047. var isSingleText = Path.equals(start.path, end.path);
  6048. var startVoid = voids ? null : Editor.void(editor, {
  6049. at: start,
  6050. mode: 'highest'
  6051. });
  6052. var endVoid = voids ? null : Editor.void(editor, {
  6053. at: end,
  6054. mode: 'highest'
  6055. }); // If the start or end points are inside an inline void, nudge them out.
  6056. if (startVoid) {
  6057. var before = Editor.before(editor, start);
  6058. if (before && startBlock && Path.isAncestor(startBlock[1], before.path)) {
  6059. start = before;
  6060. }
  6061. }
  6062. if (endVoid) {
  6063. var after = Editor.after(editor, end);
  6064. if (after && endBlock && Path.isAncestor(endBlock[1], after.path)) {
  6065. end = after;
  6066. }
  6067. } // Get the highest nodes that are completely inside the range, as well as
  6068. // the start and end nodes.
  6069. var matches = [];
  6070. var lastPath;
  6071. for (var entry of Editor.nodes(editor, {
  6072. at,
  6073. voids
  6074. })) {
  6075. var [node, path] = entry;
  6076. if (lastPath && Path.compare(path, lastPath) === 0) {
  6077. continue;
  6078. }
  6079. if (!voids && Editor.isVoid(editor, node) || !Path.isCommon(path, start.path) && !Path.isCommon(path, end.path)) {
  6080. matches.push(entry);
  6081. lastPath = path;
  6082. }
  6083. }
  6084. var pathRefs = Array.from(matches, (_ref) => {
  6085. var [, p] = _ref;
  6086. return Editor.pathRef(editor, p);
  6087. });
  6088. var startRef = Editor.pointRef(editor, start);
  6089. var endRef = Editor.pointRef(editor, end);
  6090. if (!isSingleText && !startVoid) {
  6091. var _point = startRef.current;
  6092. var [_node] = Editor.leaf(editor, _point);
  6093. var {
  6094. path: _path
  6095. } = _point;
  6096. var {
  6097. offset
  6098. } = start;
  6099. var text = _node.text.slice(offset);
  6100. editor.apply({
  6101. type: 'remove_text',
  6102. path: _path,
  6103. offset,
  6104. text
  6105. });
  6106. }
  6107. for (var pathRef of pathRefs) {
  6108. var _path2 = pathRef.unref();
  6109. Transforms.removeNodes(editor, {
  6110. at: _path2,
  6111. voids
  6112. });
  6113. }
  6114. if (!endVoid) {
  6115. var _point2 = endRef.current;
  6116. var [_node2] = Editor.leaf(editor, _point2);
  6117. var {
  6118. path: _path3
  6119. } = _point2;
  6120. var _offset = isSingleText ? start.offset : 0;
  6121. var _text = _node2.text.slice(_offset, end.offset);
  6122. editor.apply({
  6123. type: 'remove_text',
  6124. path: _path3,
  6125. offset: _offset,
  6126. text: _text
  6127. });
  6128. }
  6129. if (!isSingleText && isAcrossBlocks && endRef.current && startRef.current) {
  6130. Transforms.mergeNodes(editor, {
  6131. at: endRef.current,
  6132. hanging: true,
  6133. voids
  6134. });
  6135. }
  6136. var point = endRef.unref() || startRef.unref();
  6137. if (options.at == null && point) {
  6138. Transforms.select(editor, point);
  6139. }
  6140. });
  6141. },
  6142. /**
  6143. * Insert a fragment at a specific location in the editor.
  6144. */
  6145. insertFragment(editor, fragment) {
  6146. var options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
  6147. Editor.withoutNormalizing(editor, () => {
  6148. var {
  6149. hanging = false,
  6150. voids = false
  6151. } = options;
  6152. var {
  6153. at = editor.selection
  6154. } = options;
  6155. if (!fragment.length) {
  6156. return;
  6157. }
  6158. if (!at) {
  6159. return;
  6160. } else if (Range.isRange(at)) {
  6161. if (!hanging) {
  6162. at = Editor.unhangRange(editor, at);
  6163. }
  6164. if (Range.isCollapsed(at)) {
  6165. at = at.anchor;
  6166. } else {
  6167. var [, end] = Range.edges(at);
  6168. if (!voids && Editor.void(editor, {
  6169. at: end
  6170. })) {
  6171. return;
  6172. }
  6173. var pointRef = Editor.pointRef(editor, end);
  6174. Transforms.delete(editor, {
  6175. at
  6176. });
  6177. at = pointRef.unref();
  6178. }
  6179. } else if (Path.isPath(at)) {
  6180. at = Editor.start(editor, at);
  6181. }
  6182. if (!voids && Editor.void(editor, {
  6183. at
  6184. })) {
  6185. return;
  6186. } // If the insert point is at the edge of an inline node, move it outside
  6187. // instead since it will need to be split otherwise.
  6188. var inlineElementMatch = Editor.above(editor, {
  6189. at,
  6190. match: n => Editor.isInline(editor, n),
  6191. mode: 'highest',
  6192. voids
  6193. });
  6194. if (inlineElementMatch) {
  6195. var [, _inlinePath] = inlineElementMatch;
  6196. if (Editor.isEnd(editor, at, _inlinePath)) {
  6197. var after = Editor.after(editor, _inlinePath);
  6198. at = after;
  6199. } else if (Editor.isStart(editor, at, _inlinePath)) {
  6200. var before = Editor.before(editor, _inlinePath);
  6201. at = before;
  6202. }
  6203. }
  6204. var blockMatch = Editor.above(editor, {
  6205. match: n => Editor.isBlock(editor, n),
  6206. at,
  6207. voids
  6208. });
  6209. var [, blockPath] = blockMatch;
  6210. var isBlockStart = Editor.isStart(editor, at, blockPath);
  6211. var isBlockEnd = Editor.isEnd(editor, at, blockPath);
  6212. var mergeStart = !isBlockStart || isBlockStart && isBlockEnd;
  6213. var mergeEnd = !isBlockEnd;
  6214. var [, firstPath] = Node.first({
  6215. children: fragment
  6216. }, []);
  6217. var [, lastPath] = Node.last({
  6218. children: fragment
  6219. }, []);
  6220. var matches = [];
  6221. var matcher = (_ref2) => {
  6222. var [n, p] = _ref2;
  6223. if (mergeStart && Path.isAncestor(p, firstPath) && Element.isElement(n) && !editor.isVoid(n) && !editor.isInline(n)) {
  6224. return false;
  6225. }
  6226. if (mergeEnd && Path.isAncestor(p, lastPath) && Element.isElement(n) && !editor.isVoid(n) && !editor.isInline(n)) {
  6227. return false;
  6228. }
  6229. return true;
  6230. };
  6231. for (var entry of Node.nodes({
  6232. children: fragment
  6233. }, {
  6234. pass: matcher
  6235. })) {
  6236. if (entry[1].length > 0 && matcher(entry)) {
  6237. matches.push(entry);
  6238. }
  6239. }
  6240. var starts = [];
  6241. var middles = [];
  6242. var ends = [];
  6243. var starting = true;
  6244. var hasBlocks = false;
  6245. for (var [node] of matches) {
  6246. if (Element.isElement(node) && !editor.isInline(node)) {
  6247. starting = false;
  6248. hasBlocks = true;
  6249. middles.push(node);
  6250. } else if (starting) {
  6251. starts.push(node);
  6252. } else {
  6253. ends.push(node);
  6254. }
  6255. }
  6256. var [inlineMatch] = Editor.nodes(editor, {
  6257. at,
  6258. match: n => Text.isText(n) || Editor.isInline(editor, n),
  6259. mode: 'highest',
  6260. voids
  6261. });
  6262. var [, inlinePath] = inlineMatch;
  6263. var isInlineStart = Editor.isStart(editor, at, inlinePath);
  6264. var isInlineEnd = Editor.isEnd(editor, at, inlinePath);
  6265. var middleRef = Editor.pathRef(editor, isBlockEnd ? Path.next(blockPath) : blockPath);
  6266. var endRef = Editor.pathRef(editor, isInlineEnd ? Path.next(inlinePath) : inlinePath);
  6267. Transforms.splitNodes(editor, {
  6268. at,
  6269. match: n => hasBlocks ? Editor.isBlock(editor, n) : Text.isText(n) || Editor.isInline(editor, n),
  6270. mode: hasBlocks ? 'lowest' : 'highest',
  6271. voids
  6272. });
  6273. var startRef = Editor.pathRef(editor, !isInlineStart || isInlineStart && isInlineEnd ? Path.next(inlinePath) : inlinePath);
  6274. Transforms.insertNodes(editor, starts, {
  6275. at: startRef.current,
  6276. match: n => Text.isText(n) || Editor.isInline(editor, n),
  6277. mode: 'highest',
  6278. voids
  6279. });
  6280. Transforms.insertNodes(editor, middles, {
  6281. at: middleRef.current,
  6282. match: n => Editor.isBlock(editor, n),
  6283. mode: 'lowest',
  6284. voids
  6285. });
  6286. Transforms.insertNodes(editor, ends, {
  6287. at: endRef.current,
  6288. match: n => Text.isText(n) || Editor.isInline(editor, n),
  6289. mode: 'highest',
  6290. voids
  6291. });
  6292. if (!options.at) {
  6293. var path;
  6294. if (ends.length > 0) {
  6295. path = Path.previous(endRef.current);
  6296. } else if (middles.length > 0) {
  6297. path = Path.previous(middleRef.current);
  6298. } else {
  6299. path = Path.previous(startRef.current);
  6300. }
  6301. var _end = Editor.end(editor, path);
  6302. Transforms.select(editor, _end);
  6303. }
  6304. startRef.unref();
  6305. middleRef.unref();
  6306. endRef.unref();
  6307. });
  6308. },
  6309. /**
  6310. * Insert a string of text in the Editor.
  6311. */
  6312. insertText(editor, text) {
  6313. var options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
  6314. Editor.withoutNormalizing(editor, () => {
  6315. var {
  6316. voids = false
  6317. } = options;
  6318. var {
  6319. at = editor.selection
  6320. } = options;
  6321. if (!at) {
  6322. return;
  6323. }
  6324. if (Path.isPath(at)) {
  6325. at = Editor.range(editor, at);
  6326. }
  6327. if (Range.isRange(at)) {
  6328. if (Range.isCollapsed(at)) {
  6329. at = at.anchor;
  6330. } else {
  6331. var end = Range.end(at);
  6332. if (!voids && Editor.void(editor, {
  6333. at: end
  6334. })) {
  6335. return;
  6336. }
  6337. var pointRef = Editor.pointRef(editor, end);
  6338. Transforms.delete(editor, {
  6339. at,
  6340. voids
  6341. });
  6342. at = pointRef.unref();
  6343. Transforms.setSelection(editor, {
  6344. anchor: at,
  6345. focus: at
  6346. });
  6347. }
  6348. }
  6349. if (!voids && Editor.void(editor, {
  6350. at
  6351. })) {
  6352. return;
  6353. }
  6354. var {
  6355. path,
  6356. offset
  6357. } = at;
  6358. editor.apply({
  6359. type: 'insert_text',
  6360. path,
  6361. offset,
  6362. text
  6363. });
  6364. });
  6365. }
  6366. };
  6367. function ownKeys$8(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); keys.push.apply(keys, symbols); } return keys; }
  6368. function _objectSpread$8(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys$8(Object(source), true).forEach(function (key) { _defineProperty(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys$8(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; }
  6369. var Transforms = _objectSpread$8({}, GeneralTransforms, {}, NodeTransforms, {}, SelectionTransforms, {}, TextTransforms);
  6370. exports.Editor = Editor;
  6371. exports.Element = Element;
  6372. exports.Location = Location;
  6373. exports.Node = Node;
  6374. exports.Operation = Operation;
  6375. exports.Path = Path;
  6376. exports.PathRef = PathRef;
  6377. exports.Point = Point;
  6378. exports.PointRef = PointRef;
  6379. exports.Range = Range;
  6380. exports.RangeRef = RangeRef;
  6381. exports.Span = Span;
  6382. exports.Text = Text;
  6383. exports.Transforms = Transforms;
  6384. exports.createEditor = createEditor;
  6385. });
  6386. unwrapExports(dist);
  6387. var dist_1 = dist.Editor;
  6388. var dist_2 = dist.Element;
  6389. var dist_3 = dist.Location;
  6390. var dist_4 = dist.Node;
  6391. var dist_5 = dist.Operation;
  6392. var dist_6 = dist.Path;
  6393. var dist_7 = dist.PathRef;
  6394. var dist_8 = dist.Point;
  6395. var dist_9 = dist.PointRef;
  6396. var dist_10 = dist.Range;
  6397. var dist_11 = dist.RangeRef;
  6398. var dist_12 = dist.Span;
  6399. var dist_13 = dist.Text;
  6400. var dist_14 = dist.Transforms;
  6401. var dist_15 = dist.createEditor;
  6402. /**
  6403. * Returns a function, that, as long as it continues to be invoked, will not
  6404. * be triggered. The function will be called after it stops being called for
  6405. * N milliseconds. If `immediate` is passed, trigger the function on the
  6406. * leading edge, instead of the trailing. The function also has a property 'clear'
  6407. * that is a function which will clear the timer to prevent previously scheduled executions.
  6408. *
  6409. * @source underscore.js
  6410. * @see http://unscriptable.com/2009/03/20/debouncing-javascript-methods/
  6411. * @param {Function} function to wrap
  6412. * @param {Number} timeout in ms (`100`)
  6413. * @param {Boolean} whether to execute at the beginning (`false`)
  6414. * @api public
  6415. */
  6416. function debounce(func, wait, immediate){
  6417. var timeout, args, context, timestamp, result;
  6418. if (null == wait) wait = 100;
  6419. function later() {
  6420. var last = Date.now() - timestamp;
  6421. if (last < wait && last >= 0) {
  6422. timeout = setTimeout(later, wait - last);
  6423. } else {
  6424. timeout = null;
  6425. if (!immediate) {
  6426. result = func.apply(context, args);
  6427. context = args = null;
  6428. }
  6429. }
  6430. }
  6431. var debounced = function(){
  6432. context = this;
  6433. args = arguments;
  6434. timestamp = Date.now();
  6435. var callNow = immediate && !timeout;
  6436. if (!timeout) timeout = setTimeout(later, wait);
  6437. if (callNow) {
  6438. result = func.apply(context, args);
  6439. context = args = null;
  6440. }
  6441. return result;
  6442. };
  6443. debounced.clear = function() {
  6444. if (timeout) {
  6445. clearTimeout(timeout);
  6446. timeout = null;
  6447. }
  6448. };
  6449. debounced.flush = function() {
  6450. if (timeout) {
  6451. result = func.apply(context, args);
  6452. context = args = null;
  6453. clearTimeout(timeout);
  6454. timeout = null;
  6455. }
  6456. };
  6457. return debounced;
  6458. }
  6459. // Adds compatibility for ES modules
  6460. debounce.debounce = debounce;
  6461. var debounce_1 = debounce;
  6462. var computeScrollIntoView = createCommonjsModule(function (module, exports) {
  6463. exports.__esModule = true;
  6464. exports["default"] = void 0;
  6465. function isElement(el) {
  6466. return el != null && typeof el === 'object' && el.nodeType === 1;
  6467. }
  6468. function canOverflow(overflow, skipOverflowHiddenElements) {
  6469. if (skipOverflowHiddenElements && overflow === 'hidden') {
  6470. return false;
  6471. }
  6472. return overflow !== 'visible' && overflow !== 'clip';
  6473. }
  6474. function getFrameElement(el) {
  6475. if (!el.ownerDocument || !el.ownerDocument.defaultView) {
  6476. return null;
  6477. }
  6478. return el.ownerDocument.defaultView.frameElement;
  6479. }
  6480. function isHiddenByFrame(el) {
  6481. var frame = getFrameElement(el);
  6482. if (!frame) {
  6483. return false;
  6484. }
  6485. return frame.clientHeight < el.scrollHeight || frame.clientWidth < el.scrollWidth;
  6486. }
  6487. function isScrollable(el, skipOverflowHiddenElements) {
  6488. if (el.clientHeight < el.scrollHeight || el.clientWidth < el.scrollWidth) {
  6489. var style = getComputedStyle(el, null);
  6490. return canOverflow(style.overflowY, skipOverflowHiddenElements) || canOverflow(style.overflowX, skipOverflowHiddenElements) || isHiddenByFrame(el);
  6491. }
  6492. return false;
  6493. }
  6494. function alignNearest(scrollingEdgeStart, scrollingEdgeEnd, scrollingSize, scrollingBorderStart, scrollingBorderEnd, elementEdgeStart, elementEdgeEnd, elementSize) {
  6495. if (elementEdgeStart < scrollingEdgeStart && elementEdgeEnd > scrollingEdgeEnd || elementEdgeStart > scrollingEdgeStart && elementEdgeEnd < scrollingEdgeEnd) {
  6496. return 0;
  6497. }
  6498. if (elementEdgeStart <= scrollingEdgeStart && elementSize <= scrollingSize || elementEdgeEnd >= scrollingEdgeEnd && elementSize >= scrollingSize) {
  6499. return elementEdgeStart - scrollingEdgeStart - scrollingBorderStart;
  6500. }
  6501. if (elementEdgeEnd > scrollingEdgeEnd && elementSize < scrollingSize || elementEdgeStart < scrollingEdgeStart && elementSize > scrollingSize) {
  6502. return elementEdgeEnd - scrollingEdgeEnd + scrollingBorderEnd;
  6503. }
  6504. return 0;
  6505. }
  6506. var _default = function _default(target, options) {
  6507. var scrollMode = options.scrollMode,
  6508. block = options.block,
  6509. inline = options.inline,
  6510. boundary = options.boundary,
  6511. skipOverflowHiddenElements = options.skipOverflowHiddenElements;
  6512. var checkBoundary = typeof boundary === 'function' ? boundary : function (node) {
  6513. return node !== boundary;
  6514. };
  6515. if (!isElement(target)) {
  6516. throw new TypeError('Invalid target');
  6517. }
  6518. var scrollingElement = document.scrollingElement || document.documentElement;
  6519. var frames = [];
  6520. var cursor = target;
  6521. while (isElement(cursor) && checkBoundary(cursor)) {
  6522. cursor = cursor.parentNode;
  6523. if (cursor === scrollingElement) {
  6524. frames.push(cursor);
  6525. break;
  6526. }
  6527. if (cursor === document.body && isScrollable(cursor) && !isScrollable(document.documentElement)) {
  6528. continue;
  6529. }
  6530. if (isScrollable(cursor, skipOverflowHiddenElements)) {
  6531. frames.push(cursor);
  6532. }
  6533. }
  6534. var viewportWidth = window.visualViewport ? visualViewport.width : innerWidth;
  6535. var viewportHeight = window.visualViewport ? visualViewport.height : innerHeight;
  6536. var viewportX = window.scrollX || pageXOffset;
  6537. var viewportY = window.scrollY || pageYOffset;
  6538. var _target$getBoundingCl = target.getBoundingClientRect(),
  6539. targetHeight = _target$getBoundingCl.height,
  6540. targetWidth = _target$getBoundingCl.width,
  6541. targetTop = _target$getBoundingCl.top,
  6542. targetRight = _target$getBoundingCl.right,
  6543. targetBottom = _target$getBoundingCl.bottom,
  6544. targetLeft = _target$getBoundingCl.left;
  6545. var targetBlock = block === 'start' || block === 'nearest' ? targetTop : block === 'end' ? targetBottom : targetTop + targetHeight / 2;
  6546. var targetInline = inline === 'center' ? targetLeft + targetWidth / 2 : inline === 'end' ? targetRight : targetLeft;
  6547. var computations = [];
  6548. for (var index = 0; index < frames.length; index++) {
  6549. var frame = frames[index];
  6550. var _frame$getBoundingCli = frame.getBoundingClientRect(),
  6551. height = _frame$getBoundingCli.height,
  6552. width = _frame$getBoundingCli.width,
  6553. top = _frame$getBoundingCli.top,
  6554. right = _frame$getBoundingCli.right,
  6555. bottom = _frame$getBoundingCli.bottom,
  6556. left = _frame$getBoundingCli.left;
  6557. if (scrollMode === 'if-needed' && targetTop >= 0 && targetLeft >= 0 && targetBottom <= viewportHeight && targetRight <= viewportWidth && targetTop >= top && targetBottom <= bottom && targetLeft >= left && targetRight <= right) {
  6558. return computations;
  6559. }
  6560. var frameStyle = getComputedStyle(frame);
  6561. var borderLeft = parseInt(frameStyle.borderLeftWidth, 10);
  6562. var borderTop = parseInt(frameStyle.borderTopWidth, 10);
  6563. var borderRight = parseInt(frameStyle.borderRightWidth, 10);
  6564. var borderBottom = parseInt(frameStyle.borderBottomWidth, 10);
  6565. var blockScroll = 0;
  6566. var inlineScroll = 0;
  6567. var scrollbarWidth = 'offsetWidth' in frame ? frame.offsetWidth - frame.clientWidth - borderLeft - borderRight : 0;
  6568. var scrollbarHeight = 'offsetHeight' in frame ? frame.offsetHeight - frame.clientHeight - borderTop - borderBottom : 0;
  6569. if (scrollingElement === frame) {
  6570. if (block === 'start') {
  6571. blockScroll = targetBlock;
  6572. } else if (block === 'end') {
  6573. blockScroll = targetBlock - viewportHeight;
  6574. } else if (block === 'nearest') {
  6575. blockScroll = alignNearest(viewportY, viewportY + viewportHeight, viewportHeight, borderTop, borderBottom, viewportY + targetBlock, viewportY + targetBlock + targetHeight, targetHeight);
  6576. } else {
  6577. blockScroll = targetBlock - viewportHeight / 2;
  6578. }
  6579. if (inline === 'start') {
  6580. inlineScroll = targetInline;
  6581. } else if (inline === 'center') {
  6582. inlineScroll = targetInline - viewportWidth / 2;
  6583. } else if (inline === 'end') {
  6584. inlineScroll = targetInline - viewportWidth;
  6585. } else {
  6586. inlineScroll = alignNearest(viewportX, viewportX + viewportWidth, viewportWidth, borderLeft, borderRight, viewportX + targetInline, viewportX + targetInline + targetWidth, targetWidth);
  6587. }
  6588. blockScroll = Math.max(0, blockScroll + viewportY);
  6589. inlineScroll = Math.max(0, inlineScroll + viewportX);
  6590. } else {
  6591. if (block === 'start') {
  6592. blockScroll = targetBlock - top - borderTop;
  6593. } else if (block === 'end') {
  6594. blockScroll = targetBlock - bottom + borderBottom + scrollbarHeight;
  6595. } else if (block === 'nearest') {
  6596. blockScroll = alignNearest(top, bottom, height, borderTop, borderBottom + scrollbarHeight, targetBlock, targetBlock + targetHeight, targetHeight);
  6597. } else {
  6598. blockScroll = targetBlock - (top + height / 2) + scrollbarHeight / 2;
  6599. }
  6600. if (inline === 'start') {
  6601. inlineScroll = targetInline - left - borderLeft;
  6602. } else if (inline === 'center') {
  6603. inlineScroll = targetInline - (left + width / 2) + scrollbarWidth / 2;
  6604. } else if (inline === 'end') {
  6605. inlineScroll = targetInline - right + borderRight + scrollbarWidth;
  6606. } else {
  6607. inlineScroll = alignNearest(left, right, width, borderLeft, borderRight + scrollbarWidth, targetInline, targetInline + targetWidth, targetWidth);
  6608. }
  6609. var scrollLeft = frame.scrollLeft,
  6610. scrollTop = frame.scrollTop;
  6611. blockScroll = Math.max(0, Math.min(scrollTop + blockScroll, frame.scrollHeight - height + scrollbarHeight));
  6612. inlineScroll = Math.max(0, Math.min(scrollLeft + inlineScroll, frame.scrollWidth - width + scrollbarWidth));
  6613. targetBlock += scrollTop - blockScroll;
  6614. targetInline += scrollLeft - inlineScroll;
  6615. }
  6616. computations.push({
  6617. el: frame,
  6618. top: blockScroll,
  6619. left: inlineScroll
  6620. });
  6621. }
  6622. return computations;
  6623. };
  6624. exports["default"] = _default;
  6625. module.exports = exports.default;
  6626. });
  6627. unwrapExports(computeScrollIntoView);
  6628. var scrollIntoViewIfNeeded = createCommonjsModule(function (module, exports) {
  6629. exports.__esModule = true;
  6630. exports["default"] = void 0;
  6631. var _computeScrollIntoView = _interopRequireDefault(computeScrollIntoView);
  6632. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
  6633. function isOptionsObject(options) {
  6634. return options === Object(options) && Object.keys(options).length !== 0;
  6635. }
  6636. function defaultBehavior(actions, behavior) {
  6637. if (behavior === void 0) {
  6638. behavior = 'auto';
  6639. }
  6640. var canSmoothScroll = 'scrollBehavior' in document.body.style;
  6641. actions.forEach(function (_ref) {
  6642. var el = _ref.el,
  6643. top = _ref.top,
  6644. left = _ref.left;
  6645. if (el.scroll && canSmoothScroll) {
  6646. el.scroll({
  6647. top: top,
  6648. left: left,
  6649. behavior: behavior
  6650. });
  6651. } else {
  6652. el.scrollTop = top;
  6653. el.scrollLeft = left;
  6654. }
  6655. });
  6656. }
  6657. function getOptions(options) {
  6658. if (options === false) {
  6659. return {
  6660. block: 'end',
  6661. inline: 'nearest'
  6662. };
  6663. }
  6664. if (isOptionsObject(options)) {
  6665. return options;
  6666. }
  6667. return {
  6668. block: 'start',
  6669. inline: 'nearest'
  6670. };
  6671. }
  6672. function scrollIntoView(target, options) {
  6673. var targetIsDetached = !target.ownerDocument.documentElement.contains(target);
  6674. if (isOptionsObject(options) && typeof options.behavior === 'function') {
  6675. return options.behavior(targetIsDetached ? [] : (0, _computeScrollIntoView["default"])(target, options));
  6676. }
  6677. if (targetIsDetached) {
  6678. return;
  6679. }
  6680. var computeOptions = getOptions(options);
  6681. return defaultBehavior((0, _computeScrollIntoView["default"])(target, computeOptions), computeOptions.behavior);
  6682. }
  6683. var _default = scrollIntoView;
  6684. exports["default"] = _default;
  6685. module.exports = exports.default;
  6686. });
  6687. unwrapExports(scrollIntoViewIfNeeded);
  6688. var direction_1 = direction;
  6689. var RTL = '\u0591-\u07FF\uFB1D-\uFDFD\uFE70-\uFEFC';
  6690. var LTR =
  6691. 'A-Za-z\u00C0-\u00D6\u00D8-\u00F6' +
  6692. '\u00F8-\u02B8\u0300-\u0590\u0800-\u1FFF\u200E\u2C00-\uFB1C' +
  6693. '\uFE00-\uFE6F\uFEFD-\uFFFF';
  6694. var rtl = new RegExp('^[^' + LTR + ']*[' + RTL + ']');
  6695. var ltr = new RegExp('^[^' + RTL + ']*[' + LTR + ']');
  6696. function direction(value) {
  6697. value = String(value || '');
  6698. if (rtl.test(value)) {
  6699. return 'rtl'
  6700. }
  6701. if (ltr.test(value)) {
  6702. return 'ltr'
  6703. }
  6704. return 'neutral'
  6705. }
  6706. var lib = createCommonjsModule(function (module, exports) {
  6707. Object.defineProperty(exports, "__esModule", {
  6708. value: true
  6709. });
  6710. /**
  6711. * Constants.
  6712. */
  6713. var IS_MAC = typeof window != 'undefined' && /Mac|iPod|iPhone|iPad/.test(window.navigator.platform);
  6714. var MODIFIERS = {
  6715. alt: 'altKey',
  6716. control: 'ctrlKey',
  6717. meta: 'metaKey',
  6718. shift: 'shiftKey'
  6719. };
  6720. var ALIASES = {
  6721. add: '+',
  6722. break: 'pause',
  6723. cmd: 'meta',
  6724. command: 'meta',
  6725. ctl: 'control',
  6726. ctrl: 'control',
  6727. del: 'delete',
  6728. down: 'arrowdown',
  6729. esc: 'escape',
  6730. ins: 'insert',
  6731. left: 'arrowleft',
  6732. mod: IS_MAC ? 'meta' : 'control',
  6733. opt: 'alt',
  6734. option: 'alt',
  6735. return: 'enter',
  6736. right: 'arrowright',
  6737. space: ' ',
  6738. spacebar: ' ',
  6739. up: 'arrowup',
  6740. win: 'meta',
  6741. windows: 'meta'
  6742. };
  6743. var CODES = {
  6744. backspace: 8,
  6745. tab: 9,
  6746. enter: 13,
  6747. shift: 16,
  6748. control: 17,
  6749. alt: 18,
  6750. pause: 19,
  6751. capslock: 20,
  6752. escape: 27,
  6753. ' ': 32,
  6754. pageup: 33,
  6755. pagedown: 34,
  6756. end: 35,
  6757. home: 36,
  6758. arrowleft: 37,
  6759. arrowup: 38,
  6760. arrowright: 39,
  6761. arrowdown: 40,
  6762. insert: 45,
  6763. delete: 46,
  6764. meta: 91,
  6765. numlock: 144,
  6766. scrolllock: 145,
  6767. ';': 186,
  6768. '=': 187,
  6769. ',': 188,
  6770. '-': 189,
  6771. '.': 190,
  6772. '/': 191,
  6773. '`': 192,
  6774. '[': 219,
  6775. '\\': 220,
  6776. ']': 221,
  6777. '\'': 222
  6778. };
  6779. for (var f = 1; f < 20; f++) {
  6780. CODES['f' + f] = 111 + f;
  6781. }
  6782. /**
  6783. * Is hotkey?
  6784. */
  6785. function isHotkey(hotkey, options, event) {
  6786. if (options && !('byKey' in options)) {
  6787. event = options;
  6788. options = null;
  6789. }
  6790. if (!Array.isArray(hotkey)) {
  6791. hotkey = [hotkey];
  6792. }
  6793. var array = hotkey.map(function (string) {
  6794. return parseHotkey(string, options);
  6795. });
  6796. var check = function check(e) {
  6797. return array.some(function (object) {
  6798. return compareHotkey(object, e);
  6799. });
  6800. };
  6801. var ret = event == null ? check : check(event);
  6802. return ret;
  6803. }
  6804. function isCodeHotkey(hotkey, event) {
  6805. return isHotkey(hotkey, event);
  6806. }
  6807. function isKeyHotkey(hotkey, event) {
  6808. return isHotkey(hotkey, { byKey: true }, event);
  6809. }
  6810. /**
  6811. * Parse.
  6812. */
  6813. function parseHotkey(hotkey, options) {
  6814. var byKey = options && options.byKey;
  6815. var ret = {};
  6816. // Special case to handle the `+` key since we use it as a separator.
  6817. hotkey = hotkey.replace('++', '+add');
  6818. var values = hotkey.split('+');
  6819. var length = values.length;
  6820. // Ensure that all the modifiers are set to false unless the hotkey has them.
  6821. for (var k in MODIFIERS) {
  6822. ret[MODIFIERS[k]] = false;
  6823. }
  6824. var _iteratorNormalCompletion = true;
  6825. var _didIteratorError = false;
  6826. var _iteratorError = undefined;
  6827. try {
  6828. for (var _iterator = values[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) {
  6829. var value = _step.value;
  6830. var optional = value.endsWith('?') && value.length > 1;
  6831. if (optional) {
  6832. value = value.slice(0, -1);
  6833. }
  6834. var name = toKeyName(value);
  6835. var modifier = MODIFIERS[name];
  6836. if (length === 1 || !modifier) {
  6837. if (byKey) {
  6838. ret.key = name;
  6839. } else {
  6840. ret.which = toKeyCode(value);
  6841. }
  6842. }
  6843. if (modifier) {
  6844. ret[modifier] = optional ? null : true;
  6845. }
  6846. }
  6847. } catch (err) {
  6848. _didIteratorError = true;
  6849. _iteratorError = err;
  6850. } finally {
  6851. try {
  6852. if (!_iteratorNormalCompletion && _iterator.return) {
  6853. _iterator.return();
  6854. }
  6855. } finally {
  6856. if (_didIteratorError) {
  6857. throw _iteratorError;
  6858. }
  6859. }
  6860. }
  6861. return ret;
  6862. }
  6863. /**
  6864. * Compare.
  6865. */
  6866. function compareHotkey(object, event) {
  6867. for (var key in object) {
  6868. var expected = object[key];
  6869. var actual = void 0;
  6870. if (expected == null) {
  6871. continue;
  6872. }
  6873. if (key === 'key' && event.key != null) {
  6874. actual = event.key.toLowerCase();
  6875. } else if (key === 'which') {
  6876. actual = expected === 91 && event.which === 93 ? 91 : event.which;
  6877. } else {
  6878. actual = event[key];
  6879. }
  6880. if (actual == null && expected === false) {
  6881. continue;
  6882. }
  6883. if (actual !== expected) {
  6884. return false;
  6885. }
  6886. }
  6887. return true;
  6888. }
  6889. /**
  6890. * Utils.
  6891. */
  6892. function toKeyCode(name) {
  6893. name = toKeyName(name);
  6894. var code = CODES[name] || name.toUpperCase().charCodeAt(0);
  6895. return code;
  6896. }
  6897. function toKeyName(name) {
  6898. name = name.toLowerCase();
  6899. name = ALIASES[name] || name;
  6900. return name;
  6901. }
  6902. /**
  6903. * Export.
  6904. */
  6905. exports.default = isHotkey;
  6906. exports.isHotkey = isHotkey;
  6907. exports.isCodeHotkey = isCodeHotkey;
  6908. exports.isKeyHotkey = isKeyHotkey;
  6909. exports.parseHotkey = parseHotkey;
  6910. exports.compareHotkey = compareHotkey;
  6911. exports.toKeyCode = toKeyCode;
  6912. exports.toKeyName = toKeyName;
  6913. });
  6914. unwrapExports(lib);
  6915. var lib_1 = lib.isHotkey;
  6916. var lib_2 = lib.isCodeHotkey;
  6917. var lib_3 = lib.isKeyHotkey;
  6918. var lib_4 = lib.parseHotkey;
  6919. var lib_5 = lib.compareHotkey;
  6920. var lib_6 = lib.toKeyCode;
  6921. var lib_7 = lib.toKeyName;
  6922. var dist$1 = createCommonjsModule(function (module, exports) {
  6923. Object.defineProperty(exports, '__esModule', { value: true });
  6924. function _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; }
  6925. var React__default = _interopDefault(React$1);
  6926. var debounce = _interopDefault(debounce_1);
  6927. var scrollIntoView = _interopDefault(scrollIntoViewIfNeeded);
  6928. var getDirection = _interopDefault(direction_1);
  6929. var ReactDOM = _interopDefault(require$$3);
  6930. /**
  6931. * Leaf content strings.
  6932. */
  6933. const String = (props) => {
  6934. const { isLast, leaf, parent, text } = props;
  6935. const editor = useEditor();
  6936. const path = ReactEditor.findPath(editor, text);
  6937. const parentPath = dist.Path.parent(path);
  6938. // COMPAT: Render text inside void nodes with a zero-width space.
  6939. // So the node can contain selection but the text is not visible.
  6940. if (editor.isVoid(parent)) {
  6941. return React__default.createElement(ZeroWidthString, { length: dist.Node.string(parent).length });
  6942. }
  6943. // COMPAT: If this is the last text node in an empty block, render a zero-
  6944. // width space that will convert into a line break when copying and pasting
  6945. // to support expected plain text.
  6946. if (leaf.text === '' &&
  6947. parent.children[parent.children.length - 1] === text &&
  6948. !editor.isInline(parent) &&
  6949. dist.Editor.string(editor, parentPath) === '') {
  6950. return React__default.createElement(ZeroWidthString, { isLineBreak: true });
  6951. }
  6952. // COMPAT: If the text is empty, it's because it's on the edge of an inline
  6953. // node, so we render a zero-width space so that the selection can be
  6954. // inserted next to it still.
  6955. if (leaf.text === '') {
  6956. return React__default.createElement(ZeroWidthString, null);
  6957. }
  6958. // COMPAT: Browsers will collapse trailing new lines at the end of blocks,
  6959. // so we need to add an extra trailing new lines to prevent that.
  6960. if (isLast && leaf.text.slice(-1) === '\n') {
  6961. return React__default.createElement(TextString, { isTrailing: true, text: leaf.text });
  6962. }
  6963. return React__default.createElement(TextString, { text: leaf.text });
  6964. };
  6965. /**
  6966. * Leaf strings with text in them.
  6967. */
  6968. const TextString = (props) => {
  6969. const { text, isTrailing = false } = props;
  6970. return (React__default.createElement("span", { "data-slate-string": true },
  6971. text,
  6972. isTrailing ? '\n' : null));
  6973. };
  6974. /**
  6975. * Leaf strings without text, render as zero-width strings.
  6976. */
  6977. const ZeroWidthString = (props) => {
  6978. const { length = 0, isLineBreak = false } = props;
  6979. return (React__default.createElement("span", { "data-slate-zero-width": isLineBreak ? 'n' : 'z', "data-slate-length": length },
  6980. '\uFEFF',
  6981. isLineBreak ? React__default.createElement("br", null) : null));
  6982. };
  6983. /**
  6984. * Two weak maps that allow us rebuild a path given a node. They are populated
  6985. * at render time such that after a render occurs we can always backtrack.
  6986. */
  6987. var NODE_TO_INDEX = new WeakMap();
  6988. var NODE_TO_PARENT = new WeakMap();
  6989. /**
  6990. * Weak maps that allow us to go between Slate nodes and DOM nodes. These
  6991. * are used to resolve DOM event-related logic into Slate actions.
  6992. */
  6993. var EDITOR_TO_ELEMENT = new WeakMap();
  6994. var ELEMENT_TO_NODE = new WeakMap();
  6995. var KEY_TO_ELEMENT = new WeakMap();
  6996. var NODE_TO_ELEMENT = new WeakMap();
  6997. var NODE_TO_KEY = new WeakMap();
  6998. /**
  6999. * Weak maps for storing editor-related state.
  7000. */
  7001. var IS_READ_ONLY = new WeakMap();
  7002. var IS_FOCUSED = new WeakMap();
  7003. /**
  7004. * Weak map for associating the context `onChange` context with the plugin.
  7005. */
  7006. var EDITOR_TO_ON_CHANGE = new WeakMap();
  7007. /**
  7008. * Symbols.
  7009. */
  7010. var PLACEHOLDER_SYMBOL = Symbol('placeholder');
  7011. /**
  7012. * Individual leaves in a text node with unique formatting.
  7013. */
  7014. const Leaf = (props) => {
  7015. const { leaf, isLast, text, parent, renderLeaf = (props) => React__default.createElement(DefaultLeaf, Object.assign({}, props)), } = props;
  7016. let children = (React__default.createElement(String, { isLast: isLast, leaf: leaf, parent: parent, text: text }));
  7017. if (leaf[PLACEHOLDER_SYMBOL]) {
  7018. children = (React__default.createElement(React__default.Fragment, null,
  7019. React__default.createElement("span", { contentEditable: false, style: {
  7020. pointerEvents: 'none',
  7021. display: 'inline-block',
  7022. verticalAlign: 'text-top',
  7023. width: '0',
  7024. maxWidth: '100%',
  7025. whiteSpace: 'nowrap',
  7026. opacity: '0.333',
  7027. } }, leaf.placeholder),
  7028. children));
  7029. }
  7030. // COMPAT: Having the `data-` attributes on these leaf elements ensures that
  7031. // in certain misbehaving browsers they aren't weirdly cloned/destroyed by
  7032. // contenteditable behaviors. (2019/05/08)
  7033. const attributes = {
  7034. 'data-slate-leaf': true,
  7035. };
  7036. return renderLeaf({ attributes, children, leaf, text });
  7037. };
  7038. const MemoizedLeaf = React__default.memo(Leaf, (prev, next) => {
  7039. return (next.parent === prev.parent &&
  7040. next.isLast === prev.isLast &&
  7041. next.renderLeaf === prev.renderLeaf &&
  7042. next.text === prev.text &&
  7043. dist.Text.matches(next.leaf, prev.leaf));
  7044. });
  7045. /**
  7046. * The default custom leaf renderer.
  7047. */
  7048. const DefaultLeaf = (props) => {
  7049. const { attributes, children } = props;
  7050. return React__default.createElement("span", Object.assign({}, attributes), children);
  7051. };
  7052. /**
  7053. * Prevent warning on SSR by falling back to useEffect when window is not defined
  7054. */
  7055. var useIsomorphicLayoutEffect = typeof window !== 'undefined' ? React$1.useLayoutEffect : React$1.useEffect;
  7056. /**
  7057. * Text.
  7058. */
  7059. const Text = (props) => {
  7060. const { decorations, isLast, parent, renderLeaf, text } = props;
  7061. const editor = useEditor();
  7062. const ref = React$1.useRef(null);
  7063. const leaves = dist.Text.decorations(text, decorations);
  7064. const key = ReactEditor.findKey(editor, text);
  7065. const children = [];
  7066. for (let i = 0; i < leaves.length; i++) {
  7067. const leaf = leaves[i];
  7068. children.push(React__default.createElement(MemoizedLeaf, { isLast: isLast && i === leaves.length - 1, key: `${key.id}-${i}`, leaf: leaf, text: text, parent: parent, renderLeaf: renderLeaf }));
  7069. }
  7070. // Update element-related weak maps with the DOM element ref.
  7071. useIsomorphicLayoutEffect(() => {
  7072. if (ref.current) {
  7073. KEY_TO_ELEMENT.set(key, ref.current);
  7074. NODE_TO_ELEMENT.set(text, ref.current);
  7075. ELEMENT_TO_NODE.set(ref.current, text);
  7076. }
  7077. else {
  7078. KEY_TO_ELEMENT.delete(key);
  7079. NODE_TO_ELEMENT.delete(text);
  7080. }
  7081. });
  7082. return (React__default.createElement("span", { "data-slate-node": "text", ref: ref }, children));
  7083. };
  7084. const MemoizedText = React__default.memo(Text, (prev, next) => {
  7085. return (next.parent === prev.parent &&
  7086. next.isLast === prev.isLast &&
  7087. next.renderLeaf === prev.renderLeaf &&
  7088. next.text === prev.text);
  7089. });
  7090. /**
  7091. * A React context for sharing the `selected` state of an element.
  7092. */
  7093. var SelectedContext = React$1.createContext(false);
  7094. /**
  7095. * Get the current `selected` state of an element.
  7096. */
  7097. var useSelected = () => {
  7098. return React$1.useContext(SelectedContext);
  7099. };
  7100. /**
  7101. * Element.
  7102. */
  7103. const Element = (props) => {
  7104. const { decorate, decorations, element, renderElement = (p) => React__default.createElement(DefaultElement, Object.assign({}, p)), renderLeaf, selection, } = props;
  7105. const ref = React$1.useRef(null);
  7106. const editor = useEditor();
  7107. const readOnly = useReadOnly();
  7108. const isInline = editor.isInline(element);
  7109. const key = ReactEditor.findKey(editor, element);
  7110. let children = (React__default.createElement(Children, { decorate: decorate, decorations: decorations, node: element, renderElement: renderElement, renderLeaf: renderLeaf, selection: selection }));
  7111. // Attributes that the developer must mix into the element in their
  7112. // custom node renderer component.
  7113. const attributes = {
  7114. 'data-slate-node': 'element',
  7115. ref,
  7116. };
  7117. if (isInline) {
  7118. attributes['data-slate-inline'] = true;
  7119. }
  7120. // If it's a block node with inline children, add the proper `dir` attribute
  7121. // for text direction.
  7122. if (!isInline && dist.Editor.hasInlines(editor, element)) {
  7123. const text = dist.Node.string(element);
  7124. const dir = getDirection(text);
  7125. if (dir === 'rtl') {
  7126. attributes.dir = dir;
  7127. }
  7128. }
  7129. // If it's a void node, wrap the children in extra void-specific elements.
  7130. if (dist.Editor.isVoid(editor, element)) {
  7131. attributes['data-slate-void'] = true;
  7132. if (!readOnly && isInline) {
  7133. attributes.contentEditable = false;
  7134. }
  7135. const Tag = isInline ? 'span' : 'div';
  7136. const [[text]] = dist.Node.texts(element);
  7137. children = readOnly ? null : (React__default.createElement(Tag, { "data-slate-spacer": true, style: {
  7138. height: '0',
  7139. color: 'transparent',
  7140. outline: 'none',
  7141. position: 'absolute',
  7142. } },
  7143. React__default.createElement(MemoizedText, { decorations: [], isLast: false, parent: element, text: text })));
  7144. NODE_TO_INDEX.set(text, 0);
  7145. NODE_TO_PARENT.set(text, element);
  7146. }
  7147. // Update element-related weak maps with the DOM element ref.
  7148. useIsomorphicLayoutEffect(() => {
  7149. if (ref.current) {
  7150. KEY_TO_ELEMENT.set(key, ref.current);
  7151. NODE_TO_ELEMENT.set(element, ref.current);
  7152. ELEMENT_TO_NODE.set(ref.current, element);
  7153. }
  7154. else {
  7155. KEY_TO_ELEMENT.delete(key);
  7156. NODE_TO_ELEMENT.delete(element);
  7157. }
  7158. });
  7159. return (React__default.createElement(SelectedContext.Provider, { value: !!selection }, renderElement({ attributes, children, element })));
  7160. };
  7161. const MemoizedElement = React__default.memo(Element, (prev, next) => {
  7162. return (prev.decorate === next.decorate &&
  7163. prev.element === next.element &&
  7164. prev.renderElement === next.renderElement &&
  7165. prev.renderLeaf === next.renderLeaf &&
  7166. isRangeListEqual(prev.decorations, next.decorations) &&
  7167. (prev.selection === next.selection ||
  7168. (!!prev.selection &&
  7169. !!next.selection &&
  7170. dist.Range.equals(prev.selection, next.selection))));
  7171. });
  7172. /**
  7173. * The default element renderer.
  7174. */
  7175. const DefaultElement = (props) => {
  7176. const { attributes, children, element } = props;
  7177. const editor = useEditor();
  7178. const Tag = editor.isInline(element) ? 'span' : 'div';
  7179. return (React__default.createElement(Tag, Object.assign({}, attributes, { style: { position: 'relative' } }), children));
  7180. };
  7181. /**
  7182. * Check if a list of ranges is equal to another.
  7183. *
  7184. * PERF: this requires the two lists to also have the ranges inside them in the
  7185. * same order, but this is an okay constraint for us since decorations are
  7186. * kept in order, and the odd case where they aren't is okay to re-render for.
  7187. */
  7188. const isRangeListEqual = (list, another) => {
  7189. if (list.length !== another.length) {
  7190. return false;
  7191. }
  7192. for (let i = 0; i < list.length; i++) {
  7193. const range = list[i];
  7194. const other = another[i];
  7195. if (!dist.Range.equals(range, other)) {
  7196. return false;
  7197. }
  7198. }
  7199. return true;
  7200. };
  7201. /**
  7202. * A React context for sharing the editor object.
  7203. */
  7204. const EditorContext = React$1.createContext(null);
  7205. /**
  7206. * Get the current editor object from the React context.
  7207. */
  7208. const useEditor = () => {
  7209. const editor = React$1.useContext(EditorContext);
  7210. if (!editor) {
  7211. throw new Error(`The \`useEditor\` hook must be used inside the <Slate> component's context.`);
  7212. }
  7213. return editor;
  7214. };
  7215. /**
  7216. * Children.
  7217. */
  7218. const Children = (props) => {
  7219. const { decorate, decorations, node, renderElement, renderLeaf, selection, } = props;
  7220. const editor = useEditor();
  7221. const path = ReactEditor.findPath(editor, node);
  7222. const children = [];
  7223. const isLeafBlock = dist.Element.isElement(node) &&
  7224. !editor.isInline(node) &&
  7225. dist.Editor.hasInlines(editor, node);
  7226. for (let i = 0; i < node.children.length; i++) {
  7227. const p = path.concat(i);
  7228. const n = node.children[i];
  7229. const key = ReactEditor.findKey(editor, n);
  7230. const range = dist.Editor.range(editor, p);
  7231. const sel = selection && dist.Range.intersection(range, selection);
  7232. const ds = decorate([n, p]);
  7233. for (const dec of decorations) {
  7234. const d = dist.Range.intersection(dec, range);
  7235. if (d) {
  7236. ds.push(d);
  7237. }
  7238. }
  7239. if (dist.Element.isElement(n)) {
  7240. children.push(React__default.createElement(MemoizedElement, { decorate: decorate, decorations: ds, element: n, key: key.id, renderElement: renderElement, renderLeaf: renderLeaf, selection: sel }));
  7241. }
  7242. else {
  7243. children.push(React__default.createElement(MemoizedText, { decorations: ds, key: key.id, isLast: isLeafBlock && i === node.children.length - 1, parent: node, renderLeaf: renderLeaf, text: n }));
  7244. }
  7245. NODE_TO_INDEX.set(n, i);
  7246. NODE_TO_PARENT.set(n, node);
  7247. }
  7248. return React__default.createElement(React__default.Fragment, null, children);
  7249. };
  7250. var IS_IOS = typeof navigator !== 'undefined' && typeof window !== 'undefined' && /iPad|iPhone|iPod/.test(navigator.userAgent) && !window.MSStream;
  7251. var IS_APPLE = typeof navigator !== 'undefined' && /Mac OS X/.test(navigator.userAgent);
  7252. var IS_FIREFOX = typeof navigator !== 'undefined' && /^(?!.*Seamonkey)(?=.*Firefox).*/i.test(navigator.userAgent);
  7253. var IS_SAFARI = typeof navigator !== 'undefined' && /Version\/[\d\.]+.*Safari/.test(navigator.userAgent);
  7254. /**
  7255. * Hotkey mappings for each platform.
  7256. */
  7257. var HOTKEYS = {
  7258. bold: 'mod+b',
  7259. compose: ['down', 'left', 'right', 'up', 'backspace', 'enter'],
  7260. moveBackward: 'left',
  7261. moveForward: 'right',
  7262. moveWordBackward: 'ctrl+left',
  7263. moveWordForward: 'ctrl+right',
  7264. deleteBackward: 'shift?+backspace',
  7265. deleteForward: 'shift?+delete',
  7266. extendBackward: 'shift+left',
  7267. extendForward: 'shift+right',
  7268. italic: 'mod+i',
  7269. splitBlock: 'shift?+enter',
  7270. undo: 'mod+z'
  7271. };
  7272. var APPLE_HOTKEYS = {
  7273. moveLineBackward: 'opt+up',
  7274. moveLineForward: 'opt+down',
  7275. moveWordBackward: 'opt+left',
  7276. moveWordForward: 'opt+right',
  7277. deleteBackward: ['ctrl+backspace', 'ctrl+h'],
  7278. deleteForward: ['ctrl+delete', 'ctrl+d'],
  7279. deleteLineBackward: 'cmd+shift?+backspace',
  7280. deleteLineForward: ['cmd+shift?+delete', 'ctrl+k'],
  7281. deleteWordBackward: 'opt+shift?+backspace',
  7282. deleteWordForward: 'opt+shift?+delete',
  7283. extendLineBackward: 'opt+shift+up',
  7284. extendLineForward: 'opt+shift+down',
  7285. redo: 'cmd+shift+z',
  7286. transposeCharacter: 'ctrl+t'
  7287. };
  7288. var WINDOWS_HOTKEYS = {
  7289. deleteWordBackward: 'ctrl+shift?+backspace',
  7290. deleteWordForward: 'ctrl+shift?+delete',
  7291. redo: ['ctrl+y', 'ctrl+shift+z']
  7292. };
  7293. /**
  7294. * Create a platform-aware hotkey checker.
  7295. */
  7296. var create = key => {
  7297. var generic = HOTKEYS[key];
  7298. var apple = APPLE_HOTKEYS[key];
  7299. var windows = WINDOWS_HOTKEYS[key];
  7300. var isGeneric = generic && lib.isKeyHotkey(generic);
  7301. var isApple = apple && lib.isKeyHotkey(apple);
  7302. var isWindows = windows && lib.isKeyHotkey(windows);
  7303. return event => {
  7304. if (isGeneric && isGeneric(event)) return true;
  7305. if (IS_APPLE && isApple && isApple(event)) return true;
  7306. if (!IS_APPLE && isWindows && isWindows(event)) return true;
  7307. return false;
  7308. };
  7309. };
  7310. /**
  7311. * Hotkeys.
  7312. */
  7313. var Hotkeys = {
  7314. isBold: create('bold'),
  7315. isCompose: create('compose'),
  7316. isMoveBackward: create('moveBackward'),
  7317. isMoveForward: create('moveForward'),
  7318. isDeleteBackward: create('deleteBackward'),
  7319. isDeleteForward: create('deleteForward'),
  7320. isDeleteLineBackward: create('deleteLineBackward'),
  7321. isDeleteLineForward: create('deleteLineForward'),
  7322. isDeleteWordBackward: create('deleteWordBackward'),
  7323. isDeleteWordForward: create('deleteWordForward'),
  7324. isExtendBackward: create('extendBackward'),
  7325. isExtendForward: create('extendForward'),
  7326. isExtendLineBackward: create('extendLineBackward'),
  7327. isExtendLineForward: create('extendLineForward'),
  7328. isItalic: create('italic'),
  7329. isMoveLineBackward: create('moveLineBackward'),
  7330. isMoveLineForward: create('moveLineForward'),
  7331. isMoveWordBackward: create('moveWordBackward'),
  7332. isMoveWordForward: create('moveWordForward'),
  7333. isRedo: create('redo'),
  7334. isSplitBlock: create('splitBlock'),
  7335. isTransposeCharacter: create('transposeCharacter'),
  7336. isUndo: create('undo')
  7337. };
  7338. /**
  7339. * A React context for sharing the `readOnly` state of the editor.
  7340. */
  7341. var ReadOnlyContext = React$1.createContext(false);
  7342. /**
  7343. * Get the current `readOnly` state of the editor.
  7344. */
  7345. var useReadOnly = () => {
  7346. return React$1.useContext(ReadOnlyContext);
  7347. };
  7348. /**
  7349. * A React context for sharing the editor object, in a way that re-renders the
  7350. * context whenever changes occur.
  7351. */
  7352. const SlateContext = React$1.createContext(null);
  7353. /**
  7354. * Get the current editor object from the React context.
  7355. */
  7356. const useSlate = () => {
  7357. const context = React$1.useContext(SlateContext);
  7358. if (!context) {
  7359. throw new Error(`The \`useSlate\` hook must be used inside the <SlateProvider> component's context.`);
  7360. }
  7361. const [editor] = context;
  7362. return editor;
  7363. };
  7364. /**
  7365. * Types.
  7366. */
  7367. /**
  7368. * Check if a DOM node is a comment node.
  7369. */
  7370. var isDOMComment = value => {
  7371. return isDOMNode(value) && value.nodeType === 8;
  7372. };
  7373. /**
  7374. * Check if a DOM node is an element node.
  7375. */
  7376. var isDOMElement = value => {
  7377. return isDOMNode(value) && value.nodeType === 1;
  7378. };
  7379. /**
  7380. * Check if a value is a DOM node.
  7381. */
  7382. var isDOMNode = value => {
  7383. return value instanceof Node;
  7384. };
  7385. /**
  7386. * Check if a DOM node is an element node.
  7387. */
  7388. var isDOMText = value => {
  7389. return isDOMNode(value) && value.nodeType === 3;
  7390. };
  7391. /**
  7392. * Normalize a DOM point so that it always refers to a text node.
  7393. */
  7394. var normalizeDOMPoint = domPoint => {
  7395. var [node, offset] = domPoint; // If it's an element node, its offset refers to the index of its children
  7396. // including comment nodes, so try to find the right text child node.
  7397. if (isDOMElement(node) && node.childNodes.length) {
  7398. var isLast = offset === node.childNodes.length;
  7399. var direction = isLast ? 'backward' : 'forward';
  7400. var index = isLast ? offset - 1 : offset;
  7401. node = getEditableChild(node, index, direction); // If the node has children, traverse until we have a leaf node. Leaf nodes
  7402. // can be either text nodes, or other void DOM nodes.
  7403. while (isDOMElement(node) && node.childNodes.length) {
  7404. var i = isLast ? node.childNodes.length - 1 : 0;
  7405. node = getEditableChild(node, i, direction);
  7406. } // Determine the new offset inside the text node.
  7407. offset = isLast && node.textContent != null ? node.textContent.length : 0;
  7408. } // Return the node and offset.
  7409. return [node, offset];
  7410. };
  7411. /**
  7412. * Get the nearest editable child at `index` in a `parent`, preferring
  7413. * `direction`.
  7414. */
  7415. var getEditableChild = (parent, index, direction) => {
  7416. var {
  7417. childNodes
  7418. } = parent;
  7419. var child = childNodes[index];
  7420. var i = index;
  7421. var triedForward = false;
  7422. var triedBackward = false; // While the child is a comment node, or an element node with no children,
  7423. // keep iterating to find a sibling non-void, non-comment node.
  7424. while (isDOMComment(child) || isDOMElement(child) && child.childNodes.length === 0 || isDOMElement(child) && child.getAttribute('contenteditable') === 'false') {
  7425. if (triedForward && triedBackward) {
  7426. break;
  7427. }
  7428. if (i >= childNodes.length) {
  7429. triedForward = true;
  7430. i = index - 1;
  7431. direction = 'backward';
  7432. continue;
  7433. }
  7434. if (i < 0) {
  7435. triedBackward = true;
  7436. i = index + 1;
  7437. direction = 'forward';
  7438. continue;
  7439. }
  7440. child = childNodes[i];
  7441. i += direction === 'forward' ? 1 : -1;
  7442. }
  7443. return child;
  7444. };
  7445. /**
  7446. * Editable.
  7447. */
  7448. const Editable = (props) => {
  7449. const { autoFocus, decorate = defaultDecorate, onDOMBeforeInput: propsOnDOMBeforeInput, placeholder, readOnly = false, renderElement, renderLeaf, style = {}, as: Component = 'div', ...attributes } = props;
  7450. const editor = useSlate();
  7451. const ref = React$1.useRef(null);
  7452. // Update internal state on each render.
  7453. IS_READ_ONLY.set(editor, readOnly);
  7454. // Keep track of some state for the event handler logic.
  7455. const state = React$1.useMemo(() => ({
  7456. isComposing: false,
  7457. isUpdatingSelection: false,
  7458. latestElement: null,
  7459. }), []);
  7460. // Update element-related weak maps with the DOM element ref.
  7461. useIsomorphicLayoutEffect(() => {
  7462. if (ref.current) {
  7463. EDITOR_TO_ELEMENT.set(editor, ref.current);
  7464. NODE_TO_ELEMENT.set(editor, ref.current);
  7465. ELEMENT_TO_NODE.set(ref.current, editor);
  7466. }
  7467. else {
  7468. NODE_TO_ELEMENT.delete(editor);
  7469. }
  7470. });
  7471. // Attach a native DOM event handler for `selectionchange`, because React's
  7472. // built-in `onSelect` handler doesn't fire for all selection changes. It's a
  7473. // leaky polyfill that only fires on keypresses or clicks. Instead, we want to
  7474. // fire for any change to the selection inside the editor. (2019/11/04)
  7475. // https://github.com/facebook/react/issues/5785
  7476. useIsomorphicLayoutEffect(() => {
  7477. window.document.addEventListener('selectionchange', onDOMSelectionChange);
  7478. return () => {
  7479. window.document.removeEventListener('selectionchange', onDOMSelectionChange);
  7480. };
  7481. }, []);
  7482. // Attach a native DOM event handler for `beforeinput` events, because React's
  7483. // built-in `onBeforeInput` is actually a leaky polyfill that doesn't expose
  7484. // real `beforeinput` events sadly... (2019/11/04)
  7485. // https://github.com/facebook/react/issues/11211
  7486. useIsomorphicLayoutEffect(() => {
  7487. if (ref.current) {
  7488. // @ts-ignore The `beforeinput` event isn't recognized.
  7489. ref.current.addEventListener('beforeinput', onDOMBeforeInput);
  7490. }
  7491. return () => {
  7492. if (ref.current) {
  7493. // @ts-ignore The `beforeinput` event isn't recognized.
  7494. ref.current.removeEventListener('beforeinput', onDOMBeforeInput);
  7495. }
  7496. };
  7497. }, []);
  7498. // Whenever the editor updates, make sure the DOM selection state is in sync.
  7499. useIsomorphicLayoutEffect(() => {
  7500. const { selection } = editor;
  7501. const domSelection = window.getSelection();
  7502. if (state.isComposing || !domSelection || !ReactEditor.isFocused(editor)) {
  7503. return;
  7504. }
  7505. const hasDomSelection = domSelection.type !== 'None';
  7506. // If the DOM selection is properly unset, we're done.
  7507. if (!selection && !hasDomSelection) {
  7508. return;
  7509. }
  7510. const newDomRange = selection && ReactEditor.toDOMRange(editor, selection);
  7511. // If the DOM selection is already correct, we're done.
  7512. if (hasDomSelection &&
  7513. newDomRange &&
  7514. isRangeEqual(domSelection.getRangeAt(0), newDomRange)) {
  7515. return;
  7516. }
  7517. // Otherwise the DOM selection is out of sync, so update it.
  7518. const el = ReactEditor.toDOMNode(editor, editor);
  7519. state.isUpdatingSelection = true;
  7520. domSelection.removeAllRanges();
  7521. if (newDomRange) {
  7522. domSelection.addRange(newDomRange);
  7523. const leafEl = newDomRange.startContainer.parentElement;
  7524. scrollIntoView(leafEl, { scrollMode: 'if-needed' });
  7525. }
  7526. setTimeout(() => {
  7527. // COMPAT: In Firefox, it's not enough to create a range, you also need
  7528. // to focus the contenteditable element too. (2016/11/16)
  7529. if (newDomRange && IS_FIREFOX) {
  7530. el.focus();
  7531. }
  7532. state.isUpdatingSelection = false;
  7533. });
  7534. });
  7535. // The autoFocus TextareaHTMLAttribute doesn't do anything on a div, so it
  7536. // needs to be manually focused.
  7537. React$1.useEffect(() => {
  7538. if (ref.current && autoFocus) {
  7539. ref.current.focus();
  7540. }
  7541. }, [autoFocus]);
  7542. // Listen on the native `beforeinput` event to get real "Level 2" events. This
  7543. // is required because React's `beforeinput` is fake and never really attaches
  7544. // to the real event sadly. (2019/11/01)
  7545. // https://github.com/facebook/react/issues/11211
  7546. const onDOMBeforeInput = React$1.useCallback((event) => {
  7547. if (!readOnly &&
  7548. hasEditableTarget(editor, event.target) &&
  7549. !isDOMEventHandled(event, propsOnDOMBeforeInput)) {
  7550. const { selection } = editor;
  7551. const { inputType: type } = event;
  7552. const data = event.dataTransfer || event.data || undefined;
  7553. // These two types occur while a user is composing text and can't be
  7554. // cancelled. Let them through and wait for the composition to end.
  7555. if (type === 'insertCompositionText' ||
  7556. type === 'deleteCompositionText') {
  7557. return;
  7558. }
  7559. event.preventDefault();
  7560. // COMPAT: For the deleting forward/backward input types we don't want
  7561. // to change the selection because it is the range that will be deleted,
  7562. // and those commands determine that for themselves.
  7563. if (!type.startsWith('delete') || type.startsWith('deleteBy')) {
  7564. const [targetRange] = event.getTargetRanges();
  7565. if (targetRange) {
  7566. const range = ReactEditor.toSlateRange(editor, targetRange);
  7567. if (!selection || !dist.Range.equals(selection, range)) {
  7568. dist.Transforms.select(editor, range);
  7569. }
  7570. }
  7571. }
  7572. // COMPAT: If the selection is expanded, even if the command seems like
  7573. // a delete forward/backward command it should delete the selection.
  7574. if (selection &&
  7575. dist.Range.isExpanded(selection) &&
  7576. type.startsWith('delete')) {
  7577. dist.Editor.deleteFragment(editor);
  7578. return;
  7579. }
  7580. switch (type) {
  7581. case 'deleteByComposition':
  7582. case 'deleteByCut':
  7583. case 'deleteByDrag': {
  7584. dist.Editor.deleteFragment(editor);
  7585. break;
  7586. }
  7587. case 'deleteContent':
  7588. case 'deleteContentForward': {
  7589. dist.Editor.deleteForward(editor);
  7590. break;
  7591. }
  7592. case 'deleteContentBackward': {
  7593. dist.Editor.deleteBackward(editor);
  7594. break;
  7595. }
  7596. case 'deleteEntireSoftLine': {
  7597. dist.Editor.deleteBackward(editor, { unit: 'line' });
  7598. dist.Editor.deleteForward(editor, { unit: 'line' });
  7599. break;
  7600. }
  7601. case 'deleteHardLineBackward': {
  7602. dist.Editor.deleteBackward(editor, { unit: 'block' });
  7603. break;
  7604. }
  7605. case 'deleteSoftLineBackward': {
  7606. dist.Editor.deleteBackward(editor, { unit: 'line' });
  7607. break;
  7608. }
  7609. case 'deleteHardLineForward': {
  7610. dist.Editor.deleteForward(editor, { unit: 'block' });
  7611. break;
  7612. }
  7613. case 'deleteSoftLineForward': {
  7614. dist.Editor.deleteForward(editor, { unit: 'line' });
  7615. break;
  7616. }
  7617. case 'deleteWordBackward': {
  7618. dist.Editor.deleteBackward(editor, { unit: 'word' });
  7619. break;
  7620. }
  7621. case 'deleteWordForward': {
  7622. dist.Editor.deleteForward(editor, { unit: 'word' });
  7623. break;
  7624. }
  7625. case 'insertLineBreak':
  7626. case 'insertParagraph': {
  7627. dist.Editor.insertBreak(editor);
  7628. break;
  7629. }
  7630. case 'insertFromComposition':
  7631. case 'insertFromDrop':
  7632. case 'insertFromPaste':
  7633. case 'insertFromYank':
  7634. case 'insertReplacementText':
  7635. case 'insertText': {
  7636. if (data instanceof DataTransfer) {
  7637. ReactEditor.insertData(editor, data);
  7638. }
  7639. else if (typeof data === 'string') {
  7640. dist.Editor.insertText(editor, data);
  7641. }
  7642. break;
  7643. }
  7644. }
  7645. }
  7646. }, []);
  7647. // Listen on the native `selectionchange` event to be able to update any time
  7648. // the selection changes. This is required because React's `onSelect` is leaky
  7649. // and non-standard so it doesn't fire until after a selection has been
  7650. // released. This causes issues in situations where another change happens
  7651. // while a selection is being dragged.
  7652. const onDOMSelectionChange = React$1.useCallback(debounce(() => {
  7653. if (!readOnly && !state.isComposing && !state.isUpdatingSelection) {
  7654. const { activeElement } = window.document;
  7655. const el = ReactEditor.toDOMNode(editor, editor);
  7656. const domSelection = window.getSelection();
  7657. const domRange = domSelection &&
  7658. domSelection.rangeCount > 0 &&
  7659. domSelection.getRangeAt(0);
  7660. if (activeElement === el) {
  7661. state.latestElement = activeElement;
  7662. IS_FOCUSED.set(editor, true);
  7663. }
  7664. else {
  7665. IS_FOCUSED.delete(editor);
  7666. }
  7667. if (domRange &&
  7668. hasEditableTarget(editor, domRange.startContainer) &&
  7669. hasEditableTarget(editor, domRange.endContainer)) {
  7670. const range = ReactEditor.toSlateRange(editor, domRange);
  7671. dist.Transforms.select(editor, range);
  7672. }
  7673. else {
  7674. dist.Transforms.deselect(editor);
  7675. }
  7676. }
  7677. }, 100), []);
  7678. const decorations = decorate([editor, []]);
  7679. if (placeholder &&
  7680. editor.children.length === 1 &&
  7681. Array.from(dist.Node.texts(editor)).length === 1 &&
  7682. dist.Node.string(editor) === '') {
  7683. const start = dist.Editor.start(editor, []);
  7684. decorations.push({
  7685. [PLACEHOLDER_SYMBOL]: true,
  7686. placeholder,
  7687. anchor: start,
  7688. focus: start,
  7689. });
  7690. }
  7691. return (React__default.createElement(ReadOnlyContext.Provider, { value: readOnly },
  7692. React__default.createElement(Component
  7693. // COMPAT: The Grammarly Chrome extension works by changing the DOM
  7694. // out from under `contenteditable` elements, which leads to weird
  7695. // behaviors so we have to disable it like editor. (2017/04/24)
  7696. , Object.assign({ "data-gramm": false, role: readOnly ? undefined : 'textbox' }, attributes, {
  7697. // COMPAT: Firefox doesn't support the `beforeinput` event, so we'd
  7698. // have to use hacks to make these replacement-based features work.
  7699. spellCheck: IS_FIREFOX ? undefined : attributes.spellCheck, autoCorrect: IS_FIREFOX ? undefined : attributes.autoCorrect, autoCapitalize: IS_FIREFOX ? undefined : attributes.autoCapitalize, "data-slate-editor": true, "data-slate-node": "value", contentEditable: readOnly ? undefined : true, suppressContentEditableWarning: true, ref: ref, style: {
  7700. // Prevent the default outline styles.
  7701. outline: 'none',
  7702. // Preserve adjacent whitespace and new lines.
  7703. whiteSpace: 'pre-wrap',
  7704. // Allow words to break if they are too long.
  7705. wordWrap: 'break-word',
  7706. // Allow for passed-in styles to override anything.
  7707. ...style,
  7708. }, onBeforeInput: React$1.useCallback((event) => {
  7709. // COMPAT: Firefox doesn't support the `beforeinput` event, so we
  7710. // fall back to React's leaky polyfill instead just for it. It
  7711. // only works for the `insertText` input type.
  7712. if (IS_FIREFOX && !readOnly) {
  7713. event.preventDefault();
  7714. const text = event.data;
  7715. dist.Editor.insertText(editor, text);
  7716. }
  7717. }, [readOnly]), onBlur: React$1.useCallback((event) => {
  7718. if (readOnly ||
  7719. state.isUpdatingSelection ||
  7720. !hasEditableTarget(editor, event.target) ||
  7721. isEventHandled(event, attributes.onBlur)) {
  7722. return;
  7723. }
  7724. // COMPAT: If the current `activeElement` is still the previous
  7725. // one, this is due to the window being blurred when the tab
  7726. // itself becomes unfocused, so we want to abort early to allow to
  7727. // editor to stay focused when the tab becomes focused again.
  7728. if (state.latestElement === window.document.activeElement) {
  7729. return;
  7730. }
  7731. const { relatedTarget } = event;
  7732. const el = ReactEditor.toDOMNode(editor, editor);
  7733. // COMPAT: The event should be ignored if the focus is returning
  7734. // to the editor from an embedded editable element (eg. an <input>
  7735. // element inside a void node).
  7736. if (relatedTarget === el) {
  7737. return;
  7738. }
  7739. // COMPAT: The event should be ignored if the focus is moving from
  7740. // the editor to inside a void node's spacer element.
  7741. if (isDOMElement(relatedTarget) &&
  7742. relatedTarget.hasAttribute('data-slate-spacer')) {
  7743. return;
  7744. }
  7745. // COMPAT: The event should be ignored if the focus is moving to a
  7746. // non- editable section of an element that isn't a void node (eg.
  7747. // a list item of the check list example).
  7748. if (relatedTarget != null &&
  7749. isDOMNode(relatedTarget) &&
  7750. ReactEditor.hasDOMNode(editor, relatedTarget)) {
  7751. const node = ReactEditor.toSlateNode(editor, relatedTarget);
  7752. if (dist.Element.isElement(node) && !editor.isVoid(node)) {
  7753. return;
  7754. }
  7755. }
  7756. IS_FOCUSED.delete(editor);
  7757. }, [readOnly, attributes.onBlur]), onClick: React$1.useCallback((event) => {
  7758. if (!readOnly &&
  7759. hasTarget(editor, event.target) &&
  7760. !isEventHandled(event, attributes.onClick) &&
  7761. isDOMNode(event.target)) {
  7762. const node = ReactEditor.toSlateNode(editor, event.target);
  7763. const path = ReactEditor.findPath(editor, node);
  7764. const start = dist.Editor.start(editor, path);
  7765. if (dist.Editor.void(editor, { at: start })) {
  7766. const range = dist.Editor.range(editor, start);
  7767. dist.Transforms.select(editor, range);
  7768. }
  7769. }
  7770. }, [readOnly, attributes.onClick]), onCompositionEnd: React$1.useCallback((event) => {
  7771. if (hasEditableTarget(editor, event.target) &&
  7772. !isEventHandled(event, attributes.onCompositionEnd)) {
  7773. state.isComposing = false;
  7774. // COMPAT: In Chrome, `beforeinput` events for compositions
  7775. // aren't correct and never fire the "insertFromComposition"
  7776. // type that we need. So instead, insert whenever a composition
  7777. // ends since it will already have been committed to the DOM.
  7778. if (!IS_SAFARI && !IS_FIREFOX && event.data) {
  7779. dist.Editor.insertText(editor, event.data);
  7780. }
  7781. }
  7782. }, [attributes.onCompositionEnd]), onCompositionStart: React$1.useCallback((event) => {
  7783. if (hasEditableTarget(editor, event.target) &&
  7784. !isEventHandled(event, attributes.onCompositionStart)) {
  7785. state.isComposing = true;
  7786. }
  7787. }, [attributes.onCompositionStart]), onCopy: React$1.useCallback((event) => {
  7788. if (hasEditableTarget(editor, event.target) &&
  7789. !isEventHandled(event, attributes.onCopy)) {
  7790. event.preventDefault();
  7791. setFragmentData(event.clipboardData, editor);
  7792. }
  7793. }, [attributes.onCopy]), onCut: React$1.useCallback((event) => {
  7794. if (!readOnly &&
  7795. hasEditableTarget(editor, event.target) &&
  7796. !isEventHandled(event, attributes.onCut)) {
  7797. event.preventDefault();
  7798. setFragmentData(event.clipboardData, editor);
  7799. const { selection } = editor;
  7800. if (selection && dist.Range.isExpanded(selection)) {
  7801. dist.Editor.deleteFragment(editor);
  7802. }
  7803. }
  7804. }, [readOnly, attributes.onCut]), onDragOver: React$1.useCallback((event) => {
  7805. if (hasTarget(editor, event.target) &&
  7806. !isEventHandled(event, attributes.onDragOver)) {
  7807. // Only when the target is void, call `preventDefault` to signal
  7808. // that drops are allowed. Editable content is droppable by
  7809. // default, and calling `preventDefault` hides the cursor.
  7810. const node = ReactEditor.toSlateNode(editor, event.target);
  7811. if (dist.Editor.isVoid(editor, node)) {
  7812. event.preventDefault();
  7813. }
  7814. }
  7815. }, [attributes.onDragOver]), onDragStart: React$1.useCallback((event) => {
  7816. if (hasTarget(editor, event.target) &&
  7817. !isEventHandled(event, attributes.onDragStart)) {
  7818. const node = ReactEditor.toSlateNode(editor, event.target);
  7819. const path = ReactEditor.findPath(editor, node);
  7820. const voidMatch = dist.Editor.void(editor, { at: path });
  7821. // If starting a drag on a void node, make sure it is selected
  7822. // so that it shows up in the selection's fragment.
  7823. if (voidMatch) {
  7824. const range = dist.Editor.range(editor, path);
  7825. dist.Transforms.select(editor, range);
  7826. }
  7827. setFragmentData(event.dataTransfer, editor);
  7828. }
  7829. }, [attributes.onDragStart]), onDrop: React$1.useCallback((event) => {
  7830. if (hasTarget(editor, event.target) &&
  7831. !readOnly &&
  7832. !isEventHandled(event, attributes.onDrop)) {
  7833. // COMPAT: Firefox doesn't fire `beforeinput` events at all, and
  7834. // Chromium browsers don't properly fire them for files being
  7835. // dropped into a `contenteditable`. (2019/11/26)
  7836. // https://bugs.chromium.org/p/chromium/issues/detail?id=1028668
  7837. if (IS_FIREFOX ||
  7838. (!IS_SAFARI && event.dataTransfer.files.length > 0)) {
  7839. event.preventDefault();
  7840. const range = ReactEditor.findEventRange(editor, event);
  7841. const data = event.dataTransfer;
  7842. dist.Transforms.select(editor, range);
  7843. ReactEditor.insertData(editor, data);
  7844. }
  7845. }
  7846. }, [readOnly, attributes.onDrop]), onFocus: React$1.useCallback((event) => {
  7847. if (!readOnly &&
  7848. !state.isUpdatingSelection &&
  7849. hasEditableTarget(editor, event.target) &&
  7850. !isEventHandled(event, attributes.onFocus)) {
  7851. const el = ReactEditor.toDOMNode(editor, editor);
  7852. state.latestElement = window.document.activeElement;
  7853. // COMPAT: If the editor has nested editable elements, the focus
  7854. // can go to them. In Firefox, this must be prevented because it
  7855. // results in issues with keyboard navigation. (2017/03/30)
  7856. if (IS_FIREFOX && event.target !== el) {
  7857. el.focus();
  7858. return;
  7859. }
  7860. IS_FOCUSED.set(editor, true);
  7861. }
  7862. }, [readOnly, attributes.onFocus]), onKeyDown: React$1.useCallback((event) => {
  7863. if (!readOnly &&
  7864. hasEditableTarget(editor, event.target) &&
  7865. !isEventHandled(event, attributes.onKeyDown)) {
  7866. const { nativeEvent } = event;
  7867. const { selection } = editor;
  7868. // COMPAT: Since we prevent the default behavior on
  7869. // `beforeinput` events, the browser doesn't think there's ever
  7870. // any history stack to undo or redo, so we have to manage these
  7871. // hotkeys ourselves. (2019/11/06)
  7872. if (Hotkeys.isRedo(nativeEvent)) {
  7873. event.preventDefault();
  7874. if (editor.redo) {
  7875. editor.redo();
  7876. }
  7877. return;
  7878. }
  7879. if (Hotkeys.isUndo(nativeEvent)) {
  7880. event.preventDefault();
  7881. if (editor.undo) {
  7882. editor.undo();
  7883. }
  7884. return;
  7885. }
  7886. // COMPAT: Certain browsers don't handle the selection updates
  7887. // properly. In Chrome, the selection isn't properly extended.
  7888. // And in Firefox, the selection isn't properly collapsed.
  7889. // (2017/10/17)
  7890. if (Hotkeys.isMoveLineBackward(nativeEvent)) {
  7891. event.preventDefault();
  7892. dist.Transforms.move(editor, { unit: 'line', reverse: true });
  7893. return;
  7894. }
  7895. if (Hotkeys.isMoveLineForward(nativeEvent)) {
  7896. event.preventDefault();
  7897. dist.Transforms.move(editor, { unit: 'line' });
  7898. return;
  7899. }
  7900. if (Hotkeys.isExtendLineBackward(nativeEvent)) {
  7901. event.preventDefault();
  7902. dist.Transforms.move(editor, {
  7903. unit: 'line',
  7904. edge: 'focus',
  7905. reverse: true,
  7906. });
  7907. return;
  7908. }
  7909. if (Hotkeys.isExtendLineForward(nativeEvent)) {
  7910. event.preventDefault();
  7911. dist.Transforms.move(editor, { unit: 'line', edge: 'focus' });
  7912. return;
  7913. }
  7914. // COMPAT: If a void node is selected, or a zero-width text node
  7915. // adjacent to an inline is selected, we need to handle these
  7916. // hotkeys manually because browsers won't be able to skip over
  7917. // the void node with the zero-width space not being an empty
  7918. // string.
  7919. if (Hotkeys.isMoveBackward(nativeEvent)) {
  7920. event.preventDefault();
  7921. if (selection && dist.Range.isCollapsed(selection)) {
  7922. dist.Transforms.move(editor, { reverse: true });
  7923. }
  7924. else {
  7925. dist.Transforms.collapse(editor, { edge: 'start' });
  7926. }
  7927. return;
  7928. }
  7929. if (Hotkeys.isMoveForward(nativeEvent)) {
  7930. event.preventDefault();
  7931. if (selection && dist.Range.isCollapsed(selection)) {
  7932. dist.Transforms.move(editor);
  7933. }
  7934. else {
  7935. dist.Transforms.collapse(editor, { edge: 'end' });
  7936. }
  7937. return;
  7938. }
  7939. if (Hotkeys.isMoveWordBackward(nativeEvent)) {
  7940. event.preventDefault();
  7941. dist.Transforms.move(editor, { unit: 'word', reverse: true });
  7942. return;
  7943. }
  7944. if (Hotkeys.isMoveWordForward(nativeEvent)) {
  7945. event.preventDefault();
  7946. dist.Transforms.move(editor, { unit: 'word' });
  7947. return;
  7948. }
  7949. // COMPAT: Firefox doesn't support the `beforeinput` event, so we
  7950. // fall back to guessing at the input intention for hotkeys.
  7951. // COMPAT: In iOS, some of these hotkeys are handled in the
  7952. if (IS_FIREFOX) {
  7953. // We don't have a core behavior for these, but they change the
  7954. // DOM if we don't prevent them, so we have to.
  7955. if (Hotkeys.isBold(nativeEvent) ||
  7956. Hotkeys.isItalic(nativeEvent) ||
  7957. Hotkeys.isTransposeCharacter(nativeEvent)) {
  7958. event.preventDefault();
  7959. return;
  7960. }
  7961. if (Hotkeys.isSplitBlock(nativeEvent)) {
  7962. event.preventDefault();
  7963. dist.Editor.insertBreak(editor);
  7964. return;
  7965. }
  7966. if (Hotkeys.isDeleteBackward(nativeEvent)) {
  7967. event.preventDefault();
  7968. if (selection && dist.Range.isExpanded(selection)) {
  7969. dist.Editor.deleteFragment(editor);
  7970. }
  7971. else {
  7972. dist.Editor.deleteBackward(editor);
  7973. }
  7974. return;
  7975. }
  7976. if (Hotkeys.isDeleteForward(nativeEvent)) {
  7977. event.preventDefault();
  7978. if (selection && dist.Range.isExpanded(selection)) {
  7979. dist.Editor.deleteFragment(editor);
  7980. }
  7981. else {
  7982. dist.Editor.deleteForward(editor);
  7983. }
  7984. return;
  7985. }
  7986. if (Hotkeys.isDeleteLineBackward(nativeEvent)) {
  7987. event.preventDefault();
  7988. if (selection && dist.Range.isExpanded(selection)) {
  7989. dist.Editor.deleteFragment(editor);
  7990. }
  7991. else {
  7992. dist.Editor.deleteBackward(editor, { unit: 'line' });
  7993. }
  7994. return;
  7995. }
  7996. if (Hotkeys.isDeleteLineForward(nativeEvent)) {
  7997. event.preventDefault();
  7998. if (selection && dist.Range.isExpanded(selection)) {
  7999. dist.Editor.deleteFragment(editor);
  8000. }
  8001. else {
  8002. dist.Editor.deleteForward(editor, { unit: 'line' });
  8003. }
  8004. return;
  8005. }
  8006. if (Hotkeys.isDeleteWordBackward(nativeEvent)) {
  8007. event.preventDefault();
  8008. if (selection && dist.Range.isExpanded(selection)) {
  8009. dist.Editor.deleteFragment(editor);
  8010. }
  8011. else {
  8012. dist.Editor.deleteBackward(editor, { unit: 'word' });
  8013. }
  8014. return;
  8015. }
  8016. if (Hotkeys.isDeleteWordForward(nativeEvent)) {
  8017. event.preventDefault();
  8018. if (selection && dist.Range.isExpanded(selection)) {
  8019. dist.Editor.deleteFragment(editor);
  8020. }
  8021. else {
  8022. dist.Editor.deleteForward(editor, { unit: 'word' });
  8023. }
  8024. return;
  8025. }
  8026. }
  8027. }
  8028. }, [readOnly, attributes.onKeyDown]), onPaste: React$1.useCallback((event) => {
  8029. // COMPAT: Firefox doesn't support the `beforeinput` event, so we
  8030. // fall back to React's `onPaste` here instead.
  8031. if (IS_FIREFOX &&
  8032. !readOnly &&
  8033. hasEditableTarget(editor, event.target) &&
  8034. !isEventHandled(event, attributes.onPaste)) {
  8035. event.preventDefault();
  8036. ReactEditor.insertData(editor, event.clipboardData);
  8037. }
  8038. }, [readOnly, attributes.onPaste]) }),
  8039. React__default.createElement(Children, { decorate: decorate, decorations: decorations, node: editor, renderElement: renderElement, renderLeaf: renderLeaf, selection: editor.selection }))));
  8040. };
  8041. /**
  8042. * A default memoized decorate function.
  8043. */
  8044. const defaultDecorate = () => [];
  8045. /**
  8046. * Check if two DOM range objects are equal.
  8047. */
  8048. const isRangeEqual = (a, b) => {
  8049. return ((a.startContainer === b.startContainer &&
  8050. a.startOffset === b.startOffset &&
  8051. a.endContainer === b.endContainer &&
  8052. a.endOffset === b.endOffset) ||
  8053. (a.startContainer === b.endContainer &&
  8054. a.startOffset === b.endOffset &&
  8055. a.endContainer === b.startContainer &&
  8056. a.endOffset === b.startOffset));
  8057. };
  8058. /**
  8059. * Check if the target is in the editor.
  8060. */
  8061. const hasTarget = (editor, target) => {
  8062. return isDOMNode(target) && ReactEditor.hasDOMNode(editor, target);
  8063. };
  8064. /**
  8065. * Check if the target is editable and in the editor.
  8066. */
  8067. const hasEditableTarget = (editor, target) => {
  8068. return (isDOMNode(target) &&
  8069. ReactEditor.hasDOMNode(editor, target, { editable: true }));
  8070. };
  8071. /**
  8072. * Check if an event is overrided by a handler.
  8073. */
  8074. const isEventHandled = (event, handler) => {
  8075. if (!handler) {
  8076. return false;
  8077. }
  8078. handler(event);
  8079. return event.isDefaultPrevented() || event.isPropagationStopped();
  8080. };
  8081. /**
  8082. * Check if a DOM event is overrided by a handler.
  8083. */
  8084. const isDOMEventHandled = (event, handler) => {
  8085. if (!handler) {
  8086. return false;
  8087. }
  8088. handler(event);
  8089. return event.defaultPrevented;
  8090. };
  8091. /**
  8092. * Set the currently selected fragment to the clipboard.
  8093. */
  8094. const setFragmentData = (dataTransfer, editor) => {
  8095. const { selection } = editor;
  8096. if (!selection) {
  8097. return;
  8098. }
  8099. const [start, end] = dist.Range.edges(selection);
  8100. const startVoid = dist.Editor.void(editor, { at: start.path });
  8101. const endVoid = dist.Editor.void(editor, { at: end.path });
  8102. if (dist.Range.isCollapsed(selection) && !startVoid) {
  8103. return;
  8104. }
  8105. // Create a fake selection so that we can add a Base64-encoded copy of the
  8106. // fragment to the HTML, to decode on future pastes.
  8107. const domRange = ReactEditor.toDOMRange(editor, selection);
  8108. let contents = domRange.cloneContents();
  8109. let attach = contents.childNodes[0];
  8110. // Make sure attach is non-empty, since empty nodes will not get copied.
  8111. contents.childNodes.forEach(node => {
  8112. if (node.textContent && node.textContent.trim() !== '') {
  8113. attach = node;
  8114. }
  8115. });
  8116. // COMPAT: If the end node is a void node, we need to move the end of the
  8117. // range from the void node's spacer span, to the end of the void node's
  8118. // content, since the spacer is before void's content in the DOM.
  8119. if (endVoid) {
  8120. const [voidNode] = endVoid;
  8121. const r = domRange.cloneRange();
  8122. const domNode = ReactEditor.toDOMNode(editor, voidNode);
  8123. r.setEndAfter(domNode);
  8124. contents = r.cloneContents();
  8125. }
  8126. // COMPAT: If the start node is a void node, we need to attach the encoded
  8127. // fragment to the void node's content node instead of the spacer, because
  8128. // attaching it to empty `<div>/<span>` nodes will end up having it erased by
  8129. // most browsers. (2018/04/27)
  8130. if (startVoid) {
  8131. attach = contents.querySelector('[data-slate-spacer]');
  8132. }
  8133. // Remove any zero-width space spans from the cloned DOM so that they don't
  8134. // show up elsewhere when pasted.
  8135. Array.from(contents.querySelectorAll('[data-slate-zero-width]')).forEach(zw => {
  8136. const isNewline = zw.getAttribute('data-slate-zero-width') === 'n';
  8137. zw.textContent = isNewline ? '\n' : '';
  8138. });
  8139. // Set a `data-slate-fragment` attribute on a non-empty node, so it shows up
  8140. // in the HTML, and can be used for intra-Slate pasting. If it's a text
  8141. // node, wrap it in a `<span>` so we have something to set an attribute on.
  8142. if (isDOMText(attach)) {
  8143. const span = document.createElement('span');
  8144. // COMPAT: In Chrome and Safari, if we don't add the `white-space` style
  8145. // then leading and trailing spaces will be ignored. (2017/09/21)
  8146. span.style.whiteSpace = 'pre';
  8147. span.appendChild(attach);
  8148. contents.appendChild(span);
  8149. attach = span;
  8150. }
  8151. const fragment = dist.Node.fragment(editor, selection);
  8152. const string = JSON.stringify(fragment);
  8153. const encoded = window.btoa(encodeURIComponent(string));
  8154. attach.setAttribute('data-slate-fragment', encoded);
  8155. dataTransfer.setData('application/x-slate-fragment', encoded);
  8156. // Add the content to a <div> so that we can get its inner HTML.
  8157. const div = document.createElement('div');
  8158. div.appendChild(contents);
  8159. dataTransfer.setData('text/html', div.innerHTML);
  8160. dataTransfer.setData('text/plain', getPlainText(div));
  8161. };
  8162. /**
  8163. * Get a plaintext representation of the content of a node, accounting for block
  8164. * elements which get a newline appended.
  8165. */
  8166. const getPlainText = (domNode) => {
  8167. let text = '';
  8168. if (isDOMText(domNode) && domNode.nodeValue) {
  8169. return domNode.nodeValue;
  8170. }
  8171. if (isDOMElement(domNode)) {
  8172. for (const childNode of Array.from(domNode.childNodes)) {
  8173. text += getPlainText(childNode);
  8174. }
  8175. const display = getComputedStyle(domNode).getPropertyValue('display');
  8176. if (display === 'block' || display === 'list' || domNode.tagName === 'BR') {
  8177. text += '\n';
  8178. }
  8179. }
  8180. return text;
  8181. };
  8182. /**
  8183. * An auto-incrementing identifier for keys.
  8184. */
  8185. var n = 0;
  8186. /**
  8187. * A class that keeps track of a key string. We use a full class here because we
  8188. * want to be able to use them as keys in `WeakMap` objects.
  8189. */
  8190. class Key {
  8191. constructor() {
  8192. this.id = "".concat(n++);
  8193. }
  8194. }
  8195. var ReactEditor = {
  8196. /**
  8197. * Find a key for a Slate node.
  8198. */
  8199. findKey(editor, node) {
  8200. var key = NODE_TO_KEY.get(node);
  8201. if (!key) {
  8202. key = new Key();
  8203. NODE_TO_KEY.set(node, key);
  8204. }
  8205. return key;
  8206. },
  8207. /**
  8208. * Find the path of Slate node.
  8209. */
  8210. findPath(editor, node) {
  8211. var path = [];
  8212. var child = node;
  8213. while (true) {
  8214. var parent = NODE_TO_PARENT.get(child);
  8215. if (parent == null) {
  8216. if (dist.Editor.isEditor(child)) {
  8217. return path;
  8218. } else {
  8219. break;
  8220. }
  8221. }
  8222. var i = NODE_TO_INDEX.get(child);
  8223. if (i == null) {
  8224. break;
  8225. }
  8226. path.unshift(i);
  8227. child = parent;
  8228. }
  8229. throw new Error("Unable to find the path for Slate node: ".concat(JSON.stringify(node)));
  8230. },
  8231. /**
  8232. * Check if the editor is focused.
  8233. */
  8234. isFocused(editor) {
  8235. return !!IS_FOCUSED.get(editor);
  8236. },
  8237. /**
  8238. * Check if the editor is in read-only mode.
  8239. */
  8240. isReadOnly(editor) {
  8241. return !!IS_READ_ONLY.get(editor);
  8242. },
  8243. /**
  8244. * Blur the editor.
  8245. */
  8246. blur(editor) {
  8247. var el = ReactEditor.toDOMNode(editor, editor);
  8248. IS_FOCUSED.set(editor, false);
  8249. if (window.document.activeElement === el) {
  8250. el.blur();
  8251. }
  8252. },
  8253. /**
  8254. * Focus the editor.
  8255. */
  8256. focus(editor) {
  8257. var el = ReactEditor.toDOMNode(editor, editor);
  8258. IS_FOCUSED.set(editor, true);
  8259. if (window.document.activeElement !== el) {
  8260. el.focus({
  8261. preventScroll: true
  8262. });
  8263. }
  8264. },
  8265. /**
  8266. * Deselect the editor.
  8267. */
  8268. deselect(editor) {
  8269. var {
  8270. selection
  8271. } = editor;
  8272. var domSelection = window.getSelection();
  8273. if (domSelection && domSelection.rangeCount > 0) {
  8274. domSelection.removeAllRanges();
  8275. }
  8276. if (selection) {
  8277. dist.Transforms.deselect(editor);
  8278. }
  8279. },
  8280. /**
  8281. * Check if a DOM node is within the editor.
  8282. */
  8283. hasDOMNode(editor, target) {
  8284. var options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
  8285. var {
  8286. editable = false
  8287. } = options;
  8288. var el = ReactEditor.toDOMNode(editor, editor);
  8289. var element; // COMPAT: In Firefox, reading `target.nodeType` will throw an error if
  8290. // target is originating from an internal "restricted" element (e.g. a
  8291. // stepper arrow on a number input). (2018/05/04)
  8292. // https://github.com/ianstormtaylor/slate/issues/1819
  8293. try {
  8294. element = isDOMElement(target) ? target : target.parentElement;
  8295. } catch (err) {
  8296. if (!err.message.includes('Permission denied to access property "nodeType"')) {
  8297. throw err;
  8298. }
  8299. }
  8300. if (!element) {
  8301. return false;
  8302. }
  8303. return element.closest("[data-slate-editor]") === el && (!editable || el.isContentEditable);
  8304. },
  8305. /**
  8306. * Insert data from a `DataTransfer` into the editor.
  8307. */
  8308. insertData(editor, data) {
  8309. editor.insertData(data);
  8310. },
  8311. /**
  8312. * Find the native DOM element from a Slate node.
  8313. */
  8314. toDOMNode(editor, node) {
  8315. var domNode = dist.Editor.isEditor(node) ? EDITOR_TO_ELEMENT.get(editor) : KEY_TO_ELEMENT.get(ReactEditor.findKey(editor, node));
  8316. if (!domNode) {
  8317. throw new Error("Cannot resolve a DOM node from Slate node: ".concat(JSON.stringify(node)));
  8318. }
  8319. return domNode;
  8320. },
  8321. /**
  8322. * Find a native DOM selection point from a Slate point.
  8323. */
  8324. toDOMPoint(editor, point) {
  8325. var [node] = dist.Editor.node(editor, point.path);
  8326. var el = ReactEditor.toDOMNode(editor, node);
  8327. var domPoint; // If we're inside a void node, force the offset to 0, otherwise the zero
  8328. // width spacing character will result in an incorrect offset of 1
  8329. if (dist.Editor.void(editor, {
  8330. at: point
  8331. })) {
  8332. point = {
  8333. path: point.path,
  8334. offset: 0
  8335. };
  8336. } // For each leaf, we need to isolate its content, which means filtering
  8337. // to its direct text and zero-width spans. (We have to filter out any
  8338. // other siblings that may have been rendered alongside them.)
  8339. var selector = "[data-slate-string], [data-slate-zero-width]";
  8340. var texts = Array.from(el.querySelectorAll(selector));
  8341. var start = 0;
  8342. for (var text of texts) {
  8343. var domNode = text.childNodes[0];
  8344. if (domNode == null || domNode.textContent == null) {
  8345. continue;
  8346. }
  8347. var {
  8348. length
  8349. } = domNode.textContent;
  8350. var attr = text.getAttribute('data-slate-length');
  8351. var trueLength = attr == null ? length : parseInt(attr, 10);
  8352. var end = start + trueLength;
  8353. if (point.offset <= end) {
  8354. var offset = Math.min(length, Math.max(0, point.offset - start));
  8355. domPoint = [domNode, offset];
  8356. break;
  8357. }
  8358. start = end;
  8359. }
  8360. if (!domPoint) {
  8361. throw new Error("Cannot resolve a DOM point from Slate point: ".concat(JSON.stringify(point)));
  8362. }
  8363. return domPoint;
  8364. },
  8365. /**
  8366. * Find a native DOM range from a Slate `range`.
  8367. */
  8368. toDOMRange(editor, range) {
  8369. var {
  8370. anchor,
  8371. focus
  8372. } = range;
  8373. var domAnchor = ReactEditor.toDOMPoint(editor, anchor);
  8374. var domFocus = dist.Range.isCollapsed(range) ? domAnchor : ReactEditor.toDOMPoint(editor, focus);
  8375. var domRange = window.document.createRange();
  8376. var start = dist.Range.isBackward(range) ? domFocus : domAnchor;
  8377. var end = dist.Range.isBackward(range) ? domAnchor : domFocus;
  8378. domRange.setStart(start[0], start[1]);
  8379. domRange.setEnd(end[0], end[1]);
  8380. return domRange;
  8381. },
  8382. /**
  8383. * Find a Slate node from a native DOM `element`.
  8384. */
  8385. toSlateNode(editor, domNode) {
  8386. var domEl = isDOMElement(domNode) ? domNode : domNode.parentElement;
  8387. if (domEl && !domEl.hasAttribute('data-slate-node')) {
  8388. domEl = domEl.closest("[data-slate-node]");
  8389. }
  8390. var node = domEl ? ELEMENT_TO_NODE.get(domEl) : null;
  8391. if (!node) {
  8392. throw new Error("Cannot resolve a Slate node from DOM node: ".concat(domEl));
  8393. }
  8394. return node;
  8395. },
  8396. /**
  8397. * Get the target range from a DOM `event`.
  8398. */
  8399. findEventRange(editor, event) {
  8400. if ('nativeEvent' in event) {
  8401. event = event.nativeEvent;
  8402. }
  8403. var {
  8404. clientX: x,
  8405. clientY: y,
  8406. target
  8407. } = event;
  8408. if (x == null || y == null) {
  8409. throw new Error("Cannot resolve a Slate range from a DOM event: ".concat(event));
  8410. }
  8411. var node = ReactEditor.toSlateNode(editor, event.target);
  8412. var path = ReactEditor.findPath(editor, node); // If the drop target is inside a void node, move it into either the
  8413. // next or previous node, depending on which side the `x` and `y`
  8414. // coordinates are closest to.
  8415. if (dist.Editor.isVoid(editor, node)) {
  8416. var rect = target.getBoundingClientRect();
  8417. var isPrev = editor.isInline(node) ? x - rect.left < rect.left + rect.width - x : y - rect.top < rect.top + rect.height - y;
  8418. var edge = dist.Editor.point(editor, path, {
  8419. edge: isPrev ? 'start' : 'end'
  8420. });
  8421. var point = isPrev ? dist.Editor.before(editor, edge) : dist.Editor.after(editor, edge);
  8422. if (point) {
  8423. var _range = dist.Editor.range(editor, point);
  8424. return _range;
  8425. }
  8426. } // Else resolve a range from the caret position where the drop occured.
  8427. var domRange;
  8428. var {
  8429. document
  8430. } = window; // COMPAT: In Firefox, `caretRangeFromPoint` doesn't exist. (2016/07/25)
  8431. if (document.caretRangeFromPoint) {
  8432. domRange = document.caretRangeFromPoint(x, y);
  8433. } else {
  8434. var position = document.caretPositionFromPoint(x, y);
  8435. if (position) {
  8436. domRange = document.createRange();
  8437. domRange.setStart(position.offsetNode, position.offset);
  8438. domRange.setEnd(position.offsetNode, position.offset);
  8439. }
  8440. }
  8441. if (!domRange) {
  8442. throw new Error("Cannot resolve a Slate range from a DOM event: ".concat(event));
  8443. } // Resolve a Slate range from the DOM range.
  8444. var range = ReactEditor.toSlateRange(editor, domRange);
  8445. return range;
  8446. },
  8447. /**
  8448. * Find a Slate point from a DOM selection's `domNode` and `domOffset`.
  8449. */
  8450. toSlatePoint(editor, domPoint) {
  8451. var [nearestNode, nearestOffset] = normalizeDOMPoint(domPoint);
  8452. var parentNode = nearestNode.parentNode;
  8453. var textNode = null;
  8454. var offset = 0;
  8455. if (parentNode) {
  8456. var voidNode = parentNode.closest('[data-slate-void="true"]');
  8457. var leafNode = parentNode.closest('[data-slate-leaf]');
  8458. var domNode = null; // Calculate how far into the text node the `nearestNode` is, so that we
  8459. // can determine what the offset relative to the text node is.
  8460. if (leafNode) {
  8461. textNode = leafNode.closest('[data-slate-node="text"]');
  8462. var range = window.document.createRange();
  8463. range.setStart(textNode, 0);
  8464. range.setEnd(nearestNode, nearestOffset);
  8465. var contents = range.cloneContents();
  8466. var removals = [...contents.querySelectorAll('[data-slate-zero-width]'), ...contents.querySelectorAll('[contenteditable=false]')];
  8467. removals.forEach(el => {
  8468. el.parentNode.removeChild(el);
  8469. }); // COMPAT: Edge has a bug where Range.prototype.toString() will
  8470. // convert \n into \r\n. The bug causes a loop when slate-react
  8471. // attempts to reposition its cursor to match the native position. Use
  8472. // textContent.length instead.
  8473. // https://developer.microsoft.com/en-us/microsoft-edge/platform/issues/10291116/
  8474. offset = contents.textContent.length;
  8475. domNode = textNode;
  8476. } else if (voidNode) {
  8477. // For void nodes, the element with the offset key will be a cousin, not an
  8478. // ancestor, so find it by going down from the nearest void parent.
  8479. leafNode = voidNode.querySelector('[data-slate-leaf]');
  8480. textNode = leafNode.closest('[data-slate-node="text"]');
  8481. domNode = leafNode;
  8482. offset = domNode.textContent.length;
  8483. } // COMPAT: If the parent node is a Slate zero-width space, editor is
  8484. // because the text node should have no characters. However, during IME
  8485. // composition the ASCII characters will be prepended to the zero-width
  8486. // space, so subtract 1 from the offset to account for the zero-width
  8487. // space character.
  8488. if (domNode && offset === domNode.textContent.length && parentNode.hasAttribute('data-slate-zero-width')) {
  8489. offset--;
  8490. }
  8491. }
  8492. if (!textNode) {
  8493. throw new Error("Cannot resolve a Slate point from DOM point: ".concat(domPoint));
  8494. } // COMPAT: If someone is clicking from one Slate editor into another,
  8495. // the select event fires twice, once for the old editor's `element`
  8496. // first, and then afterwards for the correct `element`. (2017/03/03)
  8497. var slateNode = ReactEditor.toSlateNode(editor, textNode);
  8498. var path = ReactEditor.findPath(editor, slateNode);
  8499. return {
  8500. path,
  8501. offset
  8502. };
  8503. },
  8504. /**
  8505. * Find a Slate range from a DOM range or selection.
  8506. */
  8507. toSlateRange(editor, domRange) {
  8508. var el = domRange instanceof Selection ? domRange.anchorNode : domRange.startContainer;
  8509. var anchorNode;
  8510. var anchorOffset;
  8511. var focusNode;
  8512. var focusOffset;
  8513. var isCollapsed;
  8514. if (el) {
  8515. if (domRange instanceof Selection) {
  8516. anchorNode = domRange.anchorNode;
  8517. anchorOffset = domRange.anchorOffset;
  8518. focusNode = domRange.focusNode;
  8519. focusOffset = domRange.focusOffset;
  8520. isCollapsed = domRange.isCollapsed;
  8521. } else {
  8522. anchorNode = domRange.startContainer;
  8523. anchorOffset = domRange.startOffset;
  8524. focusNode = domRange.endContainer;
  8525. focusOffset = domRange.endOffset;
  8526. isCollapsed = domRange.collapsed;
  8527. }
  8528. }
  8529. if (anchorNode == null || focusNode == null || anchorOffset == null || focusOffset == null) {
  8530. throw new Error("Cannot resolve a Slate range from DOM range: ".concat(domRange));
  8531. }
  8532. var anchor = ReactEditor.toSlatePoint(editor, [anchorNode, anchorOffset]);
  8533. var focus = isCollapsed ? anchor : ReactEditor.toSlatePoint(editor, [focusNode, focusOffset]);
  8534. return {
  8535. anchor,
  8536. focus
  8537. };
  8538. }
  8539. };
  8540. /**
  8541. * A React context for sharing the `focused` state of the editor.
  8542. */
  8543. var FocusedContext = React$1.createContext(false);
  8544. /**
  8545. * Get the current `focused` state of the editor.
  8546. */
  8547. var useFocused = () => {
  8548. return React$1.useContext(FocusedContext);
  8549. };
  8550. /**
  8551. * A wrapper around the provider to handle `onChange` events, because the editor
  8552. * is a mutable singleton so it won't ever register as "changed" otherwise.
  8553. */
  8554. const Slate = (props) => {
  8555. const { editor, children, onChange, value, ...rest } = props;
  8556. const [key, setKey] = React$1.useState(0);
  8557. const context = React$1.useMemo(() => {
  8558. editor.children = value;
  8559. Object.assign(editor, rest);
  8560. return [editor];
  8561. }, [key, value, ...Object.values(rest)]);
  8562. const onContextChange = React$1.useCallback(() => {
  8563. onChange(editor.children);
  8564. setKey(key + 1);
  8565. }, [key, onChange]);
  8566. EDITOR_TO_ON_CHANGE.set(editor, onContextChange);
  8567. return (React__default.createElement(SlateContext.Provider, { value: context },
  8568. React__default.createElement(EditorContext.Provider, { value: editor },
  8569. React__default.createElement(FocusedContext.Provider, { value: ReactEditor.isFocused(editor) }, children))));
  8570. };
  8571. /**
  8572. * `withReact` adds React and DOM specific behaviors to the editor.
  8573. */
  8574. var withReact = editor => {
  8575. var e = editor;
  8576. var {
  8577. apply,
  8578. onChange
  8579. } = e;
  8580. e.apply = op => {
  8581. var matches = [];
  8582. switch (op.type) {
  8583. case 'insert_text':
  8584. case 'remove_text':
  8585. case 'set_node':
  8586. {
  8587. for (var [node, path] of dist.Editor.levels(e, {
  8588. at: op.path
  8589. })) {
  8590. var key = ReactEditor.findKey(e, node);
  8591. matches.push([path, key]);
  8592. }
  8593. break;
  8594. }
  8595. case 'insert_node':
  8596. case 'remove_node':
  8597. case 'merge_node':
  8598. case 'split_node':
  8599. {
  8600. for (var [_node, _path] of dist.Editor.levels(e, {
  8601. at: dist.Path.parent(op.path)
  8602. })) {
  8603. var _key = ReactEditor.findKey(e, _node);
  8604. matches.push([_path, _key]);
  8605. }
  8606. break;
  8607. }
  8608. }
  8609. apply(op);
  8610. for (var [_path2, _key2] of matches) {
  8611. var [_node2] = dist.Editor.node(e, _path2);
  8612. NODE_TO_KEY.set(_node2, _key2);
  8613. }
  8614. };
  8615. e.insertData = data => {
  8616. var fragment = data.getData('application/x-slate-fragment');
  8617. if (fragment) {
  8618. var decoded = decodeURIComponent(window.atob(fragment));
  8619. var parsed = JSON.parse(decoded);
  8620. dist.Transforms.insertFragment(e, parsed);
  8621. return;
  8622. }
  8623. var text = data.getData('text/plain');
  8624. if (text) {
  8625. var lines = text.split('\n');
  8626. var split = false;
  8627. for (var line of lines) {
  8628. if (split) {
  8629. dist.Transforms.splitNodes(e);
  8630. }
  8631. dist.Transforms.insertText(e, line);
  8632. split = true;
  8633. }
  8634. }
  8635. };
  8636. e.onChange = () => {
  8637. // COMPAT: React doesn't batch `setState` hook calls, which means that the
  8638. // children and selection can get out of sync for one render pass. So we
  8639. // have to use this unstable API to ensure it batches them. (2019/12/03)
  8640. // https://github.com/facebook/react/issues/14259#issuecomment-439702367
  8641. ReactDOM.unstable_batchedUpdates(() => {
  8642. var onContextChange = EDITOR_TO_ON_CHANGE.get(e);
  8643. if (onContextChange) {
  8644. onContextChange();
  8645. }
  8646. onChange();
  8647. });
  8648. };
  8649. return e;
  8650. };
  8651. exports.DefaultElement = DefaultElement;
  8652. exports.DefaultLeaf = DefaultLeaf;
  8653. exports.Editable = Editable;
  8654. exports.ReactEditor = ReactEditor;
  8655. exports.Slate = Slate;
  8656. exports.useEditor = useEditor;
  8657. exports.useFocused = useFocused;
  8658. exports.useReadOnly = useReadOnly;
  8659. exports.useSelected = useSelected;
  8660. exports.useSlate = useSlate;
  8661. exports.withReact = withReact;
  8662. });
  8663. unwrapExports(dist$1);
  8664. var dist_1$1 = dist$1.DefaultElement;
  8665. var dist_2$1 = dist$1.DefaultLeaf;
  8666. var dist_3$1 = dist$1.Editable;
  8667. var dist_4$1 = dist$1.ReactEditor;
  8668. var dist_5$1 = dist$1.Slate;
  8669. var dist_6$1 = dist$1.useEditor;
  8670. var dist_7$1 = dist$1.useFocused;
  8671. var dist_8$1 = dist$1.useReadOnly;
  8672. var dist_9$1 = dist$1.useSelected;
  8673. var dist_10$1 = dist$1.useSlate;
  8674. var dist_11$1 = dist$1.withReact;
  8675. var RichTextEditorForSlate = function RichTextEditorForSlate() {
  8676. var editor = useMemo(function () {
  8677. return dist_11$1(dist_15());
  8678. }, []);
  8679. var _useState = useState([{
  8680. type: 'paragraph',
  8681. children: [{
  8682. text: 'A line of text in a paragraph.'
  8683. }]
  8684. }]),
  8685. _useState2 = _slicedToArray(_useState, 2),
  8686. value = _useState2[0],
  8687. setValue = _useState2[1];
  8688. return (// Add the editable component inside the context.
  8689. React$1.createElement(dist_5$1, {
  8690. editor: editor,
  8691. value: value,
  8692. onChange: function onChange(value) {
  8693. console.log('value: ', value);
  8694. setValue(value);
  8695. }
  8696. }, React$1.createElement(dist_3$1, null))
  8697. );
  8698. }; // class RichTextEditorForSlate extends React.Component<RichTextEditorForSlateProps, RichTextEditorForSlateState> {
  8699. export default RichTextEditorForSlate;
  8700. //# sourceMappingURL=index.js.map