Nenhuma descrição

index.js 289KB

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