Geen omschrijving

index.js 290KB

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