No Description

index.js 290KB

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