No Description

index.js 1.8MB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349163501635116352163531635416355163561635716358163591636016361163621636316364163651636616367163681636916370163711637216373163741637516376163771637816379163801638116382163831638416385163861638716388163891639016391163921639316394163951639616397163981639916400164011640216403164041640516406164071640816409164101641116412164131641416415164161641716418164191642016421164221642316424164251642616427164281642916430164311643216433164341643516436164371643816439164401644116442164431644416445164461644716448164491645016451164521645316454164551645616457164581645916460164611646216463164641646516466164671646816469164701647116472164731647416475164761647716478164791648016481164821648316484164851648616487164881648916490164911649216493164941649516496164971649816499165001650116502165031650416505165061650716508165091651016511165121651316514165151651616517165181651916520165211652216523165241652516526165271652816529165301653116532165331653416535165361653716538165391654016541165421654316544165451654616547165481654916550165511655216553165541655516556165571655816559165601656116562165631656416565165661656716568165691657016571165721657316574165751657616577165781657916580165811658216583165841658516586165871658816589165901659116592165931659416595165961659716598165991660016601166021660316604166051660616607166081660916610166111661216613166141661516616166171661816619166201662116622166231662416625166261662716628166291663016631166321663316634166351663616637166381663916640166411664216643166441664516646166471664816649166501665116652166531665416655166561665716658166591666016661166621666316664166651666616667166681666916670166711667216673166741667516676166771667816679166801668116682166831668416685166861668716688166891669016691166921669316694166951669616697166981669916700167011670216703167041670516706167071670816709167101671116712167131671416715167161671716718167191672016721167221672316724167251672616727167281672916730167311673216733167341673516736167371673816739167401674116742167431674416745167461674716748167491675016751167521675316754167551675616757167581675916760167611676216763167641676516766167671676816769167701677116772167731677416775167761677716778167791678016781167821678316784167851678616787167881678916790167911679216793167941679516796167971679816799168001680116802168031680416805168061680716808168091681016811168121681316814168151681616817168181681916820168211682216823168241682516826168271682816829168301683116832168331683416835168361683716838168391684016841168421684316844168451684616847168481684916850168511685216853168541685516856168571685816859168601686116862168631686416865168661686716868168691687016871168721687316874168751687616877168781687916880168811688216883168841688516886168871688816889168901689116892168931689416895168961689716898168991690016901169021690316904169051690616907169081690916910169111691216913169141691516916169171691816919169201692116922169231692416925169261692716928169291693016931169321693316934169351693616937169381693916940169411694216943169441694516946169471694816949169501695116952169531695416955169561695716958169591696016961169621696316964169651696616967169681696916970169711697216973169741697516976169771697816979169801698116982169831698416985169861698716988169891699016991169921699316994169951699616997169981699917000170011700217003170041700517006170071700817009170101701117012170131701417015170161701717018170191702017021170221702317024170251702617027170281702917030170311703217033170341703517036170371703817039170401704117042170431704417045170461704717048170491705017051170521705317054170551705617057170581705917060170611706217063170641706517066170671706817069170701707117072170731707417075170761707717078170791708017081170821708317084170851708617087170881708917090170911709217093170941709517096170971709817099171001710117102171031710417105171061710717108171091711017111171121711317114171151711617117171181711917120171211712217123171241712517126171271712817129171301713117132171331713417135171361713717138171391714017141171421714317144171451714617147171481714917150171511715217153171541715517156171571715817159171601716117162171631716417165171661716717168171691717017171171721717317174171751717617177171781717917180171811718217183171841718517186171871718817189171901719117192171931719417195171961719717198171991720017201172021720317204172051720617207172081720917210172111721217213172141721517216172171721817219172201722117222172231722417225172261722717228172291723017231172321723317234172351723617237172381723917240172411724217243172441724517246172471724817249172501725117252172531725417255172561725717258172591726017261172621726317264172651726617267172681726917270172711727217273172741727517276172771727817279172801728117282172831728417285172861728717288172891729017291172921729317294172951729617297172981729917300173011730217303173041730517306173071730817309173101731117312173131731417315173161731717318173191732017321173221732317324173251732617327173281732917330173311733217333173341733517336173371733817339173401734117342173431734417345173461734717348173491735017351173521735317354173551735617357173581735917360173611736217363173641736517366173671736817369173701737117372173731737417375173761737717378173791738017381173821738317384173851738617387173881738917390173911739217393173941739517396173971739817399174001740117402174031740417405174061740717408174091741017411174121741317414174151741617417174181741917420174211742217423174241742517426174271742817429174301743117432174331743417435174361743717438174391744017441174421744317444174451744617447174481744917450174511745217453174541745517456174571745817459174601746117462174631746417465174661746717468174691747017471174721747317474174751747617477174781747917480174811748217483174841748517486174871748817489174901749117492174931749417495174961749717498174991750017501175021750317504175051750617507175081750917510175111751217513175141751517516175171751817519175201752117522175231752417525175261752717528175291753017531175321753317534175351753617537175381753917540175411754217543175441754517546175471754817549175501755117552175531755417555175561755717558175591756017561175621756317564175651756617567175681756917570175711757217573175741757517576175771757817579175801758117582175831758417585175861758717588175891759017591175921759317594175951759617597175981759917600176011760217603176041760517606176071760817609176101761117612176131761417615176161761717618176191762017621176221762317624176251762617627176281762917630176311763217633176341763517636176371763817639176401764117642176431764417645176461764717648176491765017651176521765317654176551765617657176581765917660176611766217663176641766517666176671766817669176701767117672176731767417675176761767717678176791768017681176821768317684176851768617687176881768917690176911769217693176941769517696176971769817699177001770117702177031770417705177061770717708177091771017711177121771317714177151771617717177181771917720177211772217723177241772517726177271772817729177301773117732177331773417735177361773717738177391774017741177421774317744177451774617747177481774917750177511775217753177541775517756177571775817759177601776117762177631776417765177661776717768177691777017771177721777317774177751777617777177781777917780177811778217783177841778517786177871778817789177901779117792177931779417795177961779717798177991780017801178021780317804178051780617807178081780917810178111781217813178141781517816178171781817819178201782117822178231782417825178261782717828178291783017831178321783317834178351783617837178381783917840178411784217843178441784517846178471784817849178501785117852178531785417855178561785717858178591786017861178621786317864178651786617867178681786917870178711787217873178741787517876178771787817879178801788117882178831788417885178861788717888178891789017891178921789317894178951789617897178981789917900179011790217903179041790517906179071790817909179101791117912179131791417915179161791717918179191792017921179221792317924179251792617927179281792917930179311793217933179341793517936179371793817939179401794117942179431794417945179461794717948179491795017951179521795317954179551795617957179581795917960179611796217963179641796517966179671796817969179701797117972179731797417975179761797717978179791798017981179821798317984179851798617987179881798917990179911799217993179941799517996179971799817999180001800118002180031800418005180061800718008180091801018011180121801318014180151801618017180181801918020180211802218023180241802518026180271802818029180301803118032180331803418035180361803718038180391804018041180421804318044180451804618047180481804918050180511805218053180541805518056180571805818059180601806118062180631806418065180661806718068180691807018071180721807318074180751807618077180781807918080180811808218083180841808518086180871808818089180901809118092180931809418095180961809718098180991810018101181021810318104181051810618107181081810918110181111811218113181141811518116181171811818119181201812118122181231812418125181261812718128181291813018131181321813318134181351813618137181381813918140181411814218143181441814518146181471814818149181501815118152181531815418155181561815718158181591816018161181621816318164181651816618167181681816918170181711817218173181741817518176181771817818179181801818118182181831818418185181861818718188181891819018191181921819318194181951819618197181981819918200182011820218203182041820518206182071820818209182101821118212182131821418215182161821718218182191822018221182221822318224182251822618227182281822918230182311823218233182341823518236182371823818239182401824118242182431824418245182461824718248182491825018251182521825318254182551825618257182581825918260182611826218263182641826518266182671826818269182701827118272182731827418275182761827718278182791828018281182821828318284182851828618287182881828918290182911829218293182941829518296182971829818299183001830118302183031830418305183061830718308183091831018311183121831318314183151831618317183181831918320183211832218323183241832518326183271832818329183301833118332183331833418335183361833718338183391834018341183421834318344183451834618347183481834918350183511835218353183541835518356183571835818359183601836118362183631836418365183661836718368183691837018371183721837318374183751837618377183781837918380183811838218383183841838518386183871838818389183901839118392183931839418395183961839718398183991840018401184021840318404184051840618407184081840918410184111841218413184141841518416184171841818419184201842118422184231842418425184261842718428184291843018431184321843318434184351843618437184381843918440184411844218443184441844518446184471844818449184501845118452184531845418455184561845718458184591846018461184621846318464184651846618467184681846918470184711847218473184741847518476184771847818479184801848118482184831848418485184861848718488184891849018491184921849318494184951849618497184981849918500185011850218503185041850518506185071850818509185101851118512185131851418515185161851718518185191852018521185221852318524185251852618527185281852918530185311853218533185341853518536185371853818539185401854118542185431854418545185461854718548185491855018551185521855318554185551855618557185581855918560185611856218563185641856518566185671856818569185701857118572185731857418575185761857718578185791858018581185821858318584185851858618587185881858918590185911859218593185941859518596185971859818599186001860118602186031860418605186061860718608186091861018611186121861318614186151861618617186181861918620186211862218623186241862518626186271862818629186301863118632186331863418635186361863718638186391864018641186421864318644186451864618647186481864918650186511865218653186541865518656186571865818659186601866118662186631866418665186661866718668186691867018671186721867318674186751867618677186781867918680186811868218683186841868518686186871868818689186901869118692186931869418695186961869718698186991870018701187021870318704187051870618707187081870918710187111871218713187141871518716187171871818719187201872118722187231872418725187261872718728187291873018731187321873318734187351873618737187381873918740187411874218743187441874518746187471874818749187501875118752187531875418755187561875718758187591876018761187621876318764187651876618767187681876918770187711877218773187741877518776187771877818779187801878118782187831878418785187861878718788187891879018791187921879318794187951879618797187981879918800188011880218803188041880518806188071880818809188101881118812188131881418815188161881718818188191882018821188221882318824188251882618827188281882918830188311883218833188341883518836188371883818839188401884118842188431884418845188461884718848188491885018851188521885318854188551885618857188581885918860188611886218863188641886518866188671886818869188701887118872188731887418875188761887718878188791888018881188821888318884188851888618887188881888918890188911889218893188941889518896188971889818899189001890118902189031890418905189061890718908189091891018911189121891318914189151891618917189181891918920189211892218923189241892518926189271892818929189301893118932189331893418935189361893718938189391894018941189421894318944189451894618947189481894918950189511895218953189541895518956189571895818959189601896118962189631896418965189661896718968189691897018971189721897318974189751897618977189781897918980189811898218983189841898518986189871898818989189901899118992189931899418995189961899718998189991900019001190021900319004190051900619007190081900919010190111901219013190141901519016190171901819019190201902119022190231902419025190261902719028190291903019031190321903319034190351903619037190381903919040190411904219043190441904519046190471904819049190501905119052190531905419055190561905719058190591906019061190621906319064190651906619067190681906919070190711907219073190741907519076190771907819079190801908119082190831908419085190861908719088190891909019091190921909319094190951909619097190981909919100191011910219103191041910519106191071910819109191101911119112191131911419115191161911719118191191912019121191221912319124191251912619127191281912919130191311913219133191341913519136191371913819139191401914119142191431914419145191461914719148191491915019151191521915319154191551915619157191581915919160191611916219163191641916519166191671916819169191701917119172191731917419175191761917719178191791918019181191821918319184191851918619187191881918919190191911919219193191941919519196191971919819199192001920119202192031920419205192061920719208192091921019211192121921319214192151921619217192181921919220192211922219223192241922519226192271922819229192301923119232192331923419235192361923719238192391924019241192421924319244192451924619247192481924919250192511925219253192541925519256192571925819259192601926119262192631926419265192661926719268192691927019271192721927319274192751927619277192781927919280192811928219283192841928519286192871928819289192901929119292192931929419295192961929719298192991930019301193021930319304193051930619307193081930919310193111931219313193141931519316193171931819319193201932119322193231932419325193261932719328193291933019331193321933319334193351933619337193381933919340193411934219343193441934519346193471934819349193501935119352193531935419355193561935719358193591936019361193621936319364193651936619367193681936919370193711937219373193741937519376193771937819379193801938119382193831938419385193861938719388193891939019391193921939319394193951939619397193981939919400194011940219403194041940519406194071940819409194101941119412194131941419415194161941719418194191942019421194221942319424194251942619427194281942919430194311943219433194341943519436194371943819439194401944119442194431944419445194461944719448194491945019451194521945319454194551945619457194581945919460194611946219463194641946519466194671946819469194701947119472194731947419475194761947719478194791948019481194821948319484194851948619487194881948919490194911949219493194941949519496194971949819499195001950119502195031950419505195061950719508195091951019511195121951319514195151951619517195181951919520195211952219523195241952519526195271952819529195301953119532195331953419535195361953719538195391954019541195421954319544195451954619547195481954919550195511955219553195541955519556195571955819559195601956119562195631956419565195661956719568195691957019571195721957319574195751957619577195781957919580195811958219583195841958519586195871958819589195901959119592195931959419595195961959719598195991960019601196021960319604196051960619607196081960919610196111961219613196141961519616196171961819619196201962119622196231962419625196261962719628196291963019631196321963319634196351963619637196381963919640196411964219643196441964519646196471964819649196501965119652196531965419655196561965719658196591966019661196621966319664196651966619667196681966919670196711967219673196741967519676196771967819679196801968119682196831968419685196861968719688196891969019691196921969319694196951969619697196981969919700197011970219703197041970519706197071970819709197101971119712197131971419715197161971719718197191972019721197221972319724197251972619727197281972919730197311973219733197341973519736197371973819739197401974119742197431974419745197461974719748197491975019751197521975319754197551975619757197581975919760197611976219763197641976519766197671976819769197701977119772197731977419775197761977719778197791978019781197821978319784197851978619787197881978919790197911979219793197941979519796197971979819799198001980119802198031980419805198061980719808198091981019811198121981319814198151981619817198181981919820198211982219823198241982519826198271982819829198301983119832198331983419835198361983719838198391984019841198421984319844198451984619847198481984919850198511985219853198541985519856198571985819859198601986119862198631986419865198661986719868198691987019871198721987319874198751987619877198781987919880198811988219883198841988519886198871988819889198901989119892198931989419895198961989719898198991990019901199021990319904199051990619907199081990919910199111991219913199141991519916199171991819919199201992119922199231992419925199261992719928199291993019931199321993319934199351993619937199381993919940199411994219943199441994519946199471994819949199501995119952199531995419955199561995719958199591996019961199621996319964199651996619967199681996919970199711997219973199741997519976199771997819979199801998119982199831998419985199861998719988199891999019991199921999319994199951999619997199981999920000200012000220003200042000520006200072000820009200102001120012200132001420015200162001720018200192002020021200222002320024200252002620027200282002920030200312003220033200342003520036200372003820039200402004120042200432004420045200462004720048200492005020051200522005320054200552005620057200582005920060200612006220063200642006520066200672006820069200702007120072200732007420075200762007720078200792008020081200822008320084200852008620087200882008920090200912009220093200942009520096200972009820099201002010120102201032010420105201062010720108201092011020111201122011320114201152011620117201182011920120201212012220123201242012520126201272012820129201302013120132201332013420135201362013720138201392014020141201422014320144201452014620147201482014920150201512015220153201542015520156201572015820159201602016120162201632016420165201662016720168201692017020171201722017320174201752017620177201782017920180201812018220183201842018520186201872018820189201902019120192201932019420195201962019720198201992020020201202022020320204202052020620207202082020920210202112021220213202142021520216202172021820219202202022120222202232022420225202262022720228202292023020231202322023320234202352023620237202382023920240202412024220243202442024520246202472024820249202502025120252202532025420255202562025720258202592026020261202622026320264202652026620267202682026920270202712027220273202742027520276202772027820279202802028120282202832028420285202862028720288202892029020291202922029320294202952029620297202982029920300203012030220303203042030520306203072030820309203102031120312203132031420315203162031720318203192032020321203222032320324203252032620327203282032920330203312033220333203342033520336203372033820339203402034120342203432034420345203462034720348203492035020351203522035320354203552035620357203582035920360203612036220363203642036520366203672036820369203702037120372203732037420375203762037720378203792038020381203822038320384203852038620387203882038920390203912039220393203942039520396203972039820399204002040120402204032040420405204062040720408204092041020411204122041320414204152041620417204182041920420204212042220423204242042520426204272042820429204302043120432204332043420435204362043720438204392044020441204422044320444204452044620447204482044920450204512045220453204542045520456204572045820459204602046120462204632046420465204662046720468204692047020471204722047320474204752047620477204782047920480204812048220483204842048520486204872048820489204902049120492204932049420495204962049720498204992050020501205022050320504205052050620507205082050920510205112051220513205142051520516205172051820519205202052120522205232052420525205262052720528205292053020531205322053320534205352053620537205382053920540205412054220543205442054520546205472054820549205502055120552205532055420555205562055720558205592056020561205622056320564205652056620567205682056920570205712057220573205742057520576205772057820579205802058120582205832058420585205862058720588205892059020591205922059320594205952059620597205982059920600206012060220603206042060520606206072060820609206102061120612206132061420615206162061720618206192062020621206222062320624206252062620627206282062920630206312063220633206342063520636206372063820639206402064120642206432064420645206462064720648206492065020651206522065320654206552065620657206582065920660206612066220663206642066520666206672066820669206702067120672206732067420675206762067720678206792068020681206822068320684206852068620687206882068920690206912069220693206942069520696206972069820699207002070120702207032070420705207062070720708207092071020711207122071320714207152071620717207182071920720207212072220723207242072520726207272072820729207302073120732207332073420735207362073720738207392074020741207422074320744207452074620747207482074920750207512075220753207542075520756207572075820759207602076120762207632076420765207662076720768207692077020771207722077320774207752077620777207782077920780207812078220783207842078520786207872078820789207902079120792207932079420795207962079720798207992080020801208022080320804208052080620807208082080920810208112081220813208142081520816208172081820819208202082120822208232082420825208262082720828208292083020831208322083320834208352083620837208382083920840208412084220843208442084520846208472084820849208502085120852208532085420855208562085720858208592086020861208622086320864208652086620867208682086920870208712087220873208742087520876208772087820879208802088120882208832088420885208862088720888208892089020891208922089320894208952089620897208982089920900209012090220903209042090520906209072090820909209102091120912209132091420915209162091720918209192092020921209222092320924209252092620927209282092920930209312093220933209342093520936209372093820939209402094120942209432094420945209462094720948209492095020951209522095320954209552095620957209582095920960209612096220963209642096520966209672096820969209702097120972209732097420975209762097720978209792098020981209822098320984209852098620987209882098920990209912099220993209942099520996209972099820999210002100121002210032100421005210062100721008210092101021011210122101321014210152101621017210182101921020210212102221023210242102521026210272102821029210302103121032210332103421035210362103721038210392104021041210422104321044210452104621047210482104921050210512105221053210542105521056210572105821059210602106121062210632106421065210662106721068210692107021071210722107321074210752107621077210782107921080210812108221083210842108521086210872108821089210902109121092210932109421095210962109721098210992110021101211022110321104211052110621107211082110921110211112111221113211142111521116211172111821119211202112121122211232112421125211262112721128211292113021131211322113321134211352113621137211382113921140211412114221143211442114521146211472114821149211502115121152211532115421155211562115721158211592116021161211622116321164211652116621167211682116921170211712117221173211742117521176211772117821179211802118121182211832118421185211862118721188211892119021191211922119321194211952119621197211982119921200212012120221203212042120521206212072120821209212102121121212212132121421215212162121721218212192122021221212222122321224212252122621227212282122921230212312123221233212342123521236212372123821239212402124121242212432124421245212462124721248212492125021251212522125321254212552125621257212582125921260212612126221263212642126521266212672126821269212702127121272212732127421275212762127721278212792128021281212822128321284212852128621287212882128921290212912129221293212942129521296212972129821299213002130121302213032130421305213062130721308213092131021311213122131321314213152131621317213182131921320213212132221323213242132521326213272132821329213302133121332213332133421335213362133721338213392134021341213422134321344213452134621347213482134921350213512135221353213542135521356213572135821359213602136121362213632136421365213662136721368213692137021371213722137321374213752137621377213782137921380213812138221383213842138521386213872138821389213902139121392213932139421395213962139721398213992140021401214022140321404214052140621407214082140921410214112141221413214142141521416214172141821419214202142121422214232142421425214262142721428214292143021431214322143321434214352143621437214382143921440214412144221443214442144521446214472144821449214502145121452214532145421455214562145721458214592146021461214622146321464214652146621467214682146921470214712147221473214742147521476214772147821479214802148121482214832148421485214862148721488214892149021491214922149321494214952149621497214982149921500215012150221503215042150521506215072150821509215102151121512215132151421515215162151721518215192152021521215222152321524215252152621527215282152921530215312153221533215342153521536215372153821539215402154121542215432154421545215462154721548215492155021551215522155321554215552155621557215582155921560215612156221563215642156521566215672156821569215702157121572215732157421575215762157721578215792158021581215822158321584215852158621587215882158921590215912159221593215942159521596215972159821599216002160121602216032160421605216062160721608216092161021611216122161321614216152161621617216182161921620216212162221623216242162521626216272162821629216302163121632216332163421635216362163721638216392164021641216422164321644216452164621647216482164921650216512165221653216542165521656216572165821659216602166121662216632166421665216662166721668216692167021671216722167321674216752167621677216782167921680216812168221683216842168521686216872168821689216902169121692216932169421695216962169721698216992170021701217022170321704217052170621707217082170921710217112171221713217142171521716217172171821719217202172121722217232172421725217262172721728217292173021731217322173321734217352173621737217382173921740217412174221743217442174521746217472174821749217502175121752217532175421755217562175721758217592176021761217622176321764217652176621767217682176921770217712177221773217742177521776217772177821779217802178121782217832178421785217862178721788217892179021791217922179321794217952179621797217982179921800218012180221803218042180521806218072180821809218102181121812218132181421815218162181721818218192182021821218222182321824218252182621827218282182921830218312183221833218342183521836218372183821839218402184121842218432184421845218462184721848218492185021851218522185321854218552185621857218582185921860218612186221863218642186521866218672186821869218702187121872218732187421875218762187721878218792188021881218822188321884218852188621887218882188921890218912189221893218942189521896218972189821899219002190121902219032190421905219062190721908219092191021911219122191321914219152191621917219182191921920219212192221923219242192521926219272192821929219302193121932219332193421935219362193721938219392194021941219422194321944219452194621947219482194921950219512195221953219542195521956219572195821959219602196121962219632196421965219662196721968219692197021971219722197321974219752197621977219782197921980219812198221983219842198521986219872198821989219902199121992219932199421995219962199721998219992200022001220022200322004220052200622007220082200922010220112201222013220142201522016220172201822019220202202122022220232202422025220262202722028220292203022031220322203322034220352203622037220382203922040220412204222043220442204522046220472204822049220502205122052220532205422055220562205722058220592206022061220622206322064220652206622067220682206922070220712207222073220742207522076220772207822079220802208122082220832208422085220862208722088220892209022091220922209322094220952209622097220982209922100221012210222103221042210522106221072210822109221102211122112221132211422115221162211722118221192212022121221222212322124221252212622127221282212922130221312213222133221342213522136221372213822139221402214122142221432214422145221462214722148221492215022151221522215322154221552215622157221582215922160221612216222163221642216522166221672216822169221702217122172221732217422175221762217722178221792218022181221822218322184221852218622187221882218922190221912219222193221942219522196221972219822199222002220122202222032220422205222062220722208222092221022211222122221322214222152221622217222182221922220222212222222223222242222522226222272222822229222302223122232222332223422235222362223722238222392224022241222422224322244222452224622247222482224922250222512225222253222542225522256222572225822259222602226122262222632226422265222662226722268222692227022271222722227322274222752227622277222782227922280222812228222283222842228522286222872228822289222902229122292222932229422295222962229722298222992230022301223022230322304223052230622307223082230922310223112231222313223142231522316223172231822319223202232122322223232232422325223262232722328223292233022331223322233322334223352233622337223382233922340223412234222343223442234522346223472234822349223502235122352223532235422355223562235722358223592236022361223622236322364223652236622367223682236922370223712237222373223742237522376223772237822379223802238122382223832238422385223862238722388223892239022391223922239322394223952239622397223982239922400224012240222403224042240522406224072240822409224102241122412224132241422415224162241722418224192242022421224222242322424224252242622427224282242922430224312243222433224342243522436224372243822439224402244122442224432244422445224462244722448224492245022451224522245322454224552245622457224582245922460224612246222463224642246522466224672246822469224702247122472224732247422475224762247722478224792248022481224822248322484224852248622487224882248922490224912249222493224942249522496224972249822499225002250122502225032250422505225062250722508225092251022511225122251322514225152251622517225182251922520225212252222523225242252522526225272252822529225302253122532225332253422535225362253722538225392254022541225422254322544225452254622547225482254922550225512255222553225542255522556225572255822559225602256122562225632256422565225662256722568225692257022571225722257322574225752257622577225782257922580225812258222583225842258522586225872258822589225902259122592225932259422595225962259722598225992260022601226022260322604226052260622607226082260922610226112261222613226142261522616226172261822619226202262122622226232262422625226262262722628226292263022631226322263322634226352263622637226382263922640226412264222643226442264522646226472264822649226502265122652226532265422655226562265722658226592266022661226622266322664226652266622667226682266922670226712267222673226742267522676226772267822679226802268122682226832268422685226862268722688226892269022691226922269322694226952269622697226982269922700227012270222703227042270522706227072270822709227102271122712227132271422715227162271722718227192272022721227222272322724227252272622727227282272922730227312273222733227342273522736227372273822739227402274122742227432274422745227462274722748227492275022751227522275322754227552275622757227582275922760227612276222763227642276522766227672276822769227702277122772227732277422775227762277722778227792278022781227822278322784227852278622787227882278922790227912279222793227942279522796227972279822799228002280122802228032280422805228062280722808228092281022811228122281322814228152281622817228182281922820228212282222823228242282522826228272282822829228302283122832228332283422835228362283722838228392284022841228422284322844228452284622847228482284922850228512285222853228542285522856228572285822859228602286122862228632286422865228662286722868228692287022871228722287322874228752287622877228782287922880228812288222883228842288522886228872288822889228902289122892228932289422895228962289722898228992290022901229022290322904229052290622907229082290922910229112291222913229142291522916229172291822919229202292122922229232292422925229262292722928229292293022931229322293322934229352293622937229382293922940229412294222943229442294522946229472294822949229502295122952229532295422955229562295722958229592296022961229622296322964229652296622967229682296922970229712297222973229742297522976229772297822979229802298122982229832298422985229862298722988229892299022991229922299322994229952299622997229982299923000230012300223003230042300523006230072300823009230102301123012230132301423015230162301723018230192302023021230222302323024230252302623027230282302923030230312303223033230342303523036230372303823039230402304123042230432304423045230462304723048230492305023051230522305323054230552305623057230582305923060230612306223063230642306523066230672306823069230702307123072230732307423075230762307723078230792308023081230822308323084230852308623087230882308923090230912309223093230942309523096230972309823099231002310123102231032310423105231062310723108231092311023111231122311323114231152311623117231182311923120231212312223123231242312523126231272312823129231302313123132231332313423135231362313723138231392314023141231422314323144231452314623147231482314923150231512315223153231542315523156231572315823159231602316123162231632316423165231662316723168231692317023171231722317323174231752317623177231782317923180231812318223183231842318523186231872318823189231902319123192231932319423195231962319723198231992320023201232022320323204232052320623207232082320923210232112321223213232142321523216232172321823219232202322123222232232322423225232262322723228232292323023231232322323323234232352323623237232382323923240232412324223243232442324523246232472324823249232502325123252232532325423255232562325723258232592326023261232622326323264232652326623267232682326923270232712327223273232742327523276232772327823279232802328123282232832328423285232862328723288232892329023291232922329323294232952329623297232982329923300233012330223303233042330523306233072330823309233102331123312233132331423315233162331723318233192332023321233222332323324233252332623327233282332923330233312333223333233342333523336233372333823339233402334123342233432334423345233462334723348233492335023351233522335323354233552335623357233582335923360233612336223363233642336523366233672336823369233702337123372233732337423375233762337723378233792338023381233822338323384233852338623387233882338923390233912339223393233942339523396233972339823399234002340123402234032340423405234062340723408234092341023411234122341323414234152341623417234182341923420234212342223423234242342523426234272342823429234302343123432234332343423435234362343723438234392344023441234422344323444234452344623447234482344923450234512345223453234542345523456234572345823459234602346123462234632346423465234662346723468234692347023471234722347323474234752347623477234782347923480234812348223483234842348523486234872348823489234902349123492234932349423495234962349723498234992350023501235022350323504235052350623507235082350923510235112351223513235142351523516235172351823519235202352123522235232352423525235262352723528235292353023531235322353323534235352353623537235382353923540235412354223543235442354523546235472354823549235502355123552235532355423555235562355723558235592356023561235622356323564235652356623567235682356923570235712357223573235742357523576235772357823579235802358123582235832358423585235862358723588235892359023591235922359323594235952359623597235982359923600236012360223603236042360523606236072360823609236102361123612236132361423615236162361723618236192362023621236222362323624236252362623627236282362923630236312363223633236342363523636236372363823639236402364123642236432364423645236462364723648236492365023651236522365323654236552365623657236582365923660236612366223663236642366523666236672366823669236702367123672236732367423675236762367723678236792368023681236822368323684236852368623687236882368923690236912369223693236942369523696236972369823699237002370123702237032370423705237062370723708237092371023711237122371323714237152371623717237182371923720237212372223723237242372523726237272372823729237302373123732237332373423735237362373723738237392374023741237422374323744237452374623747237482374923750237512375223753237542375523756237572375823759237602376123762237632376423765237662376723768237692377023771237722377323774237752377623777237782377923780237812378223783237842378523786237872378823789237902379123792237932379423795237962379723798237992380023801238022380323804238052380623807238082380923810238112381223813238142381523816238172381823819238202382123822238232382423825238262382723828238292383023831238322383323834238352383623837238382383923840238412384223843238442384523846238472384823849238502385123852238532385423855238562385723858238592386023861238622386323864238652386623867238682386923870238712387223873238742387523876238772387823879238802388123882238832388423885238862388723888238892389023891238922389323894238952389623897238982389923900239012390223903239042390523906239072390823909239102391123912239132391423915239162391723918239192392023921239222392323924239252392623927239282392923930239312393223933239342393523936239372393823939239402394123942239432394423945239462394723948239492395023951239522395323954239552395623957239582395923960239612396223963239642396523966239672396823969239702397123972239732397423975239762397723978239792398023981239822398323984239852398623987239882398923990239912399223993239942399523996239972399823999240002400124002240032400424005240062400724008240092401024011240122401324014240152401624017240182401924020240212402224023240242402524026240272402824029240302403124032240332403424035240362403724038240392404024041240422404324044240452404624047240482404924050240512405224053240542405524056240572405824059240602406124062240632406424065240662406724068240692407024071240722407324074240752407624077240782407924080240812408224083240842408524086240872408824089240902409124092240932409424095240962409724098240992410024101241022410324104241052410624107241082410924110241112411224113241142411524116241172411824119241202412124122241232412424125241262412724128241292413024131241322413324134241352413624137241382413924140241412414224143241442414524146241472414824149241502415124152241532415424155241562415724158241592416024161241622416324164241652416624167241682416924170241712417224173241742417524176241772417824179241802418124182241832418424185241862418724188241892419024191241922419324194241952419624197241982419924200242012420224203242042420524206242072420824209242102421124212242132421424215242162421724218242192422024221242222422324224242252422624227242282422924230242312423224233242342423524236242372423824239242402424124242242432424424245242462424724248242492425024251242522425324254242552425624257242582425924260242612426224263242642426524266242672426824269242702427124272242732427424275242762427724278242792428024281242822428324284242852428624287242882428924290242912429224293242942429524296242972429824299243002430124302243032430424305243062430724308243092431024311243122431324314243152431624317243182431924320243212432224323243242432524326243272432824329243302433124332243332433424335243362433724338243392434024341243422434324344243452434624347243482434924350243512435224353243542435524356243572435824359243602436124362243632436424365243662436724368243692437024371243722437324374243752437624377243782437924380243812438224383243842438524386243872438824389243902439124392243932439424395243962439724398243992440024401244022440324404244052440624407244082440924410244112441224413244142441524416244172441824419244202442124422244232442424425244262442724428244292443024431244322443324434244352443624437244382443924440244412444224443244442444524446244472444824449244502445124452244532445424455244562445724458244592446024461244622446324464244652446624467244682446924470244712447224473244742447524476244772447824479244802448124482244832448424485244862448724488244892449024491244922449324494244952449624497244982449924500245012450224503245042450524506245072450824509245102451124512245132451424515245162451724518245192452024521245222452324524245252452624527245282452924530245312453224533245342453524536245372453824539245402454124542245432454424545245462454724548245492455024551245522455324554245552455624557245582455924560245612456224563245642456524566245672456824569245702457124572245732457424575245762457724578245792458024581245822458324584245852458624587245882458924590245912459224593245942459524596245972459824599246002460124602246032460424605246062460724608246092461024611246122461324614246152461624617246182461924620246212462224623246242462524626246272462824629246302463124632246332463424635246362463724638246392464024641246422464324644246452464624647246482464924650246512465224653246542465524656246572465824659246602466124662246632466424665246662466724668246692467024671246722467324674246752467624677246782467924680246812468224683246842468524686246872468824689246902469124692246932469424695246962469724698246992470024701247022470324704247052470624707247082470924710247112471224713247142471524716247172471824719247202472124722247232472424725247262472724728247292473024731247322473324734247352473624737247382473924740247412474224743247442474524746247472474824749247502475124752247532475424755247562475724758247592476024761247622476324764247652476624767247682476924770247712477224773247742477524776247772477824779247802478124782247832478424785247862478724788247892479024791247922479324794247952479624797247982479924800248012480224803248042480524806248072480824809248102481124812248132481424815248162481724818248192482024821248222482324824248252482624827248282482924830248312483224833248342483524836248372483824839248402484124842248432484424845248462484724848248492485024851248522485324854248552485624857248582485924860248612486224863248642486524866248672486824869248702487124872248732487424875248762487724878248792488024881248822488324884248852488624887248882488924890248912489224893248942489524896248972489824899249002490124902249032490424905249062490724908249092491024911249122491324914249152491624917249182491924920249212492224923249242492524926249272492824929249302493124932249332493424935249362493724938249392494024941249422494324944249452494624947249482494924950249512495224953249542495524956249572495824959249602496124962249632496424965249662496724968249692497024971249722497324974249752497624977249782497924980249812498224983249842498524986249872498824989249902499124992249932499424995249962499724998249992500025001250022500325004250052500625007250082500925010250112501225013250142501525016250172501825019250202502125022250232502425025250262502725028250292503025031250322503325034250352503625037250382503925040250412504225043250442504525046250472504825049250502505125052250532505425055250562505725058250592506025061250622506325064250652506625067250682506925070250712507225073250742507525076250772507825079250802508125082250832508425085250862508725088250892509025091250922509325094250952509625097250982509925100251012510225103251042510525106251072510825109251102511125112251132511425115251162511725118251192512025121251222512325124251252512625127251282512925130251312513225133251342513525136251372513825139251402514125142251432514425145251462514725148251492515025151251522515325154251552515625157251582515925160251612516225163251642516525166251672516825169251702517125172251732517425175251762517725178251792518025181251822518325184251852518625187251882518925190251912519225193251942519525196251972519825199252002520125202252032520425205252062520725208252092521025211252122521325214252152521625217252182521925220252212522225223252242522525226252272522825229252302523125232252332523425235252362523725238252392524025241252422524325244252452524625247252482524925250252512525225253252542525525256252572525825259252602526125262252632526425265252662526725268252692527025271252722527325274252752527625277252782527925280252812528225283252842528525286252872528825289252902529125292252932529425295252962529725298252992530025301253022530325304253052530625307253082530925310253112531225313253142531525316253172531825319253202532125322253232532425325253262532725328253292533025331253322533325334253352533625337253382533925340253412534225343253442534525346253472534825349253502535125352253532535425355253562535725358253592536025361253622536325364253652536625367253682536925370253712537225373253742537525376253772537825379253802538125382253832538425385253862538725388253892539025391253922539325394253952539625397253982539925400254012540225403254042540525406254072540825409254102541125412254132541425415254162541725418254192542025421254222542325424254252542625427254282542925430254312543225433254342543525436254372543825439254402544125442254432544425445254462544725448254492545025451254522545325454254552545625457254582545925460254612546225463254642546525466254672546825469254702547125472254732547425475254762547725478254792548025481254822548325484254852548625487254882548925490254912549225493254942549525496254972549825499255002550125502255032550425505255062550725508255092551025511255122551325514255152551625517255182551925520255212552225523255242552525526255272552825529255302553125532255332553425535255362553725538255392554025541255422554325544255452554625547255482554925550255512555225553255542555525556255572555825559255602556125562255632556425565255662556725568255692557025571255722557325574255752557625577255782557925580255812558225583255842558525586255872558825589255902559125592255932559425595255962559725598255992560025601256022560325604256052560625607256082560925610256112561225613256142561525616256172561825619256202562125622256232562425625256262562725628256292563025631256322563325634256352563625637256382563925640256412564225643256442564525646256472564825649256502565125652256532565425655256562565725658256592566025661256622566325664256652566625667256682566925670256712567225673256742567525676256772567825679256802568125682256832568425685256862568725688256892569025691256922569325694256952569625697256982569925700257012570225703257042570525706257072570825709257102571125712257132571425715257162571725718257192572025721257222572325724257252572625727257282572925730257312573225733257342573525736257372573825739257402574125742257432574425745257462574725748257492575025751257522575325754257552575625757257582575925760257612576225763257642576525766257672576825769257702577125772257732577425775257762577725778257792578025781257822578325784257852578625787257882578925790257912579225793257942579525796257972579825799258002580125802258032580425805258062580725808258092581025811258122581325814258152581625817258182581925820258212582225823258242582525826258272582825829258302583125832258332583425835258362583725838258392584025841258422584325844258452584625847258482584925850258512585225853258542585525856258572585825859258602586125862258632586425865258662586725868258692587025871258722587325874258752587625877258782587925880258812588225883258842588525886258872588825889258902589125892258932589425895258962589725898258992590025901259022590325904259052590625907259082590925910259112591225913259142591525916259172591825919259202592125922259232592425925259262592725928259292593025931259322593325934259352593625937259382593925940259412594225943259442594525946259472594825949259502595125952259532595425955259562595725958259592596025961259622596325964259652596625967259682596925970259712597225973259742597525976259772597825979259802598125982259832598425985259862598725988259892599025991259922599325994259952599625997259982599926000260012600226003260042600526006260072600826009260102601126012260132601426015260162601726018260192602026021260222602326024260252602626027260282602926030260312603226033260342603526036260372603826039260402604126042260432604426045260462604726048260492605026051260522605326054260552605626057260582605926060260612606226063260642606526066260672606826069260702607126072260732607426075260762607726078260792608026081260822608326084260852608626087260882608926090260912609226093260942609526096260972609826099261002610126102261032610426105261062610726108261092611026111261122611326114261152611626117261182611926120261212612226123261242612526126261272612826129261302613126132261332613426135261362613726138261392614026141261422614326144261452614626147261482614926150261512615226153261542615526156261572615826159261602616126162261632616426165261662616726168261692617026171261722617326174261752617626177261782617926180261812618226183261842618526186261872618826189261902619126192261932619426195261962619726198261992620026201262022620326204262052620626207262082620926210262112621226213262142621526216262172621826219262202622126222262232622426225262262622726228262292623026231262322623326234262352623626237262382623926240262412624226243262442624526246262472624826249262502625126252262532625426255262562625726258262592626026261262622626326264262652626626267262682626926270262712627226273262742627526276262772627826279262802628126282262832628426285262862628726288262892629026291262922629326294262952629626297262982629926300263012630226303263042630526306263072630826309263102631126312263132631426315263162631726318263192632026321263222632326324263252632626327263282632926330263312633226333263342633526336263372633826339263402634126342263432634426345263462634726348263492635026351263522635326354263552635626357263582635926360263612636226363263642636526366263672636826369263702637126372263732637426375263762637726378263792638026381263822638326384263852638626387263882638926390263912639226393263942639526396263972639826399264002640126402264032640426405264062640726408264092641026411264122641326414264152641626417264182641926420264212642226423264242642526426264272642826429264302643126432264332643426435264362643726438264392644026441264422644326444264452644626447264482644926450264512645226453264542645526456264572645826459264602646126462264632646426465264662646726468264692647026471264722647326474264752647626477264782647926480264812648226483264842648526486264872648826489264902649126492264932649426495264962649726498264992650026501265022650326504265052650626507265082650926510265112651226513265142651526516265172651826519265202652126522265232652426525265262652726528265292653026531265322653326534265352653626537265382653926540265412654226543265442654526546265472654826549265502655126552265532655426555265562655726558265592656026561265622656326564265652656626567265682656926570265712657226573265742657526576265772657826579265802658126582265832658426585265862658726588265892659026591265922659326594265952659626597265982659926600266012660226603266042660526606266072660826609266102661126612266132661426615266162661726618266192662026621266222662326624266252662626627266282662926630266312663226633266342663526636266372663826639266402664126642266432664426645266462664726648266492665026651266522665326654266552665626657266582665926660266612666226663266642666526666266672666826669266702667126672266732667426675266762667726678266792668026681266822668326684266852668626687266882668926690266912669226693266942669526696266972669826699267002670126702267032670426705267062670726708267092671026711267122671326714267152671626717267182671926720267212672226723267242672526726267272672826729267302673126732267332673426735267362673726738267392674026741267422674326744267452674626747267482674926750267512675226753267542675526756267572675826759267602676126762267632676426765267662676726768267692677026771267722677326774267752677626777267782677926780267812678226783267842678526786267872678826789267902679126792267932679426795267962679726798267992680026801268022680326804268052680626807268082680926810268112681226813268142681526816268172681826819268202682126822268232682426825268262682726828268292683026831268322683326834268352683626837268382683926840268412684226843268442684526846268472684826849268502685126852268532685426855268562685726858268592686026861268622686326864268652686626867268682686926870268712687226873268742687526876268772687826879268802688126882268832688426885268862688726888268892689026891268922689326894268952689626897268982689926900269012690226903269042690526906269072690826909269102691126912269132691426915269162691726918269192692026921269222692326924269252692626927269282692926930269312693226933269342693526936269372693826939269402694126942269432694426945269462694726948269492695026951269522695326954269552695626957269582695926960269612696226963269642696526966269672696826969269702697126972269732697426975269762697726978269792698026981269822698326984269852698626987269882698926990269912699226993269942699526996269972699826999270002700127002270032700427005270062700727008270092701027011270122701327014270152701627017270182701927020270212702227023270242702527026270272702827029270302703127032270332703427035270362703727038270392704027041270422704327044270452704627047270482704927050270512705227053270542705527056270572705827059270602706127062270632706427065270662706727068270692707027071270722707327074270752707627077270782707927080270812708227083270842708527086270872708827089270902709127092270932709427095270962709727098270992710027101271022710327104271052710627107271082710927110271112711227113271142711527116271172711827119271202712127122271232712427125271262712727128271292713027131271322713327134271352713627137271382713927140271412714227143271442714527146271472714827149271502715127152271532715427155271562715727158271592716027161271622716327164271652716627167271682716927170271712717227173271742717527176271772717827179271802718127182271832718427185271862718727188271892719027191271922719327194271952719627197271982719927200272012720227203272042720527206272072720827209272102721127212272132721427215272162721727218272192722027221272222722327224272252722627227272282722927230272312723227233272342723527236272372723827239272402724127242272432724427245272462724727248272492725027251272522725327254272552725627257272582725927260272612726227263272642726527266272672726827269272702727127272272732727427275272762727727278272792728027281272822728327284272852728627287272882728927290272912729227293272942729527296272972729827299273002730127302273032730427305273062730727308273092731027311273122731327314273152731627317273182731927320273212732227323273242732527326273272732827329273302733127332273332733427335273362733727338273392734027341273422734327344273452734627347273482734927350273512735227353273542735527356273572735827359273602736127362273632736427365273662736727368273692737027371273722737327374273752737627377273782737927380273812738227383273842738527386273872738827389273902739127392273932739427395273962739727398273992740027401274022740327404274052740627407274082740927410274112741227413274142741527416274172741827419274202742127422274232742427425274262742727428274292743027431274322743327434274352743627437274382743927440274412744227443274442744527446274472744827449274502745127452274532745427455274562745727458274592746027461274622746327464274652746627467274682746927470274712747227473274742747527476274772747827479274802748127482274832748427485274862748727488274892749027491274922749327494274952749627497274982749927500275012750227503275042750527506275072750827509275102751127512275132751427515275162751727518275192752027521275222752327524275252752627527275282752927530275312753227533275342753527536275372753827539275402754127542275432754427545275462754727548275492755027551275522755327554275552755627557275582755927560275612756227563275642756527566275672756827569275702757127572275732757427575275762757727578275792758027581275822758327584275852758627587275882758927590275912759227593275942759527596275972759827599276002760127602276032760427605276062760727608276092761027611276122761327614276152761627617276182761927620276212762227623276242762527626276272762827629276302763127632276332763427635276362763727638276392764027641276422764327644276452764627647276482764927650276512765227653276542765527656276572765827659276602766127662276632766427665276662766727668276692767027671276722767327674276752767627677276782767927680276812768227683276842768527686276872768827689276902769127692276932769427695276962769727698276992770027701277022770327704277052770627707277082770927710277112771227713277142771527716277172771827719277202772127722277232772427725277262772727728277292773027731277322773327734277352773627737277382773927740277412774227743277442774527746277472774827749277502775127752277532775427755277562775727758277592776027761277622776327764277652776627767277682776927770277712777227773277742777527776277772777827779277802778127782277832778427785277862778727788277892779027791277922779327794277952779627797277982779927800278012780227803278042780527806278072780827809278102781127812278132781427815278162781727818278192782027821278222782327824278252782627827278282782927830278312783227833278342783527836278372783827839278402784127842278432784427845278462784727848278492785027851278522785327854278552785627857278582785927860278612786227863278642786527866278672786827869278702787127872278732787427875278762787727878278792788027881278822788327884278852788627887278882788927890278912789227893278942789527896278972789827899279002790127902279032790427905279062790727908279092791027911279122791327914279152791627917279182791927920279212792227923279242792527926279272792827929279302793127932279332793427935279362793727938279392794027941279422794327944279452794627947279482794927950279512795227953279542795527956279572795827959279602796127962279632796427965279662796727968279692797027971279722797327974279752797627977279782797927980279812798227983279842798527986279872798827989279902799127992279932799427995279962799727998279992800028001280022800328004280052800628007280082800928010280112801228013280142801528016280172801828019280202802128022280232802428025280262802728028280292803028031280322803328034280352803628037280382803928040280412804228043280442804528046280472804828049280502805128052280532805428055280562805728058280592806028061280622806328064280652806628067280682806928070280712807228073280742807528076280772807828079280802808128082280832808428085280862808728088280892809028091280922809328094280952809628097280982809928100281012810228103281042810528106281072810828109281102811128112281132811428115281162811728118281192812028121281222812328124281252812628127281282812928130281312813228133281342813528136281372813828139281402814128142281432814428145281462814728148281492815028151281522815328154281552815628157281582815928160281612816228163281642816528166281672816828169281702817128172281732817428175281762817728178281792818028181281822818328184281852818628187281882818928190281912819228193281942819528196281972819828199282002820128202282032820428205282062820728208282092821028211282122821328214282152821628217282182821928220282212822228223282242822528226282272822828229282302823128232282332823428235282362823728238282392824028241282422824328244282452824628247282482824928250282512825228253282542825528256282572825828259282602826128262282632826428265282662826728268282692827028271282722827328274282752827628277282782827928280282812828228283282842828528286282872828828289282902829128292282932829428295282962829728298282992830028301283022830328304283052830628307283082830928310283112831228313283142831528316283172831828319283202832128322283232832428325283262832728328283292833028331283322833328334283352833628337283382833928340283412834228343283442834528346283472834828349283502835128352283532835428355283562835728358283592836028361283622836328364283652836628367283682836928370283712837228373283742837528376283772837828379283802838128382283832838428385283862838728388283892839028391283922839328394283952839628397283982839928400284012840228403284042840528406284072840828409284102841128412284132841428415284162841728418284192842028421284222842328424284252842628427284282842928430284312843228433284342843528436284372843828439284402844128442284432844428445284462844728448284492845028451284522845328454284552845628457284582845928460284612846228463284642846528466284672846828469284702847128472284732847428475284762847728478284792848028481284822848328484284852848628487284882848928490284912849228493284942849528496284972849828499285002850128502285032850428505285062850728508285092851028511285122851328514285152851628517285182851928520285212852228523285242852528526285272852828529285302853128532285332853428535285362853728538285392854028541285422854328544285452854628547285482854928550285512855228553285542855528556285572855828559285602856128562285632856428565285662856728568285692857028571285722857328574285752857628577285782857928580285812858228583285842858528586285872858828589285902859128592285932859428595285962859728598285992860028601286022860328604286052860628607286082860928610286112861228613286142861528616286172861828619286202862128622286232862428625286262862728628286292863028631286322863328634286352863628637286382863928640286412864228643286442864528646286472864828649286502865128652286532865428655286562865728658286592866028661286622866328664286652866628667286682866928670286712867228673286742867528676286772867828679286802868128682286832868428685286862868728688286892869028691286922869328694286952869628697286982869928700287012870228703287042870528706287072870828709287102871128712287132871428715287162871728718287192872028721287222872328724287252872628727287282872928730287312873228733287342873528736287372873828739287402874128742287432874428745287462874728748287492875028751287522875328754287552875628757287582875928760287612876228763287642876528766287672876828769287702877128772287732877428775287762877728778287792878028781287822878328784287852878628787287882878928790287912879228793287942879528796287972879828799288002880128802288032880428805288062880728808288092881028811288122881328814288152881628817288182881928820288212882228823288242882528826288272882828829288302883128832288332883428835288362883728838288392884028841288422884328844288452884628847288482884928850288512885228853288542885528856288572885828859288602886128862288632886428865288662886728868288692887028871288722887328874288752887628877288782887928880288812888228883288842888528886288872888828889288902889128892288932889428895288962889728898288992890028901289022890328904289052890628907289082890928910289112891228913289142891528916289172891828919289202892128922289232892428925289262892728928289292893028931289322893328934289352893628937289382893928940289412894228943289442894528946289472894828949289502895128952289532895428955289562895728958289592896028961289622896328964289652896628967289682896928970289712897228973289742897528976289772897828979289802898128982289832898428985289862898728988289892899028991289922899328994289952899628997289982899929000290012900229003290042900529006290072900829009290102901129012290132901429015290162901729018290192902029021290222902329024290252902629027290282902929030290312903229033290342903529036290372903829039290402904129042290432904429045290462904729048290492905029051290522905329054290552905629057290582905929060290612906229063290642906529066290672906829069290702907129072290732907429075290762907729078290792908029081290822908329084290852908629087290882908929090290912909229093290942909529096290972909829099291002910129102291032910429105291062910729108291092911029111291122911329114291152911629117291182911929120291212912229123291242912529126291272912829129291302913129132291332913429135291362913729138291392914029141291422914329144291452914629147291482914929150291512915229153291542915529156291572915829159291602916129162291632916429165291662916729168291692917029171291722917329174291752917629177291782917929180291812918229183291842918529186291872918829189291902919129192291932919429195291962919729198291992920029201292022920329204292052920629207292082920929210292112921229213292142921529216292172921829219292202922129222292232922429225292262922729228292292923029231292322923329234292352923629237292382923929240292412924229243292442924529246292472924829249292502925129252292532925429255292562925729258292592926029261292622926329264292652926629267292682926929270292712927229273292742927529276292772927829279292802928129282292832928429285292862928729288292892929029291292922929329294292952929629297292982929929300293012930229303293042930529306293072930829309293102931129312293132931429315293162931729318293192932029321293222932329324293252932629327293282932929330293312933229333293342933529336293372933829339293402934129342293432934429345293462934729348293492935029351293522935329354293552935629357293582935929360293612936229363293642936529366293672936829369293702937129372293732937429375293762937729378293792938029381293822938329384293852938629387293882938929390293912939229393293942939529396293972939829399294002940129402294032940429405294062940729408294092941029411294122941329414294152941629417294182941929420294212942229423294242942529426294272942829429294302943129432294332943429435294362943729438294392944029441294422944329444294452944629447294482944929450294512945229453294542945529456294572945829459294602946129462294632946429465294662946729468294692947029471294722947329474294752947629477294782947929480294812948229483294842948529486294872948829489294902949129492294932949429495294962949729498294992950029501295022950329504295052950629507295082950929510295112951229513295142951529516295172951829519295202952129522295232952429525295262952729528295292953029531295322953329534295352953629537295382953929540295412954229543295442954529546295472954829549295502955129552295532955429555295562955729558295592956029561295622956329564295652956629567295682956929570295712957229573295742957529576295772957829579295802958129582295832958429585295862958729588295892959029591295922959329594295952959629597295982959929600296012960229603296042960529606296072960829609296102961129612296132961429615296162961729618296192962029621296222962329624296252962629627296282962929630296312963229633296342963529636296372963829639296402964129642296432964429645296462964729648296492965029651296522965329654296552965629657296582965929660296612966229663296642966529666296672966829669296702967129672296732967429675296762967729678296792968029681296822968329684296852968629687296882968929690296912969229693296942969529696296972969829699297002970129702297032970429705297062970729708297092971029711297122971329714297152971629717297182971929720297212972229723297242972529726297272972829729297302973129732297332973429735297362973729738297392974029741297422974329744297452974629747297482974929750297512975229753297542975529756297572975829759297602976129762297632976429765297662976729768297692977029771297722977329774297752977629777297782977929780297812978229783297842978529786297872978829789297902979129792297932979429795297962979729798297992980029801298022980329804298052980629807298082980929810298112981229813298142981529816298172981829819298202982129822298232982429825298262982729828298292983029831298322983329834298352983629837298382983929840298412984229843298442984529846298472984829849298502985129852298532985429855298562985729858298592986029861298622986329864298652986629867298682986929870298712987229873298742987529876298772987829879298802988129882298832988429885298862988729888298892989029891298922989329894298952989629897298982989929900299012990229903299042990529906299072990829909299102991129912299132991429915299162991729918299192992029921299222992329924299252992629927299282992929930299312993229933299342993529936299372993829939299402994129942299432994429945299462994729948299492995029951299522995329954299552995629957299582995929960299612996229963299642996529966299672996829969299702997129972299732997429975299762997729978299792998029981299822998329984299852998629987299882998929990299912999229993299942999529996299972999829999300003000130002300033000430005300063000730008300093001030011300123001330014300153001630017300183001930020300213002230023300243002530026300273002830029300303003130032300333003430035300363003730038300393004030041300423004330044300453004630047300483004930050300513005230053300543005530056300573005830059300603006130062300633006430065300663006730068300693007030071300723007330074300753007630077300783007930080300813008230083300843008530086300873008830089300903009130092300933009430095300963009730098300993010030101301023010330104301053010630107301083010930110301113011230113301143011530116301173011830119301203012130122301233012430125301263012730128301293013030131301323013330134301353013630137301383013930140301413014230143301443014530146301473014830149301503015130152301533015430155301563015730158301593016030161301623016330164301653016630167301683016930170301713017230173301743017530176301773017830179301803018130182301833018430185301863018730188301893019030191301923019330194301953019630197301983019930200302013020230203302043020530206302073020830209302103021130212302133021430215302163021730218302193022030221302223022330224302253022630227302283022930230302313023230233302343023530236302373023830239302403024130242302433024430245302463024730248302493025030251302523025330254302553025630257302583025930260302613026230263302643026530266302673026830269302703027130272302733027430275302763027730278302793028030281302823028330284302853028630287302883028930290302913029230293302943029530296302973029830299303003030130302303033030430305303063030730308303093031030311303123031330314303153031630317303183031930320303213032230323303243032530326303273032830329303303033130332303333033430335303363033730338303393034030341303423034330344303453034630347303483034930350303513035230353303543035530356303573035830359303603036130362303633036430365303663036730368303693037030371303723037330374303753037630377303783037930380303813038230383303843038530386303873038830389303903039130392303933039430395303963039730398303993040030401304023040330404304053040630407304083040930410304113041230413304143041530416304173041830419304203042130422304233042430425304263042730428304293043030431304323043330434304353043630437304383043930440304413044230443304443044530446304473044830449304503045130452304533045430455304563045730458304593046030461304623046330464304653046630467304683046930470304713047230473304743047530476304773047830479304803048130482304833048430485304863048730488304893049030491304923049330494304953049630497304983049930500305013050230503305043050530506305073050830509305103051130512305133051430515305163051730518305193052030521305223052330524305253052630527305283052930530305313053230533305343053530536305373053830539305403054130542305433054430545305463054730548305493055030551305523055330554305553055630557305583055930560305613056230563305643056530566305673056830569305703057130572305733057430575305763057730578305793058030581305823058330584305853058630587305883058930590305913059230593305943059530596305973059830599306003060130602306033060430605306063060730608306093061030611306123061330614306153061630617306183061930620306213062230623306243062530626306273062830629306303063130632306333063430635306363063730638306393064030641306423064330644306453064630647306483064930650306513065230653306543065530656306573065830659306603066130662306633066430665306663066730668306693067030671306723067330674306753067630677306783067930680306813068230683306843068530686306873068830689306903069130692306933069430695306963069730698306993070030701307023070330704307053070630707307083070930710307113071230713307143071530716307173071830719307203072130722307233072430725307263072730728307293073030731307323073330734307353073630737307383073930740307413074230743307443074530746307473074830749307503075130752307533075430755307563075730758307593076030761307623076330764307653076630767307683076930770307713077230773307743077530776307773077830779307803078130782307833078430785307863078730788307893079030791307923079330794307953079630797307983079930800308013080230803308043080530806308073080830809308103081130812308133081430815308163081730818308193082030821308223082330824308253082630827308283082930830308313083230833308343083530836308373083830839308403084130842308433084430845308463084730848308493085030851308523085330854308553085630857308583085930860308613086230863308643086530866308673086830869308703087130872308733087430875308763087730878308793088030881308823088330884308853088630887308883088930890308913089230893308943089530896308973089830899309003090130902309033090430905309063090730908309093091030911309123091330914309153091630917309183091930920309213092230923309243092530926309273092830929309303093130932309333093430935309363093730938309393094030941309423094330944309453094630947309483094930950309513095230953309543095530956309573095830959309603096130962309633096430965309663096730968309693097030971309723097330974309753097630977309783097930980309813098230983309843098530986309873098830989309903099130992309933099430995309963099730998309993100031001310023100331004310053100631007310083100931010310113101231013310143101531016310173101831019310203102131022310233102431025310263102731028310293103031031310323103331034310353103631037310383103931040310413104231043310443104531046310473104831049310503105131052310533105431055310563105731058310593106031061310623106331064310653106631067310683106931070310713107231073310743107531076310773107831079310803108131082310833108431085310863108731088310893109031091310923109331094310953109631097310983109931100311013110231103311043110531106311073110831109311103111131112311133111431115311163111731118311193112031121311223112331124311253112631127311283112931130311313113231133311343113531136311373113831139311403114131142311433114431145311463114731148311493115031151311523115331154311553115631157311583115931160311613116231163311643116531166311673116831169311703117131172311733117431175311763117731178311793118031181311823118331184311853118631187311883118931190311913119231193311943119531196311973119831199312003120131202312033120431205312063120731208312093121031211312123121331214312153121631217312183121931220312213122231223312243122531226312273122831229312303123131232312333123431235312363123731238312393124031241312423124331244312453124631247312483124931250312513125231253312543125531256312573125831259312603126131262312633126431265312663126731268312693127031271312723127331274312753127631277312783127931280312813128231283312843128531286312873128831289312903129131292312933129431295312963129731298312993130031301313023130331304313053130631307313083130931310313113131231313313143131531316313173131831319313203132131322313233132431325313263132731328313293133031331313323133331334313353133631337313383133931340313413134231343313443134531346313473134831349313503135131352313533135431355313563135731358313593136031361313623136331364313653136631367313683136931370313713137231373313743137531376313773137831379313803138131382313833138431385313863138731388313893139031391313923139331394313953139631397313983139931400314013140231403314043140531406314073140831409314103141131412314133141431415314163141731418314193142031421314223142331424314253142631427314283142931430314313143231433314343143531436314373143831439314403144131442314433144431445314463144731448314493145031451314523145331454314553145631457314583145931460314613146231463314643146531466314673146831469314703147131472314733147431475314763147731478314793148031481314823148331484314853148631487314883148931490314913149231493314943149531496314973149831499315003150131502315033150431505315063150731508315093151031511315123151331514315153151631517315183151931520315213152231523315243152531526315273152831529315303153131532315333153431535315363153731538315393154031541315423154331544315453154631547315483154931550315513155231553315543155531556315573155831559315603156131562315633156431565315663156731568315693157031571315723157331574315753157631577315783157931580315813158231583315843158531586315873158831589315903159131592315933159431595315963159731598315993160031601316023160331604316053160631607316083160931610316113161231613316143161531616316173161831619316203162131622316233162431625316263162731628316293163031631316323163331634316353163631637316383163931640316413164231643316443164531646316473164831649316503165131652316533165431655316563165731658316593166031661316623166331664316653166631667316683166931670316713167231673316743167531676316773167831679316803168131682316833168431685316863168731688316893169031691316923169331694316953169631697316983169931700317013170231703317043170531706317073170831709317103171131712317133171431715317163171731718317193172031721317223172331724317253172631727317283172931730317313173231733317343173531736317373173831739317403174131742317433174431745317463174731748317493175031751317523175331754317553175631757317583175931760317613176231763317643176531766317673176831769317703177131772317733177431775317763177731778317793178031781317823178331784317853178631787317883178931790317913179231793317943179531796317973179831799318003180131802318033180431805318063180731808318093181031811318123181331814318153181631817318183181931820318213182231823318243182531826318273182831829318303183131832318333183431835318363183731838318393184031841318423184331844318453184631847318483184931850318513185231853318543185531856318573185831859318603186131862318633186431865318663186731868318693187031871318723187331874318753187631877318783187931880318813188231883318843188531886318873188831889318903189131892318933189431895318963189731898318993190031901319023190331904319053190631907319083190931910319113191231913319143191531916319173191831919319203192131922319233192431925319263192731928319293193031931319323193331934319353193631937319383193931940319413194231943319443194531946319473194831949319503195131952319533195431955319563195731958319593196031961319623196331964319653196631967319683196931970319713197231973319743197531976319773197831979319803198131982319833198431985319863198731988319893199031991319923199331994319953199631997319983199932000320013200232003320043200532006320073200832009320103201132012320133201432015320163201732018320193202032021320223202332024320253202632027320283202932030320313203232033320343203532036320373203832039320403204132042320433204432045320463204732048320493205032051320523205332054320553205632057320583205932060320613206232063320643206532066320673206832069320703207132072320733207432075320763207732078320793208032081320823208332084320853208632087320883208932090320913209232093320943209532096320973209832099321003210132102321033210432105321063210732108321093211032111321123211332114321153211632117321183211932120321213212232123321243212532126321273212832129321303213132132321333213432135321363213732138321393214032141321423214332144321453214632147321483214932150321513215232153321543215532156321573215832159321603216132162321633216432165321663216732168321693217032171321723217332174321753217632177321783217932180321813218232183321843218532186321873218832189321903219132192321933219432195321963219732198321993220032201322023220332204322053220632207322083220932210322113221232213322143221532216322173221832219322203222132222322233222432225322263222732228322293223032231322323223332234322353223632237322383223932240322413224232243322443224532246322473224832249322503225132252322533225432255322563225732258322593226032261322623226332264322653226632267322683226932270322713227232273322743227532276322773227832279322803228132282322833228432285322863228732288322893229032291322923229332294322953229632297322983229932300323013230232303323043230532306323073230832309323103231132312323133231432315323163231732318323193232032321323223232332324323253232632327323283232932330323313233232333323343233532336323373233832339323403234132342323433234432345323463234732348323493235032351323523235332354323553235632357323583235932360323613236232363323643236532366323673236832369323703237132372323733237432375323763237732378323793238032381323823238332384323853238632387323883238932390323913239232393323943239532396323973239832399324003240132402324033240432405324063240732408324093241032411324123241332414324153241632417324183241932420324213242232423324243242532426324273242832429324303243132432324333243432435324363243732438324393244032441324423244332444324453244632447324483244932450324513245232453324543245532456324573245832459324603246132462324633246432465324663246732468324693247032471324723247332474324753247632477324783247932480324813248232483324843248532486324873248832489324903249132492324933249432495324963249732498324993250032501325023250332504325053250632507325083250932510325113251232513325143251532516325173251832519325203252132522325233252432525325263252732528325293253032531325323253332534325353253632537325383253932540325413254232543325443254532546325473254832549325503255132552325533255432555325563255732558325593256032561325623256332564325653256632567325683256932570325713257232573325743257532576325773257832579325803258132582325833258432585325863258732588325893259032591325923259332594325953259632597325983259932600326013260232603326043260532606326073260832609326103261132612326133261432615326163261732618326193262032621326223262332624326253262632627326283262932630326313263232633326343263532636326373263832639326403264132642326433264432645326463264732648326493265032651326523265332654326553265632657326583265932660326613266232663326643266532666326673266832669326703267132672326733267432675326763267732678326793268032681326823268332684326853268632687326883268932690326913269232693326943269532696326973269832699327003270132702327033270432705327063270732708327093271032711327123271332714327153271632717327183271932720327213272232723327243272532726327273272832729327303273132732327333273432735327363273732738327393274032741327423274332744327453274632747327483274932750327513275232753327543275532756327573275832759327603276132762327633276432765327663276732768327693277032771327723277332774327753277632777327783277932780327813278232783327843278532786327873278832789327903279132792327933279432795327963279732798327993280032801328023280332804328053280632807328083280932810328113281232813328143281532816328173281832819328203282132822328233282432825328263282732828328293283032831328323283332834328353283632837328383283932840328413284232843328443284532846328473284832849328503285132852328533285432855328563285732858328593286032861328623286332864328653286632867328683286932870328713287232873328743287532876328773287832879328803288132882328833288432885328863288732888328893289032891328923289332894328953289632897328983289932900329013290232903329043290532906329073290832909329103291132912329133291432915329163291732918329193292032921329223292332924329253292632927329283292932930329313293232933329343293532936329373293832939329403294132942329433294432945329463294732948329493295032951329523295332954329553295632957329583295932960329613296232963329643296532966329673296832969329703297132972329733297432975329763297732978329793298032981329823298332984329853298632987329883298932990329913299232993329943299532996329973299832999330003300133002330033300433005330063300733008330093301033011330123301333014330153301633017330183301933020330213302233023330243302533026330273302833029330303303133032330333303433035330363303733038330393304033041330423304333044330453304633047330483304933050330513305233053330543305533056330573305833059330603306133062330633306433065330663306733068330693307033071330723307333074330753307633077330783307933080330813308233083330843308533086330873308833089330903309133092330933309433095330963309733098330993310033101331023310333104331053310633107331083310933110331113311233113331143311533116331173311833119331203312133122331233312433125331263312733128331293313033131331323313333134331353313633137331383313933140331413314233143331443314533146331473314833149331503315133152331533315433155331563315733158331593316033161331623316333164331653316633167331683316933170331713317233173331743317533176331773317833179331803318133182331833318433185331863318733188331893319033191331923319333194331953319633197331983319933200332013320233203332043320533206332073320833209332103321133212332133321433215332163321733218332193322033221332223322333224332253322633227332283322933230332313323233233332343323533236332373323833239332403324133242332433324433245332463324733248332493325033251332523325333254332553325633257332583325933260332613326233263332643326533266332673326833269332703327133272332733327433275332763327733278332793328033281332823328333284332853328633287332883328933290332913329233293332943329533296332973329833299333003330133302333033330433305333063330733308333093331033311333123331333314333153331633317333183331933320333213332233323333243332533326333273332833329333303333133332333333333433335333363333733338333393334033341333423334333344333453334633347333483334933350333513335233353333543335533356333573335833359333603336133362333633336433365333663336733368333693337033371333723337333374333753337633377333783337933380333813338233383333843338533386333873338833389333903339133392333933339433395333963339733398333993340033401334023340333404334053340633407334083340933410334113341233413334143341533416334173341833419334203342133422334233342433425334263342733428334293343033431334323343333434334353343633437334383343933440334413344233443334443344533446334473344833449334503345133452334533345433455334563345733458334593346033461334623346333464334653346633467334683346933470334713347233473334743347533476334773347833479334803348133482334833348433485334863348733488334893349033491334923349333494334953349633497334983349933500335013350233503335043350533506335073350833509335103351133512335133351433515335163351733518335193352033521335223352333524335253352633527335283352933530335313353233533335343353533536335373353833539335403354133542335433354433545335463354733548335493355033551335523355333554335553355633557335583355933560335613356233563335643356533566335673356833569335703357133572335733357433575335763357733578335793358033581335823358333584335853358633587335883358933590335913359233593335943359533596335973359833599336003360133602336033360433605336063360733608336093361033611336123361333614336153361633617336183361933620336213362233623336243362533626336273362833629336303363133632336333363433635336363363733638336393364033641336423364333644336453364633647336483364933650336513365233653336543365533656336573365833659336603366133662336633366433665336663366733668336693367033671336723367333674336753367633677336783367933680336813368233683336843368533686336873368833689336903369133692336933369433695336963369733698336993370033701337023370333704337053370633707337083370933710337113371233713337143371533716337173371833719337203372133722337233372433725337263372733728337293373033731337323373333734337353373633737337383373933740337413374233743337443374533746337473374833749337503375133752337533375433755337563375733758337593376033761337623376333764337653376633767337683376933770337713377233773337743377533776337773377833779337803378133782337833378433785337863378733788337893379033791337923379333794337953379633797337983379933800338013380233803338043380533806338073380833809338103381133812338133381433815338163381733818338193382033821338223382333824338253382633827338283382933830338313383233833338343383533836338373383833839338403384133842338433384433845338463384733848338493385033851338523385333854338553385633857338583385933860338613386233863338643386533866338673386833869338703387133872338733387433875338763387733878338793388033881338823388333884338853388633887338883388933890338913389233893338943389533896338973389833899339003390133902339033390433905339063390733908339093391033911339123391333914339153391633917339183391933920339213392233923339243392533926339273392833929339303393133932339333393433935339363393733938339393394033941339423394333944339453394633947339483394933950339513395233953339543395533956339573395833959339603396133962339633396433965339663396733968339693397033971339723397333974339753397633977339783397933980339813398233983339843398533986339873398833989339903399133992339933399433995339963399733998339993400034001340023400334004340053400634007340083400934010340113401234013340143401534016340173401834019340203402134022340233402434025340263402734028340293403034031340323403334034340353403634037340383403934040340413404234043340443404534046340473404834049340503405134052340533405434055340563405734058340593406034061340623406334064340653406634067340683406934070340713407234073340743407534076340773407834079340803408134082340833408434085340863408734088340893409034091340923409334094340953409634097340983409934100341013410234103341043410534106341073410834109341103411134112341133411434115341163411734118341193412034121341223412334124341253412634127341283412934130341313413234133341343413534136341373413834139341403414134142341433414434145341463414734148341493415034151341523415334154341553415634157341583415934160341613416234163341643416534166341673416834169341703417134172341733417434175341763417734178341793418034181341823418334184341853418634187341883418934190341913419234193341943419534196341973419834199342003420134202342033420434205342063420734208342093421034211342123421334214342153421634217342183421934220342213422234223342243422534226342273422834229342303423134232342333423434235342363423734238342393424034241342423424334244342453424634247342483424934250342513425234253342543425534256342573425834259342603426134262342633426434265342663426734268342693427034271342723427334274342753427634277342783427934280342813428234283342843428534286342873428834289342903429134292342933429434295342963429734298342993430034301343023430334304343053430634307343083430934310343113431234313343143431534316343173431834319343203432134322343233432434325343263432734328343293433034331343323433334334343353433634337343383433934340343413434234343343443434534346343473434834349343503435134352343533435434355343563435734358343593436034361343623436334364343653436634367343683436934370343713437234373343743437534376343773437834379343803438134382343833438434385343863438734388343893439034391343923439334394343953439634397343983439934400344013440234403344043440534406344073440834409344103441134412344133441434415344163441734418344193442034421344223442334424344253442634427344283442934430344313443234433344343443534436344373443834439344403444134442344433444434445344463444734448344493445034451344523445334454344553445634457344583445934460344613446234463344643446534466344673446834469344703447134472344733447434475344763447734478344793448034481344823448334484344853448634487344883448934490344913449234493344943449534496344973449834499345003450134502345033450434505345063450734508345093451034511345123451334514345153451634517345183451934520345213452234523345243452534526345273452834529345303453134532345333453434535345363453734538345393454034541345423454334544345453454634547345483454934550345513455234553345543455534556345573455834559345603456134562345633456434565345663456734568345693457034571345723457334574345753457634577345783457934580345813458234583345843458534586345873458834589345903459134592345933459434595345963459734598345993460034601346023460334604346053460634607346083460934610346113461234613346143461534616346173461834619346203462134622346233462434625346263462734628346293463034631346323463334634346353463634637346383463934640346413464234643346443464534646346473464834649346503465134652346533465434655346563465734658346593466034661346623466334664346653466634667346683466934670346713467234673346743467534676346773467834679346803468134682346833468434685346863468734688346893469034691346923469334694346953469634697346983469934700347013470234703347043470534706347073470834709347103471134712347133471434715347163471734718347193472034721347223472334724347253472634727347283472934730347313473234733347343473534736347373473834739347403474134742347433474434745347463474734748347493475034751347523475334754347553475634757347583475934760347613476234763347643476534766347673476834769347703477134772347733477434775347763477734778347793478034781347823478334784347853478634787347883478934790347913479234793347943479534796347973479834799348003480134802348033480434805348063480734808348093481034811348123481334814348153481634817348183481934820348213482234823348243482534826348273482834829348303483134832348333483434835348363483734838348393484034841348423484334844348453484634847348483484934850348513485234853348543485534856348573485834859348603486134862348633486434865348663486734868348693487034871348723487334874348753487634877348783487934880348813488234883348843488534886348873488834889348903489134892348933489434895348963489734898348993490034901349023490334904349053490634907349083490934910349113491234913349143491534916349173491834919349203492134922349233492434925349263492734928349293493034931349323493334934349353493634937349383493934940349413494234943349443494534946349473494834949349503495134952349533495434955349563495734958349593496034961349623496334964349653496634967349683496934970349713497234973349743497534976349773497834979349803498134982349833498434985349863498734988349893499034991349923499334994349953499634997349983499935000350013500235003350043500535006350073500835009350103501135012350133501435015350163501735018350193502035021350223502335024350253502635027350283502935030350313503235033350343503535036350373503835039350403504135042350433504435045350463504735048350493505035051350523505335054350553505635057350583505935060350613506235063350643506535066350673506835069350703507135072350733507435075350763507735078350793508035081350823508335084350853508635087350883508935090350913509235093350943509535096350973509835099351003510135102351033510435105351063510735108351093511035111351123511335114351153511635117351183511935120351213512235123351243512535126351273512835129351303513135132351333513435135351363513735138351393514035141351423514335144351453514635147351483514935150351513515235153351543515535156351573515835159351603516135162351633516435165351663516735168351693517035171351723517335174351753517635177351783517935180351813518235183351843518535186351873518835189351903519135192351933519435195351963519735198351993520035201352023520335204352053520635207352083520935210352113521235213352143521535216352173521835219352203522135222352233522435225352263522735228352293523035231352323523335234352353523635237352383523935240352413524235243352443524535246352473524835249352503525135252352533525435255352563525735258352593526035261352623526335264352653526635267352683526935270352713527235273352743527535276352773527835279352803528135282352833528435285352863528735288352893529035291352923529335294352953529635297352983529935300353013530235303353043530535306353073530835309353103531135312353133531435315353163531735318353193532035321353223532335324353253532635327353283532935330353313533235333353343533535336353373533835339353403534135342353433534435345353463534735348353493535035351353523535335354353553535635357353583535935360353613536235363353643536535366353673536835369353703537135372353733537435375353763537735378353793538035381353823538335384353853538635387353883538935390353913539235393353943539535396353973539835399354003540135402354033540435405354063540735408354093541035411354123541335414354153541635417354183541935420354213542235423354243542535426354273542835429354303543135432354333543435435354363543735438354393544035441354423544335444354453544635447354483544935450354513545235453354543545535456354573545835459354603546135462354633546435465354663546735468354693547035471354723547335474354753547635477354783547935480354813548235483354843548535486354873548835489354903549135492354933549435495354963549735498354993550035501355023550335504355053550635507355083550935510355113551235513355143551535516355173551835519355203552135522355233552435525355263552735528355293553035531355323553335534355353553635537355383553935540355413554235543355443554535546355473554835549355503555135552355533555435555355563555735558355593556035561355623556335564355653556635567355683556935570355713557235573355743557535576355773557835579355803558135582355833558435585355863558735588355893559035591355923559335594355953559635597355983559935600356013560235603356043560535606356073560835609356103561135612356133561435615356163561735618356193562035621356223562335624356253562635627356283562935630356313563235633356343563535636356373563835639356403564135642356433564435645356463564735648356493565035651356523565335654356553565635657356583565935660356613566235663356643566535666356673566835669356703567135672356733567435675356763567735678356793568035681356823568335684356853568635687356883568935690356913569235693356943569535696356973569835699357003570135702357033570435705357063570735708357093571035711357123571335714357153571635717357183571935720357213572235723357243572535726357273572835729357303573135732357333573435735357363573735738357393574035741357423574335744357453574635747357483574935750357513575235753357543575535756357573575835759357603576135762357633576435765357663576735768357693577035771357723577335774357753577635777357783577935780357813578235783357843578535786357873578835789357903579135792357933579435795357963579735798357993580035801358023580335804358053580635807358083580935810358113581235813358143581535816358173581835819358203582135822358233582435825358263582735828358293583035831358323583335834358353583635837358383583935840358413584235843358443584535846358473584835849358503585135852358533585435855358563585735858358593586035861358623586335864358653586635867358683586935870358713587235873358743587535876358773587835879358803588135882358833588435885358863588735888358893589035891358923589335894358953589635897358983589935900359013590235903359043590535906359073590835909359103591135912359133591435915359163591735918359193592035921359223592335924359253592635927359283592935930359313593235933359343593535936359373593835939359403594135942359433594435945359463594735948359493595035951359523595335954359553595635957359583595935960359613596235963359643596535966359673596835969359703597135972359733597435975359763597735978359793598035981359823598335984359853598635987359883598935990359913599235993359943599535996359973599835999360003600136002360033600436005360063600736008360093601036011360123601336014360153601636017360183601936020360213602236023360243602536026360273602836029360303603136032360333603436035360363603736038360393604036041360423604336044360453604636047360483604936050360513605236053360543605536056360573605836059360603606136062360633606436065360663606736068360693607036071360723607336074360753607636077360783607936080360813608236083360843608536086360873608836089360903609136092360933609436095360963609736098360993610036101361023610336104361053610636107361083610936110361113611236113361143611536116361173611836119361203612136122361233612436125361263612736128361293613036131361323613336134361353613636137361383613936140361413614236143361443614536146361473614836149361503615136152361533615436155361563615736158361593616036161361623616336164361653616636167361683616936170361713617236173361743617536176361773617836179361803618136182361833618436185361863618736188361893619036191361923619336194361953619636197361983619936200362013620236203362043620536206362073620836209362103621136212362133621436215362163621736218362193622036221362223622336224362253622636227362283622936230362313623236233362343623536236362373623836239362403624136242362433624436245362463624736248362493625036251362523625336254362553625636257362583625936260362613626236263362643626536266362673626836269362703627136272362733627436275362763627736278362793628036281362823628336284362853628636287362883628936290362913629236293362943629536296362973629836299363003630136302363033630436305363063630736308363093631036311363123631336314363153631636317363183631936320363213632236323363243632536326363273632836329363303633136332363333633436335363363633736338363393634036341363423634336344363453634636347363483634936350363513635236353363543635536356363573635836359363603636136362363633636436365363663636736368363693637036371363723637336374363753637636377363783637936380363813638236383363843638536386363873638836389363903639136392363933639436395363963639736398363993640036401364023640336404364053640636407364083640936410364113641236413364143641536416364173641836419364203642136422364233642436425364263642736428364293643036431364323643336434364353643636437364383643936440364413644236443364443644536446364473644836449364503645136452364533645436455364563645736458364593646036461364623646336464364653646636467364683646936470364713647236473364743647536476364773647836479364803648136482364833648436485364863648736488364893649036491364923649336494364953649636497364983649936500365013650236503365043650536506365073650836509365103651136512365133651436515365163651736518365193652036521365223652336524365253652636527365283652936530365313653236533365343653536536365373653836539365403654136542365433654436545365463654736548365493655036551365523655336554365553655636557365583655936560365613656236563365643656536566365673656836569365703657136572365733657436575365763657736578365793658036581365823658336584365853658636587365883658936590365913659236593365943659536596365973659836599366003660136602366033660436605366063660736608366093661036611366123661336614366153661636617366183661936620366213662236623366243662536626366273662836629366303663136632366333663436635366363663736638366393664036641366423664336644366453664636647366483664936650366513665236653366543665536656366573665836659366603666136662366633666436665366663666736668366693667036671366723667336674366753667636677366783667936680366813668236683366843668536686366873668836689366903669136692366933669436695366963669736698366993670036701367023670336704367053670636707367083670936710367113671236713367143671536716367173671836719367203672136722367233672436725367263672736728367293673036731367323673336734367353673636737367383673936740367413674236743367443674536746367473674836749367503675136752367533675436755367563675736758367593676036761367623676336764367653676636767367683676936770367713677236773367743677536776367773677836779367803678136782367833678436785367863678736788367893679036791367923679336794367953679636797367983679936800368013680236803368043680536806368073680836809368103681136812368133681436815368163681736818368193682036821368223682336824368253682636827368283682936830368313683236833368343683536836368373683836839368403684136842368433684436845368463684736848368493685036851368523685336854368553685636857368583685936860368613686236863368643686536866368673686836869368703687136872368733687436875368763687736878368793688036881368823688336884368853688636887368883688936890368913689236893368943689536896368973689836899369003690136902369033690436905369063690736908369093691036911369123691336914369153691636917369183691936920369213692236923369243692536926369273692836929369303693136932369333693436935369363693736938369393694036941369423694336944369453694636947369483694936950369513695236953369543695536956369573695836959369603696136962369633696436965369663696736968369693697036971369723697336974369753697636977369783697936980369813698236983369843698536986369873698836989369903699136992369933699436995369963699736998369993700037001370023700337004370053700637007370083700937010370113701237013370143701537016370173701837019370203702137022370233702437025370263702737028370293703037031370323703337034370353703637037370383703937040370413704237043370443704537046370473704837049370503705137052370533705437055370563705737058370593706037061370623706337064370653706637067370683706937070370713707237073370743707537076370773707837079370803708137082370833708437085370863708737088370893709037091370923709337094370953709637097370983709937100371013710237103371043710537106371073710837109371103711137112371133711437115371163711737118371193712037121371223712337124371253712637127371283712937130371313713237133371343713537136371373713837139371403714137142371433714437145371463714737148371493715037151371523715337154371553715637157371583715937160371613716237163371643716537166371673716837169371703717137172371733717437175371763717737178371793718037181371823718337184371853718637187371883718937190371913719237193371943719537196371973719837199372003720137202372033720437205372063720737208372093721037211372123721337214372153721637217372183721937220372213722237223372243722537226372273722837229372303723137232372333723437235372363723737238372393724037241372423724337244372453724637247372483724937250372513725237253372543725537256372573725837259372603726137262372633726437265372663726737268372693727037271372723727337274372753727637277372783727937280372813728237283372843728537286372873728837289372903729137292372933729437295372963729737298372993730037301373023730337304373053730637307373083730937310373113731237313373143731537316373173731837319373203732137322373233732437325373263732737328373293733037331373323733337334373353733637337373383733937340373413734237343373443734537346373473734837349373503735137352373533735437355373563735737358373593736037361373623736337364373653736637367373683736937370373713737237373373743737537376373773737837379373803738137382373833738437385373863738737388373893739037391373923739337394373953739637397373983739937400374013740237403374043740537406374073740837409374103741137412374133741437415374163741737418374193742037421374223742337424374253742637427374283742937430374313743237433374343743537436374373743837439374403744137442374433744437445374463744737448374493745037451374523745337454374553745637457374583745937460374613746237463374643746537466374673746837469374703747137472374733747437475374763747737478374793748037481374823748337484374853748637487374883748937490374913749237493374943749537496374973749837499375003750137502375033750437505375063750737508375093751037511375123751337514375153751637517375183751937520375213752237523375243752537526375273752837529375303753137532375333753437535375363753737538375393754037541375423754337544375453754637547375483754937550375513755237553375543755537556375573755837559375603756137562375633756437565375663756737568375693757037571375723757337574375753757637577375783757937580375813758237583375843758537586375873758837589375903759137592375933759437595375963759737598375993760037601376023760337604376053760637607376083760937610376113761237613376143761537616376173761837619376203762137622376233762437625376263762737628376293763037631376323763337634376353763637637376383763937640376413764237643376443764537646376473764837649376503765137652376533765437655376563765737658376593766037661376623766337664376653766637667376683766937670376713767237673376743767537676376773767837679376803768137682376833768437685376863768737688376893769037691376923769337694376953769637697376983769937700377013770237703377043770537706377073770837709377103771137712377133771437715377163771737718377193772037721377223772337724377253772637727377283772937730377313773237733377343773537736377373773837739377403774137742377433774437745377463774737748377493775037751377523775337754377553775637757377583775937760377613776237763377643776537766377673776837769377703777137772377733777437775377763777737778377793778037781377823778337784377853778637787377883778937790377913779237793377943779537796377973779837799378003780137802378033780437805378063780737808378093781037811378123781337814378153781637817378183781937820378213782237823378243782537826378273782837829378303783137832378333783437835378363783737838378393784037841378423784337844378453784637847378483784937850378513785237853378543785537856378573785837859378603786137862378633786437865378663786737868378693787037871378723787337874378753787637877378783787937880378813788237883378843788537886378873788837889378903789137892378933789437895378963789737898378993790037901379023790337904379053790637907379083790937910379113791237913379143791537916379173791837919379203792137922379233792437925379263792737928379293793037931379323793337934379353793637937379383793937940379413794237943379443794537946379473794837949379503795137952379533795437955379563795737958379593796037961379623796337964379653796637967379683796937970379713797237973379743797537976379773797837979379803798137982379833798437985379863798737988379893799037991379923799337994379953799637997379983799938000380013800238003380043800538006380073800838009380103801138012380133801438015380163801738018380193802038021380223802338024380253802638027380283802938030380313803238033380343803538036380373803838039380403804138042380433804438045380463804738048380493805038051380523805338054380553805638057380583805938060380613806238063380643806538066380673806838069380703807138072380733807438075380763807738078380793808038081380823808338084380853808638087380883808938090380913809238093380943809538096380973809838099381003810138102381033810438105381063810738108381093811038111381123811338114381153811638117381183811938120381213812238123381243812538126381273812838129381303813138132381333813438135381363813738138381393814038141381423814338144381453814638147381483814938150381513815238153381543815538156381573815838159381603816138162381633816438165381663816738168381693817038171381723817338174381753817638177381783817938180381813818238183381843818538186381873818838189381903819138192381933819438195381963819738198381993820038201382023820338204382053820638207382083820938210382113821238213382143821538216382173821838219382203822138222382233822438225382263822738228382293823038231382323823338234382353823638237382383823938240382413824238243382443824538246382473824838249382503825138252382533825438255382563825738258382593826038261382623826338264382653826638267382683826938270382713827238273382743827538276382773827838279382803828138282382833828438285382863828738288382893829038291382923829338294382953829638297382983829938300383013830238303383043830538306383073830838309383103831138312383133831438315383163831738318383193832038321383223832338324383253832638327383283832938330383313833238333383343833538336383373833838339383403834138342383433834438345383463834738348383493835038351383523835338354383553835638357383583835938360383613836238363383643836538366383673836838369383703837138372383733837438375383763837738378383793838038381383823838338384383853838638387383883838938390383913839238393383943839538396383973839838399384003840138402384033840438405384063840738408384093841038411384123841338414384153841638417384183841938420384213842238423384243842538426384273842838429384303843138432384333843438435384363843738438384393844038441384423844338444384453844638447384483844938450384513845238453384543845538456384573845838459384603846138462384633846438465384663846738468384693847038471384723847338474384753847638477384783847938480384813848238483384843848538486384873848838489384903849138492384933849438495384963849738498384993850038501385023850338504385053850638507385083850938510385113851238513385143851538516385173851838519385203852138522385233852438525385263852738528385293853038531385323853338534385353853638537385383853938540385413854238543385443854538546385473854838549385503855138552385533855438555385563855738558385593856038561385623856338564385653856638567385683856938570385713857238573385743857538576385773857838579385803858138582385833858438585385863858738588385893859038591385923859338594385953859638597385983859938600386013860238603386043860538606386073860838609386103861138612386133861438615386163861738618386193862038621386223862338624386253862638627386283862938630386313863238633386343863538636386373863838639386403864138642386433864438645386463864738648386493865038651386523865338654386553865638657386583865938660386613866238663386643866538666386673866838669386703867138672386733867438675386763867738678386793868038681386823868338684386853868638687386883868938690386913869238693386943869538696386973869838699387003870138702387033870438705387063870738708387093871038711387123871338714387153871638717387183871938720387213872238723387243872538726387273872838729387303873138732387333873438735387363873738738387393874038741387423874338744387453874638747387483874938750387513875238753387543875538756387573875838759387603876138762387633876438765387663876738768387693877038771387723877338774387753877638777387783877938780387813878238783387843878538786387873878838789387903879138792387933879438795387963879738798387993880038801388023880338804388053880638807388083880938810388113881238813388143881538816388173881838819388203882138822388233882438825388263882738828388293883038831388323883338834388353883638837388383883938840388413884238843388443884538846388473884838849388503885138852388533885438855388563885738858388593886038861388623886338864388653886638867388683886938870388713887238873388743887538876388773887838879388803888138882388833888438885388863888738888388893889038891388923889338894388953889638897388983889938900389013890238903389043890538906389073890838909389103891138912389133891438915389163891738918389193892038921389223892338924389253892638927389283892938930389313893238933389343893538936389373893838939389403894138942389433894438945389463894738948389493895038951389523895338954389553895638957389583895938960389613896238963389643896538966389673896838969389703897138972389733897438975389763897738978389793898038981389823898338984389853898638987389883898938990389913899238993389943899538996389973899838999390003900139002390033900439005390063900739008390093901039011390123901339014390153901639017390183901939020390213902239023390243902539026390273902839029390303903139032390333903439035390363903739038390393904039041390423904339044390453904639047390483904939050390513905239053390543905539056390573905839059390603906139062390633906439065390663906739068390693907039071390723907339074390753907639077390783907939080390813908239083390843908539086390873908839089390903909139092390933909439095390963909739098390993910039101391023910339104391053910639107391083910939110391113911239113391143911539116391173911839119391203912139122391233912439125391263912739128391293913039131391323913339134391353913639137391383913939140391413914239143391443914539146391473914839149391503915139152391533915439155391563915739158391593916039161391623916339164391653916639167391683916939170391713917239173391743917539176391773917839179391803918139182391833918439185391863918739188391893919039191391923919339194391953919639197391983919939200392013920239203392043920539206392073920839209392103921139212392133921439215392163921739218392193922039221392223922339224392253922639227392283922939230392313923239233392343923539236392373923839239392403924139242392433924439245392463924739248392493925039251392523925339254392553925639257392583925939260392613926239263392643926539266392673926839269392703927139272392733927439275392763927739278392793928039281392823928339284392853928639287392883928939290392913929239293392943929539296392973929839299393003930139302393033930439305393063930739308393093931039311393123931339314393153931639317393183931939320393213932239323393243932539326393273932839329393303933139332393333933439335393363933739338393393934039341393423934339344393453934639347393483934939350393513935239353393543935539356393573935839359393603936139362393633936439365393663936739368393693937039371393723937339374393753937639377393783937939380393813938239383393843938539386393873938839389393903939139392393933939439395393963939739398393993940039401394023940339404394053940639407394083940939410394113941239413394143941539416394173941839419394203942139422394233942439425394263942739428394293943039431394323943339434394353943639437394383943939440394413944239443394443944539446394473944839449394503945139452394533945439455394563945739458394593946039461394623946339464394653946639467394683946939470394713947239473394743947539476394773947839479394803948139482394833948439485394863948739488394893949039491394923949339494394953949639497394983949939500395013950239503395043950539506395073950839509395103951139512395133951439515395163951739518395193952039521395223952339524395253952639527395283952939530395313953239533395343953539536395373953839539395403954139542395433954439545395463954739548395493955039551395523955339554395553955639557395583955939560395613956239563395643956539566395673956839569395703957139572395733957439575395763957739578395793958039581395823958339584395853958639587395883958939590395913959239593395943959539596395973959839599396003960139602396033960439605396063960739608396093961039611396123961339614396153961639617396183961939620396213962239623396243962539626396273962839629396303963139632396333963439635396363963739638396393964039641396423964339644396453964639647396483964939650396513965239653396543965539656396573965839659396603966139662396633966439665396663966739668396693967039671396723967339674396753967639677396783967939680396813968239683396843968539686396873968839689396903969139692396933969439695396963969739698396993970039701397023970339704397053970639707397083970939710397113971239713397143971539716397173971839719397203972139722397233972439725397263972739728397293973039731397323973339734397353973639737397383973939740397413974239743397443974539746397473974839749397503975139752397533975439755397563975739758397593976039761397623976339764397653976639767397683976939770397713977239773397743977539776397773977839779397803978139782397833978439785397863978739788397893979039791397923979339794397953979639797397983979939800398013980239803398043980539806398073980839809398103981139812398133981439815398163981739818398193982039821398223982339824398253982639827398283982939830398313983239833398343983539836398373983839839398403984139842398433984439845398463984739848398493985039851398523985339854398553985639857398583985939860398613986239863398643986539866398673986839869398703987139872398733987439875398763987739878398793988039881398823988339884398853988639887398883988939890398913989239893398943989539896398973989839899399003990139902399033990439905399063990739908399093991039911399123991339914399153991639917399183991939920399213992239923399243992539926399273992839929399303993139932399333993439935399363993739938399393994039941399423994339944399453994639947399483994939950399513995239953399543995539956399573995839959399603996139962399633996439965399663996739968399693997039971399723997339974399753997639977399783997939980399813998239983399843998539986399873998839989399903999139992399933999439995399963999739998399994000040001400024000340004400054000640007400084000940010400114001240013400144001540016400174001840019400204002140022400234002440025400264002740028400294003040031400324003340034400354003640037400384003940040400414004240043400444004540046400474004840049400504005140052400534005440055400564005740058400594006040061400624006340064400654006640067400684006940070400714007240073400744007540076400774007840079400804008140082400834008440085400864008740088400894009040091400924009340094400954009640097400984009940100401014010240103401044010540106401074010840109401104011140112401134011440115401164011740118401194012040121401224012340124401254012640127401284012940130401314013240133401344013540136401374013840139401404014140142401434014440145401464014740148401494015040151401524015340154401554015640157401584015940160401614016240163401644016540166401674016840169401704017140172401734017440175401764017740178401794018040181401824018340184401854018640187401884018940190401914019240193401944019540196401974019840199402004020140202402034020440205402064020740208402094021040211402124021340214402154021640217402184021940220402214022240223402244022540226402274022840229402304023140232402334023440235402364023740238402394024040241402424024340244402454024640247402484024940250402514025240253402544025540256402574025840259402604026140262402634026440265402664026740268402694027040271402724027340274402754027640277402784027940280402814028240283402844028540286402874028840289402904029140292402934029440295402964029740298402994030040301403024030340304403054030640307403084030940310403114031240313403144031540316403174031840319403204032140322403234032440325403264032740328403294033040331403324033340334403354033640337403384033940340403414034240343403444034540346403474034840349403504035140352403534035440355403564035740358403594036040361403624036340364403654036640367403684036940370403714037240373403744037540376403774037840379403804038140382403834038440385403864038740388403894039040391403924039340394403954039640397403984039940400404014040240403404044040540406404074040840409404104041140412404134041440415404164041740418404194042040421404224042340424404254042640427404284042940430404314043240433404344043540436404374043840439404404044140442404434044440445404464044740448404494045040451404524045340454404554045640457404584045940460404614046240463404644046540466404674046840469404704047140472404734047440475404764047740478404794048040481404824048340484404854048640487404884048940490404914049240493404944049540496404974049840499405004050140502405034050440505405064050740508405094051040511405124051340514405154051640517405184051940520405214052240523405244052540526405274052840529405304053140532405334053440535405364053740538405394054040541405424054340544405454054640547405484054940550405514055240553405544055540556405574055840559405604056140562405634056440565405664056740568405694057040571405724057340574405754057640577405784057940580405814058240583405844058540586405874058840589405904059140592405934059440595405964059740598405994060040601406024060340604406054060640607406084060940610406114061240613406144061540616406174061840619406204062140622406234062440625406264062740628406294063040631406324063340634406354063640637406384063940640406414064240643406444064540646406474064840649406504065140652406534065440655406564065740658406594066040661406624066340664406654066640667406684066940670406714067240673406744067540676406774067840679406804068140682406834068440685406864068740688406894069040691406924069340694406954069640697406984069940700407014070240703407044070540706407074070840709407104071140712407134071440715407164071740718407194072040721407224072340724407254072640727407284072940730407314073240733407344073540736407374073840739407404074140742407434074440745407464074740748407494075040751407524075340754407554075640757407584075940760407614076240763407644076540766407674076840769407704077140772407734077440775407764077740778407794078040781407824078340784407854078640787407884078940790407914079240793407944079540796407974079840799408004080140802408034080440805408064080740808408094081040811408124081340814408154081640817408184081940820408214082240823408244082540826408274082840829408304083140832408334083440835408364083740838408394084040841408424084340844408454084640847408484084940850408514085240853408544085540856408574085840859408604086140862408634086440865408664086740868408694087040871408724087340874408754087640877408784087940880408814088240883408844088540886408874088840889408904089140892408934089440895408964089740898408994090040901409024090340904409054090640907409084090940910409114091240913409144091540916409174091840919409204092140922409234092440925409264092740928409294093040931409324093340934409354093640937409384093940940409414094240943409444094540946409474094840949409504095140952409534095440955409564095740958409594096040961409624096340964409654096640967409684096940970409714097240973409744097540976409774097840979409804098140982409834098440985409864098740988409894099040991409924099340994409954099640997409984099941000410014100241003410044100541006410074100841009410104101141012410134101441015410164101741018410194102041021410224102341024410254102641027410284102941030410314103241033410344103541036410374103841039410404104141042410434104441045410464104741048410494105041051410524105341054410554105641057410584105941060410614106241063410644106541066410674106841069410704107141072410734107441075410764107741078410794108041081410824108341084410854108641087410884108941090410914109241093410944109541096410974109841099411004110141102411034110441105411064110741108411094111041111411124111341114411154111641117411184111941120411214112241123411244112541126411274112841129411304113141132411334113441135411364113741138411394114041141411424114341144411454114641147411484114941150411514115241153411544115541156411574115841159411604116141162411634116441165411664116741168411694117041171411724117341174411754117641177411784117941180411814118241183411844118541186411874118841189411904119141192411934119441195411964119741198411994120041201412024120341204412054120641207412084120941210412114121241213412144121541216412174121841219412204122141222412234122441225412264122741228412294123041231412324123341234412354123641237412384123941240412414124241243412444124541246412474124841249412504125141252412534125441255412564125741258412594126041261412624126341264412654126641267412684126941270412714127241273412744127541276412774127841279412804128141282412834128441285412864128741288412894129041291412924129341294412954129641297412984129941300413014130241303413044130541306413074130841309413104131141312413134131441315413164131741318413194132041321413224132341324413254132641327413284132941330413314133241333413344133541336413374133841339413404134141342413434134441345413464134741348413494135041351413524135341354413554135641357413584135941360413614136241363413644136541366413674136841369413704137141372413734137441375413764137741378413794138041381413824138341384413854138641387413884138941390413914139241393413944139541396413974139841399414004140141402414034140441405414064140741408414094141041411414124141341414414154141641417414184141941420414214142241423414244142541426414274142841429414304143141432414334143441435414364143741438414394144041441414424144341444414454144641447414484144941450414514145241453414544145541456414574145841459414604146141462414634146441465414664146741468414694147041471414724147341474414754147641477414784147941480414814148241483414844148541486414874148841489414904149141492414934149441495414964149741498414994150041501415024150341504415054150641507415084150941510415114151241513415144151541516415174151841519415204152141522415234152441525415264152741528415294153041531415324153341534415354153641537415384153941540415414154241543415444154541546415474154841549415504155141552415534155441555415564155741558415594156041561415624156341564415654156641567415684156941570415714157241573415744157541576415774157841579415804158141582415834158441585415864158741588415894159041591415924159341594415954159641597415984159941600416014160241603416044160541606416074160841609416104161141612416134161441615416164161741618416194162041621416224162341624416254162641627416284162941630416314163241633416344163541636416374163841639416404164141642416434164441645416464164741648416494165041651416524165341654416554165641657416584165941660416614166241663416644166541666416674166841669416704167141672416734167441675416764167741678416794168041681416824168341684416854168641687416884168941690416914169241693416944169541696416974169841699417004170141702417034170441705417064170741708417094171041711417124171341714417154171641717417184171941720417214172241723417244172541726417274172841729417304173141732417334173441735417364173741738417394174041741417424174341744417454174641747417484174941750417514175241753417544175541756417574175841759417604176141762417634176441765417664176741768417694177041771417724177341774417754177641777417784177941780417814178241783417844178541786417874178841789417904179141792417934179441795417964179741798417994180041801418024180341804418054180641807418084180941810418114181241813418144181541816418174181841819418204182141822418234182441825418264182741828418294183041831418324183341834418354183641837418384183941840418414184241843418444184541846418474184841849418504185141852418534185441855418564185741858418594186041861418624186341864418654186641867418684186941870418714187241873418744187541876418774187841879418804188141882418834188441885418864188741888418894189041891418924189341894418954189641897418984189941900419014190241903419044190541906419074190841909419104191141912419134191441915419164191741918419194192041921419224192341924419254192641927419284192941930419314193241933419344193541936419374193841939419404194141942419434194441945419464194741948419494195041951419524195341954419554195641957419584195941960419614196241963419644196541966419674196841969419704197141972419734197441975419764197741978419794198041981419824198341984419854198641987419884198941990419914199241993419944199541996419974199841999420004200142002420034200442005420064200742008420094201042011420124201342014420154201642017420184201942020420214202242023420244202542026420274202842029420304203142032420334203442035420364203742038420394204042041420424204342044420454204642047420484204942050420514205242053420544205542056420574205842059420604206142062420634206442065420664206742068420694207042071420724207342074420754207642077420784207942080420814208242083420844208542086420874208842089420904209142092420934209442095420964209742098420994210042101421024210342104421054210642107421084210942110421114211242113421144211542116421174211842119421204212142122421234212442125421264212742128421294213042131421324213342134421354213642137421384213942140421414214242143421444214542146421474214842149421504215142152421534215442155421564215742158421594216042161421624216342164421654216642167421684216942170421714217242173421744217542176421774217842179421804218142182421834218442185421864218742188421894219042191421924219342194421954219642197421984219942200422014220242203422044220542206422074220842209422104221142212422134221442215422164221742218422194222042221422224222342224422254222642227422284222942230422314223242233422344223542236422374223842239422404224142242422434224442245422464224742248422494225042251422524225342254422554225642257422584225942260422614226242263422644226542266422674226842269422704227142272422734227442275422764227742278422794228042281422824228342284422854228642287422884228942290422914229242293422944229542296422974229842299423004230142302423034230442305423064230742308423094231042311423124231342314423154231642317423184231942320423214232242323423244232542326423274232842329423304233142332423334233442335423364233742338423394234042341423424234342344423454234642347423484234942350423514235242353423544235542356423574235842359423604236142362423634236442365423664236742368423694237042371423724237342374423754237642377423784237942380423814238242383423844238542386423874238842389423904239142392423934239442395423964239742398423994240042401424024240342404424054240642407424084240942410424114241242413424144241542416424174241842419424204242142422424234242442425424264242742428424294243042431424324243342434424354243642437424384243942440424414244242443424444244542446424474244842449424504245142452424534245442455424564245742458424594246042461424624246342464424654246642467424684246942470424714247242473424744247542476424774247842479424804248142482424834248442485424864248742488424894249042491424924249342494424954249642497424984249942500425014250242503425044250542506425074250842509425104251142512425134251442515425164251742518425194252042521425224252342524425254252642527425284252942530425314253242533425344253542536425374253842539425404254142542425434254442545425464254742548425494255042551425524255342554425554255642557425584255942560425614256242563425644256542566425674256842569425704257142572425734257442575425764257742578425794258042581425824258342584425854258642587425884258942590425914259242593425944259542596425974259842599426004260142602426034260442605426064260742608426094261042611426124261342614426154261642617426184261942620426214262242623426244262542626426274262842629426304263142632426334263442635426364263742638426394264042641426424264342644426454264642647426484264942650426514265242653426544265542656426574265842659426604266142662426634266442665426664266742668426694267042671426724267342674426754267642677426784267942680426814268242683426844268542686426874268842689426904269142692426934269442695426964269742698426994270042701427024270342704427054270642707427084270942710427114271242713427144271542716427174271842719427204272142722427234272442725427264272742728427294273042731427324273342734427354273642737427384273942740427414274242743427444274542746427474274842749427504275142752427534275442755427564275742758427594276042761427624276342764427654276642767427684276942770427714277242773427744277542776427774277842779427804278142782427834278442785427864278742788427894279042791427924279342794427954279642797427984279942800428014280242803428044280542806428074280842809428104281142812428134281442815428164281742818428194282042821428224282342824428254282642827428284282942830428314283242833428344283542836428374283842839428404284142842428434284442845428464284742848428494285042851428524285342854428554285642857428584285942860428614286242863428644286542866428674286842869428704287142872428734287442875428764287742878428794288042881428824288342884428854288642887428884288942890428914289242893428944289542896428974289842899429004290142902429034290442905429064290742908429094291042911429124291342914429154291642917429184291942920429214292242923429244292542926429274292842929429304293142932429334293442935429364293742938429394294042941429424294342944429454294642947429484294942950429514295242953429544295542956429574295842959429604296142962429634296442965429664296742968429694297042971429724297342974429754297642977429784297942980429814298242983429844298542986429874298842989429904299142992429934299442995429964299742998429994300043001430024300343004430054300643007430084300943010430114301243013430144301543016430174301843019430204302143022430234302443025430264302743028430294303043031430324303343034430354303643037430384303943040430414304243043430444304543046430474304843049430504305143052430534305443055430564305743058430594306043061430624306343064430654306643067430684306943070430714307243073430744307543076430774307843079430804308143082430834308443085430864308743088430894309043091430924309343094430954309643097430984309943100431014310243103431044310543106431074310843109431104311143112431134311443115431164311743118431194312043121431224312343124431254312643127431284312943130431314313243133431344313543136431374313843139431404314143142431434314443145431464314743148431494315043151431524315343154431554315643157431584315943160431614316243163431644316543166431674316843169431704317143172431734317443175431764317743178431794318043181431824318343184431854318643187431884318943190431914319243193431944319543196431974319843199432004320143202432034320443205432064320743208432094321043211432124321343214432154321643217432184321943220432214322243223432244322543226432274322843229432304323143232432334323443235432364323743238432394324043241432424324343244432454324643247432484324943250432514325243253432544325543256432574325843259432604326143262432634326443265432664326743268432694327043271432724327343274432754327643277432784327943280432814328243283432844328543286432874328843289432904329143292432934329443295432964329743298432994330043301433024330343304433054330643307433084330943310433114331243313433144331543316433174331843319433204332143322433234332443325433264332743328433294333043331433324333343334433354333643337433384333943340433414334243343433444334543346433474334843349433504335143352433534335443355433564335743358433594336043361433624336343364433654336643367433684336943370433714337243373433744337543376433774337843379433804338143382433834338443385433864338743388433894339043391433924339343394433954339643397433984339943400434014340243403434044340543406434074340843409434104341143412434134341443415434164341743418434194342043421434224342343424434254342643427434284342943430434314343243433434344343543436434374343843439434404344143442434434344443445434464344743448434494345043451434524345343454434554345643457434584345943460434614346243463434644346543466434674346843469434704347143472434734347443475434764347743478434794348043481434824348343484434854348643487434884348943490434914349243493434944349543496434974349843499435004350143502435034350443505435064350743508435094351043511435124351343514435154351643517435184351943520435214352243523435244352543526435274352843529435304353143532435334353443535435364353743538435394354043541435424354343544435454354643547435484354943550435514355243553435544355543556435574355843559435604356143562435634356443565435664356743568435694357043571435724357343574435754357643577435784357943580435814358243583435844358543586435874358843589435904359143592435934359443595435964359743598435994360043601436024360343604436054360643607436084360943610436114361243613436144361543616436174361843619436204362143622436234362443625436264362743628436294363043631436324363343634436354363643637436384363943640436414364243643436444364543646436474364843649436504365143652436534365443655436564365743658436594366043661436624366343664436654366643667436684366943670436714367243673436744367543676436774367843679436804368143682436834368443685436864368743688436894369043691436924369343694436954369643697436984369943700437014370243703437044370543706437074370843709437104371143712437134371443715437164371743718437194372043721437224372343724437254372643727437284372943730437314373243733437344373543736437374373843739437404374143742437434374443745437464374743748437494375043751437524375343754437554375643757437584375943760437614376243763437644376543766437674376843769437704377143772437734377443775437764377743778437794378043781437824378343784437854378643787437884378943790437914379243793437944379543796437974379843799438004380143802438034380443805438064380743808438094381043811438124381343814438154381643817438184381943820438214382243823438244382543826438274382843829438304383143832438334383443835438364383743838438394384043841438424384343844438454384643847438484384943850438514385243853438544385543856438574385843859438604386143862438634386443865438664386743868438694387043871438724387343874438754387643877438784387943880438814388243883438844388543886438874388843889438904389143892438934389443895438964389743898438994390043901439024390343904439054390643907439084390943910439114391243913439144391543916439174391843919439204392143922439234392443925439264392743928439294393043931439324393343934439354393643937439384393943940439414394243943439444394543946439474394843949439504395143952439534395443955439564395743958439594396043961439624396343964439654396643967439684396943970439714397243973439744397543976439774397843979439804398143982439834398443985439864398743988439894399043991439924399343994439954399643997439984399944000440014400244003440044400544006440074400844009440104401144012440134401444015440164401744018440194402044021440224402344024440254402644027440284402944030440314403244033440344403544036440374403844039440404404144042440434404444045440464404744048440494405044051440524405344054440554405644057440584405944060440614406244063440644406544066440674406844069440704407144072440734407444075440764407744078440794408044081440824408344084440854408644087440884408944090440914409244093440944409544096440974409844099441004410144102441034410444105441064410744108441094411044111441124411344114441154411644117441184411944120441214412244123441244412544126441274412844129441304413144132441334413444135441364413744138441394414044141441424414344144441454414644147441484414944150441514415244153441544415544156441574415844159441604416144162441634416444165441664416744168441694417044171441724417344174441754417644177441784417944180441814418244183441844418544186441874418844189441904419144192441934419444195441964419744198441994420044201442024420344204442054420644207442084420944210442114421244213442144421544216442174421844219442204422144222442234422444225442264422744228442294423044231442324423344234442354423644237442384423944240442414424244243442444424544246442474424844249442504425144252442534425444255442564425744258442594426044261442624426344264442654426644267442684426944270442714427244273442744427544276442774427844279442804428144282442834428444285442864428744288442894429044291442924429344294442954429644297442984429944300443014430244303443044430544306443074430844309443104431144312443134431444315443164431744318443194432044321443224432344324443254432644327443284432944330443314433244333443344433544336443374433844339443404434144342443434434444345443464434744348443494435044351443524435344354443554435644357443584435944360443614436244363443644436544366443674436844369443704437144372443734437444375443764437744378443794438044381443824438344384443854438644387443884438944390443914439244393443944439544396443974439844399444004440144402444034440444405444064440744408444094441044411444124441344414444154441644417444184441944420444214442244423444244442544426444274442844429444304443144432444334443444435444364443744438444394444044441444424444344444444454444644447444484444944450444514445244453444544445544456444574445844459444604446144462444634446444465444664446744468444694447044471444724447344474444754447644477444784447944480444814448244483444844448544486444874448844489444904449144492444934449444495444964449744498444994450044501445024450344504445054450644507445084450944510445114451244513445144451544516445174451844519445204452144522445234452444525445264452744528445294453044531445324453344534445354453644537445384453944540445414454244543445444454544546445474454844549445504455144552445534455444555445564455744558445594456044561445624456344564445654456644567445684456944570445714457244573445744457544576445774457844579445804458144582445834458444585445864458744588445894459044591445924459344594445954459644597445984459944600446014460244603446044460544606446074460844609446104461144612446134461444615446164461744618446194462044621446224462344624446254462644627446284462944630446314463244633446344463544636446374463844639446404464144642446434464444645446464464744648446494465044651446524465344654446554465644657446584465944660446614466244663446644466544666446674466844669446704467144672446734467444675446764467744678446794468044681446824468344684446854468644687446884468944690446914469244693446944469544696446974469844699447004470144702447034470444705447064470744708447094471044711447124471344714447154471644717447184471944720447214472244723447244472544726447274472844729447304473144732447334473444735447364473744738447394474044741447424474344744447454474644747447484474944750447514475244753447544475544756447574475844759447604476144762447634476444765447664476744768447694477044771447724477344774447754477644777447784477944780447814478244783447844478544786447874478844789447904479144792447934479444795447964479744798447994480044801448024480344804448054480644807448084480944810448114481244813448144481544816448174481844819448204482144822448234482444825448264482744828448294483044831448324483344834448354483644837448384483944840448414484244843448444484544846448474484844849448504485144852448534485444855448564485744858448594486044861448624486344864448654486644867448684486944870448714487244873448744487544876448774487844879448804488144882448834488444885448864488744888448894489044891448924489344894448954489644897448984489944900449014490244903449044490544906449074490844909449104491144912449134491444915449164491744918449194492044921449224492344924449254492644927449284492944930449314493244933449344493544936449374493844939449404494144942449434494444945449464494744948449494495044951449524495344954449554495644957449584495944960449614496244963449644496544966449674496844969449704497144972449734497444975449764497744978449794498044981449824498344984449854498644987449884498944990449914499244993449944499544996449974499844999450004500145002450034500445005450064500745008450094501045011450124501345014450154501645017450184501945020450214502245023450244502545026450274502845029450304503145032450334503445035450364503745038450394504045041450424504345044450454504645047450484504945050450514505245053450544505545056450574505845059450604506145062450634506445065450664506745068450694507045071450724507345074450754507645077450784507945080450814508245083450844508545086450874508845089450904509145092450934509445095450964509745098450994510045101451024510345104451054510645107451084510945110451114511245113451144511545116451174511845119451204512145122451234512445125451264512745128451294513045131451324513345134451354513645137451384513945140451414514245143451444514545146451474514845149451504515145152451534515445155451564515745158451594516045161451624516345164451654516645167451684516945170451714517245173451744517545176451774517845179451804518145182451834518445185451864518745188451894519045191451924519345194451954519645197451984519945200452014520245203452044520545206452074520845209452104521145212452134521445215452164521745218452194522045221452224522345224452254522645227452284522945230452314523245233452344523545236452374523845239452404524145242452434524445245452464524745248452494525045251452524525345254452554525645257452584525945260452614526245263452644526545266452674526845269452704527145272452734527445275452764527745278452794528045281452824528345284452854528645287452884528945290452914529245293452944529545296452974529845299453004530145302453034530445305453064530745308453094531045311453124531345314453154531645317453184531945320453214532245323453244532545326453274532845329453304533145332453334533445335453364533745338453394534045341453424534345344453454534645347453484534945350453514535245353453544535545356453574535845359453604536145362453634536445365453664536745368453694537045371453724537345374453754537645377453784537945380453814538245383453844538545386453874538845389453904539145392453934539445395453964539745398453994540045401454024540345404454054540645407454084540945410454114541245413454144541545416454174541845419454204542145422454234542445425454264542745428454294543045431454324543345434454354543645437454384543945440454414544245443454444544545446454474544845449454504545145452454534545445455454564545745458454594546045461454624546345464454654546645467454684546945470454714547245473454744547545476454774547845479454804548145482454834548445485454864548745488454894549045491454924549345494454954549645497454984549945500455014550245503455044550545506455074550845509455104551145512455134551445515455164551745518455194552045521455224552345524455254552645527455284552945530455314553245533455344553545536455374553845539455404554145542455434554445545455464554745548455494555045551455524555345554455554555645557455584555945560455614556245563455644556545566455674556845569455704557145572455734557445575455764557745578455794558045581455824558345584455854558645587455884558945590455914559245593455944559545596455974559845599456004560145602456034560445605456064560745608456094561045611456124561345614456154561645617456184561945620456214562245623456244562545626456274562845629456304563145632456334563445635456364563745638456394564045641456424564345644456454564645647456484564945650456514565245653456544565545656456574565845659456604566145662456634566445665456664566745668456694567045671456724567345674456754567645677456784567945680456814568245683456844568545686456874568845689456904569145692456934569445695456964569745698456994570045701457024570345704457054570645707457084570945710457114571245713457144571545716457174571845719457204572145722457234572445725457264572745728457294573045731457324573345734457354573645737457384573945740457414574245743457444574545746457474574845749457504575145752457534575445755457564575745758457594576045761457624576345764457654576645767457684576945770457714577245773457744577545776457774577845779457804578145782457834578445785457864578745788457894579045791457924579345794457954579645797457984579945800458014580245803458044580545806458074580845809458104581145812458134581445815458164581745818458194582045821458224582345824458254582645827458284582945830458314583245833458344583545836458374583845839458404584145842458434584445845458464584745848458494585045851458524585345854458554585645857458584585945860458614586245863458644586545866458674586845869458704587145872458734587445875458764587745878458794588045881458824588345884458854588645887458884588945890458914589245893458944589545896458974589845899459004590145902459034590445905459064590745908459094591045911459124591345914459154591645917459184591945920459214592245923459244592545926459274592845929459304593145932459334593445935459364593745938459394594045941459424594345944459454594645947459484594945950459514595245953459544595545956459574595845959459604596145962459634596445965459664596745968459694597045971459724597345974459754597645977459784597945980459814598245983459844598545986459874598845989459904599145992459934599445995459964599745998459994600046001460024600346004460054600646007460084600946010460114601246013460144601546016460174601846019460204602146022460234602446025460264602746028460294603046031460324603346034460354603646037460384603946040460414604246043460444604546046460474604846049460504605146052460534605446055460564605746058460594606046061460624606346064460654606646067460684606946070460714607246073460744607546076460774607846079460804608146082460834608446085460864608746088460894609046091460924609346094460954609646097460984609946100461014610246103461044610546106461074610846109461104611146112461134611446115461164611746118461194612046121461224612346124461254612646127461284612946130461314613246133461344613546136461374613846139461404614146142461434614446145461464614746148461494615046151461524615346154461554615646157461584615946160461614616246163461644616546166461674616846169461704617146172461734617446175461764617746178461794618046181461824618346184461854618646187461884618946190461914619246193461944619546196461974619846199462004620146202462034620446205462064620746208462094621046211462124621346214462154621646217462184621946220462214622246223462244622546226462274622846229462304623146232462334623446235462364623746238462394624046241462424624346244462454624646247462484624946250462514625246253462544625546256462574625846259462604626146262462634626446265462664626746268462694627046271462724627346274462754627646277462784627946280462814628246283462844628546286462874628846289462904629146292462934629446295462964629746298462994630046301463024630346304463054630646307463084630946310463114631246313463144631546316463174631846319463204632146322463234632446325463264632746328463294633046331463324633346334463354633646337463384633946340463414634246343463444634546346463474634846349463504635146352463534635446355463564635746358463594636046361463624636346364463654636646367463684636946370463714637246373463744637546376463774637846379463804638146382463834638446385463864638746388463894639046391463924639346394463954639646397463984639946400464014640246403464044640546406464074640846409464104641146412464134641446415464164641746418464194642046421464224642346424464254642646427464284642946430464314643246433464344643546436464374643846439464404644146442464434644446445464464644746448464494645046451464524645346454464554645646457464584645946460464614646246463464644646546466464674646846469464704647146472464734647446475464764647746478464794648046481464824648346484464854648646487464884648946490464914649246493464944649546496464974649846499465004650146502465034650446505465064650746508465094651046511465124651346514465154651646517465184651946520465214652246523465244652546526465274652846529465304653146532465334653446535465364653746538465394654046541465424654346544465454654646547465484654946550465514655246553465544655546556465574655846559465604656146562465634656446565465664656746568465694657046571465724657346574465754657646577465784657946580465814658246583465844658546586465874658846589465904659146592465934659446595465964659746598465994660046601466024660346604466054660646607466084660946610466114661246613466144661546616466174661846619466204662146622466234662446625466264662746628466294663046631466324663346634466354663646637466384663946640466414664246643466444664546646466474664846649466504665146652466534665446655466564665746658466594666046661466624666346664466654666646667466684666946670466714667246673466744667546676466774667846679466804668146682466834668446685466864668746688466894669046691466924669346694466954669646697466984669946700467014670246703467044670546706467074670846709467104671146712467134671446715467164671746718467194672046721467224672346724467254672646727467284672946730467314673246733467344673546736467374673846739467404674146742467434674446745467464674746748467494675046751467524675346754467554675646757467584675946760467614676246763467644676546766467674676846769467704677146772467734677446775467764677746778467794678046781467824678346784467854678646787467884678946790467914679246793467944679546796467974679846799468004680146802468034680446805468064680746808468094681046811468124681346814468154681646817468184681946820468214682246823468244682546826468274682846829468304683146832468334683446835468364683746838468394684046841468424684346844468454684646847468484684946850468514685246853468544685546856468574685846859468604686146862468634686446865468664686746868468694687046871468724687346874468754687646877468784687946880468814688246883468844688546886468874688846889468904689146892468934689446895468964689746898468994690046901469024690346904469054690646907469084690946910469114691246913469144691546916469174691846919469204692146922469234692446925469264692746928469294693046931469324693346934469354693646937469384693946940469414694246943469444694546946469474694846949469504695146952469534695446955469564695746958469594696046961469624696346964469654696646967469684696946970469714697246973469744697546976469774697846979469804698146982469834698446985469864698746988469894699046991469924699346994469954699646997469984699947000470014700247003470044700547006470074700847009470104701147012470134701447015470164701747018470194702047021470224702347024470254702647027470284702947030470314703247033470344703547036470374703847039470404704147042470434704447045470464704747048470494705047051470524705347054470554705647057470584705947060470614706247063470644706547066470674706847069470704707147072470734707447075470764707747078470794708047081470824708347084470854708647087470884708947090470914709247093470944709547096470974709847099471004710147102471034710447105471064710747108471094711047111471124711347114471154711647117471184711947120471214712247123471244712547126471274712847129471304713147132471334713447135471364713747138471394714047141471424714347144471454714647147471484714947150471514715247153471544715547156471574715847159471604716147162471634716447165471664716747168471694717047171471724717347174471754717647177471784717947180471814718247183471844718547186471874718847189471904719147192471934719447195471964719747198471994720047201472024720347204472054720647207472084720947210472114721247213472144721547216472174721847219472204722147222472234722447225472264722747228472294723047231472324723347234472354723647237472384723947240472414724247243472444724547246472474724847249472504725147252472534725447255472564725747258472594726047261472624726347264472654726647267472684726947270472714727247273472744727547276472774727847279472804728147282472834728447285472864728747288472894729047291472924729347294472954729647297472984729947300473014730247303473044730547306473074730847309473104731147312473134731447315473164731747318473194732047321473224732347324473254732647327473284732947330473314733247333473344733547336473374733847339473404734147342473434734447345473464734747348473494735047351473524735347354473554735647357473584735947360473614736247363473644736547366473674736847369473704737147372473734737447375473764737747378473794738047381473824738347384473854738647387473884738947390473914739247393473944739547396473974739847399474004740147402474034740447405474064740747408474094741047411474124741347414474154741647417474184741947420474214742247423474244742547426474274742847429474304743147432474334743447435474364743747438474394744047441474424744347444474454744647447474484744947450474514745247453474544745547456474574745847459474604746147462474634746447465474664746747468474694747047471474724747347474474754747647477474784747947480474814748247483474844748547486474874748847489474904749147492474934749447495474964749747498474994750047501475024750347504475054750647507475084750947510475114751247513475144751547516475174751847519475204752147522475234752447525475264752747528475294753047531475324753347534475354753647537475384753947540475414754247543475444754547546475474754847549475504755147552475534755447555475564755747558475594756047561475624756347564475654756647567475684756947570475714757247573475744757547576475774757847579475804758147582475834758447585475864758747588475894759047591475924759347594475954759647597475984759947600476014760247603476044760547606476074760847609476104761147612476134761447615476164761747618476194762047621476224762347624476254762647627476284762947630476314763247633476344763547636476374763847639476404764147642476434764447645476464764747648476494765047651476524765347654476554765647657476584765947660476614766247663476644766547666476674766847669476704767147672476734767447675476764767747678476794768047681476824768347684476854768647687476884768947690476914769247693476944769547696476974769847699477004770147702477034770447705477064770747708477094771047711477124771347714477154771647717477184771947720477214772247723477244772547726477274772847729477304773147732477334773447735477364773747738477394774047741477424774347744477454774647747477484774947750477514775247753477544775547756477574775847759477604776147762477634776447765477664776747768477694777047771477724777347774477754777647777477784777947780477814778247783477844778547786477874778847789477904779147792477934779447795477964779747798477994780047801478024780347804478054780647807478084780947810478114781247813478144781547816478174781847819478204782147822478234782447825478264782747828478294783047831478324783347834478354783647837478384783947840478414784247843478444784547846478474784847849478504785147852478534785447855478564785747858478594786047861478624786347864478654786647867478684786947870478714787247873478744787547876478774787847879478804788147882478834788447885478864788747888478894789047891478924789347894478954789647897478984789947900479014790247903479044790547906479074790847909479104791147912479134791447915479164791747918479194792047921479224792347924479254792647927479284792947930479314793247933479344793547936479374793847939479404794147942479434794447945479464794747948479494795047951479524795347954479554795647957479584795947960479614796247963479644796547966479674796847969479704797147972479734797447975479764797747978479794798047981479824798347984479854798647987479884798947990479914799247993479944799547996479974799847999480004800148002480034800448005480064800748008480094801048011480124801348014480154801648017480184801948020480214802248023480244802548026480274802848029480304803148032480334803448035480364803748038480394804048041480424804348044480454804648047480484804948050480514805248053480544805548056480574805848059480604806148062480634806448065480664806748068480694807048071480724807348074480754807648077480784807948080480814808248083480844808548086480874808848089480904809148092480934809448095480964809748098480994810048101481024810348104481054810648107481084810948110481114811248113481144811548116481174811848119481204812148122481234812448125481264812748128481294813048131481324813348134481354813648137481384813948140481414814248143481444814548146481474814848149481504815148152481534815448155481564815748158481594816048161481624816348164481654816648167481684816948170481714817248173481744817548176481774817848179481804818148182481834818448185481864818748188481894819048191481924819348194481954819648197481984819948200482014820248203482044820548206482074820848209482104821148212482134821448215482164821748218482194822048221482224822348224482254822648227482284822948230482314823248233482344823548236482374823848239482404824148242482434824448245482464824748248482494825048251482524825348254482554825648257482584825948260482614826248263482644826548266482674826848269482704827148272482734827448275482764827748278482794828048281482824828348284482854828648287482884828948290482914829248293482944829548296482974829848299483004830148302483034830448305483064830748308483094831048311483124831348314483154831648317483184831948320483214832248323483244832548326483274832848329483304833148332483334833448335483364833748338483394834048341483424834348344483454834648347483484834948350483514835248353483544835548356483574835848359483604836148362483634836448365483664836748368483694837048371483724837348374483754837648377483784837948380483814838248383483844838548386483874838848389483904839148392483934839448395483964839748398483994840048401484024840348404484054840648407484084840948410484114841248413484144841548416484174841848419484204842148422484234842448425484264842748428484294843048431484324843348434484354843648437484384843948440484414844248443484444844548446484474844848449484504845148452484534845448455484564845748458484594846048461484624846348464484654846648467484684846948470484714847248473484744847548476484774847848479484804848148482484834848448485484864848748488484894849048491484924849348494484954849648497484984849948500485014850248503485044850548506485074850848509485104851148512485134851448515485164851748518485194852048521485224852348524485254852648527485284852948530485314853248533485344853548536485374853848539485404854148542485434854448545485464854748548485494855048551485524855348554485554855648557485584855948560485614856248563485644856548566485674856848569485704857148572485734857448575485764857748578485794858048581485824858348584485854858648587485884858948590485914859248593485944859548596485974859848599486004860148602486034860448605486064860748608486094861048611486124861348614486154861648617486184861948620486214862248623486244862548626486274862848629486304863148632486334863448635486364863748638486394864048641486424864348644486454864648647486484864948650486514865248653486544865548656486574865848659486604866148662486634866448665486664866748668486694867048671486724867348674486754867648677486784867948680486814868248683486844868548686486874868848689486904869148692486934869448695486964869748698486994870048701487024870348704487054870648707487084870948710487114871248713487144871548716487174871848719487204872148722487234872448725487264872748728487294873048731487324873348734487354873648737487384873948740487414874248743487444874548746487474874848749487504875148752487534875448755487564875748758487594876048761487624876348764487654876648767487684876948770487714877248773487744877548776487774877848779487804878148782487834878448785487864878748788487894879048791487924879348794487954879648797487984879948800488014880248803488044880548806488074880848809488104881148812488134881448815488164881748818488194882048821488224882348824488254882648827488284882948830488314883248833488344883548836488374883848839488404884148842488434884448845488464884748848488494885048851488524885348854488554885648857488584885948860488614886248863488644886548866488674886848869488704887148872488734887448875488764887748878488794888048881488824888348884488854888648887488884888948890488914889248893488944889548896488974889848899489004890148902489034890448905489064890748908489094891048911489124891348914489154891648917489184891948920489214892248923489244892548926489274892848929489304893148932489334893448935489364893748938489394894048941489424894348944489454894648947489484894948950489514895248953489544895548956489574895848959489604896148962489634896448965489664896748968489694897048971489724897348974489754897648977489784897948980489814898248983489844898548986489874898848989489904899148992489934899448995489964899748998489994900049001490024900349004490054900649007490084900949010490114901249013490144901549016490174901849019490204902149022490234902449025490264902749028490294903049031490324903349034490354903649037490384903949040490414904249043490444904549046490474904849049490504905149052490534905449055490564905749058490594906049061490624906349064490654906649067490684906949070490714907249073490744907549076490774907849079490804908149082490834908449085490864908749088490894909049091490924909349094490954909649097490984909949100491014910249103491044910549106491074910849109491104911149112491134911449115491164911749118491194912049121491224912349124491254912649127491284912949130491314913249133491344913549136491374913849139491404914149142491434914449145491464914749148491494915049151491524915349154491554915649157491584915949160491614916249163491644916549166491674916849169491704917149172491734917449175491764917749178491794918049181491824918349184491854918649187491884918949190491914919249193491944919549196491974919849199492004920149202492034920449205492064920749208492094921049211492124921349214492154921649217492184921949220492214922249223492244922549226492274922849229492304923149232492334923449235492364923749238492394924049241492424924349244492454924649247492484924949250492514925249253492544925549256492574925849259492604926149262492634926449265492664926749268492694927049271492724927349274492754927649277492784927949280492814928249283492844928549286492874928849289492904929149292492934929449295492964929749298492994930049301493024930349304493054930649307493084930949310493114931249313493144931549316493174931849319493204932149322493234932449325493264932749328493294933049331493324933349334493354933649337493384933949340493414934249343493444934549346493474934849349493504935149352493534935449355493564935749358493594936049361493624936349364493654936649367493684936949370493714937249373493744937549376493774937849379493804938149382493834938449385493864938749388493894939049391493924939349394493954939649397493984939949400494014940249403494044940549406494074940849409494104941149412494134941449415494164941749418494194942049421494224942349424494254942649427494284942949430494314943249433494344943549436494374943849439494404944149442494434944449445494464944749448494494945049451494524945349454494554945649457494584945949460494614946249463494644946549466494674946849469494704947149472494734947449475494764947749478494794948049481494824948349484494854948649487494884948949490494914949249493494944949549496494974949849499495004950149502495034950449505495064950749508495094951049511495124951349514495154951649517495184951949520495214952249523495244952549526495274952849529495304953149532495334953449535495364953749538495394954049541495424954349544495454954649547495484954949550495514955249553495544955549556495574955849559495604956149562495634956449565495664956749568495694957049571495724957349574495754957649577495784957949580495814958249583495844958549586495874958849589495904959149592495934959449595495964959749598495994960049601496024960349604496054960649607496084960949610496114961249613496144961549616496174961849619496204962149622496234962449625496264962749628496294963049631496324963349634496354963649637496384963949640496414964249643496444964549646496474964849649496504965149652496534965449655496564965749658496594966049661496624966349664496654966649667496684966949670496714967249673496744967549676496774967849679496804968149682496834968449685496864968749688496894969049691496924969349694496954969649697496984969949700497014970249703497044970549706497074970849709497104971149712497134971449715497164971749718497194972049721497224972349724497254972649727497284972949730497314973249733497344973549736497374973849739497404974149742497434974449745497464974749748497494975049751497524975349754497554975649757497584975949760497614976249763497644976549766497674976849769497704977149772497734977449775497764977749778497794978049781497824978349784497854978649787497884978949790497914979249793497944979549796497974979849799498004980149802498034980449805498064980749808498094981049811498124981349814498154981649817498184981949820498214982249823498244982549826498274982849829498304983149832498334983449835498364983749838498394984049841498424984349844498454984649847498484984949850498514985249853498544985549856498574985849859498604986149862498634986449865498664986749868498694987049871498724987349874498754987649877498784987949880498814988249883498844988549886498874988849889498904989149892498934989449895498964989749898498994990049901499024990349904499054990649907499084990949910499114991249913499144991549916499174991849919499204992149922499234992449925499264992749928499294993049931499324993349934499354993649937499384993949940499414994249943499444994549946499474994849949499504995149952499534995449955499564995749958499594996049961499624996349964499654996649967499684996949970499714997249973499744997549976499774997849979499804998149982499834998449985499864998749988499894999049991499924999349994499954999649997499984999950000500015000250003500045000550006500075000850009500105001150012500135001450015500165001750018500195002050021500225002350024500255002650027500285002950030500315003250033500345003550036500375003850039500405004150042500435004450045500465004750048500495005050051500525005350054500555005650057500585005950060500615006250063500645006550066500675006850069500705007150072500735007450075500765007750078500795008050081500825008350084500855008650087500885008950090500915009250093500945009550096500975009850099501005010150102501035010450105501065010750108501095011050111501125011350114501155011650117501185011950120501215012250123501245012550126501275012850129501305013150132501335013450135501365013750138501395014050141501425014350144501455014650147501485014950150501515015250153501545015550156501575015850159501605016150162501635016450165501665016750168501695017050171501725017350174501755017650177501785017950180501815018250183501845018550186501875018850189501905019150192501935019450195501965019750198501995020050201502025020350204502055020650207502085020950210502115021250213502145021550216502175021850219502205022150222502235022450225502265022750228502295023050231502325023350234502355023650237502385023950240502415024250243502445024550246502475024850249502505025150252502535025450255502565025750258502595026050261502625026350264502655026650267502685026950270502715027250273502745027550276502775027850279502805028150282502835028450285502865028750288502895029050291502925029350294502955029650297502985029950300503015030250303503045030550306503075030850309503105031150312503135031450315503165031750318503195032050321503225032350324503255032650327503285032950330503315033250333503345033550336503375033850339503405034150342503435034450345503465034750348503495035050351503525035350354503555035650357503585035950360503615036250363503645036550366503675036850369503705037150372503735037450375503765037750378503795038050381503825038350384503855038650387503885038950390503915039250393503945039550396503975039850399504005040150402504035040450405504065040750408504095041050411504125041350414504155041650417504185041950420504215042250423504245042550426504275042850429504305043150432504335043450435504365043750438504395044050441504425044350444504455044650447504485044950450504515045250453504545045550456504575045850459504605046150462504635046450465504665046750468504695047050471504725047350474504755047650477504785047950480504815048250483504845048550486504875048850489504905049150492504935049450495504965049750498504995050050501505025050350504505055050650507505085050950510505115051250513505145051550516505175051850519505205052150522505235052450525505265052750528505295053050531505325053350534505355053650537505385053950540505415054250543505445054550546505475054850549505505055150552505535055450555505565055750558505595056050561505625056350564505655056650567505685056950570505715057250573505745057550576505775057850579505805058150582505835058450585505865058750588505895059050591505925059350594505955059650597505985059950600506015060250603506045060550606506075060850609506105061150612506135061450615506165061750618506195062050621506225062350624506255062650627506285062950630506315063250633506345063550636506375063850639506405064150642506435064450645506465064750648506495065050651506525065350654506555065650657506585065950660506615066250663506645066550666506675066850669506705067150672506735067450675506765067750678506795068050681506825068350684506855068650687506885068950690506915069250693506945069550696506975069850699507005070150702507035070450705507065070750708507095071050711507125071350714507155071650717507185071950720507215072250723507245072550726507275072850729507305073150732507335073450735507365073750738507395074050741507425074350744507455074650747507485074950750507515075250753507545075550756507575075850759507605076150762507635076450765507665076750768507695077050771507725077350774507755077650777507785077950780507815078250783507845078550786507875078850789507905079150792507935079450795507965079750798507995080050801508025080350804508055080650807508085080950810508115081250813508145081550816508175081850819508205082150822508235082450825508265082750828508295083050831508325083350834508355083650837508385083950840508415084250843508445084550846508475084850849508505085150852508535085450855508565085750858508595086050861508625086350864508655086650867508685086950870508715087250873508745087550876508775087850879508805088150882508835088450885508865088750888508895089050891508925089350894508955089650897508985089950900509015090250903509045090550906509075090850909509105091150912509135091450915509165091750918509195092050921509225092350924509255092650927509285092950930509315093250933509345093550936509375093850939509405094150942509435094450945509465094750948509495095050951509525095350954509555095650957509585095950960509615096250963509645096550966509675096850969509705097150972509735097450975509765097750978509795098050981509825098350984509855098650987509885098950990509915099250993509945099550996509975099850999510005100151002510035100451005510065100751008510095101051011510125101351014510155101651017510185101951020510215102251023510245102551026510275102851029510305103151032510335103451035510365103751038510395104051041510425104351044510455104651047510485104951050510515105251053510545105551056510575105851059510605106151062510635106451065510665106751068510695107051071510725107351074510755107651077510785107951080510815108251083510845108551086510875108851089510905109151092510935109451095510965109751098510995110051101511025110351104511055110651107511085110951110511115111251113511145111551116511175111851119511205112151122511235112451125511265112751128511295113051131511325113351134511355113651137511385113951140511415114251143511445114551146511475114851149511505115151152511535115451155511565115751158511595116051161511625116351164511655116651167511685116951170511715117251173511745117551176511775117851179511805118151182511835118451185511865118751188511895119051191511925119351194511955119651197511985119951200512015120251203512045120551206512075120851209512105121151212512135121451215512165121751218512195122051221512225122351224512255122651227512285122951230512315123251233512345123551236512375123851239512405124151242512435124451245512465124751248512495125051251512525125351254512555125651257512585125951260512615126251263512645126551266512675126851269512705127151272512735127451275512765127751278512795128051281512825128351284512855128651287512885128951290512915129251293512945129551296512975129851299513005130151302513035130451305513065130751308513095131051311513125131351314513155131651317513185131951320513215132251323513245132551326513275132851329513305133151332513335133451335513365133751338513395134051341513425134351344513455134651347513485134951350513515135251353513545135551356513575135851359513605136151362513635136451365513665136751368513695137051371513725137351374513755137651377513785137951380513815138251383513845138551386513875138851389513905139151392513935139451395513965139751398513995140051401514025140351404514055140651407514085140951410514115141251413514145141551416514175141851419514205142151422514235142451425514265142751428514295143051431514325143351434514355143651437514385143951440514415144251443514445144551446514475144851449514505145151452514535145451455514565145751458514595146051461514625146351464514655146651467514685146951470514715147251473514745147551476514775147851479514805148151482514835148451485514865148751488514895149051491514925149351494514955149651497514985149951500515015150251503515045150551506515075150851509515105151151512515135151451515515165151751518515195152051521515225152351524515255152651527515285152951530515315153251533515345153551536515375153851539515405154151542515435154451545515465154751548515495155051551515525155351554515555155651557515585155951560515615156251563515645156551566515675156851569515705157151572515735157451575515765157751578515795158051581515825158351584515855158651587515885158951590515915159251593515945159551596515975159851599516005160151602516035160451605516065160751608516095161051611516125161351614516155161651617516185161951620516215162251623516245162551626516275162851629516305163151632516335163451635516365163751638516395164051641516425164351644516455164651647516485164951650516515165251653516545165551656516575165851659516605166151662516635166451665516665166751668516695167051671516725167351674516755167651677516785167951680516815168251683516845168551686516875168851689516905169151692516935169451695516965169751698516995170051701517025170351704517055170651707517085170951710517115171251713517145171551716517175171851719517205172151722517235172451725517265172751728517295173051731517325173351734517355173651737517385173951740517415174251743517445174551746517475174851749517505175151752517535175451755517565175751758517595176051761517625176351764517655176651767517685176951770517715177251773517745177551776517775177851779517805178151782517835178451785517865178751788517895179051791517925179351794517955179651797517985179951800518015180251803518045180551806518075180851809518105181151812518135181451815518165181751818518195182051821518225182351824518255182651827518285182951830518315183251833518345183551836518375183851839518405184151842518435184451845518465184751848518495185051851518525185351854518555185651857518585185951860518615186251863518645186551866518675186851869518705187151872518735187451875518765187751878518795188051881518825188351884518855188651887518885188951890518915189251893518945189551896518975189851899519005190151902519035190451905519065190751908519095191051911519125191351914519155191651917519185191951920519215192251923519245192551926519275192851929519305193151932519335193451935519365193751938519395194051941519425194351944519455194651947519485194951950519515195251953519545195551956519575195851959519605196151962519635196451965519665196751968519695197051971519725197351974519755197651977519785197951980519815198251983519845198551986519875198851989519905199151992519935199451995519965199751998519995200052001520025200352004520055200652007520085200952010520115201252013520145201552016520175201852019520205202152022520235202452025520265202752028520295203052031520325203352034520355203652037520385203952040520415204252043520445204552046520475204852049520505205152052520535205452055520565205752058520595206052061520625206352064520655206652067520685206952070520715207252073520745207552076520775207852079520805208152082520835208452085520865208752088520895209052091520925209352094520955209652097520985209952100521015210252103521045210552106521075210852109521105211152112521135211452115521165211752118521195212052121521225212352124521255212652127521285212952130521315213252133521345213552136521375213852139521405214152142521435214452145521465214752148521495215052151521525215352154521555215652157521585215952160521615216252163521645216552166521675216852169521705217152172521735217452175521765217752178521795218052181521825218352184521855218652187521885218952190521915219252193521945219552196521975219852199522005220152202522035220452205522065220752208522095221052211522125221352214522155221652217522185221952220522215222252223522245222552226522275222852229522305223152232522335223452235522365223752238522395224052241522425224352244522455224652247522485224952250522515225252253522545225552256522575225852259522605226152262522635226452265522665226752268522695227052271522725227352274522755227652277522785227952280522815228252283522845228552286522875228852289522905229152292522935229452295522965229752298522995230052301523025230352304523055230652307523085230952310523115231252313523145231552316523175231852319523205232152322523235232452325523265232752328523295233052331523325233352334523355233652337523385233952340523415234252343523445234552346523475234852349523505235152352523535235452355523565235752358523595236052361523625236352364523655236652367523685236952370523715237252373523745237552376523775237852379523805238152382523835238452385523865238752388523895239052391523925239352394523955239652397523985239952400524015240252403524045240552406524075240852409524105241152412524135241452415524165241752418524195242052421524225242352424524255242652427524285242952430524315243252433524345243552436524375243852439524405244152442524435244452445524465244752448524495245052451524525245352454524555245652457524585245952460524615246252463524645246552466524675246852469524705247152472524735247452475524765247752478524795248052481524825248352484524855248652487524885248952490524915249252493524945249552496524975249852499525005250152502525035250452505525065250752508525095251052511525125251352514525155251652517525185251952520525215252252523525245252552526525275252852529525305253152532525335253452535525365253752538525395254052541525425254352544525455254652547525485254952550525515255252553525545255552556525575255852559525605256152562525635256452565525665256752568525695257052571525725257352574525755257652577525785257952580525815258252583525845258552586525875258852589525905259152592525935259452595525965259752598525995260052601526025260352604526055260652607526085260952610526115261252613526145261552616526175261852619526205262152622526235262452625526265262752628526295263052631526325263352634526355263652637526385263952640526415264252643526445264552646526475264852649526505265152652526535265452655526565265752658526595266052661526625266352664526655266652667526685266952670526715267252673526745267552676526775267852679526805268152682526835268452685526865268752688526895269052691526925269352694526955269652697526985269952700527015270252703527045270552706527075270852709527105271152712527135271452715527165271752718527195272052721527225272352724527255272652727527285272952730527315273252733527345273552736527375273852739527405274152742527435274452745527465274752748527495275052751527525275352754527555275652757527585275952760527615276252763527645276552766527675276852769527705277152772527735277452775527765277752778527795278052781527825278352784527855278652787527885278952790527915279252793527945279552796527975279852799528005280152802528035280452805528065280752808528095281052811528125281352814528155281652817528185281952820528215282252823528245282552826528275282852829528305283152832528335283452835528365283752838528395284052841528425284352844528455284652847528485284952850528515285252853528545285552856528575285852859528605286152862528635286452865528665286752868528695287052871528725287352874528755287652877528785287952880528815288252883528845288552886528875288852889528905289152892528935289452895528965289752898528995290052901529025290352904529055290652907529085290952910529115291252913529145291552916529175291852919529205292152922529235292452925529265292752928529295293052931529325293352934529355293652937529385293952940529415294252943529445294552946529475294852949529505295152952529535295452955529565295752958529595296052961529625296352964529655296652967529685296952970529715297252973529745297552976529775297852979529805298152982529835298452985529865298752988529895299052991529925299352994529955299652997529985299953000530015300253003530045300553006530075300853009530105301153012530135301453015530165301753018530195302053021530225302353024530255302653027530285302953030530315303253033530345303553036530375303853039530405304153042530435304453045530465304753048530495305053051530525305353054530555305653057530585305953060530615306253063530645306553066530675306853069530705307153072530735307453075530765307753078530795308053081530825308353084530855308653087530885308953090530915309253093530945309553096530975309853099531005310153102531035310453105531065310753108531095311053111531125311353114531155311653117531185311953120531215312253123531245312553126531275312853129531305313153132531335313453135531365313753138531395314053141531425314353144531455314653147531485314953150531515315253153531545315553156531575315853159531605316153162531635316453165531665316753168531695317053171531725317353174531755317653177531785317953180531815318253183531845318553186531875318853189531905319153192531935319453195531965319753198531995320053201532025320353204532055320653207532085320953210532115321253213532145321553216532175321853219532205322153222532235322453225532265322753228532295323053231532325323353234532355323653237532385323953240532415324253243532445324553246532475324853249532505325153252532535325453255532565325753258532595326053261532625326353264532655326653267532685326953270532715327253273532745327553276532775327853279532805328153282532835328453285532865328753288532895329053291532925329353294532955329653297532985329953300533015330253303533045330553306533075330853309533105331153312533135331453315533165331753318533195332053321533225332353324533255332653327533285332953330533315333253333533345333553336533375333853339533405334153342533435334453345533465334753348533495335053351533525335353354533555335653357533585335953360533615336253363533645336553366533675336853369533705337153372533735337453375533765337753378533795338053381533825338353384533855338653387533885338953390533915339253393533945339553396533975339853399534005340153402534035340453405534065340753408534095341053411534125341353414534155341653417534185341953420534215342253423534245342553426534275342853429534305343153432534335343453435534365343753438534395344053441534425344353444534455344653447534485344953450534515345253453534545345553456534575345853459534605346153462534635346453465534665346753468534695347053471534725347353474534755347653477534785347953480534815348253483534845348553486534875348853489534905349153492534935349453495534965349753498534995350053501535025350353504535055350653507535085350953510535115351253513535145351553516535175351853519535205352153522535235352453525535265352753528535295353053531535325353353534535355353653537535385353953540535415354253543535445354553546535475354853549535505355153552535535355453555535565355753558535595356053561535625356353564535655356653567535685356953570535715357253573535745357553576535775357853579535805358153582535835358453585535865358753588535895359053591535925359353594535955359653597535985359953600536015360253603536045360553606536075360853609536105361153612536135361453615536165361753618536195362053621536225362353624536255362653627536285362953630536315363253633536345363553636536375363853639536405364153642536435364453645536465364753648536495365053651536525365353654536555365653657536585365953660536615366253663536645366553666536675366853669536705367153672536735367453675536765367753678536795368053681536825368353684536855368653687536885368953690536915369253693536945369553696536975369853699537005370153702537035370453705537065370753708537095371053711537125371353714537155371653717537185371953720537215372253723537245372553726537275372853729537305373153732537335373453735537365373753738537395374053741537425374353744537455374653747537485374953750537515375253753537545375553756537575375853759537605376153762537635376453765537665376753768537695377053771537725377353774537755377653777537785377953780537815378253783537845378553786537875378853789537905379153792537935379453795537965379753798537995380053801538025380353804538055380653807538085380953810538115381253813538145381553816538175381853819538205382153822538235382453825538265382753828538295383053831538325383353834538355383653837538385383953840538415384253843538445384553846538475384853849538505385153852538535385453855538565385753858538595386053861538625386353864538655386653867538685386953870538715387253873538745387553876538775387853879538805388153882538835388453885538865388753888538895389053891538925389353894538955389653897538985389953900539015390253903539045390553906539075390853909539105391153912539135391453915539165391753918539195392053921539225392353924539255392653927539285392953930539315393253933539345393553936539375393853939539405394153942539435394453945539465394753948539495395053951539525395353954539555395653957539585395953960539615396253963539645396553966539675396853969539705397153972539735397453975539765397753978539795398053981539825398353984539855398653987539885398953990539915399253993539945399553996539975399853999540005400154002540035400454005540065400754008540095401054011540125401354014540155401654017540185401954020540215402254023540245402554026540275402854029540305403154032540335403454035540365403754038540395404054041540425404354044540455404654047540485404954050540515405254053540545405554056540575405854059540605406154062540635406454065540665406754068540695407054071540725407354074540755407654077540785407954080540815408254083540845408554086540875408854089540905409154092540935409454095540965409754098540995410054101541025410354104541055410654107541085410954110541115411254113541145411554116541175411854119541205412154122541235412454125541265412754128541295413054131541325413354134541355413654137541385413954140541415414254143541445414554146541475414854149541505415154152541535415454155541565415754158541595416054161541625416354164541655416654167541685416954170541715417254173541745417554176541775417854179541805418154182541835418454185541865418754188541895419054191541925419354194541955419654197541985419954200542015420254203542045420554206542075420854209542105421154212542135421454215542165421754218542195422054221542225422354224542255422654227542285422954230542315423254233542345423554236542375423854239542405424154242542435424454245542465424754248542495425054251542525425354254542555425654257542585425954260542615426254263542645426554266542675426854269542705427154272542735427454275542765427754278542795428054281542825428354284542855428654287542885428954290542915429254293542945429554296542975429854299543005430154302543035430454305543065430754308543095431054311543125431354314543155431654317543185431954320543215432254323543245432554326543275432854329543305433154332543335433454335543365433754338543395434054341543425434354344543455434654347543485434954350543515435254353543545435554356543575435854359543605436154362543635436454365543665436754368543695437054371543725437354374543755437654377543785437954380543815438254383543845438554386543875438854389543905439154392543935439454395543965439754398543995440054401544025440354404544055440654407544085440954410544115441254413544145441554416544175441854419544205442154422544235442454425544265442754428544295443054431544325443354434544355443654437544385443954440544415444254443544445444554446544475444854449544505445154452544535445454455544565445754458544595446054461544625446354464544655446654467544685446954470544715447254473544745447554476544775447854479544805448154482544835448454485544865448754488544895449054491544925449354494544955449654497544985449954500545015450254503545045450554506545075450854509545105451154512545135451454515545165451754518545195452054521545225452354524545255452654527545285452954530545315453254533545345453554536545375453854539545405454154542545435454454545545465454754548545495455054551545525455354554545555455654557545585455954560545615456254563545645456554566545675456854569545705457154572545735457454575545765457754578545795458054581545825458354584545855458654587545885458954590545915459254593545945459554596545975459854599546005460154602546035460454605546065460754608546095461054611546125461354614546155461654617546185461954620546215462254623546245462554626546275462854629546305463154632546335463454635546365463754638546395464054641546425464354644546455464654647546485464954650546515465254653546545465554656546575465854659546605466154662546635466454665546665466754668546695467054671546725467354674546755467654677546785467954680546815468254683546845468554686546875468854689546905469154692546935469454695546965469754698546995470054701547025470354704547055470654707547085470954710547115471254713547145471554716547175471854719547205472154722547235472454725547265472754728547295473054731547325473354734547355473654737547385473954740547415474254743547445474554746547475474854749547505475154752547535475454755547565475754758547595476054761547625476354764547655476654767547685476954770547715477254773547745477554776547775477854779547805478154782547835478454785547865478754788547895479054791547925479354794547955479654797547985479954800548015480254803548045480554806548075480854809548105481154812548135481454815548165481754818548195482054821548225482354824548255482654827548285482954830548315483254833548345483554836548375483854839548405484154842548435484454845548465484754848548495485054851548525485354854548555485654857548585485954860548615486254863548645486554866548675486854869548705487154872548735487454875548765487754878548795488054881548825488354884548855488654887548885488954890548915489254893548945489554896548975489854899549005490154902549035490454905549065490754908549095491054911549125491354914549155491654917549185491954920549215492254923549245492554926549275492854929549305493154932549335493454935549365493754938549395494054941549425494354944549455494654947549485494954950549515495254953549545495554956549575495854959549605496154962549635496454965549665496754968549695497054971549725497354974549755497654977549785497954980549815498254983549845498554986549875498854989549905499154992549935499454995549965499754998549995500055001550025500355004550055500655007550085500955010550115501255013550145501555016550175501855019550205502155022550235502455025550265502755028550295503055031550325503355034550355503655037550385503955040550415504255043550445504555046550475504855049550505505155052550535505455055550565505755058550595506055061550625506355064550655506655067550685506955070550715507255073550745507555076550775507855079550805508155082550835508455085550865508755088550895509055091550925509355094550955509655097550985509955100551015510255103551045510555106551075510855109551105511155112551135511455115551165511755118551195512055121551225512355124551255512655127551285512955130551315513255133551345513555136551375513855139551405514155142551435514455145551465514755148551495515055151551525515355154551555515655157551585515955160551615516255163551645516555166551675516855169551705517155172551735517455175551765517755178551795518055181551825518355184551855518655187551885518955190551915519255193551945519555196551975519855199552005520155202552035520455205552065520755208552095521055211552125521355214552155521655217552185521955220552215522255223552245522555226552275522855229552305523155232552335523455235552365523755238552395524055241552425524355244552455524655247552485524955250552515525255253552545525555256552575525855259552605526155262552635526455265552665526755268552695527055271552725527355274552755527655277552785527955280552815528255283552845528555286552875528855289552905529155292552935529455295552965529755298552995530055301553025530355304553055530655307553085530955310553115531255313553145531555316553175531855319553205532155322553235532455325553265532755328553295533055331553325533355334553355533655337553385533955340553415534255343553445534555346553475534855349553505535155352553535535455355553565535755358553595536055361553625536355364553655536655367553685536955370553715537255373553745537555376553775537855379553805538155382553835538455385553865538755388553895539055391553925539355394553955539655397553985539955400554015540255403554045540555406554075540855409554105541155412554135541455415554165541755418554195542055421554225542355424554255542655427554285542955430554315543255433554345543555436554375543855439554405544155442554435544455445554465544755448554495545055451554525545355454554555545655457554585545955460554615546255463554645546555466554675546855469554705547155472554735547455475554765547755478554795548055481554825548355484554855548655487554885548955490554915549255493554945549555496554975549855499555005550155502555035550455505555065550755508555095551055511555125551355514555155551655517555185551955520555215552255523555245552555526555275552855529555305553155532555335553455535555365553755538555395554055541555425554355544555455554655547555485554955550555515555255553555545555555556555575555855559555605556155562555635556455565555665556755568555695557055571555725557355574555755557655577555785557955580555815558255583555845558555586555875558855589555905559155592555935559455595555965559755598555995560055601556025560355604556055560655607556085560955610556115561255613556145561555616556175561855619556205562155622556235562455625556265562755628556295563055631556325563355634556355563655637556385563955640556415564255643556445564555646556475564855649556505565155652556535565455655556565565755658556595566055661556625566355664556655566655667556685566955670556715567255673556745567555676556775567855679556805568155682556835568455685556865568755688556895569055691556925569355694556955569655697556985569955700557015570255703557045570555706557075570855709557105571155712557135571455715557165571755718557195572055721557225572355724557255572655727557285572955730557315573255733557345573555736557375573855739557405574155742557435574455745557465574755748557495575055751557525575355754557555575655757557585575955760557615576255763557645576555766557675576855769557705577155772557735577455775557765577755778557795578055781557825578355784557855578655787557885578955790557915579255793557945579555796557975579855799558005580155802558035580455805558065580755808558095581055811558125581355814558155581655817558185581955820558215582255823558245582555826558275582855829558305583155832558335583455835558365583755838558395584055841558425584355844558455584655847558485584955850558515585255853558545585555856558575585855859558605586155862558635586455865558665586755868558695587055871558725587355874558755587655877558785587955880558815588255883558845588555886558875588855889558905589155892558935589455895558965589755898558995590055901559025590355904559055590655907559085590955910559115591255913559145591555916559175591855919559205592155922559235592455925559265592755928559295593055931559325593355934559355593655937559385593955940559415594255943559445594555946559475594855949559505595155952559535595455955559565595755958559595596055961559625596355964559655596655967559685596955970559715597255973559745597555976559775597855979559805598155982559835598455985559865598755988559895599055991559925599355994559955599655997559985599956000560015600256003560045600556006560075600856009560105601156012560135601456015560165601756018560195602056021560225602356024560255602656027560285602956030560315603256033560345603556036560375603856039560405604156042560435604456045560465604756048560495605056051560525605356054560555605656057560585605956060560615606256063560645606556066560675606856069560705607156072560735607456075560765607756078560795608056081560825608356084560855608656087560885608956090560915609256093560945609556096560975609856099561005610156102561035610456105561065610756108561095611056111561125611356114561155611656117561185611956120561215612256123561245612556126561275612856129561305613156132561335613456135561365613756138561395614056141561425614356144561455614656147561485614956150561515615256153561545615556156561575615856159561605616156162561635616456165561665616756168561695617056171561725617356174561755617656177561785617956180561815618256183561845618556186561875618856189561905619156192561935619456195561965619756198561995620056201562025620356204562055620656207562085620956210562115621256213562145621556216562175621856219562205622156222562235622456225562265622756228562295623056231562325623356234562355623656237562385623956240562415624256243562445624556246562475624856249562505625156252562535625456255562565625756258562595626056261562625626356264562655626656267562685626956270562715627256273562745627556276562775627856279562805628156282562835628456285562865628756288562895629056291562925629356294562955629656297562985629956300563015630256303563045630556306563075630856309563105631156312563135631456315563165631756318563195632056321563225632356324563255632656327563285632956330563315633256333563345633556336563375633856339563405634156342563435634456345563465634756348563495635056351563525635356354563555635656357563585635956360563615636256363563645636556366563675636856369563705637156372563735637456375563765637756378563795638056381563825638356384563855638656387563885638956390563915639256393563945639556396563975639856399564005640156402564035640456405564065640756408564095641056411564125641356414564155641656417564185641956420564215642256423564245642556426564275642856429564305643156432564335643456435564365643756438564395644056441564425644356444564455644656447564485644956450564515645256453564545645556456564575645856459564605646156462564635646456465564665646756468564695647056471564725647356474564755647656477564785647956480564815648256483564845648556486564875648856489564905649156492564935649456495564965649756498564995650056501565025650356504565055650656507565085650956510565115651256513565145651556516565175651856519565205652156522565235652456525565265652756528565295653056531565325653356534565355653656537565385653956540565415654256543565445654556546565475654856549565505655156552565535655456555565565655756558565595656056561565625656356564565655656656567565685656956570565715657256573565745657556576565775657856579565805658156582565835658456585565865658756588565895659056591565925659356594565955659656597565985659956600566015660256603566045660556606566075660856609566105661156612566135661456615566165661756618566195662056621566225662356624566255662656627566285662956630566315663256633566345663556636566375663856639566405664156642566435664456645566465664756648566495665056651566525665356654566555665656657566585665956660566615666256663566645666556666566675666856669566705667156672566735667456675566765667756678566795668056681566825668356684566855668656687566885668956690566915669256693566945669556696566975669856699567005670156702567035670456705567065670756708567095671056711567125671356714567155671656717567185671956720567215672256723567245672556726567275672856729567305673156732567335673456735567365673756738567395674056741567425674356744567455674656747567485674956750567515675256753567545675556756567575675856759567605676156762567635676456765567665676756768567695677056771567725677356774567755677656777567785677956780567815678256783567845678556786567875678856789567905679156792567935679456795567965679756798567995680056801568025680356804568055680656807568085680956810568115681256813568145681556816568175681856819568205682156822568235682456825568265682756828568295683056831568325683356834568355683656837568385683956840568415684256843568445684556846568475684856849568505685156852568535685456855568565685756858568595686056861568625686356864568655686656867568685686956870568715687256873568745687556876568775687856879568805688156882568835688456885568865688756888568895689056891568925689356894568955689656897568985689956900569015690256903569045690556906569075690856909569105691156912569135691456915569165691756918569195692056921569225692356924569255692656927569285692956930569315693256933569345693556936569375693856939569405694156942569435694456945569465694756948569495695056951569525695356954569555695656957569585695956960569615696256963569645696556966569675696856969569705697156972569735697456975569765697756978569795698056981569825698356984569855698656987569885698956990569915699256993569945699556996569975699856999570005700157002570035700457005570065700757008570095701057011570125701357014570155701657017570185701957020570215702257023570245702557026570275702857029570305703157032570335703457035570365703757038570395704057041570425704357044570455704657047570485704957050570515705257053570545705557056570575705857059570605706157062570635706457065570665706757068570695707057071570725707357074570755707657077570785707957080570815708257083570845708557086570875708857089570905709157092570935709457095570965709757098570995710057101571025710357104571055710657107571085710957110571115711257113571145711557116571175711857119571205712157122571235712457125571265712757128571295713057131571325713357134571355713657137571385713957140571415714257143571445714557146571475714857149571505715157152
  1. import { c as createCommonjsModule, j as commonjsGlobal, u as unwrapExports, s as styleInject, i as _slicedToArray, a as _inherits$c, b as _createClass, d as _classCallCheck$h, e as _possibleConstructorReturn$c, f as _getPrototypeOf, _ as _defineProperty$1, k as _assertThisInitialized } from '../style-inject.es-610f1f83.js';
  2. import React, { useState, useMemo } from 'react';
  3. import reactDom from 'react-dom';
  4. import server from 'react-dom/server';
  5. /*
  6. object-assign
  7. (c) Sindre Sorhus
  8. @license MIT
  9. */
  10. /* eslint-disable no-unused-vars */
  11. var getOwnPropertySymbols = Object.getOwnPropertySymbols;
  12. var hasOwnProperty = Object.prototype.hasOwnProperty;
  13. var propIsEnumerable = Object.prototype.propertyIsEnumerable;
  14. function toObject(val) {
  15. if (val === null || val === undefined) {
  16. throw new TypeError('Object.assign cannot be called with null or undefined');
  17. }
  18. return Object(val);
  19. }
  20. function shouldUseNative() {
  21. try {
  22. if (!Object.assign) {
  23. return false;
  24. }
  25. // Detect buggy property enumeration order in older V8 versions.
  26. // https://bugs.chromium.org/p/v8/issues/detail?id=4118
  27. var test1 = new String('abc'); // eslint-disable-line no-new-wrappers
  28. test1[5] = 'de';
  29. if (Object.getOwnPropertyNames(test1)[0] === '5') {
  30. return false;
  31. }
  32. // https://bugs.chromium.org/p/v8/issues/detail?id=3056
  33. var test2 = {};
  34. for (var i = 0; i < 10; i++) {
  35. test2['_' + String.fromCharCode(i)] = i;
  36. }
  37. var order2 = Object.getOwnPropertyNames(test2).map(function (n) {
  38. return test2[n];
  39. });
  40. if (order2.join('') !== '0123456789') {
  41. return false;
  42. }
  43. // https://bugs.chromium.org/p/v8/issues/detail?id=3056
  44. var test3 = {};
  45. 'abcdefghijklmnopqrst'.split('').forEach(function (letter) {
  46. test3[letter] = letter;
  47. });
  48. if (Object.keys(Object.assign({}, test3)).join('') !==
  49. 'abcdefghijklmnopqrst') {
  50. return false;
  51. }
  52. return true;
  53. } catch (err) {
  54. // We don't expect any of the above to throw, but better to be safe.
  55. return false;
  56. }
  57. }
  58. var objectAssign = shouldUseNative() ? Object.assign : function (target, source) {
  59. var from;
  60. var to = toObject(target);
  61. var symbols;
  62. for (var s = 1; s < arguments.length; s++) {
  63. from = Object(arguments[s]);
  64. for (var key in from) {
  65. if (hasOwnProperty.call(from, key)) {
  66. to[key] = from[key];
  67. }
  68. }
  69. if (getOwnPropertySymbols) {
  70. symbols = getOwnPropertySymbols(from);
  71. for (var i = 0; i < symbols.length; i++) {
  72. if (propIsEnumerable.call(from, symbols[i])) {
  73. to[symbols[i]] = from[symbols[i]];
  74. }
  75. }
  76. }
  77. }
  78. return to;
  79. };
  80. var immutable = createCommonjsModule(function (module, exports) {
  81. /**
  82. * Copyright (c) 2014-2015, Facebook, Inc.
  83. * All rights reserved.
  84. *
  85. * This source code is licensed under the BSD-style license found in the
  86. * LICENSE file in the root directory of this source tree. An additional grant
  87. * of patent rights can be found in the PATENTS file in the same directory.
  88. */
  89. (function (global, factory) {
  90. module.exports = factory() ;
  91. }(commonjsGlobal, function () {var SLICE$0 = Array.prototype.slice;
  92. function createClass(ctor, superClass) {
  93. if (superClass) {
  94. ctor.prototype = Object.create(superClass.prototype);
  95. }
  96. ctor.prototype.constructor = ctor;
  97. }
  98. function Iterable(value) {
  99. return isIterable(value) ? value : Seq(value);
  100. }
  101. createClass(KeyedIterable, Iterable);
  102. function KeyedIterable(value) {
  103. return isKeyed(value) ? value : KeyedSeq(value);
  104. }
  105. createClass(IndexedIterable, Iterable);
  106. function IndexedIterable(value) {
  107. return isIndexed(value) ? value : IndexedSeq(value);
  108. }
  109. createClass(SetIterable, Iterable);
  110. function SetIterable(value) {
  111. return isIterable(value) && !isAssociative(value) ? value : SetSeq(value);
  112. }
  113. function isIterable(maybeIterable) {
  114. return !!(maybeIterable && maybeIterable[IS_ITERABLE_SENTINEL]);
  115. }
  116. function isKeyed(maybeKeyed) {
  117. return !!(maybeKeyed && maybeKeyed[IS_KEYED_SENTINEL]);
  118. }
  119. function isIndexed(maybeIndexed) {
  120. return !!(maybeIndexed && maybeIndexed[IS_INDEXED_SENTINEL]);
  121. }
  122. function isAssociative(maybeAssociative) {
  123. return isKeyed(maybeAssociative) || isIndexed(maybeAssociative);
  124. }
  125. function isOrdered(maybeOrdered) {
  126. return !!(maybeOrdered && maybeOrdered[IS_ORDERED_SENTINEL]);
  127. }
  128. Iterable.isIterable = isIterable;
  129. Iterable.isKeyed = isKeyed;
  130. Iterable.isIndexed = isIndexed;
  131. Iterable.isAssociative = isAssociative;
  132. Iterable.isOrdered = isOrdered;
  133. Iterable.Keyed = KeyedIterable;
  134. Iterable.Indexed = IndexedIterable;
  135. Iterable.Set = SetIterable;
  136. var IS_ITERABLE_SENTINEL = '@@__IMMUTABLE_ITERABLE__@@';
  137. var IS_KEYED_SENTINEL = '@@__IMMUTABLE_KEYED__@@';
  138. var IS_INDEXED_SENTINEL = '@@__IMMUTABLE_INDEXED__@@';
  139. var IS_ORDERED_SENTINEL = '@@__IMMUTABLE_ORDERED__@@';
  140. // Used for setting prototype methods that IE8 chokes on.
  141. var DELETE = 'delete';
  142. // Constants describing the size of trie nodes.
  143. var SHIFT = 5; // Resulted in best performance after ______?
  144. var SIZE = 1 << SHIFT;
  145. var MASK = SIZE - 1;
  146. // A consistent shared value representing "not set" which equals nothing other
  147. // than itself, and nothing that could be provided externally.
  148. var NOT_SET = {};
  149. // Boolean references, Rough equivalent of `bool &`.
  150. var CHANGE_LENGTH = { value: false };
  151. var DID_ALTER = { value: false };
  152. function MakeRef(ref) {
  153. ref.value = false;
  154. return ref;
  155. }
  156. function SetRef(ref) {
  157. ref && (ref.value = true);
  158. }
  159. // A function which returns a value representing an "owner" for transient writes
  160. // to tries. The return value will only ever equal itself, and will not equal
  161. // the return of any subsequent call of this function.
  162. function OwnerID() {}
  163. // http://jsperf.com/copy-array-inline
  164. function arrCopy(arr, offset) {
  165. offset = offset || 0;
  166. var len = Math.max(0, arr.length - offset);
  167. var newArr = new Array(len);
  168. for (var ii = 0; ii < len; ii++) {
  169. newArr[ii] = arr[ii + offset];
  170. }
  171. return newArr;
  172. }
  173. function ensureSize(iter) {
  174. if (iter.size === undefined) {
  175. iter.size = iter.__iterate(returnTrue);
  176. }
  177. return iter.size;
  178. }
  179. function wrapIndex(iter, index) {
  180. // This implements "is array index" which the ECMAString spec defines as:
  181. //
  182. // A String property name P is an array index if and only if
  183. // ToString(ToUint32(P)) is equal to P and ToUint32(P) is not equal
  184. // to 2^32−1.
  185. //
  186. // http://www.ecma-international.org/ecma-262/6.0/#sec-array-exotic-objects
  187. if (typeof index !== 'number') {
  188. var uint32Index = index >>> 0; // N >>> 0 is shorthand for ToUint32
  189. if ('' + uint32Index !== index || uint32Index === 4294967295) {
  190. return NaN;
  191. }
  192. index = uint32Index;
  193. }
  194. return index < 0 ? ensureSize(iter) + index : index;
  195. }
  196. function returnTrue() {
  197. return true;
  198. }
  199. function wholeSlice(begin, end, size) {
  200. return (begin === 0 || (size !== undefined && begin <= -size)) &&
  201. (end === undefined || (size !== undefined && end >= size));
  202. }
  203. function resolveBegin(begin, size) {
  204. return resolveIndex(begin, size, 0);
  205. }
  206. function resolveEnd(end, size) {
  207. return resolveIndex(end, size, size);
  208. }
  209. function resolveIndex(index, size, defaultIndex) {
  210. return index === undefined ?
  211. defaultIndex :
  212. index < 0 ?
  213. Math.max(0, size + index) :
  214. size === undefined ?
  215. index :
  216. Math.min(size, index);
  217. }
  218. /* global Symbol */
  219. var ITERATE_KEYS = 0;
  220. var ITERATE_VALUES = 1;
  221. var ITERATE_ENTRIES = 2;
  222. var REAL_ITERATOR_SYMBOL = typeof Symbol === 'function' && Symbol.iterator;
  223. var FAUX_ITERATOR_SYMBOL = '@@iterator';
  224. var ITERATOR_SYMBOL = REAL_ITERATOR_SYMBOL || FAUX_ITERATOR_SYMBOL;
  225. function Iterator(next) {
  226. this.next = next;
  227. }
  228. Iterator.prototype.toString = function() {
  229. return '[Iterator]';
  230. };
  231. Iterator.KEYS = ITERATE_KEYS;
  232. Iterator.VALUES = ITERATE_VALUES;
  233. Iterator.ENTRIES = ITERATE_ENTRIES;
  234. Iterator.prototype.inspect =
  235. Iterator.prototype.toSource = function () { return this.toString(); };
  236. Iterator.prototype[ITERATOR_SYMBOL] = function () {
  237. return this;
  238. };
  239. function iteratorValue(type, k, v, iteratorResult) {
  240. var value = type === 0 ? k : type === 1 ? v : [k, v];
  241. iteratorResult ? (iteratorResult.value = value) : (iteratorResult = {
  242. value: value, done: false
  243. });
  244. return iteratorResult;
  245. }
  246. function iteratorDone() {
  247. return { value: undefined, done: true };
  248. }
  249. function hasIterator(maybeIterable) {
  250. return !!getIteratorFn(maybeIterable);
  251. }
  252. function isIterator(maybeIterator) {
  253. return maybeIterator && typeof maybeIterator.next === 'function';
  254. }
  255. function getIterator(iterable) {
  256. var iteratorFn = getIteratorFn(iterable);
  257. return iteratorFn && iteratorFn.call(iterable);
  258. }
  259. function getIteratorFn(iterable) {
  260. var iteratorFn = iterable && (
  261. (REAL_ITERATOR_SYMBOL && iterable[REAL_ITERATOR_SYMBOL]) ||
  262. iterable[FAUX_ITERATOR_SYMBOL]
  263. );
  264. if (typeof iteratorFn === 'function') {
  265. return iteratorFn;
  266. }
  267. }
  268. function isArrayLike(value) {
  269. return value && typeof value.length === 'number';
  270. }
  271. createClass(Seq, Iterable);
  272. function Seq(value) {
  273. return value === null || value === undefined ? emptySequence() :
  274. isIterable(value) ? value.toSeq() : seqFromValue(value);
  275. }
  276. Seq.of = function(/*...values*/) {
  277. return Seq(arguments);
  278. };
  279. Seq.prototype.toSeq = function() {
  280. return this;
  281. };
  282. Seq.prototype.toString = function() {
  283. return this.__toString('Seq {', '}');
  284. };
  285. Seq.prototype.cacheResult = function() {
  286. if (!this._cache && this.__iterateUncached) {
  287. this._cache = this.entrySeq().toArray();
  288. this.size = this._cache.length;
  289. }
  290. return this;
  291. };
  292. // abstract __iterateUncached(fn, reverse)
  293. Seq.prototype.__iterate = function(fn, reverse) {
  294. return seqIterate(this, fn, reverse, true);
  295. };
  296. // abstract __iteratorUncached(type, reverse)
  297. Seq.prototype.__iterator = function(type, reverse) {
  298. return seqIterator(this, type, reverse, true);
  299. };
  300. createClass(KeyedSeq, Seq);
  301. function KeyedSeq(value) {
  302. return value === null || value === undefined ?
  303. emptySequence().toKeyedSeq() :
  304. isIterable(value) ?
  305. (isKeyed(value) ? value.toSeq() : value.fromEntrySeq()) :
  306. keyedSeqFromValue(value);
  307. }
  308. KeyedSeq.prototype.toKeyedSeq = function() {
  309. return this;
  310. };
  311. createClass(IndexedSeq, Seq);
  312. function IndexedSeq(value) {
  313. return value === null || value === undefined ? emptySequence() :
  314. !isIterable(value) ? indexedSeqFromValue(value) :
  315. isKeyed(value) ? value.entrySeq() : value.toIndexedSeq();
  316. }
  317. IndexedSeq.of = function(/*...values*/) {
  318. return IndexedSeq(arguments);
  319. };
  320. IndexedSeq.prototype.toIndexedSeq = function() {
  321. return this;
  322. };
  323. IndexedSeq.prototype.toString = function() {
  324. return this.__toString('Seq [', ']');
  325. };
  326. IndexedSeq.prototype.__iterate = function(fn, reverse) {
  327. return seqIterate(this, fn, reverse, false);
  328. };
  329. IndexedSeq.prototype.__iterator = function(type, reverse) {
  330. return seqIterator(this, type, reverse, false);
  331. };
  332. createClass(SetSeq, Seq);
  333. function SetSeq(value) {
  334. return (
  335. value === null || value === undefined ? emptySequence() :
  336. !isIterable(value) ? indexedSeqFromValue(value) :
  337. isKeyed(value) ? value.entrySeq() : value
  338. ).toSetSeq();
  339. }
  340. SetSeq.of = function(/*...values*/) {
  341. return SetSeq(arguments);
  342. };
  343. SetSeq.prototype.toSetSeq = function() {
  344. return this;
  345. };
  346. Seq.isSeq = isSeq;
  347. Seq.Keyed = KeyedSeq;
  348. Seq.Set = SetSeq;
  349. Seq.Indexed = IndexedSeq;
  350. var IS_SEQ_SENTINEL = '@@__IMMUTABLE_SEQ__@@';
  351. Seq.prototype[IS_SEQ_SENTINEL] = true;
  352. createClass(ArraySeq, IndexedSeq);
  353. function ArraySeq(array) {
  354. this._array = array;
  355. this.size = array.length;
  356. }
  357. ArraySeq.prototype.get = function(index, notSetValue) {
  358. return this.has(index) ? this._array[wrapIndex(this, index)] : notSetValue;
  359. };
  360. ArraySeq.prototype.__iterate = function(fn, reverse) {
  361. var array = this._array;
  362. var maxIndex = array.length - 1;
  363. for (var ii = 0; ii <= maxIndex; ii++) {
  364. if (fn(array[reverse ? maxIndex - ii : ii], ii, this) === false) {
  365. return ii + 1;
  366. }
  367. }
  368. return ii;
  369. };
  370. ArraySeq.prototype.__iterator = function(type, reverse) {
  371. var array = this._array;
  372. var maxIndex = array.length - 1;
  373. var ii = 0;
  374. return new Iterator(function()
  375. {return ii > maxIndex ?
  376. iteratorDone() :
  377. iteratorValue(type, ii, array[reverse ? maxIndex - ii++ : ii++])}
  378. );
  379. };
  380. createClass(ObjectSeq, KeyedSeq);
  381. function ObjectSeq(object) {
  382. var keys = Object.keys(object);
  383. this._object = object;
  384. this._keys = keys;
  385. this.size = keys.length;
  386. }
  387. ObjectSeq.prototype.get = function(key, notSetValue) {
  388. if (notSetValue !== undefined && !this.has(key)) {
  389. return notSetValue;
  390. }
  391. return this._object[key];
  392. };
  393. ObjectSeq.prototype.has = function(key) {
  394. return this._object.hasOwnProperty(key);
  395. };
  396. ObjectSeq.prototype.__iterate = function(fn, reverse) {
  397. var object = this._object;
  398. var keys = this._keys;
  399. var maxIndex = keys.length - 1;
  400. for (var ii = 0; ii <= maxIndex; ii++) {
  401. var key = keys[reverse ? maxIndex - ii : ii];
  402. if (fn(object[key], key, this) === false) {
  403. return ii + 1;
  404. }
  405. }
  406. return ii;
  407. };
  408. ObjectSeq.prototype.__iterator = function(type, reverse) {
  409. var object = this._object;
  410. var keys = this._keys;
  411. var maxIndex = keys.length - 1;
  412. var ii = 0;
  413. return new Iterator(function() {
  414. var key = keys[reverse ? maxIndex - ii : ii];
  415. return ii++ > maxIndex ?
  416. iteratorDone() :
  417. iteratorValue(type, key, object[key]);
  418. });
  419. };
  420. ObjectSeq.prototype[IS_ORDERED_SENTINEL] = true;
  421. createClass(IterableSeq, IndexedSeq);
  422. function IterableSeq(iterable) {
  423. this._iterable = iterable;
  424. this.size = iterable.length || iterable.size;
  425. }
  426. IterableSeq.prototype.__iterateUncached = function(fn, reverse) {
  427. if (reverse) {
  428. return this.cacheResult().__iterate(fn, reverse);
  429. }
  430. var iterable = this._iterable;
  431. var iterator = getIterator(iterable);
  432. var iterations = 0;
  433. if (isIterator(iterator)) {
  434. var step;
  435. while (!(step = iterator.next()).done) {
  436. if (fn(step.value, iterations++, this) === false) {
  437. break;
  438. }
  439. }
  440. }
  441. return iterations;
  442. };
  443. IterableSeq.prototype.__iteratorUncached = function(type, reverse) {
  444. if (reverse) {
  445. return this.cacheResult().__iterator(type, reverse);
  446. }
  447. var iterable = this._iterable;
  448. var iterator = getIterator(iterable);
  449. if (!isIterator(iterator)) {
  450. return new Iterator(iteratorDone);
  451. }
  452. var iterations = 0;
  453. return new Iterator(function() {
  454. var step = iterator.next();
  455. return step.done ? step : iteratorValue(type, iterations++, step.value);
  456. });
  457. };
  458. createClass(IteratorSeq, IndexedSeq);
  459. function IteratorSeq(iterator) {
  460. this._iterator = iterator;
  461. this._iteratorCache = [];
  462. }
  463. IteratorSeq.prototype.__iterateUncached = function(fn, reverse) {
  464. if (reverse) {
  465. return this.cacheResult().__iterate(fn, reverse);
  466. }
  467. var iterator = this._iterator;
  468. var cache = this._iteratorCache;
  469. var iterations = 0;
  470. while (iterations < cache.length) {
  471. if (fn(cache[iterations], iterations++, this) === false) {
  472. return iterations;
  473. }
  474. }
  475. var step;
  476. while (!(step = iterator.next()).done) {
  477. var val = step.value;
  478. cache[iterations] = val;
  479. if (fn(val, iterations++, this) === false) {
  480. break;
  481. }
  482. }
  483. return iterations;
  484. };
  485. IteratorSeq.prototype.__iteratorUncached = function(type, reverse) {
  486. if (reverse) {
  487. return this.cacheResult().__iterator(type, reverse);
  488. }
  489. var iterator = this._iterator;
  490. var cache = this._iteratorCache;
  491. var iterations = 0;
  492. return new Iterator(function() {
  493. if (iterations >= cache.length) {
  494. var step = iterator.next();
  495. if (step.done) {
  496. return step;
  497. }
  498. cache[iterations] = step.value;
  499. }
  500. return iteratorValue(type, iterations, cache[iterations++]);
  501. });
  502. };
  503. // # pragma Helper functions
  504. function isSeq(maybeSeq) {
  505. return !!(maybeSeq && maybeSeq[IS_SEQ_SENTINEL]);
  506. }
  507. var EMPTY_SEQ;
  508. function emptySequence() {
  509. return EMPTY_SEQ || (EMPTY_SEQ = new ArraySeq([]));
  510. }
  511. function keyedSeqFromValue(value) {
  512. var seq =
  513. Array.isArray(value) ? new ArraySeq(value).fromEntrySeq() :
  514. isIterator(value) ? new IteratorSeq(value).fromEntrySeq() :
  515. hasIterator(value) ? new IterableSeq(value).fromEntrySeq() :
  516. typeof value === 'object' ? new ObjectSeq(value) :
  517. undefined;
  518. if (!seq) {
  519. throw new TypeError(
  520. 'Expected Array or iterable object of [k, v] entries, '+
  521. 'or keyed object: ' + value
  522. );
  523. }
  524. return seq;
  525. }
  526. function indexedSeqFromValue(value) {
  527. var seq = maybeIndexedSeqFromValue(value);
  528. if (!seq) {
  529. throw new TypeError(
  530. 'Expected Array or iterable object of values: ' + value
  531. );
  532. }
  533. return seq;
  534. }
  535. function seqFromValue(value) {
  536. var seq = maybeIndexedSeqFromValue(value) ||
  537. (typeof value === 'object' && new ObjectSeq(value));
  538. if (!seq) {
  539. throw new TypeError(
  540. 'Expected Array or iterable object of values, or keyed object: ' + value
  541. );
  542. }
  543. return seq;
  544. }
  545. function maybeIndexedSeqFromValue(value) {
  546. return (
  547. isArrayLike(value) ? new ArraySeq(value) :
  548. isIterator(value) ? new IteratorSeq(value) :
  549. hasIterator(value) ? new IterableSeq(value) :
  550. undefined
  551. );
  552. }
  553. function seqIterate(seq, fn, reverse, useKeys) {
  554. var cache = seq._cache;
  555. if (cache) {
  556. var maxIndex = cache.length - 1;
  557. for (var ii = 0; ii <= maxIndex; ii++) {
  558. var entry = cache[reverse ? maxIndex - ii : ii];
  559. if (fn(entry[1], useKeys ? entry[0] : ii, seq) === false) {
  560. return ii + 1;
  561. }
  562. }
  563. return ii;
  564. }
  565. return seq.__iterateUncached(fn, reverse);
  566. }
  567. function seqIterator(seq, type, reverse, useKeys) {
  568. var cache = seq._cache;
  569. if (cache) {
  570. var maxIndex = cache.length - 1;
  571. var ii = 0;
  572. return new Iterator(function() {
  573. var entry = cache[reverse ? maxIndex - ii : ii];
  574. return ii++ > maxIndex ?
  575. iteratorDone() :
  576. iteratorValue(type, useKeys ? entry[0] : ii - 1, entry[1]);
  577. });
  578. }
  579. return seq.__iteratorUncached(type, reverse);
  580. }
  581. function fromJS(json, converter) {
  582. return converter ?
  583. fromJSWith(converter, json, '', {'': json}) :
  584. fromJSDefault(json);
  585. }
  586. function fromJSWith(converter, json, key, parentJSON) {
  587. if (Array.isArray(json)) {
  588. return converter.call(parentJSON, key, IndexedSeq(json).map(function(v, k) {return fromJSWith(converter, v, k, json)}));
  589. }
  590. if (isPlainObj(json)) {
  591. return converter.call(parentJSON, key, KeyedSeq(json).map(function(v, k) {return fromJSWith(converter, v, k, json)}));
  592. }
  593. return json;
  594. }
  595. function fromJSDefault(json) {
  596. if (Array.isArray(json)) {
  597. return IndexedSeq(json).map(fromJSDefault).toList();
  598. }
  599. if (isPlainObj(json)) {
  600. return KeyedSeq(json).map(fromJSDefault).toMap();
  601. }
  602. return json;
  603. }
  604. function isPlainObj(value) {
  605. return value && (value.constructor === Object || value.constructor === undefined);
  606. }
  607. /**
  608. * An extension of the "same-value" algorithm as [described for use by ES6 Map
  609. * and Set](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map#Key_equality)
  610. *
  611. * NaN is considered the same as NaN, however -0 and 0 are considered the same
  612. * value, which is different from the algorithm described by
  613. * [`Object.is`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/is).
  614. *
  615. * This is extended further to allow Objects to describe the values they
  616. * represent, by way of `valueOf` or `equals` (and `hashCode`).
  617. *
  618. * Note: because of this extension, the key equality of Immutable.Map and the
  619. * value equality of Immutable.Set will differ from ES6 Map and Set.
  620. *
  621. * ### Defining custom values
  622. *
  623. * The easiest way to describe the value an object represents is by implementing
  624. * `valueOf`. For example, `Date` represents a value by returning a unix
  625. * timestamp for `valueOf`:
  626. *
  627. * var date1 = new Date(1234567890000); // Fri Feb 13 2009 ...
  628. * var date2 = new Date(1234567890000);
  629. * date1.valueOf(); // 1234567890000
  630. * assert( date1 !== date2 );
  631. * assert( Immutable.is( date1, date2 ) );
  632. *
  633. * Note: overriding `valueOf` may have other implications if you use this object
  634. * where JavaScript expects a primitive, such as implicit string coercion.
  635. *
  636. * For more complex types, especially collections, implementing `valueOf` may
  637. * not be performant. An alternative is to implement `equals` and `hashCode`.
  638. *
  639. * `equals` takes another object, presumably of similar type, and returns true
  640. * if the it is equal. Equality is symmetrical, so the same result should be
  641. * returned if this and the argument are flipped.
  642. *
  643. * assert( a.equals(b) === b.equals(a) );
  644. *
  645. * `hashCode` returns a 32bit integer number representing the object which will
  646. * be used to determine how to store the value object in a Map or Set. You must
  647. * provide both or neither methods, one must not exist without the other.
  648. *
  649. * Also, an important relationship between these methods must be upheld: if two
  650. * values are equal, they *must* return the same hashCode. If the values are not
  651. * equal, they might have the same hashCode; this is called a hash collision,
  652. * and while undesirable for performance reasons, it is acceptable.
  653. *
  654. * if (a.equals(b)) {
  655. * assert( a.hashCode() === b.hashCode() );
  656. * }
  657. *
  658. * All Immutable collections implement `equals` and `hashCode`.
  659. *
  660. */
  661. function is(valueA, valueB) {
  662. if (valueA === valueB || (valueA !== valueA && valueB !== valueB)) {
  663. return true;
  664. }
  665. if (!valueA || !valueB) {
  666. return false;
  667. }
  668. if (typeof valueA.valueOf === 'function' &&
  669. typeof valueB.valueOf === 'function') {
  670. valueA = valueA.valueOf();
  671. valueB = valueB.valueOf();
  672. if (valueA === valueB || (valueA !== valueA && valueB !== valueB)) {
  673. return true;
  674. }
  675. if (!valueA || !valueB) {
  676. return false;
  677. }
  678. }
  679. if (typeof valueA.equals === 'function' &&
  680. typeof valueB.equals === 'function' &&
  681. valueA.equals(valueB)) {
  682. return true;
  683. }
  684. return false;
  685. }
  686. function deepEqual(a, b) {
  687. if (a === b) {
  688. return true;
  689. }
  690. if (
  691. !isIterable(b) ||
  692. a.size !== undefined && b.size !== undefined && a.size !== b.size ||
  693. a.__hash !== undefined && b.__hash !== undefined && a.__hash !== b.__hash ||
  694. isKeyed(a) !== isKeyed(b) ||
  695. isIndexed(a) !== isIndexed(b) ||
  696. isOrdered(a) !== isOrdered(b)
  697. ) {
  698. return false;
  699. }
  700. if (a.size === 0 && b.size === 0) {
  701. return true;
  702. }
  703. var notAssociative = !isAssociative(a);
  704. if (isOrdered(a)) {
  705. var entries = a.entries();
  706. return b.every(function(v, k) {
  707. var entry = entries.next().value;
  708. return entry && is(entry[1], v) && (notAssociative || is(entry[0], k));
  709. }) && entries.next().done;
  710. }
  711. var flipped = false;
  712. if (a.size === undefined) {
  713. if (b.size === undefined) {
  714. if (typeof a.cacheResult === 'function') {
  715. a.cacheResult();
  716. }
  717. } else {
  718. flipped = true;
  719. var _ = a;
  720. a = b;
  721. b = _;
  722. }
  723. }
  724. var allEqual = true;
  725. var bSize = b.__iterate(function(v, k) {
  726. if (notAssociative ? !a.has(v) :
  727. flipped ? !is(v, a.get(k, NOT_SET)) : !is(a.get(k, NOT_SET), v)) {
  728. allEqual = false;
  729. return false;
  730. }
  731. });
  732. return allEqual && a.size === bSize;
  733. }
  734. createClass(Repeat, IndexedSeq);
  735. function Repeat(value, times) {
  736. if (!(this instanceof Repeat)) {
  737. return new Repeat(value, times);
  738. }
  739. this._value = value;
  740. this.size = times === undefined ? Infinity : Math.max(0, times);
  741. if (this.size === 0) {
  742. if (EMPTY_REPEAT) {
  743. return EMPTY_REPEAT;
  744. }
  745. EMPTY_REPEAT = this;
  746. }
  747. }
  748. Repeat.prototype.toString = function() {
  749. if (this.size === 0) {
  750. return 'Repeat []';
  751. }
  752. return 'Repeat [ ' + this._value + ' ' + this.size + ' times ]';
  753. };
  754. Repeat.prototype.get = function(index, notSetValue) {
  755. return this.has(index) ? this._value : notSetValue;
  756. };
  757. Repeat.prototype.includes = function(searchValue) {
  758. return is(this._value, searchValue);
  759. };
  760. Repeat.prototype.slice = function(begin, end) {
  761. var size = this.size;
  762. return wholeSlice(begin, end, size) ? this :
  763. new Repeat(this._value, resolveEnd(end, size) - resolveBegin(begin, size));
  764. };
  765. Repeat.prototype.reverse = function() {
  766. return this;
  767. };
  768. Repeat.prototype.indexOf = function(searchValue) {
  769. if (is(this._value, searchValue)) {
  770. return 0;
  771. }
  772. return -1;
  773. };
  774. Repeat.prototype.lastIndexOf = function(searchValue) {
  775. if (is(this._value, searchValue)) {
  776. return this.size;
  777. }
  778. return -1;
  779. };
  780. Repeat.prototype.__iterate = function(fn, reverse) {
  781. for (var ii = 0; ii < this.size; ii++) {
  782. if (fn(this._value, ii, this) === false) {
  783. return ii + 1;
  784. }
  785. }
  786. return ii;
  787. };
  788. Repeat.prototype.__iterator = function(type, reverse) {var this$0 = this;
  789. var ii = 0;
  790. return new Iterator(function()
  791. {return ii < this$0.size ? iteratorValue(type, ii++, this$0._value) : iteratorDone()}
  792. );
  793. };
  794. Repeat.prototype.equals = function(other) {
  795. return other instanceof Repeat ?
  796. is(this._value, other._value) :
  797. deepEqual(other);
  798. };
  799. var EMPTY_REPEAT;
  800. function invariant(condition, error) {
  801. if (!condition) throw new Error(error);
  802. }
  803. createClass(Range, IndexedSeq);
  804. function Range(start, end, step) {
  805. if (!(this instanceof Range)) {
  806. return new Range(start, end, step);
  807. }
  808. invariant(step !== 0, 'Cannot step a Range by 0');
  809. start = start || 0;
  810. if (end === undefined) {
  811. end = Infinity;
  812. }
  813. step = step === undefined ? 1 : Math.abs(step);
  814. if (end < start) {
  815. step = -step;
  816. }
  817. this._start = start;
  818. this._end = end;
  819. this._step = step;
  820. this.size = Math.max(0, Math.ceil((end - start) / step - 1) + 1);
  821. if (this.size === 0) {
  822. if (EMPTY_RANGE) {
  823. return EMPTY_RANGE;
  824. }
  825. EMPTY_RANGE = this;
  826. }
  827. }
  828. Range.prototype.toString = function() {
  829. if (this.size === 0) {
  830. return 'Range []';
  831. }
  832. return 'Range [ ' +
  833. this._start + '...' + this._end +
  834. (this._step > 1 ? ' by ' + this._step : '') +
  835. ' ]';
  836. };
  837. Range.prototype.get = function(index, notSetValue) {
  838. return this.has(index) ?
  839. this._start + wrapIndex(this, index) * this._step :
  840. notSetValue;
  841. };
  842. Range.prototype.includes = function(searchValue) {
  843. var possibleIndex = (searchValue - this._start) / this._step;
  844. return possibleIndex >= 0 &&
  845. possibleIndex < this.size &&
  846. possibleIndex === Math.floor(possibleIndex);
  847. };
  848. Range.prototype.slice = function(begin, end) {
  849. if (wholeSlice(begin, end, this.size)) {
  850. return this;
  851. }
  852. begin = resolveBegin(begin, this.size);
  853. end = resolveEnd(end, this.size);
  854. if (end <= begin) {
  855. return new Range(0, 0);
  856. }
  857. return new Range(this.get(begin, this._end), this.get(end, this._end), this._step);
  858. };
  859. Range.prototype.indexOf = function(searchValue) {
  860. var offsetValue = searchValue - this._start;
  861. if (offsetValue % this._step === 0) {
  862. var index = offsetValue / this._step;
  863. if (index >= 0 && index < this.size) {
  864. return index
  865. }
  866. }
  867. return -1;
  868. };
  869. Range.prototype.lastIndexOf = function(searchValue) {
  870. return this.indexOf(searchValue);
  871. };
  872. Range.prototype.__iterate = function(fn, reverse) {
  873. var maxIndex = this.size - 1;
  874. var step = this._step;
  875. var value = reverse ? this._start + maxIndex * step : this._start;
  876. for (var ii = 0; ii <= maxIndex; ii++) {
  877. if (fn(value, ii, this) === false) {
  878. return ii + 1;
  879. }
  880. value += reverse ? -step : step;
  881. }
  882. return ii;
  883. };
  884. Range.prototype.__iterator = function(type, reverse) {
  885. var maxIndex = this.size - 1;
  886. var step = this._step;
  887. var value = reverse ? this._start + maxIndex * step : this._start;
  888. var ii = 0;
  889. return new Iterator(function() {
  890. var v = value;
  891. value += reverse ? -step : step;
  892. return ii > maxIndex ? iteratorDone() : iteratorValue(type, ii++, v);
  893. });
  894. };
  895. Range.prototype.equals = function(other) {
  896. return other instanceof Range ?
  897. this._start === other._start &&
  898. this._end === other._end &&
  899. this._step === other._step :
  900. deepEqual(this, other);
  901. };
  902. var EMPTY_RANGE;
  903. createClass(Collection, Iterable);
  904. function Collection() {
  905. throw TypeError('Abstract');
  906. }
  907. createClass(KeyedCollection, Collection);function KeyedCollection() {}
  908. createClass(IndexedCollection, Collection);function IndexedCollection() {}
  909. createClass(SetCollection, Collection);function SetCollection() {}
  910. Collection.Keyed = KeyedCollection;
  911. Collection.Indexed = IndexedCollection;
  912. Collection.Set = SetCollection;
  913. var imul =
  914. typeof Math.imul === 'function' && Math.imul(0xffffffff, 2) === -2 ?
  915. Math.imul :
  916. function imul(a, b) {
  917. a = a | 0; // int
  918. b = b | 0; // int
  919. var c = a & 0xffff;
  920. var d = b & 0xffff;
  921. // Shift by 0 fixes the sign on the high part.
  922. return (c * d) + ((((a >>> 16) * d + c * (b >>> 16)) << 16) >>> 0) | 0; // int
  923. };
  924. // v8 has an optimization for storing 31-bit signed numbers.
  925. // Values which have either 00 or 11 as the high order bits qualify.
  926. // This function drops the highest order bit in a signed number, maintaining
  927. // the sign bit.
  928. function smi(i32) {
  929. return ((i32 >>> 1) & 0x40000000) | (i32 & 0xBFFFFFFF);
  930. }
  931. function hash(o) {
  932. if (o === false || o === null || o === undefined) {
  933. return 0;
  934. }
  935. if (typeof o.valueOf === 'function') {
  936. o = o.valueOf();
  937. if (o === false || o === null || o === undefined) {
  938. return 0;
  939. }
  940. }
  941. if (o === true) {
  942. return 1;
  943. }
  944. var type = typeof o;
  945. if (type === 'number') {
  946. var h = o | 0;
  947. if (h !== o) {
  948. h ^= o * 0xFFFFFFFF;
  949. }
  950. while (o > 0xFFFFFFFF) {
  951. o /= 0xFFFFFFFF;
  952. h ^= o;
  953. }
  954. return smi(h);
  955. }
  956. if (type === 'string') {
  957. return o.length > STRING_HASH_CACHE_MIN_STRLEN ? cachedHashString(o) : hashString(o);
  958. }
  959. if (typeof o.hashCode === 'function') {
  960. return o.hashCode();
  961. }
  962. if (type === 'object') {
  963. return hashJSObj(o);
  964. }
  965. if (typeof o.toString === 'function') {
  966. return hashString(o.toString());
  967. }
  968. throw new Error('Value type ' + type + ' cannot be hashed.');
  969. }
  970. function cachedHashString(string) {
  971. var hash = stringHashCache[string];
  972. if (hash === undefined) {
  973. hash = hashString(string);
  974. if (STRING_HASH_CACHE_SIZE === STRING_HASH_CACHE_MAX_SIZE) {
  975. STRING_HASH_CACHE_SIZE = 0;
  976. stringHashCache = {};
  977. }
  978. STRING_HASH_CACHE_SIZE++;
  979. stringHashCache[string] = hash;
  980. }
  981. return hash;
  982. }
  983. // http://jsperf.com/hashing-strings
  984. function hashString(string) {
  985. // This is the hash from JVM
  986. // The hash code for a string is computed as
  987. // s[0] * 31 ^ (n - 1) + s[1] * 31 ^ (n - 2) + ... + s[n - 1],
  988. // where s[i] is the ith character of the string and n is the length of
  989. // the string. We "mod" the result to make it between 0 (inclusive) and 2^31
  990. // (exclusive) by dropping high bits.
  991. var hash = 0;
  992. for (var ii = 0; ii < string.length; ii++) {
  993. hash = 31 * hash + string.charCodeAt(ii) | 0;
  994. }
  995. return smi(hash);
  996. }
  997. function hashJSObj(obj) {
  998. var hash;
  999. if (usingWeakMap) {
  1000. hash = weakMap.get(obj);
  1001. if (hash !== undefined) {
  1002. return hash;
  1003. }
  1004. }
  1005. hash = obj[UID_HASH_KEY];
  1006. if (hash !== undefined) {
  1007. return hash;
  1008. }
  1009. if (!canDefineProperty) {
  1010. hash = obj.propertyIsEnumerable && obj.propertyIsEnumerable[UID_HASH_KEY];
  1011. if (hash !== undefined) {
  1012. return hash;
  1013. }
  1014. hash = getIENodeHash(obj);
  1015. if (hash !== undefined) {
  1016. return hash;
  1017. }
  1018. }
  1019. hash = ++objHashUID;
  1020. if (objHashUID & 0x40000000) {
  1021. objHashUID = 0;
  1022. }
  1023. if (usingWeakMap) {
  1024. weakMap.set(obj, hash);
  1025. } else if (isExtensible !== undefined && isExtensible(obj) === false) {
  1026. throw new Error('Non-extensible objects are not allowed as keys.');
  1027. } else if (canDefineProperty) {
  1028. Object.defineProperty(obj, UID_HASH_KEY, {
  1029. 'enumerable': false,
  1030. 'configurable': false,
  1031. 'writable': false,
  1032. 'value': hash
  1033. });
  1034. } else if (obj.propertyIsEnumerable !== undefined &&
  1035. obj.propertyIsEnumerable === obj.constructor.prototype.propertyIsEnumerable) {
  1036. // Since we can't define a non-enumerable property on the object
  1037. // we'll hijack one of the less-used non-enumerable properties to
  1038. // save our hash on it. Since this is a function it will not show up in
  1039. // `JSON.stringify` which is what we want.
  1040. obj.propertyIsEnumerable = function() {
  1041. return this.constructor.prototype.propertyIsEnumerable.apply(this, arguments);
  1042. };
  1043. obj.propertyIsEnumerable[UID_HASH_KEY] = hash;
  1044. } else if (obj.nodeType !== undefined) {
  1045. // At this point we couldn't get the IE `uniqueID` to use as a hash
  1046. // and we couldn't use a non-enumerable property to exploit the
  1047. // dontEnum bug so we simply add the `UID_HASH_KEY` on the node
  1048. // itself.
  1049. obj[UID_HASH_KEY] = hash;
  1050. } else {
  1051. throw new Error('Unable to set a non-enumerable property on object.');
  1052. }
  1053. return hash;
  1054. }
  1055. // Get references to ES5 object methods.
  1056. var isExtensible = Object.isExtensible;
  1057. // True if Object.defineProperty works as expected. IE8 fails this test.
  1058. var canDefineProperty = (function() {
  1059. try {
  1060. Object.defineProperty({}, '@', {});
  1061. return true;
  1062. } catch (e) {
  1063. return false;
  1064. }
  1065. }());
  1066. // IE has a `uniqueID` property on DOM nodes. We can construct the hash from it
  1067. // and avoid memory leaks from the IE cloneNode bug.
  1068. function getIENodeHash(node) {
  1069. if (node && node.nodeType > 0) {
  1070. switch (node.nodeType) {
  1071. case 1: // Element
  1072. return node.uniqueID;
  1073. case 9: // Document
  1074. return node.documentElement && node.documentElement.uniqueID;
  1075. }
  1076. }
  1077. }
  1078. // If possible, use a WeakMap.
  1079. var usingWeakMap = typeof WeakMap === 'function';
  1080. var weakMap;
  1081. if (usingWeakMap) {
  1082. weakMap = new WeakMap();
  1083. }
  1084. var objHashUID = 0;
  1085. var UID_HASH_KEY = '__immutablehash__';
  1086. if (typeof Symbol === 'function') {
  1087. UID_HASH_KEY = Symbol(UID_HASH_KEY);
  1088. }
  1089. var STRING_HASH_CACHE_MIN_STRLEN = 16;
  1090. var STRING_HASH_CACHE_MAX_SIZE = 255;
  1091. var STRING_HASH_CACHE_SIZE = 0;
  1092. var stringHashCache = {};
  1093. function assertNotInfinite(size) {
  1094. invariant(
  1095. size !== Infinity,
  1096. 'Cannot perform this action with an infinite size.'
  1097. );
  1098. }
  1099. createClass(Map, KeyedCollection);
  1100. // @pragma Construction
  1101. function Map(value) {
  1102. return value === null || value === undefined ? emptyMap() :
  1103. isMap(value) && !isOrdered(value) ? value :
  1104. emptyMap().withMutations(function(map ) {
  1105. var iter = KeyedIterable(value);
  1106. assertNotInfinite(iter.size);
  1107. iter.forEach(function(v, k) {return map.set(k, v)});
  1108. });
  1109. }
  1110. Map.prototype.toString = function() {
  1111. return this.__toString('Map {', '}');
  1112. };
  1113. // @pragma Access
  1114. Map.prototype.get = function(k, notSetValue) {
  1115. return this._root ?
  1116. this._root.get(0, undefined, k, notSetValue) :
  1117. notSetValue;
  1118. };
  1119. // @pragma Modification
  1120. Map.prototype.set = function(k, v) {
  1121. return updateMap(this, k, v);
  1122. };
  1123. Map.prototype.setIn = function(keyPath, v) {
  1124. return this.updateIn(keyPath, NOT_SET, function() {return v});
  1125. };
  1126. Map.prototype.remove = function(k) {
  1127. return updateMap(this, k, NOT_SET);
  1128. };
  1129. Map.prototype.deleteIn = function(keyPath) {
  1130. return this.updateIn(keyPath, function() {return NOT_SET});
  1131. };
  1132. Map.prototype.update = function(k, notSetValue, updater) {
  1133. return arguments.length === 1 ?
  1134. k(this) :
  1135. this.updateIn([k], notSetValue, updater);
  1136. };
  1137. Map.prototype.updateIn = function(keyPath, notSetValue, updater) {
  1138. if (!updater) {
  1139. updater = notSetValue;
  1140. notSetValue = undefined;
  1141. }
  1142. var updatedValue = updateInDeepMap(
  1143. this,
  1144. forceIterator(keyPath),
  1145. notSetValue,
  1146. updater
  1147. );
  1148. return updatedValue === NOT_SET ? undefined : updatedValue;
  1149. };
  1150. Map.prototype.clear = function() {
  1151. if (this.size === 0) {
  1152. return this;
  1153. }
  1154. if (this.__ownerID) {
  1155. this.size = 0;
  1156. this._root = null;
  1157. this.__hash = undefined;
  1158. this.__altered = true;
  1159. return this;
  1160. }
  1161. return emptyMap();
  1162. };
  1163. // @pragma Composition
  1164. Map.prototype.merge = function(/*...iters*/) {
  1165. return mergeIntoMapWith(this, undefined, arguments);
  1166. };
  1167. Map.prototype.mergeWith = function(merger) {var iters = SLICE$0.call(arguments, 1);
  1168. return mergeIntoMapWith(this, merger, iters);
  1169. };
  1170. Map.prototype.mergeIn = function(keyPath) {var iters = SLICE$0.call(arguments, 1);
  1171. return this.updateIn(
  1172. keyPath,
  1173. emptyMap(),
  1174. function(m ) {return typeof m.merge === 'function' ?
  1175. m.merge.apply(m, iters) :
  1176. iters[iters.length - 1]}
  1177. );
  1178. };
  1179. Map.prototype.mergeDeep = function(/*...iters*/) {
  1180. return mergeIntoMapWith(this, deepMerger, arguments);
  1181. };
  1182. Map.prototype.mergeDeepWith = function(merger) {var iters = SLICE$0.call(arguments, 1);
  1183. return mergeIntoMapWith(this, deepMergerWith(merger), iters);
  1184. };
  1185. Map.prototype.mergeDeepIn = function(keyPath) {var iters = SLICE$0.call(arguments, 1);
  1186. return this.updateIn(
  1187. keyPath,
  1188. emptyMap(),
  1189. function(m ) {return typeof m.mergeDeep === 'function' ?
  1190. m.mergeDeep.apply(m, iters) :
  1191. iters[iters.length - 1]}
  1192. );
  1193. };
  1194. Map.prototype.sort = function(comparator) {
  1195. // Late binding
  1196. return OrderedMap(sortFactory(this, comparator));
  1197. };
  1198. Map.prototype.sortBy = function(mapper, comparator) {
  1199. // Late binding
  1200. return OrderedMap(sortFactory(this, comparator, mapper));
  1201. };
  1202. // @pragma Mutability
  1203. Map.prototype.withMutations = function(fn) {
  1204. var mutable = this.asMutable();
  1205. fn(mutable);
  1206. return mutable.wasAltered() ? mutable.__ensureOwner(this.__ownerID) : this;
  1207. };
  1208. Map.prototype.asMutable = function() {
  1209. return this.__ownerID ? this : this.__ensureOwner(new OwnerID());
  1210. };
  1211. Map.prototype.asImmutable = function() {
  1212. return this.__ensureOwner();
  1213. };
  1214. Map.prototype.wasAltered = function() {
  1215. return this.__altered;
  1216. };
  1217. Map.prototype.__iterator = function(type, reverse) {
  1218. return new MapIterator(this, type, reverse);
  1219. };
  1220. Map.prototype.__iterate = function(fn, reverse) {var this$0 = this;
  1221. var iterations = 0;
  1222. this._root && this._root.iterate(function(entry ) {
  1223. iterations++;
  1224. return fn(entry[1], entry[0], this$0);
  1225. }, reverse);
  1226. return iterations;
  1227. };
  1228. Map.prototype.__ensureOwner = function(ownerID) {
  1229. if (ownerID === this.__ownerID) {
  1230. return this;
  1231. }
  1232. if (!ownerID) {
  1233. this.__ownerID = ownerID;
  1234. this.__altered = false;
  1235. return this;
  1236. }
  1237. return makeMap(this.size, this._root, ownerID, this.__hash);
  1238. };
  1239. function isMap(maybeMap) {
  1240. return !!(maybeMap && maybeMap[IS_MAP_SENTINEL]);
  1241. }
  1242. Map.isMap = isMap;
  1243. var IS_MAP_SENTINEL = '@@__IMMUTABLE_MAP__@@';
  1244. var MapPrototype = Map.prototype;
  1245. MapPrototype[IS_MAP_SENTINEL] = true;
  1246. MapPrototype[DELETE] = MapPrototype.remove;
  1247. MapPrototype.removeIn = MapPrototype.deleteIn;
  1248. // #pragma Trie Nodes
  1249. function ArrayMapNode(ownerID, entries) {
  1250. this.ownerID = ownerID;
  1251. this.entries = entries;
  1252. }
  1253. ArrayMapNode.prototype.get = function(shift, keyHash, key, notSetValue) {
  1254. var entries = this.entries;
  1255. for (var ii = 0, len = entries.length; ii < len; ii++) {
  1256. if (is(key, entries[ii][0])) {
  1257. return entries[ii][1];
  1258. }
  1259. }
  1260. return notSetValue;
  1261. };
  1262. ArrayMapNode.prototype.update = function(ownerID, shift, keyHash, key, value, didChangeSize, didAlter) {
  1263. var removed = value === NOT_SET;
  1264. var entries = this.entries;
  1265. var idx = 0;
  1266. for (var len = entries.length; idx < len; idx++) {
  1267. if (is(key, entries[idx][0])) {
  1268. break;
  1269. }
  1270. }
  1271. var exists = idx < len;
  1272. if (exists ? entries[idx][1] === value : removed) {
  1273. return this;
  1274. }
  1275. SetRef(didAlter);
  1276. (removed || !exists) && SetRef(didChangeSize);
  1277. if (removed && entries.length === 1) {
  1278. return; // undefined
  1279. }
  1280. if (!exists && !removed && entries.length >= MAX_ARRAY_MAP_SIZE) {
  1281. return createNodes(ownerID, entries, key, value);
  1282. }
  1283. var isEditable = ownerID && ownerID === this.ownerID;
  1284. var newEntries = isEditable ? entries : arrCopy(entries);
  1285. if (exists) {
  1286. if (removed) {
  1287. idx === len - 1 ? newEntries.pop() : (newEntries[idx] = newEntries.pop());
  1288. } else {
  1289. newEntries[idx] = [key, value];
  1290. }
  1291. } else {
  1292. newEntries.push([key, value]);
  1293. }
  1294. if (isEditable) {
  1295. this.entries = newEntries;
  1296. return this;
  1297. }
  1298. return new ArrayMapNode(ownerID, newEntries);
  1299. };
  1300. function BitmapIndexedNode(ownerID, bitmap, nodes) {
  1301. this.ownerID = ownerID;
  1302. this.bitmap = bitmap;
  1303. this.nodes = nodes;
  1304. }
  1305. BitmapIndexedNode.prototype.get = function(shift, keyHash, key, notSetValue) {
  1306. if (keyHash === undefined) {
  1307. keyHash = hash(key);
  1308. }
  1309. var bit = (1 << ((shift === 0 ? keyHash : keyHash >>> shift) & MASK));
  1310. var bitmap = this.bitmap;
  1311. return (bitmap & bit) === 0 ? notSetValue :
  1312. this.nodes[popCount(bitmap & (bit - 1))].get(shift + SHIFT, keyHash, key, notSetValue);
  1313. };
  1314. BitmapIndexedNode.prototype.update = function(ownerID, shift, keyHash, key, value, didChangeSize, didAlter) {
  1315. if (keyHash === undefined) {
  1316. keyHash = hash(key);
  1317. }
  1318. var keyHashFrag = (shift === 0 ? keyHash : keyHash >>> shift) & MASK;
  1319. var bit = 1 << keyHashFrag;
  1320. var bitmap = this.bitmap;
  1321. var exists = (bitmap & bit) !== 0;
  1322. if (!exists && value === NOT_SET) {
  1323. return this;
  1324. }
  1325. var idx = popCount(bitmap & (bit - 1));
  1326. var nodes = this.nodes;
  1327. var node = exists ? nodes[idx] : undefined;
  1328. var newNode = updateNode(node, ownerID, shift + SHIFT, keyHash, key, value, didChangeSize, didAlter);
  1329. if (newNode === node) {
  1330. return this;
  1331. }
  1332. if (!exists && newNode && nodes.length >= MAX_BITMAP_INDEXED_SIZE) {
  1333. return expandNodes(ownerID, nodes, bitmap, keyHashFrag, newNode);
  1334. }
  1335. if (exists && !newNode && nodes.length === 2 && isLeafNode(nodes[idx ^ 1])) {
  1336. return nodes[idx ^ 1];
  1337. }
  1338. if (exists && newNode && nodes.length === 1 && isLeafNode(newNode)) {
  1339. return newNode;
  1340. }
  1341. var isEditable = ownerID && ownerID === this.ownerID;
  1342. var newBitmap = exists ? newNode ? bitmap : bitmap ^ bit : bitmap | bit;
  1343. var newNodes = exists ? newNode ?
  1344. setIn(nodes, idx, newNode, isEditable) :
  1345. spliceOut(nodes, idx, isEditable) :
  1346. spliceIn(nodes, idx, newNode, isEditable);
  1347. if (isEditable) {
  1348. this.bitmap = newBitmap;
  1349. this.nodes = newNodes;
  1350. return this;
  1351. }
  1352. return new BitmapIndexedNode(ownerID, newBitmap, newNodes);
  1353. };
  1354. function HashArrayMapNode(ownerID, count, nodes) {
  1355. this.ownerID = ownerID;
  1356. this.count = count;
  1357. this.nodes = nodes;
  1358. }
  1359. HashArrayMapNode.prototype.get = function(shift, keyHash, key, notSetValue) {
  1360. if (keyHash === undefined) {
  1361. keyHash = hash(key);
  1362. }
  1363. var idx = (shift === 0 ? keyHash : keyHash >>> shift) & MASK;
  1364. var node = this.nodes[idx];
  1365. return node ? node.get(shift + SHIFT, keyHash, key, notSetValue) : notSetValue;
  1366. };
  1367. HashArrayMapNode.prototype.update = function(ownerID, shift, keyHash, key, value, didChangeSize, didAlter) {
  1368. if (keyHash === undefined) {
  1369. keyHash = hash(key);
  1370. }
  1371. var idx = (shift === 0 ? keyHash : keyHash >>> shift) & MASK;
  1372. var removed = value === NOT_SET;
  1373. var nodes = this.nodes;
  1374. var node = nodes[idx];
  1375. if (removed && !node) {
  1376. return this;
  1377. }
  1378. var newNode = updateNode(node, ownerID, shift + SHIFT, keyHash, key, value, didChangeSize, didAlter);
  1379. if (newNode === node) {
  1380. return this;
  1381. }
  1382. var newCount = this.count;
  1383. if (!node) {
  1384. newCount++;
  1385. } else if (!newNode) {
  1386. newCount--;
  1387. if (newCount < MIN_HASH_ARRAY_MAP_SIZE) {
  1388. return packNodes(ownerID, nodes, newCount, idx);
  1389. }
  1390. }
  1391. var isEditable = ownerID && ownerID === this.ownerID;
  1392. var newNodes = setIn(nodes, idx, newNode, isEditable);
  1393. if (isEditable) {
  1394. this.count = newCount;
  1395. this.nodes = newNodes;
  1396. return this;
  1397. }
  1398. return new HashArrayMapNode(ownerID, newCount, newNodes);
  1399. };
  1400. function HashCollisionNode(ownerID, keyHash, entries) {
  1401. this.ownerID = ownerID;
  1402. this.keyHash = keyHash;
  1403. this.entries = entries;
  1404. }
  1405. HashCollisionNode.prototype.get = function(shift, keyHash, key, notSetValue) {
  1406. var entries = this.entries;
  1407. for (var ii = 0, len = entries.length; ii < len; ii++) {
  1408. if (is(key, entries[ii][0])) {
  1409. return entries[ii][1];
  1410. }
  1411. }
  1412. return notSetValue;
  1413. };
  1414. HashCollisionNode.prototype.update = function(ownerID, shift, keyHash, key, value, didChangeSize, didAlter) {
  1415. if (keyHash === undefined) {
  1416. keyHash = hash(key);
  1417. }
  1418. var removed = value === NOT_SET;
  1419. if (keyHash !== this.keyHash) {
  1420. if (removed) {
  1421. return this;
  1422. }
  1423. SetRef(didAlter);
  1424. SetRef(didChangeSize);
  1425. return mergeIntoNode(this, ownerID, shift, keyHash, [key, value]);
  1426. }
  1427. var entries = this.entries;
  1428. var idx = 0;
  1429. for (var len = entries.length; idx < len; idx++) {
  1430. if (is(key, entries[idx][0])) {
  1431. break;
  1432. }
  1433. }
  1434. var exists = idx < len;
  1435. if (exists ? entries[idx][1] === value : removed) {
  1436. return this;
  1437. }
  1438. SetRef(didAlter);
  1439. (removed || !exists) && SetRef(didChangeSize);
  1440. if (removed && len === 2) {
  1441. return new ValueNode(ownerID, this.keyHash, entries[idx ^ 1]);
  1442. }
  1443. var isEditable = ownerID && ownerID === this.ownerID;
  1444. var newEntries = isEditable ? entries : arrCopy(entries);
  1445. if (exists) {
  1446. if (removed) {
  1447. idx === len - 1 ? newEntries.pop() : (newEntries[idx] = newEntries.pop());
  1448. } else {
  1449. newEntries[idx] = [key, value];
  1450. }
  1451. } else {
  1452. newEntries.push([key, value]);
  1453. }
  1454. if (isEditable) {
  1455. this.entries = newEntries;
  1456. return this;
  1457. }
  1458. return new HashCollisionNode(ownerID, this.keyHash, newEntries);
  1459. };
  1460. function ValueNode(ownerID, keyHash, entry) {
  1461. this.ownerID = ownerID;
  1462. this.keyHash = keyHash;
  1463. this.entry = entry;
  1464. }
  1465. ValueNode.prototype.get = function(shift, keyHash, key, notSetValue) {
  1466. return is(key, this.entry[0]) ? this.entry[1] : notSetValue;
  1467. };
  1468. ValueNode.prototype.update = function(ownerID, shift, keyHash, key, value, didChangeSize, didAlter) {
  1469. var removed = value === NOT_SET;
  1470. var keyMatch = is(key, this.entry[0]);
  1471. if (keyMatch ? value === this.entry[1] : removed) {
  1472. return this;
  1473. }
  1474. SetRef(didAlter);
  1475. if (removed) {
  1476. SetRef(didChangeSize);
  1477. return; // undefined
  1478. }
  1479. if (keyMatch) {
  1480. if (ownerID && ownerID === this.ownerID) {
  1481. this.entry[1] = value;
  1482. return this;
  1483. }
  1484. return new ValueNode(ownerID, this.keyHash, [key, value]);
  1485. }
  1486. SetRef(didChangeSize);
  1487. return mergeIntoNode(this, ownerID, shift, hash(key), [key, value]);
  1488. };
  1489. // #pragma Iterators
  1490. ArrayMapNode.prototype.iterate =
  1491. HashCollisionNode.prototype.iterate = function (fn, reverse) {
  1492. var entries = this.entries;
  1493. for (var ii = 0, maxIndex = entries.length - 1; ii <= maxIndex; ii++) {
  1494. if (fn(entries[reverse ? maxIndex - ii : ii]) === false) {
  1495. return false;
  1496. }
  1497. }
  1498. };
  1499. BitmapIndexedNode.prototype.iterate =
  1500. HashArrayMapNode.prototype.iterate = function (fn, reverse) {
  1501. var nodes = this.nodes;
  1502. for (var ii = 0, maxIndex = nodes.length - 1; ii <= maxIndex; ii++) {
  1503. var node = nodes[reverse ? maxIndex - ii : ii];
  1504. if (node && node.iterate(fn, reverse) === false) {
  1505. return false;
  1506. }
  1507. }
  1508. };
  1509. ValueNode.prototype.iterate = function (fn, reverse) {
  1510. return fn(this.entry);
  1511. };
  1512. createClass(MapIterator, Iterator);
  1513. function MapIterator(map, type, reverse) {
  1514. this._type = type;
  1515. this._reverse = reverse;
  1516. this._stack = map._root && mapIteratorFrame(map._root);
  1517. }
  1518. MapIterator.prototype.next = function() {
  1519. var type = this._type;
  1520. var stack = this._stack;
  1521. while (stack) {
  1522. var node = stack.node;
  1523. var index = stack.index++;
  1524. var maxIndex;
  1525. if (node.entry) {
  1526. if (index === 0) {
  1527. return mapIteratorValue(type, node.entry);
  1528. }
  1529. } else if (node.entries) {
  1530. maxIndex = node.entries.length - 1;
  1531. if (index <= maxIndex) {
  1532. return mapIteratorValue(type, node.entries[this._reverse ? maxIndex - index : index]);
  1533. }
  1534. } else {
  1535. maxIndex = node.nodes.length - 1;
  1536. if (index <= maxIndex) {
  1537. var subNode = node.nodes[this._reverse ? maxIndex - index : index];
  1538. if (subNode) {
  1539. if (subNode.entry) {
  1540. return mapIteratorValue(type, subNode.entry);
  1541. }
  1542. stack = this._stack = mapIteratorFrame(subNode, stack);
  1543. }
  1544. continue;
  1545. }
  1546. }
  1547. stack = this._stack = this._stack.__prev;
  1548. }
  1549. return iteratorDone();
  1550. };
  1551. function mapIteratorValue(type, entry) {
  1552. return iteratorValue(type, entry[0], entry[1]);
  1553. }
  1554. function mapIteratorFrame(node, prev) {
  1555. return {
  1556. node: node,
  1557. index: 0,
  1558. __prev: prev
  1559. };
  1560. }
  1561. function makeMap(size, root, ownerID, hash) {
  1562. var map = Object.create(MapPrototype);
  1563. map.size = size;
  1564. map._root = root;
  1565. map.__ownerID = ownerID;
  1566. map.__hash = hash;
  1567. map.__altered = false;
  1568. return map;
  1569. }
  1570. var EMPTY_MAP;
  1571. function emptyMap() {
  1572. return EMPTY_MAP || (EMPTY_MAP = makeMap(0));
  1573. }
  1574. function updateMap(map, k, v) {
  1575. var newRoot;
  1576. var newSize;
  1577. if (!map._root) {
  1578. if (v === NOT_SET) {
  1579. return map;
  1580. }
  1581. newSize = 1;
  1582. newRoot = new ArrayMapNode(map.__ownerID, [[k, v]]);
  1583. } else {
  1584. var didChangeSize = MakeRef(CHANGE_LENGTH);
  1585. var didAlter = MakeRef(DID_ALTER);
  1586. newRoot = updateNode(map._root, map.__ownerID, 0, undefined, k, v, didChangeSize, didAlter);
  1587. if (!didAlter.value) {
  1588. return map;
  1589. }
  1590. newSize = map.size + (didChangeSize.value ? v === NOT_SET ? -1 : 1 : 0);
  1591. }
  1592. if (map.__ownerID) {
  1593. map.size = newSize;
  1594. map._root = newRoot;
  1595. map.__hash = undefined;
  1596. map.__altered = true;
  1597. return map;
  1598. }
  1599. return newRoot ? makeMap(newSize, newRoot) : emptyMap();
  1600. }
  1601. function updateNode(node, ownerID, shift, keyHash, key, value, didChangeSize, didAlter) {
  1602. if (!node) {
  1603. if (value === NOT_SET) {
  1604. return node;
  1605. }
  1606. SetRef(didAlter);
  1607. SetRef(didChangeSize);
  1608. return new ValueNode(ownerID, keyHash, [key, value]);
  1609. }
  1610. return node.update(ownerID, shift, keyHash, key, value, didChangeSize, didAlter);
  1611. }
  1612. function isLeafNode(node) {
  1613. return node.constructor === ValueNode || node.constructor === HashCollisionNode;
  1614. }
  1615. function mergeIntoNode(node, ownerID, shift, keyHash, entry) {
  1616. if (node.keyHash === keyHash) {
  1617. return new HashCollisionNode(ownerID, keyHash, [node.entry, entry]);
  1618. }
  1619. var idx1 = (shift === 0 ? node.keyHash : node.keyHash >>> shift) & MASK;
  1620. var idx2 = (shift === 0 ? keyHash : keyHash >>> shift) & MASK;
  1621. var newNode;
  1622. var nodes = idx1 === idx2 ?
  1623. [mergeIntoNode(node, ownerID, shift + SHIFT, keyHash, entry)] :
  1624. ((newNode = new ValueNode(ownerID, keyHash, entry)), idx1 < idx2 ? [node, newNode] : [newNode, node]);
  1625. return new BitmapIndexedNode(ownerID, (1 << idx1) | (1 << idx2), nodes);
  1626. }
  1627. function createNodes(ownerID, entries, key, value) {
  1628. if (!ownerID) {
  1629. ownerID = new OwnerID();
  1630. }
  1631. var node = new ValueNode(ownerID, hash(key), [key, value]);
  1632. for (var ii = 0; ii < entries.length; ii++) {
  1633. var entry = entries[ii];
  1634. node = node.update(ownerID, 0, undefined, entry[0], entry[1]);
  1635. }
  1636. return node;
  1637. }
  1638. function packNodes(ownerID, nodes, count, excluding) {
  1639. var bitmap = 0;
  1640. var packedII = 0;
  1641. var packedNodes = new Array(count);
  1642. for (var ii = 0, bit = 1, len = nodes.length; ii < len; ii++, bit <<= 1) {
  1643. var node = nodes[ii];
  1644. if (node !== undefined && ii !== excluding) {
  1645. bitmap |= bit;
  1646. packedNodes[packedII++] = node;
  1647. }
  1648. }
  1649. return new BitmapIndexedNode(ownerID, bitmap, packedNodes);
  1650. }
  1651. function expandNodes(ownerID, nodes, bitmap, including, node) {
  1652. var count = 0;
  1653. var expandedNodes = new Array(SIZE);
  1654. for (var ii = 0; bitmap !== 0; ii++, bitmap >>>= 1) {
  1655. expandedNodes[ii] = bitmap & 1 ? nodes[count++] : undefined;
  1656. }
  1657. expandedNodes[including] = node;
  1658. return new HashArrayMapNode(ownerID, count + 1, expandedNodes);
  1659. }
  1660. function mergeIntoMapWith(map, merger, iterables) {
  1661. var iters = [];
  1662. for (var ii = 0; ii < iterables.length; ii++) {
  1663. var value = iterables[ii];
  1664. var iter = KeyedIterable(value);
  1665. if (!isIterable(value)) {
  1666. iter = iter.map(function(v ) {return fromJS(v)});
  1667. }
  1668. iters.push(iter);
  1669. }
  1670. return mergeIntoCollectionWith(map, merger, iters);
  1671. }
  1672. function deepMerger(existing, value, key) {
  1673. return existing && existing.mergeDeep && isIterable(value) ?
  1674. existing.mergeDeep(value) :
  1675. is(existing, value) ? existing : value;
  1676. }
  1677. function deepMergerWith(merger) {
  1678. return function(existing, value, key) {
  1679. if (existing && existing.mergeDeepWith && isIterable(value)) {
  1680. return existing.mergeDeepWith(merger, value);
  1681. }
  1682. var nextValue = merger(existing, value, key);
  1683. return is(existing, nextValue) ? existing : nextValue;
  1684. };
  1685. }
  1686. function mergeIntoCollectionWith(collection, merger, iters) {
  1687. iters = iters.filter(function(x ) {return x.size !== 0});
  1688. if (iters.length === 0) {
  1689. return collection;
  1690. }
  1691. if (collection.size === 0 && !collection.__ownerID && iters.length === 1) {
  1692. return collection.constructor(iters[0]);
  1693. }
  1694. return collection.withMutations(function(collection ) {
  1695. var mergeIntoMap = merger ?
  1696. function(value, key) {
  1697. collection.update(key, NOT_SET, function(existing )
  1698. {return existing === NOT_SET ? value : merger(existing, value, key)}
  1699. );
  1700. } :
  1701. function(value, key) {
  1702. collection.set(key, value);
  1703. };
  1704. for (var ii = 0; ii < iters.length; ii++) {
  1705. iters[ii].forEach(mergeIntoMap);
  1706. }
  1707. });
  1708. }
  1709. function updateInDeepMap(existing, keyPathIter, notSetValue, updater) {
  1710. var isNotSet = existing === NOT_SET;
  1711. var step = keyPathIter.next();
  1712. if (step.done) {
  1713. var existingValue = isNotSet ? notSetValue : existing;
  1714. var newValue = updater(existingValue);
  1715. return newValue === existingValue ? existing : newValue;
  1716. }
  1717. invariant(
  1718. isNotSet || (existing && existing.set),
  1719. 'invalid keyPath'
  1720. );
  1721. var key = step.value;
  1722. var nextExisting = isNotSet ? NOT_SET : existing.get(key, NOT_SET);
  1723. var nextUpdated = updateInDeepMap(
  1724. nextExisting,
  1725. keyPathIter,
  1726. notSetValue,
  1727. updater
  1728. );
  1729. return nextUpdated === nextExisting ? existing :
  1730. nextUpdated === NOT_SET ? existing.remove(key) :
  1731. (isNotSet ? emptyMap() : existing).set(key, nextUpdated);
  1732. }
  1733. function popCount(x) {
  1734. x = x - ((x >> 1) & 0x55555555);
  1735. x = (x & 0x33333333) + ((x >> 2) & 0x33333333);
  1736. x = (x + (x >> 4)) & 0x0f0f0f0f;
  1737. x = x + (x >> 8);
  1738. x = x + (x >> 16);
  1739. return x & 0x7f;
  1740. }
  1741. function setIn(array, idx, val, canEdit) {
  1742. var newArray = canEdit ? array : arrCopy(array);
  1743. newArray[idx] = val;
  1744. return newArray;
  1745. }
  1746. function spliceIn(array, idx, val, canEdit) {
  1747. var newLen = array.length + 1;
  1748. if (canEdit && idx + 1 === newLen) {
  1749. array[idx] = val;
  1750. return array;
  1751. }
  1752. var newArray = new Array(newLen);
  1753. var after = 0;
  1754. for (var ii = 0; ii < newLen; ii++) {
  1755. if (ii === idx) {
  1756. newArray[ii] = val;
  1757. after = -1;
  1758. } else {
  1759. newArray[ii] = array[ii + after];
  1760. }
  1761. }
  1762. return newArray;
  1763. }
  1764. function spliceOut(array, idx, canEdit) {
  1765. var newLen = array.length - 1;
  1766. if (canEdit && idx === newLen) {
  1767. array.pop();
  1768. return array;
  1769. }
  1770. var newArray = new Array(newLen);
  1771. var after = 0;
  1772. for (var ii = 0; ii < newLen; ii++) {
  1773. if (ii === idx) {
  1774. after = 1;
  1775. }
  1776. newArray[ii] = array[ii + after];
  1777. }
  1778. return newArray;
  1779. }
  1780. var MAX_ARRAY_MAP_SIZE = SIZE / 4;
  1781. var MAX_BITMAP_INDEXED_SIZE = SIZE / 2;
  1782. var MIN_HASH_ARRAY_MAP_SIZE = SIZE / 4;
  1783. createClass(List, IndexedCollection);
  1784. // @pragma Construction
  1785. function List(value) {
  1786. var empty = emptyList();
  1787. if (value === null || value === undefined) {
  1788. return empty;
  1789. }
  1790. if (isList(value)) {
  1791. return value;
  1792. }
  1793. var iter = IndexedIterable(value);
  1794. var size = iter.size;
  1795. if (size === 0) {
  1796. return empty;
  1797. }
  1798. assertNotInfinite(size);
  1799. if (size > 0 && size < SIZE) {
  1800. return makeList(0, size, SHIFT, null, new VNode(iter.toArray()));
  1801. }
  1802. return empty.withMutations(function(list ) {
  1803. list.setSize(size);
  1804. iter.forEach(function(v, i) {return list.set(i, v)});
  1805. });
  1806. }
  1807. List.of = function(/*...values*/) {
  1808. return this(arguments);
  1809. };
  1810. List.prototype.toString = function() {
  1811. return this.__toString('List [', ']');
  1812. };
  1813. // @pragma Access
  1814. List.prototype.get = function(index, notSetValue) {
  1815. index = wrapIndex(this, index);
  1816. if (index >= 0 && index < this.size) {
  1817. index += this._origin;
  1818. var node = listNodeFor(this, index);
  1819. return node && node.array[index & MASK];
  1820. }
  1821. return notSetValue;
  1822. };
  1823. // @pragma Modification
  1824. List.prototype.set = function(index, value) {
  1825. return updateList(this, index, value);
  1826. };
  1827. List.prototype.remove = function(index) {
  1828. return !this.has(index) ? this :
  1829. index === 0 ? this.shift() :
  1830. index === this.size - 1 ? this.pop() :
  1831. this.splice(index, 1);
  1832. };
  1833. List.prototype.insert = function(index, value) {
  1834. return this.splice(index, 0, value);
  1835. };
  1836. List.prototype.clear = function() {
  1837. if (this.size === 0) {
  1838. return this;
  1839. }
  1840. if (this.__ownerID) {
  1841. this.size = this._origin = this._capacity = 0;
  1842. this._level = SHIFT;
  1843. this._root = this._tail = null;
  1844. this.__hash = undefined;
  1845. this.__altered = true;
  1846. return this;
  1847. }
  1848. return emptyList();
  1849. };
  1850. List.prototype.push = function(/*...values*/) {
  1851. var values = arguments;
  1852. var oldSize = this.size;
  1853. return this.withMutations(function(list ) {
  1854. setListBounds(list, 0, oldSize + values.length);
  1855. for (var ii = 0; ii < values.length; ii++) {
  1856. list.set(oldSize + ii, values[ii]);
  1857. }
  1858. });
  1859. };
  1860. List.prototype.pop = function() {
  1861. return setListBounds(this, 0, -1);
  1862. };
  1863. List.prototype.unshift = function(/*...values*/) {
  1864. var values = arguments;
  1865. return this.withMutations(function(list ) {
  1866. setListBounds(list, -values.length);
  1867. for (var ii = 0; ii < values.length; ii++) {
  1868. list.set(ii, values[ii]);
  1869. }
  1870. });
  1871. };
  1872. List.prototype.shift = function() {
  1873. return setListBounds(this, 1);
  1874. };
  1875. // @pragma Composition
  1876. List.prototype.merge = function(/*...iters*/) {
  1877. return mergeIntoListWith(this, undefined, arguments);
  1878. };
  1879. List.prototype.mergeWith = function(merger) {var iters = SLICE$0.call(arguments, 1);
  1880. return mergeIntoListWith(this, merger, iters);
  1881. };
  1882. List.prototype.mergeDeep = function(/*...iters*/) {
  1883. return mergeIntoListWith(this, deepMerger, arguments);
  1884. };
  1885. List.prototype.mergeDeepWith = function(merger) {var iters = SLICE$0.call(arguments, 1);
  1886. return mergeIntoListWith(this, deepMergerWith(merger), iters);
  1887. };
  1888. List.prototype.setSize = function(size) {
  1889. return setListBounds(this, 0, size);
  1890. };
  1891. // @pragma Iteration
  1892. List.prototype.slice = function(begin, end) {
  1893. var size = this.size;
  1894. if (wholeSlice(begin, end, size)) {
  1895. return this;
  1896. }
  1897. return setListBounds(
  1898. this,
  1899. resolveBegin(begin, size),
  1900. resolveEnd(end, size)
  1901. );
  1902. };
  1903. List.prototype.__iterator = function(type, reverse) {
  1904. var index = 0;
  1905. var values = iterateList(this, reverse);
  1906. return new Iterator(function() {
  1907. var value = values();
  1908. return value === DONE ?
  1909. iteratorDone() :
  1910. iteratorValue(type, index++, value);
  1911. });
  1912. };
  1913. List.prototype.__iterate = function(fn, reverse) {
  1914. var index = 0;
  1915. var values = iterateList(this, reverse);
  1916. var value;
  1917. while ((value = values()) !== DONE) {
  1918. if (fn(value, index++, this) === false) {
  1919. break;
  1920. }
  1921. }
  1922. return index;
  1923. };
  1924. List.prototype.__ensureOwner = function(ownerID) {
  1925. if (ownerID === this.__ownerID) {
  1926. return this;
  1927. }
  1928. if (!ownerID) {
  1929. this.__ownerID = ownerID;
  1930. return this;
  1931. }
  1932. return makeList(this._origin, this._capacity, this._level, this._root, this._tail, ownerID, this.__hash);
  1933. };
  1934. function isList(maybeList) {
  1935. return !!(maybeList && maybeList[IS_LIST_SENTINEL]);
  1936. }
  1937. List.isList = isList;
  1938. var IS_LIST_SENTINEL = '@@__IMMUTABLE_LIST__@@';
  1939. var ListPrototype = List.prototype;
  1940. ListPrototype[IS_LIST_SENTINEL] = true;
  1941. ListPrototype[DELETE] = ListPrototype.remove;
  1942. ListPrototype.setIn = MapPrototype.setIn;
  1943. ListPrototype.deleteIn =
  1944. ListPrototype.removeIn = MapPrototype.removeIn;
  1945. ListPrototype.update = MapPrototype.update;
  1946. ListPrototype.updateIn = MapPrototype.updateIn;
  1947. ListPrototype.mergeIn = MapPrototype.mergeIn;
  1948. ListPrototype.mergeDeepIn = MapPrototype.mergeDeepIn;
  1949. ListPrototype.withMutations = MapPrototype.withMutations;
  1950. ListPrototype.asMutable = MapPrototype.asMutable;
  1951. ListPrototype.asImmutable = MapPrototype.asImmutable;
  1952. ListPrototype.wasAltered = MapPrototype.wasAltered;
  1953. function VNode(array, ownerID) {
  1954. this.array = array;
  1955. this.ownerID = ownerID;
  1956. }
  1957. // TODO: seems like these methods are very similar
  1958. VNode.prototype.removeBefore = function(ownerID, level, index) {
  1959. if (index === level ? 1 << level : this.array.length === 0) {
  1960. return this;
  1961. }
  1962. var originIndex = (index >>> level) & MASK;
  1963. if (originIndex >= this.array.length) {
  1964. return new VNode([], ownerID);
  1965. }
  1966. var removingFirst = originIndex === 0;
  1967. var newChild;
  1968. if (level > 0) {
  1969. var oldChild = this.array[originIndex];
  1970. newChild = oldChild && oldChild.removeBefore(ownerID, level - SHIFT, index);
  1971. if (newChild === oldChild && removingFirst) {
  1972. return this;
  1973. }
  1974. }
  1975. if (removingFirst && !newChild) {
  1976. return this;
  1977. }
  1978. var editable = editableVNode(this, ownerID);
  1979. if (!removingFirst) {
  1980. for (var ii = 0; ii < originIndex; ii++) {
  1981. editable.array[ii] = undefined;
  1982. }
  1983. }
  1984. if (newChild) {
  1985. editable.array[originIndex] = newChild;
  1986. }
  1987. return editable;
  1988. };
  1989. VNode.prototype.removeAfter = function(ownerID, level, index) {
  1990. if (index === (level ? 1 << level : 0) || this.array.length === 0) {
  1991. return this;
  1992. }
  1993. var sizeIndex = ((index - 1) >>> level) & MASK;
  1994. if (sizeIndex >= this.array.length) {
  1995. return this;
  1996. }
  1997. var newChild;
  1998. if (level > 0) {
  1999. var oldChild = this.array[sizeIndex];
  2000. newChild = oldChild && oldChild.removeAfter(ownerID, level - SHIFT, index);
  2001. if (newChild === oldChild && sizeIndex === this.array.length - 1) {
  2002. return this;
  2003. }
  2004. }
  2005. var editable = editableVNode(this, ownerID);
  2006. editable.array.splice(sizeIndex + 1);
  2007. if (newChild) {
  2008. editable.array[sizeIndex] = newChild;
  2009. }
  2010. return editable;
  2011. };
  2012. var DONE = {};
  2013. function iterateList(list, reverse) {
  2014. var left = list._origin;
  2015. var right = list._capacity;
  2016. var tailPos = getTailOffset(right);
  2017. var tail = list._tail;
  2018. return iterateNodeOrLeaf(list._root, list._level, 0);
  2019. function iterateNodeOrLeaf(node, level, offset) {
  2020. return level === 0 ?
  2021. iterateLeaf(node, offset) :
  2022. iterateNode(node, level, offset);
  2023. }
  2024. function iterateLeaf(node, offset) {
  2025. var array = offset === tailPos ? tail && tail.array : node && node.array;
  2026. var from = offset > left ? 0 : left - offset;
  2027. var to = right - offset;
  2028. if (to > SIZE) {
  2029. to = SIZE;
  2030. }
  2031. return function() {
  2032. if (from === to) {
  2033. return DONE;
  2034. }
  2035. var idx = reverse ? --to : from++;
  2036. return array && array[idx];
  2037. };
  2038. }
  2039. function iterateNode(node, level, offset) {
  2040. var values;
  2041. var array = node && node.array;
  2042. var from = offset > left ? 0 : (left - offset) >> level;
  2043. var to = ((right - offset) >> level) + 1;
  2044. if (to > SIZE) {
  2045. to = SIZE;
  2046. }
  2047. return function() {
  2048. do {
  2049. if (values) {
  2050. var value = values();
  2051. if (value !== DONE) {
  2052. return value;
  2053. }
  2054. values = null;
  2055. }
  2056. if (from === to) {
  2057. return DONE;
  2058. }
  2059. var idx = reverse ? --to : from++;
  2060. values = iterateNodeOrLeaf(
  2061. array && array[idx], level - SHIFT, offset + (idx << level)
  2062. );
  2063. } while (true);
  2064. };
  2065. }
  2066. }
  2067. function makeList(origin, capacity, level, root, tail, ownerID, hash) {
  2068. var list = Object.create(ListPrototype);
  2069. list.size = capacity - origin;
  2070. list._origin = origin;
  2071. list._capacity = capacity;
  2072. list._level = level;
  2073. list._root = root;
  2074. list._tail = tail;
  2075. list.__ownerID = ownerID;
  2076. list.__hash = hash;
  2077. list.__altered = false;
  2078. return list;
  2079. }
  2080. var EMPTY_LIST;
  2081. function emptyList() {
  2082. return EMPTY_LIST || (EMPTY_LIST = makeList(0, 0, SHIFT));
  2083. }
  2084. function updateList(list, index, value) {
  2085. index = wrapIndex(list, index);
  2086. if (index !== index) {
  2087. return list;
  2088. }
  2089. if (index >= list.size || index < 0) {
  2090. return list.withMutations(function(list ) {
  2091. index < 0 ?
  2092. setListBounds(list, index).set(0, value) :
  2093. setListBounds(list, 0, index + 1).set(index, value);
  2094. });
  2095. }
  2096. index += list._origin;
  2097. var newTail = list._tail;
  2098. var newRoot = list._root;
  2099. var didAlter = MakeRef(DID_ALTER);
  2100. if (index >= getTailOffset(list._capacity)) {
  2101. newTail = updateVNode(newTail, list.__ownerID, 0, index, value, didAlter);
  2102. } else {
  2103. newRoot = updateVNode(newRoot, list.__ownerID, list._level, index, value, didAlter);
  2104. }
  2105. if (!didAlter.value) {
  2106. return list;
  2107. }
  2108. if (list.__ownerID) {
  2109. list._root = newRoot;
  2110. list._tail = newTail;
  2111. list.__hash = undefined;
  2112. list.__altered = true;
  2113. return list;
  2114. }
  2115. return makeList(list._origin, list._capacity, list._level, newRoot, newTail);
  2116. }
  2117. function updateVNode(node, ownerID, level, index, value, didAlter) {
  2118. var idx = (index >>> level) & MASK;
  2119. var nodeHas = node && idx < node.array.length;
  2120. if (!nodeHas && value === undefined) {
  2121. return node;
  2122. }
  2123. var newNode;
  2124. if (level > 0) {
  2125. var lowerNode = node && node.array[idx];
  2126. var newLowerNode = updateVNode(lowerNode, ownerID, level - SHIFT, index, value, didAlter);
  2127. if (newLowerNode === lowerNode) {
  2128. return node;
  2129. }
  2130. newNode = editableVNode(node, ownerID);
  2131. newNode.array[idx] = newLowerNode;
  2132. return newNode;
  2133. }
  2134. if (nodeHas && node.array[idx] === value) {
  2135. return node;
  2136. }
  2137. SetRef(didAlter);
  2138. newNode = editableVNode(node, ownerID);
  2139. if (value === undefined && idx === newNode.array.length - 1) {
  2140. newNode.array.pop();
  2141. } else {
  2142. newNode.array[idx] = value;
  2143. }
  2144. return newNode;
  2145. }
  2146. function editableVNode(node, ownerID) {
  2147. if (ownerID && node && ownerID === node.ownerID) {
  2148. return node;
  2149. }
  2150. return new VNode(node ? node.array.slice() : [], ownerID);
  2151. }
  2152. function listNodeFor(list, rawIndex) {
  2153. if (rawIndex >= getTailOffset(list._capacity)) {
  2154. return list._tail;
  2155. }
  2156. if (rawIndex < 1 << (list._level + SHIFT)) {
  2157. var node = list._root;
  2158. var level = list._level;
  2159. while (node && level > 0) {
  2160. node = node.array[(rawIndex >>> level) & MASK];
  2161. level -= SHIFT;
  2162. }
  2163. return node;
  2164. }
  2165. }
  2166. function setListBounds(list, begin, end) {
  2167. // Sanitize begin & end using this shorthand for ToInt32(argument)
  2168. // http://www.ecma-international.org/ecma-262/6.0/#sec-toint32
  2169. if (begin !== undefined) {
  2170. begin = begin | 0;
  2171. }
  2172. if (end !== undefined) {
  2173. end = end | 0;
  2174. }
  2175. var owner = list.__ownerID || new OwnerID();
  2176. var oldOrigin = list._origin;
  2177. var oldCapacity = list._capacity;
  2178. var newOrigin = oldOrigin + begin;
  2179. var newCapacity = end === undefined ? oldCapacity : end < 0 ? oldCapacity + end : oldOrigin + end;
  2180. if (newOrigin === oldOrigin && newCapacity === oldCapacity) {
  2181. return list;
  2182. }
  2183. // If it's going to end after it starts, it's empty.
  2184. if (newOrigin >= newCapacity) {
  2185. return list.clear();
  2186. }
  2187. var newLevel = list._level;
  2188. var newRoot = list._root;
  2189. // New origin might need creating a higher root.
  2190. var offsetShift = 0;
  2191. while (newOrigin + offsetShift < 0) {
  2192. newRoot = new VNode(newRoot && newRoot.array.length ? [undefined, newRoot] : [], owner);
  2193. newLevel += SHIFT;
  2194. offsetShift += 1 << newLevel;
  2195. }
  2196. if (offsetShift) {
  2197. newOrigin += offsetShift;
  2198. oldOrigin += offsetShift;
  2199. newCapacity += offsetShift;
  2200. oldCapacity += offsetShift;
  2201. }
  2202. var oldTailOffset = getTailOffset(oldCapacity);
  2203. var newTailOffset = getTailOffset(newCapacity);
  2204. // New size might need creating a higher root.
  2205. while (newTailOffset >= 1 << (newLevel + SHIFT)) {
  2206. newRoot = new VNode(newRoot && newRoot.array.length ? [newRoot] : [], owner);
  2207. newLevel += SHIFT;
  2208. }
  2209. // Locate or create the new tail.
  2210. var oldTail = list._tail;
  2211. var newTail = newTailOffset < oldTailOffset ?
  2212. listNodeFor(list, newCapacity - 1) :
  2213. newTailOffset > oldTailOffset ? new VNode([], owner) : oldTail;
  2214. // Merge Tail into tree.
  2215. if (oldTail && newTailOffset > oldTailOffset && newOrigin < oldCapacity && oldTail.array.length) {
  2216. newRoot = editableVNode(newRoot, owner);
  2217. var node = newRoot;
  2218. for (var level = newLevel; level > SHIFT; level -= SHIFT) {
  2219. var idx = (oldTailOffset >>> level) & MASK;
  2220. node = node.array[idx] = editableVNode(node.array[idx], owner);
  2221. }
  2222. node.array[(oldTailOffset >>> SHIFT) & MASK] = oldTail;
  2223. }
  2224. // If the size has been reduced, there's a chance the tail needs to be trimmed.
  2225. if (newCapacity < oldCapacity) {
  2226. newTail = newTail && newTail.removeAfter(owner, 0, newCapacity);
  2227. }
  2228. // If the new origin is within the tail, then we do not need a root.
  2229. if (newOrigin >= newTailOffset) {
  2230. newOrigin -= newTailOffset;
  2231. newCapacity -= newTailOffset;
  2232. newLevel = SHIFT;
  2233. newRoot = null;
  2234. newTail = newTail && newTail.removeBefore(owner, 0, newOrigin);
  2235. // Otherwise, if the root has been trimmed, garbage collect.
  2236. } else if (newOrigin > oldOrigin || newTailOffset < oldTailOffset) {
  2237. offsetShift = 0;
  2238. // Identify the new top root node of the subtree of the old root.
  2239. while (newRoot) {
  2240. var beginIndex = (newOrigin >>> newLevel) & MASK;
  2241. if (beginIndex !== (newTailOffset >>> newLevel) & MASK) {
  2242. break;
  2243. }
  2244. if (beginIndex) {
  2245. offsetShift += (1 << newLevel) * beginIndex;
  2246. }
  2247. newLevel -= SHIFT;
  2248. newRoot = newRoot.array[beginIndex];
  2249. }
  2250. // Trim the new sides of the new root.
  2251. if (newRoot && newOrigin > oldOrigin) {
  2252. newRoot = newRoot.removeBefore(owner, newLevel, newOrigin - offsetShift);
  2253. }
  2254. if (newRoot && newTailOffset < oldTailOffset) {
  2255. newRoot = newRoot.removeAfter(owner, newLevel, newTailOffset - offsetShift);
  2256. }
  2257. if (offsetShift) {
  2258. newOrigin -= offsetShift;
  2259. newCapacity -= offsetShift;
  2260. }
  2261. }
  2262. if (list.__ownerID) {
  2263. list.size = newCapacity - newOrigin;
  2264. list._origin = newOrigin;
  2265. list._capacity = newCapacity;
  2266. list._level = newLevel;
  2267. list._root = newRoot;
  2268. list._tail = newTail;
  2269. list.__hash = undefined;
  2270. list.__altered = true;
  2271. return list;
  2272. }
  2273. return makeList(newOrigin, newCapacity, newLevel, newRoot, newTail);
  2274. }
  2275. function mergeIntoListWith(list, merger, iterables) {
  2276. var iters = [];
  2277. var maxSize = 0;
  2278. for (var ii = 0; ii < iterables.length; ii++) {
  2279. var value = iterables[ii];
  2280. var iter = IndexedIterable(value);
  2281. if (iter.size > maxSize) {
  2282. maxSize = iter.size;
  2283. }
  2284. if (!isIterable(value)) {
  2285. iter = iter.map(function(v ) {return fromJS(v)});
  2286. }
  2287. iters.push(iter);
  2288. }
  2289. if (maxSize > list.size) {
  2290. list = list.setSize(maxSize);
  2291. }
  2292. return mergeIntoCollectionWith(list, merger, iters);
  2293. }
  2294. function getTailOffset(size) {
  2295. return size < SIZE ? 0 : (((size - 1) >>> SHIFT) << SHIFT);
  2296. }
  2297. createClass(OrderedMap, Map);
  2298. // @pragma Construction
  2299. function OrderedMap(value) {
  2300. return value === null || value === undefined ? emptyOrderedMap() :
  2301. isOrderedMap(value) ? value :
  2302. emptyOrderedMap().withMutations(function(map ) {
  2303. var iter = KeyedIterable(value);
  2304. assertNotInfinite(iter.size);
  2305. iter.forEach(function(v, k) {return map.set(k, v)});
  2306. });
  2307. }
  2308. OrderedMap.of = function(/*...values*/) {
  2309. return this(arguments);
  2310. };
  2311. OrderedMap.prototype.toString = function() {
  2312. return this.__toString('OrderedMap {', '}');
  2313. };
  2314. // @pragma Access
  2315. OrderedMap.prototype.get = function(k, notSetValue) {
  2316. var index = this._map.get(k);
  2317. return index !== undefined ? this._list.get(index)[1] : notSetValue;
  2318. };
  2319. // @pragma Modification
  2320. OrderedMap.prototype.clear = function() {
  2321. if (this.size === 0) {
  2322. return this;
  2323. }
  2324. if (this.__ownerID) {
  2325. this.size = 0;
  2326. this._map.clear();
  2327. this._list.clear();
  2328. return this;
  2329. }
  2330. return emptyOrderedMap();
  2331. };
  2332. OrderedMap.prototype.set = function(k, v) {
  2333. return updateOrderedMap(this, k, v);
  2334. };
  2335. OrderedMap.prototype.remove = function(k) {
  2336. return updateOrderedMap(this, k, NOT_SET);
  2337. };
  2338. OrderedMap.prototype.wasAltered = function() {
  2339. return this._map.wasAltered() || this._list.wasAltered();
  2340. };
  2341. OrderedMap.prototype.__iterate = function(fn, reverse) {var this$0 = this;
  2342. return this._list.__iterate(
  2343. function(entry ) {return entry && fn(entry[1], entry[0], this$0)},
  2344. reverse
  2345. );
  2346. };
  2347. OrderedMap.prototype.__iterator = function(type, reverse) {
  2348. return this._list.fromEntrySeq().__iterator(type, reverse);
  2349. };
  2350. OrderedMap.prototype.__ensureOwner = function(ownerID) {
  2351. if (ownerID === this.__ownerID) {
  2352. return this;
  2353. }
  2354. var newMap = this._map.__ensureOwner(ownerID);
  2355. var newList = this._list.__ensureOwner(ownerID);
  2356. if (!ownerID) {
  2357. this.__ownerID = ownerID;
  2358. this._map = newMap;
  2359. this._list = newList;
  2360. return this;
  2361. }
  2362. return makeOrderedMap(newMap, newList, ownerID, this.__hash);
  2363. };
  2364. function isOrderedMap(maybeOrderedMap) {
  2365. return isMap(maybeOrderedMap) && isOrdered(maybeOrderedMap);
  2366. }
  2367. OrderedMap.isOrderedMap = isOrderedMap;
  2368. OrderedMap.prototype[IS_ORDERED_SENTINEL] = true;
  2369. OrderedMap.prototype[DELETE] = OrderedMap.prototype.remove;
  2370. function makeOrderedMap(map, list, ownerID, hash) {
  2371. var omap = Object.create(OrderedMap.prototype);
  2372. omap.size = map ? map.size : 0;
  2373. omap._map = map;
  2374. omap._list = list;
  2375. omap.__ownerID = ownerID;
  2376. omap.__hash = hash;
  2377. return omap;
  2378. }
  2379. var EMPTY_ORDERED_MAP;
  2380. function emptyOrderedMap() {
  2381. return EMPTY_ORDERED_MAP || (EMPTY_ORDERED_MAP = makeOrderedMap(emptyMap(), emptyList()));
  2382. }
  2383. function updateOrderedMap(omap, k, v) {
  2384. var map = omap._map;
  2385. var list = omap._list;
  2386. var i = map.get(k);
  2387. var has = i !== undefined;
  2388. var newMap;
  2389. var newList;
  2390. if (v === NOT_SET) { // removed
  2391. if (!has) {
  2392. return omap;
  2393. }
  2394. if (list.size >= SIZE && list.size >= map.size * 2) {
  2395. newList = list.filter(function(entry, idx) {return entry !== undefined && i !== idx});
  2396. newMap = newList.toKeyedSeq().map(function(entry ) {return entry[0]}).flip().toMap();
  2397. if (omap.__ownerID) {
  2398. newMap.__ownerID = newList.__ownerID = omap.__ownerID;
  2399. }
  2400. } else {
  2401. newMap = map.remove(k);
  2402. newList = i === list.size - 1 ? list.pop() : list.set(i, undefined);
  2403. }
  2404. } else {
  2405. if (has) {
  2406. if (v === list.get(i)[1]) {
  2407. return omap;
  2408. }
  2409. newMap = map;
  2410. newList = list.set(i, [k, v]);
  2411. } else {
  2412. newMap = map.set(k, list.size);
  2413. newList = list.set(list.size, [k, v]);
  2414. }
  2415. }
  2416. if (omap.__ownerID) {
  2417. omap.size = newMap.size;
  2418. omap._map = newMap;
  2419. omap._list = newList;
  2420. omap.__hash = undefined;
  2421. return omap;
  2422. }
  2423. return makeOrderedMap(newMap, newList);
  2424. }
  2425. createClass(ToKeyedSequence, KeyedSeq);
  2426. function ToKeyedSequence(indexed, useKeys) {
  2427. this._iter = indexed;
  2428. this._useKeys = useKeys;
  2429. this.size = indexed.size;
  2430. }
  2431. ToKeyedSequence.prototype.get = function(key, notSetValue) {
  2432. return this._iter.get(key, notSetValue);
  2433. };
  2434. ToKeyedSequence.prototype.has = function(key) {
  2435. return this._iter.has(key);
  2436. };
  2437. ToKeyedSequence.prototype.valueSeq = function() {
  2438. return this._iter.valueSeq();
  2439. };
  2440. ToKeyedSequence.prototype.reverse = function() {var this$0 = this;
  2441. var reversedSequence = reverseFactory(this, true);
  2442. if (!this._useKeys) {
  2443. reversedSequence.valueSeq = function() {return this$0._iter.toSeq().reverse()};
  2444. }
  2445. return reversedSequence;
  2446. };
  2447. ToKeyedSequence.prototype.map = function(mapper, context) {var this$0 = this;
  2448. var mappedSequence = mapFactory(this, mapper, context);
  2449. if (!this._useKeys) {
  2450. mappedSequence.valueSeq = function() {return this$0._iter.toSeq().map(mapper, context)};
  2451. }
  2452. return mappedSequence;
  2453. };
  2454. ToKeyedSequence.prototype.__iterate = function(fn, reverse) {var this$0 = this;
  2455. var ii;
  2456. return this._iter.__iterate(
  2457. this._useKeys ?
  2458. function(v, k) {return fn(v, k, this$0)} :
  2459. ((ii = reverse ? resolveSize(this) : 0),
  2460. function(v ) {return fn(v, reverse ? --ii : ii++, this$0)}),
  2461. reverse
  2462. );
  2463. };
  2464. ToKeyedSequence.prototype.__iterator = function(type, reverse) {
  2465. if (this._useKeys) {
  2466. return this._iter.__iterator(type, reverse);
  2467. }
  2468. var iterator = this._iter.__iterator(ITERATE_VALUES, reverse);
  2469. var ii = reverse ? resolveSize(this) : 0;
  2470. return new Iterator(function() {
  2471. var step = iterator.next();
  2472. return step.done ? step :
  2473. iteratorValue(type, reverse ? --ii : ii++, step.value, step);
  2474. });
  2475. };
  2476. ToKeyedSequence.prototype[IS_ORDERED_SENTINEL] = true;
  2477. createClass(ToIndexedSequence, IndexedSeq);
  2478. function ToIndexedSequence(iter) {
  2479. this._iter = iter;
  2480. this.size = iter.size;
  2481. }
  2482. ToIndexedSequence.prototype.includes = function(value) {
  2483. return this._iter.includes(value);
  2484. };
  2485. ToIndexedSequence.prototype.__iterate = function(fn, reverse) {var this$0 = this;
  2486. var iterations = 0;
  2487. return this._iter.__iterate(function(v ) {return fn(v, iterations++, this$0)}, reverse);
  2488. };
  2489. ToIndexedSequence.prototype.__iterator = function(type, reverse) {
  2490. var iterator = this._iter.__iterator(ITERATE_VALUES, reverse);
  2491. var iterations = 0;
  2492. return new Iterator(function() {
  2493. var step = iterator.next();
  2494. return step.done ? step :
  2495. iteratorValue(type, iterations++, step.value, step)
  2496. });
  2497. };
  2498. createClass(ToSetSequence, SetSeq);
  2499. function ToSetSequence(iter) {
  2500. this._iter = iter;
  2501. this.size = iter.size;
  2502. }
  2503. ToSetSequence.prototype.has = function(key) {
  2504. return this._iter.includes(key);
  2505. };
  2506. ToSetSequence.prototype.__iterate = function(fn, reverse) {var this$0 = this;
  2507. return this._iter.__iterate(function(v ) {return fn(v, v, this$0)}, reverse);
  2508. };
  2509. ToSetSequence.prototype.__iterator = function(type, reverse) {
  2510. var iterator = this._iter.__iterator(ITERATE_VALUES, reverse);
  2511. return new Iterator(function() {
  2512. var step = iterator.next();
  2513. return step.done ? step :
  2514. iteratorValue(type, step.value, step.value, step);
  2515. });
  2516. };
  2517. createClass(FromEntriesSequence, KeyedSeq);
  2518. function FromEntriesSequence(entries) {
  2519. this._iter = entries;
  2520. this.size = entries.size;
  2521. }
  2522. FromEntriesSequence.prototype.entrySeq = function() {
  2523. return this._iter.toSeq();
  2524. };
  2525. FromEntriesSequence.prototype.__iterate = function(fn, reverse) {var this$0 = this;
  2526. return this._iter.__iterate(function(entry ) {
  2527. // Check if entry exists first so array access doesn't throw for holes
  2528. // in the parent iteration.
  2529. if (entry) {
  2530. validateEntry(entry);
  2531. var indexedIterable = isIterable(entry);
  2532. return fn(
  2533. indexedIterable ? entry.get(1) : entry[1],
  2534. indexedIterable ? entry.get(0) : entry[0],
  2535. this$0
  2536. );
  2537. }
  2538. }, reverse);
  2539. };
  2540. FromEntriesSequence.prototype.__iterator = function(type, reverse) {
  2541. var iterator = this._iter.__iterator(ITERATE_VALUES, reverse);
  2542. return new Iterator(function() {
  2543. while (true) {
  2544. var step = iterator.next();
  2545. if (step.done) {
  2546. return step;
  2547. }
  2548. var entry = step.value;
  2549. // Check if entry exists first so array access doesn't throw for holes
  2550. // in the parent iteration.
  2551. if (entry) {
  2552. validateEntry(entry);
  2553. var indexedIterable = isIterable(entry);
  2554. return iteratorValue(
  2555. type,
  2556. indexedIterable ? entry.get(0) : entry[0],
  2557. indexedIterable ? entry.get(1) : entry[1],
  2558. step
  2559. );
  2560. }
  2561. }
  2562. });
  2563. };
  2564. ToIndexedSequence.prototype.cacheResult =
  2565. ToKeyedSequence.prototype.cacheResult =
  2566. ToSetSequence.prototype.cacheResult =
  2567. FromEntriesSequence.prototype.cacheResult =
  2568. cacheResultThrough;
  2569. function flipFactory(iterable) {
  2570. var flipSequence = makeSequence(iterable);
  2571. flipSequence._iter = iterable;
  2572. flipSequence.size = iterable.size;
  2573. flipSequence.flip = function() {return iterable};
  2574. flipSequence.reverse = function () {
  2575. var reversedSequence = iterable.reverse.apply(this); // super.reverse()
  2576. reversedSequence.flip = function() {return iterable.reverse()};
  2577. return reversedSequence;
  2578. };
  2579. flipSequence.has = function(key ) {return iterable.includes(key)};
  2580. flipSequence.includes = function(key ) {return iterable.has(key)};
  2581. flipSequence.cacheResult = cacheResultThrough;
  2582. flipSequence.__iterateUncached = function (fn, reverse) {var this$0 = this;
  2583. return iterable.__iterate(function(v, k) {return fn(k, v, this$0) !== false}, reverse);
  2584. };
  2585. flipSequence.__iteratorUncached = function(type, reverse) {
  2586. if (type === ITERATE_ENTRIES) {
  2587. var iterator = iterable.__iterator(type, reverse);
  2588. return new Iterator(function() {
  2589. var step = iterator.next();
  2590. if (!step.done) {
  2591. var k = step.value[0];
  2592. step.value[0] = step.value[1];
  2593. step.value[1] = k;
  2594. }
  2595. return step;
  2596. });
  2597. }
  2598. return iterable.__iterator(
  2599. type === ITERATE_VALUES ? ITERATE_KEYS : ITERATE_VALUES,
  2600. reverse
  2601. );
  2602. };
  2603. return flipSequence;
  2604. }
  2605. function mapFactory(iterable, mapper, context) {
  2606. var mappedSequence = makeSequence(iterable);
  2607. mappedSequence.size = iterable.size;
  2608. mappedSequence.has = function(key ) {return iterable.has(key)};
  2609. mappedSequence.get = function(key, notSetValue) {
  2610. var v = iterable.get(key, NOT_SET);
  2611. return v === NOT_SET ?
  2612. notSetValue :
  2613. mapper.call(context, v, key, iterable);
  2614. };
  2615. mappedSequence.__iterateUncached = function (fn, reverse) {var this$0 = this;
  2616. return iterable.__iterate(
  2617. function(v, k, c) {return fn(mapper.call(context, v, k, c), k, this$0) !== false},
  2618. reverse
  2619. );
  2620. };
  2621. mappedSequence.__iteratorUncached = function (type, reverse) {
  2622. var iterator = iterable.__iterator(ITERATE_ENTRIES, reverse);
  2623. return new Iterator(function() {
  2624. var step = iterator.next();
  2625. if (step.done) {
  2626. return step;
  2627. }
  2628. var entry = step.value;
  2629. var key = entry[0];
  2630. return iteratorValue(
  2631. type,
  2632. key,
  2633. mapper.call(context, entry[1], key, iterable),
  2634. step
  2635. );
  2636. });
  2637. };
  2638. return mappedSequence;
  2639. }
  2640. function reverseFactory(iterable, useKeys) {
  2641. var reversedSequence = makeSequence(iterable);
  2642. reversedSequence._iter = iterable;
  2643. reversedSequence.size = iterable.size;
  2644. reversedSequence.reverse = function() {return iterable};
  2645. if (iterable.flip) {
  2646. reversedSequence.flip = function () {
  2647. var flipSequence = flipFactory(iterable);
  2648. flipSequence.reverse = function() {return iterable.flip()};
  2649. return flipSequence;
  2650. };
  2651. }
  2652. reversedSequence.get = function(key, notSetValue)
  2653. {return iterable.get(useKeys ? key : -1 - key, notSetValue)};
  2654. reversedSequence.has = function(key )
  2655. {return iterable.has(useKeys ? key : -1 - key)};
  2656. reversedSequence.includes = function(value ) {return iterable.includes(value)};
  2657. reversedSequence.cacheResult = cacheResultThrough;
  2658. reversedSequence.__iterate = function (fn, reverse) {var this$0 = this;
  2659. return iterable.__iterate(function(v, k) {return fn(v, k, this$0)}, !reverse);
  2660. };
  2661. reversedSequence.__iterator =
  2662. function(type, reverse) {return iterable.__iterator(type, !reverse)};
  2663. return reversedSequence;
  2664. }
  2665. function filterFactory(iterable, predicate, context, useKeys) {
  2666. var filterSequence = makeSequence(iterable);
  2667. if (useKeys) {
  2668. filterSequence.has = function(key ) {
  2669. var v = iterable.get(key, NOT_SET);
  2670. return v !== NOT_SET && !!predicate.call(context, v, key, iterable);
  2671. };
  2672. filterSequence.get = function(key, notSetValue) {
  2673. var v = iterable.get(key, NOT_SET);
  2674. return v !== NOT_SET && predicate.call(context, v, key, iterable) ?
  2675. v : notSetValue;
  2676. };
  2677. }
  2678. filterSequence.__iterateUncached = function (fn, reverse) {var this$0 = this;
  2679. var iterations = 0;
  2680. iterable.__iterate(function(v, k, c) {
  2681. if (predicate.call(context, v, k, c)) {
  2682. iterations++;
  2683. return fn(v, useKeys ? k : iterations - 1, this$0);
  2684. }
  2685. }, reverse);
  2686. return iterations;
  2687. };
  2688. filterSequence.__iteratorUncached = function (type, reverse) {
  2689. var iterator = iterable.__iterator(ITERATE_ENTRIES, reverse);
  2690. var iterations = 0;
  2691. return new Iterator(function() {
  2692. while (true) {
  2693. var step = iterator.next();
  2694. if (step.done) {
  2695. return step;
  2696. }
  2697. var entry = step.value;
  2698. var key = entry[0];
  2699. var value = entry[1];
  2700. if (predicate.call(context, value, key, iterable)) {
  2701. return iteratorValue(type, useKeys ? key : iterations++, value, step);
  2702. }
  2703. }
  2704. });
  2705. };
  2706. return filterSequence;
  2707. }
  2708. function countByFactory(iterable, grouper, context) {
  2709. var groups = Map().asMutable();
  2710. iterable.__iterate(function(v, k) {
  2711. groups.update(
  2712. grouper.call(context, v, k, iterable),
  2713. 0,
  2714. function(a ) {return a + 1}
  2715. );
  2716. });
  2717. return groups.asImmutable();
  2718. }
  2719. function groupByFactory(iterable, grouper, context) {
  2720. var isKeyedIter = isKeyed(iterable);
  2721. var groups = (isOrdered(iterable) ? OrderedMap() : Map()).asMutable();
  2722. iterable.__iterate(function(v, k) {
  2723. groups.update(
  2724. grouper.call(context, v, k, iterable),
  2725. function(a ) {return (a = a || [], a.push(isKeyedIter ? [k, v] : v), a)}
  2726. );
  2727. });
  2728. var coerce = iterableClass(iterable);
  2729. return groups.map(function(arr ) {return reify(iterable, coerce(arr))});
  2730. }
  2731. function sliceFactory(iterable, begin, end, useKeys) {
  2732. var originalSize = iterable.size;
  2733. // Sanitize begin & end using this shorthand for ToInt32(argument)
  2734. // http://www.ecma-international.org/ecma-262/6.0/#sec-toint32
  2735. if (begin !== undefined) {
  2736. begin = begin | 0;
  2737. }
  2738. if (end !== undefined) {
  2739. end = end | 0;
  2740. }
  2741. if (wholeSlice(begin, end, originalSize)) {
  2742. return iterable;
  2743. }
  2744. var resolvedBegin = resolveBegin(begin, originalSize);
  2745. var resolvedEnd = resolveEnd(end, originalSize);
  2746. // begin or end will be NaN if they were provided as negative numbers and
  2747. // this iterable's size is unknown. In that case, cache first so there is
  2748. // a known size and these do not resolve to NaN.
  2749. if (resolvedBegin !== resolvedBegin || resolvedEnd !== resolvedEnd) {
  2750. return sliceFactory(iterable.toSeq().cacheResult(), begin, end, useKeys);
  2751. }
  2752. // Note: resolvedEnd is undefined when the original sequence's length is
  2753. // unknown and this slice did not supply an end and should contain all
  2754. // elements after resolvedBegin.
  2755. // In that case, resolvedSize will be NaN and sliceSize will remain undefined.
  2756. var resolvedSize = resolvedEnd - resolvedBegin;
  2757. var sliceSize;
  2758. if (resolvedSize === resolvedSize) {
  2759. sliceSize = resolvedSize < 0 ? 0 : resolvedSize;
  2760. }
  2761. var sliceSeq = makeSequence(iterable);
  2762. // If iterable.size is undefined, the size of the realized sliceSeq is
  2763. // unknown at this point unless the number of items to slice is 0
  2764. sliceSeq.size = sliceSize === 0 ? sliceSize : iterable.size && sliceSize || undefined;
  2765. if (!useKeys && isSeq(iterable) && sliceSize >= 0) {
  2766. sliceSeq.get = function (index, notSetValue) {
  2767. index = wrapIndex(this, index);
  2768. return index >= 0 && index < sliceSize ?
  2769. iterable.get(index + resolvedBegin, notSetValue) :
  2770. notSetValue;
  2771. };
  2772. }
  2773. sliceSeq.__iterateUncached = function(fn, reverse) {var this$0 = this;
  2774. if (sliceSize === 0) {
  2775. return 0;
  2776. }
  2777. if (reverse) {
  2778. return this.cacheResult().__iterate(fn, reverse);
  2779. }
  2780. var skipped = 0;
  2781. var isSkipping = true;
  2782. var iterations = 0;
  2783. iterable.__iterate(function(v, k) {
  2784. if (!(isSkipping && (isSkipping = skipped++ < resolvedBegin))) {
  2785. iterations++;
  2786. return fn(v, useKeys ? k : iterations - 1, this$0) !== false &&
  2787. iterations !== sliceSize;
  2788. }
  2789. });
  2790. return iterations;
  2791. };
  2792. sliceSeq.__iteratorUncached = function(type, reverse) {
  2793. if (sliceSize !== 0 && reverse) {
  2794. return this.cacheResult().__iterator(type, reverse);
  2795. }
  2796. // Don't bother instantiating parent iterator if taking 0.
  2797. var iterator = sliceSize !== 0 && iterable.__iterator(type, reverse);
  2798. var skipped = 0;
  2799. var iterations = 0;
  2800. return new Iterator(function() {
  2801. while (skipped++ < resolvedBegin) {
  2802. iterator.next();
  2803. }
  2804. if (++iterations > sliceSize) {
  2805. return iteratorDone();
  2806. }
  2807. var step = iterator.next();
  2808. if (useKeys || type === ITERATE_VALUES) {
  2809. return step;
  2810. } else if (type === ITERATE_KEYS) {
  2811. return iteratorValue(type, iterations - 1, undefined, step);
  2812. } else {
  2813. return iteratorValue(type, iterations - 1, step.value[1], step);
  2814. }
  2815. });
  2816. };
  2817. return sliceSeq;
  2818. }
  2819. function takeWhileFactory(iterable, predicate, context) {
  2820. var takeSequence = makeSequence(iterable);
  2821. takeSequence.__iterateUncached = function(fn, reverse) {var this$0 = this;
  2822. if (reverse) {
  2823. return this.cacheResult().__iterate(fn, reverse);
  2824. }
  2825. var iterations = 0;
  2826. iterable.__iterate(function(v, k, c)
  2827. {return predicate.call(context, v, k, c) && ++iterations && fn(v, k, this$0)}
  2828. );
  2829. return iterations;
  2830. };
  2831. takeSequence.__iteratorUncached = function(type, reverse) {var this$0 = this;
  2832. if (reverse) {
  2833. return this.cacheResult().__iterator(type, reverse);
  2834. }
  2835. var iterator = iterable.__iterator(ITERATE_ENTRIES, reverse);
  2836. var iterating = true;
  2837. return new Iterator(function() {
  2838. if (!iterating) {
  2839. return iteratorDone();
  2840. }
  2841. var step = iterator.next();
  2842. if (step.done) {
  2843. return step;
  2844. }
  2845. var entry = step.value;
  2846. var k = entry[0];
  2847. var v = entry[1];
  2848. if (!predicate.call(context, v, k, this$0)) {
  2849. iterating = false;
  2850. return iteratorDone();
  2851. }
  2852. return type === ITERATE_ENTRIES ? step :
  2853. iteratorValue(type, k, v, step);
  2854. });
  2855. };
  2856. return takeSequence;
  2857. }
  2858. function skipWhileFactory(iterable, predicate, context, useKeys) {
  2859. var skipSequence = makeSequence(iterable);
  2860. skipSequence.__iterateUncached = function (fn, reverse) {var this$0 = this;
  2861. if (reverse) {
  2862. return this.cacheResult().__iterate(fn, reverse);
  2863. }
  2864. var isSkipping = true;
  2865. var iterations = 0;
  2866. iterable.__iterate(function(v, k, c) {
  2867. if (!(isSkipping && (isSkipping = predicate.call(context, v, k, c)))) {
  2868. iterations++;
  2869. return fn(v, useKeys ? k : iterations - 1, this$0);
  2870. }
  2871. });
  2872. return iterations;
  2873. };
  2874. skipSequence.__iteratorUncached = function(type, reverse) {var this$0 = this;
  2875. if (reverse) {
  2876. return this.cacheResult().__iterator(type, reverse);
  2877. }
  2878. var iterator = iterable.__iterator(ITERATE_ENTRIES, reverse);
  2879. var skipping = true;
  2880. var iterations = 0;
  2881. return new Iterator(function() {
  2882. var step, k, v;
  2883. do {
  2884. step = iterator.next();
  2885. if (step.done) {
  2886. if (useKeys || type === ITERATE_VALUES) {
  2887. return step;
  2888. } else if (type === ITERATE_KEYS) {
  2889. return iteratorValue(type, iterations++, undefined, step);
  2890. } else {
  2891. return iteratorValue(type, iterations++, step.value[1], step);
  2892. }
  2893. }
  2894. var entry = step.value;
  2895. k = entry[0];
  2896. v = entry[1];
  2897. skipping && (skipping = predicate.call(context, v, k, this$0));
  2898. } while (skipping);
  2899. return type === ITERATE_ENTRIES ? step :
  2900. iteratorValue(type, k, v, step);
  2901. });
  2902. };
  2903. return skipSequence;
  2904. }
  2905. function concatFactory(iterable, values) {
  2906. var isKeyedIterable = isKeyed(iterable);
  2907. var iters = [iterable].concat(values).map(function(v ) {
  2908. if (!isIterable(v)) {
  2909. v = isKeyedIterable ?
  2910. keyedSeqFromValue(v) :
  2911. indexedSeqFromValue(Array.isArray(v) ? v : [v]);
  2912. } else if (isKeyedIterable) {
  2913. v = KeyedIterable(v);
  2914. }
  2915. return v;
  2916. }).filter(function(v ) {return v.size !== 0});
  2917. if (iters.length === 0) {
  2918. return iterable;
  2919. }
  2920. if (iters.length === 1) {
  2921. var singleton = iters[0];
  2922. if (singleton === iterable ||
  2923. isKeyedIterable && isKeyed(singleton) ||
  2924. isIndexed(iterable) && isIndexed(singleton)) {
  2925. return singleton;
  2926. }
  2927. }
  2928. var concatSeq = new ArraySeq(iters);
  2929. if (isKeyedIterable) {
  2930. concatSeq = concatSeq.toKeyedSeq();
  2931. } else if (!isIndexed(iterable)) {
  2932. concatSeq = concatSeq.toSetSeq();
  2933. }
  2934. concatSeq = concatSeq.flatten(true);
  2935. concatSeq.size = iters.reduce(
  2936. function(sum, seq) {
  2937. if (sum !== undefined) {
  2938. var size = seq.size;
  2939. if (size !== undefined) {
  2940. return sum + size;
  2941. }
  2942. }
  2943. },
  2944. 0
  2945. );
  2946. return concatSeq;
  2947. }
  2948. function flattenFactory(iterable, depth, useKeys) {
  2949. var flatSequence = makeSequence(iterable);
  2950. flatSequence.__iterateUncached = function(fn, reverse) {
  2951. var iterations = 0;
  2952. var stopped = false;
  2953. function flatDeep(iter, currentDepth) {var this$0 = this;
  2954. iter.__iterate(function(v, k) {
  2955. if ((!depth || currentDepth < depth) && isIterable(v)) {
  2956. flatDeep(v, currentDepth + 1);
  2957. } else if (fn(v, useKeys ? k : iterations++, this$0) === false) {
  2958. stopped = true;
  2959. }
  2960. return !stopped;
  2961. }, reverse);
  2962. }
  2963. flatDeep(iterable, 0);
  2964. return iterations;
  2965. };
  2966. flatSequence.__iteratorUncached = function(type, reverse) {
  2967. var iterator = iterable.__iterator(type, reverse);
  2968. var stack = [];
  2969. var iterations = 0;
  2970. return new Iterator(function() {
  2971. while (iterator) {
  2972. var step = iterator.next();
  2973. if (step.done !== false) {
  2974. iterator = stack.pop();
  2975. continue;
  2976. }
  2977. var v = step.value;
  2978. if (type === ITERATE_ENTRIES) {
  2979. v = v[1];
  2980. }
  2981. if ((!depth || stack.length < depth) && isIterable(v)) {
  2982. stack.push(iterator);
  2983. iterator = v.__iterator(type, reverse);
  2984. } else {
  2985. return useKeys ? step : iteratorValue(type, iterations++, v, step);
  2986. }
  2987. }
  2988. return iteratorDone();
  2989. });
  2990. };
  2991. return flatSequence;
  2992. }
  2993. function flatMapFactory(iterable, mapper, context) {
  2994. var coerce = iterableClass(iterable);
  2995. return iterable.toSeq().map(
  2996. function(v, k) {return coerce(mapper.call(context, v, k, iterable))}
  2997. ).flatten(true);
  2998. }
  2999. function interposeFactory(iterable, separator) {
  3000. var interposedSequence = makeSequence(iterable);
  3001. interposedSequence.size = iterable.size && iterable.size * 2 -1;
  3002. interposedSequence.__iterateUncached = function(fn, reverse) {var this$0 = this;
  3003. var iterations = 0;
  3004. iterable.__iterate(function(v, k)
  3005. {return (!iterations || fn(separator, iterations++, this$0) !== false) &&
  3006. fn(v, iterations++, this$0) !== false},
  3007. reverse
  3008. );
  3009. return iterations;
  3010. };
  3011. interposedSequence.__iteratorUncached = function(type, reverse) {
  3012. var iterator = iterable.__iterator(ITERATE_VALUES, reverse);
  3013. var iterations = 0;
  3014. var step;
  3015. return new Iterator(function() {
  3016. if (!step || iterations % 2) {
  3017. step = iterator.next();
  3018. if (step.done) {
  3019. return step;
  3020. }
  3021. }
  3022. return iterations % 2 ?
  3023. iteratorValue(type, iterations++, separator) :
  3024. iteratorValue(type, iterations++, step.value, step);
  3025. });
  3026. };
  3027. return interposedSequence;
  3028. }
  3029. function sortFactory(iterable, comparator, mapper) {
  3030. if (!comparator) {
  3031. comparator = defaultComparator;
  3032. }
  3033. var isKeyedIterable = isKeyed(iterable);
  3034. var index = 0;
  3035. var entries = iterable.toSeq().map(
  3036. function(v, k) {return [k, v, index++, mapper ? mapper(v, k, iterable) : v]}
  3037. ).toArray();
  3038. entries.sort(function(a, b) {return comparator(a[3], b[3]) || a[2] - b[2]}).forEach(
  3039. isKeyedIterable ?
  3040. function(v, i) { entries[i].length = 2; } :
  3041. function(v, i) { entries[i] = v[1]; }
  3042. );
  3043. return isKeyedIterable ? KeyedSeq(entries) :
  3044. isIndexed(iterable) ? IndexedSeq(entries) :
  3045. SetSeq(entries);
  3046. }
  3047. function maxFactory(iterable, comparator, mapper) {
  3048. if (!comparator) {
  3049. comparator = defaultComparator;
  3050. }
  3051. if (mapper) {
  3052. var entry = iterable.toSeq()
  3053. .map(function(v, k) {return [v, mapper(v, k, iterable)]})
  3054. .reduce(function(a, b) {return maxCompare(comparator, a[1], b[1]) ? b : a});
  3055. return entry && entry[0];
  3056. } else {
  3057. return iterable.reduce(function(a, b) {return maxCompare(comparator, a, b) ? b : a});
  3058. }
  3059. }
  3060. function maxCompare(comparator, a, b) {
  3061. var comp = comparator(b, a);
  3062. // b is considered the new max if the comparator declares them equal, but
  3063. // they are not equal and b is in fact a nullish value.
  3064. return (comp === 0 && b !== a && (b === undefined || b === null || b !== b)) || comp > 0;
  3065. }
  3066. function zipWithFactory(keyIter, zipper, iters) {
  3067. var zipSequence = makeSequence(keyIter);
  3068. zipSequence.size = new ArraySeq(iters).map(function(i ) {return i.size}).min();
  3069. // Note: this a generic base implementation of __iterate in terms of
  3070. // __iterator which may be more generically useful in the future.
  3071. zipSequence.__iterate = function(fn, reverse) {
  3072. /* generic:
  3073. var iterator = this.__iterator(ITERATE_ENTRIES, reverse);
  3074. var step;
  3075. var iterations = 0;
  3076. while (!(step = iterator.next()).done) {
  3077. iterations++;
  3078. if (fn(step.value[1], step.value[0], this) === false) {
  3079. break;
  3080. }
  3081. }
  3082. return iterations;
  3083. */
  3084. // indexed:
  3085. var iterator = this.__iterator(ITERATE_VALUES, reverse);
  3086. var step;
  3087. var iterations = 0;
  3088. while (!(step = iterator.next()).done) {
  3089. if (fn(step.value, iterations++, this) === false) {
  3090. break;
  3091. }
  3092. }
  3093. return iterations;
  3094. };
  3095. zipSequence.__iteratorUncached = function(type, reverse) {
  3096. var iterators = iters.map(function(i )
  3097. {return (i = Iterable(i), getIterator(reverse ? i.reverse() : i))}
  3098. );
  3099. var iterations = 0;
  3100. var isDone = false;
  3101. return new Iterator(function() {
  3102. var steps;
  3103. if (!isDone) {
  3104. steps = iterators.map(function(i ) {return i.next()});
  3105. isDone = steps.some(function(s ) {return s.done});
  3106. }
  3107. if (isDone) {
  3108. return iteratorDone();
  3109. }
  3110. return iteratorValue(
  3111. type,
  3112. iterations++,
  3113. zipper.apply(null, steps.map(function(s ) {return s.value}))
  3114. );
  3115. });
  3116. };
  3117. return zipSequence
  3118. }
  3119. // #pragma Helper Functions
  3120. function reify(iter, seq) {
  3121. return isSeq(iter) ? seq : iter.constructor(seq);
  3122. }
  3123. function validateEntry(entry) {
  3124. if (entry !== Object(entry)) {
  3125. throw new TypeError('Expected [K, V] tuple: ' + entry);
  3126. }
  3127. }
  3128. function resolveSize(iter) {
  3129. assertNotInfinite(iter.size);
  3130. return ensureSize(iter);
  3131. }
  3132. function iterableClass(iterable) {
  3133. return isKeyed(iterable) ? KeyedIterable :
  3134. isIndexed(iterable) ? IndexedIterable :
  3135. SetIterable;
  3136. }
  3137. function makeSequence(iterable) {
  3138. return Object.create(
  3139. (
  3140. isKeyed(iterable) ? KeyedSeq :
  3141. isIndexed(iterable) ? IndexedSeq :
  3142. SetSeq
  3143. ).prototype
  3144. );
  3145. }
  3146. function cacheResultThrough() {
  3147. if (this._iter.cacheResult) {
  3148. this._iter.cacheResult();
  3149. this.size = this._iter.size;
  3150. return this;
  3151. } else {
  3152. return Seq.prototype.cacheResult.call(this);
  3153. }
  3154. }
  3155. function defaultComparator(a, b) {
  3156. return a > b ? 1 : a < b ? -1 : 0;
  3157. }
  3158. function forceIterator(keyPath) {
  3159. var iter = getIterator(keyPath);
  3160. if (!iter) {
  3161. // Array might not be iterable in this environment, so we need a fallback
  3162. // to our wrapped type.
  3163. if (!isArrayLike(keyPath)) {
  3164. throw new TypeError('Expected iterable or array-like: ' + keyPath);
  3165. }
  3166. iter = getIterator(Iterable(keyPath));
  3167. }
  3168. return iter;
  3169. }
  3170. createClass(Record, KeyedCollection);
  3171. function Record(defaultValues, name) {
  3172. var hasInitialized;
  3173. var RecordType = function Record(values) {
  3174. if (values instanceof RecordType) {
  3175. return values;
  3176. }
  3177. if (!(this instanceof RecordType)) {
  3178. return new RecordType(values);
  3179. }
  3180. if (!hasInitialized) {
  3181. hasInitialized = true;
  3182. var keys = Object.keys(defaultValues);
  3183. setProps(RecordTypePrototype, keys);
  3184. RecordTypePrototype.size = keys.length;
  3185. RecordTypePrototype._name = name;
  3186. RecordTypePrototype._keys = keys;
  3187. RecordTypePrototype._defaultValues = defaultValues;
  3188. }
  3189. this._map = Map(values);
  3190. };
  3191. var RecordTypePrototype = RecordType.prototype = Object.create(RecordPrototype);
  3192. RecordTypePrototype.constructor = RecordType;
  3193. return RecordType;
  3194. }
  3195. Record.prototype.toString = function() {
  3196. return this.__toString(recordName(this) + ' {', '}');
  3197. };
  3198. // @pragma Access
  3199. Record.prototype.has = function(k) {
  3200. return this._defaultValues.hasOwnProperty(k);
  3201. };
  3202. Record.prototype.get = function(k, notSetValue) {
  3203. if (!this.has(k)) {
  3204. return notSetValue;
  3205. }
  3206. var defaultVal = this._defaultValues[k];
  3207. return this._map ? this._map.get(k, defaultVal) : defaultVal;
  3208. };
  3209. // @pragma Modification
  3210. Record.prototype.clear = function() {
  3211. if (this.__ownerID) {
  3212. this._map && this._map.clear();
  3213. return this;
  3214. }
  3215. var RecordType = this.constructor;
  3216. return RecordType._empty || (RecordType._empty = makeRecord(this, emptyMap()));
  3217. };
  3218. Record.prototype.set = function(k, v) {
  3219. if (!this.has(k)) {
  3220. throw new Error('Cannot set unknown key "' + k + '" on ' + recordName(this));
  3221. }
  3222. var newMap = this._map && this._map.set(k, v);
  3223. if (this.__ownerID || newMap === this._map) {
  3224. return this;
  3225. }
  3226. return makeRecord(this, newMap);
  3227. };
  3228. Record.prototype.remove = function(k) {
  3229. if (!this.has(k)) {
  3230. return this;
  3231. }
  3232. var newMap = this._map && this._map.remove(k);
  3233. if (this.__ownerID || newMap === this._map) {
  3234. return this;
  3235. }
  3236. return makeRecord(this, newMap);
  3237. };
  3238. Record.prototype.wasAltered = function() {
  3239. return this._map.wasAltered();
  3240. };
  3241. Record.prototype.__iterator = function(type, reverse) {var this$0 = this;
  3242. return KeyedIterable(this._defaultValues).map(function(_, k) {return this$0.get(k)}).__iterator(type, reverse);
  3243. };
  3244. Record.prototype.__iterate = function(fn, reverse) {var this$0 = this;
  3245. return KeyedIterable(this._defaultValues).map(function(_, k) {return this$0.get(k)}).__iterate(fn, reverse);
  3246. };
  3247. Record.prototype.__ensureOwner = function(ownerID) {
  3248. if (ownerID === this.__ownerID) {
  3249. return this;
  3250. }
  3251. var newMap = this._map && this._map.__ensureOwner(ownerID);
  3252. if (!ownerID) {
  3253. this.__ownerID = ownerID;
  3254. this._map = newMap;
  3255. return this;
  3256. }
  3257. return makeRecord(this, newMap, ownerID);
  3258. };
  3259. var RecordPrototype = Record.prototype;
  3260. RecordPrototype[DELETE] = RecordPrototype.remove;
  3261. RecordPrototype.deleteIn =
  3262. RecordPrototype.removeIn = MapPrototype.removeIn;
  3263. RecordPrototype.merge = MapPrototype.merge;
  3264. RecordPrototype.mergeWith = MapPrototype.mergeWith;
  3265. RecordPrototype.mergeIn = MapPrototype.mergeIn;
  3266. RecordPrototype.mergeDeep = MapPrototype.mergeDeep;
  3267. RecordPrototype.mergeDeepWith = MapPrototype.mergeDeepWith;
  3268. RecordPrototype.mergeDeepIn = MapPrototype.mergeDeepIn;
  3269. RecordPrototype.setIn = MapPrototype.setIn;
  3270. RecordPrototype.update = MapPrototype.update;
  3271. RecordPrototype.updateIn = MapPrototype.updateIn;
  3272. RecordPrototype.withMutations = MapPrototype.withMutations;
  3273. RecordPrototype.asMutable = MapPrototype.asMutable;
  3274. RecordPrototype.asImmutable = MapPrototype.asImmutable;
  3275. function makeRecord(likeRecord, map, ownerID) {
  3276. var record = Object.create(Object.getPrototypeOf(likeRecord));
  3277. record._map = map;
  3278. record.__ownerID = ownerID;
  3279. return record;
  3280. }
  3281. function recordName(record) {
  3282. return record._name || record.constructor.name || 'Record';
  3283. }
  3284. function setProps(prototype, names) {
  3285. try {
  3286. names.forEach(setProp.bind(undefined, prototype));
  3287. } catch (error) {
  3288. // Object.defineProperty failed. Probably IE8.
  3289. }
  3290. }
  3291. function setProp(prototype, name) {
  3292. Object.defineProperty(prototype, name, {
  3293. get: function() {
  3294. return this.get(name);
  3295. },
  3296. set: function(value) {
  3297. invariant(this.__ownerID, 'Cannot set on an immutable record.');
  3298. this.set(name, value);
  3299. }
  3300. });
  3301. }
  3302. createClass(Set, SetCollection);
  3303. // @pragma Construction
  3304. function Set(value) {
  3305. return value === null || value === undefined ? emptySet() :
  3306. isSet(value) && !isOrdered(value) ? value :
  3307. emptySet().withMutations(function(set ) {
  3308. var iter = SetIterable(value);
  3309. assertNotInfinite(iter.size);
  3310. iter.forEach(function(v ) {return set.add(v)});
  3311. });
  3312. }
  3313. Set.of = function(/*...values*/) {
  3314. return this(arguments);
  3315. };
  3316. Set.fromKeys = function(value) {
  3317. return this(KeyedIterable(value).keySeq());
  3318. };
  3319. Set.prototype.toString = function() {
  3320. return this.__toString('Set {', '}');
  3321. };
  3322. // @pragma Access
  3323. Set.prototype.has = function(value) {
  3324. return this._map.has(value);
  3325. };
  3326. // @pragma Modification
  3327. Set.prototype.add = function(value) {
  3328. return updateSet(this, this._map.set(value, true));
  3329. };
  3330. Set.prototype.remove = function(value) {
  3331. return updateSet(this, this._map.remove(value));
  3332. };
  3333. Set.prototype.clear = function() {
  3334. return updateSet(this, this._map.clear());
  3335. };
  3336. // @pragma Composition
  3337. Set.prototype.union = function() {var iters = SLICE$0.call(arguments, 0);
  3338. iters = iters.filter(function(x ) {return x.size !== 0});
  3339. if (iters.length === 0) {
  3340. return this;
  3341. }
  3342. if (this.size === 0 && !this.__ownerID && iters.length === 1) {
  3343. return this.constructor(iters[0]);
  3344. }
  3345. return this.withMutations(function(set ) {
  3346. for (var ii = 0; ii < iters.length; ii++) {
  3347. SetIterable(iters[ii]).forEach(function(value ) {return set.add(value)});
  3348. }
  3349. });
  3350. };
  3351. Set.prototype.intersect = function() {var iters = SLICE$0.call(arguments, 0);
  3352. if (iters.length === 0) {
  3353. return this;
  3354. }
  3355. iters = iters.map(function(iter ) {return SetIterable(iter)});
  3356. var originalSet = this;
  3357. return this.withMutations(function(set ) {
  3358. originalSet.forEach(function(value ) {
  3359. if (!iters.every(function(iter ) {return iter.includes(value)})) {
  3360. set.remove(value);
  3361. }
  3362. });
  3363. });
  3364. };
  3365. Set.prototype.subtract = function() {var iters = SLICE$0.call(arguments, 0);
  3366. if (iters.length === 0) {
  3367. return this;
  3368. }
  3369. iters = iters.map(function(iter ) {return SetIterable(iter)});
  3370. var originalSet = this;
  3371. return this.withMutations(function(set ) {
  3372. originalSet.forEach(function(value ) {
  3373. if (iters.some(function(iter ) {return iter.includes(value)})) {
  3374. set.remove(value);
  3375. }
  3376. });
  3377. });
  3378. };
  3379. Set.prototype.merge = function() {
  3380. return this.union.apply(this, arguments);
  3381. };
  3382. Set.prototype.mergeWith = function(merger) {var iters = SLICE$0.call(arguments, 1);
  3383. return this.union.apply(this, iters);
  3384. };
  3385. Set.prototype.sort = function(comparator) {
  3386. // Late binding
  3387. return OrderedSet(sortFactory(this, comparator));
  3388. };
  3389. Set.prototype.sortBy = function(mapper, comparator) {
  3390. // Late binding
  3391. return OrderedSet(sortFactory(this, comparator, mapper));
  3392. };
  3393. Set.prototype.wasAltered = function() {
  3394. return this._map.wasAltered();
  3395. };
  3396. Set.prototype.__iterate = function(fn, reverse) {var this$0 = this;
  3397. return this._map.__iterate(function(_, k) {return fn(k, k, this$0)}, reverse);
  3398. };
  3399. Set.prototype.__iterator = function(type, reverse) {
  3400. return this._map.map(function(_, k) {return k}).__iterator(type, reverse);
  3401. };
  3402. Set.prototype.__ensureOwner = function(ownerID) {
  3403. if (ownerID === this.__ownerID) {
  3404. return this;
  3405. }
  3406. var newMap = this._map.__ensureOwner(ownerID);
  3407. if (!ownerID) {
  3408. this.__ownerID = ownerID;
  3409. this._map = newMap;
  3410. return this;
  3411. }
  3412. return this.__make(newMap, ownerID);
  3413. };
  3414. function isSet(maybeSet) {
  3415. return !!(maybeSet && maybeSet[IS_SET_SENTINEL]);
  3416. }
  3417. Set.isSet = isSet;
  3418. var IS_SET_SENTINEL = '@@__IMMUTABLE_SET__@@';
  3419. var SetPrototype = Set.prototype;
  3420. SetPrototype[IS_SET_SENTINEL] = true;
  3421. SetPrototype[DELETE] = SetPrototype.remove;
  3422. SetPrototype.mergeDeep = SetPrototype.merge;
  3423. SetPrototype.mergeDeepWith = SetPrototype.mergeWith;
  3424. SetPrototype.withMutations = MapPrototype.withMutations;
  3425. SetPrototype.asMutable = MapPrototype.asMutable;
  3426. SetPrototype.asImmutable = MapPrototype.asImmutable;
  3427. SetPrototype.__empty = emptySet;
  3428. SetPrototype.__make = makeSet;
  3429. function updateSet(set, newMap) {
  3430. if (set.__ownerID) {
  3431. set.size = newMap.size;
  3432. set._map = newMap;
  3433. return set;
  3434. }
  3435. return newMap === set._map ? set :
  3436. newMap.size === 0 ? set.__empty() :
  3437. set.__make(newMap);
  3438. }
  3439. function makeSet(map, ownerID) {
  3440. var set = Object.create(SetPrototype);
  3441. set.size = map ? map.size : 0;
  3442. set._map = map;
  3443. set.__ownerID = ownerID;
  3444. return set;
  3445. }
  3446. var EMPTY_SET;
  3447. function emptySet() {
  3448. return EMPTY_SET || (EMPTY_SET = makeSet(emptyMap()));
  3449. }
  3450. createClass(OrderedSet, Set);
  3451. // @pragma Construction
  3452. function OrderedSet(value) {
  3453. return value === null || value === undefined ? emptyOrderedSet() :
  3454. isOrderedSet(value) ? value :
  3455. emptyOrderedSet().withMutations(function(set ) {
  3456. var iter = SetIterable(value);
  3457. assertNotInfinite(iter.size);
  3458. iter.forEach(function(v ) {return set.add(v)});
  3459. });
  3460. }
  3461. OrderedSet.of = function(/*...values*/) {
  3462. return this(arguments);
  3463. };
  3464. OrderedSet.fromKeys = function(value) {
  3465. return this(KeyedIterable(value).keySeq());
  3466. };
  3467. OrderedSet.prototype.toString = function() {
  3468. return this.__toString('OrderedSet {', '}');
  3469. };
  3470. function isOrderedSet(maybeOrderedSet) {
  3471. return isSet(maybeOrderedSet) && isOrdered(maybeOrderedSet);
  3472. }
  3473. OrderedSet.isOrderedSet = isOrderedSet;
  3474. var OrderedSetPrototype = OrderedSet.prototype;
  3475. OrderedSetPrototype[IS_ORDERED_SENTINEL] = true;
  3476. OrderedSetPrototype.__empty = emptyOrderedSet;
  3477. OrderedSetPrototype.__make = makeOrderedSet;
  3478. function makeOrderedSet(map, ownerID) {
  3479. var set = Object.create(OrderedSetPrototype);
  3480. set.size = map ? map.size : 0;
  3481. set._map = map;
  3482. set.__ownerID = ownerID;
  3483. return set;
  3484. }
  3485. var EMPTY_ORDERED_SET;
  3486. function emptyOrderedSet() {
  3487. return EMPTY_ORDERED_SET || (EMPTY_ORDERED_SET = makeOrderedSet(emptyOrderedMap()));
  3488. }
  3489. createClass(Stack, IndexedCollection);
  3490. // @pragma Construction
  3491. function Stack(value) {
  3492. return value === null || value === undefined ? emptyStack() :
  3493. isStack(value) ? value :
  3494. emptyStack().unshiftAll(value);
  3495. }
  3496. Stack.of = function(/*...values*/) {
  3497. return this(arguments);
  3498. };
  3499. Stack.prototype.toString = function() {
  3500. return this.__toString('Stack [', ']');
  3501. };
  3502. // @pragma Access
  3503. Stack.prototype.get = function(index, notSetValue) {
  3504. var head = this._head;
  3505. index = wrapIndex(this, index);
  3506. while (head && index--) {
  3507. head = head.next;
  3508. }
  3509. return head ? head.value : notSetValue;
  3510. };
  3511. Stack.prototype.peek = function() {
  3512. return this._head && this._head.value;
  3513. };
  3514. // @pragma Modification
  3515. Stack.prototype.push = function(/*...values*/) {
  3516. if (arguments.length === 0) {
  3517. return this;
  3518. }
  3519. var newSize = this.size + arguments.length;
  3520. var head = this._head;
  3521. for (var ii = arguments.length - 1; ii >= 0; ii--) {
  3522. head = {
  3523. value: arguments[ii],
  3524. next: head
  3525. };
  3526. }
  3527. if (this.__ownerID) {
  3528. this.size = newSize;
  3529. this._head = head;
  3530. this.__hash = undefined;
  3531. this.__altered = true;
  3532. return this;
  3533. }
  3534. return makeStack(newSize, head);
  3535. };
  3536. Stack.prototype.pushAll = function(iter) {
  3537. iter = IndexedIterable(iter);
  3538. if (iter.size === 0) {
  3539. return this;
  3540. }
  3541. assertNotInfinite(iter.size);
  3542. var newSize = this.size;
  3543. var head = this._head;
  3544. iter.reverse().forEach(function(value ) {
  3545. newSize++;
  3546. head = {
  3547. value: value,
  3548. next: head
  3549. };
  3550. });
  3551. if (this.__ownerID) {
  3552. this.size = newSize;
  3553. this._head = head;
  3554. this.__hash = undefined;
  3555. this.__altered = true;
  3556. return this;
  3557. }
  3558. return makeStack(newSize, head);
  3559. };
  3560. Stack.prototype.pop = function() {
  3561. return this.slice(1);
  3562. };
  3563. Stack.prototype.unshift = function(/*...values*/) {
  3564. return this.push.apply(this, arguments);
  3565. };
  3566. Stack.prototype.unshiftAll = function(iter) {
  3567. return this.pushAll(iter);
  3568. };
  3569. Stack.prototype.shift = function() {
  3570. return this.pop.apply(this, arguments);
  3571. };
  3572. Stack.prototype.clear = function() {
  3573. if (this.size === 0) {
  3574. return this;
  3575. }
  3576. if (this.__ownerID) {
  3577. this.size = 0;
  3578. this._head = undefined;
  3579. this.__hash = undefined;
  3580. this.__altered = true;
  3581. return this;
  3582. }
  3583. return emptyStack();
  3584. };
  3585. Stack.prototype.slice = function(begin, end) {
  3586. if (wholeSlice(begin, end, this.size)) {
  3587. return this;
  3588. }
  3589. var resolvedBegin = resolveBegin(begin, this.size);
  3590. var resolvedEnd = resolveEnd(end, this.size);
  3591. if (resolvedEnd !== this.size) {
  3592. // super.slice(begin, end);
  3593. return IndexedCollection.prototype.slice.call(this, begin, end);
  3594. }
  3595. var newSize = this.size - resolvedBegin;
  3596. var head = this._head;
  3597. while (resolvedBegin--) {
  3598. head = head.next;
  3599. }
  3600. if (this.__ownerID) {
  3601. this.size = newSize;
  3602. this._head = head;
  3603. this.__hash = undefined;
  3604. this.__altered = true;
  3605. return this;
  3606. }
  3607. return makeStack(newSize, head);
  3608. };
  3609. // @pragma Mutability
  3610. Stack.prototype.__ensureOwner = function(ownerID) {
  3611. if (ownerID === this.__ownerID) {
  3612. return this;
  3613. }
  3614. if (!ownerID) {
  3615. this.__ownerID = ownerID;
  3616. this.__altered = false;
  3617. return this;
  3618. }
  3619. return makeStack(this.size, this._head, ownerID, this.__hash);
  3620. };
  3621. // @pragma Iteration
  3622. Stack.prototype.__iterate = function(fn, reverse) {
  3623. if (reverse) {
  3624. return this.reverse().__iterate(fn);
  3625. }
  3626. var iterations = 0;
  3627. var node = this._head;
  3628. while (node) {
  3629. if (fn(node.value, iterations++, this) === false) {
  3630. break;
  3631. }
  3632. node = node.next;
  3633. }
  3634. return iterations;
  3635. };
  3636. Stack.prototype.__iterator = function(type, reverse) {
  3637. if (reverse) {
  3638. return this.reverse().__iterator(type);
  3639. }
  3640. var iterations = 0;
  3641. var node = this._head;
  3642. return new Iterator(function() {
  3643. if (node) {
  3644. var value = node.value;
  3645. node = node.next;
  3646. return iteratorValue(type, iterations++, value);
  3647. }
  3648. return iteratorDone();
  3649. });
  3650. };
  3651. function isStack(maybeStack) {
  3652. return !!(maybeStack && maybeStack[IS_STACK_SENTINEL]);
  3653. }
  3654. Stack.isStack = isStack;
  3655. var IS_STACK_SENTINEL = '@@__IMMUTABLE_STACK__@@';
  3656. var StackPrototype = Stack.prototype;
  3657. StackPrototype[IS_STACK_SENTINEL] = true;
  3658. StackPrototype.withMutations = MapPrototype.withMutations;
  3659. StackPrototype.asMutable = MapPrototype.asMutable;
  3660. StackPrototype.asImmutable = MapPrototype.asImmutable;
  3661. StackPrototype.wasAltered = MapPrototype.wasAltered;
  3662. function makeStack(size, head, ownerID, hash) {
  3663. var map = Object.create(StackPrototype);
  3664. map.size = size;
  3665. map._head = head;
  3666. map.__ownerID = ownerID;
  3667. map.__hash = hash;
  3668. map.__altered = false;
  3669. return map;
  3670. }
  3671. var EMPTY_STACK;
  3672. function emptyStack() {
  3673. return EMPTY_STACK || (EMPTY_STACK = makeStack(0));
  3674. }
  3675. /**
  3676. * Contributes additional methods to a constructor
  3677. */
  3678. function mixin(ctor, methods) {
  3679. var keyCopier = function(key ) { ctor.prototype[key] = methods[key]; };
  3680. Object.keys(methods).forEach(keyCopier);
  3681. Object.getOwnPropertySymbols &&
  3682. Object.getOwnPropertySymbols(methods).forEach(keyCopier);
  3683. return ctor;
  3684. }
  3685. Iterable.Iterator = Iterator;
  3686. mixin(Iterable, {
  3687. // ### Conversion to other types
  3688. toArray: function() {
  3689. assertNotInfinite(this.size);
  3690. var array = new Array(this.size || 0);
  3691. this.valueSeq().__iterate(function(v, i) { array[i] = v; });
  3692. return array;
  3693. },
  3694. toIndexedSeq: function() {
  3695. return new ToIndexedSequence(this);
  3696. },
  3697. toJS: function() {
  3698. return this.toSeq().map(
  3699. function(value ) {return value && typeof value.toJS === 'function' ? value.toJS() : value}
  3700. ).__toJS();
  3701. },
  3702. toJSON: function() {
  3703. return this.toSeq().map(
  3704. function(value ) {return value && typeof value.toJSON === 'function' ? value.toJSON() : value}
  3705. ).__toJS();
  3706. },
  3707. toKeyedSeq: function() {
  3708. return new ToKeyedSequence(this, true);
  3709. },
  3710. toMap: function() {
  3711. // Use Late Binding here to solve the circular dependency.
  3712. return Map(this.toKeyedSeq());
  3713. },
  3714. toObject: function() {
  3715. assertNotInfinite(this.size);
  3716. var object = {};
  3717. this.__iterate(function(v, k) { object[k] = v; });
  3718. return object;
  3719. },
  3720. toOrderedMap: function() {
  3721. // Use Late Binding here to solve the circular dependency.
  3722. return OrderedMap(this.toKeyedSeq());
  3723. },
  3724. toOrderedSet: function() {
  3725. // Use Late Binding here to solve the circular dependency.
  3726. return OrderedSet(isKeyed(this) ? this.valueSeq() : this);
  3727. },
  3728. toSet: function() {
  3729. // Use Late Binding here to solve the circular dependency.
  3730. return Set(isKeyed(this) ? this.valueSeq() : this);
  3731. },
  3732. toSetSeq: function() {
  3733. return new ToSetSequence(this);
  3734. },
  3735. toSeq: function() {
  3736. return isIndexed(this) ? this.toIndexedSeq() :
  3737. isKeyed(this) ? this.toKeyedSeq() :
  3738. this.toSetSeq();
  3739. },
  3740. toStack: function() {
  3741. // Use Late Binding here to solve the circular dependency.
  3742. return Stack(isKeyed(this) ? this.valueSeq() : this);
  3743. },
  3744. toList: function() {
  3745. // Use Late Binding here to solve the circular dependency.
  3746. return List(isKeyed(this) ? this.valueSeq() : this);
  3747. },
  3748. // ### Common JavaScript methods and properties
  3749. toString: function() {
  3750. return '[Iterable]';
  3751. },
  3752. __toString: function(head, tail) {
  3753. if (this.size === 0) {
  3754. return head + tail;
  3755. }
  3756. return head + ' ' + this.toSeq().map(this.__toStringMapper).join(', ') + ' ' + tail;
  3757. },
  3758. // ### ES6 Collection methods (ES6 Array and Map)
  3759. concat: function() {var values = SLICE$0.call(arguments, 0);
  3760. return reify(this, concatFactory(this, values));
  3761. },
  3762. includes: function(searchValue) {
  3763. return this.some(function(value ) {return is(value, searchValue)});
  3764. },
  3765. entries: function() {
  3766. return this.__iterator(ITERATE_ENTRIES);
  3767. },
  3768. every: function(predicate, context) {
  3769. assertNotInfinite(this.size);
  3770. var returnValue = true;
  3771. this.__iterate(function(v, k, c) {
  3772. if (!predicate.call(context, v, k, c)) {
  3773. returnValue = false;
  3774. return false;
  3775. }
  3776. });
  3777. return returnValue;
  3778. },
  3779. filter: function(predicate, context) {
  3780. return reify(this, filterFactory(this, predicate, context, true));
  3781. },
  3782. find: function(predicate, context, notSetValue) {
  3783. var entry = this.findEntry(predicate, context);
  3784. return entry ? entry[1] : notSetValue;
  3785. },
  3786. findEntry: function(predicate, context) {
  3787. var found;
  3788. this.__iterate(function(v, k, c) {
  3789. if (predicate.call(context, v, k, c)) {
  3790. found = [k, v];
  3791. return false;
  3792. }
  3793. });
  3794. return found;
  3795. },
  3796. findLastEntry: function(predicate, context) {
  3797. return this.toSeq().reverse().findEntry(predicate, context);
  3798. },
  3799. forEach: function(sideEffect, context) {
  3800. assertNotInfinite(this.size);
  3801. return this.__iterate(context ? sideEffect.bind(context) : sideEffect);
  3802. },
  3803. join: function(separator) {
  3804. assertNotInfinite(this.size);
  3805. separator = separator !== undefined ? '' + separator : ',';
  3806. var joined = '';
  3807. var isFirst = true;
  3808. this.__iterate(function(v ) {
  3809. isFirst ? (isFirst = false) : (joined += separator);
  3810. joined += v !== null && v !== undefined ? v.toString() : '';
  3811. });
  3812. return joined;
  3813. },
  3814. keys: function() {
  3815. return this.__iterator(ITERATE_KEYS);
  3816. },
  3817. map: function(mapper, context) {
  3818. return reify(this, mapFactory(this, mapper, context));
  3819. },
  3820. reduce: function(reducer, initialReduction, context) {
  3821. assertNotInfinite(this.size);
  3822. var reduction;
  3823. var useFirst;
  3824. if (arguments.length < 2) {
  3825. useFirst = true;
  3826. } else {
  3827. reduction = initialReduction;
  3828. }
  3829. this.__iterate(function(v, k, c) {
  3830. if (useFirst) {
  3831. useFirst = false;
  3832. reduction = v;
  3833. } else {
  3834. reduction = reducer.call(context, reduction, v, k, c);
  3835. }
  3836. });
  3837. return reduction;
  3838. },
  3839. reduceRight: function(reducer, initialReduction, context) {
  3840. var reversed = this.toKeyedSeq().reverse();
  3841. return reversed.reduce.apply(reversed, arguments);
  3842. },
  3843. reverse: function() {
  3844. return reify(this, reverseFactory(this, true));
  3845. },
  3846. slice: function(begin, end) {
  3847. return reify(this, sliceFactory(this, begin, end, true));
  3848. },
  3849. some: function(predicate, context) {
  3850. return !this.every(not(predicate), context);
  3851. },
  3852. sort: function(comparator) {
  3853. return reify(this, sortFactory(this, comparator));
  3854. },
  3855. values: function() {
  3856. return this.__iterator(ITERATE_VALUES);
  3857. },
  3858. // ### More sequential methods
  3859. butLast: function() {
  3860. return this.slice(0, -1);
  3861. },
  3862. isEmpty: function() {
  3863. return this.size !== undefined ? this.size === 0 : !this.some(function() {return true});
  3864. },
  3865. count: function(predicate, context) {
  3866. return ensureSize(
  3867. predicate ? this.toSeq().filter(predicate, context) : this
  3868. );
  3869. },
  3870. countBy: function(grouper, context) {
  3871. return countByFactory(this, grouper, context);
  3872. },
  3873. equals: function(other) {
  3874. return deepEqual(this, other);
  3875. },
  3876. entrySeq: function() {
  3877. var iterable = this;
  3878. if (iterable._cache) {
  3879. // We cache as an entries array, so we can just return the cache!
  3880. return new ArraySeq(iterable._cache);
  3881. }
  3882. var entriesSequence = iterable.toSeq().map(entryMapper).toIndexedSeq();
  3883. entriesSequence.fromEntrySeq = function() {return iterable.toSeq()};
  3884. return entriesSequence;
  3885. },
  3886. filterNot: function(predicate, context) {
  3887. return this.filter(not(predicate), context);
  3888. },
  3889. findLast: function(predicate, context, notSetValue) {
  3890. return this.toKeyedSeq().reverse().find(predicate, context, notSetValue);
  3891. },
  3892. first: function() {
  3893. return this.find(returnTrue);
  3894. },
  3895. flatMap: function(mapper, context) {
  3896. return reify(this, flatMapFactory(this, mapper, context));
  3897. },
  3898. flatten: function(depth) {
  3899. return reify(this, flattenFactory(this, depth, true));
  3900. },
  3901. fromEntrySeq: function() {
  3902. return new FromEntriesSequence(this);
  3903. },
  3904. get: function(searchKey, notSetValue) {
  3905. return this.find(function(_, key) {return is(key, searchKey)}, undefined, notSetValue);
  3906. },
  3907. getIn: function(searchKeyPath, notSetValue) {
  3908. var nested = this;
  3909. // Note: in an ES6 environment, we would prefer:
  3910. // for (var key of searchKeyPath) {
  3911. var iter = forceIterator(searchKeyPath);
  3912. var step;
  3913. while (!(step = iter.next()).done) {
  3914. var key = step.value;
  3915. nested = nested && nested.get ? nested.get(key, NOT_SET) : NOT_SET;
  3916. if (nested === NOT_SET) {
  3917. return notSetValue;
  3918. }
  3919. }
  3920. return nested;
  3921. },
  3922. groupBy: function(grouper, context) {
  3923. return groupByFactory(this, grouper, context);
  3924. },
  3925. has: function(searchKey) {
  3926. return this.get(searchKey, NOT_SET) !== NOT_SET;
  3927. },
  3928. hasIn: function(searchKeyPath) {
  3929. return this.getIn(searchKeyPath, NOT_SET) !== NOT_SET;
  3930. },
  3931. isSubset: function(iter) {
  3932. iter = typeof iter.includes === 'function' ? iter : Iterable(iter);
  3933. return this.every(function(value ) {return iter.includes(value)});
  3934. },
  3935. isSuperset: function(iter) {
  3936. iter = typeof iter.isSubset === 'function' ? iter : Iterable(iter);
  3937. return iter.isSubset(this);
  3938. },
  3939. keySeq: function() {
  3940. return this.toSeq().map(keyMapper).toIndexedSeq();
  3941. },
  3942. last: function() {
  3943. return this.toSeq().reverse().first();
  3944. },
  3945. max: function(comparator) {
  3946. return maxFactory(this, comparator);
  3947. },
  3948. maxBy: function(mapper, comparator) {
  3949. return maxFactory(this, comparator, mapper);
  3950. },
  3951. min: function(comparator) {
  3952. return maxFactory(this, comparator ? neg(comparator) : defaultNegComparator);
  3953. },
  3954. minBy: function(mapper, comparator) {
  3955. return maxFactory(this, comparator ? neg(comparator) : defaultNegComparator, mapper);
  3956. },
  3957. rest: function() {
  3958. return this.slice(1);
  3959. },
  3960. skip: function(amount) {
  3961. return this.slice(Math.max(0, amount));
  3962. },
  3963. skipLast: function(amount) {
  3964. return reify(this, this.toSeq().reverse().skip(amount).reverse());
  3965. },
  3966. skipWhile: function(predicate, context) {
  3967. return reify(this, skipWhileFactory(this, predicate, context, true));
  3968. },
  3969. skipUntil: function(predicate, context) {
  3970. return this.skipWhile(not(predicate), context);
  3971. },
  3972. sortBy: function(mapper, comparator) {
  3973. return reify(this, sortFactory(this, comparator, mapper));
  3974. },
  3975. take: function(amount) {
  3976. return this.slice(0, Math.max(0, amount));
  3977. },
  3978. takeLast: function(amount) {
  3979. return reify(this, this.toSeq().reverse().take(amount).reverse());
  3980. },
  3981. takeWhile: function(predicate, context) {
  3982. return reify(this, takeWhileFactory(this, predicate, context));
  3983. },
  3984. takeUntil: function(predicate, context) {
  3985. return this.takeWhile(not(predicate), context);
  3986. },
  3987. valueSeq: function() {
  3988. return this.toIndexedSeq();
  3989. },
  3990. // ### Hashable Object
  3991. hashCode: function() {
  3992. return this.__hash || (this.__hash = hashIterable(this));
  3993. }
  3994. // ### Internal
  3995. // abstract __iterate(fn, reverse)
  3996. // abstract __iterator(type, reverse)
  3997. });
  3998. // var IS_ITERABLE_SENTINEL = '@@__IMMUTABLE_ITERABLE__@@';
  3999. // var IS_KEYED_SENTINEL = '@@__IMMUTABLE_KEYED__@@';
  4000. // var IS_INDEXED_SENTINEL = '@@__IMMUTABLE_INDEXED__@@';
  4001. // var IS_ORDERED_SENTINEL = '@@__IMMUTABLE_ORDERED__@@';
  4002. var IterablePrototype = Iterable.prototype;
  4003. IterablePrototype[IS_ITERABLE_SENTINEL] = true;
  4004. IterablePrototype[ITERATOR_SYMBOL] = IterablePrototype.values;
  4005. IterablePrototype.__toJS = IterablePrototype.toArray;
  4006. IterablePrototype.__toStringMapper = quoteString;
  4007. IterablePrototype.inspect =
  4008. IterablePrototype.toSource = function() { return this.toString(); };
  4009. IterablePrototype.chain = IterablePrototype.flatMap;
  4010. IterablePrototype.contains = IterablePrototype.includes;
  4011. // Temporary warning about using length
  4012. (function () {
  4013. try {
  4014. Object.defineProperty(IterablePrototype, 'length', {
  4015. get: function () {
  4016. if (!Iterable.noLengthWarning) {
  4017. var stack;
  4018. try {
  4019. throw new Error();
  4020. } catch (error) {
  4021. stack = error.stack;
  4022. }
  4023. if (stack.indexOf('_wrapObject') === -1) {
  4024. console && console.warn && console.warn(
  4025. 'iterable.length has been deprecated, '+
  4026. 'use iterable.size or iterable.count(). '+
  4027. 'This warning will become a silent error in a future version. ' +
  4028. stack
  4029. );
  4030. return this.size;
  4031. }
  4032. }
  4033. }
  4034. });
  4035. } catch (e) {}
  4036. })();
  4037. mixin(KeyedIterable, {
  4038. // ### More sequential methods
  4039. flip: function() {
  4040. return reify(this, flipFactory(this));
  4041. },
  4042. findKey: function(predicate, context) {
  4043. var entry = this.findEntry(predicate, context);
  4044. return entry && entry[0];
  4045. },
  4046. findLastKey: function(predicate, context) {
  4047. return this.toSeq().reverse().findKey(predicate, context);
  4048. },
  4049. keyOf: function(searchValue) {
  4050. return this.findKey(function(value ) {return is(value, searchValue)});
  4051. },
  4052. lastKeyOf: function(searchValue) {
  4053. return this.findLastKey(function(value ) {return is(value, searchValue)});
  4054. },
  4055. mapEntries: function(mapper, context) {var this$0 = this;
  4056. var iterations = 0;
  4057. return reify(this,
  4058. this.toSeq().map(
  4059. function(v, k) {return mapper.call(context, [k, v], iterations++, this$0)}
  4060. ).fromEntrySeq()
  4061. );
  4062. },
  4063. mapKeys: function(mapper, context) {var this$0 = this;
  4064. return reify(this,
  4065. this.toSeq().flip().map(
  4066. function(k, v) {return mapper.call(context, k, v, this$0)}
  4067. ).flip()
  4068. );
  4069. }
  4070. });
  4071. var KeyedIterablePrototype = KeyedIterable.prototype;
  4072. KeyedIterablePrototype[IS_KEYED_SENTINEL] = true;
  4073. KeyedIterablePrototype[ITERATOR_SYMBOL] = IterablePrototype.entries;
  4074. KeyedIterablePrototype.__toJS = IterablePrototype.toObject;
  4075. KeyedIterablePrototype.__toStringMapper = function(v, k) {return JSON.stringify(k) + ': ' + quoteString(v)};
  4076. mixin(IndexedIterable, {
  4077. // ### Conversion to other types
  4078. toKeyedSeq: function() {
  4079. return new ToKeyedSequence(this, false);
  4080. },
  4081. // ### ES6 Collection methods (ES6 Array and Map)
  4082. filter: function(predicate, context) {
  4083. return reify(this, filterFactory(this, predicate, context, false));
  4084. },
  4085. findIndex: function(predicate, context) {
  4086. var entry = this.findEntry(predicate, context);
  4087. return entry ? entry[0] : -1;
  4088. },
  4089. indexOf: function(searchValue) {
  4090. var key = this.toKeyedSeq().keyOf(searchValue);
  4091. return key === undefined ? -1 : key;
  4092. },
  4093. lastIndexOf: function(searchValue) {
  4094. var key = this.toKeyedSeq().reverse().keyOf(searchValue);
  4095. return key === undefined ? -1 : key;
  4096. // var index =
  4097. // return this.toSeq().reverse().indexOf(searchValue);
  4098. },
  4099. reverse: function() {
  4100. return reify(this, reverseFactory(this, false));
  4101. },
  4102. slice: function(begin, end) {
  4103. return reify(this, sliceFactory(this, begin, end, false));
  4104. },
  4105. splice: function(index, removeNum /*, ...values*/) {
  4106. var numArgs = arguments.length;
  4107. removeNum = Math.max(removeNum | 0, 0);
  4108. if (numArgs === 0 || (numArgs === 2 && !removeNum)) {
  4109. return this;
  4110. }
  4111. // If index is negative, it should resolve relative to the size of the
  4112. // collection. However size may be expensive to compute if not cached, so
  4113. // only call count() if the number is in fact negative.
  4114. index = resolveBegin(index, index < 0 ? this.count() : this.size);
  4115. var spliced = this.slice(0, index);
  4116. return reify(
  4117. this,
  4118. numArgs === 1 ?
  4119. spliced :
  4120. spliced.concat(arrCopy(arguments, 2), this.slice(index + removeNum))
  4121. );
  4122. },
  4123. // ### More collection methods
  4124. findLastIndex: function(predicate, context) {
  4125. var key = this.toKeyedSeq().findLastKey(predicate, context);
  4126. return key === undefined ? -1 : key;
  4127. },
  4128. first: function() {
  4129. return this.get(0);
  4130. },
  4131. flatten: function(depth) {
  4132. return reify(this, flattenFactory(this, depth, false));
  4133. },
  4134. get: function(index, notSetValue) {
  4135. index = wrapIndex(this, index);
  4136. return (index < 0 || (this.size === Infinity ||
  4137. (this.size !== undefined && index > this.size))) ?
  4138. notSetValue :
  4139. this.find(function(_, key) {return key === index}, undefined, notSetValue);
  4140. },
  4141. has: function(index) {
  4142. index = wrapIndex(this, index);
  4143. return index >= 0 && (this.size !== undefined ?
  4144. this.size === Infinity || index < this.size :
  4145. this.indexOf(index) !== -1
  4146. );
  4147. },
  4148. interpose: function(separator) {
  4149. return reify(this, interposeFactory(this, separator));
  4150. },
  4151. interleave: function(/*...iterables*/) {
  4152. var iterables = [this].concat(arrCopy(arguments));
  4153. var zipped = zipWithFactory(this.toSeq(), IndexedSeq.of, iterables);
  4154. var interleaved = zipped.flatten(true);
  4155. if (zipped.size) {
  4156. interleaved.size = zipped.size * iterables.length;
  4157. }
  4158. return reify(this, interleaved);
  4159. },
  4160. last: function() {
  4161. return this.get(-1);
  4162. },
  4163. skipWhile: function(predicate, context) {
  4164. return reify(this, skipWhileFactory(this, predicate, context, false));
  4165. },
  4166. zip: function(/*, ...iterables */) {
  4167. var iterables = [this].concat(arrCopy(arguments));
  4168. return reify(this, zipWithFactory(this, defaultZipper, iterables));
  4169. },
  4170. zipWith: function(zipper/*, ...iterables */) {
  4171. var iterables = arrCopy(arguments);
  4172. iterables[0] = this;
  4173. return reify(this, zipWithFactory(this, zipper, iterables));
  4174. }
  4175. });
  4176. IndexedIterable.prototype[IS_INDEXED_SENTINEL] = true;
  4177. IndexedIterable.prototype[IS_ORDERED_SENTINEL] = true;
  4178. mixin(SetIterable, {
  4179. // ### ES6 Collection methods (ES6 Array and Map)
  4180. get: function(value, notSetValue) {
  4181. return this.has(value) ? value : notSetValue;
  4182. },
  4183. includes: function(value) {
  4184. return this.has(value);
  4185. },
  4186. // ### More sequential methods
  4187. keySeq: function() {
  4188. return this.valueSeq();
  4189. }
  4190. });
  4191. SetIterable.prototype.has = IterablePrototype.includes;
  4192. // Mixin subclasses
  4193. mixin(KeyedSeq, KeyedIterable.prototype);
  4194. mixin(IndexedSeq, IndexedIterable.prototype);
  4195. mixin(SetSeq, SetIterable.prototype);
  4196. mixin(KeyedCollection, KeyedIterable.prototype);
  4197. mixin(IndexedCollection, IndexedIterable.prototype);
  4198. mixin(SetCollection, SetIterable.prototype);
  4199. // #pragma Helper functions
  4200. function keyMapper(v, k) {
  4201. return k;
  4202. }
  4203. function entryMapper(v, k) {
  4204. return [k, v];
  4205. }
  4206. function not(predicate) {
  4207. return function() {
  4208. return !predicate.apply(this, arguments);
  4209. }
  4210. }
  4211. function neg(predicate) {
  4212. return function() {
  4213. return -predicate.apply(this, arguments);
  4214. }
  4215. }
  4216. function quoteString(value) {
  4217. return typeof value === 'string' ? JSON.stringify(value) : value;
  4218. }
  4219. function defaultZipper() {
  4220. return arrCopy(arguments);
  4221. }
  4222. function defaultNegComparator(a, b) {
  4223. return a < b ? 1 : a > b ? -1 : 0;
  4224. }
  4225. function hashIterable(iterable) {
  4226. if (iterable.size === Infinity) {
  4227. return 0;
  4228. }
  4229. var ordered = isOrdered(iterable);
  4230. var keyed = isKeyed(iterable);
  4231. var h = ordered ? 1 : 0;
  4232. var size = iterable.__iterate(
  4233. keyed ?
  4234. ordered ?
  4235. function(v, k) { h = 31 * h + hashMerge(hash(v), hash(k)) | 0; } :
  4236. function(v, k) { h = h + hashMerge(hash(v), hash(k)) | 0; } :
  4237. ordered ?
  4238. function(v ) { h = 31 * h + hash(v) | 0; } :
  4239. function(v ) { h = h + hash(v) | 0; }
  4240. );
  4241. return murmurHashOfSize(size, h);
  4242. }
  4243. function murmurHashOfSize(size, h) {
  4244. h = imul(h, 0xCC9E2D51);
  4245. h = imul(h << 15 | h >>> -15, 0x1B873593);
  4246. h = imul(h << 13 | h >>> -13, 5);
  4247. h = (h + 0xE6546B64 | 0) ^ size;
  4248. h = imul(h ^ h >>> 16, 0x85EBCA6B);
  4249. h = imul(h ^ h >>> 13, 0xC2B2AE35);
  4250. h = smi(h ^ h >>> 16);
  4251. return h;
  4252. }
  4253. function hashMerge(a, b) {
  4254. return a ^ b + 0x9E3779B9 + (a << 6) + (a >> 2) | 0; // int
  4255. }
  4256. var Immutable = {
  4257. Iterable: Iterable,
  4258. Seq: Seq,
  4259. Collection: Collection,
  4260. Map: Map,
  4261. OrderedMap: OrderedMap,
  4262. List: List,
  4263. Stack: Stack,
  4264. Set: Set,
  4265. OrderedSet: OrderedSet,
  4266. Record: Record,
  4267. Range: Range,
  4268. Repeat: Repeat,
  4269. is: is,
  4270. fromJS: fromJS
  4271. };
  4272. return Immutable;
  4273. }));
  4274. });
  4275. var OrderedMap = immutable.OrderedMap;
  4276. var BlockMapBuilder = {
  4277. createFromArray: function createFromArray(blocks) {
  4278. return OrderedMap(blocks.map(function (block) {
  4279. return [block.getKey(), block];
  4280. }));
  4281. }
  4282. };
  4283. var BlockMapBuilder_1 = BlockMapBuilder;
  4284. function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  4285. function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }
  4286. function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
  4287. var Map$1 = immutable.Map,
  4288. OrderedSet = immutable.OrderedSet,
  4289. Record = immutable.Record;
  4290. // Immutable.map is typed such that the value for every key in the map
  4291. // must be the same type
  4292. var EMPTY_SET = OrderedSet();
  4293. var defaultRecord = {
  4294. style: EMPTY_SET,
  4295. entity: null
  4296. };
  4297. var CharacterMetadataRecord = Record(defaultRecord);
  4298. var CharacterMetadata = function (_CharacterMetadataRec) {
  4299. _inherits(CharacterMetadata, _CharacterMetadataRec);
  4300. function CharacterMetadata() {
  4301. _classCallCheck(this, CharacterMetadata);
  4302. return _possibleConstructorReturn(this, _CharacterMetadataRec.apply(this, arguments));
  4303. }
  4304. CharacterMetadata.prototype.getStyle = function getStyle() {
  4305. return this.get('style');
  4306. };
  4307. CharacterMetadata.prototype.getEntity = function getEntity() {
  4308. return this.get('entity');
  4309. };
  4310. CharacterMetadata.prototype.hasStyle = function hasStyle(style) {
  4311. return this.getStyle().includes(style);
  4312. };
  4313. CharacterMetadata.applyStyle = function applyStyle(record, style) {
  4314. var withStyle = record.set('style', record.getStyle().add(style));
  4315. return CharacterMetadata.create(withStyle);
  4316. };
  4317. CharacterMetadata.removeStyle = function removeStyle(record, style) {
  4318. var withoutStyle = record.set('style', record.getStyle().remove(style));
  4319. return CharacterMetadata.create(withoutStyle);
  4320. };
  4321. CharacterMetadata.applyEntity = function applyEntity(record, entityKey) {
  4322. var withEntity = record.getEntity() === entityKey ? record : record.set('entity', entityKey);
  4323. return CharacterMetadata.create(withEntity);
  4324. };
  4325. /**
  4326. * Use this function instead of the `CharacterMetadata` constructor.
  4327. * Since most content generally uses only a very small number of
  4328. * style/entity permutations, we can reuse these objects as often as
  4329. * possible.
  4330. */
  4331. CharacterMetadata.create = function create(config) {
  4332. if (!config) {
  4333. return EMPTY;
  4334. }
  4335. var defaultConfig = {
  4336. style: EMPTY_SET,
  4337. entity: null
  4338. };
  4339. // Fill in unspecified properties, if necessary.
  4340. var configMap = Map$1(defaultConfig).merge(config);
  4341. var existing = pool.get(configMap);
  4342. if (existing) {
  4343. return existing;
  4344. }
  4345. var newCharacter = new CharacterMetadata(configMap);
  4346. pool = pool.set(configMap, newCharacter);
  4347. return newCharacter;
  4348. };
  4349. return CharacterMetadata;
  4350. }(CharacterMetadataRecord);
  4351. var EMPTY = new CharacterMetadata();
  4352. var pool = Map$1([[Map$1(defaultRecord), EMPTY]]);
  4353. CharacterMetadata.EMPTY = EMPTY;
  4354. var CharacterMetadata_1 = CharacterMetadata;
  4355. /**
  4356. * Copyright (c) 2013-present, Facebook, Inc.
  4357. * All rights reserved.
  4358. *
  4359. * This source code is licensed under the BSD-style license found in the
  4360. * LICENSE file in the root directory of this source tree. An additional grant
  4361. * of patent rights can be found in the PATENTS file in the same directory.
  4362. *
  4363. * @providesModule findRangesImmutable
  4364. * @format
  4365. *
  4366. */
  4367. /**
  4368. * Search through an array to find contiguous stretches of elements that
  4369. * match a specified filter function.
  4370. *
  4371. * When ranges are found, execute a specified `found` function to supply
  4372. * the values to the caller.
  4373. */
  4374. function findRangesImmutable(haystack, areEqualFn, filterFn, foundFn) {
  4375. if (!haystack.size) {
  4376. return;
  4377. }
  4378. var cursor = 0;
  4379. haystack.reduce(function (value, nextValue, nextIndex) {
  4380. if (!areEqualFn(value, nextValue)) {
  4381. if (filterFn(value)) {
  4382. foundFn(cursor, nextIndex);
  4383. }
  4384. cursor = nextIndex;
  4385. }
  4386. return nextValue;
  4387. });
  4388. filterFn(haystack.last()) && foundFn(cursor, haystack.count());
  4389. }
  4390. var findRangesImmutable_1 = findRangesImmutable;
  4391. function _classCallCheck$1(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  4392. function _possibleConstructorReturn$1(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }
  4393. function _inherits$1(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
  4394. var List = immutable.List,
  4395. Map$2 = immutable.Map,
  4396. OrderedSet$1 = immutable.OrderedSet,
  4397. Record$1 = immutable.Record,
  4398. Repeat = immutable.Repeat;
  4399. var EMPTY_SET$1 = OrderedSet$1();
  4400. var defaultRecord$1 = {
  4401. key: '',
  4402. type: 'unstyled',
  4403. text: '',
  4404. characterList: List(),
  4405. depth: 0,
  4406. data: Map$2()
  4407. };
  4408. var ContentBlockRecord = Record$1(defaultRecord$1);
  4409. var decorateCharacterList = function decorateCharacterList(config) {
  4410. if (!config) {
  4411. return config;
  4412. }
  4413. var characterList = config.characterList,
  4414. text = config.text;
  4415. if (text && !characterList) {
  4416. config.characterList = List(Repeat(CharacterMetadata_1.EMPTY, text.length));
  4417. }
  4418. return config;
  4419. };
  4420. var ContentBlock = function (_ContentBlockRecord) {
  4421. _inherits$1(ContentBlock, _ContentBlockRecord);
  4422. function ContentBlock(config) {
  4423. _classCallCheck$1(this, ContentBlock);
  4424. return _possibleConstructorReturn$1(this, _ContentBlockRecord.call(this, decorateCharacterList(config)));
  4425. }
  4426. ContentBlock.prototype.getKey = function getKey() {
  4427. return this.get('key');
  4428. };
  4429. ContentBlock.prototype.getType = function getType() {
  4430. return this.get('type');
  4431. };
  4432. ContentBlock.prototype.getText = function getText() {
  4433. return this.get('text');
  4434. };
  4435. ContentBlock.prototype.getCharacterList = function getCharacterList() {
  4436. return this.get('characterList');
  4437. };
  4438. ContentBlock.prototype.getLength = function getLength() {
  4439. return this.getText().length;
  4440. };
  4441. ContentBlock.prototype.getDepth = function getDepth() {
  4442. return this.get('depth');
  4443. };
  4444. ContentBlock.prototype.getData = function getData() {
  4445. return this.get('data');
  4446. };
  4447. ContentBlock.prototype.getInlineStyleAt = function getInlineStyleAt(offset) {
  4448. var character = this.getCharacterList().get(offset);
  4449. return character ? character.getStyle() : EMPTY_SET$1;
  4450. };
  4451. ContentBlock.prototype.getEntityAt = function getEntityAt(offset) {
  4452. var character = this.getCharacterList().get(offset);
  4453. return character ? character.getEntity() : null;
  4454. };
  4455. /**
  4456. * Execute a callback for every contiguous range of styles within the block.
  4457. */
  4458. ContentBlock.prototype.findStyleRanges = function findStyleRanges(filterFn, callback) {
  4459. findRangesImmutable_1(this.getCharacterList(), haveEqualStyle, filterFn, callback);
  4460. };
  4461. /**
  4462. * Execute a callback for every contiguous range of entities within the block.
  4463. */
  4464. ContentBlock.prototype.findEntityRanges = function findEntityRanges(filterFn, callback) {
  4465. findRangesImmutable_1(this.getCharacterList(), haveEqualEntity, filterFn, callback);
  4466. };
  4467. return ContentBlock;
  4468. }(ContentBlockRecord);
  4469. function haveEqualStyle(charA, charB) {
  4470. return charA.getStyle() === charB.getStyle();
  4471. }
  4472. function haveEqualEntity(charA, charB) {
  4473. return charA.getEntity() === charB.getEntity();
  4474. }
  4475. var ContentBlock_1 = ContentBlock;
  4476. function _classCallCheck$2(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  4477. function _possibleConstructorReturn$2(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }
  4478. function _inherits$2(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
  4479. var List$1 = immutable.List,
  4480. Map$3 = immutable.Map,
  4481. OrderedSet$2 = immutable.OrderedSet,
  4482. Record$2 = immutable.Record,
  4483. Repeat$1 = immutable.Repeat;
  4484. var EMPTY_SET$2 = OrderedSet$2();
  4485. var defaultRecord$2 = {
  4486. parent: null,
  4487. characterList: List$1(),
  4488. data: Map$3(),
  4489. depth: 0,
  4490. key: '',
  4491. text: '',
  4492. type: 'unstyled',
  4493. children: List$1(),
  4494. prevSibling: null,
  4495. nextSibling: null
  4496. };
  4497. var haveEqualStyle$1 = function haveEqualStyle(charA, charB) {
  4498. return charA.getStyle() === charB.getStyle();
  4499. };
  4500. var haveEqualEntity$1 = function haveEqualEntity(charA, charB) {
  4501. return charA.getEntity() === charB.getEntity();
  4502. };
  4503. var decorateCharacterList$1 = function decorateCharacterList(config) {
  4504. if (!config) {
  4505. return config;
  4506. }
  4507. var characterList = config.characterList,
  4508. text = config.text;
  4509. if (text && !characterList) {
  4510. config.characterList = List$1(Repeat$1(CharacterMetadata_1.EMPTY, text.length));
  4511. }
  4512. return config;
  4513. };
  4514. var ContentBlockNode = function (_Record) {
  4515. _inherits$2(ContentBlockNode, _Record);
  4516. function ContentBlockNode() {
  4517. var props = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : defaultRecord$2;
  4518. _classCallCheck$2(this, ContentBlockNode);
  4519. return _possibleConstructorReturn$2(this, _Record.call(this, decorateCharacterList$1(props)));
  4520. }
  4521. ContentBlockNode.prototype.getKey = function getKey() {
  4522. return this.get('key');
  4523. };
  4524. ContentBlockNode.prototype.getType = function getType() {
  4525. return this.get('type');
  4526. };
  4527. ContentBlockNode.prototype.getText = function getText() {
  4528. return this.get('text');
  4529. };
  4530. ContentBlockNode.prototype.getCharacterList = function getCharacterList() {
  4531. return this.get('characterList');
  4532. };
  4533. ContentBlockNode.prototype.getLength = function getLength() {
  4534. return this.getText().length;
  4535. };
  4536. ContentBlockNode.prototype.getDepth = function getDepth() {
  4537. return this.get('depth');
  4538. };
  4539. ContentBlockNode.prototype.getData = function getData() {
  4540. return this.get('data');
  4541. };
  4542. ContentBlockNode.prototype.getInlineStyleAt = function getInlineStyleAt(offset) {
  4543. var character = this.getCharacterList().get(offset);
  4544. return character ? character.getStyle() : EMPTY_SET$2;
  4545. };
  4546. ContentBlockNode.prototype.getEntityAt = function getEntityAt(offset) {
  4547. var character = this.getCharacterList().get(offset);
  4548. return character ? character.getEntity() : null;
  4549. };
  4550. ContentBlockNode.prototype.getChildKeys = function getChildKeys() {
  4551. return this.get('children');
  4552. };
  4553. ContentBlockNode.prototype.getParentKey = function getParentKey() {
  4554. return this.get('parent');
  4555. };
  4556. ContentBlockNode.prototype.getPrevSiblingKey = function getPrevSiblingKey() {
  4557. return this.get('prevSibling');
  4558. };
  4559. ContentBlockNode.prototype.getNextSiblingKey = function getNextSiblingKey() {
  4560. return this.get('nextSibling');
  4561. };
  4562. ContentBlockNode.prototype.findStyleRanges = function findStyleRanges(filterFn, callback) {
  4563. findRangesImmutable_1(this.getCharacterList(), haveEqualStyle$1, filterFn, callback);
  4564. };
  4565. ContentBlockNode.prototype.findEntityRanges = function findEntityRanges(filterFn, callback) {
  4566. findRangesImmutable_1(this.getCharacterList(), haveEqualEntity$1, filterFn, callback);
  4567. };
  4568. return ContentBlockNode;
  4569. }(Record$2(defaultRecord$2));
  4570. var ContentBlockNode_1 = ContentBlockNode;
  4571. /**
  4572. * Copyright 2013-present, Facebook, Inc.
  4573. * All rights reserved.
  4574. *
  4575. * This source code is licensed under the BSD-style license found in the
  4576. * LICENSE file in the root directory of this source tree. An additional grant
  4577. * of patent rights can be found in the PATENTS file in the same directory.
  4578. *
  4579. * @providesModule DraftFeatureFlags-core
  4580. * @format
  4581. *
  4582. */
  4583. var DraftFeatureFlags = {
  4584. draft_killswitch_allow_nontextnodes: false,
  4585. draft_segmented_entities_behavior: false,
  4586. draft_handlebeforeinput_composed_text: false,
  4587. draft_tree_data_support: false
  4588. };
  4589. var DraftFeatureFlagsCore = DraftFeatureFlags;
  4590. var DraftFeatureFlags_1 = DraftFeatureFlagsCore;
  4591. var Map$4 = immutable.Map;
  4592. var ContentStateInlineStyle = {
  4593. add: function add(contentState, selectionState, inlineStyle) {
  4594. return modifyInlineStyle(contentState, selectionState, inlineStyle, true);
  4595. },
  4596. remove: function remove(contentState, selectionState, inlineStyle) {
  4597. return modifyInlineStyle(contentState, selectionState, inlineStyle, false);
  4598. }
  4599. };
  4600. function modifyInlineStyle(contentState, selectionState, inlineStyle, addOrRemove) {
  4601. var blockMap = contentState.getBlockMap();
  4602. var startKey = selectionState.getStartKey();
  4603. var startOffset = selectionState.getStartOffset();
  4604. var endKey = selectionState.getEndKey();
  4605. var endOffset = selectionState.getEndOffset();
  4606. var newBlocks = blockMap.skipUntil(function (_, k) {
  4607. return k === startKey;
  4608. }).takeUntil(function (_, k) {
  4609. return k === endKey;
  4610. }).concat(Map$4([[endKey, blockMap.get(endKey)]])).map(function (block, blockKey) {
  4611. var sliceStart;
  4612. var sliceEnd;
  4613. if (startKey === endKey) {
  4614. sliceStart = startOffset;
  4615. sliceEnd = endOffset;
  4616. } else {
  4617. sliceStart = blockKey === startKey ? startOffset : 0;
  4618. sliceEnd = blockKey === endKey ? endOffset : block.getLength();
  4619. }
  4620. var chars = block.getCharacterList();
  4621. var current;
  4622. while (sliceStart < sliceEnd) {
  4623. current = chars.get(sliceStart);
  4624. chars = chars.set(sliceStart, addOrRemove ? CharacterMetadata_1.applyStyle(current, inlineStyle) : CharacterMetadata_1.removeStyle(current, inlineStyle));
  4625. sliceStart++;
  4626. }
  4627. return block.set('characterList', chars);
  4628. });
  4629. return contentState.merge({
  4630. blockMap: blockMap.merge(newBlocks),
  4631. selectionBefore: selectionState,
  4632. selectionAfter: selectionState
  4633. });
  4634. }
  4635. var ContentStateInlineStyle_1 = ContentStateInlineStyle;
  4636. function applyEntityToContentBlock(contentBlock, start, end, entityKey) {
  4637. var characterList = contentBlock.getCharacterList();
  4638. while (start < end) {
  4639. characterList = characterList.set(start, CharacterMetadata_1.applyEntity(characterList.get(start), entityKey));
  4640. start++;
  4641. }
  4642. return contentBlock.set('characterList', characterList);
  4643. }
  4644. var applyEntityToContentBlock_1 = applyEntityToContentBlock;
  4645. function applyEntityToContentState(contentState, selectionState, entityKey) {
  4646. var blockMap = contentState.getBlockMap();
  4647. var startKey = selectionState.getStartKey();
  4648. var startOffset = selectionState.getStartOffset();
  4649. var endKey = selectionState.getEndKey();
  4650. var endOffset = selectionState.getEndOffset();
  4651. var newBlocks = blockMap.skipUntil(function (_, k) {
  4652. return k === startKey;
  4653. }).takeUntil(function (_, k) {
  4654. return k === endKey;
  4655. }).toOrderedMap().merge(immutable.OrderedMap([[endKey, blockMap.get(endKey)]])).map(function (block, blockKey) {
  4656. var sliceStart = blockKey === startKey ? startOffset : 0;
  4657. var sliceEnd = blockKey === endKey ? endOffset : block.getLength();
  4658. return applyEntityToContentBlock_1(block, sliceStart, sliceEnd, entityKey);
  4659. });
  4660. return contentState.merge({
  4661. blockMap: blockMap.merge(newBlocks),
  4662. selectionBefore: selectionState,
  4663. selectionAfter: selectionState
  4664. });
  4665. }
  4666. var applyEntityToContentState_1 = applyEntityToContentState;
  4667. /**
  4668. * Copyright (c) 2013-present, Facebook, Inc.
  4669. * All rights reserved.
  4670. *
  4671. * This source code is licensed under the BSD-style license found in the
  4672. * LICENSE file in the root directory of this source tree. An additional grant
  4673. * of patent rights can be found in the PATENTS file in the same directory.
  4674. *
  4675. * @providesModule DraftEntitySegments
  4676. * @format
  4677. *
  4678. */
  4679. /**
  4680. * Identify the range to delete from a segmented entity.
  4681. *
  4682. * Rules:
  4683. *
  4684. * Example: 'John F. Kennedy'
  4685. *
  4686. * - Deletion from within any non-whitespace (i.e. ['John', 'F.', 'Kennedy'])
  4687. * will return the range of that text.
  4688. *
  4689. * 'John F. Kennedy' -> 'John F.'
  4690. * ^
  4691. *
  4692. * - Forward deletion of whitespace will remove the following section:
  4693. *
  4694. * 'John F. Kennedy' -> 'John Kennedy'
  4695. * ^
  4696. *
  4697. * - Backward deletion of whitespace will remove the previous section:
  4698. *
  4699. * 'John F. Kennedy' -> 'F. Kennedy'
  4700. * ^
  4701. */
  4702. var DraftEntitySegments = {
  4703. getRemovalRange: function getRemovalRange(selectionStart, selectionEnd, text, entityStart, direction) {
  4704. var segments = text.split(' ');
  4705. segments = segments.map(function ( /*string*/segment, /*number*/ii) {
  4706. if (direction === 'forward') {
  4707. if (ii > 0) {
  4708. return ' ' + segment;
  4709. }
  4710. } else if (ii < segments.length - 1) {
  4711. return segment + ' ';
  4712. }
  4713. return segment;
  4714. });
  4715. var segmentStart = entityStart;
  4716. var segmentEnd;
  4717. var segment;
  4718. var removalStart = null;
  4719. var removalEnd = null;
  4720. for (var jj = 0; jj < segments.length; jj++) {
  4721. segment = segments[jj];
  4722. segmentEnd = segmentStart + segment.length;
  4723. // Our selection overlaps this segment.
  4724. if (selectionStart < segmentEnd && segmentStart < selectionEnd) {
  4725. if (removalStart !== null) {
  4726. removalEnd = segmentEnd;
  4727. } else {
  4728. removalStart = segmentStart;
  4729. removalEnd = segmentEnd;
  4730. }
  4731. } else if (removalStart !== null) {
  4732. break;
  4733. }
  4734. segmentStart = segmentEnd;
  4735. }
  4736. var entityEnd = entityStart + text.length;
  4737. var atStart = removalStart === entityStart;
  4738. var atEnd = removalEnd === entityEnd;
  4739. if (!atStart && atEnd || atStart && !atEnd) {
  4740. if (direction === 'forward') {
  4741. if (removalEnd !== entityEnd) {
  4742. removalEnd++;
  4743. }
  4744. } else if (removalStart !== entityStart) {
  4745. removalStart--;
  4746. }
  4747. }
  4748. return {
  4749. start: removalStart,
  4750. end: removalEnd
  4751. };
  4752. }
  4753. };
  4754. var DraftEntitySegments_1 = DraftEntitySegments;
  4755. /**
  4756. * Copyright (c) 2013-present, Facebook, Inc.
  4757. *
  4758. * This source code is licensed under the MIT license found in the
  4759. * LICENSE file in the root directory of this source tree.
  4760. *
  4761. */
  4762. /**
  4763. * Use invariant() to assert state which your program assumes to be true.
  4764. *
  4765. * Provide sprintf-style format (only %s is supported) and arguments
  4766. * to provide information about what broke and what you were
  4767. * expecting.
  4768. *
  4769. * The invariant message will be stripped in production, but the invariant
  4770. * will remain to ensure logic does not differ in production.
  4771. */
  4772. var validateFormat = function validateFormat(format) {};
  4773. if (process.env.NODE_ENV !== 'production') {
  4774. validateFormat = function validateFormat(format) {
  4775. if (format === undefined) {
  4776. throw new Error('invariant requires an error message argument');
  4777. }
  4778. };
  4779. }
  4780. function invariant(condition, format, a, b, c, d, e, f) {
  4781. validateFormat(format);
  4782. if (!condition) {
  4783. var error;
  4784. if (format === undefined) {
  4785. error = new Error('Minified exception occurred; use the non-minified dev environment ' + 'for the full error message and additional helpful warnings.');
  4786. } else {
  4787. var args = [a, b, c, d, e, f];
  4788. var argIndex = 0;
  4789. error = new Error(format.replace(/%s/g, function () {
  4790. return args[argIndex++];
  4791. }));
  4792. error.name = 'Invariant Violation';
  4793. }
  4794. error.framesToPop = 1; // we don't care about invariant's own frame
  4795. throw error;
  4796. }
  4797. }
  4798. var invariant_1 = invariant;
  4799. /**
  4800. * Obtain the start and end positions of the range that has the
  4801. * specified entity applied to it.
  4802. *
  4803. * Entity keys are applied only to contiguous stretches of text, so this
  4804. * method searches for the first instance of the entity key and returns
  4805. * the subsequent range.
  4806. */
  4807. function getRangesForDraftEntity(block, key) {
  4808. var ranges = [];
  4809. block.findEntityRanges(function (c) {
  4810. return c.getEntity() === key;
  4811. }, function (start, end) {
  4812. ranges.push({ start: start, end: end });
  4813. });
  4814. !!!ranges.length ? process.env.NODE_ENV !== 'production' ? invariant_1(false, 'Entity key not found in this range.') : invariant_1(false) : void 0;
  4815. return ranges;
  4816. }
  4817. var getRangesForDraftEntity_1 = getRangesForDraftEntity;
  4818. /**
  4819. * Given a SelectionState and a removal direction, determine the entire range
  4820. * that should be removed from a ContentState. This is based on any entities
  4821. * within the target, with their `mutability` values taken into account.
  4822. *
  4823. * For instance, if we are attempting to remove part of an "immutable" entity
  4824. * range, the entire entity must be removed. The returned `SelectionState`
  4825. * will be adjusted accordingly.
  4826. */
  4827. function getCharacterRemovalRange(entityMap, startBlock, endBlock, selectionState, direction) {
  4828. var start = selectionState.getStartOffset();
  4829. var end = selectionState.getEndOffset();
  4830. var startEntityKey = startBlock.getEntityAt(start);
  4831. var endEntityKey = endBlock.getEntityAt(end - 1);
  4832. if (!startEntityKey && !endEntityKey) {
  4833. return selectionState;
  4834. }
  4835. var newSelectionState = selectionState;
  4836. if (startEntityKey && startEntityKey === endEntityKey) {
  4837. newSelectionState = getEntityRemovalRange(entityMap, startBlock, newSelectionState, direction, startEntityKey, true, true);
  4838. } else if (startEntityKey && endEntityKey) {
  4839. var startSelectionState = getEntityRemovalRange(entityMap, startBlock, newSelectionState, direction, startEntityKey, false, true);
  4840. var endSelectionState = getEntityRemovalRange(entityMap, endBlock, newSelectionState, direction, endEntityKey, false, false);
  4841. newSelectionState = newSelectionState.merge({
  4842. anchorOffset: startSelectionState.getAnchorOffset(),
  4843. focusOffset: endSelectionState.getFocusOffset(),
  4844. isBackward: false
  4845. });
  4846. } else if (startEntityKey) {
  4847. var _startSelectionState = getEntityRemovalRange(entityMap, startBlock, newSelectionState, direction, startEntityKey, false, true);
  4848. newSelectionState = newSelectionState.merge({
  4849. anchorOffset: _startSelectionState.getStartOffset(),
  4850. isBackward: false
  4851. });
  4852. } else if (endEntityKey) {
  4853. var _endSelectionState = getEntityRemovalRange(entityMap, endBlock, newSelectionState, direction, endEntityKey, false, false);
  4854. newSelectionState = newSelectionState.merge({
  4855. focusOffset: _endSelectionState.getEndOffset(),
  4856. isBackward: false
  4857. });
  4858. }
  4859. return newSelectionState;
  4860. }
  4861. function getEntityRemovalRange(entityMap, block, selectionState, direction, entityKey, isEntireSelectionWithinEntity, isEntityAtStart) {
  4862. var start = selectionState.getStartOffset();
  4863. var end = selectionState.getEndOffset();
  4864. var entity = entityMap.__get(entityKey);
  4865. var mutability = entity.getMutability();
  4866. var sideToConsider = isEntityAtStart ? start : end;
  4867. // `MUTABLE` entities can just have the specified range of text removed
  4868. // directly. No adjustments are needed.
  4869. if (mutability === 'MUTABLE') {
  4870. return selectionState;
  4871. }
  4872. // Find the entity range that overlaps with our removal range.
  4873. var entityRanges = getRangesForDraftEntity_1(block, entityKey).filter(function (range) {
  4874. return sideToConsider <= range.end && sideToConsider >= range.start;
  4875. });
  4876. !(entityRanges.length == 1) ? process.env.NODE_ENV !== 'production' ? invariant_1(false, 'There should only be one entity range within this removal range.') : invariant_1(false) : void 0;
  4877. var entityRange = entityRanges[0];
  4878. // For `IMMUTABLE` entity types, we will remove the entire entity range.
  4879. if (mutability === 'IMMUTABLE') {
  4880. return selectionState.merge({
  4881. anchorOffset: entityRange.start,
  4882. focusOffset: entityRange.end,
  4883. isBackward: false
  4884. });
  4885. }
  4886. // For `SEGMENTED` entity types, determine the appropriate segment to
  4887. // remove.
  4888. if (!isEntireSelectionWithinEntity) {
  4889. if (isEntityAtStart) {
  4890. end = entityRange.end;
  4891. } else {
  4892. start = entityRange.start;
  4893. }
  4894. }
  4895. var removalRange = DraftEntitySegments_1.getRemovalRange(start, end, block.getText().slice(entityRange.start, entityRange.end), entityRange.start, direction);
  4896. return selectionState.merge({
  4897. anchorOffset: removalRange.start,
  4898. focusOffset: removalRange.end,
  4899. isBackward: false
  4900. });
  4901. }
  4902. var getCharacterRemovalRange_1 = getCharacterRemovalRange;
  4903. /**
  4904. * Copyright (c) 2013-present, Facebook, Inc.
  4905. * All rights reserved.
  4906. *
  4907. * This source code is licensed under the BSD-style license found in the
  4908. * LICENSE file in the root directory of this source tree. An additional grant
  4909. * of patent rights can be found in the PATENTS file in the same directory.
  4910. *
  4911. * @providesModule generateRandomKey
  4912. * @format
  4913. *
  4914. */
  4915. var seenKeys = {};
  4916. var MULTIPLIER = Math.pow(2, 24);
  4917. function generateRandomKey() {
  4918. var key = void 0;
  4919. while (key === undefined || seenKeys.hasOwnProperty(key) || !isNaN(+key)) {
  4920. key = Math.floor(Math.random() * MULTIPLIER).toString(32);
  4921. }
  4922. seenKeys[key] = true;
  4923. return key;
  4924. }
  4925. var generateRandomKey_1 = generateRandomKey;
  4926. var OrderedMap$1 = immutable.OrderedMap;
  4927. var randomizeContentBlockNodeKeys = function randomizeContentBlockNodeKeys(blockMap) {
  4928. var newKeysRef = {};
  4929. // we keep track of root blocks in order to update subsequent sibling links
  4930. var lastRootBlock = void 0;
  4931. return OrderedMap$1(blockMap.withMutations(function (blockMapState) {
  4932. blockMapState.forEach(function (block, index) {
  4933. var oldKey = block.getKey();
  4934. var nextKey = block.getNextSiblingKey();
  4935. var prevKey = block.getPrevSiblingKey();
  4936. var childrenKeys = block.getChildKeys();
  4937. var parentKey = block.getParentKey();
  4938. // new key that we will use to build linking
  4939. var key = generateRandomKey_1();
  4940. // we will add it here to re-use it later
  4941. newKeysRef[oldKey] = key;
  4942. if (nextKey) {
  4943. var nextBlock = blockMapState.get(nextKey);
  4944. if (nextBlock) {
  4945. blockMapState.setIn([nextKey, 'prevSibling'], key);
  4946. } else {
  4947. // this can happen when generating random keys for fragments
  4948. blockMapState.setIn([oldKey, 'nextSibling'], null);
  4949. }
  4950. }
  4951. if (prevKey) {
  4952. var prevBlock = blockMapState.get(prevKey);
  4953. if (prevBlock) {
  4954. blockMapState.setIn([prevKey, 'nextSibling'], key);
  4955. } else {
  4956. // this can happen when generating random keys for fragments
  4957. blockMapState.setIn([oldKey, 'prevSibling'], null);
  4958. }
  4959. }
  4960. if (parentKey && blockMapState.get(parentKey)) {
  4961. var parentBlock = blockMapState.get(parentKey);
  4962. var parentChildrenList = parentBlock.getChildKeys();
  4963. blockMapState.setIn([parentKey, 'children'], parentChildrenList.set(parentChildrenList.indexOf(block.getKey()), key));
  4964. } else {
  4965. // blocks will then be treated as root block nodes
  4966. blockMapState.setIn([oldKey, 'parent'], null);
  4967. if (lastRootBlock) {
  4968. blockMapState.setIn([lastRootBlock.getKey(), 'nextSibling'], key);
  4969. blockMapState.setIn([oldKey, 'prevSibling'], newKeysRef[lastRootBlock.getKey()]);
  4970. }
  4971. lastRootBlock = blockMapState.get(oldKey);
  4972. }
  4973. childrenKeys.forEach(function (childKey) {
  4974. var childBlock = blockMapState.get(childKey);
  4975. if (childBlock) {
  4976. blockMapState.setIn([childKey, 'parent'], key);
  4977. } else {
  4978. blockMapState.setIn([oldKey, 'children'], block.getChildKeys().filter(function (child) {
  4979. return child !== childKey;
  4980. }));
  4981. }
  4982. });
  4983. });
  4984. }).toArray().map(function (block) {
  4985. return [newKeysRef[block.getKey()], block.set('key', newKeysRef[block.getKey()])];
  4986. }));
  4987. };
  4988. var randomizeContentBlockKeys = function randomizeContentBlockKeys(blockMap) {
  4989. return OrderedMap$1(blockMap.toArray().map(function (block) {
  4990. var key = generateRandomKey_1();
  4991. return [key, block.set('key', key)];
  4992. }));
  4993. };
  4994. var randomizeBlockMapKeys = function randomizeBlockMapKeys(blockMap) {
  4995. var isTreeBasedBlockMap = blockMap.first() instanceof ContentBlockNode_1;
  4996. if (!isTreeBasedBlockMap) {
  4997. return randomizeContentBlockKeys(blockMap);
  4998. }
  4999. return randomizeContentBlockNodeKeys(blockMap);
  5000. };
  5001. var randomizeBlockMapKeys_1 = randomizeBlockMapKeys;
  5002. function removeEntitiesAtEdges(contentState, selectionState) {
  5003. var blockMap = contentState.getBlockMap();
  5004. var entityMap = contentState.getEntityMap();
  5005. var updatedBlocks = {};
  5006. var startKey = selectionState.getStartKey();
  5007. var startOffset = selectionState.getStartOffset();
  5008. var startBlock = blockMap.get(startKey);
  5009. var updatedStart = removeForBlock(entityMap, startBlock, startOffset);
  5010. if (updatedStart !== startBlock) {
  5011. updatedBlocks[startKey] = updatedStart;
  5012. }
  5013. var endKey = selectionState.getEndKey();
  5014. var endOffset = selectionState.getEndOffset();
  5015. var endBlock = blockMap.get(endKey);
  5016. if (startKey === endKey) {
  5017. endBlock = updatedStart;
  5018. }
  5019. var updatedEnd = removeForBlock(entityMap, endBlock, endOffset);
  5020. if (updatedEnd !== endBlock) {
  5021. updatedBlocks[endKey] = updatedEnd;
  5022. }
  5023. if (!Object.keys(updatedBlocks).length) {
  5024. return contentState.set('selectionAfter', selectionState);
  5025. }
  5026. return contentState.merge({
  5027. blockMap: blockMap.merge(updatedBlocks),
  5028. selectionAfter: selectionState
  5029. });
  5030. }
  5031. function getRemovalRange(characters, key, offset) {
  5032. var removalRange;
  5033. findRangesImmutable_1(characters, function (a, b) {
  5034. return a.getEntity() === b.getEntity();
  5035. }, function (element) {
  5036. return element.getEntity() === key;
  5037. }, function (start, end) {
  5038. if (start <= offset && end >= offset) {
  5039. removalRange = { start: start, end: end };
  5040. }
  5041. });
  5042. !(typeof removalRange === 'object') ? process.env.NODE_ENV !== 'production' ? invariant_1(false, 'Removal range must exist within character list.') : invariant_1(false) : void 0;
  5043. return removalRange;
  5044. }
  5045. function removeForBlock(entityMap, block, offset) {
  5046. var chars = block.getCharacterList();
  5047. var charBefore = offset > 0 ? chars.get(offset - 1) : undefined;
  5048. var charAfter = offset < chars.count() ? chars.get(offset) : undefined;
  5049. var entityBeforeCursor = charBefore ? charBefore.getEntity() : undefined;
  5050. var entityAfterCursor = charAfter ? charAfter.getEntity() : undefined;
  5051. if (entityAfterCursor && entityAfterCursor === entityBeforeCursor) {
  5052. var entity = entityMap.__get(entityAfterCursor);
  5053. if (entity.getMutability() !== 'MUTABLE') {
  5054. var _getRemovalRange = getRemovalRange(chars, entityAfterCursor, offset),
  5055. start = _getRemovalRange.start,
  5056. end = _getRemovalRange.end;
  5057. var current;
  5058. while (start < end) {
  5059. current = chars.get(start);
  5060. chars = chars.set(start, CharacterMetadata_1.applyEntity(current, null));
  5061. start++;
  5062. }
  5063. return block.set('characterList', chars);
  5064. }
  5065. }
  5066. return block;
  5067. }
  5068. var removeEntitiesAtEdges_1 = removeEntitiesAtEdges;
  5069. var getContentStateFragment = function getContentStateFragment(contentState, selectionState) {
  5070. var startKey = selectionState.getStartKey();
  5071. var startOffset = selectionState.getStartOffset();
  5072. var endKey = selectionState.getEndKey();
  5073. var endOffset = selectionState.getEndOffset();
  5074. // Edge entities should be stripped to ensure that we don't preserve
  5075. // invalid partial entities when the fragment is reused. We do, however,
  5076. // preserve entities that are entirely within the selection range.
  5077. var contentWithoutEdgeEntities = removeEntitiesAtEdges_1(contentState, selectionState);
  5078. var blockMap = contentWithoutEdgeEntities.getBlockMap();
  5079. var blockKeys = blockMap.keySeq();
  5080. var startIndex = blockKeys.indexOf(startKey);
  5081. var endIndex = blockKeys.indexOf(endKey) + 1;
  5082. return randomizeBlockMapKeys_1(blockMap.slice(startIndex, endIndex).map(function (block, blockKey) {
  5083. var text = block.getText();
  5084. var chars = block.getCharacterList();
  5085. if (startKey === endKey) {
  5086. return block.merge({
  5087. text: text.slice(startOffset, endOffset),
  5088. characterList: chars.slice(startOffset, endOffset)
  5089. });
  5090. }
  5091. if (blockKey === startKey) {
  5092. return block.merge({
  5093. text: text.slice(startOffset),
  5094. characterList: chars.slice(startOffset)
  5095. });
  5096. }
  5097. if (blockKey === endKey) {
  5098. return block.merge({
  5099. text: text.slice(0, endOffset),
  5100. characterList: chars.slice(0, endOffset)
  5101. });
  5102. }
  5103. return block;
  5104. }));
  5105. };
  5106. var getContentStateFragment_1 = getContentStateFragment;
  5107. /**
  5108. * Copyright (c) 2013-present, Facebook, Inc.
  5109. * All rights reserved.
  5110. *
  5111. * This source code is licensed under the BSD-style license found in the
  5112. * LICENSE file in the root directory of this source tree. An additional grant
  5113. * of patent rights can be found in the PATENTS file in the same directory.
  5114. *
  5115. * @providesModule insertIntoList
  5116. * @format
  5117. *
  5118. */
  5119. /**
  5120. * Maintain persistence for target list when appending and prepending.
  5121. */
  5122. function insertIntoList(targetList, toInsert, offset) {
  5123. if (offset === targetList.count()) {
  5124. toInsert.forEach(function (c) {
  5125. targetList = targetList.push(c);
  5126. });
  5127. } else if (offset === 0) {
  5128. toInsert.reverse().forEach(function (c) {
  5129. targetList = targetList.unshift(c);
  5130. });
  5131. } else {
  5132. var head = targetList.slice(0, offset);
  5133. var tail = targetList.slice(offset);
  5134. targetList = head.concat(toInsert, tail).toList();
  5135. }
  5136. return targetList;
  5137. }
  5138. var insertIntoList_1 = insertIntoList;
  5139. var List$2 = immutable.List;
  5140. var updateExistingBlock = function updateExistingBlock(contentState, selectionState, blockMap, fragmentBlock, targetKey, targetOffset) {
  5141. var targetBlock = blockMap.get(targetKey);
  5142. var text = targetBlock.getText();
  5143. var chars = targetBlock.getCharacterList();
  5144. var finalKey = targetKey;
  5145. var finalOffset = targetOffset + fragmentBlock.getText().length;
  5146. var newBlock = targetBlock.merge({
  5147. text: text.slice(0, targetOffset) + fragmentBlock.getText() + text.slice(targetOffset),
  5148. characterList: insertIntoList_1(chars, fragmentBlock.getCharacterList(), targetOffset),
  5149. data: fragmentBlock.getData()
  5150. });
  5151. return contentState.merge({
  5152. blockMap: blockMap.set(targetKey, newBlock),
  5153. selectionBefore: selectionState,
  5154. selectionAfter: selectionState.merge({
  5155. anchorKey: finalKey,
  5156. anchorOffset: finalOffset,
  5157. focusKey: finalKey,
  5158. focusOffset: finalOffset,
  5159. isBackward: false
  5160. })
  5161. });
  5162. };
  5163. /**
  5164. * Appends text/characterList from the fragment first block to
  5165. * target block.
  5166. */
  5167. var updateHead = function updateHead(block, targetOffset, fragment) {
  5168. var text = block.getText();
  5169. var chars = block.getCharacterList();
  5170. // Modify head portion of block.
  5171. var headText = text.slice(0, targetOffset);
  5172. var headCharacters = chars.slice(0, targetOffset);
  5173. var appendToHead = fragment.first();
  5174. return block.merge({
  5175. text: headText + appendToHead.getText(),
  5176. characterList: headCharacters.concat(appendToHead.getCharacterList()),
  5177. type: headText ? block.getType() : appendToHead.getType(),
  5178. data: appendToHead.getData()
  5179. });
  5180. };
  5181. /**
  5182. * Appends offset text/characterList from the target block to the last
  5183. * fragment block.
  5184. */
  5185. var updateTail = function updateTail(block, targetOffset, fragment) {
  5186. // Modify tail portion of block.
  5187. var text = block.getText();
  5188. var chars = block.getCharacterList();
  5189. // Modify head portion of block.
  5190. var blockSize = text.length;
  5191. var tailText = text.slice(targetOffset, blockSize);
  5192. var tailCharacters = chars.slice(targetOffset, blockSize);
  5193. var prependToTail = fragment.last();
  5194. return prependToTail.merge({
  5195. text: prependToTail.getText() + tailText,
  5196. characterList: prependToTail.getCharacterList().concat(tailCharacters),
  5197. data: prependToTail.getData()
  5198. });
  5199. };
  5200. var getRootBlocks = function getRootBlocks(block, blockMap) {
  5201. var headKey = block.getKey();
  5202. var rootBlock = block;
  5203. var rootBlocks = [];
  5204. // sometimes the fragment head block will not be part of the blockMap itself this can happen when
  5205. // the fragment head is used to update the target block, however when this does not happen we need
  5206. // to make sure that we include it on the rootBlocks since the first block of a fragment is always a
  5207. // fragment root block
  5208. if (blockMap.get(headKey)) {
  5209. rootBlocks.push(headKey);
  5210. }
  5211. while (rootBlock && rootBlock.getNextSiblingKey()) {
  5212. var lastSiblingKey = rootBlock.getNextSiblingKey();
  5213. if (!lastSiblingKey) {
  5214. break;
  5215. }
  5216. rootBlocks.push(lastSiblingKey);
  5217. rootBlock = blockMap.get(lastSiblingKey);
  5218. }
  5219. return rootBlocks;
  5220. };
  5221. var updateBlockMapLinks = function updateBlockMapLinks(blockMap, originalBlockMap, targetBlock, fragmentHeadBlock) {
  5222. return blockMap.withMutations(function (blockMapState) {
  5223. var targetKey = targetBlock.getKey();
  5224. var headKey = fragmentHeadBlock.getKey();
  5225. var targetNextKey = targetBlock.getNextSiblingKey();
  5226. var targetParentKey = targetBlock.getParentKey();
  5227. var fragmentRootBlocks = getRootBlocks(fragmentHeadBlock, blockMap);
  5228. var lastRootFragmentBlockKey = fragmentRootBlocks[fragmentRootBlocks.length - 1];
  5229. if (blockMapState.get(headKey)) {
  5230. // update the fragment head when it is part of the blockMap otherwise
  5231. blockMapState.setIn([targetKey, 'nextSibling'], headKey);
  5232. blockMapState.setIn([headKey, 'prevSibling'], targetKey);
  5233. } else {
  5234. // update the target block that had the fragment head contents merged into it
  5235. blockMapState.setIn([targetKey, 'nextSibling'], fragmentHeadBlock.getNextSiblingKey());
  5236. blockMapState.setIn([fragmentHeadBlock.getNextSiblingKey(), 'prevSibling'], targetKey);
  5237. }
  5238. // update the last root block fragment
  5239. blockMapState.setIn([lastRootFragmentBlockKey, 'nextSibling'], targetNextKey);
  5240. // update the original target next block
  5241. if (targetNextKey) {
  5242. blockMapState.setIn([targetNextKey, 'prevSibling'], lastRootFragmentBlockKey);
  5243. }
  5244. // update fragment parent links
  5245. fragmentRootBlocks.forEach(function (blockKey) {
  5246. return blockMapState.setIn([blockKey, 'parent'], targetParentKey);
  5247. });
  5248. // update targetBlock parent child links
  5249. if (targetParentKey) {
  5250. var targetParent = blockMap.get(targetParentKey);
  5251. var originalTargetParentChildKeys = targetParent.getChildKeys();
  5252. var targetBlockIndex = originalTargetParentChildKeys.indexOf(targetKey);
  5253. var insertionIndex = targetBlockIndex + 1;
  5254. var newChildrenKeysArray = originalTargetParentChildKeys.toArray();
  5255. // insert fragment children
  5256. newChildrenKeysArray.splice.apply(newChildrenKeysArray, [insertionIndex, 0].concat(fragmentRootBlocks));
  5257. blockMapState.setIn([targetParentKey, 'children'], List$2(newChildrenKeysArray));
  5258. }
  5259. });
  5260. };
  5261. var insertFragment = function insertFragment(contentState, selectionState, blockMap, fragment, targetKey, targetOffset) {
  5262. var isTreeBasedBlockMap = blockMap.first() instanceof ContentBlockNode_1;
  5263. var newBlockArr = [];
  5264. var fragmentSize = fragment.size;
  5265. var target = blockMap.get(targetKey);
  5266. var head = fragment.first();
  5267. var tail = fragment.last();
  5268. var finalOffset = tail.getLength();
  5269. var finalKey = tail.getKey();
  5270. var shouldNotUpdateFromFragmentBlock = isTreeBasedBlockMap && (!target.getChildKeys().isEmpty() || !head.getChildKeys().isEmpty());
  5271. blockMap.forEach(function (block, blockKey) {
  5272. if (blockKey !== targetKey) {
  5273. newBlockArr.push(block);
  5274. return;
  5275. }
  5276. if (shouldNotUpdateFromFragmentBlock) {
  5277. newBlockArr.push(block);
  5278. } else {
  5279. newBlockArr.push(updateHead(block, targetOffset, fragment));
  5280. }
  5281. // Insert fragment blocks after the head and before the tail.
  5282. fragment
  5283. // when we are updating the target block with the head fragment block we skip the first fragment
  5284. // head since its contents have already been merged with the target block otherwise we include
  5285. // the whole fragment
  5286. .slice(shouldNotUpdateFromFragmentBlock ? 0 : 1, fragmentSize - 1).forEach(function (fragmentBlock) {
  5287. return newBlockArr.push(fragmentBlock);
  5288. });
  5289. // update tail
  5290. newBlockArr.push(updateTail(block, targetOffset, fragment));
  5291. });
  5292. var updatedBlockMap = BlockMapBuilder_1.createFromArray(newBlockArr);
  5293. if (isTreeBasedBlockMap) {
  5294. updatedBlockMap = updateBlockMapLinks(updatedBlockMap, blockMap, target, head);
  5295. }
  5296. return contentState.merge({
  5297. blockMap: updatedBlockMap,
  5298. selectionBefore: selectionState,
  5299. selectionAfter: selectionState.merge({
  5300. anchorKey: finalKey,
  5301. anchorOffset: finalOffset,
  5302. focusKey: finalKey,
  5303. focusOffset: finalOffset,
  5304. isBackward: false
  5305. })
  5306. });
  5307. };
  5308. var insertFragmentIntoContentState = function insertFragmentIntoContentState(contentState, selectionState, fragmentBlockMap) {
  5309. !selectionState.isCollapsed() ? process.env.NODE_ENV !== 'production' ? invariant_1(false, '`insertFragment` should only be called with a collapsed selection state.') : invariant_1(false) : void 0;
  5310. var blockMap = contentState.getBlockMap();
  5311. var fragment = randomizeBlockMapKeys_1(fragmentBlockMap);
  5312. var targetKey = selectionState.getStartKey();
  5313. var targetOffset = selectionState.getStartOffset();
  5314. var targetBlock = blockMap.get(targetKey);
  5315. if (targetBlock instanceof ContentBlockNode_1) {
  5316. !targetBlock.getChildKeys().isEmpty() ? process.env.NODE_ENV !== 'production' ? invariant_1(false, '`insertFragment` should not be called when a container node is selected.') : invariant_1(false) : void 0;
  5317. }
  5318. // When we insert a fragment with a single block we simply update the target block
  5319. // with the contents of the inserted fragment block
  5320. if (fragment.size === 1) {
  5321. return updateExistingBlock(contentState, selectionState, blockMap, fragment.first(), targetKey, targetOffset);
  5322. }
  5323. return insertFragment(contentState, selectionState, blockMap, fragment, targetKey, targetOffset);
  5324. };
  5325. var insertFragmentIntoContentState_1 = insertFragmentIntoContentState;
  5326. var Repeat$2 = immutable.Repeat;
  5327. function insertTextIntoContentState(contentState, selectionState, text, characterMetadata) {
  5328. !selectionState.isCollapsed() ? process.env.NODE_ENV !== 'production' ? invariant_1(false, '`insertText` should only be called with a collapsed range.') : invariant_1(false) : void 0;
  5329. var len = text.length;
  5330. if (!len) {
  5331. return contentState;
  5332. }
  5333. var blockMap = contentState.getBlockMap();
  5334. var key = selectionState.getStartKey();
  5335. var offset = selectionState.getStartOffset();
  5336. var block = blockMap.get(key);
  5337. var blockText = block.getText();
  5338. var newBlock = block.merge({
  5339. text: blockText.slice(0, offset) + text + blockText.slice(offset, block.getLength()),
  5340. characterList: insertIntoList_1(block.getCharacterList(), Repeat$2(characterMetadata, len).toList(), offset)
  5341. });
  5342. var newOffset = offset + len;
  5343. return contentState.merge({
  5344. blockMap: blockMap.set(key, newBlock),
  5345. selectionAfter: selectionState.merge({
  5346. anchorOffset: newOffset,
  5347. focusOffset: newOffset
  5348. })
  5349. });
  5350. }
  5351. var insertTextIntoContentState_1 = insertTextIntoContentState;
  5352. var Map$5 = immutable.Map;
  5353. function modifyBlockForContentState(contentState, selectionState, operation) {
  5354. var startKey = selectionState.getStartKey();
  5355. var endKey = selectionState.getEndKey();
  5356. var blockMap = contentState.getBlockMap();
  5357. var newBlocks = blockMap.toSeq().skipUntil(function (_, k) {
  5358. return k === startKey;
  5359. }).takeUntil(function (_, k) {
  5360. return k === endKey;
  5361. }).concat(Map$5([[endKey, blockMap.get(endKey)]])).map(operation);
  5362. return contentState.merge({
  5363. blockMap: blockMap.merge(newBlocks),
  5364. selectionBefore: selectionState,
  5365. selectionAfter: selectionState
  5366. });
  5367. }
  5368. var modifyBlockForContentState_1 = modifyBlockForContentState;
  5369. /**
  5370. * Copyright (c) 2013-present, Facebook, Inc.
  5371. * All rights reserved.
  5372. *
  5373. * This source code is licensed under the BSD-style license found in the
  5374. * LICENSE file in the root directory of this source tree. An additional grant
  5375. * of patent rights can be found in the PATENTS file in the same directory.
  5376. *
  5377. * @providesModule getNextDelimiterBlockKey
  5378. * @format
  5379. *
  5380. *
  5381. * This is unstable and not part of the public API and should not be used by
  5382. * production systems. This file may be update/removed without notice.
  5383. */
  5384. var getNextDelimiterBlockKey = function getNextDelimiterBlockKey(block, blockMap) {
  5385. var isExperimentalTreeBlock = block instanceof ContentBlockNode_1;
  5386. if (!isExperimentalTreeBlock) {
  5387. return null;
  5388. }
  5389. var nextSiblingKey = block.getNextSiblingKey();
  5390. if (nextSiblingKey) {
  5391. return nextSiblingKey;
  5392. }
  5393. var parent = block.getParentKey();
  5394. if (!parent) {
  5395. return null;
  5396. }
  5397. var nextNonDescendantBlock = blockMap.get(parent);
  5398. while (nextNonDescendantBlock && !nextNonDescendantBlock.getNextSiblingKey()) {
  5399. var parentKey = nextNonDescendantBlock.getParentKey();
  5400. nextNonDescendantBlock = parentKey ? blockMap.get(parentKey) : null;
  5401. }
  5402. if (!nextNonDescendantBlock) {
  5403. return null;
  5404. }
  5405. return nextNonDescendantBlock.getNextSiblingKey();
  5406. };
  5407. var getNextDelimiterBlockKey_1 = getNextDelimiterBlockKey;
  5408. var List$3 = immutable.List,
  5409. Map$6 = immutable.Map;
  5410. var transformBlock = function transformBlock(key, blockMap, func) {
  5411. if (!key) {
  5412. return;
  5413. }
  5414. var block = blockMap.get(key);
  5415. if (!block) {
  5416. return;
  5417. }
  5418. blockMap.set(key, func(block));
  5419. };
  5420. /**
  5421. * Ancestors needs to be preserved when there are non selected
  5422. * children to make sure we do not leave any orphans behind
  5423. */
  5424. var getAncestorsKeys = function getAncestorsKeys(blockKey, blockMap) {
  5425. var parents = [];
  5426. if (!blockKey) {
  5427. return parents;
  5428. }
  5429. var blockNode = blockMap.get(blockKey);
  5430. while (blockNode && blockNode.getParentKey()) {
  5431. var parentKey = blockNode.getParentKey();
  5432. if (parentKey) {
  5433. parents.push(parentKey);
  5434. }
  5435. blockNode = parentKey ? blockMap.get(parentKey) : null;
  5436. }
  5437. return parents;
  5438. };
  5439. /**
  5440. * Get all next delimiter keys until we hit a root delimiter and return
  5441. * an array of key references
  5442. */
  5443. var getNextDelimitersBlockKeys = function getNextDelimitersBlockKeys(block, blockMap) {
  5444. var nextDelimiters = [];
  5445. if (!block) {
  5446. return nextDelimiters;
  5447. }
  5448. var nextDelimiter = getNextDelimiterBlockKey_1(block, blockMap);
  5449. while (nextDelimiter && blockMap.get(nextDelimiter)) {
  5450. var _block = blockMap.get(nextDelimiter);
  5451. nextDelimiters.push(nextDelimiter);
  5452. // we do not need to keep checking all root node siblings, just the first occurance
  5453. nextDelimiter = _block.getParentKey() ? getNextDelimiterBlockKey_1(_block, blockMap) : null;
  5454. }
  5455. return nextDelimiters;
  5456. };
  5457. var getNextValidSibling = function getNextValidSibling(block, blockMap, originalBlockMap) {
  5458. if (!block) {
  5459. return null;
  5460. }
  5461. // note that we need to make sure we refer to the original block since this
  5462. // function is called within a withMutations
  5463. var nextValidSiblingKey = originalBlockMap.get(block.getKey()).getNextSiblingKey();
  5464. while (nextValidSiblingKey && !blockMap.get(nextValidSiblingKey)) {
  5465. nextValidSiblingKey = originalBlockMap.get(nextValidSiblingKey).getNextSiblingKey() || null;
  5466. }
  5467. return nextValidSiblingKey;
  5468. };
  5469. var getPrevValidSibling = function getPrevValidSibling(block, blockMap, originalBlockMap) {
  5470. if (!block) {
  5471. return null;
  5472. }
  5473. // note that we need to make sure we refer to the original block since this
  5474. // function is called within a withMutations
  5475. var prevValidSiblingKey = originalBlockMap.get(block.getKey()).getPrevSiblingKey();
  5476. while (prevValidSiblingKey && !blockMap.get(prevValidSiblingKey)) {
  5477. prevValidSiblingKey = originalBlockMap.get(prevValidSiblingKey).getPrevSiblingKey() || null;
  5478. }
  5479. return prevValidSiblingKey;
  5480. };
  5481. var updateBlockMapLinks$1 = function updateBlockMapLinks(blockMap, startBlock, endBlock, originalBlockMap) {
  5482. return blockMap.withMutations(function (blocks) {
  5483. // update start block if its retained
  5484. transformBlock(startBlock.getKey(), blocks, function (block) {
  5485. return block.merge({
  5486. nextSibling: getNextValidSibling(startBlock, blocks, originalBlockMap),
  5487. prevSibling: getPrevValidSibling(startBlock, blocks, originalBlockMap)
  5488. });
  5489. });
  5490. // update endblock if its retained
  5491. transformBlock(endBlock.getKey(), blocks, function (block) {
  5492. return block.merge({
  5493. nextSibling: getNextValidSibling(endBlock, blocks, originalBlockMap),
  5494. prevSibling: getPrevValidSibling(endBlock, blocks, originalBlockMap)
  5495. });
  5496. });
  5497. // update start block parent ancestors
  5498. getAncestorsKeys(startBlock.getKey(), originalBlockMap).forEach(function (parentKey) {
  5499. return transformBlock(parentKey, blocks, function (block) {
  5500. return block.merge({
  5501. children: block.getChildKeys().filter(function (key) {
  5502. return blocks.get(key);
  5503. }),
  5504. nextSibling: getNextValidSibling(block, blocks, originalBlockMap),
  5505. prevSibling: getPrevValidSibling(block, blocks, originalBlockMap)
  5506. });
  5507. });
  5508. });
  5509. // update start block next - can only happen if startBlock == endBlock
  5510. transformBlock(startBlock.getNextSiblingKey(), blocks, function (block) {
  5511. return block.merge({
  5512. prevSibling: startBlock.getPrevSiblingKey()
  5513. });
  5514. });
  5515. // update start block prev
  5516. transformBlock(startBlock.getPrevSiblingKey(), blocks, function (block) {
  5517. return block.merge({
  5518. nextSibling: getNextValidSibling(startBlock, blocks, originalBlockMap)
  5519. });
  5520. });
  5521. // update end block next
  5522. transformBlock(endBlock.getNextSiblingKey(), blocks, function (block) {
  5523. return block.merge({
  5524. prevSibling: getPrevValidSibling(endBlock, blocks, originalBlockMap)
  5525. });
  5526. });
  5527. // update end block prev
  5528. transformBlock(endBlock.getPrevSiblingKey(), blocks, function (block) {
  5529. return block.merge({
  5530. nextSibling: endBlock.getNextSiblingKey()
  5531. });
  5532. });
  5533. // update end block parent ancestors
  5534. getAncestorsKeys(endBlock.getKey(), originalBlockMap).forEach(function (parentKey) {
  5535. transformBlock(parentKey, blocks, function (block) {
  5536. return block.merge({
  5537. children: block.getChildKeys().filter(function (key) {
  5538. return blocks.get(key);
  5539. }),
  5540. nextSibling: getNextValidSibling(block, blocks, originalBlockMap),
  5541. prevSibling: getPrevValidSibling(block, blocks, originalBlockMap)
  5542. });
  5543. });
  5544. });
  5545. // update next delimiters all the way to a root delimiter
  5546. getNextDelimitersBlockKeys(endBlock, originalBlockMap).forEach(function (delimiterKey) {
  5547. return transformBlock(delimiterKey, blocks, function (block) {
  5548. return block.merge({
  5549. nextSibling: getNextValidSibling(block, blocks, originalBlockMap),
  5550. prevSibling: getPrevValidSibling(block, blocks, originalBlockMap)
  5551. });
  5552. });
  5553. });
  5554. });
  5555. };
  5556. var removeRangeFromContentState = function removeRangeFromContentState(contentState, selectionState) {
  5557. if (selectionState.isCollapsed()) {
  5558. return contentState;
  5559. }
  5560. var blockMap = contentState.getBlockMap();
  5561. var startKey = selectionState.getStartKey();
  5562. var startOffset = selectionState.getStartOffset();
  5563. var endKey = selectionState.getEndKey();
  5564. var endOffset = selectionState.getEndOffset();
  5565. var startBlock = blockMap.get(startKey);
  5566. var endBlock = blockMap.get(endKey);
  5567. // we assume that ContentBlockNode and ContentBlocks are not mixed together
  5568. var isExperimentalTreeBlock = startBlock instanceof ContentBlockNode_1;
  5569. // used to retain blocks that should not be deleted to avoid orphan children
  5570. var parentAncestors = [];
  5571. if (isExperimentalTreeBlock) {
  5572. var endBlockchildrenKeys = endBlock.getChildKeys();
  5573. var endBlockAncestors = getAncestorsKeys(endKey, blockMap);
  5574. // endBlock has unselected sibblings so we can not remove its ancestors parents
  5575. if (endBlock.getNextSiblingKey()) {
  5576. parentAncestors = parentAncestors.concat(endBlockAncestors);
  5577. }
  5578. // endBlock has children so can not remove this block or any of its ancestors
  5579. if (!endBlockchildrenKeys.isEmpty()) {
  5580. parentAncestors = parentAncestors.concat(endBlockAncestors.concat([endKey]));
  5581. }
  5582. // we need to retain all ancestors of the next delimiter block
  5583. parentAncestors = parentAncestors.concat(getAncestorsKeys(getNextDelimiterBlockKey_1(endBlock, blockMap), blockMap));
  5584. }
  5585. var characterList = void 0;
  5586. if (startBlock === endBlock) {
  5587. characterList = removeFromList(startBlock.getCharacterList(), startOffset, endOffset);
  5588. } else {
  5589. characterList = startBlock.getCharacterList().slice(0, startOffset).concat(endBlock.getCharacterList().slice(endOffset));
  5590. }
  5591. var modifiedStart = startBlock.merge({
  5592. text: startBlock.getText().slice(0, startOffset) + endBlock.getText().slice(endOffset),
  5593. characterList: characterList
  5594. });
  5595. var newBlocks = blockMap.toSeq().skipUntil(function (_, k) {
  5596. return k === startKey;
  5597. }).takeUntil(function (_, k) {
  5598. return k === endKey;
  5599. }).filter(function (_, k) {
  5600. return parentAncestors.indexOf(k) === -1;
  5601. }).concat(Map$6([[endKey, null]])).map(function (_, k) {
  5602. return k === startKey ? modifiedStart : null;
  5603. });
  5604. var updatedBlockMap = blockMap.merge(newBlocks).filter(function (block) {
  5605. return !!block;
  5606. });
  5607. if (isExperimentalTreeBlock) {
  5608. updatedBlockMap = updateBlockMapLinks$1(updatedBlockMap, startBlock, endBlock, blockMap);
  5609. }
  5610. return contentState.merge({
  5611. blockMap: updatedBlockMap,
  5612. selectionBefore: selectionState,
  5613. selectionAfter: selectionState.merge({
  5614. anchorKey: startKey,
  5615. anchorOffset: startOffset,
  5616. focusKey: startKey,
  5617. focusOffset: startOffset,
  5618. isBackward: false
  5619. })
  5620. });
  5621. };
  5622. /**
  5623. * Maintain persistence for target list when removing characters on the
  5624. * head and tail of the character list.
  5625. */
  5626. var removeFromList = function removeFromList(targetList, startOffset, endOffset) {
  5627. if (startOffset === 0) {
  5628. while (startOffset < endOffset) {
  5629. targetList = targetList.shift();
  5630. startOffset++;
  5631. }
  5632. } else if (endOffset === targetList.count()) {
  5633. while (endOffset > startOffset) {
  5634. targetList = targetList.pop();
  5635. endOffset--;
  5636. }
  5637. } else {
  5638. var head = targetList.slice(0, startOffset);
  5639. var tail = targetList.slice(endOffset);
  5640. targetList = head.concat(tail).toList();
  5641. }
  5642. return targetList;
  5643. };
  5644. var removeRangeFromContentState_1 = removeRangeFromContentState;
  5645. var List$4 = immutable.List,
  5646. Map$7 = immutable.Map;
  5647. var transformBlock$1 = function transformBlock(key, blockMap, func) {
  5648. if (!key) {
  5649. return;
  5650. }
  5651. var block = blockMap.get(key);
  5652. if (!block) {
  5653. return;
  5654. }
  5655. blockMap.set(key, func(block));
  5656. };
  5657. var updateBlockMapLinks$2 = function updateBlockMapLinks(blockMap, originalBlock, belowBlock) {
  5658. return blockMap.withMutations(function (blocks) {
  5659. var originalBlockKey = originalBlock.getKey();
  5660. var belowBlockKey = belowBlock.getKey();
  5661. // update block parent
  5662. transformBlock$1(originalBlock.getParentKey(), blocks, function (block) {
  5663. var parentChildrenList = block.getChildKeys();
  5664. var insertionIndex = parentChildrenList.indexOf(originalBlockKey) + 1;
  5665. var newChildrenArray = parentChildrenList.toArray();
  5666. newChildrenArray.splice(insertionIndex, 0, belowBlockKey);
  5667. return block.merge({
  5668. children: List$4(newChildrenArray)
  5669. });
  5670. });
  5671. // update original next block
  5672. transformBlock$1(originalBlock.getNextSiblingKey(), blocks, function (block) {
  5673. return block.merge({
  5674. prevSibling: belowBlockKey
  5675. });
  5676. });
  5677. // update original block
  5678. transformBlock$1(originalBlockKey, blocks, function (block) {
  5679. return block.merge({
  5680. nextSibling: belowBlockKey
  5681. });
  5682. });
  5683. // update below block
  5684. transformBlock$1(belowBlockKey, blocks, function (block) {
  5685. return block.merge({
  5686. prevSibling: originalBlockKey
  5687. });
  5688. });
  5689. });
  5690. };
  5691. var splitBlockInContentState = function splitBlockInContentState(contentState, selectionState) {
  5692. !selectionState.isCollapsed() ? process.env.NODE_ENV !== 'production' ? invariant_1(false, 'Selection range must be collapsed.') : invariant_1(false) : void 0;
  5693. var key = selectionState.getAnchorKey();
  5694. var offset = selectionState.getAnchorOffset();
  5695. var blockMap = contentState.getBlockMap();
  5696. var blockToSplit = blockMap.get(key);
  5697. var text = blockToSplit.getText();
  5698. var chars = blockToSplit.getCharacterList();
  5699. var keyBelow = generateRandomKey_1();
  5700. var isExperimentalTreeBlock = blockToSplit instanceof ContentBlockNode_1;
  5701. var blockAbove = blockToSplit.merge({
  5702. text: text.slice(0, offset),
  5703. characterList: chars.slice(0, offset)
  5704. });
  5705. var blockBelow = blockAbove.merge({
  5706. key: keyBelow,
  5707. text: text.slice(offset),
  5708. characterList: chars.slice(offset),
  5709. data: Map$7()
  5710. });
  5711. var blocksBefore = blockMap.toSeq().takeUntil(function (v) {
  5712. return v === blockToSplit;
  5713. });
  5714. var blocksAfter = blockMap.toSeq().skipUntil(function (v) {
  5715. return v === blockToSplit;
  5716. }).rest();
  5717. var newBlocks = blocksBefore.concat([[key, blockAbove], [keyBelow, blockBelow]], blocksAfter).toOrderedMap();
  5718. if (isExperimentalTreeBlock) {
  5719. !blockToSplit.getChildKeys().isEmpty() ? process.env.NODE_ENV !== 'production' ? invariant_1(false, 'ContentBlockNode must not have children') : invariant_1(false) : void 0;
  5720. newBlocks = updateBlockMapLinks$2(newBlocks, blockAbove, blockBelow);
  5721. }
  5722. return contentState.merge({
  5723. blockMap: newBlocks,
  5724. selectionBefore: selectionState,
  5725. selectionAfter: selectionState.merge({
  5726. anchorKey: keyBelow,
  5727. anchorOffset: 0,
  5728. focusKey: keyBelow,
  5729. focusOffset: 0,
  5730. isBackward: false
  5731. })
  5732. });
  5733. };
  5734. var splitBlockInContentState_1 = splitBlockInContentState;
  5735. var OrderedSet$3 = immutable.OrderedSet;
  5736. /**
  5737. * `DraftModifier` provides a set of convenience methods that apply
  5738. * modifications to a `ContentState` object based on a target `SelectionState`.
  5739. *
  5740. * Any change to a `ContentState` should be decomposable into a series of
  5741. * transaction functions that apply the required changes and return output
  5742. * `ContentState` objects.
  5743. *
  5744. * These functions encapsulate some of the most common transaction sequences.
  5745. */
  5746. var DraftModifier = {
  5747. replaceText: function replaceText(contentState, rangeToReplace, text, inlineStyle, entityKey) {
  5748. var withoutEntities = removeEntitiesAtEdges_1(contentState, rangeToReplace);
  5749. var withoutText = removeRangeFromContentState_1(withoutEntities, rangeToReplace);
  5750. var character = CharacterMetadata_1.create({
  5751. style: inlineStyle || OrderedSet$3(),
  5752. entity: entityKey || null
  5753. });
  5754. return insertTextIntoContentState_1(withoutText, withoutText.getSelectionAfter(), text, character);
  5755. },
  5756. insertText: function insertText(contentState, targetRange, text, inlineStyle, entityKey) {
  5757. !targetRange.isCollapsed() ? process.env.NODE_ENV !== 'production' ? invariant_1(false, 'Target range must be collapsed for `insertText`.') : invariant_1(false) : void 0;
  5758. return DraftModifier.replaceText(contentState, targetRange, text, inlineStyle, entityKey);
  5759. },
  5760. moveText: function moveText(contentState, removalRange, targetRange) {
  5761. var movedFragment = getContentStateFragment_1(contentState, removalRange);
  5762. var afterRemoval = DraftModifier.removeRange(contentState, removalRange, 'backward');
  5763. return DraftModifier.replaceWithFragment(afterRemoval, targetRange, movedFragment);
  5764. },
  5765. replaceWithFragment: function replaceWithFragment(contentState, targetRange, fragment) {
  5766. var withoutEntities = removeEntitiesAtEdges_1(contentState, targetRange);
  5767. var withoutText = removeRangeFromContentState_1(withoutEntities, targetRange);
  5768. return insertFragmentIntoContentState_1(withoutText, withoutText.getSelectionAfter(), fragment);
  5769. },
  5770. removeRange: function removeRange(contentState, rangeToRemove, removalDirection) {
  5771. var startKey = void 0,
  5772. endKey = void 0,
  5773. startBlock = void 0,
  5774. endBlock = void 0;
  5775. if (rangeToRemove.getIsBackward()) {
  5776. rangeToRemove = rangeToRemove.merge({
  5777. anchorKey: rangeToRemove.getFocusKey(),
  5778. anchorOffset: rangeToRemove.getFocusOffset(),
  5779. focusKey: rangeToRemove.getAnchorKey(),
  5780. focusOffset: rangeToRemove.getAnchorOffset(),
  5781. isBackward: false
  5782. });
  5783. }
  5784. startKey = rangeToRemove.getAnchorKey();
  5785. endKey = rangeToRemove.getFocusKey();
  5786. startBlock = contentState.getBlockForKey(startKey);
  5787. endBlock = contentState.getBlockForKey(endKey);
  5788. var startOffset = rangeToRemove.getStartOffset();
  5789. var endOffset = rangeToRemove.getEndOffset();
  5790. var startEntityKey = startBlock.getEntityAt(startOffset);
  5791. var endEntityKey = endBlock.getEntityAt(endOffset - 1);
  5792. // Check whether the selection state overlaps with a single entity.
  5793. // If so, try to remove the appropriate substring of the entity text.
  5794. if (startKey === endKey) {
  5795. if (startEntityKey && startEntityKey === endEntityKey) {
  5796. var _adjustedRemovalRange = getCharacterRemovalRange_1(contentState.getEntityMap(), startBlock, endBlock, rangeToRemove, removalDirection);
  5797. return removeRangeFromContentState_1(contentState, _adjustedRemovalRange);
  5798. }
  5799. }
  5800. var adjustedRemovalRange = rangeToRemove;
  5801. var withoutEntities = removeEntitiesAtEdges_1(contentState, adjustedRemovalRange);
  5802. return removeRangeFromContentState_1(withoutEntities, adjustedRemovalRange);
  5803. },
  5804. splitBlock: function splitBlock(contentState, selectionState) {
  5805. var withoutEntities = removeEntitiesAtEdges_1(contentState, selectionState);
  5806. var withoutText = removeRangeFromContentState_1(withoutEntities, selectionState);
  5807. return splitBlockInContentState_1(withoutText, withoutText.getSelectionAfter());
  5808. },
  5809. applyInlineStyle: function applyInlineStyle(contentState, selectionState, inlineStyle) {
  5810. return ContentStateInlineStyle_1.add(contentState, selectionState, inlineStyle);
  5811. },
  5812. removeInlineStyle: function removeInlineStyle(contentState, selectionState, inlineStyle) {
  5813. return ContentStateInlineStyle_1.remove(contentState, selectionState, inlineStyle);
  5814. },
  5815. setBlockType: function setBlockType(contentState, selectionState, blockType) {
  5816. return modifyBlockForContentState_1(contentState, selectionState, function (block) {
  5817. return block.merge({ type: blockType, depth: 0 });
  5818. });
  5819. },
  5820. setBlockData: function setBlockData(contentState, selectionState, blockData) {
  5821. return modifyBlockForContentState_1(contentState, selectionState, function (block) {
  5822. return block.merge({ data: blockData });
  5823. });
  5824. },
  5825. mergeBlockData: function mergeBlockData(contentState, selectionState, blockData) {
  5826. return modifyBlockForContentState_1(contentState, selectionState, function (block) {
  5827. return block.merge({ data: block.getData().merge(blockData) });
  5828. });
  5829. },
  5830. applyEntity: function applyEntity(contentState, selectionState, entityKey) {
  5831. var withoutEntities = removeEntitiesAtEdges_1(contentState, selectionState);
  5832. return applyEntityToContentState_1(withoutEntities, selectionState, entityKey);
  5833. }
  5834. };
  5835. var DraftModifier_1 = DraftModifier;
  5836. /**
  5837. * Copyright (c) 2013-present, Facebook, Inc.
  5838. *
  5839. * This source code is licensed under the MIT license found in the
  5840. * LICENSE file in the root directory of this source tree.
  5841. *
  5842. *
  5843. */
  5844. function makeEmptyFunction(arg) {
  5845. return function () {
  5846. return arg;
  5847. };
  5848. }
  5849. /**
  5850. * This function accepts and discards inputs; it has no side effects. This is
  5851. * primarily useful idiomatically for overridable function endpoints which
  5852. * always need to be callable, since JS lacks a null-call idiom ala Cocoa.
  5853. */
  5854. var emptyFunction = function emptyFunction() {};
  5855. emptyFunction.thatReturns = makeEmptyFunction;
  5856. emptyFunction.thatReturnsFalse = makeEmptyFunction(false);
  5857. emptyFunction.thatReturnsTrue = makeEmptyFunction(true);
  5858. emptyFunction.thatReturnsNull = makeEmptyFunction(null);
  5859. emptyFunction.thatReturnsThis = function () {
  5860. return this;
  5861. };
  5862. emptyFunction.thatReturnsArgument = function (arg) {
  5863. return arg;
  5864. };
  5865. var emptyFunction_1 = emptyFunction;
  5866. var List$5 = immutable.List,
  5867. Repeat$3 = immutable.Repeat,
  5868. Record$3 = immutable.Record;
  5869. var returnTrue = emptyFunction_1.thatReturnsTrue;
  5870. var FINGERPRINT_DELIMITER = '-';
  5871. var defaultLeafRange = {
  5872. start: null,
  5873. end: null
  5874. };
  5875. var LeafRange = Record$3(defaultLeafRange);
  5876. var defaultDecoratorRange = {
  5877. start: null,
  5878. end: null,
  5879. decoratorKey: null,
  5880. leaves: null
  5881. };
  5882. var DecoratorRange = Record$3(defaultDecoratorRange);
  5883. var BlockTree = {
  5884. /**
  5885. * Generate a block tree for a given ContentBlock/decorator pair.
  5886. */
  5887. generate: function generate(contentState, block, decorator) {
  5888. var textLength = block.getLength();
  5889. if (!textLength) {
  5890. return List$5.of(new DecoratorRange({
  5891. start: 0,
  5892. end: 0,
  5893. decoratorKey: null,
  5894. leaves: List$5.of(new LeafRange({ start: 0, end: 0 }))
  5895. }));
  5896. }
  5897. var leafSets = [];
  5898. var decorations = decorator ? decorator.getDecorations(block, contentState) : List$5(Repeat$3(null, textLength));
  5899. var chars = block.getCharacterList();
  5900. findRangesImmutable_1(decorations, areEqual, returnTrue, function (start, end) {
  5901. leafSets.push(new DecoratorRange({
  5902. start: start,
  5903. end: end,
  5904. decoratorKey: decorations.get(start),
  5905. leaves: generateLeaves(chars.slice(start, end).toList(), start)
  5906. }));
  5907. });
  5908. return List$5(leafSets);
  5909. },
  5910. /**
  5911. * Create a string representation of the given tree map. This allows us
  5912. * to rapidly determine whether a tree has undergone a significant
  5913. * structural change.
  5914. */
  5915. getFingerprint: function getFingerprint(tree) {
  5916. return tree.map(function (leafSet) {
  5917. var decoratorKey = leafSet.get('decoratorKey');
  5918. var fingerprintString = decoratorKey !== null ? decoratorKey + '.' + (leafSet.get('end') - leafSet.get('start')) : '';
  5919. return '' + fingerprintString + '.' + leafSet.get('leaves').size;
  5920. }).join(FINGERPRINT_DELIMITER);
  5921. }
  5922. };
  5923. /**
  5924. * Generate LeafRange records for a given character list.
  5925. */
  5926. function generateLeaves(characters, offset) {
  5927. var leaves = [];
  5928. var inlineStyles = characters.map(function (c) {
  5929. return c.getStyle();
  5930. }).toList();
  5931. findRangesImmutable_1(inlineStyles, areEqual, returnTrue, function (start, end) {
  5932. leaves.push(new LeafRange({
  5933. start: start + offset,
  5934. end: end + offset
  5935. }));
  5936. });
  5937. return List$5(leaves);
  5938. }
  5939. function areEqual(a, b) {
  5940. return a === b;
  5941. }
  5942. var BlockTree_1 = BlockTree;
  5943. function _classCallCheck$3(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  5944. function _possibleConstructorReturn$3(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }
  5945. function _inherits$3(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
  5946. var Record$4 = immutable.Record;
  5947. var DraftEntityInstanceRecord = Record$4({
  5948. type: 'TOKEN',
  5949. mutability: 'IMMUTABLE',
  5950. data: Object
  5951. });
  5952. /**
  5953. * An instance of a document entity, consisting of a `type` and relevant
  5954. * `data`, metadata about the entity.
  5955. *
  5956. * For instance, a "link" entity might provide a URI, and a "mention"
  5957. * entity might provide the mentioned user's ID. These pieces of data
  5958. * may be used when rendering the entity as part of a ContentBlock DOM
  5959. * representation. For a link, the data would be used as an href for
  5960. * the rendered anchor. For a mention, the ID could be used to retrieve
  5961. * a hovercard.
  5962. */
  5963. var DraftEntityInstance = function (_DraftEntityInstanceR) {
  5964. _inherits$3(DraftEntityInstance, _DraftEntityInstanceR);
  5965. function DraftEntityInstance() {
  5966. _classCallCheck$3(this, DraftEntityInstance);
  5967. return _possibleConstructorReturn$3(this, _DraftEntityInstanceR.apply(this, arguments));
  5968. }
  5969. DraftEntityInstance.prototype.getType = function getType() {
  5970. return this.get('type');
  5971. };
  5972. DraftEntityInstance.prototype.getMutability = function getMutability() {
  5973. return this.get('mutability');
  5974. };
  5975. DraftEntityInstance.prototype.getData = function getData() {
  5976. return this.get('data');
  5977. };
  5978. return DraftEntityInstance;
  5979. }(DraftEntityInstanceRecord);
  5980. var DraftEntityInstance_1 = DraftEntityInstance;
  5981. var _extends = objectAssign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };
  5982. /**
  5983. * Copyright (c) 2013-present, Facebook, Inc.
  5984. * All rights reserved.
  5985. *
  5986. * This source code is licensed under the BSD-style license found in the
  5987. * LICENSE file in the root directory of this source tree. An additional grant
  5988. * of patent rights can be found in the PATENTS file in the same directory.
  5989. *
  5990. * @providesModule DraftEntity
  5991. * @format
  5992. *
  5993. */
  5994. var Map$8 = immutable.Map;
  5995. var instances = Map$8();
  5996. var instanceKey = 0;
  5997. /**
  5998. * Temporary utility for generating the warnings
  5999. */
  6000. function logWarning(oldMethodCall, newMethodCall) {
  6001. console.warn('WARNING: ' + oldMethodCall + ' will be deprecated soon!\nPlease use "' + newMethodCall + '" instead.');
  6002. }
  6003. /**
  6004. * A "document entity" is an object containing metadata associated with a
  6005. * piece of text in a ContentBlock.
  6006. *
  6007. * For example, a `link` entity might include a `uri` property. When a
  6008. * ContentBlock is rendered in the browser, text that refers to that link
  6009. * entity may be rendered as an anchor, with the `uri` as the href value.
  6010. *
  6011. * In a ContentBlock, every position in the text may correspond to zero
  6012. * or one entities. This correspondence is tracked using a key string,
  6013. * generated via DraftEntity.create() and used to obtain entity metadata
  6014. * via DraftEntity.get().
  6015. */
  6016. var DraftEntity = {
  6017. /**
  6018. * WARNING: This method will be deprecated soon!
  6019. * Please use 'contentState.getLastCreatedEntityKey' instead.
  6020. * ---
  6021. * Get the random key string from whatever entity was last created.
  6022. * We need this to support the new API, as part of transitioning to put Entity
  6023. * storage in contentState.
  6024. */
  6025. getLastCreatedEntityKey: function getLastCreatedEntityKey() {
  6026. logWarning('DraftEntity.getLastCreatedEntityKey', 'contentState.getLastCreatedEntityKey');
  6027. return DraftEntity.__getLastCreatedEntityKey();
  6028. },
  6029. /**
  6030. * WARNING: This method will be deprecated soon!
  6031. * Please use 'contentState.createEntity' instead.
  6032. * ---
  6033. * Create a DraftEntityInstance and store it for later retrieval.
  6034. *
  6035. * A random key string will be generated and returned. This key may
  6036. * be used to track the entity's usage in a ContentBlock, and for
  6037. * retrieving data about the entity at render time.
  6038. */
  6039. create: function create(type, mutability, data) {
  6040. logWarning('DraftEntity.create', 'contentState.createEntity');
  6041. return DraftEntity.__create(type, mutability, data);
  6042. },
  6043. /**
  6044. * WARNING: This method will be deprecated soon!
  6045. * Please use 'contentState.addEntity' instead.
  6046. * ---
  6047. * Add an existing DraftEntityInstance to the DraftEntity map. This is
  6048. * useful when restoring instances from the server.
  6049. */
  6050. add: function add(instance) {
  6051. logWarning('DraftEntity.add', 'contentState.addEntity');
  6052. return DraftEntity.__add(instance);
  6053. },
  6054. /**
  6055. * WARNING: This method will be deprecated soon!
  6056. * Please use 'contentState.getEntity' instead.
  6057. * ---
  6058. * Retrieve the entity corresponding to the supplied key string.
  6059. */
  6060. get: function get(key) {
  6061. logWarning('DraftEntity.get', 'contentState.getEntity');
  6062. return DraftEntity.__get(key);
  6063. },
  6064. /**
  6065. * WARNING: This method will be deprecated soon!
  6066. * Please use 'contentState.mergeEntityData' instead.
  6067. * ---
  6068. * Entity instances are immutable. If you need to update the data for an
  6069. * instance, this method will merge your data updates and return a new
  6070. * instance.
  6071. */
  6072. mergeData: function mergeData(key, toMerge) {
  6073. logWarning('DraftEntity.mergeData', 'contentState.mergeEntityData');
  6074. return DraftEntity.__mergeData(key, toMerge);
  6075. },
  6076. /**
  6077. * WARNING: This method will be deprecated soon!
  6078. * Please use 'contentState.replaceEntityData' instead.
  6079. * ---
  6080. * Completely replace the data for a given instance.
  6081. */
  6082. replaceData: function replaceData(key, newData) {
  6083. logWarning('DraftEntity.replaceData', 'contentState.replaceEntityData');
  6084. return DraftEntity.__replaceData(key, newData);
  6085. },
  6086. // ***********************************WARNING******************************
  6087. // --- the above public API will be deprecated in the next version of Draft!
  6088. // The methods below this line are private - don't call them directly.
  6089. /**
  6090. * Get the random key string from whatever entity was last created.
  6091. * We need this to support the new API, as part of transitioning to put Entity
  6092. * storage in contentState.
  6093. */
  6094. __getLastCreatedEntityKey: function __getLastCreatedEntityKey() {
  6095. return '' + instanceKey;
  6096. },
  6097. /**
  6098. * Create a DraftEntityInstance and store it for later retrieval.
  6099. *
  6100. * A random key string will be generated and returned. This key may
  6101. * be used to track the entity's usage in a ContentBlock, and for
  6102. * retrieving data about the entity at render time.
  6103. */
  6104. __create: function __create(type, mutability, data) {
  6105. return DraftEntity.__add(new DraftEntityInstance_1({ type: type, mutability: mutability, data: data || {} }));
  6106. },
  6107. /**
  6108. * Add an existing DraftEntityInstance to the DraftEntity map. This is
  6109. * useful when restoring instances from the server.
  6110. */
  6111. __add: function __add(instance) {
  6112. var key = '' + ++instanceKey;
  6113. instances = instances.set(key, instance);
  6114. return key;
  6115. },
  6116. /**
  6117. * Retrieve the entity corresponding to the supplied key string.
  6118. */
  6119. __get: function __get(key) {
  6120. var instance = instances.get(key);
  6121. !!!instance ? process.env.NODE_ENV !== 'production' ? invariant_1(false, 'Unknown DraftEntity key: %s.', key) : invariant_1(false) : void 0;
  6122. return instance;
  6123. },
  6124. /**
  6125. * Entity instances are immutable. If you need to update the data for an
  6126. * instance, this method will merge your data updates and return a new
  6127. * instance.
  6128. */
  6129. __mergeData: function __mergeData(key, toMerge) {
  6130. var instance = DraftEntity.__get(key);
  6131. var newData = _extends({}, instance.getData(), toMerge);
  6132. var newInstance = instance.set('data', newData);
  6133. instances = instances.set(key, newInstance);
  6134. return newInstance;
  6135. },
  6136. /**
  6137. * Completely replace the data for a given instance.
  6138. */
  6139. __replaceData: function __replaceData(key, newData) {
  6140. var instance = DraftEntity.__get(key);
  6141. var newInstance = instance.set('data', newData);
  6142. instances = instances.set(key, newInstance);
  6143. return newInstance;
  6144. }
  6145. };
  6146. var DraftEntity_1 = DraftEntity;
  6147. function _classCallCheck$4(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  6148. function _possibleConstructorReturn$4(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }
  6149. function _inherits$4(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
  6150. var Record$5 = immutable.Record;
  6151. var defaultRecord$3 = {
  6152. anchorKey: '',
  6153. anchorOffset: 0,
  6154. focusKey: '',
  6155. focusOffset: 0,
  6156. isBackward: false,
  6157. hasFocus: false
  6158. };
  6159. var SelectionStateRecord = Record$5(defaultRecord$3);
  6160. var SelectionState = function (_SelectionStateRecord) {
  6161. _inherits$4(SelectionState, _SelectionStateRecord);
  6162. function SelectionState() {
  6163. _classCallCheck$4(this, SelectionState);
  6164. return _possibleConstructorReturn$4(this, _SelectionStateRecord.apply(this, arguments));
  6165. }
  6166. SelectionState.prototype.serialize = function serialize() {
  6167. return 'Anchor: ' + this.getAnchorKey() + ':' + this.getAnchorOffset() + ', ' + 'Focus: ' + this.getFocusKey() + ':' + this.getFocusOffset() + ', ' + 'Is Backward: ' + String(this.getIsBackward()) + ', ' + 'Has Focus: ' + String(this.getHasFocus());
  6168. };
  6169. SelectionState.prototype.getAnchorKey = function getAnchorKey() {
  6170. return this.get('anchorKey');
  6171. };
  6172. SelectionState.prototype.getAnchorOffset = function getAnchorOffset() {
  6173. return this.get('anchorOffset');
  6174. };
  6175. SelectionState.prototype.getFocusKey = function getFocusKey() {
  6176. return this.get('focusKey');
  6177. };
  6178. SelectionState.prototype.getFocusOffset = function getFocusOffset() {
  6179. return this.get('focusOffset');
  6180. };
  6181. SelectionState.prototype.getIsBackward = function getIsBackward() {
  6182. return this.get('isBackward');
  6183. };
  6184. SelectionState.prototype.getHasFocus = function getHasFocus() {
  6185. return this.get('hasFocus');
  6186. };
  6187. /**
  6188. * Return whether the specified range overlaps with an edge of the
  6189. * SelectionState.
  6190. */
  6191. SelectionState.prototype.hasEdgeWithin = function hasEdgeWithin(blockKey, start, end) {
  6192. var anchorKey = this.getAnchorKey();
  6193. var focusKey = this.getFocusKey();
  6194. if (anchorKey === focusKey && anchorKey === blockKey) {
  6195. var selectionStart = this.getStartOffset();
  6196. var selectionEnd = this.getEndOffset();
  6197. return start <= selectionEnd && selectionStart <= end;
  6198. }
  6199. if (blockKey !== anchorKey && blockKey !== focusKey) {
  6200. return false;
  6201. }
  6202. var offsetToCheck = blockKey === anchorKey ? this.getAnchorOffset() : this.getFocusOffset();
  6203. return start <= offsetToCheck && end >= offsetToCheck;
  6204. };
  6205. SelectionState.prototype.isCollapsed = function isCollapsed() {
  6206. return this.getAnchorKey() === this.getFocusKey() && this.getAnchorOffset() === this.getFocusOffset();
  6207. };
  6208. SelectionState.prototype.getStartKey = function getStartKey() {
  6209. return this.getIsBackward() ? this.getFocusKey() : this.getAnchorKey();
  6210. };
  6211. SelectionState.prototype.getStartOffset = function getStartOffset() {
  6212. return this.getIsBackward() ? this.getFocusOffset() : this.getAnchorOffset();
  6213. };
  6214. SelectionState.prototype.getEndKey = function getEndKey() {
  6215. return this.getIsBackward() ? this.getAnchorKey() : this.getFocusKey();
  6216. };
  6217. SelectionState.prototype.getEndOffset = function getEndOffset() {
  6218. return this.getIsBackward() ? this.getAnchorOffset() : this.getFocusOffset();
  6219. };
  6220. SelectionState.createEmpty = function createEmpty(key) {
  6221. return new SelectionState({
  6222. anchorKey: key,
  6223. anchorOffset: 0,
  6224. focusKey: key,
  6225. focusOffset: 0,
  6226. isBackward: false,
  6227. hasFocus: false
  6228. });
  6229. };
  6230. return SelectionState;
  6231. }(SelectionStateRecord);
  6232. var SelectionState_1 = SelectionState;
  6233. /**
  6234. * Copyright (c) 2013-present, Facebook, Inc.
  6235. * All rights reserved.
  6236. *
  6237. * This source code is licensed under the BSD-style license found in the
  6238. * LICENSE file in the root directory of this source tree. An additional grant
  6239. * of patent rights can be found in the PATENTS file in the same directory.
  6240. *
  6241. * @providesModule sanitizeDraftText
  6242. * @format
  6243. *
  6244. */
  6245. var REGEX_BLOCK_DELIMITER = new RegExp('\r', 'g');
  6246. function sanitizeDraftText(input) {
  6247. return input.replace(REGEX_BLOCK_DELIMITER, '');
  6248. }
  6249. var sanitizeDraftText_1 = sanitizeDraftText;
  6250. function _classCallCheck$5(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  6251. function _possibleConstructorReturn$5(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }
  6252. function _inherits$5(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
  6253. var List$6 = immutable.List,
  6254. Record$6 = immutable.Record,
  6255. Repeat$4 = immutable.Repeat;
  6256. var defaultRecord$4 = {
  6257. entityMap: null,
  6258. blockMap: null,
  6259. selectionBefore: null,
  6260. selectionAfter: null
  6261. };
  6262. var ContentBlockNodeRecord = ContentBlock_1;
  6263. var ContentStateRecord = Record$6(defaultRecord$4);
  6264. var ContentState = function (_ContentStateRecord) {
  6265. _inherits$5(ContentState, _ContentStateRecord);
  6266. function ContentState() {
  6267. _classCallCheck$5(this, ContentState);
  6268. return _possibleConstructorReturn$5(this, _ContentStateRecord.apply(this, arguments));
  6269. }
  6270. ContentState.prototype.getEntityMap = function getEntityMap() {
  6271. // TODO: update this when we fully remove DraftEntity
  6272. return DraftEntity_1;
  6273. };
  6274. ContentState.prototype.getBlockMap = function getBlockMap() {
  6275. return this.get('blockMap');
  6276. };
  6277. ContentState.prototype.getSelectionBefore = function getSelectionBefore() {
  6278. return this.get('selectionBefore');
  6279. };
  6280. ContentState.prototype.getSelectionAfter = function getSelectionAfter() {
  6281. return this.get('selectionAfter');
  6282. };
  6283. ContentState.prototype.getBlockForKey = function getBlockForKey(key) {
  6284. var block = this.getBlockMap().get(key);
  6285. return block;
  6286. };
  6287. ContentState.prototype.getKeyBefore = function getKeyBefore(key) {
  6288. return this.getBlockMap().reverse().keySeq().skipUntil(function (v) {
  6289. return v === key;
  6290. }).skip(1).first();
  6291. };
  6292. ContentState.prototype.getKeyAfter = function getKeyAfter(key) {
  6293. return this.getBlockMap().keySeq().skipUntil(function (v) {
  6294. return v === key;
  6295. }).skip(1).first();
  6296. };
  6297. ContentState.prototype.getBlockAfter = function getBlockAfter(key) {
  6298. return this.getBlockMap().skipUntil(function (_, k) {
  6299. return k === key;
  6300. }).skip(1).first();
  6301. };
  6302. ContentState.prototype.getBlockBefore = function getBlockBefore(key) {
  6303. return this.getBlockMap().reverse().skipUntil(function (_, k) {
  6304. return k === key;
  6305. }).skip(1).first();
  6306. };
  6307. ContentState.prototype.getBlocksAsArray = function getBlocksAsArray() {
  6308. return this.getBlockMap().toArray();
  6309. };
  6310. ContentState.prototype.getFirstBlock = function getFirstBlock() {
  6311. return this.getBlockMap().first();
  6312. };
  6313. ContentState.prototype.getLastBlock = function getLastBlock() {
  6314. return this.getBlockMap().last();
  6315. };
  6316. ContentState.prototype.getPlainText = function getPlainText(delimiter) {
  6317. return this.getBlockMap().map(function (block) {
  6318. return block ? block.getText() : '';
  6319. }).join(delimiter || '\n');
  6320. };
  6321. ContentState.prototype.getLastCreatedEntityKey = function getLastCreatedEntityKey() {
  6322. // TODO: update this when we fully remove DraftEntity
  6323. return DraftEntity_1.__getLastCreatedEntityKey();
  6324. };
  6325. ContentState.prototype.hasText = function hasText() {
  6326. var blockMap = this.getBlockMap();
  6327. return blockMap.size > 1 || blockMap.first().getLength() > 0;
  6328. };
  6329. ContentState.prototype.createEntity = function createEntity(type, mutability, data) {
  6330. // TODO: update this when we fully remove DraftEntity
  6331. DraftEntity_1.__create(type, mutability, data);
  6332. return this;
  6333. };
  6334. ContentState.prototype.mergeEntityData = function mergeEntityData(key, toMerge) {
  6335. // TODO: update this when we fully remove DraftEntity
  6336. DraftEntity_1.__mergeData(key, toMerge);
  6337. return this;
  6338. };
  6339. ContentState.prototype.replaceEntityData = function replaceEntityData(key, newData) {
  6340. // TODO: update this when we fully remove DraftEntity
  6341. DraftEntity_1.__replaceData(key, newData);
  6342. return this;
  6343. };
  6344. ContentState.prototype.addEntity = function addEntity(instance) {
  6345. // TODO: update this when we fully remove DraftEntity
  6346. DraftEntity_1.__add(instance);
  6347. return this;
  6348. };
  6349. ContentState.prototype.getEntity = function getEntity(key) {
  6350. // TODO: update this when we fully remove DraftEntity
  6351. return DraftEntity_1.__get(key);
  6352. };
  6353. ContentState.createFromBlockArray = function createFromBlockArray(
  6354. // TODO: update flow type when we completely deprecate the old entity API
  6355. blocks, entityMap) {
  6356. // TODO: remove this when we completely deprecate the old entity API
  6357. var theBlocks = Array.isArray(blocks) ? blocks : blocks.contentBlocks;
  6358. var blockMap = BlockMapBuilder_1.createFromArray(theBlocks);
  6359. var selectionState = blockMap.isEmpty() ? new SelectionState_1() : SelectionState_1.createEmpty(blockMap.first().getKey());
  6360. return new ContentState({
  6361. blockMap: blockMap,
  6362. entityMap: entityMap || DraftEntity_1,
  6363. selectionBefore: selectionState,
  6364. selectionAfter: selectionState
  6365. });
  6366. };
  6367. ContentState.createFromText = function createFromText(text) {
  6368. var delimiter = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : /\r\n?|\n/g;
  6369. var strings = text.split(delimiter);
  6370. var blocks = strings.map(function (block) {
  6371. block = sanitizeDraftText_1(block);
  6372. return new ContentBlockNodeRecord({
  6373. key: generateRandomKey_1(),
  6374. text: block,
  6375. type: 'unstyled',
  6376. characterList: List$6(Repeat$4(CharacterMetadata_1.EMPTY, block.length))
  6377. });
  6378. });
  6379. return ContentState.createFromBlockArray(blocks);
  6380. };
  6381. return ContentState;
  6382. }(ContentStateRecord);
  6383. var ContentState_1 = ContentState;
  6384. var NEUTRAL = 'NEUTRAL'; // No strong direction
  6385. var LTR = 'LTR'; // Left-to-Right direction
  6386. var RTL = 'RTL'; // Right-to-Left direction
  6387. var globalDir = null;
  6388. // == Helpers ==
  6389. /**
  6390. * Check if a directionality value is a Strong one
  6391. */
  6392. function isStrong(dir) {
  6393. return dir === LTR || dir === RTL;
  6394. }
  6395. /**
  6396. * Get string value to be used for `dir` HTML attribute or `direction` CSS
  6397. * property.
  6398. */
  6399. function getHTMLDir(dir) {
  6400. !isStrong(dir) ? process.env.NODE_ENV !== 'production' ? invariant_1(false, '`dir` must be a strong direction to be converted to HTML Direction') : invariant_1(false) : void 0;
  6401. return dir === LTR ? 'ltr' : 'rtl';
  6402. }
  6403. /**
  6404. * Get string value to be used for `dir` HTML attribute or `direction` CSS
  6405. * property, but returns null if `dir` has same value as `otherDir`.
  6406. * `null`.
  6407. */
  6408. function getHTMLDirIfDifferent(dir, otherDir) {
  6409. !isStrong(dir) ? process.env.NODE_ENV !== 'production' ? invariant_1(false, '`dir` must be a strong direction to be converted to HTML Direction') : invariant_1(false) : void 0;
  6410. !isStrong(otherDir) ? process.env.NODE_ENV !== 'production' ? invariant_1(false, '`otherDir` must be a strong direction to be converted to HTML Direction') : invariant_1(false) : void 0;
  6411. return dir === otherDir ? null : getHTMLDir(dir);
  6412. }
  6413. // == Global Direction ==
  6414. /**
  6415. * Set the global direction.
  6416. */
  6417. function setGlobalDir(dir) {
  6418. globalDir = dir;
  6419. }
  6420. /**
  6421. * Initialize the global direction
  6422. */
  6423. function initGlobalDir() {
  6424. setGlobalDir(LTR);
  6425. }
  6426. /**
  6427. * Get the global direction
  6428. */
  6429. function getGlobalDir() {
  6430. if (!globalDir) {
  6431. this.initGlobalDir();
  6432. }
  6433. !globalDir ? process.env.NODE_ENV !== 'production' ? invariant_1(false, 'Global direction not set.') : invariant_1(false) : void 0;
  6434. return globalDir;
  6435. }
  6436. var UnicodeBidiDirection = {
  6437. // Values
  6438. NEUTRAL: NEUTRAL,
  6439. LTR: LTR,
  6440. RTL: RTL,
  6441. // Helpers
  6442. isStrong: isStrong,
  6443. getHTMLDir: getHTMLDir,
  6444. getHTMLDirIfDifferent: getHTMLDirIfDifferent,
  6445. // Global Direction
  6446. setGlobalDir: setGlobalDir,
  6447. initGlobalDir: initGlobalDir,
  6448. getGlobalDir: getGlobalDir
  6449. };
  6450. var UnicodeBidiDirection_1 = UnicodeBidiDirection;
  6451. /**
  6452. * RegExp ranges of characters with a *Strong* Bidi_Class value.
  6453. *
  6454. * Data is based on DerivedBidiClass.txt in UCD version 7.0.0.
  6455. *
  6456. * NOTE: For performance reasons, we only support Unicode's
  6457. * Basic Multilingual Plane (BMP) for now.
  6458. */
  6459. var RANGE_BY_BIDI_TYPE = {
  6460. L: 'A-Za-z\xAA\xB5\xBA\xC0-\xD6\xD8-\xF6\xF8-\u01BA\u01BB' + '\u01BC-\u01BF\u01C0-\u01C3\u01C4-\u0293\u0294\u0295-\u02AF\u02B0-\u02B8' + '\u02BB-\u02C1\u02D0-\u02D1\u02E0-\u02E4\u02EE\u0370-\u0373\u0376-\u0377' + '\u037A\u037B-\u037D\u037F\u0386\u0388-\u038A\u038C\u038E-\u03A1' + '\u03A3-\u03F5\u03F7-\u0481\u0482\u048A-\u052F\u0531-\u0556\u0559' + '\u055A-\u055F\u0561-\u0587\u0589\u0903\u0904-\u0939\u093B\u093D' + '\u093E-\u0940\u0949-\u094C\u094E-\u094F\u0950\u0958-\u0961\u0964-\u0965' + '\u0966-\u096F\u0970\u0971\u0972-\u0980\u0982-\u0983\u0985-\u098C' + '\u098F-\u0990\u0993-\u09A8\u09AA-\u09B0\u09B2\u09B6-\u09B9\u09BD' + '\u09BE-\u09C0\u09C7-\u09C8\u09CB-\u09CC\u09CE\u09D7\u09DC-\u09DD' + '\u09DF-\u09E1\u09E6-\u09EF\u09F0-\u09F1\u09F4-\u09F9\u09FA\u0A03' + '\u0A05-\u0A0A\u0A0F-\u0A10\u0A13-\u0A28\u0A2A-\u0A30\u0A32-\u0A33' + '\u0A35-\u0A36\u0A38-\u0A39\u0A3E-\u0A40\u0A59-\u0A5C\u0A5E\u0A66-\u0A6F' + '\u0A72-\u0A74\u0A83\u0A85-\u0A8D\u0A8F-\u0A91\u0A93-\u0AA8\u0AAA-\u0AB0' + '\u0AB2-\u0AB3\u0AB5-\u0AB9\u0ABD\u0ABE-\u0AC0\u0AC9\u0ACB-\u0ACC\u0AD0' + '\u0AE0-\u0AE1\u0AE6-\u0AEF\u0AF0\u0B02-\u0B03\u0B05-\u0B0C\u0B0F-\u0B10' + '\u0B13-\u0B28\u0B2A-\u0B30\u0B32-\u0B33\u0B35-\u0B39\u0B3D\u0B3E\u0B40' + '\u0B47-\u0B48\u0B4B-\u0B4C\u0B57\u0B5C-\u0B5D\u0B5F-\u0B61\u0B66-\u0B6F' + '\u0B70\u0B71\u0B72-\u0B77\u0B83\u0B85-\u0B8A\u0B8E-\u0B90\u0B92-\u0B95' + '\u0B99-\u0B9A\u0B9C\u0B9E-\u0B9F\u0BA3-\u0BA4\u0BA8-\u0BAA\u0BAE-\u0BB9' + '\u0BBE-\u0BBF\u0BC1-\u0BC2\u0BC6-\u0BC8\u0BCA-\u0BCC\u0BD0\u0BD7' + '\u0BE6-\u0BEF\u0BF0-\u0BF2\u0C01-\u0C03\u0C05-\u0C0C\u0C0E-\u0C10' + '\u0C12-\u0C28\u0C2A-\u0C39\u0C3D\u0C41-\u0C44\u0C58-\u0C59\u0C60-\u0C61' + '\u0C66-\u0C6F\u0C7F\u0C82-\u0C83\u0C85-\u0C8C\u0C8E-\u0C90\u0C92-\u0CA8' + '\u0CAA-\u0CB3\u0CB5-\u0CB9\u0CBD\u0CBE\u0CBF\u0CC0-\u0CC4\u0CC6' + '\u0CC7-\u0CC8\u0CCA-\u0CCB\u0CD5-\u0CD6\u0CDE\u0CE0-\u0CE1\u0CE6-\u0CEF' + '\u0CF1-\u0CF2\u0D02-\u0D03\u0D05-\u0D0C\u0D0E-\u0D10\u0D12-\u0D3A\u0D3D' + '\u0D3E-\u0D40\u0D46-\u0D48\u0D4A-\u0D4C\u0D4E\u0D57\u0D60-\u0D61' + '\u0D66-\u0D6F\u0D70-\u0D75\u0D79\u0D7A-\u0D7F\u0D82-\u0D83\u0D85-\u0D96' + '\u0D9A-\u0DB1\u0DB3-\u0DBB\u0DBD\u0DC0-\u0DC6\u0DCF-\u0DD1\u0DD8-\u0DDF' + '\u0DE6-\u0DEF\u0DF2-\u0DF3\u0DF4\u0E01-\u0E30\u0E32-\u0E33\u0E40-\u0E45' + '\u0E46\u0E4F\u0E50-\u0E59\u0E5A-\u0E5B\u0E81-\u0E82\u0E84\u0E87-\u0E88' + '\u0E8A\u0E8D\u0E94-\u0E97\u0E99-\u0E9F\u0EA1-\u0EA3\u0EA5\u0EA7' + '\u0EAA-\u0EAB\u0EAD-\u0EB0\u0EB2-\u0EB3\u0EBD\u0EC0-\u0EC4\u0EC6' + '\u0ED0-\u0ED9\u0EDC-\u0EDF\u0F00\u0F01-\u0F03\u0F04-\u0F12\u0F13\u0F14' + '\u0F15-\u0F17\u0F1A-\u0F1F\u0F20-\u0F29\u0F2A-\u0F33\u0F34\u0F36\u0F38' + '\u0F3E-\u0F3F\u0F40-\u0F47\u0F49-\u0F6C\u0F7F\u0F85\u0F88-\u0F8C' + '\u0FBE-\u0FC5\u0FC7-\u0FCC\u0FCE-\u0FCF\u0FD0-\u0FD4\u0FD5-\u0FD8' + '\u0FD9-\u0FDA\u1000-\u102A\u102B-\u102C\u1031\u1038\u103B-\u103C\u103F' + '\u1040-\u1049\u104A-\u104F\u1050-\u1055\u1056-\u1057\u105A-\u105D\u1061' + '\u1062-\u1064\u1065-\u1066\u1067-\u106D\u106E-\u1070\u1075-\u1081' + '\u1083-\u1084\u1087-\u108C\u108E\u108F\u1090-\u1099\u109A-\u109C' + '\u109E-\u109F\u10A0-\u10C5\u10C7\u10CD\u10D0-\u10FA\u10FB\u10FC' + '\u10FD-\u1248\u124A-\u124D\u1250-\u1256\u1258\u125A-\u125D\u1260-\u1288' + '\u128A-\u128D\u1290-\u12B0\u12B2-\u12B5\u12B8-\u12BE\u12C0\u12C2-\u12C5' + '\u12C8-\u12D6\u12D8-\u1310\u1312-\u1315\u1318-\u135A\u1360-\u1368' + '\u1369-\u137C\u1380-\u138F\u13A0-\u13F4\u1401-\u166C\u166D-\u166E' + '\u166F-\u167F\u1681-\u169A\u16A0-\u16EA\u16EB-\u16ED\u16EE-\u16F0' + '\u16F1-\u16F8\u1700-\u170C\u170E-\u1711\u1720-\u1731\u1735-\u1736' + '\u1740-\u1751\u1760-\u176C\u176E-\u1770\u1780-\u17B3\u17B6\u17BE-\u17C5' + '\u17C7-\u17C8\u17D4-\u17D6\u17D7\u17D8-\u17DA\u17DC\u17E0-\u17E9' + '\u1810-\u1819\u1820-\u1842\u1843\u1844-\u1877\u1880-\u18A8\u18AA' + '\u18B0-\u18F5\u1900-\u191E\u1923-\u1926\u1929-\u192B\u1930-\u1931' + '\u1933-\u1938\u1946-\u194F\u1950-\u196D\u1970-\u1974\u1980-\u19AB' + '\u19B0-\u19C0\u19C1-\u19C7\u19C8-\u19C9\u19D0-\u19D9\u19DA\u1A00-\u1A16' + '\u1A19-\u1A1A\u1A1E-\u1A1F\u1A20-\u1A54\u1A55\u1A57\u1A61\u1A63-\u1A64' + '\u1A6D-\u1A72\u1A80-\u1A89\u1A90-\u1A99\u1AA0-\u1AA6\u1AA7\u1AA8-\u1AAD' + '\u1B04\u1B05-\u1B33\u1B35\u1B3B\u1B3D-\u1B41\u1B43-\u1B44\u1B45-\u1B4B' + '\u1B50-\u1B59\u1B5A-\u1B60\u1B61-\u1B6A\u1B74-\u1B7C\u1B82\u1B83-\u1BA0' + '\u1BA1\u1BA6-\u1BA7\u1BAA\u1BAE-\u1BAF\u1BB0-\u1BB9\u1BBA-\u1BE5\u1BE7' + '\u1BEA-\u1BEC\u1BEE\u1BF2-\u1BF3\u1BFC-\u1BFF\u1C00-\u1C23\u1C24-\u1C2B' + '\u1C34-\u1C35\u1C3B-\u1C3F\u1C40-\u1C49\u1C4D-\u1C4F\u1C50-\u1C59' + '\u1C5A-\u1C77\u1C78-\u1C7D\u1C7E-\u1C7F\u1CC0-\u1CC7\u1CD3\u1CE1' + '\u1CE9-\u1CEC\u1CEE-\u1CF1\u1CF2-\u1CF3\u1CF5-\u1CF6\u1D00-\u1D2B' + '\u1D2C-\u1D6A\u1D6B-\u1D77\u1D78\u1D79-\u1D9A\u1D9B-\u1DBF\u1E00-\u1F15' + '\u1F18-\u1F1D\u1F20-\u1F45\u1F48-\u1F4D\u1F50-\u1F57\u1F59\u1F5B\u1F5D' + '\u1F5F-\u1F7D\u1F80-\u1FB4\u1FB6-\u1FBC\u1FBE\u1FC2-\u1FC4\u1FC6-\u1FCC' + '\u1FD0-\u1FD3\u1FD6-\u1FDB\u1FE0-\u1FEC\u1FF2-\u1FF4\u1FF6-\u1FFC\u200E' + '\u2071\u207F\u2090-\u209C\u2102\u2107\u210A-\u2113\u2115\u2119-\u211D' + '\u2124\u2126\u2128\u212A-\u212D\u212F-\u2134\u2135-\u2138\u2139' + '\u213C-\u213F\u2145-\u2149\u214E\u214F\u2160-\u2182\u2183-\u2184' + '\u2185-\u2188\u2336-\u237A\u2395\u249C-\u24E9\u26AC\u2800-\u28FF' + '\u2C00-\u2C2E\u2C30-\u2C5E\u2C60-\u2C7B\u2C7C-\u2C7D\u2C7E-\u2CE4' + '\u2CEB-\u2CEE\u2CF2-\u2CF3\u2D00-\u2D25\u2D27\u2D2D\u2D30-\u2D67\u2D6F' + '\u2D70\u2D80-\u2D96\u2DA0-\u2DA6\u2DA8-\u2DAE\u2DB0-\u2DB6\u2DB8-\u2DBE' + '\u2DC0-\u2DC6\u2DC8-\u2DCE\u2DD0-\u2DD6\u2DD8-\u2DDE\u3005\u3006\u3007' + '\u3021-\u3029\u302E-\u302F\u3031-\u3035\u3038-\u303A\u303B\u303C' + '\u3041-\u3096\u309D-\u309E\u309F\u30A1-\u30FA\u30FC-\u30FE\u30FF' + '\u3105-\u312D\u3131-\u318E\u3190-\u3191\u3192-\u3195\u3196-\u319F' + '\u31A0-\u31BA\u31F0-\u31FF\u3200-\u321C\u3220-\u3229\u322A-\u3247' + '\u3248-\u324F\u3260-\u327B\u327F\u3280-\u3289\u328A-\u32B0\u32C0-\u32CB' + '\u32D0-\u32FE\u3300-\u3376\u337B-\u33DD\u33E0-\u33FE\u3400-\u4DB5' + '\u4E00-\u9FCC\uA000-\uA014\uA015\uA016-\uA48C\uA4D0-\uA4F7\uA4F8-\uA4FD' + '\uA4FE-\uA4FF\uA500-\uA60B\uA60C\uA610-\uA61F\uA620-\uA629\uA62A-\uA62B' + '\uA640-\uA66D\uA66E\uA680-\uA69B\uA69C-\uA69D\uA6A0-\uA6E5\uA6E6-\uA6EF' + '\uA6F2-\uA6F7\uA722-\uA76F\uA770\uA771-\uA787\uA789-\uA78A\uA78B-\uA78E' + '\uA790-\uA7AD\uA7B0-\uA7B1\uA7F7\uA7F8-\uA7F9\uA7FA\uA7FB-\uA801' + '\uA803-\uA805\uA807-\uA80A\uA80C-\uA822\uA823-\uA824\uA827\uA830-\uA835' + '\uA836-\uA837\uA840-\uA873\uA880-\uA881\uA882-\uA8B3\uA8B4-\uA8C3' + '\uA8CE-\uA8CF\uA8D0-\uA8D9\uA8F2-\uA8F7\uA8F8-\uA8FA\uA8FB\uA900-\uA909' + '\uA90A-\uA925\uA92E-\uA92F\uA930-\uA946\uA952-\uA953\uA95F\uA960-\uA97C' + '\uA983\uA984-\uA9B2\uA9B4-\uA9B5\uA9BA-\uA9BB\uA9BD-\uA9C0\uA9C1-\uA9CD' + '\uA9CF\uA9D0-\uA9D9\uA9DE-\uA9DF\uA9E0-\uA9E4\uA9E6\uA9E7-\uA9EF' + '\uA9F0-\uA9F9\uA9FA-\uA9FE\uAA00-\uAA28\uAA2F-\uAA30\uAA33-\uAA34' + '\uAA40-\uAA42\uAA44-\uAA4B\uAA4D\uAA50-\uAA59\uAA5C-\uAA5F\uAA60-\uAA6F' + '\uAA70\uAA71-\uAA76\uAA77-\uAA79\uAA7A\uAA7B\uAA7D\uAA7E-\uAAAF\uAAB1' + '\uAAB5-\uAAB6\uAAB9-\uAABD\uAAC0\uAAC2\uAADB-\uAADC\uAADD\uAADE-\uAADF' + '\uAAE0-\uAAEA\uAAEB\uAAEE-\uAAEF\uAAF0-\uAAF1\uAAF2\uAAF3-\uAAF4\uAAF5' + '\uAB01-\uAB06\uAB09-\uAB0E\uAB11-\uAB16\uAB20-\uAB26\uAB28-\uAB2E' + '\uAB30-\uAB5A\uAB5B\uAB5C-\uAB5F\uAB64-\uAB65\uABC0-\uABE2\uABE3-\uABE4' + '\uABE6-\uABE7\uABE9-\uABEA\uABEB\uABEC\uABF0-\uABF9\uAC00-\uD7A3' + '\uD7B0-\uD7C6\uD7CB-\uD7FB\uE000-\uF8FF\uF900-\uFA6D\uFA70-\uFAD9' + '\uFB00-\uFB06\uFB13-\uFB17\uFF21-\uFF3A\uFF41-\uFF5A\uFF66-\uFF6F\uFF70' + '\uFF71-\uFF9D\uFF9E-\uFF9F\uFFA0-\uFFBE\uFFC2-\uFFC7\uFFCA-\uFFCF' + '\uFFD2-\uFFD7\uFFDA-\uFFDC',
  6461. R: '\u0590\u05BE\u05C0\u05C3\u05C6\u05C8-\u05CF\u05D0-\u05EA\u05EB-\u05EF' + '\u05F0-\u05F2\u05F3-\u05F4\u05F5-\u05FF\u07C0-\u07C9\u07CA-\u07EA' + '\u07F4-\u07F5\u07FA\u07FB-\u07FF\u0800-\u0815\u081A\u0824\u0828' + '\u082E-\u082F\u0830-\u083E\u083F\u0840-\u0858\u085C-\u085D\u085E' + '\u085F-\u089F\u200F\uFB1D\uFB1F-\uFB28\uFB2A-\uFB36\uFB37\uFB38-\uFB3C' + '\uFB3D\uFB3E\uFB3F\uFB40-\uFB41\uFB42\uFB43-\uFB44\uFB45\uFB46-\uFB4F',
  6462. AL: '\u0608\u060B\u060D\u061B\u061C\u061D\u061E-\u061F\u0620-\u063F\u0640' + '\u0641-\u064A\u066D\u066E-\u066F\u0671-\u06D3\u06D4\u06D5\u06E5-\u06E6' + '\u06EE-\u06EF\u06FA-\u06FC\u06FD-\u06FE\u06FF\u0700-\u070D\u070E\u070F' + '\u0710\u0712-\u072F\u074B-\u074C\u074D-\u07A5\u07B1\u07B2-\u07BF' + '\u08A0-\u08B2\u08B3-\u08E3\uFB50-\uFBB1\uFBB2-\uFBC1\uFBC2-\uFBD2' + '\uFBD3-\uFD3D\uFD40-\uFD4F\uFD50-\uFD8F\uFD90-\uFD91\uFD92-\uFDC7' + '\uFDC8-\uFDCF\uFDF0-\uFDFB\uFDFC\uFDFE-\uFDFF\uFE70-\uFE74\uFE75' + '\uFE76-\uFEFC\uFEFD-\uFEFE'
  6463. };
  6464. var REGEX_STRONG = new RegExp('[' + RANGE_BY_BIDI_TYPE.L + RANGE_BY_BIDI_TYPE.R + RANGE_BY_BIDI_TYPE.AL + ']');
  6465. var REGEX_RTL = new RegExp('[' + RANGE_BY_BIDI_TYPE.R + RANGE_BY_BIDI_TYPE.AL + ']');
  6466. /**
  6467. * Returns the first strong character (has Bidi_Class value of L, R, or AL).
  6468. *
  6469. * @param str A text block; e.g. paragraph, table cell, tag
  6470. * @return A character with strong bidi direction, or null if not found
  6471. */
  6472. function firstStrongChar(str) {
  6473. var match = REGEX_STRONG.exec(str);
  6474. return match == null ? null : match[0];
  6475. }
  6476. /**
  6477. * Returns the direction of a block of text, based on the direction of its
  6478. * first strong character (has Bidi_Class value of L, R, or AL).
  6479. *
  6480. * @param str A text block; e.g. paragraph, table cell, tag
  6481. * @return The resolved direction
  6482. */
  6483. function firstStrongCharDir(str) {
  6484. var strongChar = firstStrongChar(str);
  6485. if (strongChar == null) {
  6486. return UnicodeBidiDirection_1.NEUTRAL;
  6487. }
  6488. return REGEX_RTL.exec(strongChar) ? UnicodeBidiDirection_1.RTL : UnicodeBidiDirection_1.LTR;
  6489. }
  6490. /**
  6491. * Returns the direction of a block of text, based on the direction of its
  6492. * first strong character (has Bidi_Class value of L, R, or AL), or a fallback
  6493. * direction, if no strong character is found.
  6494. *
  6495. * This function is supposed to be used in respect to Higher-Level Protocol
  6496. * rule HL1. (http://www.unicode.org/reports/tr9/#HL1)
  6497. *
  6498. * @param str A text block; e.g. paragraph, table cell, tag
  6499. * @param fallback Fallback direction, used if no strong direction detected
  6500. * for the block (default = NEUTRAL)
  6501. * @return The resolved direction
  6502. */
  6503. function resolveBlockDir(str, fallback) {
  6504. fallback = fallback || UnicodeBidiDirection_1.NEUTRAL;
  6505. if (!str.length) {
  6506. return fallback;
  6507. }
  6508. var blockDir = firstStrongCharDir(str);
  6509. return blockDir === UnicodeBidiDirection_1.NEUTRAL ? fallback : blockDir;
  6510. }
  6511. /**
  6512. * Returns the direction of a block of text, based on the direction of its
  6513. * first strong character (has Bidi_Class value of L, R, or AL), or a fallback
  6514. * direction, if no strong character is found.
  6515. *
  6516. * NOTE: This function is similar to resolveBlockDir(), but uses the global
  6517. * direction as the fallback, so it *always* returns a Strong direction,
  6518. * making it useful for integration in places that you need to make the final
  6519. * decision, like setting some CSS class.
  6520. *
  6521. * This function is supposed to be used in respect to Higher-Level Protocol
  6522. * rule HL1. (http://www.unicode.org/reports/tr9/#HL1)
  6523. *
  6524. * @param str A text block; e.g. paragraph, table cell
  6525. * @param strongFallback Fallback direction, used if no strong direction
  6526. * detected for the block (default = global direction)
  6527. * @return The resolved Strong direction
  6528. */
  6529. function getDirection(str, strongFallback) {
  6530. if (!strongFallback) {
  6531. strongFallback = UnicodeBidiDirection_1.getGlobalDir();
  6532. }
  6533. !UnicodeBidiDirection_1.isStrong(strongFallback) ? process.env.NODE_ENV !== 'production' ? invariant_1(false, 'Fallback direction must be a strong direction') : invariant_1(false) : void 0;
  6534. return resolveBlockDir(str, strongFallback);
  6535. }
  6536. /**
  6537. * Returns true if getDirection(arguments...) returns LTR.
  6538. *
  6539. * @param str A text block; e.g. paragraph, table cell
  6540. * @param strongFallback Fallback direction, used if no strong direction
  6541. * detected for the block (default = global direction)
  6542. * @return True if the resolved direction is LTR
  6543. */
  6544. function isDirectionLTR(str, strongFallback) {
  6545. return getDirection(str, strongFallback) === UnicodeBidiDirection_1.LTR;
  6546. }
  6547. /**
  6548. * Returns true if getDirection(arguments...) returns RTL.
  6549. *
  6550. * @param str A text block; e.g. paragraph, table cell
  6551. * @param strongFallback Fallback direction, used if no strong direction
  6552. * detected for the block (default = global direction)
  6553. * @return True if the resolved direction is RTL
  6554. */
  6555. function isDirectionRTL(str, strongFallback) {
  6556. return getDirection(str, strongFallback) === UnicodeBidiDirection_1.RTL;
  6557. }
  6558. var UnicodeBidi = {
  6559. firstStrongChar: firstStrongChar,
  6560. firstStrongCharDir: firstStrongCharDir,
  6561. resolveBlockDir: resolveBlockDir,
  6562. getDirection: getDirection,
  6563. isDirectionLTR: isDirectionLTR,
  6564. isDirectionRTL: isDirectionRTL
  6565. };
  6566. var UnicodeBidi_1 = UnicodeBidi;
  6567. function _classCallCheck$6(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  6568. var UnicodeBidiService = function () {
  6569. /**
  6570. * Stateful class for paragraph direction detection
  6571. *
  6572. * @param defaultDir Default direction of the service
  6573. */
  6574. function UnicodeBidiService(defaultDir) {
  6575. _classCallCheck$6(this, UnicodeBidiService);
  6576. if (!defaultDir) {
  6577. defaultDir = UnicodeBidiDirection_1.getGlobalDir();
  6578. } else {
  6579. !UnicodeBidiDirection_1.isStrong(defaultDir) ? process.env.NODE_ENV !== 'production' ? invariant_1(false, 'Default direction must be a strong direction (LTR or RTL)') : invariant_1(false) : void 0;
  6580. }
  6581. this._defaultDir = defaultDir;
  6582. this.reset();
  6583. }
  6584. /**
  6585. * Reset the internal state
  6586. *
  6587. * Instead of creating a new instance, you can just reset() your instance
  6588. * everytime you start a new loop.
  6589. */
  6590. UnicodeBidiService.prototype.reset = function reset() {
  6591. this._lastDir = this._defaultDir;
  6592. };
  6593. /**
  6594. * Returns the direction of a block of text, and remembers it as the
  6595. * fall-back direction for the next paragraph.
  6596. *
  6597. * @param str A text block, e.g. paragraph, table cell, tag
  6598. * @return The resolved direction
  6599. */
  6600. UnicodeBidiService.prototype.getDirection = function getDirection(str) {
  6601. this._lastDir = UnicodeBidi_1.getDirection(str, this._lastDir);
  6602. return this._lastDir;
  6603. };
  6604. return UnicodeBidiService;
  6605. }();
  6606. var UnicodeBidiService_1 = UnicodeBidiService;
  6607. /**
  6608. * Copyright (c) 2013-present, Facebook, Inc.
  6609. *
  6610. * This source code is licensed under the MIT license found in the
  6611. * LICENSE file in the root directory of this source tree.
  6612. *
  6613. *
  6614. */
  6615. var nullthrows = function nullthrows(x) {
  6616. if (x != null) {
  6617. return x;
  6618. }
  6619. throw new Error("Got unexpected null or undefined");
  6620. };
  6621. var nullthrows_1 = nullthrows;
  6622. var OrderedMap$2 = immutable.OrderedMap;
  6623. var bidiService;
  6624. var EditorBidiService = {
  6625. getDirectionMap: function getDirectionMap(content, prevBidiMap) {
  6626. if (!bidiService) {
  6627. bidiService = new UnicodeBidiService_1();
  6628. } else {
  6629. bidiService.reset();
  6630. }
  6631. var blockMap = content.getBlockMap();
  6632. var nextBidi = blockMap.valueSeq().map(function (block) {
  6633. return nullthrows_1(bidiService).getDirection(block.getText());
  6634. });
  6635. var bidiMap = OrderedMap$2(blockMap.keySeq().zip(nextBidi));
  6636. if (prevBidiMap != null && immutable.is(prevBidiMap, bidiMap)) {
  6637. return prevBidiMap;
  6638. }
  6639. return bidiMap;
  6640. }
  6641. };
  6642. var EditorBidiService_1 = EditorBidiService;
  6643. var _extends$1 = objectAssign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };
  6644. function _classCallCheck$7(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  6645. var OrderedSet$4 = immutable.OrderedSet,
  6646. Record$7 = immutable.Record,
  6647. Stack = immutable.Stack;
  6648. var defaultRecord$5 = {
  6649. allowUndo: true,
  6650. currentContent: null,
  6651. decorator: null,
  6652. directionMap: null,
  6653. forceSelection: false,
  6654. inCompositionMode: false,
  6655. inlineStyleOverride: null,
  6656. lastChangeType: null,
  6657. nativelyRenderedContent: null,
  6658. redoStack: Stack(),
  6659. selection: null,
  6660. treeMap: null,
  6661. undoStack: Stack()
  6662. };
  6663. var EditorStateRecord = Record$7(defaultRecord$5);
  6664. var EditorState = function () {
  6665. EditorState.createEmpty = function createEmpty(decorator) {
  6666. return EditorState.createWithContent(ContentState_1.createFromText(''), decorator);
  6667. };
  6668. EditorState.createWithContent = function createWithContent(contentState, decorator) {
  6669. var firstKey = contentState.getBlockMap().first().getKey();
  6670. return EditorState.create({
  6671. currentContent: contentState,
  6672. undoStack: Stack(),
  6673. redoStack: Stack(),
  6674. decorator: decorator || null,
  6675. selection: SelectionState_1.createEmpty(firstKey)
  6676. });
  6677. };
  6678. EditorState.create = function create(config) {
  6679. var currentContent = config.currentContent,
  6680. decorator = config.decorator;
  6681. var recordConfig = _extends$1({}, config, {
  6682. treeMap: generateNewTreeMap(currentContent, decorator),
  6683. directionMap: EditorBidiService_1.getDirectionMap(currentContent)
  6684. });
  6685. return new EditorState(new EditorStateRecord(recordConfig));
  6686. };
  6687. EditorState.set = function set(editorState, put) {
  6688. var map = editorState.getImmutable().withMutations(function (state) {
  6689. var existingDecorator = state.get('decorator');
  6690. var decorator = existingDecorator;
  6691. if (put.decorator === null) {
  6692. decorator = null;
  6693. } else if (put.decorator) {
  6694. decorator = put.decorator;
  6695. }
  6696. var newContent = put.currentContent || editorState.getCurrentContent();
  6697. if (decorator !== existingDecorator) {
  6698. var treeMap = state.get('treeMap');
  6699. var newTreeMap;
  6700. if (decorator && existingDecorator) {
  6701. newTreeMap = regenerateTreeForNewDecorator(newContent, newContent.getBlockMap(), treeMap, decorator, existingDecorator);
  6702. } else {
  6703. newTreeMap = generateNewTreeMap(newContent, decorator);
  6704. }
  6705. state.merge({
  6706. decorator: decorator,
  6707. treeMap: newTreeMap,
  6708. nativelyRenderedContent: null
  6709. });
  6710. return;
  6711. }
  6712. var existingContent = editorState.getCurrentContent();
  6713. if (newContent !== existingContent) {
  6714. state.set('treeMap', regenerateTreeForNewBlocks(editorState, newContent.getBlockMap(), newContent.getEntityMap(), decorator));
  6715. }
  6716. state.merge(put);
  6717. });
  6718. return new EditorState(map);
  6719. };
  6720. EditorState.prototype.toJS = function toJS() {
  6721. return this.getImmutable().toJS();
  6722. };
  6723. EditorState.prototype.getAllowUndo = function getAllowUndo() {
  6724. return this.getImmutable().get('allowUndo');
  6725. };
  6726. EditorState.prototype.getCurrentContent = function getCurrentContent() {
  6727. return this.getImmutable().get('currentContent');
  6728. };
  6729. EditorState.prototype.getUndoStack = function getUndoStack() {
  6730. return this.getImmutable().get('undoStack');
  6731. };
  6732. EditorState.prototype.getRedoStack = function getRedoStack() {
  6733. return this.getImmutable().get('redoStack');
  6734. };
  6735. EditorState.prototype.getSelection = function getSelection() {
  6736. return this.getImmutable().get('selection');
  6737. };
  6738. EditorState.prototype.getDecorator = function getDecorator() {
  6739. return this.getImmutable().get('decorator');
  6740. };
  6741. EditorState.prototype.isInCompositionMode = function isInCompositionMode() {
  6742. return this.getImmutable().get('inCompositionMode');
  6743. };
  6744. EditorState.prototype.mustForceSelection = function mustForceSelection() {
  6745. return this.getImmutable().get('forceSelection');
  6746. };
  6747. EditorState.prototype.getNativelyRenderedContent = function getNativelyRenderedContent() {
  6748. return this.getImmutable().get('nativelyRenderedContent');
  6749. };
  6750. EditorState.prototype.getLastChangeType = function getLastChangeType() {
  6751. return this.getImmutable().get('lastChangeType');
  6752. };
  6753. /**
  6754. * While editing, the user may apply inline style commands with a collapsed
  6755. * cursor, intending to type text that adopts the specified style. In this
  6756. * case, we track the specified style as an "override" that takes precedence
  6757. * over the inline style of the text adjacent to the cursor.
  6758. *
  6759. * If null, there is no override in place.
  6760. */
  6761. EditorState.prototype.getInlineStyleOverride = function getInlineStyleOverride() {
  6762. return this.getImmutable().get('inlineStyleOverride');
  6763. };
  6764. EditorState.setInlineStyleOverride = function setInlineStyleOverride(editorState, inlineStyleOverride) {
  6765. return EditorState.set(editorState, { inlineStyleOverride: inlineStyleOverride });
  6766. };
  6767. /**
  6768. * Get the appropriate inline style for the editor state. If an
  6769. * override is in place, use it. Otherwise, the current style is
  6770. * based on the location of the selection state.
  6771. */
  6772. EditorState.prototype.getCurrentInlineStyle = function getCurrentInlineStyle() {
  6773. var override = this.getInlineStyleOverride();
  6774. if (override != null) {
  6775. return override;
  6776. }
  6777. var content = this.getCurrentContent();
  6778. var selection = this.getSelection();
  6779. if (selection.isCollapsed()) {
  6780. return getInlineStyleForCollapsedSelection(content, selection);
  6781. }
  6782. return getInlineStyleForNonCollapsedSelection(content, selection);
  6783. };
  6784. EditorState.prototype.getBlockTree = function getBlockTree(blockKey) {
  6785. return this.getImmutable().getIn(['treeMap', blockKey]);
  6786. };
  6787. EditorState.prototype.isSelectionAtStartOfContent = function isSelectionAtStartOfContent() {
  6788. var firstKey = this.getCurrentContent().getBlockMap().first().getKey();
  6789. return this.getSelection().hasEdgeWithin(firstKey, 0, 0);
  6790. };
  6791. EditorState.prototype.isSelectionAtEndOfContent = function isSelectionAtEndOfContent() {
  6792. var content = this.getCurrentContent();
  6793. var blockMap = content.getBlockMap();
  6794. var last = blockMap.last();
  6795. var end = last.getLength();
  6796. return this.getSelection().hasEdgeWithin(last.getKey(), end, end);
  6797. };
  6798. EditorState.prototype.getDirectionMap = function getDirectionMap() {
  6799. return this.getImmutable().get('directionMap');
  6800. };
  6801. /**
  6802. * Incorporate native DOM selection changes into the EditorState. This
  6803. * method can be used when we simply want to accept whatever the DOM
  6804. * has given us to represent selection, and we do not need to re-render
  6805. * the editor.
  6806. *
  6807. * To forcibly move the DOM selection, see `EditorState.forceSelection`.
  6808. */
  6809. EditorState.acceptSelection = function acceptSelection(editorState, selection) {
  6810. return updateSelection(editorState, selection, false);
  6811. };
  6812. /**
  6813. * At times, we need to force the DOM selection to be where we
  6814. * need it to be. This can occur when the anchor or focus nodes
  6815. * are non-text nodes, for instance. In this case, we want to trigger
  6816. * a re-render of the editor, which in turn forces selection into
  6817. * the correct place in the DOM. The `forceSelection` method
  6818. * accomplishes this.
  6819. *
  6820. * This method should be used in cases where you need to explicitly
  6821. * move the DOM selection from one place to another without a change
  6822. * in ContentState.
  6823. */
  6824. EditorState.forceSelection = function forceSelection(editorState, selection) {
  6825. if (!selection.getHasFocus()) {
  6826. selection = selection.set('hasFocus', true);
  6827. }
  6828. return updateSelection(editorState, selection, true);
  6829. };
  6830. /**
  6831. * Move selection to the end of the editor without forcing focus.
  6832. */
  6833. EditorState.moveSelectionToEnd = function moveSelectionToEnd(editorState) {
  6834. var content = editorState.getCurrentContent();
  6835. var lastBlock = content.getLastBlock();
  6836. var lastKey = lastBlock.getKey();
  6837. var length = lastBlock.getLength();
  6838. return EditorState.acceptSelection(editorState, new SelectionState_1({
  6839. anchorKey: lastKey,
  6840. anchorOffset: length,
  6841. focusKey: lastKey,
  6842. focusOffset: length,
  6843. isBackward: false
  6844. }));
  6845. };
  6846. /**
  6847. * Force focus to the end of the editor. This is useful in scenarios
  6848. * where we want to programmatically focus the input and it makes sense
  6849. * to allow the user to continue working seamlessly.
  6850. */
  6851. EditorState.moveFocusToEnd = function moveFocusToEnd(editorState) {
  6852. var afterSelectionMove = EditorState.moveSelectionToEnd(editorState);
  6853. return EditorState.forceSelection(afterSelectionMove, afterSelectionMove.getSelection());
  6854. };
  6855. /**
  6856. * Push the current ContentState onto the undo stack if it should be
  6857. * considered a boundary state, and set the provided ContentState as the
  6858. * new current content.
  6859. */
  6860. EditorState.push = function push(editorState, contentState, changeType) {
  6861. if (editorState.getCurrentContent() === contentState) {
  6862. return editorState;
  6863. }
  6864. var forceSelection = changeType !== 'insert-characters';
  6865. var directionMap = EditorBidiService_1.getDirectionMap(contentState, editorState.getDirectionMap());
  6866. if (!editorState.getAllowUndo()) {
  6867. return EditorState.set(editorState, {
  6868. currentContent: contentState,
  6869. directionMap: directionMap,
  6870. lastChangeType: changeType,
  6871. selection: contentState.getSelectionAfter(),
  6872. forceSelection: forceSelection,
  6873. inlineStyleOverride: null
  6874. });
  6875. }
  6876. var selection = editorState.getSelection();
  6877. var currentContent = editorState.getCurrentContent();
  6878. var undoStack = editorState.getUndoStack();
  6879. var newContent = contentState;
  6880. if (selection !== currentContent.getSelectionAfter() || mustBecomeBoundary(editorState, changeType)) {
  6881. undoStack = undoStack.push(currentContent);
  6882. newContent = newContent.set('selectionBefore', selection);
  6883. } else if (changeType === 'insert-characters' || changeType === 'backspace-character' || changeType === 'delete-character') {
  6884. // Preserve the previous selection.
  6885. newContent = newContent.set('selectionBefore', currentContent.getSelectionBefore());
  6886. }
  6887. var inlineStyleOverride = editorState.getInlineStyleOverride();
  6888. // Don't discard inline style overrides for the following change types:
  6889. var overrideChangeTypes = ['adjust-depth', 'change-block-type', 'split-block'];
  6890. if (overrideChangeTypes.indexOf(changeType) === -1) {
  6891. inlineStyleOverride = null;
  6892. }
  6893. var editorStateChanges = {
  6894. currentContent: newContent,
  6895. directionMap: directionMap,
  6896. undoStack: undoStack,
  6897. redoStack: Stack(),
  6898. lastChangeType: changeType,
  6899. selection: contentState.getSelectionAfter(),
  6900. forceSelection: forceSelection,
  6901. inlineStyleOverride: inlineStyleOverride
  6902. };
  6903. return EditorState.set(editorState, editorStateChanges);
  6904. };
  6905. /**
  6906. * Make the top ContentState in the undo stack the new current content and
  6907. * push the current content onto the redo stack.
  6908. */
  6909. EditorState.undo = function undo(editorState) {
  6910. if (!editorState.getAllowUndo()) {
  6911. return editorState;
  6912. }
  6913. var undoStack = editorState.getUndoStack();
  6914. var newCurrentContent = undoStack.peek();
  6915. if (!newCurrentContent) {
  6916. return editorState;
  6917. }
  6918. var currentContent = editorState.getCurrentContent();
  6919. var directionMap = EditorBidiService_1.getDirectionMap(newCurrentContent, editorState.getDirectionMap());
  6920. return EditorState.set(editorState, {
  6921. currentContent: newCurrentContent,
  6922. directionMap: directionMap,
  6923. undoStack: undoStack.shift(),
  6924. redoStack: editorState.getRedoStack().push(currentContent),
  6925. forceSelection: true,
  6926. inlineStyleOverride: null,
  6927. lastChangeType: 'undo',
  6928. nativelyRenderedContent: null,
  6929. selection: currentContent.getSelectionBefore()
  6930. });
  6931. };
  6932. /**
  6933. * Make the top ContentState in the redo stack the new current content and
  6934. * push the current content onto the undo stack.
  6935. */
  6936. EditorState.redo = function redo(editorState) {
  6937. if (!editorState.getAllowUndo()) {
  6938. return editorState;
  6939. }
  6940. var redoStack = editorState.getRedoStack();
  6941. var newCurrentContent = redoStack.peek();
  6942. if (!newCurrentContent) {
  6943. return editorState;
  6944. }
  6945. var currentContent = editorState.getCurrentContent();
  6946. var directionMap = EditorBidiService_1.getDirectionMap(newCurrentContent, editorState.getDirectionMap());
  6947. return EditorState.set(editorState, {
  6948. currentContent: newCurrentContent,
  6949. directionMap: directionMap,
  6950. undoStack: editorState.getUndoStack().push(currentContent),
  6951. redoStack: redoStack.shift(),
  6952. forceSelection: true,
  6953. inlineStyleOverride: null,
  6954. lastChangeType: 'redo',
  6955. nativelyRenderedContent: null,
  6956. selection: newCurrentContent.getSelectionAfter()
  6957. });
  6958. };
  6959. /**
  6960. * Not for public consumption.
  6961. */
  6962. function EditorState(immutable) {
  6963. _classCallCheck$7(this, EditorState);
  6964. this._immutable = immutable;
  6965. }
  6966. /**
  6967. * Not for public consumption.
  6968. */
  6969. EditorState.prototype.getImmutable = function getImmutable() {
  6970. return this._immutable;
  6971. };
  6972. return EditorState;
  6973. }();
  6974. /**
  6975. * Set the supplied SelectionState as the new current selection, and set
  6976. * the `force` flag to trigger manual selection placement by the view.
  6977. */
  6978. function updateSelection(editorState, selection, forceSelection) {
  6979. return EditorState.set(editorState, {
  6980. selection: selection,
  6981. forceSelection: forceSelection,
  6982. nativelyRenderedContent: null,
  6983. inlineStyleOverride: null
  6984. });
  6985. }
  6986. /**
  6987. * Regenerate the entire tree map for a given ContentState and decorator.
  6988. * Returns an OrderedMap that maps all available ContentBlock objects.
  6989. */
  6990. function generateNewTreeMap(contentState, decorator) {
  6991. return contentState.getBlockMap().map(function (block) {
  6992. return BlockTree_1.generate(contentState, block, decorator);
  6993. }).toOrderedMap();
  6994. }
  6995. /**
  6996. * Regenerate tree map objects for all ContentBlocks that have changed
  6997. * between the current editorState and newContent. Returns an OrderedMap
  6998. * with only changed regenerated tree map objects.
  6999. */
  7000. function regenerateTreeForNewBlocks(editorState, newBlockMap, newEntityMap, decorator) {
  7001. var contentState = editorState.getCurrentContent().set('entityMap', newEntityMap);
  7002. var prevBlockMap = contentState.getBlockMap();
  7003. var prevTreeMap = editorState.getImmutable().get('treeMap');
  7004. return prevTreeMap.merge(newBlockMap.toSeq().filter(function (block, key) {
  7005. return block !== prevBlockMap.get(key);
  7006. }).map(function (block) {
  7007. return BlockTree_1.generate(contentState, block, decorator);
  7008. }));
  7009. }
  7010. /**
  7011. * Generate tree map objects for a new decorator object, preserving any
  7012. * decorations that are unchanged from the previous decorator.
  7013. *
  7014. * Note that in order for this to perform optimally, decoration Lists for
  7015. * decorators should be preserved when possible to allow for direct immutable
  7016. * List comparison.
  7017. */
  7018. function regenerateTreeForNewDecorator(content, blockMap, previousTreeMap, decorator, existingDecorator) {
  7019. return previousTreeMap.merge(blockMap.toSeq().filter(function (block) {
  7020. return decorator.getDecorations(block, content) !== existingDecorator.getDecorations(block, content);
  7021. }).map(function (block) {
  7022. return BlockTree_1.generate(content, block, decorator);
  7023. }));
  7024. }
  7025. /**
  7026. * Return whether a change should be considered a boundary state, given
  7027. * the previous change type. Allows us to discard potential boundary states
  7028. * during standard typing or deletion behavior.
  7029. */
  7030. function mustBecomeBoundary(editorState, changeType) {
  7031. var lastChangeType = editorState.getLastChangeType();
  7032. return changeType !== lastChangeType || changeType !== 'insert-characters' && changeType !== 'backspace-character' && changeType !== 'delete-character';
  7033. }
  7034. function getInlineStyleForCollapsedSelection(content, selection) {
  7035. var startKey = selection.getStartKey();
  7036. var startOffset = selection.getStartOffset();
  7037. var startBlock = content.getBlockForKey(startKey);
  7038. // If the cursor is not at the start of the block, look backward to
  7039. // preserve the style of the preceding character.
  7040. if (startOffset > 0) {
  7041. return startBlock.getInlineStyleAt(startOffset - 1);
  7042. }
  7043. // The caret is at position zero in this block. If the block has any
  7044. // text at all, use the style of the first character.
  7045. if (startBlock.getLength()) {
  7046. return startBlock.getInlineStyleAt(0);
  7047. }
  7048. // Otherwise, look upward in the document to find the closest character.
  7049. return lookUpwardForInlineStyle(content, startKey);
  7050. }
  7051. function getInlineStyleForNonCollapsedSelection(content, selection) {
  7052. var startKey = selection.getStartKey();
  7053. var startOffset = selection.getStartOffset();
  7054. var startBlock = content.getBlockForKey(startKey);
  7055. // If there is a character just inside the selection, use its style.
  7056. if (startOffset < startBlock.getLength()) {
  7057. return startBlock.getInlineStyleAt(startOffset);
  7058. }
  7059. // Check if the selection at the end of a non-empty block. Use the last
  7060. // style in the block.
  7061. if (startOffset > 0) {
  7062. return startBlock.getInlineStyleAt(startOffset - 1);
  7063. }
  7064. // Otherwise, look upward in the document to find the closest character.
  7065. return lookUpwardForInlineStyle(content, startKey);
  7066. }
  7067. function lookUpwardForInlineStyle(content, fromKey) {
  7068. var lastNonEmpty = content.getBlockMap().reverse().skipUntil(function (_, k) {
  7069. return k === fromKey;
  7070. }).skip(1).skipUntil(function (block, _) {
  7071. return block.getLength();
  7072. }).first();
  7073. if (lastNonEmpty) return lastNonEmpty.getInlineStyleAt(lastNonEmpty.getLength() - 1);
  7074. return OrderedSet$4();
  7075. }
  7076. var EditorState_1 = EditorState;
  7077. var OrderedMap$3 = immutable.OrderedMap,
  7078. List$7 = immutable.List;
  7079. var transformBlock$2 = function transformBlock(key, blockMap, func) {
  7080. if (!key) {
  7081. return;
  7082. }
  7083. var block = blockMap.get(key);
  7084. if (!block) {
  7085. return;
  7086. }
  7087. blockMap.set(key, func(block));
  7088. };
  7089. var updateBlockMapLinks$3 = function updateBlockMapLinks(blockMap, originalBlockToBeMoved, originalTargetBlock, insertionMode, isExperimentalTreeBlock) {
  7090. if (!isExperimentalTreeBlock) {
  7091. return blockMap;
  7092. }
  7093. // possible values of 'insertionMode' are: 'after', 'before'
  7094. var isInsertedAfterTarget = insertionMode === 'after';
  7095. var originalBlockKey = originalBlockToBeMoved.getKey();
  7096. var originalTargetKey = originalTargetBlock.getKey();
  7097. var originalParentKey = originalBlockToBeMoved.getParentKey();
  7098. var originalNextSiblingKey = originalBlockToBeMoved.getNextSiblingKey();
  7099. var originalPrevSiblingKey = originalBlockToBeMoved.getPrevSiblingKey();
  7100. var newParentKey = originalTargetBlock.getParentKey();
  7101. var newNextSiblingKey = isInsertedAfterTarget ? originalTargetBlock.getNextSiblingKey() : originalTargetKey;
  7102. var newPrevSiblingKey = isInsertedAfterTarget ? originalTargetKey : originalTargetBlock.getPrevSiblingKey();
  7103. return blockMap.withMutations(function (blocks) {
  7104. // update old parent
  7105. transformBlock$2(originalParentKey, blocks, function (block) {
  7106. var parentChildrenList = block.getChildKeys();
  7107. return block.merge({
  7108. children: parentChildrenList['delete'](parentChildrenList.indexOf(originalBlockKey))
  7109. });
  7110. });
  7111. // update old prev
  7112. transformBlock$2(originalPrevSiblingKey, blocks, function (block) {
  7113. return block.merge({
  7114. nextSibling: originalNextSiblingKey
  7115. });
  7116. });
  7117. // update old next
  7118. transformBlock$2(originalNextSiblingKey, blocks, function (block) {
  7119. return block.merge({
  7120. prevSibling: originalPrevSiblingKey
  7121. });
  7122. });
  7123. // update new next
  7124. transformBlock$2(newNextSiblingKey, blocks, function (block) {
  7125. return block.merge({
  7126. prevSibling: originalBlockKey
  7127. });
  7128. });
  7129. // update new prev
  7130. transformBlock$2(newPrevSiblingKey, blocks, function (block) {
  7131. return block.merge({
  7132. nextSibling: originalBlockKey
  7133. });
  7134. });
  7135. // update new parent
  7136. transformBlock$2(newParentKey, blocks, function (block) {
  7137. var newParentChildrenList = block.getChildKeys();
  7138. var targetBlockIndex = newParentChildrenList.indexOf(originalTargetKey);
  7139. var insertionIndex = isInsertedAfterTarget ? targetBlockIndex + 1 : targetBlockIndex !== 0 ? targetBlockIndex - 1 : 0;
  7140. var newChildrenArray = newParentChildrenList.toArray();
  7141. newChildrenArray.splice(insertionIndex, 0, originalBlockKey);
  7142. return block.merge({
  7143. children: List$7(newChildrenArray)
  7144. });
  7145. });
  7146. // update block
  7147. transformBlock$2(originalBlockKey, blocks, function (block) {
  7148. return block.merge({
  7149. nextSibling: newNextSiblingKey,
  7150. prevSibling: newPrevSiblingKey,
  7151. parent: newParentKey
  7152. });
  7153. });
  7154. });
  7155. };
  7156. var moveBlockInContentState = function moveBlockInContentState(contentState, blockToBeMoved, targetBlock, insertionMode) {
  7157. !(insertionMode !== 'replace') ? process.env.NODE_ENV !== 'production' ? invariant_1(false, 'Replacing blocks is not supported.') : invariant_1(false) : void 0;
  7158. var targetKey = targetBlock.getKey();
  7159. var blockKey = blockToBeMoved.getKey();
  7160. !(blockKey !== targetKey) ? process.env.NODE_ENV !== 'production' ? invariant_1(false, 'Block cannot be moved next to itself.') : invariant_1(false) : void 0;
  7161. var blockMap = contentState.getBlockMap();
  7162. var isExperimentalTreeBlock = blockToBeMoved instanceof ContentBlockNode_1;
  7163. var blocksToBeMoved = [blockToBeMoved];
  7164. var blockMapWithoutBlocksToBeMoved = blockMap['delete'](blockKey);
  7165. if (isExperimentalTreeBlock) {
  7166. blocksToBeMoved = [];
  7167. blockMapWithoutBlocksToBeMoved = blockMap.withMutations(function (blocks) {
  7168. var nextSiblingKey = blockToBeMoved.getNextSiblingKey();
  7169. var nextDelimiterBlockKey = getNextDelimiterBlockKey_1(blockToBeMoved, blocks);
  7170. blocks.toSeq().skipUntil(function (block) {
  7171. return block.getKey() === blockKey;
  7172. }).takeWhile(function (block) {
  7173. var key = block.getKey();
  7174. var isBlockToBeMoved = key === blockKey;
  7175. var hasNextSiblingAndIsNotNextSibling = nextSiblingKey && key !== nextSiblingKey;
  7176. var doesNotHaveNextSiblingAndIsNotDelimiter = !nextSiblingKey && block.getParentKey() && (!nextDelimiterBlockKey || key !== nextDelimiterBlockKey);
  7177. return !!(isBlockToBeMoved || hasNextSiblingAndIsNotNextSibling || doesNotHaveNextSiblingAndIsNotDelimiter);
  7178. }).forEach(function (block) {
  7179. blocksToBeMoved.push(block);
  7180. blocks['delete'](block.getKey());
  7181. });
  7182. });
  7183. }
  7184. var blocksBefore = blockMapWithoutBlocksToBeMoved.toSeq().takeUntil(function (v) {
  7185. return v === targetBlock;
  7186. });
  7187. var blocksAfter = blockMapWithoutBlocksToBeMoved.toSeq().skipUntil(function (v) {
  7188. return v === targetBlock;
  7189. }).skip(1);
  7190. var slicedBlocks = blocksToBeMoved.map(function (block) {
  7191. return [block.getKey(), block];
  7192. });
  7193. var newBlocks = OrderedMap$3();
  7194. if (insertionMode === 'before') {
  7195. var blockBefore = contentState.getBlockBefore(targetKey);
  7196. !(!blockBefore || blockBefore.getKey() !== blockToBeMoved.getKey()) ? process.env.NODE_ENV !== 'production' ? invariant_1(false, 'Block cannot be moved next to itself.') : invariant_1(false) : void 0;
  7197. newBlocks = blocksBefore.concat([].concat(slicedBlocks, [[targetKey, targetBlock]]), blocksAfter).toOrderedMap();
  7198. } else if (insertionMode === 'after') {
  7199. var blockAfter = contentState.getBlockAfter(targetKey);
  7200. !(!blockAfter || blockAfter.getKey() !== blockKey) ? process.env.NODE_ENV !== 'production' ? invariant_1(false, 'Block cannot be moved next to itself.') : invariant_1(false) : void 0;
  7201. newBlocks = blocksBefore.concat([[targetKey, targetBlock]].concat(slicedBlocks), blocksAfter).toOrderedMap();
  7202. }
  7203. return contentState.merge({
  7204. blockMap: updateBlockMapLinks$3(newBlocks, blockToBeMoved, targetBlock, insertionMode, isExperimentalTreeBlock),
  7205. selectionBefore: contentState.getSelectionAfter(),
  7206. selectionAfter: contentState.getSelectionAfter().merge({
  7207. anchorKey: blockKey,
  7208. focusKey: blockKey
  7209. })
  7210. });
  7211. };
  7212. var moveBlockInContentState_1 = moveBlockInContentState;
  7213. var ContentBlockRecord$1 = ContentBlock_1;
  7214. var List$8 = immutable.List,
  7215. Repeat$5 = immutable.Repeat;
  7216. var AtomicBlockUtils = {
  7217. insertAtomicBlock: function insertAtomicBlock(editorState, entityKey, character) {
  7218. var contentState = editorState.getCurrentContent();
  7219. var selectionState = editorState.getSelection();
  7220. var afterRemoval = DraftModifier_1.removeRange(contentState, selectionState, 'backward');
  7221. var targetSelection = afterRemoval.getSelectionAfter();
  7222. var afterSplit = DraftModifier_1.splitBlock(afterRemoval, targetSelection);
  7223. var insertionTarget = afterSplit.getSelectionAfter();
  7224. var asAtomicBlock = DraftModifier_1.setBlockType(afterSplit, insertionTarget, 'atomic');
  7225. var charData = CharacterMetadata_1.create({ entity: entityKey });
  7226. var atomicBlockConfig = {
  7227. key: generateRandomKey_1(),
  7228. type: 'atomic',
  7229. text: character,
  7230. characterList: List$8(Repeat$5(charData, character.length))
  7231. };
  7232. var atomicDividerBlockConfig = {
  7233. key: generateRandomKey_1(),
  7234. type: 'unstyled'
  7235. };
  7236. var fragmentArray = [new ContentBlockRecord$1(atomicBlockConfig), new ContentBlockRecord$1(atomicDividerBlockConfig)];
  7237. var fragment = BlockMapBuilder_1.createFromArray(fragmentArray);
  7238. var withAtomicBlock = DraftModifier_1.replaceWithFragment(asAtomicBlock, insertionTarget, fragment);
  7239. var newContent = withAtomicBlock.merge({
  7240. selectionBefore: selectionState,
  7241. selectionAfter: withAtomicBlock.getSelectionAfter().set('hasFocus', true)
  7242. });
  7243. return EditorState_1.push(editorState, newContent, 'insert-fragment');
  7244. },
  7245. moveAtomicBlock: function moveAtomicBlock(editorState, atomicBlock, targetRange, insertionMode) {
  7246. var contentState = editorState.getCurrentContent();
  7247. var selectionState = editorState.getSelection();
  7248. var withMovedAtomicBlock = void 0;
  7249. if (insertionMode === 'before' || insertionMode === 'after') {
  7250. var targetBlock = contentState.getBlockForKey(insertionMode === 'before' ? targetRange.getStartKey() : targetRange.getEndKey());
  7251. withMovedAtomicBlock = moveBlockInContentState_1(contentState, atomicBlock, targetBlock, insertionMode);
  7252. } else {
  7253. var afterRemoval = DraftModifier_1.removeRange(contentState, targetRange, 'backward');
  7254. var selectionAfterRemoval = afterRemoval.getSelectionAfter();
  7255. var _targetBlock = afterRemoval.getBlockForKey(selectionAfterRemoval.getFocusKey());
  7256. if (selectionAfterRemoval.getStartOffset() === 0) {
  7257. withMovedAtomicBlock = moveBlockInContentState_1(afterRemoval, atomicBlock, _targetBlock, 'before');
  7258. } else if (selectionAfterRemoval.getEndOffset() === _targetBlock.getLength()) {
  7259. withMovedAtomicBlock = moveBlockInContentState_1(afterRemoval, atomicBlock, _targetBlock, 'after');
  7260. } else {
  7261. var afterSplit = DraftModifier_1.splitBlock(afterRemoval, selectionAfterRemoval);
  7262. var selectionAfterSplit = afterSplit.getSelectionAfter();
  7263. var _targetBlock2 = afterSplit.getBlockForKey(selectionAfterSplit.getFocusKey());
  7264. withMovedAtomicBlock = moveBlockInContentState_1(afterSplit, atomicBlock, _targetBlock2, 'before');
  7265. }
  7266. }
  7267. var newContent = withMovedAtomicBlock.merge({
  7268. selectionBefore: selectionState,
  7269. selectionAfter: withMovedAtomicBlock.getSelectionAfter().set('hasFocus', true)
  7270. });
  7271. return EditorState_1.push(editorState, newContent, 'move-block');
  7272. }
  7273. };
  7274. var AtomicBlockUtils_1 = AtomicBlockUtils;
  7275. function _classCallCheck$8(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  7276. var List$9 = immutable.List;
  7277. var DELIMITER = '.';
  7278. /**
  7279. * A CompositeDraftDecorator traverses through a list of DraftDecorator
  7280. * instances to identify sections of a ContentBlock that should be rendered
  7281. * in a "decorated" manner. For example, hashtags, mentions, and links may
  7282. * be intended to stand out visually, be rendered as anchors, etc.
  7283. *
  7284. * The list of decorators supplied to the constructor will be used in the
  7285. * order they are provided. This allows the caller to specify a priority for
  7286. * string matching, in case of match collisions among decorators.
  7287. *
  7288. * For instance, I may have a link with a `#` in its text. Though this section
  7289. * of text may match our hashtag decorator, it should not be treated as a
  7290. * hashtag. I should therefore list my link DraftDecorator
  7291. * before my hashtag DraftDecorator when constructing this composite
  7292. * decorator instance.
  7293. *
  7294. * Thus, when a collision like this is encountered, the earlier match is
  7295. * preserved and the new match is discarded.
  7296. */
  7297. var CompositeDraftDecorator = function () {
  7298. function CompositeDraftDecorator(decorators) {
  7299. _classCallCheck$8(this, CompositeDraftDecorator);
  7300. // Copy the decorator array, since we use this array order to determine
  7301. // precedence of decoration matching. If the array is mutated externally,
  7302. // we don't want to be affected here.
  7303. this._decorators = decorators.slice();
  7304. }
  7305. CompositeDraftDecorator.prototype.getDecorations = function getDecorations(block, contentState) {
  7306. var decorations = Array(block.getText().length).fill(null);
  7307. this._decorators.forEach(function ( /*object*/decorator, /*number*/ii) {
  7308. var counter = 0;
  7309. var strategy = decorator.strategy;
  7310. var callback = function callback( /*number*/start, /*number*/end) {
  7311. // Find out if any of our matching range is already occupied
  7312. // by another decorator. If so, discard the match. Otherwise, store
  7313. // the component key for rendering.
  7314. if (canOccupySlice(decorations, start, end)) {
  7315. occupySlice(decorations, start, end, ii + DELIMITER + counter);
  7316. counter++;
  7317. }
  7318. };
  7319. strategy(block, callback, contentState);
  7320. });
  7321. return List$9(decorations);
  7322. };
  7323. CompositeDraftDecorator.prototype.getComponentForKey = function getComponentForKey(key) {
  7324. var componentKey = parseInt(key.split(DELIMITER)[0], 10);
  7325. return this._decorators[componentKey].component;
  7326. };
  7327. CompositeDraftDecorator.prototype.getPropsForKey = function getPropsForKey(key) {
  7328. var componentKey = parseInt(key.split(DELIMITER)[0], 10);
  7329. return this._decorators[componentKey].props;
  7330. };
  7331. return CompositeDraftDecorator;
  7332. }();
  7333. /**
  7334. * Determine whether we can occupy the specified slice of the decorations
  7335. * array.
  7336. */
  7337. function canOccupySlice(decorations, start, end) {
  7338. for (var ii = start; ii < end; ii++) {
  7339. if (decorations[ii] != null) {
  7340. return false;
  7341. }
  7342. }
  7343. return true;
  7344. }
  7345. /**
  7346. * Splice the specified component into our decoration array at the desired
  7347. * range.
  7348. */
  7349. function occupySlice(targetArr, start, end, componentKey) {
  7350. for (var ii = start; ii < end; ii++) {
  7351. targetArr[ii] = componentKey;
  7352. }
  7353. }
  7354. var CompositeDraftDecorator_1 = CompositeDraftDecorator;
  7355. /**
  7356. * Copyright (c) 2013-present, Facebook, Inc.
  7357. *
  7358. * This source code is licensed under the MIT license found in the
  7359. * LICENSE file in the root directory of this source tree.
  7360. *
  7361. */
  7362. /**
  7363. * This function is used to mark string literals representing CSS class names
  7364. * so that they can be transformed statically. This allows for modularization
  7365. * and minification of CSS class names.
  7366. *
  7367. * In static_upstream, this function is actually implemented, but it should
  7368. * eventually be replaced with something more descriptive, and the transform
  7369. * that is used in the main stack should be ported for use elsewhere.
  7370. *
  7371. * @param string|object className to modularize, or an object of key/values.
  7372. * In the object case, the values are conditions that
  7373. * determine if the className keys should be included.
  7374. * @param [string ...] Variable list of classNames in the string case.
  7375. * @return string Renderable space-separated CSS className.
  7376. */
  7377. function cx(classNames) {
  7378. if (typeof classNames == 'object') {
  7379. return Object.keys(classNames).filter(function (className) {
  7380. return classNames[className];
  7381. }).map(replace).join(' ');
  7382. }
  7383. return Array.prototype.map.call(arguments, replace).join(' ');
  7384. }
  7385. function replace(str) {
  7386. return str.replace(/\//g, '-');
  7387. }
  7388. var cx_1 = cx;
  7389. var Map$9 = immutable.Map;
  7390. var UL_WRAP = React.createElement('ul', { className: cx_1('public/DraftStyleDefault/ul') });
  7391. var OL_WRAP = React.createElement('ol', { className: cx_1('public/DraftStyleDefault/ol') });
  7392. var PRE_WRAP = React.createElement('pre', { className: cx_1('public/DraftStyleDefault/pre') });
  7393. var DefaultDraftBlockRenderMap = Map$9({
  7394. 'header-one': {
  7395. element: 'h1'
  7396. },
  7397. 'header-two': {
  7398. element: 'h2'
  7399. },
  7400. 'header-three': {
  7401. element: 'h3'
  7402. },
  7403. 'header-four': {
  7404. element: 'h4'
  7405. },
  7406. 'header-five': {
  7407. element: 'h5'
  7408. },
  7409. 'header-six': {
  7410. element: 'h6'
  7411. },
  7412. 'unordered-list-item': {
  7413. element: 'li',
  7414. wrapper: UL_WRAP
  7415. },
  7416. 'ordered-list-item': {
  7417. element: 'li',
  7418. wrapper: OL_WRAP
  7419. },
  7420. blockquote: {
  7421. element: 'blockquote'
  7422. },
  7423. atomic: {
  7424. element: 'figure'
  7425. },
  7426. 'code-block': {
  7427. element: 'pre',
  7428. wrapper: PRE_WRAP
  7429. },
  7430. unstyled: {
  7431. element: 'div',
  7432. aliasedElements: ['p']
  7433. }
  7434. });
  7435. var DefaultDraftBlockRenderMap_1 = DefaultDraftBlockRenderMap;
  7436. /**
  7437. * Copyright (c) 2013-present, Facebook, Inc.
  7438. * All rights reserved.
  7439. *
  7440. * This source code is licensed under the BSD-style license found in the
  7441. * LICENSE file in the root directory of this source tree. An additional grant
  7442. * of patent rights can be found in the PATENTS file in the same directory.
  7443. *
  7444. * @providesModule DefaultDraftInlineStyle
  7445. * @format
  7446. *
  7447. */
  7448. var DefaultDraftInlineStyle = {
  7449. BOLD: {
  7450. fontWeight: 'bold'
  7451. },
  7452. CODE: {
  7453. fontFamily: 'monospace',
  7454. wordWrap: 'break-word'
  7455. },
  7456. ITALIC: {
  7457. fontStyle: 'italic'
  7458. },
  7459. STRIKETHROUGH: {
  7460. textDecoration: 'line-through'
  7461. },
  7462. UNDERLINE: {
  7463. textDecoration: 'underline'
  7464. }
  7465. };
  7466. /**
  7467. * Copyright (c) 2013-present, Facebook, Inc.
  7468. *
  7469. * This source code is licensed under the MIT license found in the
  7470. * LICENSE file in the root directory of this source tree.
  7471. *
  7472. */
  7473. var Keys = {
  7474. BACKSPACE: 8,
  7475. TAB: 9,
  7476. RETURN: 13,
  7477. ALT: 18,
  7478. ESC: 27,
  7479. SPACE: 32,
  7480. PAGE_UP: 33,
  7481. PAGE_DOWN: 34,
  7482. END: 35,
  7483. HOME: 36,
  7484. LEFT: 37,
  7485. UP: 38,
  7486. RIGHT: 39,
  7487. DOWN: 40,
  7488. DELETE: 46,
  7489. COMMA: 188,
  7490. PERIOD: 190,
  7491. A: 65,
  7492. Z: 90,
  7493. ZERO: 48,
  7494. NUMPAD_0: 96,
  7495. NUMPAD_9: 105
  7496. };
  7497. /**
  7498. * Copyright (c) 2013-present, Facebook, Inc.
  7499. * All rights reserved.
  7500. *
  7501. * This source code is licensed under the BSD-style license found in the
  7502. * LICENSE file in the root directory of this source tree. An additional grant
  7503. * of patent rights can be found in the PATENTS file in the same directory.
  7504. *
  7505. * @providesModule getEntityKeyForSelection
  7506. * @format
  7507. *
  7508. */
  7509. /**
  7510. * Return the entity key that should be used when inserting text for the
  7511. * specified target selection, only if the entity is `MUTABLE`. `IMMUTABLE`
  7512. * and `SEGMENTED` entities should not be used for insertion behavior.
  7513. */
  7514. function getEntityKeyForSelection(contentState, targetSelection) {
  7515. var entityKey;
  7516. if (targetSelection.isCollapsed()) {
  7517. var key = targetSelection.getAnchorKey();
  7518. var offset = targetSelection.getAnchorOffset();
  7519. if (offset > 0) {
  7520. entityKey = contentState.getBlockForKey(key).getEntityAt(offset - 1);
  7521. if (entityKey !== contentState.getBlockForKey(key).getEntityAt(offset)) {
  7522. return null;
  7523. }
  7524. return filterKey(contentState.getEntityMap(), entityKey);
  7525. }
  7526. return null;
  7527. }
  7528. var startKey = targetSelection.getStartKey();
  7529. var startOffset = targetSelection.getStartOffset();
  7530. var startBlock = contentState.getBlockForKey(startKey);
  7531. entityKey = startOffset === startBlock.getLength() ? null : startBlock.getEntityAt(startOffset);
  7532. return filterKey(contentState.getEntityMap(), entityKey);
  7533. }
  7534. /**
  7535. * Determine whether an entity key corresponds to a `MUTABLE` entity. If so,
  7536. * return it. If not, return null.
  7537. */
  7538. function filterKey(entityMap, entityKey) {
  7539. if (entityKey) {
  7540. var entity = entityMap.__get(entityKey);
  7541. return entity.getMutability() === 'MUTABLE' ? entityKey : null;
  7542. }
  7543. return null;
  7544. }
  7545. var getEntityKeyForSelection_1 = getEntityKeyForSelection;
  7546. /**
  7547. * Copyright (c) 2013-present, Facebook, Inc.
  7548. * All rights reserved.
  7549. *
  7550. * This source code is licensed under the BSD-style license found in the
  7551. * LICENSE file in the root directory of this source tree. An additional grant
  7552. * of patent rights can be found in the PATENTS file in the same directory.
  7553. *
  7554. * @providesModule isEventHandled
  7555. * @format
  7556. *
  7557. */
  7558. /**
  7559. * Utility method for determining whether or not the value returned
  7560. * from a handler indicates that it was handled.
  7561. */
  7562. function isEventHandled(value) {
  7563. return value === 'handled' || value === true;
  7564. }
  7565. var isEventHandled_1 = isEventHandled;
  7566. /**
  7567. * Copyright (c) 2013-present, Facebook, Inc.
  7568. * All rights reserved.
  7569. *
  7570. * This source code is licensed under the BSD-style license found in the
  7571. * LICENSE file in the root directory of this source tree. An additional grant
  7572. * of patent rights can be found in the PATENTS file in the same directory.
  7573. *
  7574. * @providesModule isSelectionAtLeafStart
  7575. * @format
  7576. *
  7577. */
  7578. function isSelectionAtLeafStart(editorState) {
  7579. var selection = editorState.getSelection();
  7580. var anchorKey = selection.getAnchorKey();
  7581. var blockTree = editorState.getBlockTree(anchorKey);
  7582. var offset = selection.getStartOffset();
  7583. var isAtStart = false;
  7584. blockTree.some(function (leafSet) {
  7585. if (offset === leafSet.get('start')) {
  7586. isAtStart = true;
  7587. return true;
  7588. }
  7589. if (offset < leafSet.get('end')) {
  7590. return leafSet.get('leaves').some(function (leaf) {
  7591. var leafStart = leaf.get('start');
  7592. if (offset === leafStart) {
  7593. isAtStart = true;
  7594. return true;
  7595. }
  7596. return false;
  7597. });
  7598. }
  7599. return false;
  7600. });
  7601. return isAtStart;
  7602. }
  7603. var isSelectionAtLeafStart_1 = isSelectionAtLeafStart;
  7604. /**
  7605. * Millisecond delay to allow `compositionstart` to fire again upon
  7606. * `compositionend`.
  7607. *
  7608. * This is used for Korean input to ensure that typing can continue without
  7609. * the editor trying to render too quickly. More specifically, Safari 7.1+
  7610. * triggers `compositionstart` a little slower than Chrome/FF, which
  7611. * leads to composed characters being resolved and re-render occurring
  7612. * sooner than we want.
  7613. */
  7614. var RESOLVE_DELAY = 20;
  7615. /**
  7616. * A handful of variables used to track the current composition and its
  7617. * resolution status. These exist at the module level because it is not
  7618. * possible to have compositions occurring in multiple editors simultaneously,
  7619. * and it simplifies state management with respect to the DraftEditor component.
  7620. */
  7621. var resolved = false;
  7622. var stillComposing = false;
  7623. var textInputData = '';
  7624. var DraftEditorCompositionHandler = {
  7625. onBeforeInput: function onBeforeInput(editor, e) {
  7626. textInputData = (textInputData || '') + e.data;
  7627. },
  7628. /**
  7629. * A `compositionstart` event has fired while we're still in composition
  7630. * mode. Continue the current composition session to prevent a re-render.
  7631. */
  7632. onCompositionStart: function onCompositionStart(editor) {
  7633. stillComposing = true;
  7634. },
  7635. /**
  7636. * Attempt to end the current composition session.
  7637. *
  7638. * Defer handling because browser will still insert the chars into active
  7639. * element after `compositionend`. If a `compositionstart` event fires
  7640. * before `resolveComposition` executes, our composition session will
  7641. * continue.
  7642. *
  7643. * The `resolved` flag is useful because certain IME interfaces fire the
  7644. * `compositionend` event multiple times, thus queueing up multiple attempts
  7645. * at handling the composition. Since handling the same composition event
  7646. * twice could break the DOM, we only use the first event. Example: Arabic
  7647. * Google Input Tools on Windows 8.1 fires `compositionend` three times.
  7648. */
  7649. onCompositionEnd: function onCompositionEnd(editor) {
  7650. resolved = false;
  7651. stillComposing = false;
  7652. setTimeout(function () {
  7653. if (!resolved) {
  7654. DraftEditorCompositionHandler.resolveComposition(editor);
  7655. }
  7656. }, RESOLVE_DELAY);
  7657. },
  7658. /**
  7659. * In Safari, keydown events may fire when committing compositions. If
  7660. * the arrow keys are used to commit, prevent default so that the cursor
  7661. * doesn't move, otherwise it will jump back noticeably on re-render.
  7662. */
  7663. onKeyDown: function onKeyDown(editor, e) {
  7664. if (!stillComposing) {
  7665. // If a keydown event is received after compositionend but before the
  7666. // 20ms timer expires (ex: type option-E then backspace, or type A then
  7667. // backspace in 2-Set Korean), we should immediately resolve the
  7668. // composition and reinterpret the key press in edit mode.
  7669. DraftEditorCompositionHandler.resolveComposition(editor);
  7670. editor._onKeyDown(e);
  7671. return;
  7672. }
  7673. if (e.which === Keys.RIGHT || e.which === Keys.LEFT) {
  7674. e.preventDefault();
  7675. }
  7676. },
  7677. /**
  7678. * Keypress events may fire when committing compositions. In Firefox,
  7679. * pressing RETURN commits the composition and inserts extra newline
  7680. * characters that we do not want. `preventDefault` allows the composition
  7681. * to be committed while preventing the extra characters.
  7682. */
  7683. onKeyPress: function onKeyPress(editor, e) {
  7684. if (e.which === Keys.RETURN) {
  7685. e.preventDefault();
  7686. }
  7687. },
  7688. /**
  7689. * Attempt to insert composed characters into the document.
  7690. *
  7691. * If we are still in a composition session, do nothing. Otherwise, insert
  7692. * the characters into the document and terminate the composition session.
  7693. *
  7694. * If no characters were composed -- for instance, the user
  7695. * deleted all composed characters and committed nothing new --
  7696. * force a re-render. We also re-render when the composition occurs
  7697. * at the beginning of a leaf, to ensure that if the browser has
  7698. * created a new text node for the composition, we will discard it.
  7699. *
  7700. * Resetting innerHTML will move focus to the beginning of the editor,
  7701. * so we update to force it back to the correct place.
  7702. */
  7703. resolveComposition: function resolveComposition(editor) {
  7704. if (stillComposing) {
  7705. return;
  7706. }
  7707. resolved = true;
  7708. var composedChars = textInputData;
  7709. textInputData = '';
  7710. var editorState = EditorState_1.set(editor._latestEditorState, {
  7711. inCompositionMode: false
  7712. });
  7713. var currentStyle = editorState.getCurrentInlineStyle();
  7714. var entityKey = getEntityKeyForSelection_1(editorState.getCurrentContent(), editorState.getSelection());
  7715. var mustReset = !composedChars || isSelectionAtLeafStart_1(editorState) || currentStyle.size > 0 || entityKey !== null;
  7716. if (mustReset) {
  7717. editor.restoreEditorDOM();
  7718. }
  7719. editor.exitCurrentMode();
  7720. if (composedChars) {
  7721. // If characters have been composed, re-rendering with the update
  7722. // is sufficient to reset the editor.
  7723. var contentState = DraftModifier_1.replaceText(editorState.getCurrentContent(), editorState.getSelection(), composedChars, currentStyle, entityKey);
  7724. editor.update(EditorState_1.push(editorState, contentState, 'insert-characters'));
  7725. return;
  7726. }
  7727. if (mustReset) {
  7728. editor.update(EditorState_1.set(editorState, {
  7729. nativelyRenderedContent: null,
  7730. forceSelection: true
  7731. }));
  7732. }
  7733. }
  7734. };
  7735. var DraftEditorCompositionHandler_1 = DraftEditorCompositionHandler;
  7736. var uaParser = createCommonjsModule(function (module, exports) {
  7737. /*!
  7738. * UAParser.js v0.7.21
  7739. * Lightweight JavaScript-based User-Agent string parser
  7740. * https://github.com/faisalman/ua-parser-js
  7741. *
  7742. * Copyright © 2012-2019 Faisal Salman <f@faisalman.com>
  7743. * Licensed under MIT License
  7744. */
  7745. (function (window, undefined$1) {
  7746. //////////////
  7747. // Constants
  7748. /////////////
  7749. var LIBVERSION = '0.7.21',
  7750. EMPTY = '',
  7751. UNKNOWN = '?',
  7752. FUNC_TYPE = 'function',
  7753. OBJ_TYPE = 'object',
  7754. STR_TYPE = 'string',
  7755. MAJOR = 'major', // deprecated
  7756. MODEL = 'model',
  7757. NAME = 'name',
  7758. TYPE = 'type',
  7759. VENDOR = 'vendor',
  7760. VERSION = 'version',
  7761. ARCHITECTURE= 'architecture',
  7762. CONSOLE = 'console',
  7763. MOBILE = 'mobile',
  7764. TABLET = 'tablet',
  7765. SMARTTV = 'smarttv',
  7766. WEARABLE = 'wearable',
  7767. EMBEDDED = 'embedded';
  7768. ///////////
  7769. // Helper
  7770. //////////
  7771. var util = {
  7772. extend : function (regexes, extensions) {
  7773. var mergedRegexes = {};
  7774. for (var i in regexes) {
  7775. if (extensions[i] && extensions[i].length % 2 === 0) {
  7776. mergedRegexes[i] = extensions[i].concat(regexes[i]);
  7777. } else {
  7778. mergedRegexes[i] = regexes[i];
  7779. }
  7780. }
  7781. return mergedRegexes;
  7782. },
  7783. has : function (str1, str2) {
  7784. if (typeof str1 === "string") {
  7785. return str2.toLowerCase().indexOf(str1.toLowerCase()) !== -1;
  7786. } else {
  7787. return false;
  7788. }
  7789. },
  7790. lowerize : function (str) {
  7791. return str.toLowerCase();
  7792. },
  7793. major : function (version) {
  7794. return typeof(version) === STR_TYPE ? version.replace(/[^\d\.]/g,'').split(".")[0] : undefined$1;
  7795. },
  7796. trim : function (str) {
  7797. return str.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g, '');
  7798. }
  7799. };
  7800. ///////////////
  7801. // Map helper
  7802. //////////////
  7803. var mapper = {
  7804. rgx : function (ua, arrays) {
  7805. var i = 0, j, k, p, q, matches, match;
  7806. // loop through all regexes maps
  7807. while (i < arrays.length && !matches) {
  7808. var regex = arrays[i], // even sequence (0,2,4,..)
  7809. props = arrays[i + 1]; // odd sequence (1,3,5,..)
  7810. j = k = 0;
  7811. // try matching uastring with regexes
  7812. while (j < regex.length && !matches) {
  7813. matches = regex[j++].exec(ua);
  7814. if (!!matches) {
  7815. for (p = 0; p < props.length; p++) {
  7816. match = matches[++k];
  7817. q = props[p];
  7818. // check if given property is actually array
  7819. if (typeof q === OBJ_TYPE && q.length > 0) {
  7820. if (q.length == 2) {
  7821. if (typeof q[1] == FUNC_TYPE) {
  7822. // assign modified match
  7823. this[q[0]] = q[1].call(this, match);
  7824. } else {
  7825. // assign given value, ignore regex match
  7826. this[q[0]] = q[1];
  7827. }
  7828. } else if (q.length == 3) {
  7829. // check whether function or regex
  7830. if (typeof q[1] === FUNC_TYPE && !(q[1].exec && q[1].test)) {
  7831. // call function (usually string mapper)
  7832. this[q[0]] = match ? q[1].call(this, match, q[2]) : undefined$1;
  7833. } else {
  7834. // sanitize match using given regex
  7835. this[q[0]] = match ? match.replace(q[1], q[2]) : undefined$1;
  7836. }
  7837. } else if (q.length == 4) {
  7838. this[q[0]] = match ? q[3].call(this, match.replace(q[1], q[2])) : undefined$1;
  7839. }
  7840. } else {
  7841. this[q] = match ? match : undefined$1;
  7842. }
  7843. }
  7844. }
  7845. }
  7846. i += 2;
  7847. }
  7848. },
  7849. str : function (str, map) {
  7850. for (var i in map) {
  7851. // check if array
  7852. if (typeof map[i] === OBJ_TYPE && map[i].length > 0) {
  7853. for (var j = 0; j < map[i].length; j++) {
  7854. if (util.has(map[i][j], str)) {
  7855. return (i === UNKNOWN) ? undefined$1 : i;
  7856. }
  7857. }
  7858. } else if (util.has(map[i], str)) {
  7859. return (i === UNKNOWN) ? undefined$1 : i;
  7860. }
  7861. }
  7862. return str;
  7863. }
  7864. };
  7865. ///////////////
  7866. // String map
  7867. //////////////
  7868. var maps = {
  7869. browser : {
  7870. oldsafari : {
  7871. version : {
  7872. '1.0' : '/8',
  7873. '1.2' : '/1',
  7874. '1.3' : '/3',
  7875. '2.0' : '/412',
  7876. '2.0.2' : '/416',
  7877. '2.0.3' : '/417',
  7878. '2.0.4' : '/419',
  7879. '?' : '/'
  7880. }
  7881. }
  7882. },
  7883. device : {
  7884. amazon : {
  7885. model : {
  7886. 'Fire Phone' : ['SD', 'KF']
  7887. }
  7888. },
  7889. sprint : {
  7890. model : {
  7891. 'Evo Shift 4G' : '7373KT'
  7892. },
  7893. vendor : {
  7894. 'HTC' : 'APA',
  7895. 'Sprint' : 'Sprint'
  7896. }
  7897. }
  7898. },
  7899. os : {
  7900. windows : {
  7901. version : {
  7902. 'ME' : '4.90',
  7903. 'NT 3.11' : 'NT3.51',
  7904. 'NT 4.0' : 'NT4.0',
  7905. '2000' : 'NT 5.0',
  7906. 'XP' : ['NT 5.1', 'NT 5.2'],
  7907. 'Vista' : 'NT 6.0',
  7908. '7' : 'NT 6.1',
  7909. '8' : 'NT 6.2',
  7910. '8.1' : 'NT 6.3',
  7911. '10' : ['NT 6.4', 'NT 10.0'],
  7912. 'RT' : 'ARM'
  7913. }
  7914. }
  7915. }
  7916. };
  7917. //////////////
  7918. // Regex map
  7919. /////////////
  7920. var regexes = {
  7921. browser : [[
  7922. // Presto based
  7923. /(opera\smini)\/([\w\.-]+)/i, // Opera Mini
  7924. /(opera\s[mobiletab]+).+version\/([\w\.-]+)/i, // Opera Mobi/Tablet
  7925. /(opera).+version\/([\w\.]+)/i, // Opera > 9.80
  7926. /(opera)[\/\s]+([\w\.]+)/i // Opera < 9.80
  7927. ], [NAME, VERSION], [
  7928. /(opios)[\/\s]+([\w\.]+)/i // Opera mini on iphone >= 8.0
  7929. ], [[NAME, 'Opera Mini'], VERSION], [
  7930. /\s(opr)\/([\w\.]+)/i // Opera Webkit
  7931. ], [[NAME, 'Opera'], VERSION], [
  7932. // Mixed
  7933. /(kindle)\/([\w\.]+)/i, // Kindle
  7934. /(lunascape|maxthon|netfront|jasmine|blazer)[\/\s]?([\w\.]*)/i,
  7935. // Lunascape/Maxthon/Netfront/Jasmine/Blazer
  7936. // Trident based
  7937. /(avant\s|iemobile|slim)(?:browser)?[\/\s]?([\w\.]*)/i,
  7938. // Avant/IEMobile/SlimBrowser
  7939. /(bidubrowser|baidubrowser)[\/\s]?([\w\.]+)/i, // Baidu Browser
  7940. /(?:ms|\()(ie)\s([\w\.]+)/i, // Internet Explorer
  7941. // Webkit/KHTML based
  7942. /(rekonq)\/([\w\.]*)/i, // Rekonq
  7943. /(chromium|flock|rockmelt|midori|epiphany|silk|skyfire|ovibrowser|bolt|iron|vivaldi|iridium|phantomjs|bowser|quark|qupzilla|falkon)\/([\w\.-]+)/i
  7944. // Chromium/Flock/RockMelt/Midori/Epiphany/Silk/Skyfire/Bolt/Iron/Iridium/PhantomJS/Bowser/QupZilla/Falkon
  7945. ], [NAME, VERSION], [
  7946. /(konqueror)\/([\w\.]+)/i // Konqueror
  7947. ], [[NAME, 'Konqueror'], VERSION], [
  7948. /(trident).+rv[:\s]([\w\.]+).+like\sgecko/i // IE11
  7949. ], [[NAME, 'IE'], VERSION], [
  7950. /(edge|edgios|edga|edg)\/((\d+)?[\w\.]+)/i // Microsoft Edge
  7951. ], [[NAME, 'Edge'], VERSION], [
  7952. /(yabrowser)\/([\w\.]+)/i // Yandex
  7953. ], [[NAME, 'Yandex'], VERSION], [
  7954. /(Avast)\/([\w\.]+)/i // Avast Secure Browser
  7955. ], [[NAME, 'Avast Secure Browser'], VERSION], [
  7956. /(AVG)\/([\w\.]+)/i // AVG Secure Browser
  7957. ], [[NAME, 'AVG Secure Browser'], VERSION], [
  7958. /(puffin)\/([\w\.]+)/i // Puffin
  7959. ], [[NAME, 'Puffin'], VERSION], [
  7960. /(focus)\/([\w\.]+)/i // Firefox Focus
  7961. ], [[NAME, 'Firefox Focus'], VERSION], [
  7962. /(opt)\/([\w\.]+)/i // Opera Touch
  7963. ], [[NAME, 'Opera Touch'], VERSION], [
  7964. /((?:[\s\/])uc?\s?browser|(?:juc.+)ucweb)[\/\s]?([\w\.]+)/i // UCBrowser
  7965. ], [[NAME, 'UCBrowser'], VERSION], [
  7966. /(comodo_dragon)\/([\w\.]+)/i // Comodo Dragon
  7967. ], [[NAME, /_/g, ' '], VERSION], [
  7968. /(windowswechat qbcore)\/([\w\.]+)/i // WeChat Desktop for Windows Built-in Browser
  7969. ], [[NAME, 'WeChat(Win) Desktop'], VERSION], [
  7970. /(micromessenger)\/([\w\.]+)/i // WeChat
  7971. ], [[NAME, 'WeChat'], VERSION], [
  7972. /(brave)\/([\w\.]+)/i // Brave browser
  7973. ], [[NAME, 'Brave'], VERSION], [
  7974. /(qqbrowserlite)\/([\w\.]+)/i // QQBrowserLite
  7975. ], [NAME, VERSION], [
  7976. /(QQ)\/([\d\.]+)/i // QQ, aka ShouQ
  7977. ], [NAME, VERSION], [
  7978. /m?(qqbrowser)[\/\s]?([\w\.]+)/i // QQBrowser
  7979. ], [NAME, VERSION], [
  7980. /(baiduboxapp)[\/\s]?([\w\.]+)/i // Baidu App
  7981. ], [NAME, VERSION], [
  7982. /(2345Explorer)[\/\s]?([\w\.]+)/i // 2345 Browser
  7983. ], [NAME, VERSION], [
  7984. /(MetaSr)[\/\s]?([\w\.]+)/i // SouGouBrowser
  7985. ], [NAME], [
  7986. /(LBBROWSER)/i // LieBao Browser
  7987. ], [NAME], [
  7988. /xiaomi\/miuibrowser\/([\w\.]+)/i // MIUI Browser
  7989. ], [VERSION, [NAME, 'MIUI Browser']], [
  7990. /;fbav\/([\w\.]+);/i // Facebook App for iOS & Android
  7991. ], [VERSION, [NAME, 'Facebook']], [
  7992. /safari\s(line)\/([\w\.]+)/i, // Line App for iOS
  7993. /android.+(line)\/([\w\.]+)\/iab/i // Line App for Android
  7994. ], [NAME, VERSION], [
  7995. /headlesschrome(?:\/([\w\.]+)|\s)/i // Chrome Headless
  7996. ], [VERSION, [NAME, 'Chrome Headless']], [
  7997. /\swv\).+(chrome)\/([\w\.]+)/i // Chrome WebView
  7998. ], [[NAME, /(.+)/, '$1 WebView'], VERSION], [
  7999. /((?:oculus|samsung)browser)\/([\w\.]+)/i
  8000. ], [[NAME, /(.+(?:g|us))(.+)/, '$1 $2'], VERSION], [ // Oculus / Samsung Browser
  8001. /android.+version\/([\w\.]+)\s+(?:mobile\s?safari|safari)*/i // Android Browser
  8002. ], [VERSION, [NAME, 'Android Browser']], [
  8003. /(sailfishbrowser)\/([\w\.]+)/i // Sailfish Browser
  8004. ], [[NAME, 'Sailfish Browser'], VERSION], [
  8005. /(chrome|omniweb|arora|[tizenoka]{5}\s?browser)\/v?([\w\.]+)/i
  8006. // Chrome/OmniWeb/Arora/Tizen/Nokia
  8007. ], [NAME, VERSION], [
  8008. /(dolfin)\/([\w\.]+)/i // Dolphin
  8009. ], [[NAME, 'Dolphin'], VERSION], [
  8010. /(qihu|qhbrowser|qihoobrowser|360browser)/i // 360
  8011. ], [[NAME, '360 Browser']], [
  8012. /((?:android.+)crmo|crios)\/([\w\.]+)/i // Chrome for Android/iOS
  8013. ], [[NAME, 'Chrome'], VERSION], [
  8014. /(coast)\/([\w\.]+)/i // Opera Coast
  8015. ], [[NAME, 'Opera Coast'], VERSION], [
  8016. /fxios\/([\w\.-]+)/i // Firefox for iOS
  8017. ], [VERSION, [NAME, 'Firefox']], [
  8018. /version\/([\w\.]+).+?mobile\/\w+\s(safari)/i // Mobile Safari
  8019. ], [VERSION, [NAME, 'Mobile Safari']], [
  8020. /version\/([\w\.]+).+?(mobile\s?safari|safari)/i // Safari & Safari Mobile
  8021. ], [VERSION, NAME], [
  8022. /webkit.+?(gsa)\/([\w\.]+).+?(mobile\s?safari|safari)(\/[\w\.]+)/i // Google Search Appliance on iOS
  8023. ], [[NAME, 'GSA'], VERSION], [
  8024. /webkit.+?(mobile\s?safari|safari)(\/[\w\.]+)/i // Safari < 3.0
  8025. ], [NAME, [VERSION, mapper.str, maps.browser.oldsafari.version]], [
  8026. /(webkit|khtml)\/([\w\.]+)/i
  8027. ], [NAME, VERSION], [
  8028. // Gecko based
  8029. /(navigator|netscape)\/([\w\.-]+)/i // Netscape
  8030. ], [[NAME, 'Netscape'], VERSION], [
  8031. /(swiftfox)/i, // Swiftfox
  8032. /(icedragon|iceweasel|camino|chimera|fennec|maemo\sbrowser|minimo|conkeror)[\/\s]?([\w\.\+]+)/i,
  8033. // IceDragon/Iceweasel/Camino/Chimera/Fennec/Maemo/Minimo/Conkeror
  8034. /(firefox|seamonkey|k-meleon|icecat|iceape|firebird|phoenix|palemoon|basilisk|waterfox)\/([\w\.-]+)$/i,
  8035. // Firefox/SeaMonkey/K-Meleon/IceCat/IceApe/Firebird/Phoenix
  8036. /(mozilla)\/([\w\.]+).+rv\:.+gecko\/\d+/i, // Mozilla
  8037. // Other
  8038. /(polaris|lynx|dillo|icab|doris|amaya|w3m|netsurf|sleipnir)[\/\s]?([\w\.]+)/i,
  8039. // Polaris/Lynx/Dillo/iCab/Doris/Amaya/w3m/NetSurf/Sleipnir
  8040. /(links)\s\(([\w\.]+)/i, // Links
  8041. /(gobrowser)\/?([\w\.]*)/i, // GoBrowser
  8042. /(ice\s?browser)\/v?([\w\._]+)/i, // ICE Browser
  8043. /(mosaic)[\/\s]([\w\.]+)/i // Mosaic
  8044. ], [NAME, VERSION]
  8045. ],
  8046. cpu : [[
  8047. /(?:(amd|x(?:(?:86|64)[_-])?|wow|win)64)[;\)]/i // AMD64
  8048. ], [[ARCHITECTURE, 'amd64']], [
  8049. /(ia32(?=;))/i // IA32 (quicktime)
  8050. ], [[ARCHITECTURE, util.lowerize]], [
  8051. /((?:i[346]|x)86)[;\)]/i // IA32
  8052. ], [[ARCHITECTURE, 'ia32']], [
  8053. // PocketPC mistakenly identified as PowerPC
  8054. /windows\s(ce|mobile);\sppc;/i
  8055. ], [[ARCHITECTURE, 'arm']], [
  8056. /((?:ppc|powerpc)(?:64)?)(?:\smac|;|\))/i // PowerPC
  8057. ], [[ARCHITECTURE, /ower/, '', util.lowerize]], [
  8058. /(sun4\w)[;\)]/i // SPARC
  8059. ], [[ARCHITECTURE, 'sparc']], [
  8060. /((?:avr32|ia64(?=;))|68k(?=\))|arm(?:64|(?=v\d+[;l]))|(?=atmel\s)avr|(?:irix|mips|sparc)(?:64)?(?=;)|pa-risc)/i
  8061. // IA64, 68K, ARM/64, AVR/32, IRIX/64, MIPS/64, SPARC/64, PA-RISC
  8062. ], [[ARCHITECTURE, util.lowerize]]
  8063. ],
  8064. device : [[
  8065. /\((ipad|playbook);[\w\s\),;-]+(rim|apple)/i // iPad/PlayBook
  8066. ], [MODEL, VENDOR, [TYPE, TABLET]], [
  8067. /applecoremedia\/[\w\.]+ \((ipad)/ // iPad
  8068. ], [MODEL, [VENDOR, 'Apple'], [TYPE, TABLET]], [
  8069. /(apple\s{0,1}tv)/i // Apple TV
  8070. ], [[MODEL, 'Apple TV'], [VENDOR, 'Apple'], [TYPE, SMARTTV]], [
  8071. /(archos)\s(gamepad2?)/i, // Archos
  8072. /(hp).+(touchpad)/i, // HP TouchPad
  8073. /(hp).+(tablet)/i, // HP Tablet
  8074. /(kindle)\/([\w\.]+)/i, // Kindle
  8075. /\s(nook)[\w\s]+build\/(\w+)/i, // Nook
  8076. /(dell)\s(strea[kpr\s\d]*[\dko])/i // Dell Streak
  8077. ], [VENDOR, MODEL, [TYPE, TABLET]], [
  8078. /(kf[A-z]+)\sbuild\/.+silk\//i // Kindle Fire HD
  8079. ], [MODEL, [VENDOR, 'Amazon'], [TYPE, TABLET]], [
  8080. /(sd|kf)[0349hijorstuw]+\sbuild\/.+silk\//i // Fire Phone
  8081. ], [[MODEL, mapper.str, maps.device.amazon.model], [VENDOR, 'Amazon'], [TYPE, MOBILE]], [
  8082. /android.+aft([bms])\sbuild/i // Fire TV
  8083. ], [MODEL, [VENDOR, 'Amazon'], [TYPE, SMARTTV]], [
  8084. /\((ip[honed|\s\w*]+);.+(apple)/i // iPod/iPhone
  8085. ], [MODEL, VENDOR, [TYPE, MOBILE]], [
  8086. /\((ip[honed|\s\w*]+);/i // iPod/iPhone
  8087. ], [MODEL, [VENDOR, 'Apple'], [TYPE, MOBILE]], [
  8088. /(blackberry)[\s-]?(\w+)/i, // BlackBerry
  8089. /(blackberry|benq|palm(?=\-)|sonyericsson|acer|asus|dell|meizu|motorola|polytron)[\s_-]?([\w-]*)/i,
  8090. // BenQ/Palm/Sony-Ericsson/Acer/Asus/Dell/Meizu/Motorola/Polytron
  8091. /(hp)\s([\w\s]+\w)/i, // HP iPAQ
  8092. /(asus)-?(\w+)/i // Asus
  8093. ], [VENDOR, MODEL, [TYPE, MOBILE]], [
  8094. /\(bb10;\s(\w+)/i // BlackBerry 10
  8095. ], [MODEL, [VENDOR, 'BlackBerry'], [TYPE, MOBILE]], [
  8096. // Asus Tablets
  8097. /android.+(transfo[prime\s]{4,10}\s\w+|eeepc|slider\s\w+|nexus 7|padfone|p00c)/i
  8098. ], [MODEL, [VENDOR, 'Asus'], [TYPE, TABLET]], [
  8099. /(sony)\s(tablet\s[ps])\sbuild\//i, // Sony
  8100. /(sony)?(?:sgp.+)\sbuild\//i
  8101. ], [[VENDOR, 'Sony'], [MODEL, 'Xperia Tablet'], [TYPE, TABLET]], [
  8102. /android.+\s([c-g]\d{4}|so[-l]\w+)(?=\sbuild\/|\).+chrome\/(?![1-6]{0,1}\d\.))/i
  8103. ], [MODEL, [VENDOR, 'Sony'], [TYPE, MOBILE]], [
  8104. /\s(ouya)\s/i, // Ouya
  8105. /(nintendo)\s([wids3u]+)/i // Nintendo
  8106. ], [VENDOR, MODEL, [TYPE, CONSOLE]], [
  8107. /android.+;\s(shield)\sbuild/i // Nvidia
  8108. ], [MODEL, [VENDOR, 'Nvidia'], [TYPE, CONSOLE]], [
  8109. /(playstation\s[34portablevi]+)/i // Playstation
  8110. ], [MODEL, [VENDOR, 'Sony'], [TYPE, CONSOLE]], [
  8111. /(sprint\s(\w+))/i // Sprint Phones
  8112. ], [[VENDOR, mapper.str, maps.device.sprint.vendor], [MODEL, mapper.str, maps.device.sprint.model], [TYPE, MOBILE]], [
  8113. /(htc)[;_\s-]+([\w\s]+(?=\)|\sbuild)|\w+)/i, // HTC
  8114. /(zte)-(\w*)/i, // ZTE
  8115. /(alcatel|geeksphone|nexian|panasonic|(?=;\s)sony)[_\s-]?([\w-]*)/i
  8116. // Alcatel/GeeksPhone/Nexian/Panasonic/Sony
  8117. ], [VENDOR, [MODEL, /_/g, ' '], [TYPE, MOBILE]], [
  8118. /(nexus\s9)/i // HTC Nexus 9
  8119. ], [MODEL, [VENDOR, 'HTC'], [TYPE, TABLET]], [
  8120. /d\/huawei([\w\s-]+)[;\)]/i,
  8121. /(nexus\s6p|vog-l29|ane-lx1|eml-l29)/i // Huawei
  8122. ], [MODEL, [VENDOR, 'Huawei'], [TYPE, MOBILE]], [
  8123. /android.+(bah2?-a?[lw]\d{2})/i // Huawei MediaPad
  8124. ], [MODEL, [VENDOR, 'Huawei'], [TYPE, TABLET]], [
  8125. /(microsoft);\s(lumia[\s\w]+)/i // Microsoft Lumia
  8126. ], [VENDOR, MODEL, [TYPE, MOBILE]], [
  8127. /[\s\(;](xbox(?:\sone)?)[\s\);]/i // Microsoft Xbox
  8128. ], [MODEL, [VENDOR, 'Microsoft'], [TYPE, CONSOLE]], [
  8129. /(kin\.[onetw]{3})/i // Microsoft Kin
  8130. ], [[MODEL, /\./g, ' '], [VENDOR, 'Microsoft'], [TYPE, MOBILE]], [
  8131. // Motorola
  8132. /\s(milestone|droid(?:[2-4x]|\s(?:bionic|x2|pro|razr))?:?(\s4g)?)[\w\s]+build\//i,
  8133. /mot[\s-]?(\w*)/i,
  8134. /(XT\d{3,4}) build\//i,
  8135. /(nexus\s6)/i
  8136. ], [MODEL, [VENDOR, 'Motorola'], [TYPE, MOBILE]], [
  8137. /android.+\s(mz60\d|xoom[\s2]{0,2})\sbuild\//i
  8138. ], [MODEL, [VENDOR, 'Motorola'], [TYPE, TABLET]], [
  8139. /hbbtv\/\d+\.\d+\.\d+\s+\([\w\s]*;\s*(\w[^;]*);([^;]*)/i // HbbTV devices
  8140. ], [[VENDOR, util.trim], [MODEL, util.trim], [TYPE, SMARTTV]], [
  8141. /hbbtv.+maple;(\d+)/i
  8142. ], [[MODEL, /^/, 'SmartTV'], [VENDOR, 'Samsung'], [TYPE, SMARTTV]], [
  8143. /\(dtv[\);].+(aquos)/i // Sharp
  8144. ], [MODEL, [VENDOR, 'Sharp'], [TYPE, SMARTTV]], [
  8145. /android.+((sch-i[89]0\d|shw-m380s|gt-p\d{4}|gt-n\d+|sgh-t8[56]9|nexus 10))/i,
  8146. /((SM-T\w+))/i
  8147. ], [[VENDOR, 'Samsung'], MODEL, [TYPE, TABLET]], [ // Samsung
  8148. /smart-tv.+(samsung)/i
  8149. ], [VENDOR, [TYPE, SMARTTV], MODEL], [
  8150. /((s[cgp]h-\w+|gt-\w+|galaxy\snexus|sm-\w[\w\d]+))/i,
  8151. /(sam[sung]*)[\s-]*(\w+-?[\w-]*)/i,
  8152. /sec-((sgh\w+))/i
  8153. ], [[VENDOR, 'Samsung'], MODEL, [TYPE, MOBILE]], [
  8154. /sie-(\w*)/i // Siemens
  8155. ], [MODEL, [VENDOR, 'Siemens'], [TYPE, MOBILE]], [
  8156. /(maemo|nokia).*(n900|lumia\s\d+)/i, // Nokia
  8157. /(nokia)[\s_-]?([\w-]*)/i
  8158. ], [[VENDOR, 'Nokia'], MODEL, [TYPE, MOBILE]], [
  8159. /android[x\d\.\s;]+\s([ab][1-7]\-?[0178a]\d\d?)/i // Acer
  8160. ], [MODEL, [VENDOR, 'Acer'], [TYPE, TABLET]], [
  8161. /android.+([vl]k\-?\d{3})\s+build/i // LG Tablet
  8162. ], [MODEL, [VENDOR, 'LG'], [TYPE, TABLET]], [
  8163. /android\s3\.[\s\w;-]{10}(lg?)-([06cv9]{3,4})/i // LG Tablet
  8164. ], [[VENDOR, 'LG'], MODEL, [TYPE, TABLET]], [
  8165. /(lg) netcast\.tv/i // LG SmartTV
  8166. ], [VENDOR, MODEL, [TYPE, SMARTTV]], [
  8167. /(nexus\s[45])/i, // LG
  8168. /lg[e;\s\/-]+(\w*)/i,
  8169. /android.+lg(\-?[\d\w]+)\s+build/i
  8170. ], [MODEL, [VENDOR, 'LG'], [TYPE, MOBILE]], [
  8171. /(lenovo)\s?(s(?:5000|6000)(?:[\w-]+)|tab(?:[\s\w]+))/i // Lenovo tablets
  8172. ], [VENDOR, MODEL, [TYPE, TABLET]], [
  8173. /android.+(ideatab[a-z0-9\-\s]+)/i // Lenovo
  8174. ], [MODEL, [VENDOR, 'Lenovo'], [TYPE, TABLET]], [
  8175. /(lenovo)[_\s-]?([\w-]+)/i
  8176. ], [VENDOR, MODEL, [TYPE, MOBILE]], [
  8177. /linux;.+((jolla));/i // Jolla
  8178. ], [VENDOR, MODEL, [TYPE, MOBILE]], [
  8179. /((pebble))app\/[\d\.]+\s/i // Pebble
  8180. ], [VENDOR, MODEL, [TYPE, WEARABLE]], [
  8181. /android.+;\s(oppo)\s?([\w\s]+)\sbuild/i // OPPO
  8182. ], [VENDOR, MODEL, [TYPE, MOBILE]], [
  8183. /crkey/i // Google Chromecast
  8184. ], [[MODEL, 'Chromecast'], [VENDOR, 'Google'], [TYPE, SMARTTV]], [
  8185. /android.+;\s(glass)\s\d/i // Google Glass
  8186. ], [MODEL, [VENDOR, 'Google'], [TYPE, WEARABLE]], [
  8187. /android.+;\s(pixel c)[\s)]/i // Google Pixel C
  8188. ], [MODEL, [VENDOR, 'Google'], [TYPE, TABLET]], [
  8189. /android.+;\s(pixel( [23])?( xl)?)[\s)]/i // Google Pixel
  8190. ], [MODEL, [VENDOR, 'Google'], [TYPE, MOBILE]], [
  8191. /android.+;\s(\w+)\s+build\/hm\1/i, // Xiaomi Hongmi 'numeric' models
  8192. /android.+(hm[\s\-_]*note?[\s_]*(?:\d\w)?)\s+build/i, // Xiaomi Hongmi
  8193. /android.+(mi[\s\-_]*(?:a\d|one|one[\s_]plus|note lte)?[\s_]*(?:\d?\w?)[\s_]*(?:plus)?)\s+build/i,
  8194. // Xiaomi Mi
  8195. /android.+(redmi[\s\-_]*(?:note)?(?:[\s_]*[\w\s]+))\s+build/i // Redmi Phones
  8196. ], [[MODEL, /_/g, ' '], [VENDOR, 'Xiaomi'], [TYPE, MOBILE]], [
  8197. /android.+(mi[\s\-_]*(?:pad)(?:[\s_]*[\w\s]+))\s+build/i // Mi Pad tablets
  8198. ],[[MODEL, /_/g, ' '], [VENDOR, 'Xiaomi'], [TYPE, TABLET]], [
  8199. /android.+;\s(m[1-5]\snote)\sbuild/i // Meizu
  8200. ], [MODEL, [VENDOR, 'Meizu'], [TYPE, MOBILE]], [
  8201. /(mz)-([\w-]{2,})/i
  8202. ], [[VENDOR, 'Meizu'], MODEL, [TYPE, MOBILE]], [
  8203. /android.+a000(1)\s+build/i, // OnePlus
  8204. /android.+oneplus\s(a\d{4})[\s)]/i
  8205. ], [MODEL, [VENDOR, 'OnePlus'], [TYPE, MOBILE]], [
  8206. /android.+[;\/]\s*(RCT[\d\w]+)\s+build/i // RCA Tablets
  8207. ], [MODEL, [VENDOR, 'RCA'], [TYPE, TABLET]], [
  8208. /android.+[;\/\s]+(Venue[\d\s]{2,7})\s+build/i // Dell Venue Tablets
  8209. ], [MODEL, [VENDOR, 'Dell'], [TYPE, TABLET]], [
  8210. /android.+[;\/]\s*(Q[T|M][\d\w]+)\s+build/i // Verizon Tablet
  8211. ], [MODEL, [VENDOR, 'Verizon'], [TYPE, TABLET]], [
  8212. /android.+[;\/]\s+(Barnes[&\s]+Noble\s+|BN[RT])(V?.*)\s+build/i // Barnes & Noble Tablet
  8213. ], [[VENDOR, 'Barnes & Noble'], MODEL, [TYPE, TABLET]], [
  8214. /android.+[;\/]\s+(TM\d{3}.*\b)\s+build/i // Barnes & Noble Tablet
  8215. ], [MODEL, [VENDOR, 'NuVision'], [TYPE, TABLET]], [
  8216. /android.+;\s(k88)\sbuild/i // ZTE K Series Tablet
  8217. ], [MODEL, [VENDOR, 'ZTE'], [TYPE, TABLET]], [
  8218. /android.+[;\/]\s*(gen\d{3})\s+build.*49h/i // Swiss GEN Mobile
  8219. ], [MODEL, [VENDOR, 'Swiss'], [TYPE, MOBILE]], [
  8220. /android.+[;\/]\s*(zur\d{3})\s+build/i // Swiss ZUR Tablet
  8221. ], [MODEL, [VENDOR, 'Swiss'], [TYPE, TABLET]], [
  8222. /android.+[;\/]\s*((Zeki)?TB.*\b)\s+build/i // Zeki Tablets
  8223. ], [MODEL, [VENDOR, 'Zeki'], [TYPE, TABLET]], [
  8224. /(android).+[;\/]\s+([YR]\d{2})\s+build/i,
  8225. /android.+[;\/]\s+(Dragon[\-\s]+Touch\s+|DT)(\w{5})\sbuild/i // Dragon Touch Tablet
  8226. ], [[VENDOR, 'Dragon Touch'], MODEL, [TYPE, TABLET]], [
  8227. /android.+[;\/]\s*(NS-?\w{0,9})\sbuild/i // Insignia Tablets
  8228. ], [MODEL, [VENDOR, 'Insignia'], [TYPE, TABLET]], [
  8229. /android.+[;\/]\s*((NX|Next)-?\w{0,9})\s+build/i // NextBook Tablets
  8230. ], [MODEL, [VENDOR, 'NextBook'], [TYPE, TABLET]], [
  8231. /android.+[;\/]\s*(Xtreme\_)?(V(1[045]|2[015]|30|40|60|7[05]|90))\s+build/i
  8232. ], [[VENDOR, 'Voice'], MODEL, [TYPE, MOBILE]], [ // Voice Xtreme Phones
  8233. /android.+[;\/]\s*(LVTEL\-)?(V1[12])\s+build/i // LvTel Phones
  8234. ], [[VENDOR, 'LvTel'], MODEL, [TYPE, MOBILE]], [
  8235. /android.+;\s(PH-1)\s/i
  8236. ], [MODEL, [VENDOR, 'Essential'], [TYPE, MOBILE]], [ // Essential PH-1
  8237. /android.+[;\/]\s*(V(100MD|700NA|7011|917G).*\b)\s+build/i // Envizen Tablets
  8238. ], [MODEL, [VENDOR, 'Envizen'], [TYPE, TABLET]], [
  8239. /android.+[;\/]\s*(Le[\s\-]+Pan)[\s\-]+(\w{1,9})\s+build/i // Le Pan Tablets
  8240. ], [VENDOR, MODEL, [TYPE, TABLET]], [
  8241. /android.+[;\/]\s*(Trio[\s\-]*.*)\s+build/i // MachSpeed Tablets
  8242. ], [MODEL, [VENDOR, 'MachSpeed'], [TYPE, TABLET]], [
  8243. /android.+[;\/]\s*(Trinity)[\-\s]*(T\d{3})\s+build/i // Trinity Tablets
  8244. ], [VENDOR, MODEL, [TYPE, TABLET]], [
  8245. /android.+[;\/]\s*TU_(1491)\s+build/i // Rotor Tablets
  8246. ], [MODEL, [VENDOR, 'Rotor'], [TYPE, TABLET]], [
  8247. /android.+(KS(.+))\s+build/i // Amazon Kindle Tablets
  8248. ], [MODEL, [VENDOR, 'Amazon'], [TYPE, TABLET]], [
  8249. /android.+(Gigaset)[\s\-]+(Q\w{1,9})\s+build/i // Gigaset Tablets
  8250. ], [VENDOR, MODEL, [TYPE, TABLET]], [
  8251. /\s(tablet|tab)[;\/]/i, // Unidentifiable Tablet
  8252. /\s(mobile)(?:[;\/]|\ssafari)/i // Unidentifiable Mobile
  8253. ], [[TYPE, util.lowerize], VENDOR, MODEL], [
  8254. /[\s\/\(](smart-?tv)[;\)]/i // SmartTV
  8255. ], [[TYPE, SMARTTV]], [
  8256. /(android[\w\.\s\-]{0,9});.+build/i // Generic Android Device
  8257. ], [MODEL, [VENDOR, 'Generic']]
  8258. ],
  8259. engine : [[
  8260. /windows.+\sedge\/([\w\.]+)/i // EdgeHTML
  8261. ], [VERSION, [NAME, 'EdgeHTML']], [
  8262. /webkit\/537\.36.+chrome\/(?!27)([\w\.]+)/i // Blink
  8263. ], [VERSION, [NAME, 'Blink']], [
  8264. /(presto)\/([\w\.]+)/i, // Presto
  8265. /(webkit|trident|netfront|netsurf|amaya|lynx|w3m|goanna)\/([\w\.]+)/i,
  8266. // WebKit/Trident/NetFront/NetSurf/Amaya/Lynx/w3m/Goanna
  8267. /(khtml|tasman|links)[\/\s]\(?([\w\.]+)/i, // KHTML/Tasman/Links
  8268. /(icab)[\/\s]([23]\.[\d\.]+)/i // iCab
  8269. ], [NAME, VERSION], [
  8270. /rv\:([\w\.]{1,9}).+(gecko)/i // Gecko
  8271. ], [VERSION, NAME]
  8272. ],
  8273. os : [[
  8274. // Windows based
  8275. /microsoft\s(windows)\s(vista|xp)/i // Windows (iTunes)
  8276. ], [NAME, VERSION], [
  8277. /(windows)\snt\s6\.2;\s(arm)/i, // Windows RT
  8278. /(windows\sphone(?:\sos)*)[\s\/]?([\d\.\s\w]*)/i, // Windows Phone
  8279. /(windows\smobile|windows)[\s\/]?([ntce\d\.\s]+\w)/i
  8280. ], [NAME, [VERSION, mapper.str, maps.os.windows.version]], [
  8281. /(win(?=3|9|n)|win\s9x\s)([nt\d\.]+)/i
  8282. ], [[NAME, 'Windows'], [VERSION, mapper.str, maps.os.windows.version]], [
  8283. // Mobile/Embedded OS
  8284. /\((bb)(10);/i // BlackBerry 10
  8285. ], [[NAME, 'BlackBerry'], VERSION], [
  8286. /(blackberry)\w*\/?([\w\.]*)/i, // Blackberry
  8287. /(tizen|kaios)[\/\s]([\w\.]+)/i, // Tizen/KaiOS
  8288. /(android|webos|palm\sos|qnx|bada|rim\stablet\sos|meego|sailfish|contiki)[\/\s-]?([\w\.]*)/i
  8289. // Android/WebOS/Palm/QNX/Bada/RIM/MeeGo/Contiki/Sailfish OS
  8290. ], [NAME, VERSION], [
  8291. /(symbian\s?os|symbos|s60(?=;))[\/\s-]?([\w\.]*)/i // Symbian
  8292. ], [[NAME, 'Symbian'], VERSION], [
  8293. /\((series40);/i // Series 40
  8294. ], [NAME], [
  8295. /mozilla.+\(mobile;.+gecko.+firefox/i // Firefox OS
  8296. ], [[NAME, 'Firefox OS'], VERSION], [
  8297. // Console
  8298. /(nintendo|playstation)\s([wids34portablevu]+)/i, // Nintendo/Playstation
  8299. // GNU/Linux based
  8300. /(mint)[\/\s\(]?(\w*)/i, // Mint
  8301. /(mageia|vectorlinux)[;\s]/i, // Mageia/VectorLinux
  8302. /(joli|[kxln]?ubuntu|debian|suse|opensuse|gentoo|(?=\s)arch|slackware|fedora|mandriva|centos|pclinuxos|redhat|zenwalk|linpus)[\/\s-]?(?!chrom)([\w\.-]*)/i,
  8303. // Joli/Ubuntu/Debian/SUSE/Gentoo/Arch/Slackware
  8304. // Fedora/Mandriva/CentOS/PCLinuxOS/RedHat/Zenwalk/Linpus
  8305. /(hurd|linux)\s?([\w\.]*)/i, // Hurd/Linux
  8306. /(gnu)\s?([\w\.]*)/i // GNU
  8307. ], [NAME, VERSION], [
  8308. /(cros)\s[\w]+\s([\w\.]+\w)/i // Chromium OS
  8309. ], [[NAME, 'Chromium OS'], VERSION],[
  8310. // Solaris
  8311. /(sunos)\s?([\w\.\d]*)/i // Solaris
  8312. ], [[NAME, 'Solaris'], VERSION], [
  8313. // BSD based
  8314. /\s([frentopc-]{0,4}bsd|dragonfly)\s?([\w\.]*)/i // FreeBSD/NetBSD/OpenBSD/PC-BSD/DragonFly
  8315. ], [NAME, VERSION],[
  8316. /(haiku)\s(\w+)/i // Haiku
  8317. ], [NAME, VERSION],[
  8318. /cfnetwork\/.+darwin/i,
  8319. /ip[honead]{2,4}(?:.*os\s([\w]+)\slike\smac|;\sopera)/i // iOS
  8320. ], [[VERSION, /_/g, '.'], [NAME, 'iOS']], [
  8321. /(mac\sos\sx)\s?([\w\s\.]*)/i,
  8322. /(macintosh|mac(?=_powerpc)\s)/i // Mac OS
  8323. ], [[NAME, 'Mac OS'], [VERSION, /_/g, '.']], [
  8324. // Other
  8325. /((?:open)?solaris)[\/\s-]?([\w\.]*)/i, // Solaris
  8326. /(aix)\s((\d)(?=\.|\)|\s)[\w\.])*/i, // AIX
  8327. /(plan\s9|minix|beos|os\/2|amigaos|morphos|risc\sos|openvms|fuchsia)/i,
  8328. // Plan9/Minix/BeOS/OS2/AmigaOS/MorphOS/RISCOS/OpenVMS/Fuchsia
  8329. /(unix)\s?([\w\.]*)/i // UNIX
  8330. ], [NAME, VERSION]
  8331. ]
  8332. };
  8333. /////////////////
  8334. // Constructor
  8335. ////////////////
  8336. var UAParser = function (uastring, extensions) {
  8337. if (typeof uastring === 'object') {
  8338. extensions = uastring;
  8339. uastring = undefined$1;
  8340. }
  8341. if (!(this instanceof UAParser)) {
  8342. return new UAParser(uastring, extensions).getResult();
  8343. }
  8344. var ua = uastring || ((window && window.navigator && window.navigator.userAgent) ? window.navigator.userAgent : EMPTY);
  8345. var rgxmap = extensions ? util.extend(regexes, extensions) : regexes;
  8346. this.getBrowser = function () {
  8347. var browser = { name: undefined$1, version: undefined$1 };
  8348. mapper.rgx.call(browser, ua, rgxmap.browser);
  8349. browser.major = util.major(browser.version); // deprecated
  8350. return browser;
  8351. };
  8352. this.getCPU = function () {
  8353. var cpu = { architecture: undefined$1 };
  8354. mapper.rgx.call(cpu, ua, rgxmap.cpu);
  8355. return cpu;
  8356. };
  8357. this.getDevice = function () {
  8358. var device = { vendor: undefined$1, model: undefined$1, type: undefined$1 };
  8359. mapper.rgx.call(device, ua, rgxmap.device);
  8360. return device;
  8361. };
  8362. this.getEngine = function () {
  8363. var engine = { name: undefined$1, version: undefined$1 };
  8364. mapper.rgx.call(engine, ua, rgxmap.engine);
  8365. return engine;
  8366. };
  8367. this.getOS = function () {
  8368. var os = { name: undefined$1, version: undefined$1 };
  8369. mapper.rgx.call(os, ua, rgxmap.os);
  8370. return os;
  8371. };
  8372. this.getResult = function () {
  8373. return {
  8374. ua : this.getUA(),
  8375. browser : this.getBrowser(),
  8376. engine : this.getEngine(),
  8377. os : this.getOS(),
  8378. device : this.getDevice(),
  8379. cpu : this.getCPU()
  8380. };
  8381. };
  8382. this.getUA = function () {
  8383. return ua;
  8384. };
  8385. this.setUA = function (uastring) {
  8386. ua = uastring;
  8387. return this;
  8388. };
  8389. return this;
  8390. };
  8391. UAParser.VERSION = LIBVERSION;
  8392. UAParser.BROWSER = {
  8393. NAME : NAME,
  8394. MAJOR : MAJOR, // deprecated
  8395. VERSION : VERSION
  8396. };
  8397. UAParser.CPU = {
  8398. ARCHITECTURE : ARCHITECTURE
  8399. };
  8400. UAParser.DEVICE = {
  8401. MODEL : MODEL,
  8402. VENDOR : VENDOR,
  8403. TYPE : TYPE,
  8404. CONSOLE : CONSOLE,
  8405. MOBILE : MOBILE,
  8406. SMARTTV : SMARTTV,
  8407. TABLET : TABLET,
  8408. WEARABLE: WEARABLE,
  8409. EMBEDDED: EMBEDDED
  8410. };
  8411. UAParser.ENGINE = {
  8412. NAME : NAME,
  8413. VERSION : VERSION
  8414. };
  8415. UAParser.OS = {
  8416. NAME : NAME,
  8417. VERSION : VERSION
  8418. };
  8419. ///////////
  8420. // Export
  8421. //////////
  8422. // check js environment
  8423. {
  8424. // nodejs env
  8425. if ( module.exports) {
  8426. exports = module.exports = UAParser;
  8427. }
  8428. exports.UAParser = UAParser;
  8429. }
  8430. // jQuery/Zepto specific (optional)
  8431. // Note:
  8432. // In AMD env the global scope should be kept clean, but jQuery is an exception.
  8433. // jQuery always exports to global scope, unless jQuery.noConflict(true) is used,
  8434. // and we should catch that.
  8435. var $ = window && (window.jQuery || window.Zepto);
  8436. if ($ && !$.ua) {
  8437. var parser = new UAParser();
  8438. $.ua = parser.getResult();
  8439. $.ua.get = function () {
  8440. return parser.getUA();
  8441. };
  8442. $.ua.set = function (uastring) {
  8443. parser.setUA(uastring);
  8444. var result = parser.getResult();
  8445. for (var prop in result) {
  8446. $.ua[prop] = result[prop];
  8447. }
  8448. };
  8449. }
  8450. })(typeof window === 'object' ? window : commonjsGlobal);
  8451. });
  8452. var uaParser_1 = uaParser.UAParser;
  8453. var UNKNOWN = 'Unknown';
  8454. var PLATFORM_MAP = {
  8455. 'Mac OS': 'Mac OS X'
  8456. };
  8457. /**
  8458. * Convert from UAParser platform name to what we expect.
  8459. */
  8460. function convertPlatformName(name) {
  8461. return PLATFORM_MAP[name] || name;
  8462. }
  8463. /**
  8464. * Get the version number in parts. This is very naive. We actually get major
  8465. * version as a part of UAParser already, which is generally good enough, but
  8466. * let's get the minor just in case.
  8467. */
  8468. function getBrowserVersion(version) {
  8469. if (!version) {
  8470. return {
  8471. major: '',
  8472. minor: ''
  8473. };
  8474. }
  8475. var parts = version.split('.');
  8476. return {
  8477. major: parts[0],
  8478. minor: parts[1]
  8479. };
  8480. }
  8481. /**
  8482. * Get the UA data fom UAParser and then convert it to the format we're
  8483. * expecting for our APIS.
  8484. */
  8485. var parser = new uaParser();
  8486. var results = parser.getResult();
  8487. // Do some conversion first.
  8488. var browserVersionData = getBrowserVersion(results.browser.version);
  8489. var uaData = {
  8490. browserArchitecture: results.cpu.architecture || UNKNOWN,
  8491. browserFullVersion: results.browser.version || UNKNOWN,
  8492. browserMinorVersion: browserVersionData.minor || UNKNOWN,
  8493. browserName: results.browser.name || UNKNOWN,
  8494. browserVersion: results.browser.major || UNKNOWN,
  8495. deviceName: results.device.model || UNKNOWN,
  8496. engineName: results.engine.name || UNKNOWN,
  8497. engineVersion: results.engine.version || UNKNOWN,
  8498. platformArchitecture: results.cpu.architecture || UNKNOWN,
  8499. platformName: convertPlatformName(results.os.name) || UNKNOWN,
  8500. platformVersion: results.os.version || UNKNOWN,
  8501. platformFullVersion: results.os.version || UNKNOWN
  8502. };
  8503. var UserAgentData = uaData;
  8504. var componentRegex = /\./;
  8505. var orRegex = /\|\|/;
  8506. var rangeRegex = /\s+\-\s+/;
  8507. var modifierRegex = /^(<=|<|=|>=|~>|~|>|)?\s*(.+)/;
  8508. var numericRegex = /^(\d*)(.*)/;
  8509. /**
  8510. * Splits input `range` on "||" and returns true if any subrange matches
  8511. * `version`.
  8512. *
  8513. * @param {string} range
  8514. * @param {string} version
  8515. * @returns {boolean}
  8516. */
  8517. function checkOrExpression(range, version) {
  8518. var expressions = range.split(orRegex);
  8519. if (expressions.length > 1) {
  8520. return expressions.some(function (range) {
  8521. return VersionRange.contains(range, version);
  8522. });
  8523. } else {
  8524. range = expressions[0].trim();
  8525. return checkRangeExpression(range, version);
  8526. }
  8527. }
  8528. /**
  8529. * Splits input `range` on " - " (the surrounding whitespace is required) and
  8530. * returns true if version falls between the two operands.
  8531. *
  8532. * @param {string} range
  8533. * @param {string} version
  8534. * @returns {boolean}
  8535. */
  8536. function checkRangeExpression(range, version) {
  8537. var expressions = range.split(rangeRegex);
  8538. !(expressions.length > 0 && expressions.length <= 2) ? process.env.NODE_ENV !== 'production' ? invariant_1(false, 'the "-" operator expects exactly 2 operands') : invariant_1(false) : void 0;
  8539. if (expressions.length === 1) {
  8540. return checkSimpleExpression(expressions[0], version);
  8541. } else {
  8542. var startVersion = expressions[0],
  8543. endVersion = expressions[1];
  8544. !(isSimpleVersion(startVersion) && isSimpleVersion(endVersion)) ? process.env.NODE_ENV !== 'production' ? invariant_1(false, 'operands to the "-" operator must be simple (no modifiers)') : invariant_1(false) : void 0;
  8545. return checkSimpleExpression('>=' + startVersion, version) && checkSimpleExpression('<=' + endVersion, version);
  8546. }
  8547. }
  8548. /**
  8549. * Checks if `range` matches `version`. `range` should be a "simple" range (ie.
  8550. * not a compound range using the " - " or "||" operators).
  8551. *
  8552. * @param {string} range
  8553. * @param {string} version
  8554. * @returns {boolean}
  8555. */
  8556. function checkSimpleExpression(range, version) {
  8557. range = range.trim();
  8558. if (range === '') {
  8559. return true;
  8560. }
  8561. var versionComponents = version.split(componentRegex);
  8562. var _getModifierAndCompon = getModifierAndComponents(range),
  8563. modifier = _getModifierAndCompon.modifier,
  8564. rangeComponents = _getModifierAndCompon.rangeComponents;
  8565. switch (modifier) {
  8566. case '<':
  8567. return checkLessThan(versionComponents, rangeComponents);
  8568. case '<=':
  8569. return checkLessThanOrEqual(versionComponents, rangeComponents);
  8570. case '>=':
  8571. return checkGreaterThanOrEqual(versionComponents, rangeComponents);
  8572. case '>':
  8573. return checkGreaterThan(versionComponents, rangeComponents);
  8574. case '~':
  8575. case '~>':
  8576. return checkApproximateVersion(versionComponents, rangeComponents);
  8577. default:
  8578. return checkEqual(versionComponents, rangeComponents);
  8579. }
  8580. }
  8581. /**
  8582. * Checks whether `a` is less than `b`.
  8583. *
  8584. * @param {array<string>} a
  8585. * @param {array<string>} b
  8586. * @returns {boolean}
  8587. */
  8588. function checkLessThan(a, b) {
  8589. return compareComponents(a, b) === -1;
  8590. }
  8591. /**
  8592. * Checks whether `a` is less than or equal to `b`.
  8593. *
  8594. * @param {array<string>} a
  8595. * @param {array<string>} b
  8596. * @returns {boolean}
  8597. */
  8598. function checkLessThanOrEqual(a, b) {
  8599. var result = compareComponents(a, b);
  8600. return result === -1 || result === 0;
  8601. }
  8602. /**
  8603. * Checks whether `a` is equal to `b`.
  8604. *
  8605. * @param {array<string>} a
  8606. * @param {array<string>} b
  8607. * @returns {boolean}
  8608. */
  8609. function checkEqual(a, b) {
  8610. return compareComponents(a, b) === 0;
  8611. }
  8612. /**
  8613. * Checks whether `a` is greater than or equal to `b`.
  8614. *
  8615. * @param {array<string>} a
  8616. * @param {array<string>} b
  8617. * @returns {boolean}
  8618. */
  8619. function checkGreaterThanOrEqual(a, b) {
  8620. var result = compareComponents(a, b);
  8621. return result === 1 || result === 0;
  8622. }
  8623. /**
  8624. * Checks whether `a` is greater than `b`.
  8625. *
  8626. * @param {array<string>} a
  8627. * @param {array<string>} b
  8628. * @returns {boolean}
  8629. */
  8630. function checkGreaterThan(a, b) {
  8631. return compareComponents(a, b) === 1;
  8632. }
  8633. /**
  8634. * Checks whether `a` is "reasonably close" to `b` (as described in
  8635. * https://www.npmjs.org/doc/misc/semver.html). For example, if `b` is "1.3.1"
  8636. * then "reasonably close" is defined as ">= 1.3.1 and < 1.4".
  8637. *
  8638. * @param {array<string>} a
  8639. * @param {array<string>} b
  8640. * @returns {boolean}
  8641. */
  8642. function checkApproximateVersion(a, b) {
  8643. var lowerBound = b.slice();
  8644. var upperBound = b.slice();
  8645. if (upperBound.length > 1) {
  8646. upperBound.pop();
  8647. }
  8648. var lastIndex = upperBound.length - 1;
  8649. var numeric = parseInt(upperBound[lastIndex], 10);
  8650. if (isNumber(numeric)) {
  8651. upperBound[lastIndex] = numeric + 1 + '';
  8652. }
  8653. return checkGreaterThanOrEqual(a, lowerBound) && checkLessThan(a, upperBound);
  8654. }
  8655. /**
  8656. * Extracts the optional modifier (<, <=, =, >=, >, ~, ~>) and version
  8657. * components from `range`.
  8658. *
  8659. * For example, given `range` ">= 1.2.3" returns an object with a `modifier` of
  8660. * `">="` and `components` of `[1, 2, 3]`.
  8661. *
  8662. * @param {string} range
  8663. * @returns {object}
  8664. */
  8665. function getModifierAndComponents(range) {
  8666. var rangeComponents = range.split(componentRegex);
  8667. var matches = rangeComponents[0].match(modifierRegex);
  8668. !matches ? process.env.NODE_ENV !== 'production' ? invariant_1(false, 'expected regex to match but it did not') : invariant_1(false) : void 0;
  8669. return {
  8670. modifier: matches[1],
  8671. rangeComponents: [matches[2]].concat(rangeComponents.slice(1))
  8672. };
  8673. }
  8674. /**
  8675. * Determines if `number` is a number.
  8676. *
  8677. * @param {mixed} number
  8678. * @returns {boolean}
  8679. */
  8680. function isNumber(number) {
  8681. return !isNaN(number) && isFinite(number);
  8682. }
  8683. /**
  8684. * Tests whether `range` is a "simple" version number without any modifiers
  8685. * (">", "~" etc).
  8686. *
  8687. * @param {string} range
  8688. * @returns {boolean}
  8689. */
  8690. function isSimpleVersion(range) {
  8691. return !getModifierAndComponents(range).modifier;
  8692. }
  8693. /**
  8694. * Zero-pads array `array` until it is at least `length` long.
  8695. *
  8696. * @param {array} array
  8697. * @param {number} length
  8698. */
  8699. function zeroPad(array, length) {
  8700. for (var i = array.length; i < length; i++) {
  8701. array[i] = '0';
  8702. }
  8703. }
  8704. /**
  8705. * Normalizes `a` and `b` in preparation for comparison by doing the following:
  8706. *
  8707. * - zero-pads `a` and `b`
  8708. * - marks any "x", "X" or "*" component in `b` as equivalent by zero-ing it out
  8709. * in both `a` and `b`
  8710. * - marks any final "*" component in `b` as a greedy wildcard by zero-ing it
  8711. * and all of its successors in `a`
  8712. *
  8713. * @param {array<string>} a
  8714. * @param {array<string>} b
  8715. * @returns {array<array<string>>}
  8716. */
  8717. function normalizeVersions(a, b) {
  8718. a = a.slice();
  8719. b = b.slice();
  8720. zeroPad(a, b.length);
  8721. // mark "x" and "*" components as equal
  8722. for (var i = 0; i < b.length; i++) {
  8723. var matches = b[i].match(/^[x*]$/i);
  8724. if (matches) {
  8725. b[i] = a[i] = '0';
  8726. // final "*" greedily zeros all remaining components
  8727. if (matches[0] === '*' && i === b.length - 1) {
  8728. for (var j = i; j < a.length; j++) {
  8729. a[j] = '0';
  8730. }
  8731. }
  8732. }
  8733. }
  8734. zeroPad(b, a.length);
  8735. return [a, b];
  8736. }
  8737. /**
  8738. * Returns the numerical -- not the lexicographical -- ordering of `a` and `b`.
  8739. *
  8740. * For example, `10-alpha` is greater than `2-beta`.
  8741. *
  8742. * @param {string} a
  8743. * @param {string} b
  8744. * @returns {number} -1, 0 or 1 to indicate whether `a` is less than, equal to,
  8745. * or greater than `b`, respectively
  8746. */
  8747. function compareNumeric(a, b) {
  8748. var aPrefix = a.match(numericRegex)[1];
  8749. var bPrefix = b.match(numericRegex)[1];
  8750. var aNumeric = parseInt(aPrefix, 10);
  8751. var bNumeric = parseInt(bPrefix, 10);
  8752. if (isNumber(aNumeric) && isNumber(bNumeric) && aNumeric !== bNumeric) {
  8753. return compare(aNumeric, bNumeric);
  8754. } else {
  8755. return compare(a, b);
  8756. }
  8757. }
  8758. /**
  8759. * Returns the ordering of `a` and `b`.
  8760. *
  8761. * @param {string|number} a
  8762. * @param {string|number} b
  8763. * @returns {number} -1, 0 or 1 to indicate whether `a` is less than, equal to,
  8764. * or greater than `b`, respectively
  8765. */
  8766. function compare(a, b) {
  8767. !(typeof a === typeof b) ? process.env.NODE_ENV !== 'production' ? invariant_1(false, '"a" and "b" must be of the same type') : invariant_1(false) : void 0;
  8768. if (a > b) {
  8769. return 1;
  8770. } else if (a < b) {
  8771. return -1;
  8772. } else {
  8773. return 0;
  8774. }
  8775. }
  8776. /**
  8777. * Compares arrays of version components.
  8778. *
  8779. * @param {array<string>} a
  8780. * @param {array<string>} b
  8781. * @returns {number} -1, 0 or 1 to indicate whether `a` is less than, equal to,
  8782. * or greater than `b`, respectively
  8783. */
  8784. function compareComponents(a, b) {
  8785. var _normalizeVersions = normalizeVersions(a, b),
  8786. aNormalized = _normalizeVersions[0],
  8787. bNormalized = _normalizeVersions[1];
  8788. for (var i = 0; i < bNormalized.length; i++) {
  8789. var result = compareNumeric(aNormalized[i], bNormalized[i]);
  8790. if (result) {
  8791. return result;
  8792. }
  8793. }
  8794. return 0;
  8795. }
  8796. var VersionRange = {
  8797. /**
  8798. * Checks whether `version` satisfies the `range` specification.
  8799. *
  8800. * We support a subset of the expressions defined in
  8801. * https://www.npmjs.org/doc/misc/semver.html:
  8802. *
  8803. * version Must match version exactly
  8804. * =version Same as just version
  8805. * >version Must be greater than version
  8806. * >=version Must be greater than or equal to version
  8807. * <version Must be less than version
  8808. * <=version Must be less than or equal to version
  8809. * ~version Must be at least version, but less than the next significant
  8810. * revision above version:
  8811. * "~1.2.3" is equivalent to ">= 1.2.3 and < 1.3"
  8812. * ~>version Equivalent to ~version
  8813. * 1.2.x Must match "1.2.x", where "x" is a wildcard that matches
  8814. * anything
  8815. * 1.2.* Similar to "1.2.x", but "*" in the trailing position is a
  8816. * "greedy" wildcard, so will match any number of additional
  8817. * components:
  8818. * "1.2.*" will match "1.2.1", "1.2.1.1", "1.2.1.1.1" etc
  8819. * * Any version
  8820. * "" (Empty string) Same as *
  8821. * v1 - v2 Equivalent to ">= v1 and <= v2"
  8822. * r1 || r2 Passes if either r1 or r2 are satisfied
  8823. *
  8824. * @param {string} range
  8825. * @param {string} version
  8826. * @returns {boolean}
  8827. */
  8828. contains: function contains(range, version) {
  8829. return checkOrExpression(range.trim(), version.trim());
  8830. }
  8831. };
  8832. var VersionRange_1 = VersionRange;
  8833. /**
  8834. * Copyright (c) 2013-present, Facebook, Inc.
  8835. *
  8836. * This source code is licensed under the MIT license found in the
  8837. * LICENSE file in the root directory of this source tree.
  8838. *
  8839. */
  8840. var hasOwnProperty$1 = Object.prototype.hasOwnProperty;
  8841. /**
  8842. * Executes the provided `callback` once for each enumerable own property in the
  8843. * object and constructs a new object from the results. The `callback` is
  8844. * invoked with three arguments:
  8845. *
  8846. * - the property value
  8847. * - the property name
  8848. * - the object being traversed
  8849. *
  8850. * Properties that are added after the call to `mapObject` will not be visited
  8851. * by `callback`. If the values of existing properties are changed, the value
  8852. * passed to `callback` will be the value at the time `mapObject` visits them.
  8853. * Properties that are deleted before being visited are not visited.
  8854. *
  8855. * @grep function objectMap()
  8856. * @grep function objMap()
  8857. *
  8858. * @param {?object} object
  8859. * @param {function} callback
  8860. * @param {*} context
  8861. * @return {?object}
  8862. */
  8863. function mapObject(object, callback, context) {
  8864. if (!object) {
  8865. return null;
  8866. }
  8867. var result = {};
  8868. for (var name in object) {
  8869. if (hasOwnProperty$1.call(object, name)) {
  8870. result[name] = callback.call(context, object[name], name, object);
  8871. }
  8872. }
  8873. return result;
  8874. }
  8875. var mapObject_1 = mapObject;
  8876. /**
  8877. * Copyright (c) 2013-present, Facebook, Inc.
  8878. *
  8879. * This source code is licensed under the MIT license found in the
  8880. * LICENSE file in the root directory of this source tree.
  8881. *
  8882. *
  8883. * @typechecks static-only
  8884. */
  8885. /**
  8886. * Memoizes the return value of a function that accepts one string argument.
  8887. */
  8888. function memoizeStringOnly(callback) {
  8889. var cache = {};
  8890. return function (string) {
  8891. if (!cache.hasOwnProperty(string)) {
  8892. cache[string] = callback.call(this, string);
  8893. }
  8894. return cache[string];
  8895. };
  8896. }
  8897. var memoizeStringOnly_1 = memoizeStringOnly;
  8898. /**
  8899. * Checks to see whether `name` and `version` satisfy `query`.
  8900. *
  8901. * @param {string} name Name of the browser, device, engine or platform
  8902. * @param {?string} version Version of the browser, engine or platform
  8903. * @param {string} query Query of form "Name [range expression]"
  8904. * @param {?function} normalizer Optional pre-processor for range expression
  8905. * @return {boolean}
  8906. */
  8907. function compare$1(name, version, query, normalizer) {
  8908. // check for exact match with no version
  8909. if (name === query) {
  8910. return true;
  8911. }
  8912. // check for non-matching names
  8913. if (!query.startsWith(name)) {
  8914. return false;
  8915. }
  8916. // full comparison with version
  8917. var range = query.slice(name.length);
  8918. if (version) {
  8919. range = normalizer ? normalizer(range) : range;
  8920. return VersionRange_1.contains(range, version);
  8921. }
  8922. return false;
  8923. }
  8924. /**
  8925. * Normalizes `version` by stripping any "NT" prefix, but only on the Windows
  8926. * platform.
  8927. *
  8928. * Mimics the stripping performed by the `UserAgentWindowsPlatform` PHP class.
  8929. *
  8930. * @param {string} version
  8931. * @return {string}
  8932. */
  8933. function normalizePlatformVersion(version) {
  8934. if (UserAgentData.platformName === 'Windows') {
  8935. return version.replace(/^\s*NT/, '');
  8936. }
  8937. return version;
  8938. }
  8939. /**
  8940. * Provides client-side access to the authoritative PHP-generated User Agent
  8941. * information supplied by the server.
  8942. */
  8943. var UserAgent = {
  8944. /**
  8945. * Check if the User Agent browser matches `query`.
  8946. *
  8947. * `query` should be a string like "Chrome" or "Chrome > 33".
  8948. *
  8949. * Valid browser names include:
  8950. *
  8951. * - ACCESS NetFront
  8952. * - AOL
  8953. * - Amazon Silk
  8954. * - Android
  8955. * - BlackBerry
  8956. * - BlackBerry PlayBook
  8957. * - Chrome
  8958. * - Chrome for iOS
  8959. * - Chrome frame
  8960. * - Facebook PHP SDK
  8961. * - Facebook for iOS
  8962. * - Firefox
  8963. * - IE
  8964. * - IE Mobile
  8965. * - Mobile Safari
  8966. * - Motorola Internet Browser
  8967. * - Nokia
  8968. * - Openwave Mobile Browser
  8969. * - Opera
  8970. * - Opera Mini
  8971. * - Opera Mobile
  8972. * - Safari
  8973. * - UIWebView
  8974. * - Unknown
  8975. * - webOS
  8976. * - etc...
  8977. *
  8978. * An authoritative list can be found in the PHP `BrowserDetector` class and
  8979. * related classes in the same file (see calls to `new UserAgentBrowser` here:
  8980. * https://fburl.com/50728104).
  8981. *
  8982. * @note Function results are memoized
  8983. *
  8984. * @param {string} query Query of the form "Name [range expression]"
  8985. * @return {boolean}
  8986. */
  8987. isBrowser: function isBrowser(query) {
  8988. return compare$1(UserAgentData.browserName, UserAgentData.browserFullVersion, query);
  8989. },
  8990. /**
  8991. * Check if the User Agent browser uses a 32 or 64 bit architecture.
  8992. *
  8993. * @note Function results are memoized
  8994. *
  8995. * @param {string} query Query of the form "32" or "64".
  8996. * @return {boolean}
  8997. */
  8998. isBrowserArchitecture: function isBrowserArchitecture(query) {
  8999. return compare$1(UserAgentData.browserArchitecture, null, query);
  9000. },
  9001. /**
  9002. * Check if the User Agent device matches `query`.
  9003. *
  9004. * `query` should be a string like "iPhone" or "iPad".
  9005. *
  9006. * Valid device names include:
  9007. *
  9008. * - Kindle
  9009. * - Kindle Fire
  9010. * - Unknown
  9011. * - iPad
  9012. * - iPhone
  9013. * - iPod
  9014. * - etc...
  9015. *
  9016. * An authoritative list can be found in the PHP `DeviceDetector` class and
  9017. * related classes in the same file (see calls to `new UserAgentDevice` here:
  9018. * https://fburl.com/50728332).
  9019. *
  9020. * @note Function results are memoized
  9021. *
  9022. * @param {string} query Query of the form "Name"
  9023. * @return {boolean}
  9024. */
  9025. isDevice: function isDevice(query) {
  9026. return compare$1(UserAgentData.deviceName, null, query);
  9027. },
  9028. /**
  9029. * Check if the User Agent rendering engine matches `query`.
  9030. *
  9031. * `query` should be a string like "WebKit" or "WebKit >= 537".
  9032. *
  9033. * Valid engine names include:
  9034. *
  9035. * - Gecko
  9036. * - Presto
  9037. * - Trident
  9038. * - WebKit
  9039. * - etc...
  9040. *
  9041. * An authoritative list can be found in the PHP `RenderingEngineDetector`
  9042. * class related classes in the same file (see calls to `new
  9043. * UserAgentRenderingEngine` here: https://fburl.com/50728617).
  9044. *
  9045. * @note Function results are memoized
  9046. *
  9047. * @param {string} query Query of the form "Name [range expression]"
  9048. * @return {boolean}
  9049. */
  9050. isEngine: function isEngine(query) {
  9051. return compare$1(UserAgentData.engineName, UserAgentData.engineVersion, query);
  9052. },
  9053. /**
  9054. * Check if the User Agent platform matches `query`.
  9055. *
  9056. * `query` should be a string like "Windows" or "iOS 5 - 6".
  9057. *
  9058. * Valid platform names include:
  9059. *
  9060. * - Android
  9061. * - BlackBerry OS
  9062. * - Java ME
  9063. * - Linux
  9064. * - Mac OS X
  9065. * - Mac OS X Calendar
  9066. * - Mac OS X Internet Account
  9067. * - Symbian
  9068. * - SymbianOS
  9069. * - Windows
  9070. * - Windows Mobile
  9071. * - Windows Phone
  9072. * - iOS
  9073. * - iOS Facebook Integration Account
  9074. * - iOS Facebook Social Sharing UI
  9075. * - webOS
  9076. * - Chrome OS
  9077. * - etc...
  9078. *
  9079. * An authoritative list can be found in the PHP `PlatformDetector` class and
  9080. * related classes in the same file (see calls to `new UserAgentPlatform`
  9081. * here: https://fburl.com/50729226).
  9082. *
  9083. * @note Function results are memoized
  9084. *
  9085. * @param {string} query Query of the form "Name [range expression]"
  9086. * @return {boolean}
  9087. */
  9088. isPlatform: function isPlatform(query) {
  9089. return compare$1(UserAgentData.platformName, UserAgentData.platformFullVersion, query, normalizePlatformVersion);
  9090. },
  9091. /**
  9092. * Check if the User Agent platform is a 32 or 64 bit architecture.
  9093. *
  9094. * @note Function results are memoized
  9095. *
  9096. * @param {string} query Query of the form "32" or "64".
  9097. * @return {boolean}
  9098. */
  9099. isPlatformArchitecture: function isPlatformArchitecture(query) {
  9100. return compare$1(UserAgentData.platformArchitecture, null, query);
  9101. }
  9102. };
  9103. var UserAgent_1 = mapObject_1(UserAgent, memoizeStringOnly_1);
  9104. function _classCallCheck$9(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  9105. function _possibleConstructorReturn$6(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }
  9106. function _inherits$6(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
  9107. // In IE, spans with <br> tags render as two newlines. By rendering a span
  9108. // with only a newline character, we can be sure to render a single line.
  9109. var useNewlineChar = UserAgent_1.isBrowser('IE <= 11');
  9110. /**
  9111. * Check whether the node should be considered a newline.
  9112. */
  9113. function isNewline(node) {
  9114. return useNewlineChar ? node.textContent === '\n' : node.tagName === 'BR';
  9115. }
  9116. /**
  9117. * Placeholder elements for empty text content.
  9118. *
  9119. * What is this `data-text` attribute, anyway? It turns out that we need to
  9120. * put an attribute on the lowest-level text node in order to preserve correct
  9121. * spellcheck handling. If the <span> is naked, Chrome and Safari may do
  9122. * bizarre things to do the DOM -- split text nodes, create extra spans, etc.
  9123. * If the <span> has an attribute, this appears not to happen.
  9124. * See http://jsfiddle.net/9khdavod/ for the failure case, and
  9125. * http://jsfiddle.net/7pg143f7/ for the fixed case.
  9126. */
  9127. var NEWLINE_A = useNewlineChar ? React.createElement(
  9128. 'span',
  9129. { key: 'A', 'data-text': 'true' },
  9130. '\n'
  9131. ) : React.createElement('br', { key: 'A', 'data-text': 'true' });
  9132. var NEWLINE_B = useNewlineChar ? React.createElement(
  9133. 'span',
  9134. { key: 'B', 'data-text': 'true' },
  9135. '\n'
  9136. ) : React.createElement('br', { key: 'B', 'data-text': 'true' });
  9137. /**
  9138. * The lowest-level component in a `DraftEditor`, the text node component
  9139. * replaces the default React text node implementation. This allows us to
  9140. * perform custom handling of newline behavior and avoid re-rendering text
  9141. * nodes with DOM state that already matches the expectations of our immutable
  9142. * editor state.
  9143. */
  9144. var DraftEditorTextNode = function (_React$Component) {
  9145. _inherits$6(DraftEditorTextNode, _React$Component);
  9146. function DraftEditorTextNode(props) {
  9147. _classCallCheck$9(this, DraftEditorTextNode);
  9148. // By flipping this flag, we also keep flipping keys which forces
  9149. // React to remount this node every time it rerenders.
  9150. var _this = _possibleConstructorReturn$6(this, _React$Component.call(this, props));
  9151. _this._forceFlag = false;
  9152. return _this;
  9153. }
  9154. DraftEditorTextNode.prototype.shouldComponentUpdate = function shouldComponentUpdate(nextProps) {
  9155. var node = reactDom.findDOMNode(this);
  9156. var shouldBeNewline = nextProps.children === '';
  9157. !(node instanceof Element) ? process.env.NODE_ENV !== 'production' ? invariant_1(false, 'node is not an Element') : invariant_1(false) : void 0;
  9158. if (shouldBeNewline) {
  9159. return !isNewline(node);
  9160. }
  9161. return node.textContent !== nextProps.children;
  9162. };
  9163. DraftEditorTextNode.prototype.componentDidMount = function componentDidMount() {
  9164. this._forceFlag = !this._forceFlag;
  9165. };
  9166. DraftEditorTextNode.prototype.componentDidUpdate = function componentDidUpdate() {
  9167. this._forceFlag = !this._forceFlag;
  9168. };
  9169. DraftEditorTextNode.prototype.render = function render() {
  9170. if (this.props.children === '') {
  9171. return this._forceFlag ? NEWLINE_A : NEWLINE_B;
  9172. }
  9173. return React.createElement(
  9174. 'span',
  9175. { key: this._forceFlag ? 'A' : 'B', 'data-text': 'true' },
  9176. this.props.children
  9177. );
  9178. };
  9179. return DraftEditorTextNode;
  9180. }(React.Component);
  9181. var DraftEditorTextNode_react = DraftEditorTextNode;
  9182. /**
  9183. * Copyright (c) 2013-present, Facebook, Inc.
  9184. * All rights reserved.
  9185. *
  9186. * This source code is licensed under the BSD-style license found in the
  9187. * LICENSE file in the root directory of this source tree. An additional grant
  9188. * of patent rights can be found in the PATENTS file in the same directory.
  9189. *
  9190. * @providesModule DraftJsDebugLogging
  9191. */
  9192. var DraftJsDebugLogging = {
  9193. logSelectionStateFailure: function logSelectionStateFailure() {
  9194. return null;
  9195. }
  9196. };
  9197. /**
  9198. * Copyright (c) 2013-present, Facebook, Inc.
  9199. *
  9200. * This source code is licensed under the MIT license found in the
  9201. * LICENSE file in the root directory of this source tree.
  9202. *
  9203. * @typechecks
  9204. */
  9205. /**
  9206. * @param {*} object The object to check.
  9207. * @return {boolean} Whether or not the object is a DOM node.
  9208. */
  9209. function isNode(object) {
  9210. var doc = object ? object.ownerDocument || object : document;
  9211. var defaultView = doc.defaultView || window;
  9212. return !!(object && (typeof defaultView.Node === 'function' ? object instanceof defaultView.Node : typeof object === 'object' && typeof object.nodeType === 'number' && typeof object.nodeName === 'string'));
  9213. }
  9214. var isNode_1 = isNode;
  9215. /**
  9216. * Copyright (c) 2013-present, Facebook, Inc.
  9217. *
  9218. * This source code is licensed under the MIT license found in the
  9219. * LICENSE file in the root directory of this source tree.
  9220. *
  9221. * @typechecks
  9222. */
  9223. /**
  9224. * @param {*} object The object to check.
  9225. * @return {boolean} Whether or not the object is a DOM text node.
  9226. */
  9227. function isTextNode(object) {
  9228. return isNode_1(object) && object.nodeType == 3;
  9229. }
  9230. var isTextNode_1 = isTextNode;
  9231. /**
  9232. * Copyright (c) 2013-present, Facebook, Inc.
  9233. *
  9234. * This source code is licensed under the MIT license found in the
  9235. * LICENSE file in the root directory of this source tree.
  9236. *
  9237. *
  9238. */
  9239. /*eslint-disable no-bitwise */
  9240. /**
  9241. * Checks if a given DOM node contains or is another DOM node.
  9242. */
  9243. function containsNode(outerNode, innerNode) {
  9244. if (!outerNode || !innerNode) {
  9245. return false;
  9246. } else if (outerNode === innerNode) {
  9247. return true;
  9248. } else if (isTextNode_1(outerNode)) {
  9249. return false;
  9250. } else if (isTextNode_1(innerNode)) {
  9251. return containsNode(outerNode, innerNode.parentNode);
  9252. } else if ('contains' in outerNode) {
  9253. return outerNode.contains(innerNode);
  9254. } else if (outerNode.compareDocumentPosition) {
  9255. return !!(outerNode.compareDocumentPosition(innerNode) & 16);
  9256. } else {
  9257. return false;
  9258. }
  9259. }
  9260. var containsNode_1 = containsNode;
  9261. /**
  9262. * Copyright (c) 2013-present, Facebook, Inc.
  9263. *
  9264. * This source code is licensed under the MIT license found in the
  9265. * LICENSE file in the root directory of this source tree.
  9266. *
  9267. * @typechecks
  9268. */
  9269. /* eslint-disable fb-www/typeof-undefined */
  9270. /**
  9271. * Same as document.activeElement but wraps in a try-catch block. In IE it is
  9272. * not safe to call document.activeElement if there is nothing focused.
  9273. *
  9274. * The activeElement will be null only if the document or document body is not
  9275. * yet defined.
  9276. *
  9277. * @param {?DOMDocument} doc Defaults to current document.
  9278. * @return {?DOMElement}
  9279. */
  9280. function getActiveElement(doc) /*?DOMElement*/{
  9281. doc = doc || (typeof document !== 'undefined' ? document : undefined);
  9282. if (typeof doc === 'undefined') {
  9283. return null;
  9284. }
  9285. try {
  9286. return doc.activeElement || doc.body;
  9287. } catch (e) {
  9288. return doc.body;
  9289. }
  9290. }
  9291. var getActiveElement_1 = getActiveElement;
  9292. function getAnonymizedDOM(node, getNodeLabels) {
  9293. if (!node) {
  9294. return '[empty]';
  9295. }
  9296. var anonymized = anonymizeTextWithin(node, getNodeLabels);
  9297. if (anonymized.nodeType === Node.TEXT_NODE) {
  9298. return anonymized.textContent;
  9299. }
  9300. !(anonymized instanceof Element) ? process.env.NODE_ENV !== 'production' ? invariant_1(false, 'Node must be an Element if it is not a text node.') : invariant_1(false) : void 0;
  9301. return anonymized.outerHTML;
  9302. }
  9303. function anonymizeTextWithin(node, getNodeLabels) {
  9304. var labels = getNodeLabels !== undefined ? getNodeLabels(node) : [];
  9305. if (node.nodeType === Node.TEXT_NODE) {
  9306. var length = node.textContent.length;
  9307. return document.createTextNode('[text ' + length + (labels.length ? ' | ' + labels.join(', ') : '') + ']');
  9308. }
  9309. var clone = node.cloneNode();
  9310. if (clone.nodeType === 1 && labels.length) {
  9311. clone.setAttribute('data-labels', labels.join(', '));
  9312. }
  9313. var childNodes = node.childNodes;
  9314. for (var ii = 0; ii < childNodes.length; ii++) {
  9315. clone.appendChild(anonymizeTextWithin(childNodes[ii], getNodeLabels));
  9316. }
  9317. return clone;
  9318. }
  9319. function getAnonymizedEditorDOM(node, getNodeLabels) {
  9320. // grabbing the DOM content of the Draft editor
  9321. var currentNode = node;
  9322. while (currentNode) {
  9323. if (currentNode instanceof Element && currentNode.hasAttribute('contenteditable')) {
  9324. // found the Draft editor container
  9325. return getAnonymizedDOM(currentNode, getNodeLabels);
  9326. } else {
  9327. currentNode = currentNode.parentNode;
  9328. }
  9329. }
  9330. return 'Could not find contentEditable parent of node';
  9331. }
  9332. function getNodeLength(node) {
  9333. return node.nodeValue === null ? node.childNodes.length : node.nodeValue.length;
  9334. }
  9335. /**
  9336. * In modern non-IE browsers, we can support both forward and backward
  9337. * selections.
  9338. *
  9339. * Note: IE10+ supports the Selection object, but it does not support
  9340. * the `extend` method, which means that even in modern IE, it's not possible
  9341. * to programatically create a backward selection. Thus, for all IE
  9342. * versions, we use the old IE API to create our selections.
  9343. */
  9344. function setDraftEditorSelection(selectionState, node, blockKey, nodeStart, nodeEnd) {
  9345. // It's possible that the editor has been removed from the DOM but
  9346. // our selection code doesn't know it yet. Forcing selection in
  9347. // this case may lead to errors, so just bail now.
  9348. if (!containsNode_1(document.documentElement, node)) {
  9349. return;
  9350. }
  9351. var selection = commonjsGlobal.getSelection();
  9352. var anchorKey = selectionState.getAnchorKey();
  9353. var anchorOffset = selectionState.getAnchorOffset();
  9354. var focusKey = selectionState.getFocusKey();
  9355. var focusOffset = selectionState.getFocusOffset();
  9356. var isBackward = selectionState.getIsBackward();
  9357. // IE doesn't support backward selection. Swap key/offset pairs.
  9358. if (!selection.extend && isBackward) {
  9359. var tempKey = anchorKey;
  9360. var tempOffset = anchorOffset;
  9361. anchorKey = focusKey;
  9362. anchorOffset = focusOffset;
  9363. focusKey = tempKey;
  9364. focusOffset = tempOffset;
  9365. isBackward = false;
  9366. }
  9367. var hasAnchor = anchorKey === blockKey && nodeStart <= anchorOffset && nodeEnd >= anchorOffset;
  9368. var hasFocus = focusKey === blockKey && nodeStart <= focusOffset && nodeEnd >= focusOffset;
  9369. // If the selection is entirely bound within this node, set the selection
  9370. // and be done.
  9371. if (hasAnchor && hasFocus) {
  9372. selection.removeAllRanges();
  9373. addPointToSelection(selection, node, anchorOffset - nodeStart, selectionState);
  9374. addFocusToSelection(selection, node, focusOffset - nodeStart, selectionState);
  9375. return;
  9376. }
  9377. if (!isBackward) {
  9378. // If the anchor is within this node, set the range start.
  9379. if (hasAnchor) {
  9380. selection.removeAllRanges();
  9381. addPointToSelection(selection, node, anchorOffset - nodeStart, selectionState);
  9382. }
  9383. // If the focus is within this node, we can assume that we have
  9384. // already set the appropriate start range on the selection, and
  9385. // can simply extend the selection.
  9386. if (hasFocus) {
  9387. addFocusToSelection(selection, node, focusOffset - nodeStart, selectionState);
  9388. }
  9389. } else {
  9390. // If this node has the focus, set the selection range to be a
  9391. // collapsed range beginning here. Later, when we encounter the anchor,
  9392. // we'll use this information to extend the selection.
  9393. if (hasFocus) {
  9394. selection.removeAllRanges();
  9395. addPointToSelection(selection, node, focusOffset - nodeStart, selectionState);
  9396. }
  9397. // If this node has the anchor, we may assume that the correct
  9398. // focus information is already stored on the selection object.
  9399. // We keep track of it, reset the selection range, and extend it
  9400. // back to the focus point.
  9401. if (hasAnchor) {
  9402. var storedFocusNode = selection.focusNode;
  9403. var storedFocusOffset = selection.focusOffset;
  9404. selection.removeAllRanges();
  9405. addPointToSelection(selection, node, anchorOffset - nodeStart, selectionState);
  9406. addFocusToSelection(selection, storedFocusNode, storedFocusOffset, selectionState);
  9407. }
  9408. }
  9409. }
  9410. /**
  9411. * Extend selection towards focus point.
  9412. */
  9413. function addFocusToSelection(selection, node, offset, selectionState) {
  9414. var activeElement = getActiveElement_1();
  9415. if (selection.extend && containsNode_1(activeElement, node)) {
  9416. // If `extend` is called while another element has focus, an error is
  9417. // thrown. We therefore disable `extend` if the active element is somewhere
  9418. // other than the node we are selecting. This should only occur in Firefox,
  9419. // since it is the only browser to support multiple selections.
  9420. // See https://bugzilla.mozilla.org/show_bug.cgi?id=921444.
  9421. // logging to catch bug that is being reported in t16250795
  9422. if (offset > getNodeLength(node)) {
  9423. // the call to 'selection.extend' is about to throw
  9424. DraftJsDebugLogging.logSelectionStateFailure({
  9425. anonymizedDom: getAnonymizedEditorDOM(node),
  9426. extraParams: JSON.stringify({ offset: offset }),
  9427. selectionState: JSON.stringify(selectionState.toJS())
  9428. });
  9429. }
  9430. // logging to catch bug that is being reported in t18110632
  9431. var nodeWasFocus = node === selection.focusNode;
  9432. try {
  9433. selection.extend(node, offset);
  9434. } catch (e) {
  9435. DraftJsDebugLogging.logSelectionStateFailure({
  9436. anonymizedDom: getAnonymizedEditorDOM(node, function (n) {
  9437. var labels = [];
  9438. if (n === activeElement) {
  9439. labels.push('active element');
  9440. }
  9441. if (n === selection.anchorNode) {
  9442. labels.push('selection anchor node');
  9443. }
  9444. if (n === selection.focusNode) {
  9445. labels.push('selection focus node');
  9446. }
  9447. return labels;
  9448. }),
  9449. extraParams: JSON.stringify({
  9450. activeElementName: activeElement ? activeElement.nodeName : null,
  9451. nodeIsFocus: node === selection.focusNode,
  9452. nodeWasFocus: nodeWasFocus,
  9453. selectionRangeCount: selection.rangeCount,
  9454. selectionAnchorNodeName: selection.anchorNode ? selection.anchorNode.nodeName : null,
  9455. selectionAnchorOffset: selection.anchorOffset,
  9456. selectionFocusNodeName: selection.focusNode ? selection.focusNode.nodeName : null,
  9457. selectionFocusOffset: selection.focusOffset,
  9458. message: e ? '' + e : null,
  9459. offset: offset
  9460. }, null, 2),
  9461. selectionState: JSON.stringify(selectionState.toJS(), null, 2)
  9462. });
  9463. // allow the error to be thrown -
  9464. // better than continuing in a broken state
  9465. throw e;
  9466. }
  9467. } else {
  9468. // IE doesn't support extend. This will mean no backward selection.
  9469. // Extract the existing selection range and add focus to it.
  9470. // Additionally, clone the selection range. IE11 throws an
  9471. // InvalidStateError when attempting to access selection properties
  9472. // after the range is detached.
  9473. var range = selection.getRangeAt(0);
  9474. range.setEnd(node, offset);
  9475. selection.addRange(range.cloneRange());
  9476. }
  9477. }
  9478. function addPointToSelection(selection, node, offset, selectionState) {
  9479. var range = document.createRange();
  9480. // logging to catch bug that is being reported in t16250795
  9481. if (offset > getNodeLength(node)) {
  9482. // in this case we know that the call to 'range.setStart' is about to throw
  9483. DraftJsDebugLogging.logSelectionStateFailure({
  9484. anonymizedDom: getAnonymizedEditorDOM(node),
  9485. extraParams: JSON.stringify({ offset: offset }),
  9486. selectionState: JSON.stringify(selectionState.toJS())
  9487. });
  9488. }
  9489. range.setStart(node, offset);
  9490. selection.addRange(range);
  9491. }
  9492. var setDraftEditorSelection_1 = setDraftEditorSelection;
  9493. function _classCallCheck$a(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  9494. function _possibleConstructorReturn$7(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }
  9495. function _inherits$7(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
  9496. /**
  9497. * All leaf nodes in the editor are spans with single text nodes. Leaf
  9498. * elements are styled based on the merging of an optional custom style map
  9499. * and a default style map.
  9500. *
  9501. * `DraftEditorLeaf` also provides a wrapper for calling into the imperative
  9502. * DOM Selection API. In this way, top-level components can declaratively
  9503. * maintain the selection state.
  9504. */
  9505. var DraftEditorLeaf = function (_React$Component) {
  9506. _inherits$7(DraftEditorLeaf, _React$Component);
  9507. function DraftEditorLeaf() {
  9508. _classCallCheck$a(this, DraftEditorLeaf);
  9509. return _possibleConstructorReturn$7(this, _React$Component.apply(this, arguments));
  9510. }
  9511. DraftEditorLeaf.prototype._setSelection = function _setSelection() {
  9512. var selection = this.props.selection;
  9513. // If selection state is irrelevant to the parent block, no-op.
  9514. if (selection == null || !selection.getHasFocus()) {
  9515. return;
  9516. }
  9517. var _props = this.props,
  9518. block = _props.block,
  9519. start = _props.start,
  9520. text = _props.text;
  9521. var blockKey = block.getKey();
  9522. var end = start + text.length;
  9523. if (!selection.hasEdgeWithin(blockKey, start, end)) {
  9524. return;
  9525. }
  9526. // Determine the appropriate target node for selection. If the child
  9527. // is not a text node, it is a <br /> spacer. In this case, use the
  9528. // <span> itself as the selection target.
  9529. var node = reactDom.findDOMNode(this);
  9530. !node ? process.env.NODE_ENV !== 'production' ? invariant_1(false, 'Missing node') : invariant_1(false) : void 0;
  9531. var child = node.firstChild;
  9532. !child ? process.env.NODE_ENV !== 'production' ? invariant_1(false, 'Missing child') : invariant_1(false) : void 0;
  9533. var targetNode = void 0;
  9534. if (child.nodeType === Node.TEXT_NODE) {
  9535. targetNode = child;
  9536. } else if (child.tagName === 'BR') {
  9537. targetNode = node;
  9538. } else {
  9539. targetNode = child.firstChild;
  9540. !targetNode ? process.env.NODE_ENV !== 'production' ? invariant_1(false, 'Missing targetNode') : invariant_1(false) : void 0;
  9541. }
  9542. setDraftEditorSelection_1(selection, targetNode, blockKey, start, end);
  9543. };
  9544. /**
  9545. * By making individual leaf instances aware of their context within
  9546. * the text of the editor, we can set our selection range more
  9547. * easily than we could in the non-React world.
  9548. *
  9549. * Note that this depends on our maintaining tight control over the
  9550. * DOM structure of the DraftEditor component. If leaves had multiple
  9551. * text nodes, this would be harder.
  9552. */
  9553. DraftEditorLeaf.prototype.shouldComponentUpdate = function shouldComponentUpdate(nextProps) {
  9554. var leafNode = reactDom.findDOMNode(this.leaf);
  9555. !leafNode ? process.env.NODE_ENV !== 'production' ? invariant_1(false, 'Missing leafNode') : invariant_1(false) : void 0;
  9556. return leafNode.textContent !== nextProps.text || nextProps.styleSet !== this.props.styleSet || nextProps.forceSelection;
  9557. };
  9558. DraftEditorLeaf.prototype.componentDidUpdate = function componentDidUpdate() {
  9559. this._setSelection();
  9560. };
  9561. DraftEditorLeaf.prototype.componentDidMount = function componentDidMount() {
  9562. this._setSelection();
  9563. };
  9564. DraftEditorLeaf.prototype.render = function render() {
  9565. var _this2 = this;
  9566. var block = this.props.block;
  9567. var text = this.props.text;
  9568. // If the leaf is at the end of its block and ends in a soft newline, append
  9569. // an extra line feed character. Browsers collapse trailing newline
  9570. // characters, which leaves the cursor in the wrong place after a
  9571. // shift+enter. The extra character repairs this.
  9572. if (text.endsWith('\n') && this.props.isLast) {
  9573. text += '\n';
  9574. }
  9575. var _props2 = this.props,
  9576. customStyleMap = _props2.customStyleMap,
  9577. customStyleFn = _props2.customStyleFn,
  9578. offsetKey = _props2.offsetKey,
  9579. styleSet = _props2.styleSet;
  9580. var styleObj = styleSet.reduce(function (map, styleName) {
  9581. var mergedStyles = {};
  9582. var style = customStyleMap[styleName];
  9583. if (style !== undefined && map.textDecoration !== style.textDecoration) {
  9584. // .trim() is necessary for IE9/10/11 and Edge
  9585. mergedStyles.textDecoration = [map.textDecoration, style.textDecoration].join(' ').trim();
  9586. }
  9587. return objectAssign(map, style, mergedStyles);
  9588. }, {});
  9589. if (customStyleFn) {
  9590. var newStyles = customStyleFn(styleSet, block);
  9591. styleObj = objectAssign(styleObj, newStyles);
  9592. }
  9593. return React.createElement(
  9594. 'span',
  9595. {
  9596. 'data-offset-key': offsetKey,
  9597. ref: function ref(_ref) {
  9598. return _this2.leaf = _ref;
  9599. },
  9600. style: styleObj },
  9601. React.createElement(
  9602. DraftEditorTextNode_react,
  9603. null,
  9604. text
  9605. )
  9606. );
  9607. };
  9608. return DraftEditorLeaf;
  9609. }(React.Component);
  9610. var DraftEditorLeaf_react = DraftEditorLeaf;
  9611. /**
  9612. * Copyright (c) 2013-present, Facebook, Inc.
  9613. * All rights reserved.
  9614. *
  9615. * This source code is licensed under the BSD-style license found in the
  9616. * LICENSE file in the root directory of this source tree. An additional grant
  9617. * of patent rights can be found in the PATENTS file in the same directory.
  9618. *
  9619. * @providesModule DraftOffsetKey
  9620. * @format
  9621. *
  9622. */
  9623. var KEY_DELIMITER = '-';
  9624. var DraftOffsetKey = {
  9625. encode: function encode(blockKey, decoratorKey, leafKey) {
  9626. return blockKey + KEY_DELIMITER + decoratorKey + KEY_DELIMITER + leafKey;
  9627. },
  9628. decode: function decode(offsetKey) {
  9629. var _offsetKey$split = offsetKey.split(KEY_DELIMITER),
  9630. blockKey = _offsetKey$split[0],
  9631. decoratorKey = _offsetKey$split[1],
  9632. leafKey = _offsetKey$split[2];
  9633. return {
  9634. blockKey: blockKey,
  9635. decoratorKey: parseInt(decoratorKey, 10),
  9636. leafKey: parseInt(leafKey, 10)
  9637. };
  9638. }
  9639. };
  9640. var DraftOffsetKey_1 = DraftOffsetKey;
  9641. /**
  9642. * Copyright (c) 2013-present, Facebook, Inc.
  9643. *
  9644. * This source code is licensed under the MIT license found in the
  9645. * LICENSE file in the root directory of this source tree.
  9646. *
  9647. */
  9648. /**
  9649. * @param {DOMElement} element
  9650. * @param {DOMDocument} doc
  9651. * @return {boolean}
  9652. */
  9653. function _isViewportScrollElement(element, doc) {
  9654. return !!doc && (element === doc.documentElement || element === doc.body);
  9655. }
  9656. /**
  9657. * Scroll Module. This class contains 4 simple static functions
  9658. * to be used to access Element.scrollTop/scrollLeft properties.
  9659. * To solve the inconsistencies between browsers when either
  9660. * document.body or document.documentElement is supplied,
  9661. * below logic will be used to alleviate the issue:
  9662. *
  9663. * 1. If 'element' is either 'document.body' or 'document.documentElement,
  9664. * get whichever element's 'scroll{Top,Left}' is larger.
  9665. * 2. If 'element' is either 'document.body' or 'document.documentElement',
  9666. * set the 'scroll{Top,Left}' on both elements.
  9667. */
  9668. var Scroll = {
  9669. /**
  9670. * @param {DOMElement} element
  9671. * @return {number}
  9672. */
  9673. getTop: function getTop(element) {
  9674. var doc = element.ownerDocument;
  9675. return _isViewportScrollElement(element, doc) ?
  9676. // In practice, they will either both have the same value,
  9677. // or one will be zero and the other will be the scroll position
  9678. // of the viewport. So we can use `X || Y` instead of `Math.max(X, Y)`
  9679. doc.body.scrollTop || doc.documentElement.scrollTop : element.scrollTop;
  9680. },
  9681. /**
  9682. * @param {DOMElement} element
  9683. * @param {number} newTop
  9684. */
  9685. setTop: function setTop(element, newTop) {
  9686. var doc = element.ownerDocument;
  9687. if (_isViewportScrollElement(element, doc)) {
  9688. doc.body.scrollTop = doc.documentElement.scrollTop = newTop;
  9689. } else {
  9690. element.scrollTop = newTop;
  9691. }
  9692. },
  9693. /**
  9694. * @param {DOMElement} element
  9695. * @return {number}
  9696. */
  9697. getLeft: function getLeft(element) {
  9698. var doc = element.ownerDocument;
  9699. return _isViewportScrollElement(element, doc) ? doc.body.scrollLeft || doc.documentElement.scrollLeft : element.scrollLeft;
  9700. },
  9701. /**
  9702. * @param {DOMElement} element
  9703. * @param {number} newLeft
  9704. */
  9705. setLeft: function setLeft(element, newLeft) {
  9706. var doc = element.ownerDocument;
  9707. if (_isViewportScrollElement(element, doc)) {
  9708. doc.body.scrollLeft = doc.documentElement.scrollLeft = newLeft;
  9709. } else {
  9710. element.scrollLeft = newLeft;
  9711. }
  9712. }
  9713. };
  9714. var Scroll_1 = Scroll;
  9715. /**
  9716. * Copyright (c) 2013-present, Facebook, Inc.
  9717. *
  9718. * This source code is licensed under the MIT license found in the
  9719. * LICENSE file in the root directory of this source tree.
  9720. *
  9721. * @typechecks
  9722. */
  9723. var _hyphenPattern = /-(.)/g;
  9724. /**
  9725. * Camelcases a hyphenated string, for example:
  9726. *
  9727. * > camelize('background-color')
  9728. * < "backgroundColor"
  9729. *
  9730. * @param {string} string
  9731. * @return {string}
  9732. */
  9733. function camelize(string) {
  9734. return string.replace(_hyphenPattern, function (_, character) {
  9735. return character.toUpperCase();
  9736. });
  9737. }
  9738. var camelize_1 = camelize;
  9739. /**
  9740. * Copyright (c) 2013-present, Facebook, Inc.
  9741. *
  9742. * This source code is licensed under the MIT license found in the
  9743. * LICENSE file in the root directory of this source tree.
  9744. *
  9745. * @typechecks
  9746. */
  9747. var _uppercasePattern = /([A-Z])/g;
  9748. /**
  9749. * Hyphenates a camelcased string, for example:
  9750. *
  9751. * > hyphenate('backgroundColor')
  9752. * < "background-color"
  9753. *
  9754. * For CSS style names, use `hyphenateStyleName` instead which works properly
  9755. * with all vendor prefixes, including `ms`.
  9756. *
  9757. * @param {string} string
  9758. * @return {string}
  9759. */
  9760. function hyphenate(string) {
  9761. return string.replace(_uppercasePattern, '-$1').toLowerCase();
  9762. }
  9763. var hyphenate_1 = hyphenate;
  9764. /**
  9765. * Copyright (c) 2013-present, Facebook, Inc.
  9766. *
  9767. * This source code is licensed under the MIT license found in the
  9768. * LICENSE file in the root directory of this source tree.
  9769. *
  9770. * @typechecks
  9771. */
  9772. function asString(value) /*?string*/{
  9773. return value == null ? value : String(value);
  9774. }
  9775. function getStyleProperty( /*DOMNode*/node, /*string*/name) /*?string*/{
  9776. var computedStyle = void 0;
  9777. // W3C Standard
  9778. if (window.getComputedStyle) {
  9779. // In certain cases such as within an iframe in FF3, this returns null.
  9780. computedStyle = window.getComputedStyle(node, null);
  9781. if (computedStyle) {
  9782. return asString(computedStyle.getPropertyValue(hyphenate_1(name)));
  9783. }
  9784. }
  9785. // Safari
  9786. if (document.defaultView && document.defaultView.getComputedStyle) {
  9787. computedStyle = document.defaultView.getComputedStyle(node, null);
  9788. // A Safari bug causes this to return null for `display: none` elements.
  9789. if (computedStyle) {
  9790. return asString(computedStyle.getPropertyValue(hyphenate_1(name)));
  9791. }
  9792. if (name === 'display') {
  9793. return 'none';
  9794. }
  9795. }
  9796. // Internet Explorer
  9797. if (node.currentStyle) {
  9798. if (name === 'float') {
  9799. return asString(node.currentStyle.cssFloat || node.currentStyle.styleFloat);
  9800. }
  9801. return asString(node.currentStyle[camelize_1(name)]);
  9802. }
  9803. return asString(node.style && node.style[camelize_1(name)]);
  9804. }
  9805. var getStyleProperty_1 = getStyleProperty;
  9806. /**
  9807. * Copyright (c) 2013-present, Facebook, Inc.
  9808. *
  9809. * This source code is licensed under the MIT license found in the
  9810. * LICENSE file in the root directory of this source tree.
  9811. *
  9812. * @typechecks
  9813. */
  9814. /**
  9815. * @param {DOMNode} element [description]
  9816. * @param {string} name Overflow style property name.
  9817. * @return {boolean} True if the supplied ndoe is scrollable.
  9818. */
  9819. function _isNodeScrollable(element, name) {
  9820. var overflow = Style.get(element, name);
  9821. return overflow === 'auto' || overflow === 'scroll';
  9822. }
  9823. /**
  9824. * Utilities for querying and mutating style properties.
  9825. */
  9826. var Style = {
  9827. /**
  9828. * Gets the style property for the supplied node. This will return either the
  9829. * computed style, if available, or the declared style.
  9830. *
  9831. * @param {DOMNode} node
  9832. * @param {string} name Style property name.
  9833. * @return {?string} Style property value.
  9834. */
  9835. get: getStyleProperty_1,
  9836. /**
  9837. * Determines the nearest ancestor of a node that is scrollable.
  9838. *
  9839. * NOTE: This can be expensive if used repeatedly or on a node nested deeply.
  9840. *
  9841. * @param {?DOMNode} node Node from which to start searching.
  9842. * @return {?DOMWindow|DOMElement} Scroll parent of the supplied node.
  9843. */
  9844. getScrollParent: function getScrollParent(node) {
  9845. if (!node) {
  9846. return null;
  9847. }
  9848. var ownerDocument = node.ownerDocument;
  9849. while (node && node !== ownerDocument.body) {
  9850. if (_isNodeScrollable(node, 'overflow') || _isNodeScrollable(node, 'overflowY') || _isNodeScrollable(node, 'overflowX')) {
  9851. return node;
  9852. }
  9853. node = node.parentNode;
  9854. }
  9855. return ownerDocument.defaultView || ownerDocument.parentWindow;
  9856. }
  9857. };
  9858. var Style_1 = Style;
  9859. /**
  9860. * Copyright (c) 2013-present, Facebook, Inc.
  9861. *
  9862. * This source code is licensed under the MIT license found in the
  9863. * LICENSE file in the root directory of this source tree.
  9864. *
  9865. * @typechecks
  9866. */
  9867. /**
  9868. * Gets an element's bounding rect in pixels relative to the viewport.
  9869. *
  9870. * @param {DOMElement} elem
  9871. * @return {object}
  9872. */
  9873. function getElementRect(elem) {
  9874. var docElem = elem.ownerDocument.documentElement;
  9875. // FF 2, Safari 3 and Opera 9.5- do not support getBoundingClientRect().
  9876. // IE9- will throw if the element is not in the document.
  9877. if (!('getBoundingClientRect' in elem) || !containsNode_1(docElem, elem)) {
  9878. return {
  9879. left: 0,
  9880. right: 0,
  9881. top: 0,
  9882. bottom: 0
  9883. };
  9884. }
  9885. // Subtracts clientTop/Left because IE8- added a 2px border to the
  9886. // <html> element (see http://fburl.com/1493213). IE 7 in
  9887. // Quicksmode does not report clientLeft/clientTop so there
  9888. // will be an unaccounted offset of 2px when in quirksmode
  9889. var rect = elem.getBoundingClientRect();
  9890. return {
  9891. left: Math.round(rect.left) - docElem.clientLeft,
  9892. right: Math.round(rect.right) - docElem.clientLeft,
  9893. top: Math.round(rect.top) - docElem.clientTop,
  9894. bottom: Math.round(rect.bottom) - docElem.clientTop
  9895. };
  9896. }
  9897. var getElementRect_1 = getElementRect;
  9898. /**
  9899. * Copyright (c) 2013-present, Facebook, Inc.
  9900. *
  9901. * This source code is licensed under the MIT license found in the
  9902. * LICENSE file in the root directory of this source tree.
  9903. *
  9904. * @typechecks
  9905. */
  9906. /**
  9907. * Gets an element's position in pixels relative to the viewport. The returned
  9908. * object represents the position of the element's top left corner.
  9909. *
  9910. * @param {DOMElement} element
  9911. * @return {object}
  9912. */
  9913. function getElementPosition(element) {
  9914. var rect = getElementRect_1(element);
  9915. return {
  9916. x: rect.left,
  9917. y: rect.top,
  9918. width: rect.right - rect.left,
  9919. height: rect.bottom - rect.top
  9920. };
  9921. }
  9922. var getElementPosition_1 = getElementPosition;
  9923. /**
  9924. * Copyright (c) 2013-present, Facebook, Inc.
  9925. *
  9926. * This source code is licensed under the MIT license found in the
  9927. * LICENSE file in the root directory of this source tree.
  9928. *
  9929. * @typechecks
  9930. */
  9931. var isWebkit = typeof navigator !== 'undefined' && navigator.userAgent.indexOf('AppleWebKit') > -1;
  9932. /**
  9933. * Gets the element with the document scroll properties such as `scrollLeft` and
  9934. * `scrollHeight`. This may differ across different browsers.
  9935. *
  9936. * NOTE: The return value can be null if the DOM is not yet ready.
  9937. *
  9938. * @param {?DOMDocument} doc Defaults to current document.
  9939. * @return {?DOMElement}
  9940. */
  9941. function getDocumentScrollElement(doc) {
  9942. doc = doc || document;
  9943. if (doc.scrollingElement) {
  9944. return doc.scrollingElement;
  9945. }
  9946. return !isWebkit && doc.compatMode === 'CSS1Compat' ? doc.documentElement : doc.body;
  9947. }
  9948. var getDocumentScrollElement_1 = getDocumentScrollElement;
  9949. /**
  9950. * Copyright (c) 2013-present, Facebook, Inc.
  9951. *
  9952. * This source code is licensed under the MIT license found in the
  9953. * LICENSE file in the root directory of this source tree.
  9954. *
  9955. * @typechecks
  9956. */
  9957. /**
  9958. * Gets the scroll position of the supplied element or window.
  9959. *
  9960. * The return values are unbounded, unlike `getScrollPosition`. This means they
  9961. * may be negative or exceed the element boundaries (which is possible using
  9962. * inertial scrolling).
  9963. *
  9964. * @param {DOMWindow|DOMElement} scrollable
  9965. * @return {object} Map with `x` and `y` keys.
  9966. */
  9967. function getUnboundedScrollPosition(scrollable) {
  9968. if (scrollable.Window && scrollable instanceof scrollable.Window) {
  9969. return {
  9970. x: scrollable.pageXOffset || scrollable.document.documentElement.scrollLeft,
  9971. y: scrollable.pageYOffset || scrollable.document.documentElement.scrollTop
  9972. };
  9973. }
  9974. return {
  9975. x: scrollable.scrollLeft,
  9976. y: scrollable.scrollTop
  9977. };
  9978. }
  9979. var getUnboundedScrollPosition_1 = getUnboundedScrollPosition;
  9980. /**
  9981. * Gets the scroll position of the supplied element or window.
  9982. *
  9983. * The return values are bounded. This means that if the scroll position is
  9984. * negative or exceeds the element boundaries (which is possible using inertial
  9985. * scrolling), you will get zero or the maximum scroll position, respectively.
  9986. *
  9987. * If you need the unbound scroll position, use `getUnboundedScrollPosition`.
  9988. *
  9989. * @param {DOMWindow|DOMElement} scrollable
  9990. * @return {object} Map with `x` and `y` keys.
  9991. */
  9992. function getScrollPosition(scrollable) {
  9993. var documentScrollElement = getDocumentScrollElement_1(scrollable.ownerDocument || scrollable.document);
  9994. if (scrollable.Window && scrollable instanceof scrollable.Window) {
  9995. scrollable = documentScrollElement;
  9996. }
  9997. var scrollPosition = getUnboundedScrollPosition_1(scrollable);
  9998. var viewport = scrollable === documentScrollElement ? scrollable.ownerDocument.documentElement : scrollable;
  9999. var xMax = scrollable.scrollWidth - viewport.clientWidth;
  10000. var yMax = scrollable.scrollHeight - viewport.clientHeight;
  10001. scrollPosition.x = Math.max(0, Math.min(scrollPosition.x, xMax));
  10002. scrollPosition.y = Math.max(0, Math.min(scrollPosition.y, yMax));
  10003. return scrollPosition;
  10004. }
  10005. var getScrollPosition_1 = getScrollPosition;
  10006. function getViewportWidth() {
  10007. var width = void 0;
  10008. if (document.documentElement) {
  10009. width = document.documentElement.clientWidth;
  10010. }
  10011. if (!width && document.body) {
  10012. width = document.body.clientWidth;
  10013. }
  10014. return width || 0;
  10015. } /**
  10016. * Copyright (c) 2013-present, Facebook, Inc.
  10017. *
  10018. * This source code is licensed under the MIT license found in the
  10019. * LICENSE file in the root directory of this source tree.
  10020. *
  10021. *
  10022. * @typechecks
  10023. */
  10024. function getViewportHeight() {
  10025. var height = void 0;
  10026. if (document.documentElement) {
  10027. height = document.documentElement.clientHeight;
  10028. }
  10029. if (!height && document.body) {
  10030. height = document.body.clientHeight;
  10031. }
  10032. return height || 0;
  10033. }
  10034. /**
  10035. * Gets the viewport dimensions including any scrollbars.
  10036. */
  10037. function getViewportDimensions() {
  10038. return {
  10039. width: window.innerWidth || getViewportWidth(),
  10040. height: window.innerHeight || getViewportHeight()
  10041. };
  10042. }
  10043. /**
  10044. * Gets the viewport dimensions excluding any scrollbars.
  10045. */
  10046. getViewportDimensions.withoutScrollbars = function () {
  10047. return {
  10048. width: getViewportWidth(),
  10049. height: getViewportHeight()
  10050. };
  10051. };
  10052. var getViewportDimensions_1 = getViewportDimensions;
  10053. var _extends$2 = objectAssign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };
  10054. function _classCallCheck$b(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  10055. function _possibleConstructorReturn$8(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }
  10056. function _inherits$8(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
  10057. var SCROLL_BUFFER = 10;
  10058. /**
  10059. * Return whether a block overlaps with either edge of the `SelectionState`.
  10060. */
  10061. var isBlockOnSelectionEdge = function isBlockOnSelectionEdge(selection, key) {
  10062. return selection.getAnchorKey() === key || selection.getFocusKey() === key;
  10063. };
  10064. /**
  10065. * The default block renderer for a `DraftEditor` component.
  10066. *
  10067. * A `DraftEditorBlock` is able to render a given `ContentBlock` to its
  10068. * appropriate decorator and inline style components.
  10069. */
  10070. var DraftEditorBlock = function (_React$Component) {
  10071. _inherits$8(DraftEditorBlock, _React$Component);
  10072. function DraftEditorBlock() {
  10073. _classCallCheck$b(this, DraftEditorBlock);
  10074. return _possibleConstructorReturn$8(this, _React$Component.apply(this, arguments));
  10075. }
  10076. DraftEditorBlock.prototype.shouldComponentUpdate = function shouldComponentUpdate(nextProps) {
  10077. return this.props.block !== nextProps.block || this.props.tree !== nextProps.tree || this.props.direction !== nextProps.direction || isBlockOnSelectionEdge(nextProps.selection, nextProps.block.getKey()) && nextProps.forceSelection;
  10078. };
  10079. /**
  10080. * When a block is mounted and overlaps the selection state, we need to make
  10081. * sure that the cursor is visible to match native behavior. This may not
  10082. * be the case if the user has pressed `RETURN` or pasted some content, since
  10083. * programatically creating these new blocks and setting the DOM selection
  10084. * will miss out on the browser natively scrolling to that position.
  10085. *
  10086. * To replicate native behavior, if the block overlaps the selection state
  10087. * on mount, force the scroll position. Check the scroll state of the scroll
  10088. * parent, and adjust it to align the entire block to the bottom of the
  10089. * scroll parent.
  10090. */
  10091. DraftEditorBlock.prototype.componentDidMount = function componentDidMount() {
  10092. var selection = this.props.selection;
  10093. var endKey = selection.getEndKey();
  10094. if (!selection.getHasFocus() || endKey !== this.props.block.getKey()) {
  10095. return;
  10096. }
  10097. var blockNode = reactDom.findDOMNode(this);
  10098. var scrollParent = Style_1.getScrollParent(blockNode);
  10099. var scrollPosition = getScrollPosition_1(scrollParent);
  10100. var scrollDelta = void 0;
  10101. if (scrollParent === window) {
  10102. var nodePosition = getElementPosition_1(blockNode);
  10103. var nodeBottom = nodePosition.y + nodePosition.height;
  10104. var viewportHeight = getViewportDimensions_1().height;
  10105. scrollDelta = nodeBottom - viewportHeight;
  10106. if (scrollDelta > 0) {
  10107. window.scrollTo(scrollPosition.x, scrollPosition.y + scrollDelta + SCROLL_BUFFER);
  10108. }
  10109. } else {
  10110. !(blockNode instanceof HTMLElement) ? process.env.NODE_ENV !== 'production' ? invariant_1(false, 'blockNode is not an HTMLElement') : invariant_1(false) : void 0;
  10111. var blockBottom = blockNode.offsetHeight + blockNode.offsetTop;
  10112. var scrollBottom = scrollParent.offsetHeight + scrollPosition.y;
  10113. scrollDelta = blockBottom - scrollBottom;
  10114. if (scrollDelta > 0) {
  10115. Scroll_1.setTop(scrollParent, Scroll_1.getTop(scrollParent) + scrollDelta + SCROLL_BUFFER);
  10116. }
  10117. }
  10118. };
  10119. DraftEditorBlock.prototype._renderChildren = function _renderChildren() {
  10120. var _this2 = this;
  10121. var block = this.props.block;
  10122. var blockKey = block.getKey();
  10123. var text = block.getText();
  10124. var lastLeafSet = this.props.tree.size - 1;
  10125. var hasSelection = isBlockOnSelectionEdge(this.props.selection, blockKey);
  10126. return this.props.tree.map(function (leafSet, ii) {
  10127. var leavesForLeafSet = leafSet.get('leaves');
  10128. var lastLeaf = leavesForLeafSet.size - 1;
  10129. var leaves = leavesForLeafSet.map(function (leaf, jj) {
  10130. var offsetKey = DraftOffsetKey_1.encode(blockKey, ii, jj);
  10131. var start = leaf.get('start');
  10132. var end = leaf.get('end');
  10133. return React.createElement(DraftEditorLeaf_react, {
  10134. key: offsetKey,
  10135. offsetKey: offsetKey,
  10136. block: block,
  10137. start: start,
  10138. selection: hasSelection ? _this2.props.selection : null,
  10139. forceSelection: _this2.props.forceSelection,
  10140. text: text.slice(start, end),
  10141. styleSet: block.getInlineStyleAt(start),
  10142. customStyleMap: _this2.props.customStyleMap,
  10143. customStyleFn: _this2.props.customStyleFn,
  10144. isLast: ii === lastLeafSet && jj === lastLeaf
  10145. });
  10146. }).toArray();
  10147. var decoratorKey = leafSet.get('decoratorKey');
  10148. if (decoratorKey == null) {
  10149. return leaves;
  10150. }
  10151. if (!_this2.props.decorator) {
  10152. return leaves;
  10153. }
  10154. var decorator = nullthrows_1(_this2.props.decorator);
  10155. var DecoratorComponent = decorator.getComponentForKey(decoratorKey);
  10156. if (!DecoratorComponent) {
  10157. return leaves;
  10158. }
  10159. var decoratorProps = decorator.getPropsForKey(decoratorKey);
  10160. var decoratorOffsetKey = DraftOffsetKey_1.encode(blockKey, ii, 0);
  10161. var decoratedText = text.slice(leavesForLeafSet.first().get('start'), leavesForLeafSet.last().get('end'));
  10162. // Resetting dir to the same value on a child node makes Chrome/Firefox
  10163. // confused on cursor movement. See http://jsfiddle.net/d157kLck/3/
  10164. var dir = UnicodeBidiDirection_1.getHTMLDirIfDifferent(UnicodeBidi_1.getDirection(decoratedText), _this2.props.direction);
  10165. return React.createElement(
  10166. DecoratorComponent,
  10167. _extends$2({}, decoratorProps, {
  10168. contentState: _this2.props.contentState,
  10169. decoratedText: decoratedText,
  10170. dir: dir,
  10171. key: decoratorOffsetKey,
  10172. entityKey: block.getEntityAt(leafSet.get('start')),
  10173. offsetKey: decoratorOffsetKey }),
  10174. leaves
  10175. );
  10176. }).toArray();
  10177. };
  10178. DraftEditorBlock.prototype.render = function render() {
  10179. var _props = this.props,
  10180. direction = _props.direction,
  10181. offsetKey = _props.offsetKey;
  10182. var className = cx_1({
  10183. 'public/DraftStyleDefault/block': true,
  10184. 'public/DraftStyleDefault/ltr': direction === 'LTR',
  10185. 'public/DraftStyleDefault/rtl': direction === 'RTL'
  10186. });
  10187. return React.createElement(
  10188. 'div',
  10189. { 'data-offset-key': offsetKey, className: className },
  10190. this._renderChildren()
  10191. );
  10192. };
  10193. return DraftEditorBlock;
  10194. }(React.Component);
  10195. var DraftEditorBlock_react = DraftEditorBlock;
  10196. /**
  10197. * Copyright (c) 2013-present, Facebook, Inc.
  10198. *
  10199. * This source code is licensed under the MIT license found in the
  10200. * LICENSE file in the root directory of this source tree.
  10201. *
  10202. * @typechecks static-only
  10203. */
  10204. /**
  10205. * Combines multiple className strings into one.
  10206. * http://jsperf.com/joinclasses-args-vs-array
  10207. *
  10208. * @param {...?string} className
  10209. * @return {string}
  10210. */
  10211. function joinClasses(className /*, ... */) {
  10212. if (!className) {
  10213. className = '';
  10214. }
  10215. var nextClass = void 0;
  10216. var argLength = arguments.length;
  10217. if (argLength > 1) {
  10218. for (var ii = 1; ii < argLength; ii++) {
  10219. nextClass = arguments[ii];
  10220. if (nextClass) {
  10221. className = (className ? className + ' ' : '') + nextClass;
  10222. }
  10223. }
  10224. }
  10225. return className;
  10226. }
  10227. var joinClasses_1 = joinClasses;
  10228. var _extends$3 = objectAssign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };
  10229. function _classCallCheck$c(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  10230. function _possibleConstructorReturn$9(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }
  10231. function _inherits$9(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
  10232. /**
  10233. * Provide default styling for list items. This way, lists will be styled with
  10234. * proper counters and indentation even if the caller does not specify
  10235. * their own styling at all. If more than five levels of nesting are needed,
  10236. * the necessary CSS classes can be provided via `blockStyleFn` configuration.
  10237. */
  10238. var getListItemClasses = function getListItemClasses(type, depth, shouldResetCount, direction) {
  10239. return cx_1({
  10240. 'public/DraftStyleDefault/unorderedListItem': type === 'unordered-list-item',
  10241. 'public/DraftStyleDefault/orderedListItem': type === 'ordered-list-item',
  10242. 'public/DraftStyleDefault/reset': shouldResetCount,
  10243. 'public/DraftStyleDefault/depth0': depth === 0,
  10244. 'public/DraftStyleDefault/depth1': depth === 1,
  10245. 'public/DraftStyleDefault/depth2': depth === 2,
  10246. 'public/DraftStyleDefault/depth3': depth === 3,
  10247. 'public/DraftStyleDefault/depth4': depth === 4,
  10248. 'public/DraftStyleDefault/listLTR': direction === 'LTR',
  10249. 'public/DraftStyleDefault/listRTL': direction === 'RTL'
  10250. });
  10251. };
  10252. /**
  10253. * `DraftEditorContents` is the container component for all block components
  10254. * rendered for a `DraftEditor`. It is optimized to aggressively avoid
  10255. * re-rendering blocks whenever possible.
  10256. *
  10257. * This component is separate from `DraftEditor` because certain props
  10258. * (for instance, ARIA props) must be allowed to update without affecting
  10259. * the contents of the editor.
  10260. */
  10261. var DraftEditorContents = function (_React$Component) {
  10262. _inherits$9(DraftEditorContents, _React$Component);
  10263. function DraftEditorContents() {
  10264. _classCallCheck$c(this, DraftEditorContents);
  10265. return _possibleConstructorReturn$9(this, _React$Component.apply(this, arguments));
  10266. }
  10267. DraftEditorContents.prototype.shouldComponentUpdate = function shouldComponentUpdate(nextProps) {
  10268. var prevEditorState = this.props.editorState;
  10269. var nextEditorState = nextProps.editorState;
  10270. var prevDirectionMap = prevEditorState.getDirectionMap();
  10271. var nextDirectionMap = nextEditorState.getDirectionMap();
  10272. // Text direction has changed for one or more blocks. We must re-render.
  10273. if (prevDirectionMap !== nextDirectionMap) {
  10274. return true;
  10275. }
  10276. var didHaveFocus = prevEditorState.getSelection().getHasFocus();
  10277. var nowHasFocus = nextEditorState.getSelection().getHasFocus();
  10278. if (didHaveFocus !== nowHasFocus) {
  10279. return true;
  10280. }
  10281. var nextNativeContent = nextEditorState.getNativelyRenderedContent();
  10282. var wasComposing = prevEditorState.isInCompositionMode();
  10283. var nowComposing = nextEditorState.isInCompositionMode();
  10284. // If the state is unchanged or we're currently rendering a natively
  10285. // rendered state, there's nothing new to be done.
  10286. if (prevEditorState === nextEditorState || nextNativeContent !== null && nextEditorState.getCurrentContent() === nextNativeContent || wasComposing && nowComposing) {
  10287. return false;
  10288. }
  10289. var prevContent = prevEditorState.getCurrentContent();
  10290. var nextContent = nextEditorState.getCurrentContent();
  10291. var prevDecorator = prevEditorState.getDecorator();
  10292. var nextDecorator = nextEditorState.getDecorator();
  10293. return wasComposing !== nowComposing || prevContent !== nextContent || prevDecorator !== nextDecorator || nextEditorState.mustForceSelection();
  10294. };
  10295. DraftEditorContents.prototype.render = function render() {
  10296. var _props = this.props,
  10297. blockRenderMap = _props.blockRenderMap,
  10298. blockRendererFn = _props.blockRendererFn,
  10299. blockStyleFn = _props.blockStyleFn,
  10300. customStyleMap = _props.customStyleMap,
  10301. customStyleFn = _props.customStyleFn,
  10302. editorState = _props.editorState,
  10303. editorKey = _props.editorKey,
  10304. textDirectionality = _props.textDirectionality;
  10305. var content = editorState.getCurrentContent();
  10306. var selection = editorState.getSelection();
  10307. var forceSelection = editorState.mustForceSelection();
  10308. var decorator = editorState.getDecorator();
  10309. var directionMap = nullthrows_1(editorState.getDirectionMap());
  10310. var blocksAsArray = content.getBlocksAsArray();
  10311. var processedBlocks = [];
  10312. var currentDepth = null;
  10313. var lastWrapperTemplate = null;
  10314. for (var ii = 0; ii < blocksAsArray.length; ii++) {
  10315. var _block = blocksAsArray[ii];
  10316. var key = _block.getKey();
  10317. var blockType = _block.getType();
  10318. var customRenderer = blockRendererFn(_block);
  10319. var CustomComponent = void 0,
  10320. customProps = void 0,
  10321. customEditable = void 0;
  10322. if (customRenderer) {
  10323. CustomComponent = customRenderer.component;
  10324. customProps = customRenderer.props;
  10325. customEditable = customRenderer.editable;
  10326. }
  10327. var direction = textDirectionality ? textDirectionality : directionMap.get(key);
  10328. var offsetKey = DraftOffsetKey_1.encode(key, 0, 0);
  10329. var componentProps = {
  10330. contentState: content,
  10331. block: _block,
  10332. blockProps: customProps,
  10333. blockStyleFn: blockStyleFn,
  10334. customStyleMap: customStyleMap,
  10335. customStyleFn: customStyleFn,
  10336. decorator: decorator,
  10337. direction: direction,
  10338. forceSelection: forceSelection,
  10339. key: key,
  10340. offsetKey: offsetKey,
  10341. selection: selection,
  10342. tree: editorState.getBlockTree(key)
  10343. };
  10344. var configForType = blockRenderMap.get(blockType) || blockRenderMap.get('unstyled');
  10345. var wrapperTemplate = configForType.wrapper;
  10346. var Element = configForType.element || blockRenderMap.get('unstyled').element;
  10347. var depth = _block.getDepth();
  10348. var className = '';
  10349. if (blockStyleFn) {
  10350. className = blockStyleFn(_block);
  10351. }
  10352. // List items are special snowflakes, since we handle nesting and
  10353. // counters manually.
  10354. if (Element === 'li') {
  10355. var shouldResetCount = lastWrapperTemplate !== wrapperTemplate || currentDepth === null || depth > currentDepth;
  10356. className = joinClasses_1(className, getListItemClasses(blockType, depth, shouldResetCount, direction));
  10357. }
  10358. var Component = CustomComponent || DraftEditorBlock_react;
  10359. var childProps = {
  10360. className: className,
  10361. 'data-block': true,
  10362. 'data-editor': editorKey,
  10363. 'data-offset-key': offsetKey,
  10364. key: key
  10365. };
  10366. if (customEditable !== undefined) {
  10367. childProps = _extends$3({}, childProps, {
  10368. contentEditable: customEditable,
  10369. suppressContentEditableWarning: true
  10370. });
  10371. }
  10372. var child = React.createElement(Element, childProps, React.createElement(Component, componentProps));
  10373. processedBlocks.push({
  10374. block: child,
  10375. wrapperTemplate: wrapperTemplate,
  10376. key: key,
  10377. offsetKey: offsetKey
  10378. });
  10379. if (wrapperTemplate) {
  10380. currentDepth = _block.getDepth();
  10381. } else {
  10382. currentDepth = null;
  10383. }
  10384. lastWrapperTemplate = wrapperTemplate;
  10385. }
  10386. // Group contiguous runs of blocks that have the same wrapperTemplate
  10387. var outputBlocks = [];
  10388. for (var _ii = 0; _ii < processedBlocks.length;) {
  10389. var info = processedBlocks[_ii];
  10390. if (info.wrapperTemplate) {
  10391. var blocks = [];
  10392. do {
  10393. blocks.push(processedBlocks[_ii].block);
  10394. _ii++;
  10395. } while (_ii < processedBlocks.length && processedBlocks[_ii].wrapperTemplate === info.wrapperTemplate);
  10396. var wrapperElement = React.cloneElement(info.wrapperTemplate, {
  10397. key: info.key + '-wrap',
  10398. 'data-offset-key': info.offsetKey
  10399. }, blocks);
  10400. outputBlocks.push(wrapperElement);
  10401. } else {
  10402. outputBlocks.push(info.block);
  10403. _ii++;
  10404. }
  10405. }
  10406. return React.createElement(
  10407. 'div',
  10408. { 'data-contents': 'true' },
  10409. outputBlocks
  10410. );
  10411. };
  10412. return DraftEditorContents;
  10413. }(React.Component);
  10414. var DraftEditorContentsCore_react = DraftEditorContents;
  10415. var DraftEditorContents_react = DraftEditorContentsCore_react;
  10416. /**
  10417. * Copyright (c) 2013-present, Facebook, Inc.
  10418. *
  10419. * This source code is licensed under the MIT license found in the
  10420. * LICENSE file in the root directory of this source tree.
  10421. *
  10422. */
  10423. var PhotosMimeType = {
  10424. isImage: function isImage(mimeString) {
  10425. return getParts(mimeString)[0] === 'image';
  10426. },
  10427. isJpeg: function isJpeg(mimeString) {
  10428. var parts = getParts(mimeString);
  10429. return PhotosMimeType.isImage(mimeString) && (
  10430. // see http://fburl.com/10972194
  10431. parts[1] === 'jpeg' || parts[1] === 'pjpeg');
  10432. }
  10433. };
  10434. function getParts(mimeString) {
  10435. return mimeString.split('/');
  10436. }
  10437. var PhotosMimeType_1 = PhotosMimeType;
  10438. /**
  10439. * Copyright (c) 2013-present, Facebook, Inc.
  10440. *
  10441. * This source code is licensed under the MIT license found in the
  10442. * LICENSE file in the root directory of this source tree.
  10443. *
  10444. * @typechecks
  10445. */
  10446. /**
  10447. * Convert array-like objects to arrays.
  10448. *
  10449. * This API assumes the caller knows the contents of the data type. For less
  10450. * well defined inputs use createArrayFromMixed.
  10451. *
  10452. * @param {object|function|filelist} obj
  10453. * @return {array}
  10454. */
  10455. function toArray(obj) {
  10456. var length = obj.length;
  10457. // Some browsers builtin objects can report typeof 'function' (e.g. NodeList
  10458. // in old versions of Safari).
  10459. !(!Array.isArray(obj) && (typeof obj === 'object' || typeof obj === 'function')) ? process.env.NODE_ENV !== 'production' ? invariant_1(false, 'toArray: Array-like object expected') : invariant_1(false) : void 0;
  10460. !(typeof length === 'number') ? process.env.NODE_ENV !== 'production' ? invariant_1(false, 'toArray: Object needs a length property') : invariant_1(false) : void 0;
  10461. !(length === 0 || length - 1 in obj) ? process.env.NODE_ENV !== 'production' ? invariant_1(false, 'toArray: Object should have keys for indices') : invariant_1(false) : void 0;
  10462. !(typeof obj.callee !== 'function') ? process.env.NODE_ENV !== 'production' ? invariant_1(false, 'toArray: Object can\'t be `arguments`. Use rest params ' + '(function(...args) {}) or Array.from() instead.') : invariant_1(false) : void 0;
  10463. // Old IE doesn't give collections access to hasOwnProperty. Assume inputs
  10464. // without method will throw during the slice call and skip straight to the
  10465. // fallback.
  10466. if (obj.hasOwnProperty) {
  10467. try {
  10468. return Array.prototype.slice.call(obj);
  10469. } catch (e) {
  10470. // IE < 9 does not support Array#slice on collections objects
  10471. }
  10472. }
  10473. // Fall back to copying key by key. This assumes all keys have a value,
  10474. // so will not preserve sparsely populated inputs.
  10475. var ret = Array(length);
  10476. for (var ii = 0; ii < length; ii++) {
  10477. ret[ii] = obj[ii];
  10478. }
  10479. return ret;
  10480. }
  10481. /**
  10482. * Perform a heuristic test to determine if an object is "array-like".
  10483. *
  10484. * A monk asked Joshu, a Zen master, "Has a dog Buddha nature?"
  10485. * Joshu replied: "Mu."
  10486. *
  10487. * This function determines if its argument has "array nature": it returns
  10488. * true if the argument is an actual array, an `arguments' object, or an
  10489. * HTMLCollection (e.g. node.childNodes or node.getElementsByTagName()).
  10490. *
  10491. * It will return false for other array-like objects like Filelist.
  10492. *
  10493. * @param {*} obj
  10494. * @return {boolean}
  10495. */
  10496. function hasArrayNature(obj) {
  10497. return (
  10498. // not null/false
  10499. !!obj && (
  10500. // arrays are objects, NodeLists are functions in Safari
  10501. typeof obj == 'object' || typeof obj == 'function') &&
  10502. // quacks like an array
  10503. 'length' in obj &&
  10504. // not window
  10505. !('setInterval' in obj) &&
  10506. // no DOM node should be considered an array-like
  10507. // a 'select' element has 'length' and 'item' properties on IE8
  10508. typeof obj.nodeType != 'number' && (
  10509. // a real array
  10510. Array.isArray(obj) ||
  10511. // arguments
  10512. 'callee' in obj ||
  10513. // HTMLCollection/NodeList
  10514. 'item' in obj)
  10515. );
  10516. }
  10517. /**
  10518. * Ensure that the argument is an array by wrapping it in an array if it is not.
  10519. * Creates a copy of the argument if it is already an array.
  10520. *
  10521. * This is mostly useful idiomatically:
  10522. *
  10523. * var createArrayFromMixed = require('createArrayFromMixed');
  10524. *
  10525. * function takesOneOrMoreThings(things) {
  10526. * things = createArrayFromMixed(things);
  10527. * ...
  10528. * }
  10529. *
  10530. * This allows you to treat `things' as an array, but accept scalars in the API.
  10531. *
  10532. * If you need to convert an array-like object, like `arguments`, into an array
  10533. * use toArray instead.
  10534. *
  10535. * @param {*} obj
  10536. * @return {array}
  10537. */
  10538. function createArrayFromMixed(obj) {
  10539. if (!hasArrayNature(obj)) {
  10540. return [obj];
  10541. } else if (Array.isArray(obj)) {
  10542. return obj.slice();
  10543. } else {
  10544. return toArray(obj);
  10545. }
  10546. }
  10547. var createArrayFromMixed_1 = createArrayFromMixed;
  10548. function _classCallCheck$d(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  10549. /**
  10550. * Copyright (c) 2013-present, Facebook, Inc.
  10551. *
  10552. * This source code is licensed under the MIT license found in the
  10553. * LICENSE file in the root directory of this source tree.
  10554. *
  10555. * @typechecks
  10556. */
  10557. var CR_LF_REGEX = new RegExp('\r\n', 'g');
  10558. var LF_ONLY = '\n';
  10559. var RICH_TEXT_TYPES = {
  10560. 'text/rtf': 1,
  10561. 'text/html': 1
  10562. };
  10563. /**
  10564. * If DataTransferItem is a file then return the Blob of data.
  10565. *
  10566. * @param {object} item
  10567. * @return {?blob}
  10568. */
  10569. function getFileFromDataTransfer(item) {
  10570. if (item.kind == 'file') {
  10571. return item.getAsFile();
  10572. }
  10573. }
  10574. var DataTransfer$1 = function () {
  10575. /**
  10576. * @param {object} data
  10577. */
  10578. function DataTransfer(data) {
  10579. _classCallCheck$d(this, DataTransfer);
  10580. this.data = data;
  10581. // Types could be DOMStringList or array
  10582. this.types = data.types ? createArrayFromMixed_1(data.types) : [];
  10583. }
  10584. /**
  10585. * Is this likely to be a rich text data transfer?
  10586. *
  10587. * @return {boolean}
  10588. */
  10589. DataTransfer.prototype.isRichText = function isRichText() {
  10590. // If HTML is available, treat this data as rich text. This way, we avoid
  10591. // using a pasted image if it is packaged with HTML -- this may occur with
  10592. // pastes from MS Word, for example. However this is only rich text if
  10593. // there's accompanying text.
  10594. if (this.getHTML() && this.getText()) {
  10595. return true;
  10596. }
  10597. // When an image is copied from a preview window, you end up with two
  10598. // DataTransferItems one of which is a file's metadata as text. Skip those.
  10599. if (this.isImage()) {
  10600. return false;
  10601. }
  10602. return this.types.some(function (type) {
  10603. return RICH_TEXT_TYPES[type];
  10604. });
  10605. };
  10606. /**
  10607. * Get raw text.
  10608. *
  10609. * @return {?string}
  10610. */
  10611. DataTransfer.prototype.getText = function getText() {
  10612. var text;
  10613. if (this.data.getData) {
  10614. if (!this.types.length) {
  10615. text = this.data.getData('Text');
  10616. } else if (this.types.indexOf('text/plain') != -1) {
  10617. text = this.data.getData('text/plain');
  10618. }
  10619. }
  10620. return text ? text.replace(CR_LF_REGEX, LF_ONLY) : null;
  10621. };
  10622. /**
  10623. * Get HTML paste data
  10624. *
  10625. * @return {?string}
  10626. */
  10627. DataTransfer.prototype.getHTML = function getHTML() {
  10628. if (this.data.getData) {
  10629. if (!this.types.length) {
  10630. return this.data.getData('Text');
  10631. } else if (this.types.indexOf('text/html') != -1) {
  10632. return this.data.getData('text/html');
  10633. }
  10634. }
  10635. };
  10636. /**
  10637. * Is this a link data transfer?
  10638. *
  10639. * @return {boolean}
  10640. */
  10641. DataTransfer.prototype.isLink = function isLink() {
  10642. return this.types.some(function (type) {
  10643. return type.indexOf('Url') != -1 || type.indexOf('text/uri-list') != -1 || type.indexOf('text/x-moz-url');
  10644. });
  10645. };
  10646. /**
  10647. * Get a link url.
  10648. *
  10649. * @return {?string}
  10650. */
  10651. DataTransfer.prototype.getLink = function getLink() {
  10652. if (this.data.getData) {
  10653. if (this.types.indexOf('text/x-moz-url') != -1) {
  10654. var url = this.data.getData('text/x-moz-url').split('\n');
  10655. return url[0];
  10656. }
  10657. return this.types.indexOf('text/uri-list') != -1 ? this.data.getData('text/uri-list') : this.data.getData('url');
  10658. }
  10659. return null;
  10660. };
  10661. /**
  10662. * Is this an image data transfer?
  10663. *
  10664. * @return {boolean}
  10665. */
  10666. DataTransfer.prototype.isImage = function isImage() {
  10667. var isImage = this.types.some(function (type) {
  10668. // Firefox will have a type of application/x-moz-file for images during
  10669. // dragging
  10670. return type.indexOf('application/x-moz-file') != -1;
  10671. });
  10672. if (isImage) {
  10673. return true;
  10674. }
  10675. var items = this.getFiles();
  10676. for (var i = 0; i < items.length; i++) {
  10677. var type = items[i].type;
  10678. if (!PhotosMimeType_1.isImage(type)) {
  10679. return false;
  10680. }
  10681. }
  10682. return true;
  10683. };
  10684. DataTransfer.prototype.getCount = function getCount() {
  10685. if (this.data.hasOwnProperty('items')) {
  10686. return this.data.items.length;
  10687. } else if (this.data.hasOwnProperty('mozItemCount')) {
  10688. return this.data.mozItemCount;
  10689. } else if (this.data.files) {
  10690. return this.data.files.length;
  10691. }
  10692. return null;
  10693. };
  10694. /**
  10695. * Get files.
  10696. *
  10697. * @return {array}
  10698. */
  10699. DataTransfer.prototype.getFiles = function getFiles() {
  10700. if (this.data.items) {
  10701. // createArrayFromMixed doesn't properly handle DataTransferItemLists.
  10702. return Array.prototype.slice.call(this.data.items).map(getFileFromDataTransfer).filter(emptyFunction_1.thatReturnsArgument);
  10703. } else if (this.data.files) {
  10704. return Array.prototype.slice.call(this.data.files);
  10705. } else {
  10706. return [];
  10707. }
  10708. };
  10709. /**
  10710. * Are there any files to fetch?
  10711. *
  10712. * @return {boolean}
  10713. */
  10714. DataTransfer.prototype.hasFiles = function hasFiles() {
  10715. return this.getFiles().length > 0;
  10716. };
  10717. return DataTransfer;
  10718. }();
  10719. var DataTransfer_1 = DataTransfer$1;
  10720. /**
  10721. * Copyright (c) 2013-present, Facebook, Inc.
  10722. * All rights reserved.
  10723. *
  10724. * This source code is licensed under the BSD-style license found in the
  10725. * LICENSE file in the root directory of this source tree. An additional grant
  10726. * of patent rights can be found in the PATENTS file in the same directory.
  10727. *
  10728. * @providesModule getSelectionOffsetKeyForNode
  10729. * @format
  10730. *
  10731. */
  10732. /**
  10733. * Get offset key from a node or it's child nodes. Return the first offset key
  10734. * found on the DOM tree of given node.
  10735. */
  10736. function getSelectionOffsetKeyForNode(node) {
  10737. if (node instanceof Element) {
  10738. var offsetKey = node.getAttribute('data-offset-key');
  10739. if (offsetKey) {
  10740. return offsetKey;
  10741. }
  10742. for (var ii = 0; ii < node.childNodes.length; ii++) {
  10743. var childOffsetKey = getSelectionOffsetKeyForNode(node.childNodes[ii]);
  10744. if (childOffsetKey) {
  10745. return childOffsetKey;
  10746. }
  10747. }
  10748. }
  10749. return null;
  10750. }
  10751. var getSelectionOffsetKeyForNode_1 = getSelectionOffsetKeyForNode;
  10752. /**
  10753. * Get the key from the node's nearest offset-aware ancestor.
  10754. */
  10755. function findAncestorOffsetKey(node) {
  10756. var searchNode = node;
  10757. while (searchNode && searchNode !== document.documentElement) {
  10758. var key = getSelectionOffsetKeyForNode_1(searchNode);
  10759. if (key != null) {
  10760. return key;
  10761. }
  10762. searchNode = searchNode.parentNode;
  10763. }
  10764. return null;
  10765. }
  10766. var findAncestorOffsetKey_1 = findAncestorOffsetKey;
  10767. var TEXT_CLIPPING_REGEX = /\.textClipping$/;
  10768. var TEXT_TYPES = {
  10769. 'text/plain': true,
  10770. 'text/html': true,
  10771. 'text/rtf': true
  10772. };
  10773. // Somewhat arbitrary upper bound on text size. Let's not lock up the browser.
  10774. var TEXT_SIZE_UPPER_BOUND = 5000;
  10775. /**
  10776. * Extract the text content from a file list.
  10777. */
  10778. function getTextContentFromFiles(files, callback) {
  10779. var readCount = 0;
  10780. var results = [];
  10781. files.forEach(function ( /*blob*/file) {
  10782. readFile(file, function ( /*string*/text) {
  10783. readCount++;
  10784. text && results.push(text.slice(0, TEXT_SIZE_UPPER_BOUND));
  10785. if (readCount == files.length) {
  10786. callback(results.join('\r'));
  10787. }
  10788. });
  10789. });
  10790. }
  10791. /**
  10792. * todo isaac: Do work to turn html/rtf into a content fragment.
  10793. */
  10794. function readFile(file, callback) {
  10795. if (!commonjsGlobal.FileReader || file.type && !(file.type in TEXT_TYPES)) {
  10796. callback('');
  10797. return;
  10798. }
  10799. if (file.type === '') {
  10800. var contents = '';
  10801. // Special-case text clippings, which have an empty type but include
  10802. // `.textClipping` in the file name. `readAsText` results in an empty
  10803. // string for text clippings, so we force the file name to serve
  10804. // as the text value for the file.
  10805. if (TEXT_CLIPPING_REGEX.test(file.name)) {
  10806. contents = file.name.replace(TEXT_CLIPPING_REGEX, '');
  10807. }
  10808. callback(contents);
  10809. return;
  10810. }
  10811. var reader = new FileReader();
  10812. reader.onload = function () {
  10813. var result = reader.result;
  10814. !(typeof result === 'string') ? process.env.NODE_ENV !== 'production' ? invariant_1(false, 'We should be calling "FileReader.readAsText" which returns a string') : invariant_1(false) : void 0;
  10815. callback(result);
  10816. };
  10817. reader.onerror = function () {
  10818. callback('');
  10819. };
  10820. reader.readAsText(file);
  10821. }
  10822. var getTextContentFromFiles_1 = getTextContentFromFiles;
  10823. function getUpdatedSelectionState(editorState, anchorKey, anchorOffset, focusKey, focusOffset) {
  10824. var selection = nullthrows_1(editorState.getSelection());
  10825. if (process.env.NODE_ENV !== 'production') {
  10826. if (!anchorKey || !focusKey) {
  10827. /*eslint-disable no-console */
  10828. console.warn('Invalid selection state.', arguments, editorState.toJS());
  10829. /*eslint-enable no-console */
  10830. return selection;
  10831. }
  10832. }
  10833. var anchorPath = DraftOffsetKey_1.decode(anchorKey);
  10834. var anchorBlockKey = anchorPath.blockKey;
  10835. var anchorLeaf = editorState.getBlockTree(anchorBlockKey).getIn([anchorPath.decoratorKey, 'leaves', anchorPath.leafKey]);
  10836. var focusPath = DraftOffsetKey_1.decode(focusKey);
  10837. var focusBlockKey = focusPath.blockKey;
  10838. var focusLeaf = editorState.getBlockTree(focusBlockKey).getIn([focusPath.decoratorKey, 'leaves', focusPath.leafKey]);
  10839. var anchorLeafStart = anchorLeaf.get('start');
  10840. var focusLeafStart = focusLeaf.get('start');
  10841. var anchorBlockOffset = anchorLeaf ? anchorLeafStart + anchorOffset : null;
  10842. var focusBlockOffset = focusLeaf ? focusLeafStart + focusOffset : null;
  10843. var areEqual = selection.getAnchorKey() === anchorBlockKey && selection.getAnchorOffset() === anchorBlockOffset && selection.getFocusKey() === focusBlockKey && selection.getFocusOffset() === focusBlockOffset;
  10844. if (areEqual) {
  10845. return selection;
  10846. }
  10847. var isBackward = false;
  10848. if (anchorBlockKey === focusBlockKey) {
  10849. var anchorLeafEnd = anchorLeaf.get('end');
  10850. var focusLeafEnd = focusLeaf.get('end');
  10851. if (focusLeafStart === anchorLeafStart && focusLeafEnd === anchorLeafEnd) {
  10852. isBackward = focusOffset < anchorOffset;
  10853. } else {
  10854. isBackward = focusLeafStart < anchorLeafStart;
  10855. }
  10856. } else {
  10857. var startKey = editorState.getCurrentContent().getBlockMap().keySeq().skipUntil(function (v) {
  10858. return v === anchorBlockKey || v === focusBlockKey;
  10859. }).first();
  10860. isBackward = startKey === focusBlockKey;
  10861. }
  10862. return selection.merge({
  10863. anchorKey: anchorBlockKey,
  10864. anchorOffset: anchorBlockOffset,
  10865. focusKey: focusBlockKey,
  10866. focusOffset: focusBlockOffset,
  10867. isBackward: isBackward
  10868. });
  10869. }
  10870. var getUpdatedSelectionState_1 = getUpdatedSelectionState;
  10871. /**
  10872. * Get a SelectionState for the supplied mouse event.
  10873. */
  10874. function getSelectionForEvent(event, editorState) {
  10875. var node = null;
  10876. var offset = null;
  10877. if (typeof document.caretRangeFromPoint === 'function') {
  10878. var dropRange = document.caretRangeFromPoint(event.x, event.y);
  10879. node = dropRange.startContainer;
  10880. offset = dropRange.startOffset;
  10881. } else if (event.rangeParent) {
  10882. node = event.rangeParent;
  10883. offset = event.rangeOffset;
  10884. } else {
  10885. return null;
  10886. }
  10887. node = nullthrows_1(node);
  10888. offset = nullthrows_1(offset);
  10889. var offsetKey = nullthrows_1(findAncestorOffsetKey_1(node));
  10890. return getUpdatedSelectionState_1(editorState, offsetKey, offset, offsetKey, offset);
  10891. }
  10892. var DraftEditorDragHandler = {
  10893. /**
  10894. * Drag originating from input terminated.
  10895. */
  10896. onDragEnd: function onDragEnd(editor) {
  10897. editor.exitCurrentMode();
  10898. },
  10899. /**
  10900. * Handle data being dropped.
  10901. */
  10902. onDrop: function onDrop(editor, e) {
  10903. var data = new DataTransfer_1(e.nativeEvent.dataTransfer);
  10904. var editorState = editor._latestEditorState;
  10905. var dropSelection = getSelectionForEvent(e.nativeEvent, editorState);
  10906. e.preventDefault();
  10907. editor.exitCurrentMode();
  10908. if (dropSelection == null) {
  10909. return;
  10910. }
  10911. var files = data.getFiles();
  10912. if (files.length > 0) {
  10913. if (editor.props.handleDroppedFiles && isEventHandled_1(editor.props.handleDroppedFiles(dropSelection, files))) {
  10914. return;
  10915. }
  10916. getTextContentFromFiles_1(files, function (fileText) {
  10917. fileText && editor.update(insertTextAtSelection(editorState, dropSelection, fileText));
  10918. });
  10919. return;
  10920. }
  10921. var dragType = editor._internalDrag ? 'internal' : 'external';
  10922. if (editor.props.handleDrop && isEventHandled_1(editor.props.handleDrop(dropSelection, data, dragType))) {
  10923. return;
  10924. }
  10925. if (editor._internalDrag) {
  10926. editor.update(moveText(editorState, dropSelection));
  10927. return;
  10928. }
  10929. editor.update(insertTextAtSelection(editorState, dropSelection, data.getText()));
  10930. }
  10931. };
  10932. function moveText(editorState, targetSelection) {
  10933. var newContentState = DraftModifier_1.moveText(editorState.getCurrentContent(), editorState.getSelection(), targetSelection);
  10934. return EditorState_1.push(editorState, newContentState, 'insert-fragment');
  10935. }
  10936. /**
  10937. * Insert text at a specified selection.
  10938. */
  10939. function insertTextAtSelection(editorState, selection, text) {
  10940. var newContentState = DraftModifier_1.insertText(editorState.getCurrentContent(), selection, text, editorState.getCurrentInlineStyle());
  10941. return EditorState_1.push(editorState, newContentState, 'insert-fragment');
  10942. }
  10943. var DraftEditorDragHandler_1 = DraftEditorDragHandler;
  10944. (function (global, undefined$1) {
  10945. if (global.setImmediate) {
  10946. return;
  10947. }
  10948. var nextHandle = 1; // Spec says greater than zero
  10949. var tasksByHandle = {};
  10950. var currentlyRunningATask = false;
  10951. var doc = global.document;
  10952. var registerImmediate;
  10953. function setImmediate(callback) {
  10954. // Callback can either be a function or a string
  10955. if (typeof callback !== "function") {
  10956. callback = new Function("" + callback);
  10957. }
  10958. // Copy function arguments
  10959. var args = new Array(arguments.length - 1);
  10960. for (var i = 0; i < args.length; i++) {
  10961. args[i] = arguments[i + 1];
  10962. }
  10963. // Store and register the task
  10964. var task = { callback: callback, args: args };
  10965. tasksByHandle[nextHandle] = task;
  10966. registerImmediate(nextHandle);
  10967. return nextHandle++;
  10968. }
  10969. function clearImmediate(handle) {
  10970. delete tasksByHandle[handle];
  10971. }
  10972. function run(task) {
  10973. var callback = task.callback;
  10974. var args = task.args;
  10975. switch (args.length) {
  10976. case 0:
  10977. callback();
  10978. break;
  10979. case 1:
  10980. callback(args[0]);
  10981. break;
  10982. case 2:
  10983. callback(args[0], args[1]);
  10984. break;
  10985. case 3:
  10986. callback(args[0], args[1], args[2]);
  10987. break;
  10988. default:
  10989. callback.apply(undefined$1, args);
  10990. break;
  10991. }
  10992. }
  10993. function runIfPresent(handle) {
  10994. // From the spec: "Wait until any invocations of this algorithm started before this one have completed."
  10995. // So if we're currently running a task, we'll need to delay this invocation.
  10996. if (currentlyRunningATask) {
  10997. // Delay by doing a setTimeout. setImmediate was tried instead, but in Firefox 7 it generated a
  10998. // "too much recursion" error.
  10999. setTimeout(runIfPresent, 0, handle);
  11000. } else {
  11001. var task = tasksByHandle[handle];
  11002. if (task) {
  11003. currentlyRunningATask = true;
  11004. try {
  11005. run(task);
  11006. } finally {
  11007. clearImmediate(handle);
  11008. currentlyRunningATask = false;
  11009. }
  11010. }
  11011. }
  11012. }
  11013. function installNextTickImplementation() {
  11014. registerImmediate = function(handle) {
  11015. process.nextTick(function () { runIfPresent(handle); });
  11016. };
  11017. }
  11018. function canUsePostMessage() {
  11019. // The test against `importScripts` prevents this implementation from being installed inside a web worker,
  11020. // where `global.postMessage` means something completely different and can't be used for this purpose.
  11021. if (global.postMessage && !global.importScripts) {
  11022. var postMessageIsAsynchronous = true;
  11023. var oldOnMessage = global.onmessage;
  11024. global.onmessage = function() {
  11025. postMessageIsAsynchronous = false;
  11026. };
  11027. global.postMessage("", "*");
  11028. global.onmessage = oldOnMessage;
  11029. return postMessageIsAsynchronous;
  11030. }
  11031. }
  11032. function installPostMessageImplementation() {
  11033. // Installs an event handler on `global` for the `message` event: see
  11034. // * https://developer.mozilla.org/en/DOM/window.postMessage
  11035. // * http://www.whatwg.org/specs/web-apps/current-work/multipage/comms.html#crossDocumentMessages
  11036. var messagePrefix = "setImmediate$" + Math.random() + "$";
  11037. var onGlobalMessage = function(event) {
  11038. if (event.source === global &&
  11039. typeof event.data === "string" &&
  11040. event.data.indexOf(messagePrefix) === 0) {
  11041. runIfPresent(+event.data.slice(messagePrefix.length));
  11042. }
  11043. };
  11044. if (global.addEventListener) {
  11045. global.addEventListener("message", onGlobalMessage, false);
  11046. } else {
  11047. global.attachEvent("onmessage", onGlobalMessage);
  11048. }
  11049. registerImmediate = function(handle) {
  11050. global.postMessage(messagePrefix + handle, "*");
  11051. };
  11052. }
  11053. function installMessageChannelImplementation() {
  11054. var channel = new MessageChannel();
  11055. channel.port1.onmessage = function(event) {
  11056. var handle = event.data;
  11057. runIfPresent(handle);
  11058. };
  11059. registerImmediate = function(handle) {
  11060. channel.port2.postMessage(handle);
  11061. };
  11062. }
  11063. function installReadyStateChangeImplementation() {
  11064. var html = doc.documentElement;
  11065. registerImmediate = function(handle) {
  11066. // Create a <script> element; its readystatechange event will be fired asynchronously once it is inserted
  11067. // into the document. Do so, thus queuing up the task. Remember to clean up once it's been called.
  11068. var script = doc.createElement("script");
  11069. script.onreadystatechange = function () {
  11070. runIfPresent(handle);
  11071. script.onreadystatechange = null;
  11072. html.removeChild(script);
  11073. script = null;
  11074. };
  11075. html.appendChild(script);
  11076. };
  11077. }
  11078. function installSetTimeoutImplementation() {
  11079. registerImmediate = function(handle) {
  11080. setTimeout(runIfPresent, 0, handle);
  11081. };
  11082. }
  11083. // If supported, we should attach to the prototype of global, since that is where setTimeout et al. live.
  11084. var attachTo = Object.getPrototypeOf && Object.getPrototypeOf(global);
  11085. attachTo = attachTo && attachTo.setTimeout ? attachTo : global;
  11086. // Don't get fooled by e.g. browserify environments.
  11087. if ({}.toString.call(global.process) === "[object process]") {
  11088. // For Node.js before 0.9
  11089. installNextTickImplementation();
  11090. } else if (canUsePostMessage()) {
  11091. // For non-IE10 modern browsers
  11092. installPostMessageImplementation();
  11093. } else if (global.MessageChannel) {
  11094. // For web workers, where supported
  11095. installMessageChannelImplementation();
  11096. } else if (doc && "onreadystatechange" in doc.createElement("script")) {
  11097. // For IE 6–8
  11098. installReadyStateChangeImplementation();
  11099. } else {
  11100. // For older browsers
  11101. installSetTimeoutImplementation();
  11102. }
  11103. attachTo.setImmediate = setImmediate;
  11104. attachTo.clearImmediate = clearImmediate;
  11105. }(typeof self === "undefined" ? typeof commonjsGlobal === "undefined" ? commonjsGlobal : commonjsGlobal : self));
  11106. // setimmediate adds setImmediate to the global. We want to make sure we export
  11107. // the actual function.
  11108. var setImmediate = commonjsGlobal.setImmediate;
  11109. // When nothing is focused, Firefox regards two characters, `'` and `/`, as
  11110. // commands that should open and focus the "quickfind" search bar. This should
  11111. // *never* happen while a contenteditable is focused, but as of v28, it
  11112. // sometimes does, even when the keypress event target is the contenteditable.
  11113. // This breaks the input. Special case these characters to ensure that when
  11114. // they are typed, we prevent default on the event to make sure not to
  11115. // trigger quickfind.
  11116. var FF_QUICKFIND_CHAR = "'";
  11117. var FF_QUICKFIND_LINK_CHAR = '/';
  11118. var isFirefox = UserAgent_1.isBrowser('Firefox');
  11119. function mustPreventDefaultForCharacter(character) {
  11120. return isFirefox && (character == FF_QUICKFIND_CHAR || character == FF_QUICKFIND_LINK_CHAR);
  11121. }
  11122. /**
  11123. * Replace the current selection with the specified text string, with the
  11124. * inline style and entity key applied to the newly inserted text.
  11125. */
  11126. function replaceText(editorState, text, inlineStyle, entityKey) {
  11127. var contentState = DraftModifier_1.replaceText(editorState.getCurrentContent(), editorState.getSelection(), text, inlineStyle, entityKey);
  11128. return EditorState_1.push(editorState, contentState, 'insert-characters');
  11129. }
  11130. /**
  11131. * When `onBeforeInput` executes, the browser is attempting to insert a
  11132. * character into the editor. Apply this character data to the document,
  11133. * allowing native insertion if possible.
  11134. *
  11135. * Native insertion is encouraged in order to limit re-rendering and to
  11136. * preserve spellcheck highlighting, which disappears or flashes if re-render
  11137. * occurs on the relevant text nodes.
  11138. */
  11139. function editOnBeforeInput(editor, e) {
  11140. if (editor._pendingStateFromBeforeInput !== undefined) {
  11141. editor.update(editor._pendingStateFromBeforeInput);
  11142. editor._pendingStateFromBeforeInput = undefined;
  11143. }
  11144. var editorState = editor._latestEditorState;
  11145. var chars = e.data;
  11146. // In some cases (ex: IE ideographic space insertion) no character data
  11147. // is provided. There's nothing to do when this happens.
  11148. if (!chars) {
  11149. return;
  11150. }
  11151. // Allow the top-level component to handle the insertion manually. This is
  11152. // useful when triggering interesting behaviors for a character insertion,
  11153. // Simple examples: replacing a raw text ':)' with a smile emoji or image
  11154. // decorator, or setting a block to be a list item after typing '- ' at the
  11155. // start of the block.
  11156. if (editor.props.handleBeforeInput && isEventHandled_1(editor.props.handleBeforeInput(chars, editorState))) {
  11157. e.preventDefault();
  11158. return;
  11159. }
  11160. // If selection is collapsed, conditionally allow native behavior. This
  11161. // reduces re-renders and preserves spellcheck highlighting. If the selection
  11162. // is not collapsed, we will re-render.
  11163. var selection = editorState.getSelection();
  11164. var selectionStart = selection.getStartOffset();
  11165. var selectionEnd = selection.getEndOffset();
  11166. var anchorKey = selection.getAnchorKey();
  11167. if (!selection.isCollapsed()) {
  11168. e.preventDefault();
  11169. // If the currently selected text matches what the user is trying to
  11170. // replace it with, let's just update the `SelectionState`. If not, update
  11171. // the `ContentState` with the new text.
  11172. var currentlySelectedChars = editorState.getCurrentContent().getPlainText().slice(selectionStart, selectionEnd);
  11173. if (chars === currentlySelectedChars) {
  11174. editor.update(EditorState_1.forceSelection(editorState, selection.merge({
  11175. focusOffset: selectionEnd
  11176. })));
  11177. } else {
  11178. editor.update(replaceText(editorState, chars, editorState.getCurrentInlineStyle(), getEntityKeyForSelection_1(editorState.getCurrentContent(), editorState.getSelection())));
  11179. }
  11180. return;
  11181. }
  11182. var newEditorState = replaceText(editorState, chars, editorState.getCurrentInlineStyle(), getEntityKeyForSelection_1(editorState.getCurrentContent(), editorState.getSelection()));
  11183. // Bunch of different cases follow where we need to prevent native insertion.
  11184. var mustPreventNative = false;
  11185. if (!mustPreventNative) {
  11186. // Browsers tend to insert text in weird places in the DOM when typing at
  11187. // the start of a leaf, so we'll handle it ourselves.
  11188. mustPreventNative = isSelectionAtLeafStart_1(editor._latestCommittedEditorState);
  11189. }
  11190. if (!mustPreventNative) {
  11191. // Chrome will also split up a node into two pieces if it contains a Tab
  11192. // char, for no explicable reason. Seemingly caused by this commit:
  11193. // https://chromium.googlesource.com/chromium/src/+/013ac5eaf3%5E%21/
  11194. var nativeSelection = commonjsGlobal.getSelection();
  11195. // Selection is necessarily collapsed at this point due to earlier check.
  11196. if (nativeSelection.anchorNode && nativeSelection.anchorNode.nodeType === Node.TEXT_NODE) {
  11197. // See isTabHTMLSpanElement in chromium EditingUtilities.cpp.
  11198. var parentNode = nativeSelection.anchorNode.parentNode;
  11199. mustPreventNative = parentNode.nodeName === 'SPAN' && parentNode.firstChild.nodeType === Node.TEXT_NODE && parentNode.firstChild.nodeValue.indexOf('\t') !== -1;
  11200. }
  11201. }
  11202. if (!mustPreventNative) {
  11203. // Check the old and new "fingerprints" of the current block to determine
  11204. // whether this insertion requires any addition or removal of text nodes,
  11205. // in which case we would prevent the native character insertion.
  11206. var originalFingerprint = BlockTree_1.getFingerprint(editorState.getBlockTree(anchorKey));
  11207. var newFingerprint = BlockTree_1.getFingerprint(newEditorState.getBlockTree(anchorKey));
  11208. mustPreventNative = originalFingerprint !== newFingerprint;
  11209. }
  11210. if (!mustPreventNative) {
  11211. mustPreventNative = mustPreventDefaultForCharacter(chars);
  11212. }
  11213. if (!mustPreventNative) {
  11214. mustPreventNative = nullthrows_1(newEditorState.getDirectionMap()).get(anchorKey) !== nullthrows_1(editorState.getDirectionMap()).get(anchorKey);
  11215. }
  11216. if (mustPreventNative) {
  11217. e.preventDefault();
  11218. editor.update(newEditorState);
  11219. return;
  11220. }
  11221. // We made it all the way! Let the browser do its thing and insert the char.
  11222. newEditorState = EditorState_1.set(newEditorState, {
  11223. nativelyRenderedContent: newEditorState.getCurrentContent()
  11224. });
  11225. // The native event is allowed to occur. To allow user onChange handlers to
  11226. // change the inserted text, we wait until the text is actually inserted
  11227. // before we actually update our state. That way when we rerender, the text
  11228. // we see in the DOM will already have been inserted properly.
  11229. editor._pendingStateFromBeforeInput = newEditorState;
  11230. setImmediate(function () {
  11231. if (editor._pendingStateFromBeforeInput !== undefined) {
  11232. editor.update(editor._pendingStateFromBeforeInput);
  11233. editor._pendingStateFromBeforeInput = undefined;
  11234. }
  11235. });
  11236. }
  11237. var editOnBeforeInput_1 = editOnBeforeInput;
  11238. function editOnBlur(editor, e) {
  11239. // In a contentEditable element, when you select a range and then click
  11240. // another active element, this does trigger a `blur` event but will not
  11241. // remove the DOM selection from the contenteditable.
  11242. // This is consistent across all browsers, but we prefer that the editor
  11243. // behave like a textarea, where a `blur` event clears the DOM selection.
  11244. // We therefore force the issue to be certain, checking whether the active
  11245. // element is `body` to force it when blurring occurs within the window (as
  11246. // opposed to clicking to another tab or window).
  11247. if (getActiveElement_1() === document.body) {
  11248. var _selection = commonjsGlobal.getSelection();
  11249. var editorNode = editor.editor;
  11250. if (_selection.rangeCount === 1 && containsNode_1(editorNode, _selection.anchorNode) && containsNode_1(editorNode, _selection.focusNode)) {
  11251. _selection.removeAllRanges();
  11252. }
  11253. }
  11254. var editorState = editor._latestEditorState;
  11255. var currentSelection = editorState.getSelection();
  11256. if (!currentSelection.getHasFocus()) {
  11257. return;
  11258. }
  11259. var selection = currentSelection.set('hasFocus', false);
  11260. editor.props.onBlur && editor.props.onBlur(e);
  11261. editor.update(EditorState_1.acceptSelection(editorState, selection));
  11262. }
  11263. var editOnBlur_1 = editOnBlur;
  11264. /**
  11265. * The user has begun using an IME input system. Switching to `composite` mode
  11266. * allows handling composition input and disables other edit behavior.
  11267. */
  11268. function editOnCompositionStart(editor, e) {
  11269. editor.setMode('composite');
  11270. editor.update(EditorState_1.set(editor._latestEditorState, { inCompositionMode: true }));
  11271. // Allow composition handler to interpret the compositionstart event
  11272. editor._onCompositionStart(e);
  11273. }
  11274. var editOnCompositionStart_1 = editOnCompositionStart;
  11275. function getFragmentFromSelection(editorState) {
  11276. var selectionState = editorState.getSelection();
  11277. if (selectionState.isCollapsed()) {
  11278. return null;
  11279. }
  11280. return getContentStateFragment_1(editorState.getCurrentContent(), selectionState);
  11281. }
  11282. var getFragmentFromSelection_1 = getFragmentFromSelection;
  11283. /**
  11284. * If we have a selection, create a ContentState fragment and store
  11285. * it in our internal clipboard. Subsequent paste events will use this
  11286. * fragment if no external clipboard data is supplied.
  11287. */
  11288. function editOnCopy(editor, e) {
  11289. var editorState = editor._latestEditorState;
  11290. var selection = editorState.getSelection();
  11291. // No selection, so there's nothing to copy.
  11292. if (selection.isCollapsed()) {
  11293. e.preventDefault();
  11294. return;
  11295. }
  11296. editor.setClipboard(getFragmentFromSelection_1(editor._latestEditorState));
  11297. }
  11298. var editOnCopy_1 = editOnCopy;
  11299. /**
  11300. * On `cut` events, native behavior is allowed to occur so that the system
  11301. * clipboard is set properly. This means that we need to take steps to recover
  11302. * the editor DOM state after the `cut` has occurred in order to maintain
  11303. * control of the component.
  11304. *
  11305. * In addition, we can keep a copy of the removed fragment, including all
  11306. * styles and entities, for use as an internal paste.
  11307. */
  11308. function editOnCut(editor, e) {
  11309. var editorState = editor._latestEditorState;
  11310. var selection = editorState.getSelection();
  11311. var element = e.target;
  11312. var scrollPosition = void 0;
  11313. // No selection, so there's nothing to cut.
  11314. if (selection.isCollapsed()) {
  11315. e.preventDefault();
  11316. return;
  11317. }
  11318. // Track the current scroll position so that it can be forced back in place
  11319. // after the editor regains control of the DOM.
  11320. if (element instanceof Node) {
  11321. scrollPosition = getScrollPosition_1(Style_1.getScrollParent(element));
  11322. }
  11323. var fragment = getFragmentFromSelection_1(editorState);
  11324. editor.setClipboard(fragment);
  11325. // Set `cut` mode to disable all event handling temporarily.
  11326. editor.setMode('cut');
  11327. // Let native `cut` behavior occur, then recover control.
  11328. setTimeout(function () {
  11329. editor.restoreEditorDOM(scrollPosition);
  11330. editor.exitCurrentMode();
  11331. editor.update(removeFragment(editorState));
  11332. }, 0);
  11333. }
  11334. function removeFragment(editorState) {
  11335. var newContent = DraftModifier_1.removeRange(editorState.getCurrentContent(), editorState.getSelection(), 'forward');
  11336. return EditorState_1.push(editorState, newContent, 'remove-range');
  11337. }
  11338. var editOnCut_1 = editOnCut;
  11339. /**
  11340. * Copyright (c) 2013-present, Facebook, Inc.
  11341. * All rights reserved.
  11342. *
  11343. * This source code is licensed under the BSD-style license found in the
  11344. * LICENSE file in the root directory of this source tree. An additional grant
  11345. * of patent rights can be found in the PATENTS file in the same directory.
  11346. *
  11347. * @providesModule editOnDragOver
  11348. * @format
  11349. *
  11350. */
  11351. /**
  11352. * Drag behavior has begun from outside the editor element.
  11353. */
  11354. function editOnDragOver(editor, e) {
  11355. editor._internalDrag = false;
  11356. editor.setMode('drag');
  11357. e.preventDefault();
  11358. }
  11359. var editOnDragOver_1 = editOnDragOver;
  11360. /**
  11361. * Copyright (c) 2013-present, Facebook, Inc.
  11362. * All rights reserved.
  11363. *
  11364. * This source code is licensed under the BSD-style license found in the
  11365. * LICENSE file in the root directory of this source tree. An additional grant
  11366. * of patent rights can be found in the PATENTS file in the same directory.
  11367. *
  11368. * @providesModule editOnDragStart
  11369. * @format
  11370. *
  11371. */
  11372. /**
  11373. * A `dragstart` event has begun within the text editor component.
  11374. */
  11375. function editOnDragStart(editor) {
  11376. editor._internalDrag = true;
  11377. editor.setMode('drag');
  11378. }
  11379. var editOnDragStart_1 = editOnDragStart;
  11380. function editOnFocus(editor, e) {
  11381. var editorState = editor._latestEditorState;
  11382. var currentSelection = editorState.getSelection();
  11383. if (currentSelection.getHasFocus()) {
  11384. return;
  11385. }
  11386. var selection = currentSelection.set('hasFocus', true);
  11387. editor.props.onFocus && editor.props.onFocus(e);
  11388. // When the tab containing this text editor is hidden and the user does a
  11389. // find-in-page in a _different_ tab, Chrome on Mac likes to forget what the
  11390. // selection was right after sending this focus event and (if you let it)
  11391. // moves the cursor back to the beginning of the editor, so we force the
  11392. // selection here instead of simply accepting it in order to preserve the
  11393. // old cursor position. See https://crbug.com/540004.
  11394. // But it looks like this is fixed in Chrome 60.0.3081.0.
  11395. // Other browsers also don't have this bug, so we prefer to acceptSelection
  11396. // when possible, to ensure that unfocusing and refocusing a Draft editor
  11397. // doesn't preserve the selection, matching how textareas work.
  11398. if (UserAgent_1.isBrowser('Chrome < 60.0.3081.0')) {
  11399. editor.update(EditorState_1.forceSelection(editorState, selection));
  11400. } else {
  11401. editor.update(EditorState_1.acceptSelection(editorState, selection));
  11402. }
  11403. }
  11404. var editOnFocus_1 = editOnFocus;
  11405. var isGecko = UserAgent_1.isEngine('Gecko');
  11406. var DOUBLE_NEWLINE = '\n\n';
  11407. /**
  11408. * This function is intended to handle spellcheck and autocorrect changes,
  11409. * which occur in the DOM natively without any opportunity to observe or
  11410. * interpret the changes before they occur.
  11411. *
  11412. * The `input` event fires in contentEditable elements reliably for non-IE
  11413. * browsers, immediately after changes occur to the editor DOM. Since our other
  11414. * handlers override or otherwise handle cover other varieties of text input,
  11415. * the DOM state should match the model in all controlled input cases. Thus,
  11416. * when an `input` change leads to a DOM/model mismatch, the change should be
  11417. * due to a spellcheck change, and we can incorporate it into our model.
  11418. */
  11419. function editOnInput(editor) {
  11420. if (editor._pendingStateFromBeforeInput !== undefined) {
  11421. editor.update(editor._pendingStateFromBeforeInput);
  11422. editor._pendingStateFromBeforeInput = undefined;
  11423. }
  11424. var domSelection = commonjsGlobal.getSelection();
  11425. var anchorNode = domSelection.anchorNode,
  11426. isCollapsed = domSelection.isCollapsed;
  11427. var isNotTextNode = anchorNode.nodeType !== Node.TEXT_NODE;
  11428. var isNotTextOrElementNode = anchorNode.nodeType !== Node.TEXT_NODE && anchorNode.nodeType !== Node.ELEMENT_NODE;
  11429. {
  11430. if (isNotTextOrElementNode) {
  11431. // TODO: (t16149272) figure out context for this change
  11432. return;
  11433. }
  11434. }
  11435. if (anchorNode.nodeType === Node.TEXT_NODE && (anchorNode.previousSibling !== null || anchorNode.nextSibling !== null)) {
  11436. // When typing at the beginning of a visual line, Chrome splits the text
  11437. // nodes into two. Why? No one knows. This commit is suspicious:
  11438. // https://chromium.googlesource.com/chromium/src/+/a3b600981286b135632371477f902214c55a1724
  11439. // To work around, we'll merge the sibling text nodes back into this one.
  11440. var span = anchorNode.parentNode;
  11441. anchorNode.nodeValue = span.textContent;
  11442. for (var child = span.firstChild; child !== null; child = child.nextSibling) {
  11443. if (child !== anchorNode) {
  11444. span.removeChild(child);
  11445. }
  11446. }
  11447. }
  11448. var domText = anchorNode.textContent;
  11449. var editorState = editor._latestEditorState;
  11450. var offsetKey = nullthrows_1(findAncestorOffsetKey_1(anchorNode));
  11451. var _DraftOffsetKey$decod = DraftOffsetKey_1.decode(offsetKey),
  11452. blockKey = _DraftOffsetKey$decod.blockKey,
  11453. decoratorKey = _DraftOffsetKey$decod.decoratorKey,
  11454. leafKey = _DraftOffsetKey$decod.leafKey;
  11455. var _editorState$getBlock = editorState.getBlockTree(blockKey).getIn([decoratorKey, 'leaves', leafKey]),
  11456. start = _editorState$getBlock.start,
  11457. end = _editorState$getBlock.end;
  11458. var content = editorState.getCurrentContent();
  11459. var block = content.getBlockForKey(blockKey);
  11460. var modelText = block.getText().slice(start, end);
  11461. // Special-case soft newlines here. If the DOM text ends in a soft newline,
  11462. // we will have manually inserted an extra soft newline in DraftEditorLeaf.
  11463. // We want to remove this extra newline for the purpose of our comparison
  11464. // of DOM and model text.
  11465. if (domText.endsWith(DOUBLE_NEWLINE)) {
  11466. domText = domText.slice(0, -1);
  11467. }
  11468. // No change -- the DOM is up to date. Nothing to do here.
  11469. if (domText === modelText) {
  11470. // This can be buggy for some Android keyboards because they don't fire
  11471. // standard onkeydown/pressed events and only fired editOnInput
  11472. // so domText is already changed by the browser and ends up being equal
  11473. // to modelText unexpectedly
  11474. return;
  11475. }
  11476. var selection = editorState.getSelection();
  11477. // We'll replace the entire leaf with the text content of the target.
  11478. var targetRange = selection.merge({
  11479. anchorOffset: start,
  11480. focusOffset: end,
  11481. isBackward: false
  11482. });
  11483. var entityKey = block.getEntityAt(start);
  11484. var entity = entityKey && content.getEntity(entityKey);
  11485. var entityType = entity && entity.getMutability();
  11486. var preserveEntity = entityType === 'MUTABLE';
  11487. // Immutable or segmented entities cannot properly be handled by the
  11488. // default browser undo, so we have to use a different change type to
  11489. // force using our internal undo method instead of falling through to the
  11490. // native browser undo.
  11491. var changeType = preserveEntity ? 'spellcheck-change' : 'apply-entity';
  11492. var newContent = DraftModifier_1.replaceText(content, targetRange, domText, block.getInlineStyleAt(start), preserveEntity ? block.getEntityAt(start) : null);
  11493. var anchorOffset, focusOffset, startOffset, endOffset;
  11494. if (isGecko) {
  11495. // Firefox selection does not change while the context menu is open, so
  11496. // we preserve the anchor and focus values of the DOM selection.
  11497. anchorOffset = domSelection.anchorOffset;
  11498. focusOffset = domSelection.focusOffset;
  11499. startOffset = start + Math.min(anchorOffset, focusOffset);
  11500. endOffset = startOffset + Math.abs(anchorOffset - focusOffset);
  11501. anchorOffset = startOffset;
  11502. focusOffset = endOffset;
  11503. } else {
  11504. // Browsers other than Firefox may adjust DOM selection while the context
  11505. // menu is open, and Safari autocorrect is prone to providing an inaccurate
  11506. // DOM selection. Don't trust it. Instead, use our existing SelectionState
  11507. // and adjust it based on the number of characters changed during the
  11508. // mutation.
  11509. var charDelta = domText.length - modelText.length;
  11510. startOffset = selection.getStartOffset();
  11511. endOffset = selection.getEndOffset();
  11512. anchorOffset = isCollapsed ? endOffset + charDelta : startOffset;
  11513. focusOffset = endOffset + charDelta;
  11514. }
  11515. // Segmented entities are completely or partially removed when their
  11516. // text content changes. For this case we do not want any text to be selected
  11517. // after the change, so we are not merging the selection.
  11518. var contentWithAdjustedDOMSelection = newContent.merge({
  11519. selectionBefore: content.getSelectionAfter(),
  11520. selectionAfter: selection.merge({ anchorOffset: anchorOffset, focusOffset: focusOffset })
  11521. });
  11522. editor.update(EditorState_1.push(editorState, contentWithAdjustedDOMSelection, changeType));
  11523. }
  11524. var editOnInput_1 = editOnInput;
  11525. var isOSX = UserAgent_1.isPlatform('Mac OS X');
  11526. var KeyBindingUtil = {
  11527. /**
  11528. * Check whether the ctrlKey modifier is *not* being used in conjunction with
  11529. * the altKey modifier. If they are combined, the result is an `altGraph`
  11530. * key modifier, which should not be handled by this set of key bindings.
  11531. */
  11532. isCtrlKeyCommand: function isCtrlKeyCommand(e) {
  11533. return !!e.ctrlKey && !e.altKey;
  11534. },
  11535. isOptionKeyCommand: function isOptionKeyCommand(e) {
  11536. return isOSX && e.altKey;
  11537. },
  11538. hasCommandModifier: function hasCommandModifier(e) {
  11539. return isOSX ? !!e.metaKey && !e.altKey : KeyBindingUtil.isCtrlKeyCommand(e);
  11540. }
  11541. };
  11542. var KeyBindingUtil_1 = KeyBindingUtil;
  11543. var clipboard = null;
  11544. /**
  11545. * Some systems offer a "secondary" clipboard to allow quick internal cut
  11546. * and paste behavior. For instance, Ctrl+K (cut) and Ctrl+Y (paste).
  11547. */
  11548. var SecondaryClipboard = {
  11549. cut: function cut(editorState) {
  11550. var content = editorState.getCurrentContent();
  11551. var selection = editorState.getSelection();
  11552. var targetRange = null;
  11553. if (selection.isCollapsed()) {
  11554. var anchorKey = selection.getAnchorKey();
  11555. var blockEnd = content.getBlockForKey(anchorKey).getLength();
  11556. if (blockEnd === selection.getAnchorOffset()) {
  11557. return editorState;
  11558. }
  11559. targetRange = selection.set('focusOffset', blockEnd);
  11560. } else {
  11561. targetRange = selection;
  11562. }
  11563. targetRange = nullthrows_1(targetRange);
  11564. clipboard = getContentStateFragment_1(content, targetRange);
  11565. var afterRemoval = DraftModifier_1.removeRange(content, targetRange, 'forward');
  11566. if (afterRemoval === content) {
  11567. return editorState;
  11568. }
  11569. return EditorState_1.push(editorState, afterRemoval, 'remove-range');
  11570. },
  11571. paste: function paste(editorState) {
  11572. if (!clipboard) {
  11573. return editorState;
  11574. }
  11575. var newContent = DraftModifier_1.replaceWithFragment(editorState.getCurrentContent(), editorState.getSelection(), clipboard);
  11576. return EditorState_1.push(editorState, newContent, 'insert-fragment');
  11577. }
  11578. };
  11579. var SecondaryClipboard_1 = SecondaryClipboard;
  11580. // These two ranges are consecutive so anything in [HIGH_START, LOW_END] is a
  11581. // surrogate code unit.
  11582. var SURROGATE_HIGH_START = 0xD800;
  11583. var SURROGATE_HIGH_END = 0xDBFF;
  11584. var SURROGATE_LOW_START = 0xDC00;
  11585. var SURROGATE_LOW_END = 0xDFFF;
  11586. var SURROGATE_UNITS_REGEX = /[\uD800-\uDFFF]/;
  11587. /**
  11588. * @param {number} codeUnit A Unicode code-unit, in range [0, 0x10FFFF]
  11589. * @return {boolean} Whether code-unit is in a surrogate (hi/low) range
  11590. */
  11591. function isCodeUnitInSurrogateRange(codeUnit) {
  11592. return SURROGATE_HIGH_START <= codeUnit && codeUnit <= SURROGATE_LOW_END;
  11593. }
  11594. /**
  11595. * Returns whether the two characters starting at `index` form a surrogate pair.
  11596. * For example, given the string s = "\uD83D\uDE0A", (s, 0) returns true and
  11597. * (s, 1) returns false.
  11598. *
  11599. * @param {string} str
  11600. * @param {number} index
  11601. * @return {boolean}
  11602. */
  11603. function isSurrogatePair(str, index) {
  11604. !(0 <= index && index < str.length) ? process.env.NODE_ENV !== 'production' ? invariant_1(false, 'isSurrogatePair: Invalid index %s for string length %s.', index, str.length) : invariant_1(false) : void 0;
  11605. if (index + 1 === str.length) {
  11606. return false;
  11607. }
  11608. var first = str.charCodeAt(index);
  11609. var second = str.charCodeAt(index + 1);
  11610. return SURROGATE_HIGH_START <= first && first <= SURROGATE_HIGH_END && SURROGATE_LOW_START <= second && second <= SURROGATE_LOW_END;
  11611. }
  11612. /**
  11613. * @param {string} str Non-empty string
  11614. * @return {boolean} True if the input includes any surrogate code units
  11615. */
  11616. function hasSurrogateUnit(str) {
  11617. return SURROGATE_UNITS_REGEX.test(str);
  11618. }
  11619. /**
  11620. * Return the length of the original Unicode character at given position in the
  11621. * String by looking into the UTF-16 code unit; that is equal to 1 for any
  11622. * non-surrogate characters in BMP ([U+0000..U+D7FF] and [U+E000, U+FFFF]); and
  11623. * returns 2 for the hi/low surrogates ([U+D800..U+DFFF]), which are in fact
  11624. * representing non-BMP characters ([U+10000..U+10FFFF]).
  11625. *
  11626. * Examples:
  11627. * - '\u0020' => 1
  11628. * - '\u3020' => 1
  11629. * - '\uD835' => 2
  11630. * - '\uD835\uDDEF' => 2
  11631. * - '\uDDEF' => 2
  11632. *
  11633. * @param {string} str Non-empty string
  11634. * @param {number} pos Position in the string to look for one code unit
  11635. * @return {number} Number 1 or 2
  11636. */
  11637. function getUTF16Length(str, pos) {
  11638. return 1 + isCodeUnitInSurrogateRange(str.charCodeAt(pos));
  11639. }
  11640. /**
  11641. * Fully Unicode-enabled replacement for String#length
  11642. *
  11643. * @param {string} str Valid Unicode string
  11644. * @return {number} The number of Unicode characters in the string
  11645. */
  11646. function strlen(str) {
  11647. // Call the native functions if there's no surrogate char
  11648. if (!hasSurrogateUnit(str)) {
  11649. return str.length;
  11650. }
  11651. var len = 0;
  11652. for (var pos = 0; pos < str.length; pos += getUTF16Length(str, pos)) {
  11653. len++;
  11654. }
  11655. return len;
  11656. }
  11657. /**
  11658. * Fully Unicode-enabled replacement for String#substr()
  11659. *
  11660. * @param {string} str Valid Unicode string
  11661. * @param {number} start Location in Unicode sequence to begin extracting
  11662. * @param {?number} length The number of Unicode characters to extract
  11663. * (default: to the end of the string)
  11664. * @return {string} Extracted sub-string
  11665. */
  11666. function substr(str, start, length) {
  11667. start = start || 0;
  11668. length = length === undefined ? Infinity : length || 0;
  11669. // Call the native functions if there's no surrogate char
  11670. if (!hasSurrogateUnit(str)) {
  11671. return str.substr(start, length);
  11672. }
  11673. // Obvious cases
  11674. var size = str.length;
  11675. if (size <= 0 || start > size || length <= 0) {
  11676. return '';
  11677. }
  11678. // Find the actual starting position
  11679. var posA = 0;
  11680. if (start > 0) {
  11681. for (; start > 0 && posA < size; start--) {
  11682. posA += getUTF16Length(str, posA);
  11683. }
  11684. if (posA >= size) {
  11685. return '';
  11686. }
  11687. } else if (start < 0) {
  11688. for (posA = size; start < 0 && 0 < posA; start++) {
  11689. posA -= getUTF16Length(str, posA - 1);
  11690. }
  11691. if (posA < 0) {
  11692. posA = 0;
  11693. }
  11694. }
  11695. // Find the actual ending position
  11696. var posB = size;
  11697. if (length < size) {
  11698. for (posB = posA; length > 0 && posB < size; length--) {
  11699. posB += getUTF16Length(str, posB);
  11700. }
  11701. }
  11702. return str.substring(posA, posB);
  11703. }
  11704. /**
  11705. * Fully Unicode-enabled replacement for String#substring()
  11706. *
  11707. * @param {string} str Valid Unicode string
  11708. * @param {number} start Location in Unicode sequence to begin extracting
  11709. * @param {?number} end Location in Unicode sequence to end extracting
  11710. * (default: end of the string)
  11711. * @return {string} Extracted sub-string
  11712. */
  11713. function substring(str, start, end) {
  11714. start = start || 0;
  11715. end = end === undefined ? Infinity : end || 0;
  11716. if (start < 0) {
  11717. start = 0;
  11718. }
  11719. if (end < 0) {
  11720. end = 0;
  11721. }
  11722. var length = Math.abs(end - start);
  11723. start = start < end ? start : end;
  11724. return substr(str, start, length);
  11725. }
  11726. /**
  11727. * Get a list of Unicode code-points from a String
  11728. *
  11729. * @param {string} str Valid Unicode string
  11730. * @return {array<number>} A list of code-points in [0..0x10FFFF]
  11731. */
  11732. function getCodePoints(str) {
  11733. var codePoints = [];
  11734. for (var pos = 0; pos < str.length; pos += getUTF16Length(str, pos)) {
  11735. codePoints.push(str.codePointAt(pos));
  11736. }
  11737. return codePoints;
  11738. }
  11739. var UnicodeUtils = {
  11740. getCodePoints: getCodePoints,
  11741. getUTF16Length: getUTF16Length,
  11742. hasSurrogateUnit: hasSurrogateUnit,
  11743. isCodeUnitInSurrogateRange: isCodeUnitInSurrogateRange,
  11744. isSurrogatePair: isSurrogatePair,
  11745. strlen: strlen,
  11746. substring: substring,
  11747. substr: substr
  11748. };
  11749. var UnicodeUtils_1 = UnicodeUtils;
  11750. var isChrome = UserAgent_1.isBrowser('Chrome');
  11751. // In Chrome, the client rects will include the entire bounds of all nodes that
  11752. // begin (have a start tag) within the selection, even if the selection does
  11753. // not overlap the entire node. To resolve this, we split the range at each
  11754. // start tag and join the client rects together.
  11755. // https://code.google.com/p/chromium/issues/detail?id=324437
  11756. /* eslint-disable consistent-return */
  11757. function getRangeClientRectsChrome(range) {
  11758. var tempRange = range.cloneRange();
  11759. var clientRects = [];
  11760. for (var ancestor = range.endContainer; ancestor != null; ancestor = ancestor.parentNode) {
  11761. // If we've climbed up to the common ancestor, we can now use the
  11762. // original start point and stop climbing the tree.
  11763. var atCommonAncestor = ancestor === range.commonAncestorContainer;
  11764. if (atCommonAncestor) {
  11765. tempRange.setStart(range.startContainer, range.startOffset);
  11766. } else {
  11767. tempRange.setStart(tempRange.endContainer, 0);
  11768. }
  11769. var rects = Array.from(tempRange.getClientRects());
  11770. clientRects.push(rects);
  11771. if (atCommonAncestor) {
  11772. var _ref;
  11773. clientRects.reverse();
  11774. return (_ref = []).concat.apply(_ref, clientRects);
  11775. }
  11776. tempRange.setEndBefore(ancestor);
  11777. }
  11778. process.env.NODE_ENV !== 'production' ? invariant_1(false, 'Found an unexpected detached subtree when getting range client rects.') : invariant_1(false) ;
  11779. }
  11780. /* eslint-enable consistent-return */
  11781. /**
  11782. * Like range.getClientRects() but normalizes for browser bugs.
  11783. */
  11784. var getRangeClientRects = isChrome ? getRangeClientRectsChrome : function (range) {
  11785. return Array.from(range.getClientRects());
  11786. };
  11787. var getRangeClientRects_1 = getRangeClientRects;
  11788. /**
  11789. * Copyright (c) 2013-present, Facebook, Inc.
  11790. * All rights reserved.
  11791. *
  11792. * This source code is licensed under the BSD-style license found in the
  11793. * LICENSE file in the root directory of this source tree. An additional grant
  11794. * of patent rights can be found in the PATENTS file in the same directory.
  11795. *
  11796. * @providesModule expandRangeToStartOfLine
  11797. * @format
  11798. *
  11799. */
  11800. /**
  11801. * Return the computed line height, in pixels, for the provided element.
  11802. */
  11803. function getLineHeightPx(element) {
  11804. var computed = getComputedStyle(element);
  11805. var div = document.createElement('div');
  11806. div.style.fontFamily = computed.fontFamily;
  11807. div.style.fontSize = computed.fontSize;
  11808. div.style.fontStyle = computed.fontStyle;
  11809. div.style.fontWeight = computed.fontWeight;
  11810. div.style.lineHeight = computed.lineHeight;
  11811. div.style.position = 'absolute';
  11812. div.textContent = 'M';
  11813. var documentBody = document.body;
  11814. !documentBody ? process.env.NODE_ENV !== 'production' ? invariant_1(false, 'Missing document.body') : invariant_1(false) : void 0;
  11815. // forced layout here
  11816. documentBody.appendChild(div);
  11817. var rect = div.getBoundingClientRect();
  11818. documentBody.removeChild(div);
  11819. return rect.height;
  11820. }
  11821. /**
  11822. * Return whether every ClientRect in the provided list lies on the same line.
  11823. *
  11824. * We assume that the rects on the same line all contain the baseline, so the
  11825. * lowest top line needs to be above the highest bottom line (i.e., if you were
  11826. * to project the rects onto the y-axis, their intersection would be nonempty).
  11827. *
  11828. * In addition, we require that no two boxes are lineHeight (or more) apart at
  11829. * either top or bottom, which helps protect against false positives for fonts
  11830. * with extremely large glyph heights (e.g., with a font size of 17px, Zapfino
  11831. * produces rects of height 58px!).
  11832. */
  11833. function areRectsOnOneLine(rects, lineHeight) {
  11834. var minTop = Infinity;
  11835. var minBottom = Infinity;
  11836. var maxTop = -Infinity;
  11837. var maxBottom = -Infinity;
  11838. for (var ii = 0; ii < rects.length; ii++) {
  11839. var rect = rects[ii];
  11840. if (rect.width === 0 || rect.width === 1) {
  11841. // When a range starts or ends a soft wrap, many browsers (Chrome, IE,
  11842. // Safari) include an empty rect on the previous or next line. When the
  11843. // text lies in a container whose position is not integral (e.g., from
  11844. // margin: auto), Safari makes these empty rects have width 1 (instead of
  11845. // 0). Having one-pixel-wide characters seems unlikely (and most browsers
  11846. // report widths in subpixel precision anyway) so it's relatively safe to
  11847. // skip over them.
  11848. continue;
  11849. }
  11850. minTop = Math.min(minTop, rect.top);
  11851. minBottom = Math.min(minBottom, rect.bottom);
  11852. maxTop = Math.max(maxTop, rect.top);
  11853. maxBottom = Math.max(maxBottom, rect.bottom);
  11854. }
  11855. return maxTop <= minBottom && maxTop - minTop < lineHeight && maxBottom - minBottom < lineHeight;
  11856. }
  11857. /**
  11858. * Return the length of a node, as used by Range offsets.
  11859. */
  11860. function getNodeLength$1(node) {
  11861. // http://www.w3.org/TR/dom/#concept-node-length
  11862. switch (node.nodeType) {
  11863. case Node.DOCUMENT_TYPE_NODE:
  11864. return 0;
  11865. case Node.TEXT_NODE:
  11866. case Node.PROCESSING_INSTRUCTION_NODE:
  11867. case Node.COMMENT_NODE:
  11868. return node.length;
  11869. default:
  11870. return node.childNodes.length;
  11871. }
  11872. }
  11873. /**
  11874. * Given a collapsed range, move the start position backwards as far as
  11875. * possible while the range still spans only a single line.
  11876. */
  11877. function expandRangeToStartOfLine(range) {
  11878. !range.collapsed ? process.env.NODE_ENV !== 'production' ? invariant_1(false, 'expandRangeToStartOfLine: Provided range is not collapsed.') : invariant_1(false) : void 0;
  11879. range = range.cloneRange();
  11880. var containingElement = range.startContainer;
  11881. if (containingElement.nodeType !== 1) {
  11882. containingElement = containingElement.parentNode;
  11883. }
  11884. var lineHeight = getLineHeightPx(containingElement);
  11885. // Imagine our text looks like:
  11886. // <div><span>once upon a time, there was a <em>boy
  11887. // who lived</em> </span><q><strong>under^ the
  11888. // stairs</strong> in a small closet.</q></div>
  11889. // where the caret represents the cursor. First, we crawl up the tree until
  11890. // the range spans multiple lines (setting the start point to before
  11891. // "<strong>", then before "<div>"), then at each level we do a search to
  11892. // find the latest point which is still on a previous line. We'll find that
  11893. // the break point is inside the span, then inside the <em>, then in its text
  11894. // node child, the actual break point before "who".
  11895. var bestContainer = range.endContainer;
  11896. var bestOffset = range.endOffset;
  11897. range.setStart(range.startContainer, 0);
  11898. while (areRectsOnOneLine(getRangeClientRects_1(range), lineHeight)) {
  11899. bestContainer = range.startContainer;
  11900. bestOffset = range.startOffset;
  11901. !bestContainer.parentNode ? process.env.NODE_ENV !== 'production' ? invariant_1(false, 'Found unexpected detached subtree when traversing.') : invariant_1(false) : void 0;
  11902. range.setStartBefore(bestContainer);
  11903. if (bestContainer.nodeType === 1 && getComputedStyle(bestContainer).display !== 'inline') {
  11904. // The start of the line is never in a different block-level container.
  11905. break;
  11906. }
  11907. }
  11908. // In the above example, range now spans from "<div>" to "under",
  11909. // bestContainer is <div>, and bestOffset is 1 (index of <q> inside <div>)].
  11910. // Picking out which child to recurse into here is a special case since we
  11911. // don't want to check past <q> -- once we find that the final range starts
  11912. // in <span>, we can look at all of its children (and all of their children)
  11913. // to find the break point.
  11914. // At all times, (bestContainer, bestOffset) is the latest single-line start
  11915. // point that we know of.
  11916. var currentContainer = bestContainer;
  11917. var maxIndexToConsider = bestOffset - 1;
  11918. do {
  11919. var nodeValue = currentContainer.nodeValue;
  11920. for (var ii = maxIndexToConsider; ii >= 0; ii--) {
  11921. if (nodeValue != null && ii > 0 && UnicodeUtils_1.isSurrogatePair(nodeValue, ii - 1)) {
  11922. // We're in the middle of a surrogate pair -- skip over so we never
  11923. // return a range with an endpoint in the middle of a code point.
  11924. continue;
  11925. }
  11926. range.setStart(currentContainer, ii);
  11927. if (areRectsOnOneLine(getRangeClientRects_1(range), lineHeight)) {
  11928. bestContainer = currentContainer;
  11929. bestOffset = ii;
  11930. } else {
  11931. break;
  11932. }
  11933. }
  11934. if (ii === -1 || currentContainer.childNodes.length === 0) {
  11935. // If ii === -1, then (bestContainer, bestOffset), which is equal to
  11936. // (currentContainer, 0), was a single-line start point but a start
  11937. // point before currentContainer wasn't, so the line break seems to
  11938. // have occurred immediately after currentContainer's start tag
  11939. //
  11940. // If currentContainer.childNodes.length === 0, we're already at a
  11941. // terminal node (e.g., text node) and should return our current best.
  11942. break;
  11943. }
  11944. currentContainer = currentContainer.childNodes[ii];
  11945. maxIndexToConsider = getNodeLength$1(currentContainer);
  11946. } while (true);
  11947. range.setStart(bestContainer, bestOffset);
  11948. return range;
  11949. }
  11950. var expandRangeToStartOfLine_1 = expandRangeToStartOfLine;
  11951. /**
  11952. * Convert the current selection range to an anchor/focus pair of offset keys
  11953. * and values that can be interpreted by components.
  11954. */
  11955. function getDraftEditorSelectionWithNodes(editorState, root, anchorNode, anchorOffset, focusNode, focusOffset) {
  11956. var anchorIsTextNode = anchorNode.nodeType === Node.TEXT_NODE;
  11957. var focusIsTextNode = focusNode.nodeType === Node.TEXT_NODE;
  11958. // If the selection range lies only on text nodes, the task is simple.
  11959. // Find the nearest offset-aware elements and use the
  11960. // offset values supplied by the selection range.
  11961. if (anchorIsTextNode && focusIsTextNode) {
  11962. return {
  11963. selectionState: getUpdatedSelectionState_1(editorState, nullthrows_1(findAncestorOffsetKey_1(anchorNode)), anchorOffset, nullthrows_1(findAncestorOffsetKey_1(focusNode)), focusOffset),
  11964. needsRecovery: false
  11965. };
  11966. }
  11967. var anchorPoint = null;
  11968. var focusPoint = null;
  11969. var needsRecovery = true;
  11970. // An element is selected. Convert this selection range into leaf offset
  11971. // keys and offset values for consumption at the component level. This
  11972. // is common in Firefox, where select-all and triple click behavior leads
  11973. // to entire elements being selected.
  11974. //
  11975. // Note that we use the `needsRecovery` parameter in the callback here. This
  11976. // is because when certain elements are selected, the behavior for subsequent
  11977. // cursor movement (e.g. via arrow keys) is uncertain and may not match
  11978. // expectations at the component level. For example, if an entire <div> is
  11979. // selected and the user presses the right arrow, Firefox keeps the selection
  11980. // on the <div>. If we allow subsequent keypresses to insert characters
  11981. // natively, they will be inserted into a browser-created text node to the
  11982. // right of that <div>. This is obviously undesirable.
  11983. //
  11984. // With the `needsRecovery` flag, we inform the caller that it is responsible
  11985. // for manually setting the selection state on the rendered document to
  11986. // ensure proper selection state maintenance.
  11987. if (anchorIsTextNode) {
  11988. anchorPoint = {
  11989. key: nullthrows_1(findAncestorOffsetKey_1(anchorNode)),
  11990. offset: anchorOffset
  11991. };
  11992. focusPoint = getPointForNonTextNode(root, focusNode, focusOffset);
  11993. } else if (focusIsTextNode) {
  11994. focusPoint = {
  11995. key: nullthrows_1(findAncestorOffsetKey_1(focusNode)),
  11996. offset: focusOffset
  11997. };
  11998. anchorPoint = getPointForNonTextNode(root, anchorNode, anchorOffset);
  11999. } else {
  12000. anchorPoint = getPointForNonTextNode(root, anchorNode, anchorOffset);
  12001. focusPoint = getPointForNonTextNode(root, focusNode, focusOffset);
  12002. // If the selection is collapsed on an empty block, don't force recovery.
  12003. // This way, on arrow key selection changes, the browser can move the
  12004. // cursor from a non-zero offset on one block, through empty blocks,
  12005. // to a matching non-zero offset on other text blocks.
  12006. if (anchorNode === focusNode && anchorOffset === focusOffset) {
  12007. needsRecovery = !!anchorNode.firstChild && anchorNode.firstChild.nodeName !== 'BR';
  12008. }
  12009. }
  12010. return {
  12011. selectionState: getUpdatedSelectionState_1(editorState, anchorPoint.key, anchorPoint.offset, focusPoint.key, focusPoint.offset),
  12012. needsRecovery: needsRecovery
  12013. };
  12014. }
  12015. /**
  12016. * Identify the first leaf descendant for the given node.
  12017. */
  12018. function getFirstLeaf(node) {
  12019. while (node.firstChild && (
  12020. // data-blocks has no offset
  12021. node.firstChild instanceof Element && node.firstChild.getAttribute('data-blocks') === 'true' || getSelectionOffsetKeyForNode_1(node.firstChild))) {
  12022. node = node.firstChild;
  12023. }
  12024. return node;
  12025. }
  12026. /**
  12027. * Identify the last leaf descendant for the given node.
  12028. */
  12029. function getLastLeaf(node) {
  12030. while (node.lastChild && (
  12031. // data-blocks has no offset
  12032. node.lastChild instanceof Element && node.lastChild.getAttribute('data-blocks') === 'true' || getSelectionOffsetKeyForNode_1(node.lastChild))) {
  12033. node = node.lastChild;
  12034. }
  12035. return node;
  12036. }
  12037. function getPointForNonTextNode(editorRoot, startNode, childOffset) {
  12038. var node = startNode;
  12039. var offsetKey = findAncestorOffsetKey_1(node);
  12040. !(offsetKey != null || editorRoot && (editorRoot === node || editorRoot.firstChild === node)) ? process.env.NODE_ENV !== 'production' ? invariant_1(false, 'Unknown node in selection range.') : invariant_1(false) : void 0;
  12041. // If the editorRoot is the selection, step downward into the content
  12042. // wrapper.
  12043. if (editorRoot === node) {
  12044. node = node.firstChild;
  12045. !(node instanceof Element && node.getAttribute('data-contents') === 'true') ? process.env.NODE_ENV !== 'production' ? invariant_1(false, 'Invalid DraftEditorContents structure.') : invariant_1(false) : void 0;
  12046. if (childOffset > 0) {
  12047. childOffset = node.childNodes.length;
  12048. }
  12049. }
  12050. // If the child offset is zero and we have an offset key, we're done.
  12051. // If there's no offset key because the entire editor is selected,
  12052. // find the leftmost ("first") leaf in the tree and use that as the offset
  12053. // key.
  12054. if (childOffset === 0) {
  12055. var key = null;
  12056. if (offsetKey != null) {
  12057. key = offsetKey;
  12058. } else {
  12059. var firstLeaf = getFirstLeaf(node);
  12060. key = nullthrows_1(getSelectionOffsetKeyForNode_1(firstLeaf));
  12061. }
  12062. return { key: key, offset: 0 };
  12063. }
  12064. var nodeBeforeCursor = node.childNodes[childOffset - 1];
  12065. var leafKey = null;
  12066. var textLength = null;
  12067. if (!getSelectionOffsetKeyForNode_1(nodeBeforeCursor)) {
  12068. // Our target node may be a leaf or a text node, in which case we're
  12069. // already where we want to be and can just use the child's length as
  12070. // our offset.
  12071. leafKey = nullthrows_1(offsetKey);
  12072. textLength = getTextContentLength(nodeBeforeCursor);
  12073. } else {
  12074. // Otherwise, we'll look at the child to the left of the cursor and find
  12075. // the last leaf node in its subtree.
  12076. var lastLeaf = getLastLeaf(nodeBeforeCursor);
  12077. leafKey = nullthrows_1(getSelectionOffsetKeyForNode_1(lastLeaf));
  12078. textLength = getTextContentLength(lastLeaf);
  12079. }
  12080. return {
  12081. key: leafKey,
  12082. offset: textLength
  12083. };
  12084. }
  12085. /**
  12086. * Return the length of a node's textContent, regarding single newline
  12087. * characters as zero-length. This allows us to avoid problems with identifying
  12088. * the correct selection offset for empty blocks in IE, in which we
  12089. * render newlines instead of break tags.
  12090. */
  12091. function getTextContentLength(node) {
  12092. var textContent = node.textContent;
  12093. return textContent === '\n' ? 0 : textContent.length;
  12094. }
  12095. var getDraftEditorSelectionWithNodes_1 = getDraftEditorSelectionWithNodes;
  12096. /**
  12097. * Copyright (c) 2013-present, Facebook, Inc.
  12098. * All rights reserved.
  12099. *
  12100. * This source code is licensed under the BSD-style license found in the
  12101. * LICENSE file in the root directory of this source tree. An additional grant
  12102. * of patent rights can be found in the PATENTS file in the same directory.
  12103. *
  12104. * @providesModule moveSelectionBackward
  12105. * @format
  12106. *
  12107. */
  12108. /**
  12109. * Given a collapsed selection, move the focus `maxDistance` backward within
  12110. * the selected block. If the selection will go beyond the start of the block,
  12111. * move focus to the end of the previous block, but no further.
  12112. *
  12113. * This function is not Unicode-aware, so surrogate pairs will be treated
  12114. * as having length 2.
  12115. */
  12116. function moveSelectionBackward(editorState, maxDistance) {
  12117. var selection = editorState.getSelection();
  12118. var content = editorState.getCurrentContent();
  12119. var key = selection.getStartKey();
  12120. var offset = selection.getStartOffset();
  12121. var focusKey = key;
  12122. var focusOffset = 0;
  12123. if (maxDistance > offset) {
  12124. var keyBefore = content.getKeyBefore(key);
  12125. if (keyBefore == null) {
  12126. focusKey = key;
  12127. } else {
  12128. focusKey = keyBefore;
  12129. var blockBefore = content.getBlockForKey(keyBefore);
  12130. focusOffset = blockBefore.getText().length;
  12131. }
  12132. } else {
  12133. focusOffset = offset - maxDistance;
  12134. }
  12135. return selection.merge({
  12136. focusKey: focusKey,
  12137. focusOffset: focusOffset,
  12138. isBackward: true
  12139. });
  12140. }
  12141. var moveSelectionBackward_1 = moveSelectionBackward;
  12142. /**
  12143. * For a collapsed selection state, remove text based on the specified strategy.
  12144. * If the selection state is not collapsed, remove the entire selected range.
  12145. */
  12146. function removeTextWithStrategy(editorState, strategy, direction) {
  12147. var selection = editorState.getSelection();
  12148. var content = editorState.getCurrentContent();
  12149. var target = selection;
  12150. if (selection.isCollapsed()) {
  12151. if (direction === 'forward') {
  12152. if (editorState.isSelectionAtEndOfContent()) {
  12153. return content;
  12154. }
  12155. } else if (editorState.isSelectionAtStartOfContent()) {
  12156. return content;
  12157. }
  12158. target = strategy(editorState);
  12159. if (target === selection) {
  12160. return content;
  12161. }
  12162. }
  12163. return DraftModifier_1.removeRange(content, target, direction);
  12164. }
  12165. var removeTextWithStrategy_1 = removeTextWithStrategy;
  12166. function keyCommandBackspaceToStartOfLine(editorState) {
  12167. var afterRemoval = removeTextWithStrategy_1(editorState, function (strategyState) {
  12168. var selection = strategyState.getSelection();
  12169. if (selection.isCollapsed() && selection.getAnchorOffset() === 0) {
  12170. return moveSelectionBackward_1(strategyState, 1);
  12171. }
  12172. var domSelection = commonjsGlobal.getSelection();
  12173. var range = domSelection.getRangeAt(0);
  12174. range = expandRangeToStartOfLine_1(range);
  12175. return getDraftEditorSelectionWithNodes_1(strategyState, null, range.endContainer, range.endOffset, range.startContainer, range.startOffset).selectionState;
  12176. }, 'backward');
  12177. if (afterRemoval === editorState.getCurrentContent()) {
  12178. return editorState;
  12179. }
  12180. return EditorState_1.push(editorState, afterRemoval, 'remove-range');
  12181. }
  12182. var keyCommandBackspaceToStartOfLine_1 = keyCommandBackspaceToStartOfLine;
  12183. /**
  12184. * Copyright (c) 2013-present, Facebook, Inc.
  12185. *
  12186. * This source code is licensed under the MIT license found in the
  12187. * LICENSE file in the root directory of this source tree.
  12188. *
  12189. * @typechecks
  12190. * @stub
  12191. *
  12192. */
  12193. // \u00a1-\u00b1\u00b4-\u00b8\u00ba\u00bb\u00bf
  12194. // is latin supplement punctuation except fractions and superscript
  12195. // numbers
  12196. // \u2010-\u2027\u2030-\u205e
  12197. // is punctuation from the general punctuation block:
  12198. // weird quotes, commas, bullets, dashes, etc.
  12199. // \u30fb\u3001\u3002\u3008-\u3011\u3014-\u301f
  12200. // is CJK punctuation
  12201. // \uff1a-\uff1f\uff01-\uff0f\uff3b-\uff40\uff5b-\uff65
  12202. // is some full-width/half-width punctuation
  12203. // \u2E2E\u061f\u066a-\u066c\u061b\u060c\u060d\uFD3e\uFD3F
  12204. // is some Arabic punctuation marks
  12205. // \u1801\u0964\u104a\u104b
  12206. // is misc. other language punctuation marks
  12207. var PUNCTUATION = '[.,+*?$|#{}()\'\\^\\-\\[\\]\\\\\\/!@%"~=<>_:;' + '\u30FB\u3001\u3002\u3008-\u3011\u3014-\u301F\uFF1A-\uFF1F\uFF01-\uFF0F' + '\uFF3B-\uFF40\uFF5B-\uFF65\u2E2E\u061F\u066A-\u066C\u061B\u060C\u060D' + '\uFD3E\uFD3F\u1801\u0964\u104A\u104B\u2010-\u2027\u2030-\u205E' + '\xA1-\xB1\xB4-\xB8\xBA\xBB\xBF]';
  12208. var TokenizeUtil = {
  12209. getPunctuation: function getPunctuation() {
  12210. return PUNCTUATION;
  12211. }
  12212. };
  12213. var punctuation = TokenizeUtil.getPunctuation();
  12214. // The apostrophe and curly single quotes behave in a curious way: when
  12215. // surrounded on both sides by word characters, they behave as word chars; when
  12216. // either neighbor is punctuation or an end of the string, they behave as
  12217. // punctuation.
  12218. var CHAMELEON_CHARS = '[\'\u2018\u2019]';
  12219. // Remove the underscore, which should count as part of the removable word. The
  12220. // "chameleon chars" also count as punctuation in this regex.
  12221. var WHITESPACE_AND_PUNCTUATION = '\\s|(?![_])' + punctuation;
  12222. var DELETE_STRING = '^' + '(?:' + WHITESPACE_AND_PUNCTUATION + ')*' + '(?:' + CHAMELEON_CHARS + '|(?!' + WHITESPACE_AND_PUNCTUATION + ').)*' + '(?:(?!' + WHITESPACE_AND_PUNCTUATION + ').)';
  12223. var DELETE_REGEX = new RegExp(DELETE_STRING);
  12224. var BACKSPACE_STRING = '(?:(?!' + WHITESPACE_AND_PUNCTUATION + ').)' + '(?:' + CHAMELEON_CHARS + '|(?!' + WHITESPACE_AND_PUNCTUATION + ').)*' + '(?:' + WHITESPACE_AND_PUNCTUATION + ')*' + '$';
  12225. var BACKSPACE_REGEX = new RegExp(BACKSPACE_STRING);
  12226. function getRemovableWord(text, isBackward) {
  12227. var matches = isBackward ? BACKSPACE_REGEX.exec(text) : DELETE_REGEX.exec(text);
  12228. return matches ? matches[0] : text;
  12229. }
  12230. var DraftRemovableWord = {
  12231. getBackward: function getBackward(text) {
  12232. return getRemovableWord(text, true);
  12233. },
  12234. getForward: function getForward(text) {
  12235. return getRemovableWord(text, false);
  12236. }
  12237. };
  12238. var DraftRemovableWord_1 = DraftRemovableWord;
  12239. /**
  12240. * Delete the word that is left of the cursor, as well as any spaces or
  12241. * punctuation after the word.
  12242. */
  12243. function keyCommandBackspaceWord(editorState) {
  12244. var afterRemoval = removeTextWithStrategy_1(editorState, function (strategyState) {
  12245. var selection = strategyState.getSelection();
  12246. var offset = selection.getStartOffset();
  12247. // If there are no words before the cursor, remove the preceding newline.
  12248. if (offset === 0) {
  12249. return moveSelectionBackward_1(strategyState, 1);
  12250. }
  12251. var key = selection.getStartKey();
  12252. var content = strategyState.getCurrentContent();
  12253. var text = content.getBlockForKey(key).getText().slice(0, offset);
  12254. var toRemove = DraftRemovableWord_1.getBackward(text);
  12255. return moveSelectionBackward_1(strategyState, toRemove.length || 1);
  12256. }, 'backward');
  12257. if (afterRemoval === editorState.getCurrentContent()) {
  12258. return editorState;
  12259. }
  12260. return EditorState_1.push(editorState, afterRemoval, 'remove-range');
  12261. }
  12262. var keyCommandBackspaceWord_1 = keyCommandBackspaceWord;
  12263. /**
  12264. * Copyright (c) 2013-present, Facebook, Inc.
  12265. * All rights reserved.
  12266. *
  12267. * This source code is licensed under the BSD-style license found in the
  12268. * LICENSE file in the root directory of this source tree. An additional grant
  12269. * of patent rights can be found in the PATENTS file in the same directory.
  12270. *
  12271. * @providesModule moveSelectionForward
  12272. * @format
  12273. *
  12274. */
  12275. /**
  12276. * Given a collapsed selection, move the focus `maxDistance` forward within
  12277. * the selected block. If the selection will go beyond the end of the block,
  12278. * move focus to the start of the next block, but no further.
  12279. *
  12280. * This function is not Unicode-aware, so surrogate pairs will be treated
  12281. * as having length 2.
  12282. */
  12283. function moveSelectionForward(editorState, maxDistance) {
  12284. var selection = editorState.getSelection();
  12285. var key = selection.getStartKey();
  12286. var offset = selection.getStartOffset();
  12287. var content = editorState.getCurrentContent();
  12288. var focusKey = key;
  12289. var focusOffset;
  12290. var block = content.getBlockForKey(key);
  12291. if (maxDistance > block.getText().length - offset) {
  12292. focusKey = content.getKeyAfter(key);
  12293. focusOffset = 0;
  12294. } else {
  12295. focusOffset = offset + maxDistance;
  12296. }
  12297. return selection.merge({ focusKey: focusKey, focusOffset: focusOffset });
  12298. }
  12299. var moveSelectionForward_1 = moveSelectionForward;
  12300. /**
  12301. * Delete the word that is right of the cursor, as well as any spaces or
  12302. * punctuation before the word.
  12303. */
  12304. function keyCommandDeleteWord(editorState) {
  12305. var afterRemoval = removeTextWithStrategy_1(editorState, function (strategyState) {
  12306. var selection = strategyState.getSelection();
  12307. var offset = selection.getStartOffset();
  12308. var key = selection.getStartKey();
  12309. var content = strategyState.getCurrentContent();
  12310. var text = content.getBlockForKey(key).getText().slice(offset);
  12311. var toRemove = DraftRemovableWord_1.getForward(text);
  12312. // If there are no words in front of the cursor, remove the newline.
  12313. return moveSelectionForward_1(strategyState, toRemove.length || 1);
  12314. }, 'forward');
  12315. if (afterRemoval === editorState.getCurrentContent()) {
  12316. return editorState;
  12317. }
  12318. return EditorState_1.push(editorState, afterRemoval, 'remove-range');
  12319. }
  12320. var keyCommandDeleteWord_1 = keyCommandDeleteWord;
  12321. function keyCommandInsertNewline(editorState) {
  12322. var contentState = DraftModifier_1.splitBlock(editorState.getCurrentContent(), editorState.getSelection());
  12323. return EditorState_1.push(editorState, contentState, 'split-block');
  12324. }
  12325. var keyCommandInsertNewline_1 = keyCommandInsertNewline;
  12326. /**
  12327. * See comment for `moveSelectionToStartOfBlock`.
  12328. */
  12329. function keyCommandMoveSelectionToEndOfBlock(editorState) {
  12330. var selection = editorState.getSelection();
  12331. var endKey = selection.getEndKey();
  12332. var content = editorState.getCurrentContent();
  12333. var textLength = content.getBlockForKey(endKey).getLength();
  12334. return EditorState_1.set(editorState, {
  12335. selection: selection.merge({
  12336. anchorKey: endKey,
  12337. anchorOffset: textLength,
  12338. focusKey: endKey,
  12339. focusOffset: textLength,
  12340. isBackward: false
  12341. }),
  12342. forceSelection: true
  12343. });
  12344. }
  12345. var keyCommandMoveSelectionToEndOfBlock_1 = keyCommandMoveSelectionToEndOfBlock;
  12346. /**
  12347. * Collapse selection at the start of the first selected block. This is used
  12348. * for Firefox versions that attempt to navigate forward/backward instead of
  12349. * moving the cursor. Other browsers are able to move the cursor natively.
  12350. */
  12351. function keyCommandMoveSelectionToStartOfBlock(editorState) {
  12352. var selection = editorState.getSelection();
  12353. var startKey = selection.getStartKey();
  12354. return EditorState_1.set(editorState, {
  12355. selection: selection.merge({
  12356. anchorKey: startKey,
  12357. anchorOffset: 0,
  12358. focusKey: startKey,
  12359. focusOffset: 0,
  12360. isBackward: false
  12361. }),
  12362. forceSelection: true
  12363. });
  12364. }
  12365. var keyCommandMoveSelectionToStartOfBlock_1 = keyCommandMoveSelectionToStartOfBlock;
  12366. /**
  12367. * Remove the selected range. If the cursor is collapsed, remove the preceding
  12368. * character. This operation is Unicode-aware, so removing a single character
  12369. * will remove a surrogate pair properly as well.
  12370. */
  12371. function keyCommandPlainBackspace(editorState) {
  12372. var afterRemoval = removeTextWithStrategy_1(editorState, function (strategyState) {
  12373. var selection = strategyState.getSelection();
  12374. var content = strategyState.getCurrentContent();
  12375. var key = selection.getAnchorKey();
  12376. var offset = selection.getAnchorOffset();
  12377. var charBehind = content.getBlockForKey(key).getText()[offset - 1];
  12378. return moveSelectionBackward_1(strategyState, charBehind ? UnicodeUtils_1.getUTF16Length(charBehind, 0) : 1);
  12379. }, 'backward');
  12380. if (afterRemoval === editorState.getCurrentContent()) {
  12381. return editorState;
  12382. }
  12383. var selection = editorState.getSelection();
  12384. return EditorState_1.push(editorState, afterRemoval.set('selectionBefore', selection), selection.isCollapsed() ? 'backspace-character' : 'remove-range');
  12385. }
  12386. var keyCommandPlainBackspace_1 = keyCommandPlainBackspace;
  12387. /**
  12388. * Remove the selected range. If the cursor is collapsed, remove the following
  12389. * character. This operation is Unicode-aware, so removing a single character
  12390. * will remove a surrogate pair properly as well.
  12391. */
  12392. function keyCommandPlainDelete(editorState) {
  12393. var afterRemoval = removeTextWithStrategy_1(editorState, function (strategyState) {
  12394. var selection = strategyState.getSelection();
  12395. var content = strategyState.getCurrentContent();
  12396. var key = selection.getAnchorKey();
  12397. var offset = selection.getAnchorOffset();
  12398. var charAhead = content.getBlockForKey(key).getText()[offset];
  12399. return moveSelectionForward_1(strategyState, charAhead ? UnicodeUtils_1.getUTF16Length(charAhead, 0) : 1);
  12400. }, 'forward');
  12401. if (afterRemoval === editorState.getCurrentContent()) {
  12402. return editorState;
  12403. }
  12404. var selection = editorState.getSelection();
  12405. return EditorState_1.push(editorState, afterRemoval.set('selectionBefore', selection), selection.isCollapsed() ? 'delete-character' : 'remove-range');
  12406. }
  12407. var keyCommandPlainDelete_1 = keyCommandPlainDelete;
  12408. /**
  12409. * Transpose the characters on either side of a collapsed cursor, or
  12410. * if the cursor is at the end of the block, transpose the last two
  12411. * characters.
  12412. */
  12413. function keyCommandTransposeCharacters(editorState) {
  12414. var selection = editorState.getSelection();
  12415. if (!selection.isCollapsed()) {
  12416. return editorState;
  12417. }
  12418. var offset = selection.getAnchorOffset();
  12419. if (offset === 0) {
  12420. return editorState;
  12421. }
  12422. var blockKey = selection.getAnchorKey();
  12423. var content = editorState.getCurrentContent();
  12424. var block = content.getBlockForKey(blockKey);
  12425. var length = block.getLength();
  12426. // Nothing to transpose if there aren't two characters.
  12427. if (length <= 1) {
  12428. return editorState;
  12429. }
  12430. var removalRange;
  12431. var finalSelection;
  12432. if (offset === length) {
  12433. // The cursor is at the end of the block. Swap the last two characters.
  12434. removalRange = selection.set('anchorOffset', offset - 1);
  12435. finalSelection = selection;
  12436. } else {
  12437. removalRange = selection.set('focusOffset', offset + 1);
  12438. finalSelection = removalRange.set('anchorOffset', offset + 1);
  12439. }
  12440. // Extract the character to move as a fragment. This preserves its
  12441. // styling and entity, if any.
  12442. var movedFragment = getContentStateFragment_1(content, removalRange);
  12443. var afterRemoval = DraftModifier_1.removeRange(content, removalRange, 'backward');
  12444. // After the removal, the insertion target is one character back.
  12445. var selectionAfter = afterRemoval.getSelectionAfter();
  12446. var targetOffset = selectionAfter.getAnchorOffset() - 1;
  12447. var targetRange = selectionAfter.merge({
  12448. anchorOffset: targetOffset,
  12449. focusOffset: targetOffset
  12450. });
  12451. var afterInsert = DraftModifier_1.replaceWithFragment(afterRemoval, targetRange, movedFragment);
  12452. var newEditorState = EditorState_1.push(editorState, afterInsert, 'insert-fragment');
  12453. return EditorState_1.acceptSelection(newEditorState, finalSelection);
  12454. }
  12455. var keyCommandTransposeCharacters_1 = keyCommandTransposeCharacters;
  12456. function keyCommandUndo(e, editorState, updateFn) {
  12457. var undoneState = EditorState_1.undo(editorState);
  12458. // If the last change to occur was a spellcheck change, allow the undo
  12459. // event to fall through to the browser. This allows the browser to record
  12460. // the unwanted change, which should soon lead it to learn not to suggest
  12461. // the correction again.
  12462. if (editorState.getLastChangeType() === 'spellcheck-change') {
  12463. var nativelyRenderedContent = undoneState.getCurrentContent();
  12464. updateFn(EditorState_1.set(undoneState, { nativelyRenderedContent: nativelyRenderedContent }));
  12465. return;
  12466. }
  12467. // Otheriwse, manage the undo behavior manually.
  12468. e.preventDefault();
  12469. if (!editorState.getNativelyRenderedContent()) {
  12470. updateFn(undoneState);
  12471. return;
  12472. }
  12473. // Trigger a re-render with the current content state to ensure that the
  12474. // component tree has up-to-date props for comparison.
  12475. updateFn(EditorState_1.set(editorState, { nativelyRenderedContent: null }));
  12476. // Wait to ensure that the re-render has occurred before performing
  12477. // the undo action.
  12478. setTimeout(function () {
  12479. updateFn(undoneState);
  12480. }, 0);
  12481. }
  12482. var keyCommandUndo_1 = keyCommandUndo;
  12483. var isOptionKeyCommand = KeyBindingUtil_1.isOptionKeyCommand;
  12484. var isChrome$1 = UserAgent_1.isBrowser('Chrome');
  12485. /**
  12486. * Map a `DraftEditorCommand` command value to a corresponding function.
  12487. */
  12488. function onKeyCommand(command, editorState) {
  12489. switch (command) {
  12490. case 'redo':
  12491. return EditorState_1.redo(editorState);
  12492. case 'delete':
  12493. return keyCommandPlainDelete_1(editorState);
  12494. case 'delete-word':
  12495. return keyCommandDeleteWord_1(editorState);
  12496. case 'backspace':
  12497. return keyCommandPlainBackspace_1(editorState);
  12498. case 'backspace-word':
  12499. return keyCommandBackspaceWord_1(editorState);
  12500. case 'backspace-to-start-of-line':
  12501. return keyCommandBackspaceToStartOfLine_1(editorState);
  12502. case 'split-block':
  12503. return keyCommandInsertNewline_1(editorState);
  12504. case 'transpose-characters':
  12505. return keyCommandTransposeCharacters_1(editorState);
  12506. case 'move-selection-to-start-of-block':
  12507. return keyCommandMoveSelectionToStartOfBlock_1(editorState);
  12508. case 'move-selection-to-end-of-block':
  12509. return keyCommandMoveSelectionToEndOfBlock_1(editorState);
  12510. case 'secondary-cut':
  12511. return SecondaryClipboard_1.cut(editorState);
  12512. case 'secondary-paste':
  12513. return SecondaryClipboard_1.paste(editorState);
  12514. default:
  12515. return editorState;
  12516. }
  12517. }
  12518. /**
  12519. * Intercept keydown behavior to handle keys and commands manually, if desired.
  12520. *
  12521. * Keydown combinations may be mapped to `DraftCommand` values, which may
  12522. * correspond to command functions that modify the editor or its contents.
  12523. *
  12524. * See `getDefaultKeyBinding` for defaults. Alternatively, the top-level
  12525. * component may provide a custom mapping via the `keyBindingFn` prop.
  12526. */
  12527. function editOnKeyDown(editor, e) {
  12528. var keyCode = e.which;
  12529. var editorState = editor._latestEditorState;
  12530. switch (keyCode) {
  12531. case Keys.RETURN:
  12532. e.preventDefault();
  12533. // The top-level component may manually handle newline insertion. If
  12534. // no special handling is performed, fall through to command handling.
  12535. if (editor.props.handleReturn && isEventHandled_1(editor.props.handleReturn(e, editorState))) {
  12536. return;
  12537. }
  12538. break;
  12539. case Keys.ESC:
  12540. e.preventDefault();
  12541. editor.props.onEscape && editor.props.onEscape(e);
  12542. return;
  12543. case Keys.TAB:
  12544. editor.props.onTab && editor.props.onTab(e);
  12545. return;
  12546. case Keys.UP:
  12547. editor.props.onUpArrow && editor.props.onUpArrow(e);
  12548. return;
  12549. case Keys.RIGHT:
  12550. editor.props.onRightArrow && editor.props.onRightArrow(e);
  12551. return;
  12552. case Keys.DOWN:
  12553. editor.props.onDownArrow && editor.props.onDownArrow(e);
  12554. return;
  12555. case Keys.LEFT:
  12556. editor.props.onLeftArrow && editor.props.onLeftArrow(e);
  12557. return;
  12558. case Keys.SPACE:
  12559. // Handling for OSX where option + space scrolls.
  12560. if (isChrome$1 && isOptionKeyCommand(e)) {
  12561. e.preventDefault();
  12562. // Insert a nbsp into the editor.
  12563. var contentState = DraftModifier_1.replaceText(editorState.getCurrentContent(), editorState.getSelection(), '\xA0');
  12564. editor.update(EditorState_1.push(editorState, contentState, 'insert-characters'));
  12565. return;
  12566. }
  12567. }
  12568. var command = editor.props.keyBindingFn(e);
  12569. // If no command is specified, allow keydown event to continue.
  12570. if (!command) {
  12571. return;
  12572. }
  12573. if (command === 'undo') {
  12574. // Since undo requires some special updating behavior to keep the editor
  12575. // in sync, handle it separately.
  12576. keyCommandUndo_1(e, editorState, editor.update);
  12577. return;
  12578. }
  12579. // At this point, we know that we're handling a command of some kind, so
  12580. // we don't want to insert a character following the keydown.
  12581. e.preventDefault();
  12582. // Allow components higher up the tree to handle the command first.
  12583. if (editor.props.handleKeyCommand && isEventHandled_1(editor.props.handleKeyCommand(command, editorState))) {
  12584. return;
  12585. }
  12586. var newState = onKeyCommand(command, editorState);
  12587. if (newState !== editorState) {
  12588. editor.update(newState);
  12589. }
  12590. }
  12591. var editOnKeyDown_1 = editOnKeyDown;
  12592. /**
  12593. * Copyright (c) 2013-present, Facebook, Inc.
  12594. *
  12595. * This source code is licensed under the MIT license found in the
  12596. * LICENSE file in the root directory of this source tree.
  12597. *
  12598. *
  12599. */
  12600. function _classCallCheck$e(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  12601. var URI = function () {
  12602. function URI(uri) {
  12603. _classCallCheck$e(this, URI);
  12604. this._uri = uri;
  12605. }
  12606. URI.prototype.toString = function toString() {
  12607. return this._uri;
  12608. };
  12609. return URI;
  12610. }();
  12611. var URI_1 = URI;
  12612. var isOldIE = UserAgent_1.isBrowser('IE <= 9');
  12613. // Provides a dom node that will not execute scripts
  12614. // https://developer.mozilla.org/en-US/docs/Web/API/DOMImplementation.createHTMLDocument
  12615. // https://developer.mozilla.org/en-US/Add-ons/Code_snippets/HTML_to_DOM
  12616. function getSafeBodyFromHTML(html) {
  12617. var doc;
  12618. var root = null;
  12619. // Provides a safe context
  12620. if (!isOldIE && document.implementation && document.implementation.createHTMLDocument) {
  12621. doc = document.implementation.createHTMLDocument('foo');
  12622. !doc.documentElement ? process.env.NODE_ENV !== 'production' ? invariant_1(false, 'Missing doc.documentElement') : invariant_1(false) : void 0;
  12623. doc.documentElement.innerHTML = html;
  12624. root = doc.getElementsByTagName('body')[0];
  12625. }
  12626. return root;
  12627. }
  12628. var getSafeBodyFromHTML_1 = getSafeBodyFromHTML;
  12629. var _extends$4 = objectAssign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };
  12630. var _knownListItemDepthCl;
  12631. function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
  12632. var _require = immutable,
  12633. Set$1 = _require.Set;
  12634. var experimentalTreeDataSupport = DraftFeatureFlags_1.draft_tree_data_support;
  12635. var List$a = immutable.List,
  12636. OrderedSet$5 = immutable.OrderedSet;
  12637. var NBSP = '&nbsp;';
  12638. var SPACE = ' ';
  12639. // Arbitrary max indent
  12640. var MAX_DEPTH = 4;
  12641. // used for replacing characters in HTML
  12642. var REGEX_CR = new RegExp('\r', 'g');
  12643. var REGEX_LF = new RegExp('\n', 'g');
  12644. var REGEX_NBSP = new RegExp(NBSP, 'g');
  12645. var REGEX_CARRIAGE = new RegExp('&#13;?', 'g');
  12646. var REGEX_ZWS = new RegExp('&#8203;?', 'g');
  12647. // https://developer.mozilla.org/en-US/docs/Web/CSS/font-weight
  12648. var boldValues = ['bold', 'bolder', '500', '600', '700', '800', '900'];
  12649. var notBoldValues = ['light', 'lighter', '100', '200', '300', '400'];
  12650. // Block tag flow is different because LIs do not have
  12651. // a deterministic style ;_;
  12652. var inlineTags = {
  12653. b: 'BOLD',
  12654. code: 'CODE',
  12655. del: 'STRIKETHROUGH',
  12656. em: 'ITALIC',
  12657. i: 'ITALIC',
  12658. s: 'STRIKETHROUGH',
  12659. strike: 'STRIKETHROUGH',
  12660. strong: 'BOLD',
  12661. u: 'UNDERLINE'
  12662. };
  12663. var knownListItemDepthClasses = (_knownListItemDepthCl = {}, _defineProperty(_knownListItemDepthCl, cx_1('public/DraftStyleDefault/depth0'), 0), _defineProperty(_knownListItemDepthCl, cx_1('public/DraftStyleDefault/depth1'), 1), _defineProperty(_knownListItemDepthCl, cx_1('public/DraftStyleDefault/depth2'), 2), _defineProperty(_knownListItemDepthCl, cx_1('public/DraftStyleDefault/depth3'), 3), _defineProperty(_knownListItemDepthCl, cx_1('public/DraftStyleDefault/depth4'), 4), _knownListItemDepthCl);
  12664. var anchorAttr = ['className', 'href', 'rel', 'target', 'title'];
  12665. var imgAttr = ['alt', 'className', 'height', 'src', 'width'];
  12666. var lastBlock = void 0;
  12667. var EMPTY_CHUNK = {
  12668. text: '',
  12669. inlines: [],
  12670. entities: [],
  12671. blocks: []
  12672. };
  12673. var EMPTY_BLOCK = {
  12674. children: List$a(),
  12675. depth: 0,
  12676. key: '',
  12677. type: ''
  12678. };
  12679. var getListBlockType = function getListBlockType(tag, lastList) {
  12680. if (tag === 'li') {
  12681. return lastList === 'ol' ? 'ordered-list-item' : 'unordered-list-item';
  12682. }
  12683. return null;
  12684. };
  12685. var getBlockMapSupportedTags = function getBlockMapSupportedTags(blockRenderMap) {
  12686. var unstyledElement = blockRenderMap.get('unstyled').element;
  12687. var tags = Set$1([]);
  12688. blockRenderMap.forEach(function (draftBlock) {
  12689. if (draftBlock.aliasedElements) {
  12690. draftBlock.aliasedElements.forEach(function (tag) {
  12691. tags = tags.add(tag);
  12692. });
  12693. }
  12694. tags = tags.add(draftBlock.element);
  12695. });
  12696. return tags.filter(function (tag) {
  12697. return tag && tag !== unstyledElement;
  12698. }).toArray().sort();
  12699. };
  12700. // custom element conversions
  12701. var getMultiMatchedType = function getMultiMatchedType(tag, lastList, multiMatchExtractor) {
  12702. for (var ii = 0; ii < multiMatchExtractor.length; ii++) {
  12703. var matchType = multiMatchExtractor[ii](tag, lastList);
  12704. if (matchType) {
  12705. return matchType;
  12706. }
  12707. }
  12708. return null;
  12709. };
  12710. var getBlockTypeForTag = function getBlockTypeForTag(tag, lastList, blockRenderMap) {
  12711. var matchedTypes = blockRenderMap.filter(function (draftBlock) {
  12712. return draftBlock.element === tag || draftBlock.wrapper === tag || draftBlock.aliasedElements && draftBlock.aliasedElements.some(function (alias) {
  12713. return alias === tag;
  12714. });
  12715. }).keySeq().toSet().toArray().sort();
  12716. // if we dont have any matched type, return unstyled
  12717. // if we have one matched type return it
  12718. // if we have multi matched types use the multi-match function to gather type
  12719. switch (matchedTypes.length) {
  12720. case 0:
  12721. return 'unstyled';
  12722. case 1:
  12723. return matchedTypes[0];
  12724. default:
  12725. return getMultiMatchedType(tag, lastList, [getListBlockType]) || 'unstyled';
  12726. }
  12727. };
  12728. var processInlineTag = function processInlineTag(tag, node, currentStyle) {
  12729. var styleToCheck = inlineTags[tag];
  12730. if (styleToCheck) {
  12731. currentStyle = currentStyle.add(styleToCheck).toOrderedSet();
  12732. } else if (node instanceof HTMLElement) {
  12733. var htmlElement = node;
  12734. currentStyle = currentStyle.withMutations(function (style) {
  12735. var fontWeight = htmlElement.style.fontWeight;
  12736. var fontStyle = htmlElement.style.fontStyle;
  12737. var textDecoration = htmlElement.style.textDecoration;
  12738. if (boldValues.indexOf(fontWeight) >= 0) {
  12739. style.add('BOLD');
  12740. } else if (notBoldValues.indexOf(fontWeight) >= 0) {
  12741. style.remove('BOLD');
  12742. }
  12743. if (fontStyle === 'italic') {
  12744. style.add('ITALIC');
  12745. } else if (fontStyle === 'normal') {
  12746. style.remove('ITALIC');
  12747. }
  12748. if (textDecoration === 'underline') {
  12749. style.add('UNDERLINE');
  12750. }
  12751. if (textDecoration === 'line-through') {
  12752. style.add('STRIKETHROUGH');
  12753. }
  12754. if (textDecoration === 'none') {
  12755. style.remove('UNDERLINE');
  12756. style.remove('STRIKETHROUGH');
  12757. }
  12758. }).toOrderedSet();
  12759. }
  12760. return currentStyle;
  12761. };
  12762. var joinChunks = function joinChunks(A, B, experimentalHasNestedBlocks) {
  12763. // Sometimes two blocks will touch in the DOM and we need to strip the
  12764. // extra delimiter to preserve niceness.
  12765. var lastInA = A.text.slice(-1);
  12766. var firstInB = B.text.slice(0, 1);
  12767. if (lastInA === '\r' && firstInB === '\r' && !experimentalHasNestedBlocks) {
  12768. A.text = A.text.slice(0, -1);
  12769. A.inlines.pop();
  12770. A.entities.pop();
  12771. A.blocks.pop();
  12772. }
  12773. // Kill whitespace after blocks
  12774. if (lastInA === '\r') {
  12775. if (B.text === SPACE || B.text === '\n') {
  12776. return A;
  12777. } else if (firstInB === SPACE || firstInB === '\n') {
  12778. B.text = B.text.slice(1);
  12779. B.inlines.shift();
  12780. B.entities.shift();
  12781. }
  12782. }
  12783. return {
  12784. text: A.text + B.text,
  12785. inlines: A.inlines.concat(B.inlines),
  12786. entities: A.entities.concat(B.entities),
  12787. blocks: A.blocks.concat(B.blocks)
  12788. };
  12789. };
  12790. /**
  12791. * Check to see if we have anything like <p> <blockquote> <h1>... to create
  12792. * block tags from. If we do, we can use those and ignore <div> tags. If we
  12793. * don't, we can treat <div> tags as meaningful (unstyled) blocks.
  12794. */
  12795. var containsSemanticBlockMarkup = function containsSemanticBlockMarkup(html, blockTags) {
  12796. return blockTags.some(function (tag) {
  12797. return html.indexOf('<' + tag) !== -1;
  12798. });
  12799. };
  12800. var hasValidLinkText = function hasValidLinkText(link) {
  12801. !(link instanceof HTMLAnchorElement) ? process.env.NODE_ENV !== 'production' ? invariant_1(false, 'Link must be an HTMLAnchorElement.') : invariant_1(false) : void 0;
  12802. var protocol = link.protocol;
  12803. return protocol === 'http:' || protocol === 'https:' || protocol === 'mailto:';
  12804. };
  12805. var getWhitespaceChunk = function getWhitespaceChunk(inEntity) {
  12806. var entities = new Array(1);
  12807. if (inEntity) {
  12808. entities[0] = inEntity;
  12809. }
  12810. return _extends$4({}, EMPTY_CHUNK, {
  12811. text: SPACE,
  12812. inlines: [OrderedSet$5()],
  12813. entities: entities
  12814. });
  12815. };
  12816. var getSoftNewlineChunk = function getSoftNewlineChunk() {
  12817. return _extends$4({}, EMPTY_CHUNK, {
  12818. text: '\n',
  12819. inlines: [OrderedSet$5()],
  12820. entities: new Array(1)
  12821. });
  12822. };
  12823. var getChunkedBlock = function getChunkedBlock() {
  12824. var props = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
  12825. return _extends$4({}, EMPTY_BLOCK, props);
  12826. };
  12827. var getBlockDividerChunk = function getBlockDividerChunk(block, depth) {
  12828. var parentKey = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : null;
  12829. return {
  12830. text: '\r',
  12831. inlines: [OrderedSet$5()],
  12832. entities: new Array(1),
  12833. blocks: [getChunkedBlock({
  12834. parent: parentKey,
  12835. key: generateRandomKey_1(),
  12836. type: block,
  12837. depth: Math.max(0, Math.min(MAX_DEPTH, depth))
  12838. })]
  12839. };
  12840. };
  12841. /**
  12842. * If we're pasting from one DraftEditor to another we can check to see if
  12843. * existing list item depth classes are being used and preserve this style
  12844. */
  12845. var getListItemDepth = function getListItemDepth(node) {
  12846. var depth = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 0;
  12847. Object.keys(knownListItemDepthClasses).some(function (depthClass) {
  12848. if (node.classList.contains(depthClass)) {
  12849. depth = knownListItemDepthClasses[depthClass];
  12850. }
  12851. });
  12852. return depth;
  12853. };
  12854. var genFragment = function genFragment(entityMap, node, inlineStyle, lastList, inBlock, blockTags, depth, blockRenderMap, inEntity, parentKey) {
  12855. var lastLastBlock = lastBlock;
  12856. var nodeName = node.nodeName.toLowerCase();
  12857. var newEntityMap = entityMap;
  12858. var nextBlockType = 'unstyled';
  12859. var newBlock = false;
  12860. var inBlockType = inBlock && getBlockTypeForTag(inBlock, lastList, blockRenderMap);
  12861. var chunk = _extends$4({}, EMPTY_CHUNK);
  12862. var newChunk = null;
  12863. var blockKey = void 0;
  12864. // Base Case
  12865. if (nodeName === '#text') {
  12866. var _text = node.textContent;
  12867. var nodeTextContent = _text.trim();
  12868. // We should not create blocks for leading spaces that are
  12869. // existing around ol/ul and their children list items
  12870. if (lastList && nodeTextContent === '' && node.parentElement) {
  12871. var parentNodeName = node.parentElement.nodeName.toLowerCase();
  12872. if (parentNodeName === 'ol' || parentNodeName === 'ul') {
  12873. return { chunk: _extends$4({}, EMPTY_CHUNK), entityMap: entityMap };
  12874. }
  12875. }
  12876. if (nodeTextContent === '' && inBlock !== 'pre') {
  12877. return { chunk: getWhitespaceChunk(inEntity), entityMap: entityMap };
  12878. }
  12879. if (inBlock !== 'pre') {
  12880. // Can't use empty string because MSWord
  12881. _text = _text.replace(REGEX_LF, SPACE);
  12882. }
  12883. // save the last block so we can use it later
  12884. lastBlock = nodeName;
  12885. return {
  12886. chunk: {
  12887. text: _text,
  12888. inlines: Array(_text.length).fill(inlineStyle),
  12889. entities: Array(_text.length).fill(inEntity),
  12890. blocks: []
  12891. },
  12892. entityMap: entityMap
  12893. };
  12894. }
  12895. // save the last block so we can use it later
  12896. lastBlock = nodeName;
  12897. // BR tags
  12898. if (nodeName === 'br') {
  12899. if (lastLastBlock === 'br' && (!inBlock || inBlockType === 'unstyled')) {
  12900. return {
  12901. chunk: getBlockDividerChunk('unstyled', depth, parentKey),
  12902. entityMap: entityMap
  12903. };
  12904. }
  12905. return { chunk: getSoftNewlineChunk(), entityMap: entityMap };
  12906. }
  12907. // IMG tags
  12908. if (nodeName === 'img' && node instanceof HTMLImageElement && node.attributes.getNamedItem('src') && node.attributes.getNamedItem('src').value) {
  12909. var image = node;
  12910. var entityConfig = {};
  12911. imgAttr.forEach(function (attr) {
  12912. var imageAttribute = image.getAttribute(attr);
  12913. if (imageAttribute) {
  12914. entityConfig[attr] = imageAttribute;
  12915. }
  12916. });
  12917. // Forcing this node to have children because otherwise no entity will be
  12918. // created for this node.
  12919. // The child text node cannot just have a space or return as content -
  12920. // we strip those out.
  12921. // See https://github.com/facebook/draft-js/issues/231 for some context.
  12922. node.textContent = '\uD83D\uDCF7';
  12923. // TODO: update this when we remove DraftEntity entirely
  12924. inEntity = DraftEntity_1.__create('IMAGE', 'MUTABLE', entityConfig || {});
  12925. }
  12926. // Inline tags
  12927. inlineStyle = processInlineTag(nodeName, node, inlineStyle);
  12928. // Handle lists
  12929. if (nodeName === 'ul' || nodeName === 'ol') {
  12930. if (lastList) {
  12931. depth += 1;
  12932. }
  12933. lastList = nodeName;
  12934. }
  12935. if ( nodeName === 'li' && node instanceof HTMLElement) {
  12936. depth = getListItemDepth(node, depth);
  12937. }
  12938. var blockType = getBlockTypeForTag(nodeName, lastList, blockRenderMap);
  12939. var inListBlock = lastList && inBlock === 'li' && nodeName === 'li';
  12940. var inBlockOrHasNestedBlocks = (!inBlock || experimentalTreeDataSupport) && blockTags.indexOf(nodeName) !== -1;
  12941. // Block Tags
  12942. if (inListBlock || inBlockOrHasNestedBlocks) {
  12943. chunk = getBlockDividerChunk(blockType, depth, parentKey);
  12944. blockKey = chunk.blocks[0].key;
  12945. inBlock = nodeName;
  12946. newBlock = !experimentalTreeDataSupport;
  12947. }
  12948. // this is required so that we can handle 'ul' and 'ol'
  12949. if (inListBlock) {
  12950. nextBlockType = lastList === 'ul' ? 'unordered-list-item' : 'ordered-list-item';
  12951. }
  12952. // Recurse through children
  12953. var child = node.firstChild;
  12954. if (child != null) {
  12955. nodeName = child.nodeName.toLowerCase();
  12956. }
  12957. var entityId = null;
  12958. while (child) {
  12959. if (child instanceof HTMLAnchorElement && child.href && hasValidLinkText(child)) {
  12960. (function () {
  12961. var anchor = child;
  12962. var entityConfig = {};
  12963. anchorAttr.forEach(function (attr) {
  12964. var anchorAttribute = anchor.getAttribute(attr);
  12965. if (anchorAttribute) {
  12966. entityConfig[attr] = anchorAttribute;
  12967. }
  12968. });
  12969. entityConfig.url = new URI_1(anchor.href).toString();
  12970. // TODO: update this when we remove DraftEntity completely
  12971. entityId = DraftEntity_1.__create('LINK', 'MUTABLE', entityConfig || {});
  12972. })();
  12973. } else {
  12974. entityId = undefined;
  12975. }
  12976. var _genFragment = genFragment(newEntityMap, child, inlineStyle, lastList, inBlock, blockTags, depth, blockRenderMap, entityId || inEntity, null),
  12977. generatedChunk = _genFragment.chunk,
  12978. maybeUpdatedEntityMap = _genFragment.entityMap;
  12979. newChunk = generatedChunk;
  12980. newEntityMap = maybeUpdatedEntityMap;
  12981. chunk = joinChunks(chunk, newChunk, experimentalTreeDataSupport);
  12982. var sibling = child.nextSibling;
  12983. // Put in a newline to break up blocks inside blocks
  12984. if (!parentKey && sibling && blockTags.indexOf(nodeName) >= 0 && inBlock) {
  12985. chunk = joinChunks(chunk, getSoftNewlineChunk());
  12986. }
  12987. if (sibling) {
  12988. nodeName = sibling.nodeName.toLowerCase();
  12989. }
  12990. child = sibling;
  12991. }
  12992. if (newBlock) {
  12993. chunk = joinChunks(chunk, getBlockDividerChunk(nextBlockType, depth, parentKey));
  12994. }
  12995. return { chunk: chunk, entityMap: newEntityMap };
  12996. };
  12997. var getChunkForHTML = function getChunkForHTML(html, DOMBuilder, blockRenderMap, entityMap) {
  12998. html = html.trim().replace(REGEX_CR, '').replace(REGEX_NBSP, SPACE).replace(REGEX_CARRIAGE, '').replace(REGEX_ZWS, '');
  12999. var supportedBlockTags = getBlockMapSupportedTags(blockRenderMap);
  13000. var safeBody = DOMBuilder(html);
  13001. if (!safeBody) {
  13002. return null;
  13003. }
  13004. lastBlock = null;
  13005. // Sometimes we aren't dealing with content that contains nice semantic
  13006. // tags. In this case, use divs to separate everything out into paragraphs
  13007. // and hope for the best.
  13008. var workingBlocks = containsSemanticBlockMarkup(html, supportedBlockTags) ? supportedBlockTags : ['div'];
  13009. // Start with -1 block depth to offset the fact that we are passing in a fake
  13010. // UL block to start with.
  13011. var fragment = genFragment(entityMap, safeBody, OrderedSet$5(), 'ul', null, workingBlocks, -1, blockRenderMap);
  13012. var chunk = fragment.chunk;
  13013. var newEntityMap = fragment.entityMap;
  13014. // join with previous block to prevent weirdness on paste
  13015. if (chunk.text.indexOf('\r') === 0) {
  13016. chunk = {
  13017. text: chunk.text.slice(1),
  13018. inlines: chunk.inlines.slice(1),
  13019. entities: chunk.entities.slice(1),
  13020. blocks: chunk.blocks
  13021. };
  13022. }
  13023. // Kill block delimiter at the end
  13024. if (chunk.text.slice(-1) === '\r') {
  13025. chunk.text = chunk.text.slice(0, -1);
  13026. chunk.inlines = chunk.inlines.slice(0, -1);
  13027. chunk.entities = chunk.entities.slice(0, -1);
  13028. chunk.blocks.pop();
  13029. }
  13030. // If we saw no block tags, put an unstyled one in
  13031. if (chunk.blocks.length === 0) {
  13032. chunk.blocks.push(_extends$4({}, EMPTY_CHUNK, {
  13033. type: 'unstyled',
  13034. depth: 0
  13035. }));
  13036. }
  13037. // Sometimes we start with text that isn't in a block, which is then
  13038. // followed by blocks. Need to fix up the blocks to add in
  13039. // an unstyled block for this content
  13040. if (chunk.text.split('\r').length === chunk.blocks.length + 1) {
  13041. chunk.blocks.unshift({ type: 'unstyled', depth: 0 });
  13042. }
  13043. return { chunk: chunk, entityMap: newEntityMap };
  13044. };
  13045. var convertChunkToContentBlocks = function convertChunkToContentBlocks(chunk) {
  13046. if (!chunk || !chunk.text || !Array.isArray(chunk.blocks)) {
  13047. return null;
  13048. }
  13049. var initialState = {
  13050. cacheRef: {},
  13051. contentBlocks: []
  13052. };
  13053. var start = 0;
  13054. var rawBlocks = chunk.blocks,
  13055. rawInlines = chunk.inlines,
  13056. rawEntities = chunk.entities;
  13057. var BlockNodeRecord = ContentBlock_1;
  13058. return chunk.text.split('\r').reduce(function (acc, textBlock, index) {
  13059. // Make absolutely certain that our text is acceptable.
  13060. textBlock = sanitizeDraftText_1(textBlock);
  13061. var block = rawBlocks[index];
  13062. var end = start + textBlock.length;
  13063. var inlines = rawInlines.slice(start, end);
  13064. var entities = rawEntities.slice(start, end);
  13065. var characterList = List$a(inlines.map(function (style, index) {
  13066. var data = { style: style, entity: null };
  13067. if (entities[index]) {
  13068. data.entity = entities[index];
  13069. }
  13070. return CharacterMetadata_1.create(data);
  13071. }));
  13072. start = end + 1;
  13073. var depth = block.depth,
  13074. type = block.type,
  13075. parent = block.parent;
  13076. var key = block.key || generateRandomKey_1();
  13077. var parentTextNodeKey = null; // will be used to store container text nodes
  13078. // childrens add themselves to their parents since we are iterating in order
  13079. if (parent) {
  13080. var parentIndex = acc.cacheRef[parent];
  13081. var parentRecord = acc.contentBlocks[parentIndex];
  13082. // if parent has text we need to split it into a separate unstyled element
  13083. if (parentRecord.getChildKeys().isEmpty() && parentRecord.getText()) {
  13084. var parentCharacterList = parentRecord.getCharacterList();
  13085. var parentText = parentRecord.getText();
  13086. parentTextNodeKey = generateRandomKey_1();
  13087. var textNode = new ContentBlockNode_1({
  13088. key: parentTextNodeKey,
  13089. text: parentText,
  13090. characterList: parentCharacterList,
  13091. parent: parent,
  13092. nextSibling: key
  13093. });
  13094. acc.contentBlocks.push(textNode);
  13095. parentRecord = parentRecord.withMutations(function (block) {
  13096. block.set('characterList', List$a()).set('text', '').set('children', parentRecord.children.push(textNode.getKey()));
  13097. });
  13098. }
  13099. acc.contentBlocks[parentIndex] = parentRecord.set('children', parentRecord.children.push(key));
  13100. }
  13101. var blockNode = new BlockNodeRecord({
  13102. key: key,
  13103. parent: parent,
  13104. type: type,
  13105. depth: depth,
  13106. text: textBlock,
  13107. characterList: characterList,
  13108. prevSibling: parentTextNodeKey || (index === 0 || rawBlocks[index - 1].parent !== parent ? null : rawBlocks[index - 1].key),
  13109. nextSibling: index === rawBlocks.length - 1 || rawBlocks[index + 1].parent !== parent ? null : rawBlocks[index + 1].key
  13110. });
  13111. // insert node
  13112. acc.contentBlocks.push(blockNode);
  13113. // cache ref for building links
  13114. acc.cacheRef[blockNode.key] = index;
  13115. return acc;
  13116. }, initialState).contentBlocks;
  13117. };
  13118. var convertFromHTMLtoContentBlocks = function convertFromHTMLtoContentBlocks(html) {
  13119. var DOMBuilder = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : getSafeBodyFromHTML_1;
  13120. var blockRenderMap = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : DefaultDraftBlockRenderMap_1;
  13121. // Be ABSOLUTELY SURE that the dom builder you pass here won't execute
  13122. // arbitrary code in whatever environment you're running this in. For an
  13123. // example of how we try to do this in-browser, see getSafeBodyFromHTML.
  13124. // TODO: replace DraftEntity with an OrderedMap here
  13125. var chunkData = getChunkForHTML(html, DOMBuilder, blockRenderMap, DraftEntity_1);
  13126. if (chunkData == null) {
  13127. return null;
  13128. }
  13129. var chunk = chunkData.chunk,
  13130. entityMap = chunkData.entityMap;
  13131. var contentBlocks = convertChunkToContentBlocks(chunk);
  13132. return {
  13133. contentBlocks: contentBlocks,
  13134. entityMap: entityMap
  13135. };
  13136. };
  13137. var convertFromHTMLToContentBlocks = convertFromHTMLtoContentBlocks;
  13138. var List$b = immutable.List,
  13139. Repeat$6 = immutable.Repeat;
  13140. var ContentBlockRecord$2 = ContentBlock_1;
  13141. var DraftPasteProcessor = {
  13142. processHTML: function processHTML(html, blockRenderMap) {
  13143. return convertFromHTMLToContentBlocks(html, getSafeBodyFromHTML_1, blockRenderMap);
  13144. },
  13145. processText: function processText(textBlocks, character, type) {
  13146. return textBlocks.reduce(function (acc, textLine, index) {
  13147. textLine = sanitizeDraftText_1(textLine);
  13148. var key = generateRandomKey_1();
  13149. var blockNodeConfig = {
  13150. key: key,
  13151. type: type,
  13152. text: textLine,
  13153. characterList: List$b(Repeat$6(character, textLine.length))
  13154. };
  13155. acc.push(new ContentBlockRecord$2(blockNodeConfig));
  13156. return acc;
  13157. }, []);
  13158. }
  13159. };
  13160. var DraftPasteProcessor_1 = DraftPasteProcessor;
  13161. /**
  13162. * Copyright (c) 2013-present, Facebook, Inc.
  13163. * All rights reserved.
  13164. *
  13165. * This source code is licensed under the BSD-style license found in the
  13166. * LICENSE file in the root directory of this source tree. An additional grant
  13167. * of patent rights can be found in the PATENTS file in the same directory.
  13168. *
  13169. * @providesModule adjustBlockDepthForContentState
  13170. * @format
  13171. *
  13172. */
  13173. function adjustBlockDepthForContentState(contentState, selectionState, adjustment, maxDepth) {
  13174. var startKey = selectionState.getStartKey();
  13175. var endKey = selectionState.getEndKey();
  13176. var blockMap = contentState.getBlockMap();
  13177. var blocks = blockMap.toSeq().skipUntil(function (_, k) {
  13178. return k === startKey;
  13179. }).takeUntil(function (_, k) {
  13180. return k === endKey;
  13181. }).concat([[endKey, blockMap.get(endKey)]]).map(function (block) {
  13182. var depth = block.getDepth() + adjustment;
  13183. depth = Math.max(0, Math.min(depth, maxDepth));
  13184. return block.set('depth', depth);
  13185. });
  13186. blockMap = blockMap.merge(blocks);
  13187. return contentState.merge({
  13188. blockMap: blockMap,
  13189. selectionBefore: selectionState,
  13190. selectionAfter: selectionState
  13191. });
  13192. }
  13193. var adjustBlockDepthForContentState_1 = adjustBlockDepthForContentState;
  13194. var RichTextEditorUtil = {
  13195. currentBlockContainsLink: function currentBlockContainsLink(editorState) {
  13196. var selection = editorState.getSelection();
  13197. var contentState = editorState.getCurrentContent();
  13198. var entityMap = contentState.getEntityMap();
  13199. return contentState.getBlockForKey(selection.getAnchorKey()).getCharacterList().slice(selection.getStartOffset(), selection.getEndOffset()).some(function (v) {
  13200. var entity = v.getEntity();
  13201. return !!entity && entityMap.__get(entity).getType() === 'LINK';
  13202. });
  13203. },
  13204. getCurrentBlockType: function getCurrentBlockType(editorState) {
  13205. var selection = editorState.getSelection();
  13206. return editorState.getCurrentContent().getBlockForKey(selection.getStartKey()).getType();
  13207. },
  13208. getDataObjectForLinkURL: function getDataObjectForLinkURL(uri) {
  13209. return { url: uri.toString() };
  13210. },
  13211. handleKeyCommand: function handleKeyCommand(editorState, command) {
  13212. switch (command) {
  13213. case 'bold':
  13214. return RichTextEditorUtil.toggleInlineStyle(editorState, 'BOLD');
  13215. case 'italic':
  13216. return RichTextEditorUtil.toggleInlineStyle(editorState, 'ITALIC');
  13217. case 'underline':
  13218. return RichTextEditorUtil.toggleInlineStyle(editorState, 'UNDERLINE');
  13219. case 'code':
  13220. return RichTextEditorUtil.toggleCode(editorState);
  13221. case 'backspace':
  13222. case 'backspace-word':
  13223. case 'backspace-to-start-of-line':
  13224. return RichTextEditorUtil.onBackspace(editorState);
  13225. case 'delete':
  13226. case 'delete-word':
  13227. case 'delete-to-end-of-block':
  13228. return RichTextEditorUtil.onDelete(editorState);
  13229. default:
  13230. // they may have custom editor commands; ignore those
  13231. return null;
  13232. }
  13233. },
  13234. insertSoftNewline: function insertSoftNewline(editorState) {
  13235. var contentState = DraftModifier_1.insertText(editorState.getCurrentContent(), editorState.getSelection(), '\n', editorState.getCurrentInlineStyle(), null);
  13236. var newEditorState = EditorState_1.push(editorState, contentState, 'insert-characters');
  13237. return EditorState_1.forceSelection(newEditorState, contentState.getSelectionAfter());
  13238. },
  13239. /**
  13240. * For collapsed selections at the start of styled blocks, backspace should
  13241. * just remove the existing style.
  13242. */
  13243. onBackspace: function onBackspace(editorState) {
  13244. var selection = editorState.getSelection();
  13245. if (!selection.isCollapsed() || selection.getAnchorOffset() || selection.getFocusOffset()) {
  13246. return null;
  13247. }
  13248. // First, try to remove a preceding atomic block.
  13249. var content = editorState.getCurrentContent();
  13250. var startKey = selection.getStartKey();
  13251. var blockBefore = content.getBlockBefore(startKey);
  13252. if (blockBefore && blockBefore.getType() === 'atomic') {
  13253. var blockMap = content.getBlockMap()['delete'](blockBefore.getKey());
  13254. var withoutAtomicBlock = content.merge({
  13255. blockMap: blockMap,
  13256. selectionAfter: selection
  13257. });
  13258. if (withoutAtomicBlock !== content) {
  13259. return EditorState_1.push(editorState, withoutAtomicBlock, 'remove-range');
  13260. }
  13261. }
  13262. // If that doesn't succeed, try to remove the current block style.
  13263. var withoutBlockStyle = RichTextEditorUtil.tryToRemoveBlockStyle(editorState);
  13264. if (withoutBlockStyle) {
  13265. return EditorState_1.push(editorState, withoutBlockStyle, 'change-block-type');
  13266. }
  13267. return null;
  13268. },
  13269. onDelete: function onDelete(editorState) {
  13270. var selection = editorState.getSelection();
  13271. if (!selection.isCollapsed()) {
  13272. return null;
  13273. }
  13274. var content = editorState.getCurrentContent();
  13275. var startKey = selection.getStartKey();
  13276. var block = content.getBlockForKey(startKey);
  13277. var length = block.getLength();
  13278. // The cursor is somewhere within the text. Behave normally.
  13279. if (selection.getStartOffset() < length) {
  13280. return null;
  13281. }
  13282. var blockAfter = content.getBlockAfter(startKey);
  13283. if (!blockAfter || blockAfter.getType() !== 'atomic') {
  13284. return null;
  13285. }
  13286. var atomicBlockTarget = selection.merge({
  13287. focusKey: blockAfter.getKey(),
  13288. focusOffset: blockAfter.getLength()
  13289. });
  13290. var withoutAtomicBlock = DraftModifier_1.removeRange(content, atomicBlockTarget, 'forward');
  13291. if (withoutAtomicBlock !== content) {
  13292. return EditorState_1.push(editorState, withoutAtomicBlock, 'remove-range');
  13293. }
  13294. return null;
  13295. },
  13296. onTab: function onTab(event, editorState, maxDepth) {
  13297. var selection = editorState.getSelection();
  13298. var key = selection.getAnchorKey();
  13299. if (key !== selection.getFocusKey()) {
  13300. return editorState;
  13301. }
  13302. var content = editorState.getCurrentContent();
  13303. var block = content.getBlockForKey(key);
  13304. var type = block.getType();
  13305. if (type !== 'unordered-list-item' && type !== 'ordered-list-item') {
  13306. return editorState;
  13307. }
  13308. event.preventDefault();
  13309. // Only allow indenting one level beyond the block above, and only if
  13310. // the block above is a list item as well.
  13311. var blockAbove = content.getBlockBefore(key);
  13312. if (!blockAbove) {
  13313. return editorState;
  13314. }
  13315. var typeAbove = blockAbove.getType();
  13316. if (typeAbove !== 'unordered-list-item' && typeAbove !== 'ordered-list-item') {
  13317. return editorState;
  13318. }
  13319. var depth = block.getDepth();
  13320. if (!event.shiftKey && depth === maxDepth) {
  13321. return editorState;
  13322. }
  13323. maxDepth = Math.min(blockAbove.getDepth() + 1, maxDepth);
  13324. var withAdjustment = adjustBlockDepthForContentState_1(content, selection, event.shiftKey ? -1 : 1, maxDepth);
  13325. return EditorState_1.push(editorState, withAdjustment, 'adjust-depth');
  13326. },
  13327. toggleBlockType: function toggleBlockType(editorState, blockType) {
  13328. var selection = editorState.getSelection();
  13329. var startKey = selection.getStartKey();
  13330. var endKey = selection.getEndKey();
  13331. var content = editorState.getCurrentContent();
  13332. var target = selection;
  13333. // Triple-click can lead to a selection that includes offset 0 of the
  13334. // following block. The `SelectionState` for this case is accurate, but
  13335. // we should avoid toggling block type for the trailing block because it
  13336. // is a confusing interaction.
  13337. if (startKey !== endKey && selection.getEndOffset() === 0) {
  13338. var blockBefore = nullthrows_1(content.getBlockBefore(endKey));
  13339. endKey = blockBefore.getKey();
  13340. target = target.merge({
  13341. anchorKey: startKey,
  13342. anchorOffset: selection.getStartOffset(),
  13343. focusKey: endKey,
  13344. focusOffset: blockBefore.getLength(),
  13345. isBackward: false
  13346. });
  13347. }
  13348. var hasAtomicBlock = content.getBlockMap().skipWhile(function (_, k) {
  13349. return k !== startKey;
  13350. }).reverse().skipWhile(function (_, k) {
  13351. return k !== endKey;
  13352. }).some(function (v) {
  13353. return v.getType() === 'atomic';
  13354. });
  13355. if (hasAtomicBlock) {
  13356. return editorState;
  13357. }
  13358. var typeToSet = content.getBlockForKey(startKey).getType() === blockType ? 'unstyled' : blockType;
  13359. return EditorState_1.push(editorState, DraftModifier_1.setBlockType(content, target, typeToSet), 'change-block-type');
  13360. },
  13361. toggleCode: function toggleCode(editorState) {
  13362. var selection = editorState.getSelection();
  13363. var anchorKey = selection.getAnchorKey();
  13364. var focusKey = selection.getFocusKey();
  13365. if (selection.isCollapsed() || anchorKey !== focusKey) {
  13366. return RichTextEditorUtil.toggleBlockType(editorState, 'code-block');
  13367. }
  13368. return RichTextEditorUtil.toggleInlineStyle(editorState, 'CODE');
  13369. },
  13370. /**
  13371. * Toggle the specified inline style for the selection. If the
  13372. * user's selection is collapsed, apply or remove the style for the
  13373. * internal state. If it is not collapsed, apply the change directly
  13374. * to the document state.
  13375. */
  13376. toggleInlineStyle: function toggleInlineStyle(editorState, inlineStyle) {
  13377. var selection = editorState.getSelection();
  13378. var currentStyle = editorState.getCurrentInlineStyle();
  13379. // If the selection is collapsed, toggle the specified style on or off and
  13380. // set the result as the new inline style override. This will then be
  13381. // used as the inline style for the next character to be inserted.
  13382. if (selection.isCollapsed()) {
  13383. return EditorState_1.setInlineStyleOverride(editorState, currentStyle.has(inlineStyle) ? currentStyle.remove(inlineStyle) : currentStyle.add(inlineStyle));
  13384. }
  13385. // If characters are selected, immediately apply or remove the
  13386. // inline style on the document state itself.
  13387. var content = editorState.getCurrentContent();
  13388. var newContent;
  13389. // If the style is already present for the selection range, remove it.
  13390. // Otherwise, apply it.
  13391. if (currentStyle.has(inlineStyle)) {
  13392. newContent = DraftModifier_1.removeInlineStyle(content, selection, inlineStyle);
  13393. } else {
  13394. newContent = DraftModifier_1.applyInlineStyle(content, selection, inlineStyle);
  13395. }
  13396. return EditorState_1.push(editorState, newContent, 'change-inline-style');
  13397. },
  13398. toggleLink: function toggleLink(editorState, targetSelection, entityKey) {
  13399. var withoutLink = DraftModifier_1.applyEntity(editorState.getCurrentContent(), targetSelection, entityKey);
  13400. return EditorState_1.push(editorState, withoutLink, 'apply-entity');
  13401. },
  13402. /**
  13403. * When a collapsed cursor is at the start of the first styled block, or
  13404. * an empty styled block, changes block to 'unstyled'. Returns null if
  13405. * block or selection does not meet that criteria.
  13406. */
  13407. tryToRemoveBlockStyle: function tryToRemoveBlockStyle(editorState) {
  13408. var selection = editorState.getSelection();
  13409. var offset = selection.getAnchorOffset();
  13410. if (selection.isCollapsed() && offset === 0) {
  13411. var key = selection.getAnchorKey();
  13412. var content = editorState.getCurrentContent();
  13413. var block = content.getBlockForKey(key);
  13414. var firstBlock = content.getFirstBlock();
  13415. if (block.getLength() > 0 && block !== firstBlock) {
  13416. return null;
  13417. }
  13418. var type = block.getType();
  13419. var blockBefore = content.getBlockBefore(key);
  13420. if (type === 'code-block' && blockBefore && blockBefore.getType() === 'code-block' && blockBefore.getLength() !== 0) {
  13421. return null;
  13422. }
  13423. if (type !== 'unstyled') {
  13424. return DraftModifier_1.setBlockType(content, selection, 'unstyled');
  13425. }
  13426. }
  13427. return null;
  13428. }
  13429. };
  13430. var RichTextEditorUtil_1 = RichTextEditorUtil;
  13431. /**
  13432. * Copyright (c) 2013-present, Facebook, Inc.
  13433. * All rights reserved.
  13434. *
  13435. * This source code is licensed under the BSD-style license found in the
  13436. * LICENSE file in the root directory of this source tree. An additional grant
  13437. * of patent rights can be found in the PATENTS file in the same directory.
  13438. *
  13439. * @providesModule splitTextIntoTextBlocks
  13440. * @format
  13441. *
  13442. */
  13443. var NEWLINE_REGEX = /\r\n?|\n/g;
  13444. function splitTextIntoTextBlocks(text) {
  13445. return text.split(NEWLINE_REGEX);
  13446. }
  13447. var splitTextIntoTextBlocks_1 = splitTextIntoTextBlocks;
  13448. /**
  13449. * Paste content.
  13450. */
  13451. function editOnPaste(editor, e) {
  13452. e.preventDefault();
  13453. var data = new DataTransfer_1(e.clipboardData);
  13454. // Get files, unless this is likely to be a string the user wants inline.
  13455. if (!data.isRichText()) {
  13456. var files = data.getFiles();
  13457. var defaultFileText = data.getText();
  13458. if (files.length > 0) {
  13459. // Allow customized paste handling for images, etc. Otherwise, fall
  13460. // through to insert text contents into the editor.
  13461. if (editor.props.handlePastedFiles && isEventHandled_1(editor.props.handlePastedFiles(files))) {
  13462. return;
  13463. }
  13464. getTextContentFromFiles_1(files, function ( /*string*/fileText) {
  13465. fileText = fileText || defaultFileText;
  13466. if (!fileText) {
  13467. return;
  13468. }
  13469. var editorState = editor._latestEditorState;
  13470. var blocks = splitTextIntoTextBlocks_1(fileText);
  13471. var character = CharacterMetadata_1.create({
  13472. style: editorState.getCurrentInlineStyle(),
  13473. entity: getEntityKeyForSelection_1(editorState.getCurrentContent(), editorState.getSelection())
  13474. });
  13475. var currentBlockType = RichTextEditorUtil_1.getCurrentBlockType(editorState);
  13476. var text = DraftPasteProcessor_1.processText(blocks, character, currentBlockType);
  13477. var fragment = BlockMapBuilder_1.createFromArray(text);
  13478. var withInsertedText = DraftModifier_1.replaceWithFragment(editorState.getCurrentContent(), editorState.getSelection(), fragment);
  13479. editor.update(EditorState_1.push(editorState, withInsertedText, 'insert-fragment'));
  13480. });
  13481. return;
  13482. }
  13483. }
  13484. var textBlocks = [];
  13485. var text = data.getText();
  13486. var html = data.getHTML();
  13487. var editorState = editor._latestEditorState;
  13488. if (editor.props.handlePastedText && isEventHandled_1(editor.props.handlePastedText(text, html, editorState))) {
  13489. return;
  13490. }
  13491. if (text) {
  13492. textBlocks = splitTextIntoTextBlocks_1(text);
  13493. }
  13494. if (!editor.props.stripPastedStyles) {
  13495. // If the text from the paste event is rich content that matches what we
  13496. // already have on the internal clipboard, assume that we should just use
  13497. // the clipboard fragment for the paste. This will allow us to preserve
  13498. // styling and entities, if any are present. Note that newlines are
  13499. // stripped during comparison -- this is because copy/paste within the
  13500. // editor in Firefox and IE will not include empty lines. The resulting
  13501. // paste will preserve the newlines correctly.
  13502. var internalClipboard = editor.getClipboard();
  13503. if (data.isRichText() && internalClipboard) {
  13504. if (
  13505. // If the editorKey is present in the pasted HTML, it should be safe to
  13506. // assume this is an internal paste.
  13507. html.indexOf(editor.getEditorKey()) !== -1 ||
  13508. // The copy may have been made within a single block, in which case the
  13509. // editor key won't be part of the paste. In this case, just check
  13510. // whether the pasted text matches the internal clipboard.
  13511. textBlocks.length === 1 && internalClipboard.size === 1 && internalClipboard.first().getText() === text) {
  13512. editor.update(insertFragment$1(editor._latestEditorState, internalClipboard));
  13513. return;
  13514. }
  13515. } else if (internalClipboard && data.types.includes('com.apple.webarchive') && !data.types.includes('text/html') && areTextBlocksAndClipboardEqual(textBlocks, internalClipboard)) {
  13516. // Safari does not properly store text/html in some cases.
  13517. // Use the internalClipboard if present and equal to what is on
  13518. // the clipboard. See https://bugs.webkit.org/show_bug.cgi?id=19893.
  13519. editor.update(insertFragment$1(editor._latestEditorState, internalClipboard));
  13520. return;
  13521. }
  13522. // If there is html paste data, try to parse that.
  13523. if (html) {
  13524. var htmlFragment = DraftPasteProcessor_1.processHTML(html, editor.props.blockRenderMap);
  13525. if (htmlFragment) {
  13526. var contentBlocks = htmlFragment.contentBlocks,
  13527. entityMap = htmlFragment.entityMap;
  13528. if (contentBlocks) {
  13529. var htmlMap = BlockMapBuilder_1.createFromArray(contentBlocks);
  13530. editor.update(insertFragment$1(editor._latestEditorState, htmlMap, entityMap));
  13531. return;
  13532. }
  13533. }
  13534. }
  13535. // Otherwise, create a new fragment from our pasted text. Also
  13536. // empty the internal clipboard, since it's no longer valid.
  13537. editor.setClipboard(null);
  13538. }
  13539. if (textBlocks.length) {
  13540. var character = CharacterMetadata_1.create({
  13541. style: editorState.getCurrentInlineStyle(),
  13542. entity: getEntityKeyForSelection_1(editorState.getCurrentContent(), editorState.getSelection())
  13543. });
  13544. var currentBlockType = RichTextEditorUtil_1.getCurrentBlockType(editorState);
  13545. var textFragment = DraftPasteProcessor_1.processText(textBlocks, character, currentBlockType);
  13546. var textMap = BlockMapBuilder_1.createFromArray(textFragment);
  13547. editor.update(insertFragment$1(editor._latestEditorState, textMap));
  13548. }
  13549. }
  13550. function insertFragment$1(editorState, fragment, entityMap) {
  13551. var newContent = DraftModifier_1.replaceWithFragment(editorState.getCurrentContent(), editorState.getSelection(), fragment);
  13552. // TODO: merge the entity map once we stop using DraftEntity
  13553. // like this:
  13554. // const mergedEntityMap = newContent.getEntityMap().merge(entityMap);
  13555. return EditorState_1.push(editorState, newContent.set('entityMap', entityMap), 'insert-fragment');
  13556. }
  13557. function areTextBlocksAndClipboardEqual(textBlocks, blockMap) {
  13558. return textBlocks.length === blockMap.size && blockMap.valueSeq().every(function (block, ii) {
  13559. return block.getText() === textBlocks[ii];
  13560. });
  13561. }
  13562. var editOnPaste_1 = editOnPaste;
  13563. /**
  13564. * Convert the current selection range to an anchor/focus pair of offset keys
  13565. * and values that can be interpreted by components.
  13566. */
  13567. function getDraftEditorSelection(editorState, root) {
  13568. var selection = commonjsGlobal.getSelection();
  13569. // No active selection.
  13570. if (selection.rangeCount === 0) {
  13571. return {
  13572. selectionState: editorState.getSelection().set('hasFocus', false),
  13573. needsRecovery: false
  13574. };
  13575. }
  13576. return getDraftEditorSelectionWithNodes_1(editorState, root, selection.anchorNode, selection.anchorOffset, selection.focusNode, selection.focusOffset);
  13577. }
  13578. var getDraftEditorSelection_1 = getDraftEditorSelection;
  13579. function editOnSelect(editor) {
  13580. if (editor._blockSelectEvents || editor._latestEditorState !== editor.props.editorState) {
  13581. return;
  13582. }
  13583. var editorState = editor.props.editorState;
  13584. var editorNode = reactDom.findDOMNode(editor.editorContainer);
  13585. !editorNode ? process.env.NODE_ENV !== 'production' ? invariant_1(false, 'Missing editorNode') : invariant_1(false) : void 0;
  13586. !(editorNode.firstChild instanceof HTMLElement) ? process.env.NODE_ENV !== 'production' ? invariant_1(false, 'editorNode.firstChild is not an HTMLElement') : invariant_1(false) : void 0;
  13587. var documentSelection = getDraftEditorSelection_1(editorState, editorNode.firstChild);
  13588. var updatedSelectionState = documentSelection.selectionState;
  13589. if (updatedSelectionState !== editorState.getSelection()) {
  13590. if (documentSelection.needsRecovery) {
  13591. editorState = EditorState_1.forceSelection(editorState, updatedSelectionState);
  13592. } else {
  13593. editorState = EditorState_1.acceptSelection(editorState, updatedSelectionState);
  13594. }
  13595. editor.update(editorState);
  13596. }
  13597. }
  13598. var editOnSelect_1 = editOnSelect;
  13599. var DraftEditorEditHandler = {
  13600. onBeforeInput: editOnBeforeInput_1,
  13601. onBlur: editOnBlur_1,
  13602. onCompositionStart: editOnCompositionStart_1,
  13603. onCopy: editOnCopy_1,
  13604. onCut: editOnCut_1,
  13605. onDragOver: editOnDragOver_1,
  13606. onDragStart: editOnDragStart_1,
  13607. onFocus: editOnFocus_1,
  13608. onInput: editOnInput_1,
  13609. onKeyDown: editOnKeyDown_1,
  13610. onPaste: editOnPaste_1,
  13611. onSelect: editOnSelect_1
  13612. };
  13613. var DraftEditorEditHandler_1 = DraftEditorEditHandler;
  13614. function _classCallCheck$f(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  13615. function _possibleConstructorReturn$a(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }
  13616. function _inherits$a(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
  13617. /**
  13618. * This component is responsible for rendering placeholder text for the
  13619. * `DraftEditor` component.
  13620. *
  13621. * Override placeholder style via CSS.
  13622. */
  13623. var DraftEditorPlaceholder = function (_React$Component) {
  13624. _inherits$a(DraftEditorPlaceholder, _React$Component);
  13625. function DraftEditorPlaceholder() {
  13626. _classCallCheck$f(this, DraftEditorPlaceholder);
  13627. return _possibleConstructorReturn$a(this, _React$Component.apply(this, arguments));
  13628. }
  13629. DraftEditorPlaceholder.prototype.shouldComponentUpdate = function shouldComponentUpdate(nextProps) {
  13630. return this.props.text !== nextProps.text || this.props.editorState.getSelection().getHasFocus() !== nextProps.editorState.getSelection().getHasFocus();
  13631. };
  13632. DraftEditorPlaceholder.prototype.render = function render() {
  13633. var hasFocus = this.props.editorState.getSelection().getHasFocus();
  13634. var className = cx_1({
  13635. 'public/DraftEditorPlaceholder/root': true,
  13636. 'public/DraftEditorPlaceholder/hasFocus': hasFocus
  13637. });
  13638. var contentStyle = {
  13639. whiteSpace: 'pre-wrap'
  13640. };
  13641. return React.createElement(
  13642. 'div',
  13643. { className: className },
  13644. React.createElement(
  13645. 'div',
  13646. {
  13647. className: cx_1('public/DraftEditorPlaceholder/inner'),
  13648. id: this.props.accessibilityID,
  13649. style: contentStyle },
  13650. this.props.text
  13651. )
  13652. );
  13653. };
  13654. return DraftEditorPlaceholder;
  13655. }(React.Component);
  13656. var DraftEditorPlaceholder_react = DraftEditorPlaceholder;
  13657. var isOSX$1 = UserAgent_1.isPlatform('Mac OS X');
  13658. var isWindows = UserAgent_1.isPlatform('Windows');
  13659. // Firefox on OSX had a bug resulting in navigation instead of cursor movement.
  13660. // This bug was fixed in Firefox 29. Feature detection is virtually impossible
  13661. // so we just check the version number. See #342765.
  13662. var shouldFixFirefoxMovement = isOSX$1 && UserAgent_1.isBrowser('Firefox < 29');
  13663. var hasCommandModifier = KeyBindingUtil_1.hasCommandModifier,
  13664. isCtrlKeyCommand = KeyBindingUtil_1.isCtrlKeyCommand;
  13665. function shouldRemoveWord(e) {
  13666. return isOSX$1 && e.altKey || isCtrlKeyCommand(e);
  13667. }
  13668. /**
  13669. * Get the appropriate undo/redo command for a Z key command.
  13670. */
  13671. function getZCommand(e) {
  13672. if (!hasCommandModifier(e)) {
  13673. return null;
  13674. }
  13675. return e.shiftKey ? 'redo' : 'undo';
  13676. }
  13677. function getDeleteCommand(e) {
  13678. // Allow default "cut" behavior for Windows on Shift + Delete.
  13679. if (isWindows && e.shiftKey) {
  13680. return null;
  13681. }
  13682. return shouldRemoveWord(e) ? 'delete-word' : 'delete';
  13683. }
  13684. function getBackspaceCommand(e) {
  13685. if (hasCommandModifier(e) && isOSX$1) {
  13686. return 'backspace-to-start-of-line';
  13687. }
  13688. return shouldRemoveWord(e) ? 'backspace-word' : 'backspace';
  13689. }
  13690. /**
  13691. * Retrieve a bound key command for the given event.
  13692. */
  13693. function getDefaultKeyBinding(e) {
  13694. switch (e.keyCode) {
  13695. case 66:
  13696. // B
  13697. return hasCommandModifier(e) ? 'bold' : null;
  13698. case 68:
  13699. // D
  13700. return isCtrlKeyCommand(e) ? 'delete' : null;
  13701. case 72:
  13702. // H
  13703. return isCtrlKeyCommand(e) ? 'backspace' : null;
  13704. case 73:
  13705. // I
  13706. return hasCommandModifier(e) ? 'italic' : null;
  13707. case 74:
  13708. // J
  13709. return hasCommandModifier(e) ? 'code' : null;
  13710. case 75:
  13711. // K
  13712. return !isWindows && isCtrlKeyCommand(e) ? 'secondary-cut' : null;
  13713. case 77:
  13714. // M
  13715. return isCtrlKeyCommand(e) ? 'split-block' : null;
  13716. case 79:
  13717. // O
  13718. return isCtrlKeyCommand(e) ? 'split-block' : null;
  13719. case 84:
  13720. // T
  13721. return isOSX$1 && isCtrlKeyCommand(e) ? 'transpose-characters' : null;
  13722. case 85:
  13723. // U
  13724. return hasCommandModifier(e) ? 'underline' : null;
  13725. case 87:
  13726. // W
  13727. return isOSX$1 && isCtrlKeyCommand(e) ? 'backspace-word' : null;
  13728. case 89:
  13729. // Y
  13730. if (isCtrlKeyCommand(e)) {
  13731. return isWindows ? 'redo' : 'secondary-paste';
  13732. }
  13733. return null;
  13734. case 90:
  13735. // Z
  13736. return getZCommand(e) || null;
  13737. case Keys.RETURN:
  13738. return 'split-block';
  13739. case Keys.DELETE:
  13740. return getDeleteCommand(e);
  13741. case Keys.BACKSPACE:
  13742. return getBackspaceCommand(e);
  13743. // LEFT/RIGHT handlers serve as a workaround for a Firefox bug.
  13744. case Keys.LEFT:
  13745. return shouldFixFirefoxMovement && hasCommandModifier(e) ? 'move-selection-to-start-of-block' : null;
  13746. case Keys.RIGHT:
  13747. return shouldFixFirefoxMovement && hasCommandModifier(e) ? 'move-selection-to-end-of-block' : null;
  13748. default:
  13749. return null;
  13750. }
  13751. }
  13752. var getDefaultKeyBinding_1 = getDefaultKeyBinding;
  13753. var _extends$5 = objectAssign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };
  13754. function _classCallCheck$g(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  13755. function _possibleConstructorReturn$b(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }
  13756. function _inherits$b(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
  13757. var isIE = UserAgent_1.isBrowser('IE');
  13758. // IE does not support the `input` event on contentEditable, so we can't
  13759. // observe spellcheck behavior.
  13760. var allowSpellCheck = !isIE;
  13761. // Define a set of handler objects to correspond to each possible `mode`
  13762. // of editor behavior.
  13763. var handlerMap = {
  13764. edit: DraftEditorEditHandler_1,
  13765. composite: DraftEditorCompositionHandler_1,
  13766. drag: DraftEditorDragHandler_1,
  13767. cut: null,
  13768. render: null
  13769. };
  13770. /**
  13771. * `DraftEditor` is the root editor component. It composes a `contentEditable`
  13772. * div, and provides a wide variety of useful function props for managing the
  13773. * state of the editor. See `DraftEditorProps` for details.
  13774. */
  13775. var DraftEditor = function (_React$Component) {
  13776. _inherits$b(DraftEditor, _React$Component);
  13777. function DraftEditor(props) {
  13778. _classCallCheck$g(this, DraftEditor);
  13779. var _this = _possibleConstructorReturn$b(this, _React$Component.call(this, props));
  13780. _this.focus = function (scrollPosition) {
  13781. var editorState = _this.props.editorState;
  13782. var alreadyHasFocus = editorState.getSelection().getHasFocus();
  13783. var editorNode = reactDom.findDOMNode(_this.editor);
  13784. if (!editorNode) {
  13785. // once in a while people call 'focus' in a setTimeout, and the node has
  13786. // been deleted, so it can be null in that case.
  13787. return;
  13788. }
  13789. var scrollParent = Style_1.getScrollParent(editorNode);
  13790. var _ref = scrollPosition || getScrollPosition_1(scrollParent),
  13791. x = _ref.x,
  13792. y = _ref.y;
  13793. !(editorNode instanceof HTMLElement) ? process.env.NODE_ENV !== 'production' ? invariant_1(false, 'editorNode is not an HTMLElement') : invariant_1(false) : void 0;
  13794. editorNode.focus();
  13795. // Restore scroll position
  13796. if (scrollParent === window) {
  13797. window.scrollTo(x, y);
  13798. } else {
  13799. Scroll_1.setTop(scrollParent, y);
  13800. }
  13801. // On Chrome and Safari, calling focus on contenteditable focuses the
  13802. // cursor at the first character. This is something you don't expect when
  13803. // you're clicking on an input element but not directly on a character.
  13804. // Put the cursor back where it was before the blur.
  13805. if (!alreadyHasFocus) {
  13806. _this.update(EditorState_1.forceSelection(editorState, editorState.getSelection()));
  13807. }
  13808. };
  13809. _this.blur = function () {
  13810. var editorNode = reactDom.findDOMNode(_this.editor);
  13811. !(editorNode instanceof HTMLElement) ? process.env.NODE_ENV !== 'production' ? invariant_1(false, 'editorNode is not an HTMLElement') : invariant_1(false) : void 0;
  13812. editorNode.blur();
  13813. };
  13814. _this.setMode = function (mode) {
  13815. _this._handler = handlerMap[mode];
  13816. };
  13817. _this.exitCurrentMode = function () {
  13818. _this.setMode('edit');
  13819. };
  13820. _this.restoreEditorDOM = function (scrollPosition) {
  13821. _this.setState({ contentsKey: _this.state.contentsKey + 1 }, function () {
  13822. _this.focus(scrollPosition);
  13823. });
  13824. };
  13825. _this.setClipboard = function (clipboard) {
  13826. _this._clipboard = clipboard;
  13827. };
  13828. _this.getClipboard = function () {
  13829. return _this._clipboard;
  13830. };
  13831. _this.update = function (editorState) {
  13832. _this._latestEditorState = editorState;
  13833. _this.props.onChange(editorState);
  13834. };
  13835. _this.onDragEnter = function () {
  13836. _this._dragCount++;
  13837. };
  13838. _this.onDragLeave = function () {
  13839. _this._dragCount--;
  13840. if (_this._dragCount === 0) {
  13841. _this.exitCurrentMode();
  13842. }
  13843. };
  13844. _this._blockSelectEvents = false;
  13845. _this._clipboard = null;
  13846. _this._handler = null;
  13847. _this._dragCount = 0;
  13848. _this._editorKey = props.editorKey || generateRandomKey_1();
  13849. _this._placeholderAccessibilityID = 'placeholder-' + _this._editorKey;
  13850. _this._latestEditorState = props.editorState;
  13851. _this._latestCommittedEditorState = props.editorState;
  13852. _this._onBeforeInput = _this._buildHandler('onBeforeInput');
  13853. _this._onBlur = _this._buildHandler('onBlur');
  13854. _this._onCharacterData = _this._buildHandler('onCharacterData');
  13855. _this._onCompositionEnd = _this._buildHandler('onCompositionEnd');
  13856. _this._onCompositionStart = _this._buildHandler('onCompositionStart');
  13857. _this._onCopy = _this._buildHandler('onCopy');
  13858. _this._onCut = _this._buildHandler('onCut');
  13859. _this._onDragEnd = _this._buildHandler('onDragEnd');
  13860. _this._onDragOver = _this._buildHandler('onDragOver');
  13861. _this._onDragStart = _this._buildHandler('onDragStart');
  13862. _this._onDrop = _this._buildHandler('onDrop');
  13863. _this._onInput = _this._buildHandler('onInput');
  13864. _this._onFocus = _this._buildHandler('onFocus');
  13865. _this._onKeyDown = _this._buildHandler('onKeyDown');
  13866. _this._onKeyPress = _this._buildHandler('onKeyPress');
  13867. _this._onKeyUp = _this._buildHandler('onKeyUp');
  13868. _this._onMouseDown = _this._buildHandler('onMouseDown');
  13869. _this._onMouseUp = _this._buildHandler('onMouseUp');
  13870. _this._onPaste = _this._buildHandler('onPaste');
  13871. _this._onSelect = _this._buildHandler('onSelect');
  13872. _this.getEditorKey = function () {
  13873. return _this._editorKey;
  13874. };
  13875. // See `restoreEditorDOM()`.
  13876. _this.state = { contentsKey: 0 };
  13877. return _this;
  13878. }
  13879. /**
  13880. * Build a method that will pass the event to the specified handler method.
  13881. * This allows us to look up the correct handler function for the current
  13882. * editor mode, if any has been specified.
  13883. */
  13884. /**
  13885. * Define proxies that can route events to the current handler.
  13886. */
  13887. DraftEditor.prototype._buildHandler = function _buildHandler(eventName) {
  13888. var _this2 = this;
  13889. return function (e) {
  13890. if (!_this2.props.readOnly) {
  13891. var method = _this2._handler && _this2._handler[eventName];
  13892. method && method(_this2, e);
  13893. }
  13894. };
  13895. };
  13896. DraftEditor.prototype._showPlaceholder = function _showPlaceholder() {
  13897. return !!this.props.placeholder && !this.props.editorState.isInCompositionMode() && !this.props.editorState.getCurrentContent().hasText();
  13898. };
  13899. DraftEditor.prototype._renderPlaceholder = function _renderPlaceholder() {
  13900. if (this._showPlaceholder()) {
  13901. var placeHolderProps = {
  13902. text: nullthrows_1(this.props.placeholder),
  13903. editorState: this.props.editorState,
  13904. textAlignment: this.props.textAlignment,
  13905. accessibilityID: this._placeholderAccessibilityID
  13906. };
  13907. return React.createElement(DraftEditorPlaceholder_react, placeHolderProps);
  13908. }
  13909. return null;
  13910. };
  13911. DraftEditor.prototype.render = function render() {
  13912. var _this3 = this;
  13913. var _props = this.props,
  13914. blockRenderMap = _props.blockRenderMap,
  13915. blockRendererFn = _props.blockRendererFn,
  13916. blockStyleFn = _props.blockStyleFn,
  13917. customStyleFn = _props.customStyleFn,
  13918. customStyleMap = _props.customStyleMap,
  13919. editorState = _props.editorState,
  13920. readOnly = _props.readOnly,
  13921. textAlignment = _props.textAlignment,
  13922. textDirectionality = _props.textDirectionality;
  13923. var rootClass = cx_1({
  13924. 'DraftEditor/root': true,
  13925. 'DraftEditor/alignLeft': textAlignment === 'left',
  13926. 'DraftEditor/alignRight': textAlignment === 'right',
  13927. 'DraftEditor/alignCenter': textAlignment === 'center'
  13928. });
  13929. var contentStyle = {
  13930. outline: 'none',
  13931. // fix parent-draggable Safari bug. #1326
  13932. userSelect: 'text',
  13933. WebkitUserSelect: 'text',
  13934. whiteSpace: 'pre-wrap',
  13935. wordWrap: 'break-word'
  13936. };
  13937. // The aria-expanded and aria-haspopup properties should only be rendered
  13938. // for a combobox.
  13939. var ariaRole = this.props.role || 'textbox';
  13940. var ariaExpanded = ariaRole === 'combobox' ? !!this.props.ariaExpanded : null;
  13941. var editorContentsProps = {
  13942. blockRenderMap: blockRenderMap,
  13943. blockRendererFn: blockRendererFn,
  13944. blockStyleFn: blockStyleFn,
  13945. customStyleMap: _extends$5({}, DefaultDraftInlineStyle, customStyleMap),
  13946. customStyleFn: customStyleFn,
  13947. editorKey: this._editorKey,
  13948. editorState: editorState,
  13949. key: 'contents' + this.state.contentsKey,
  13950. textDirectionality: textDirectionality
  13951. };
  13952. return React.createElement(
  13953. 'div',
  13954. { className: rootClass },
  13955. this._renderPlaceholder(),
  13956. React.createElement(
  13957. 'div',
  13958. {
  13959. className: cx_1('DraftEditor/editorContainer'),
  13960. ref: function ref(_ref3) {
  13961. return _this3.editorContainer = _ref3;
  13962. } },
  13963. React.createElement(
  13964. 'div',
  13965. {
  13966. 'aria-activedescendant': readOnly ? null : this.props.ariaActiveDescendantID,
  13967. 'aria-autocomplete': readOnly ? null : this.props.ariaAutoComplete,
  13968. 'aria-controls': readOnly ? null : this.props.ariaControls,
  13969. 'aria-describedby': this.props.ariaDescribedBy || this._placeholderAccessibilityID,
  13970. 'aria-expanded': readOnly ? null : ariaExpanded,
  13971. 'aria-label': this.props.ariaLabel,
  13972. 'aria-labelledby': this.props.ariaLabelledBy,
  13973. 'aria-multiline': this.props.ariaMultiline,
  13974. autoCapitalize: this.props.autoCapitalize,
  13975. autoComplete: this.props.autoComplete,
  13976. autoCorrect: this.props.autoCorrect,
  13977. className: cx_1({
  13978. // Chrome's built-in translation feature mutates the DOM in ways
  13979. // that Draft doesn't expect (ex: adding <font> tags inside
  13980. // DraftEditorLeaf spans) and causes problems. We add notranslate
  13981. // here which makes its autotranslation skip over this subtree.
  13982. notranslate: !readOnly,
  13983. 'public/DraftEditor/content': true
  13984. }),
  13985. contentEditable: !readOnly,
  13986. 'data-testid': this.props.webDriverTestID,
  13987. onBeforeInput: this._onBeforeInput,
  13988. onBlur: this._onBlur,
  13989. onCompositionEnd: this._onCompositionEnd,
  13990. onCompositionStart: this._onCompositionStart,
  13991. onCopy: this._onCopy,
  13992. onCut: this._onCut,
  13993. onDragEnd: this._onDragEnd,
  13994. onDragEnter: this.onDragEnter,
  13995. onDragLeave: this.onDragLeave,
  13996. onDragOver: this._onDragOver,
  13997. onDragStart: this._onDragStart,
  13998. onDrop: this._onDrop,
  13999. onFocus: this._onFocus,
  14000. onInput: this._onInput,
  14001. onKeyDown: this._onKeyDown,
  14002. onKeyPress: this._onKeyPress,
  14003. onKeyUp: this._onKeyUp,
  14004. onMouseUp: this._onMouseUp,
  14005. onPaste: this._onPaste,
  14006. onSelect: this._onSelect,
  14007. ref: function ref(_ref2) {
  14008. return _this3.editor = _ref2;
  14009. },
  14010. role: readOnly ? null : ariaRole,
  14011. spellCheck: allowSpellCheck && this.props.spellCheck,
  14012. style: contentStyle,
  14013. suppressContentEditableWarning: true,
  14014. tabIndex: this.props.tabIndex },
  14015. React.createElement(DraftEditorContents_react, editorContentsProps)
  14016. )
  14017. )
  14018. );
  14019. };
  14020. DraftEditor.prototype.componentDidMount = function componentDidMount() {
  14021. this.setMode('edit');
  14022. /**
  14023. * IE has a hardcoded "feature" that attempts to convert link text into
  14024. * anchors in contentEditable DOM. This breaks the editor's expectations of
  14025. * the DOM, and control is lost. Disable it to make IE behave.
  14026. * See: http://blogs.msdn.com/b/ieinternals/archive/2010/09/15/
  14027. * ie9-beta-minor-change-list.aspx
  14028. */
  14029. if (isIE) {
  14030. document.execCommand('AutoUrlDetect', false, false);
  14031. }
  14032. };
  14033. /**
  14034. * Prevent selection events from affecting the current editor state. This
  14035. * is mostly intended to defend against IE, which fires off `selectionchange`
  14036. * events regardless of whether the selection is set via the browser or
  14037. * programmatically. We only care about selection events that occur because
  14038. * of browser interaction, not re-renders and forced selections.
  14039. */
  14040. DraftEditor.prototype.componentWillUpdate = function componentWillUpdate(nextProps) {
  14041. this._blockSelectEvents = true;
  14042. this._latestEditorState = nextProps.editorState;
  14043. };
  14044. DraftEditor.prototype.componentDidUpdate = function componentDidUpdate() {
  14045. this._blockSelectEvents = false;
  14046. this._latestCommittedEditorState = this.props.editorState;
  14047. };
  14048. /**
  14049. * Used via `this.focus()`.
  14050. *
  14051. * Force focus back onto the editor node.
  14052. *
  14053. * We attempt to preserve scroll position when focusing. You can also pass
  14054. * a specified scroll position (for cases like `cut` behavior where it should
  14055. * be restored to a known position).
  14056. */
  14057. /**
  14058. * Used via `this.setMode(...)`.
  14059. *
  14060. * Set the behavior mode for the editor component. This switches the current
  14061. * handler module to ensure that DOM events are managed appropriately for
  14062. * the active mode.
  14063. */
  14064. /**
  14065. * Used via `this.restoreEditorDOM()`.
  14066. *
  14067. * Force a complete re-render of the DraftEditorContents based on the current
  14068. * EditorState. This is useful when we know we are going to lose control of
  14069. * the DOM state (cut command, IME) and we want to make sure that
  14070. * reconciliation occurs on a version of the DOM that is synchronized with
  14071. * our EditorState.
  14072. */
  14073. /**
  14074. * Used via `this.setClipboard(...)`.
  14075. *
  14076. * Set the clipboard state for a cut/copy event.
  14077. */
  14078. /**
  14079. * Used via `this.getClipboard()`.
  14080. *
  14081. * Retrieve the clipboard state for a cut/copy event.
  14082. */
  14083. /**
  14084. * Used via `this.update(...)`.
  14085. *
  14086. * Propagate a new `EditorState` object to higher-level components. This is
  14087. * the method by which event handlers inform the `DraftEditor` component of
  14088. * state changes. A component that composes a `DraftEditor` **must** provide
  14089. * an `onChange` prop to receive state updates passed along from this
  14090. * function.
  14091. */
  14092. /**
  14093. * Used in conjunction with `onDragLeave()`, by counting the number of times
  14094. * a dragged element enters and leaves the editor (or any of its children),
  14095. * to determine when the dragged element absolutely leaves the editor.
  14096. */
  14097. /**
  14098. * See `onDragEnter()`.
  14099. */
  14100. return DraftEditor;
  14101. }(React.Component);
  14102. DraftEditor.defaultProps = {
  14103. blockRenderMap: DefaultDraftBlockRenderMap_1,
  14104. blockRendererFn: emptyFunction_1.thatReturnsNull,
  14105. blockStyleFn: emptyFunction_1.thatReturns(''),
  14106. keyBindingFn: getDefaultKeyBinding_1,
  14107. readOnly: false,
  14108. spellCheck: false,
  14109. stripPastedStyles: false
  14110. };
  14111. var DraftEditor_react = DraftEditor;
  14112. /**
  14113. * Copyright (c) 2013-present, Facebook, Inc.
  14114. * All rights reserved.
  14115. *
  14116. * This source code is licensed under the BSD-style license found in the
  14117. * LICENSE file in the root directory of this source tree. An additional grant
  14118. * of patent rights can be found in the PATENTS file in the same directory.
  14119. *
  14120. * @providesModule DraftStringKey
  14121. * @format
  14122. *
  14123. */
  14124. var DraftStringKey = {
  14125. stringify: function stringify(key) {
  14126. return '_' + String(key);
  14127. },
  14128. unstringify: function unstringify(key) {
  14129. return key.slice(1);
  14130. }
  14131. };
  14132. var DraftStringKey_1 = DraftStringKey;
  14133. var strlen$1 = UnicodeUtils_1.strlen;
  14134. /**
  14135. * Convert to UTF-8 character counts for storage.
  14136. */
  14137. function encodeEntityRanges(block, storageMap) {
  14138. var encoded = [];
  14139. block.findEntityRanges(function (character) {
  14140. return !!character.getEntity();
  14141. }, function ( /*number*/start, /*number*/end) {
  14142. var text = block.getText();
  14143. var key = block.getEntityAt(start);
  14144. encoded.push({
  14145. offset: strlen$1(text.slice(0, start)),
  14146. length: strlen$1(text.slice(start, end)),
  14147. // Encode the key as a number for range storage.
  14148. key: Number(storageMap[DraftStringKey_1.stringify(key)])
  14149. });
  14150. });
  14151. return encoded;
  14152. }
  14153. var encodeEntityRanges_1 = encodeEntityRanges;
  14154. var areEqual$1 = function areEqual(a, b) {
  14155. return a === b;
  14156. };
  14157. var isTruthy = function isTruthy(a) {
  14158. return !!a;
  14159. };
  14160. var EMPTY_ARRAY = [];
  14161. /**
  14162. * Helper function for getting encoded styles for each inline style. Convert
  14163. * to UTF-8 character counts for storage.
  14164. */
  14165. function getEncodedInlinesForType(block, styleList, styleToEncode) {
  14166. var ranges = [];
  14167. // Obtain an array with ranges for only the specified style.
  14168. var filteredInlines = styleList.map(function (style) {
  14169. return style.has(styleToEncode);
  14170. }).toList();
  14171. findRangesImmutable_1(filteredInlines, areEqual$1,
  14172. // We only want to keep ranges with nonzero style values.
  14173. isTruthy, function (start, end) {
  14174. var text = block.getText();
  14175. ranges.push({
  14176. offset: UnicodeUtils_1.strlen(text.slice(0, start)),
  14177. length: UnicodeUtils_1.strlen(text.slice(start, end)),
  14178. style: styleToEncode
  14179. });
  14180. });
  14181. return ranges;
  14182. }
  14183. /*
  14184. * Retrieve the encoded arrays of inline styles, with each individual style
  14185. * treated separately.
  14186. */
  14187. function encodeInlineStyleRanges(block) {
  14188. var styleList = block.getCharacterList().map(function (c) {
  14189. return c.getStyle();
  14190. }).toList();
  14191. var ranges = styleList.flatten().toSet().map(function (style) {
  14192. return getEncodedInlinesForType(block, styleList, style);
  14193. });
  14194. return Array.prototype.concat.apply(EMPTY_ARRAY, ranges.toJS());
  14195. }
  14196. var encodeInlineStyleRanges_1 = encodeInlineStyleRanges;
  14197. var _extends$6 = objectAssign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };
  14198. var createRawBlock = function createRawBlock(block, entityStorageMap) {
  14199. return {
  14200. key: block.getKey(),
  14201. text: block.getText(),
  14202. type: block.getType(),
  14203. depth: block.getDepth(),
  14204. inlineStyleRanges: encodeInlineStyleRanges_1(block),
  14205. entityRanges: encodeEntityRanges_1(block, entityStorageMap),
  14206. data: block.getData().toObject()
  14207. };
  14208. };
  14209. var insertRawBlock = function insertRawBlock(block, entityMap, rawBlocks, blockCacheRef) {
  14210. if (block instanceof ContentBlock_1) {
  14211. rawBlocks.push(createRawBlock(block, entityMap));
  14212. return;
  14213. }
  14214. !(block instanceof ContentBlockNode_1) ? process.env.NODE_ENV !== 'production' ? invariant_1(false, 'block is not a BlockNode') : invariant_1(false) : void 0;
  14215. var parentKey = block.getParentKey();
  14216. var rawBlock = blockCacheRef[block.getKey()] = _extends$6({}, createRawBlock(block, entityMap), {
  14217. children: []
  14218. });
  14219. if (parentKey) {
  14220. blockCacheRef[parentKey].children.push(rawBlock);
  14221. return;
  14222. }
  14223. rawBlocks.push(rawBlock);
  14224. };
  14225. var encodeRawBlocks = function encodeRawBlocks(contentState, rawState) {
  14226. var entityMap = rawState.entityMap;
  14227. var rawBlocks = [];
  14228. var blockCacheRef = {};
  14229. var entityCacheRef = {};
  14230. var entityStorageKey = 0;
  14231. contentState.getBlockMap().forEach(function (block) {
  14232. block.findEntityRanges(function (character) {
  14233. return character.getEntity() !== null;
  14234. }, function (start) {
  14235. var entityKey = block.getEntityAt(start);
  14236. // Stringify to maintain order of otherwise numeric keys.
  14237. var stringifiedEntityKey = DraftStringKey_1.stringify(entityKey);
  14238. // This makes this function resilient to two entities
  14239. // erroneously having the same key
  14240. if (entityCacheRef[stringifiedEntityKey]) {
  14241. return;
  14242. }
  14243. entityCacheRef[stringifiedEntityKey] = entityKey;
  14244. // we need the `any` casting here since this is a temporary state
  14245. // where we will later on flip the entity map and populate it with
  14246. // real entity, at this stage we just need to map back the entity
  14247. // key used by the BlockNode
  14248. entityMap[stringifiedEntityKey] = '' + entityStorageKey;
  14249. entityStorageKey++;
  14250. });
  14251. insertRawBlock(block, entityMap, rawBlocks, blockCacheRef);
  14252. });
  14253. return {
  14254. blocks: rawBlocks,
  14255. entityMap: entityMap
  14256. };
  14257. };
  14258. // Flip storage map so that our storage keys map to global
  14259. // DraftEntity keys.
  14260. var encodeRawEntityMap = function encodeRawEntityMap(contentState, rawState) {
  14261. var blocks = rawState.blocks,
  14262. entityMap = rawState.entityMap;
  14263. var rawEntityMap = {};
  14264. Object.keys(entityMap).forEach(function (key, index) {
  14265. var entity = contentState.getEntity(DraftStringKey_1.unstringify(key));
  14266. rawEntityMap[index] = {
  14267. type: entity.getType(),
  14268. mutability: entity.getMutability(),
  14269. data: entity.getData()
  14270. };
  14271. });
  14272. return {
  14273. blocks: blocks,
  14274. entityMap: rawEntityMap
  14275. };
  14276. };
  14277. var convertFromDraftStateToRaw = function convertFromDraftStateToRaw(contentState) {
  14278. var rawDraftContentState = {
  14279. entityMap: {},
  14280. blocks: []
  14281. };
  14282. // add blocks
  14283. rawDraftContentState = encodeRawBlocks(contentState, rawDraftContentState);
  14284. // add entities
  14285. rawDraftContentState = encodeRawEntityMap(contentState, rawDraftContentState);
  14286. return rawDraftContentState;
  14287. };
  14288. var convertFromDraftStateToRaw_1 = convertFromDraftStateToRaw;
  14289. var _extends$7 = objectAssign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };
  14290. /**
  14291. * Copyright (c) 2013-present, Facebook, Inc.
  14292. * All rights reserved.
  14293. *
  14294. * This source code is licensed under the BSD-style license found in the
  14295. * LICENSE file in the root directory of this source tree. An additional grant
  14296. * of patent rights can be found in the PATENTS file in the same directory.
  14297. *
  14298. * @providesModule DraftTreeAdapter
  14299. * @format
  14300. *
  14301. *
  14302. * This is unstable and not part of the public API and should not be used by
  14303. * production systems. This file may be update/removed without notice.
  14304. */
  14305. var traverseInDepthOrder = function traverseInDepthOrder(blocks, fn) {
  14306. var stack = [].concat(blocks).reverse();
  14307. while (stack.length) {
  14308. var _block = stack.pop();
  14309. fn(_block);
  14310. var children = _block.children;
  14311. !Array.isArray(children) ? process.env.NODE_ENV !== 'production' ? invariant_1(false, 'Invalid tree raw block') : invariant_1(false) : void 0;
  14312. stack = stack.concat([].concat(children.reverse()));
  14313. }
  14314. };
  14315. var isListBlock = function isListBlock(block) {
  14316. if (!(block && block.type)) {
  14317. return false;
  14318. }
  14319. var type = block.type;
  14320. return type === 'unordered-list-item' || type === 'ordered-list-item';
  14321. };
  14322. var addDepthToChildren = function addDepthToChildren(block) {
  14323. if (Array.isArray(block.children)) {
  14324. block.children = block.children.map(function (child) {
  14325. return child.type === block.type ? _extends$7({}, child, { depth: (block.depth || 0) + 1 }) : child;
  14326. });
  14327. }
  14328. };
  14329. /**
  14330. * This adapter is intended to be be used as an adapter to draft tree data
  14331. *
  14332. * draft state <=====> draft tree state
  14333. */
  14334. var DraftTreeAdapter = {
  14335. /**
  14336. * Converts from a tree raw state back to draft raw state
  14337. */
  14338. fromRawTreeStateToRawState: function fromRawTreeStateToRawState(draftTreeState) {
  14339. var blocks = draftTreeState.blocks;
  14340. var transformedBlocks = [];
  14341. !Array.isArray(blocks) ? process.env.NODE_ENV !== 'production' ? invariant_1(false, 'Invalid raw state') : invariant_1(false) : void 0;
  14342. if (!Array.isArray(blocks) || !blocks.length) {
  14343. return draftTreeState;
  14344. }
  14345. traverseInDepthOrder(blocks, function (block) {
  14346. var newBlock = _extends$7({}, block);
  14347. if (isListBlock(block)) {
  14348. newBlock.depth = newBlock.depth || 0;
  14349. addDepthToChildren(block);
  14350. }
  14351. delete newBlock.children;
  14352. transformedBlocks.push(newBlock);
  14353. });
  14354. draftTreeState.blocks = transformedBlocks;
  14355. return _extends$7({}, draftTreeState, {
  14356. blocks: transformedBlocks
  14357. });
  14358. },
  14359. /**
  14360. * Converts from draft raw state to tree draft state
  14361. */
  14362. fromRawStateToRawTreeState: function fromRawStateToRawTreeState(draftState) {
  14363. var lastListDepthCacheRef = {};
  14364. var transformedBlocks = [];
  14365. draftState.blocks.forEach(function (block) {
  14366. var isList = isListBlock(block);
  14367. var depth = block.depth || 0;
  14368. var treeBlock = _extends$7({}, block, {
  14369. children: []
  14370. });
  14371. if (!isList) {
  14372. // reset the cache path
  14373. lastListDepthCacheRef = {};
  14374. transformedBlocks.push(treeBlock);
  14375. return;
  14376. }
  14377. // update our depth cache reference path
  14378. lastListDepthCacheRef[depth] = treeBlock;
  14379. // if we are greater than zero we must have seen a parent already
  14380. if (depth > 0) {
  14381. var parent = lastListDepthCacheRef[depth - 1];
  14382. !parent ? process.env.NODE_ENV !== 'production' ? invariant_1(false, 'Invalid depth for RawDraftContentBlock') : invariant_1(false) : void 0;
  14383. // push nested list blocks
  14384. parent.children.push(treeBlock);
  14385. return;
  14386. }
  14387. // push root list blocks
  14388. transformedBlocks.push(treeBlock);
  14389. });
  14390. return _extends$7({}, draftState, {
  14391. blocks: transformedBlocks
  14392. });
  14393. }
  14394. };
  14395. var DraftTreeAdapter_1 = DraftTreeAdapter;
  14396. var List$c = immutable.List;
  14397. function createCharacterList(inlineStyles, entities) {
  14398. var characterArray = inlineStyles.map(function (style, ii) {
  14399. var entity = entities[ii];
  14400. return CharacterMetadata_1.create({ style: style, entity: entity });
  14401. });
  14402. return List$c(characterArray);
  14403. }
  14404. var createCharacterList_1 = createCharacterList;
  14405. var substr$1 = UnicodeUtils_1.substr;
  14406. /**
  14407. * Convert to native JavaScript string lengths to determine ranges.
  14408. */
  14409. function decodeEntityRanges(text, ranges) {
  14410. var entities = Array(text.length).fill(null);
  14411. if (ranges) {
  14412. ranges.forEach(function (range) {
  14413. // Using Unicode-enabled substrings converted to JavaScript lengths,
  14414. // fill the output array with entity keys.
  14415. var start = substr$1(text, 0, range.offset).length;
  14416. var end = start + substr$1(text, range.offset, range.length).length;
  14417. for (var ii = start; ii < end; ii++) {
  14418. entities[ii] = range.key;
  14419. }
  14420. });
  14421. }
  14422. return entities;
  14423. }
  14424. var decodeEntityRanges_1 = decodeEntityRanges;
  14425. var OrderedSet$6 = immutable.OrderedSet;
  14426. var substr$2 = UnicodeUtils_1.substr;
  14427. var EMPTY_SET$3 = OrderedSet$6();
  14428. /**
  14429. * Convert to native JavaScript string lengths to determine ranges.
  14430. */
  14431. function decodeInlineStyleRanges(text, ranges) {
  14432. var styles = Array(text.length).fill(EMPTY_SET$3);
  14433. if (ranges) {
  14434. ranges.forEach(function ( /*object*/range) {
  14435. var cursor = substr$2(text, 0, range.offset).length;
  14436. var end = cursor + substr$2(text, range.offset, range.length).length;
  14437. while (cursor < end) {
  14438. styles[cursor] = styles[cursor].add(range.style);
  14439. cursor++;
  14440. }
  14441. });
  14442. }
  14443. return styles;
  14444. }
  14445. var decodeInlineStyleRanges_1 = decodeInlineStyleRanges;
  14446. var _extends$8 = objectAssign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };
  14447. var List$d = immutable.List,
  14448. Map$a = immutable.Map,
  14449. OrderedMap$4 = immutable.OrderedMap;
  14450. var decodeBlockNodeConfig = function decodeBlockNodeConfig(block, entityMap) {
  14451. var key = block.key,
  14452. type = block.type,
  14453. data = block.data,
  14454. text = block.text,
  14455. depth = block.depth;
  14456. var blockNodeConfig = {
  14457. text: text,
  14458. depth: depth || 0,
  14459. type: type || 'unstyled',
  14460. key: key || generateRandomKey_1(),
  14461. data: Map$a(data),
  14462. characterList: decodeCharacterList(block, entityMap)
  14463. };
  14464. return blockNodeConfig;
  14465. };
  14466. var decodeCharacterList = function decodeCharacterList(block, entityMap) {
  14467. var text = block.text,
  14468. rawEntityRanges = block.entityRanges,
  14469. rawInlineStyleRanges = block.inlineStyleRanges;
  14470. var entityRanges = rawEntityRanges || [];
  14471. var inlineStyleRanges = rawInlineStyleRanges || [];
  14472. // Translate entity range keys to the DraftEntity map.
  14473. return createCharacterList_1(decodeInlineStyleRanges_1(text, inlineStyleRanges), decodeEntityRanges_1(text, entityRanges.filter(function (range) {
  14474. return entityMap.hasOwnProperty(range.key);
  14475. }).map(function (range) {
  14476. return _extends$8({}, range, { key: entityMap[range.key] });
  14477. })));
  14478. };
  14479. var decodeContentBlocks = function decodeContentBlocks(blocks, entityMap) {
  14480. return OrderedMap$4(blocks.map(function (block) {
  14481. var contentBlock = new ContentBlock_1(decodeBlockNodeConfig(block, entityMap));
  14482. return [contentBlock.getKey(), contentBlock];
  14483. }));
  14484. };
  14485. var decodeRawBlocks = function decodeRawBlocks(rawState, entityMap) {
  14486. var isTreeRawBlock = Array.isArray(rawState.blocks[0].children);
  14487. var rawBlocks = rawState.blocks;
  14488. {
  14489. return decodeContentBlocks(isTreeRawBlock ? DraftTreeAdapter_1.fromRawTreeStateToRawState(rawState).blocks : rawBlocks, entityMap);
  14490. }
  14491. };
  14492. var decodeRawEntityMap = function decodeRawEntityMap(rawState) {
  14493. var rawEntityMap = rawState.entityMap;
  14494. var entityMap = {};
  14495. // TODO: Update this once we completely remove DraftEntity
  14496. Object.keys(rawEntityMap).forEach(function (rawEntityKey) {
  14497. var _rawEntityMap$rawEnti = rawEntityMap[rawEntityKey],
  14498. type = _rawEntityMap$rawEnti.type,
  14499. mutability = _rawEntityMap$rawEnti.mutability,
  14500. data = _rawEntityMap$rawEnti.data;
  14501. // get the key reference to created entity
  14502. entityMap[rawEntityKey] = DraftEntity_1.__create(type, mutability, data || {});
  14503. });
  14504. return entityMap;
  14505. };
  14506. var convertFromRawToDraftState = function convertFromRawToDraftState(rawState) {
  14507. !Array.isArray(rawState.blocks) ? process.env.NODE_ENV !== 'production' ? invariant_1(false, 'invalid RawDraftContentState') : invariant_1(false) : void 0;
  14508. // decode entities
  14509. var entityMap = decodeRawEntityMap(rawState);
  14510. // decode blockMap
  14511. var blockMap = decodeRawBlocks(rawState, entityMap);
  14512. // create initial selection
  14513. var selectionState = blockMap.isEmpty() ? new SelectionState_1() : SelectionState_1.createEmpty(blockMap.first().getKey());
  14514. return new ContentState_1({
  14515. blockMap: blockMap,
  14516. entityMap: entityMap,
  14517. selectionBefore: selectionState,
  14518. selectionAfter: selectionState
  14519. });
  14520. };
  14521. var convertFromRawToDraftState_1 = convertFromRawToDraftState;
  14522. /**
  14523. * Like range.getBoundingClientRect() but normalizes for browser bugs.
  14524. */
  14525. function getRangeBoundingClientRect(range) {
  14526. // "Return a DOMRect object describing the smallest rectangle that includes
  14527. // the first rectangle in list and all of the remaining rectangles of which
  14528. // the height or width is not zero."
  14529. // http://www.w3.org/TR/cssom-view/#dom-range-getboundingclientrect
  14530. var rects = getRangeClientRects_1(range);
  14531. var top = 0;
  14532. var right = 0;
  14533. var bottom = 0;
  14534. var left = 0;
  14535. if (rects.length) {
  14536. // If the first rectangle has 0 width, we use the second, this is needed
  14537. // because Chrome renders a 0 width rectangle when the selection contains
  14538. // a line break.
  14539. if (rects.length > 1 && rects[0].width === 0) {
  14540. var _rects$ = rects[1];
  14541. top = _rects$.top;
  14542. right = _rects$.right;
  14543. bottom = _rects$.bottom;
  14544. left = _rects$.left;
  14545. } else {
  14546. var _rects$2 = rects[0];
  14547. top = _rects$2.top;
  14548. right = _rects$2.right;
  14549. bottom = _rects$2.bottom;
  14550. left = _rects$2.left;
  14551. }
  14552. for (var ii = 1; ii < rects.length; ii++) {
  14553. var rect = rects[ii];
  14554. if (rect.height !== 0 && rect.width !== 0) {
  14555. top = Math.min(top, rect.top);
  14556. right = Math.max(right, rect.right);
  14557. bottom = Math.max(bottom, rect.bottom);
  14558. left = Math.min(left, rect.left);
  14559. }
  14560. }
  14561. }
  14562. return {
  14563. top: top,
  14564. right: right,
  14565. bottom: bottom,
  14566. left: left,
  14567. width: right - left,
  14568. height: bottom - top
  14569. };
  14570. }
  14571. var getRangeBoundingClientRect_1 = getRangeBoundingClientRect;
  14572. /**
  14573. * Return the bounding ClientRect for the visible DOM selection, if any.
  14574. * In cases where there are no selected ranges or the bounding rect is
  14575. * temporarily invalid, return null.
  14576. */
  14577. function getVisibleSelectionRect(global) {
  14578. var selection = global.getSelection();
  14579. if (!selection.rangeCount) {
  14580. return null;
  14581. }
  14582. var range = selection.getRangeAt(0);
  14583. var boundingRect = getRangeBoundingClientRect_1(range);
  14584. var top = boundingRect.top,
  14585. right = boundingRect.right,
  14586. bottom = boundingRect.bottom,
  14587. left = boundingRect.left;
  14588. // When a re-render leads to a node being removed, the DOM selection will
  14589. // temporarily be placed on an ancestor node, which leads to an invalid
  14590. // bounding rect. Discard this state.
  14591. if (top === 0 && right === 0 && bottom === 0 && left === 0) {
  14592. return null;
  14593. }
  14594. return boundingRect;
  14595. }
  14596. var getVisibleSelectionRect_1 = getVisibleSelectionRect;
  14597. var DraftPublic = {
  14598. Editor: DraftEditor_react,
  14599. EditorBlock: DraftEditorBlock_react,
  14600. EditorState: EditorState_1,
  14601. CompositeDecorator: CompositeDraftDecorator_1,
  14602. Entity: DraftEntity_1,
  14603. EntityInstance: DraftEntityInstance_1,
  14604. BlockMapBuilder: BlockMapBuilder_1,
  14605. CharacterMetadata: CharacterMetadata_1,
  14606. ContentBlock: ContentBlock_1,
  14607. ContentState: ContentState_1,
  14608. SelectionState: SelectionState_1,
  14609. AtomicBlockUtils: AtomicBlockUtils_1,
  14610. KeyBindingUtil: KeyBindingUtil_1,
  14611. Modifier: DraftModifier_1,
  14612. RichUtils: RichTextEditorUtil_1,
  14613. DefaultDraftBlockRenderMap: DefaultDraftBlockRenderMap_1,
  14614. DefaultDraftInlineStyle: DefaultDraftInlineStyle,
  14615. convertFromHTML: convertFromHTMLToContentBlocks,
  14616. convertFromRaw: convertFromRawToDraftState_1,
  14617. convertToRaw: convertFromDraftStateToRaw_1,
  14618. genKey: generateRandomKey_1,
  14619. getDefaultKeyBinding: getDefaultKeyBinding_1,
  14620. getVisibleSelectionRect: getVisibleSelectionRect_1
  14621. };
  14622. var Draft = DraftPublic;
  14623. var Draft_1 = Draft.Editor;
  14624. var Draft_3 = Draft.EditorState;
  14625. var Draft_4 = Draft.CompositeDecorator;
  14626. var Draft_14 = Draft.Modifier;
  14627. var Draft_15 = Draft.RichUtils;
  14628. var Draft_20 = Draft.convertToRaw;
  14629. var immutable$1 = createCommonjsModule(function (module, exports) {
  14630. /**
  14631. * Copyright (c) 2014-present, Facebook, Inc.
  14632. *
  14633. * This source code is licensed under the MIT license found in the
  14634. * LICENSE file in the root directory of this source tree.
  14635. */
  14636. (function (global, factory) {
  14637. factory(exports) ;
  14638. }(commonjsGlobal, (function (exports) {
  14639. // Used for setting prototype methods that IE8 chokes on.
  14640. var DELETE = 'delete';
  14641. // Constants describing the size of trie nodes.
  14642. var SHIFT = 5; // Resulted in best performance after ______?
  14643. var SIZE = 1 << SHIFT;
  14644. var MASK = SIZE - 1;
  14645. // A consistent shared value representing "not set" which equals nothing other
  14646. // than itself, and nothing that could be provided externally.
  14647. var NOT_SET = {};
  14648. // Boolean references, Rough equivalent of `bool &`.
  14649. function MakeRef() {
  14650. return { value: false };
  14651. }
  14652. function SetRef(ref) {
  14653. if (ref) {
  14654. ref.value = true;
  14655. }
  14656. }
  14657. // A function which returns a value representing an "owner" for transient writes
  14658. // to tries. The return value will only ever equal itself, and will not equal
  14659. // the return of any subsequent call of this function.
  14660. function OwnerID() {}
  14661. function ensureSize(iter) {
  14662. if (iter.size === undefined) {
  14663. iter.size = iter.__iterate(returnTrue);
  14664. }
  14665. return iter.size;
  14666. }
  14667. function wrapIndex(iter, index) {
  14668. // This implements "is array index" which the ECMAString spec defines as:
  14669. //
  14670. // A String property name P is an array index if and only if
  14671. // ToString(ToUint32(P)) is equal to P and ToUint32(P) is not equal
  14672. // to 2^32−1.
  14673. //
  14674. // http://www.ecma-international.org/ecma-262/6.0/#sec-array-exotic-objects
  14675. if (typeof index !== 'number') {
  14676. var uint32Index = index >>> 0; // N >>> 0 is shorthand for ToUint32
  14677. if ('' + uint32Index !== index || uint32Index === 4294967295) {
  14678. return NaN;
  14679. }
  14680. index = uint32Index;
  14681. }
  14682. return index < 0 ? ensureSize(iter) + index : index;
  14683. }
  14684. function returnTrue() {
  14685. return true;
  14686. }
  14687. function wholeSlice(begin, end, size) {
  14688. return (
  14689. ((begin === 0 && !isNeg(begin)) ||
  14690. (size !== undefined && begin <= -size)) &&
  14691. (end === undefined || (size !== undefined && end >= size))
  14692. );
  14693. }
  14694. function resolveBegin(begin, size) {
  14695. return resolveIndex(begin, size, 0);
  14696. }
  14697. function resolveEnd(end, size) {
  14698. return resolveIndex(end, size, size);
  14699. }
  14700. function resolveIndex(index, size, defaultIndex) {
  14701. // Sanitize indices using this shorthand for ToInt32(argument)
  14702. // http://www.ecma-international.org/ecma-262/6.0/#sec-toint32
  14703. return index === undefined
  14704. ? defaultIndex
  14705. : isNeg(index)
  14706. ? size === Infinity
  14707. ? size
  14708. : Math.max(0, size + index) | 0
  14709. : size === undefined || size === index
  14710. ? index
  14711. : Math.min(size, index) | 0;
  14712. }
  14713. function isNeg(value) {
  14714. // Account for -0 which is negative, but not less than 0.
  14715. return value < 0 || (value === 0 && 1 / value === -Infinity);
  14716. }
  14717. // Note: value is unchanged to not break immutable-devtools.
  14718. var IS_COLLECTION_SYMBOL = '@@__IMMUTABLE_ITERABLE__@@';
  14719. function isCollection(maybeCollection) {
  14720. return Boolean(maybeCollection && maybeCollection[IS_COLLECTION_SYMBOL]);
  14721. }
  14722. var IS_KEYED_SYMBOL = '@@__IMMUTABLE_KEYED__@@';
  14723. function isKeyed(maybeKeyed) {
  14724. return Boolean(maybeKeyed && maybeKeyed[IS_KEYED_SYMBOL]);
  14725. }
  14726. var IS_INDEXED_SYMBOL = '@@__IMMUTABLE_INDEXED__@@';
  14727. function isIndexed(maybeIndexed) {
  14728. return Boolean(maybeIndexed && maybeIndexed[IS_INDEXED_SYMBOL]);
  14729. }
  14730. function isAssociative(maybeAssociative) {
  14731. return isKeyed(maybeAssociative) || isIndexed(maybeAssociative);
  14732. }
  14733. var Collection = function Collection(value) {
  14734. return isCollection(value) ? value : Seq(value);
  14735. };
  14736. var KeyedCollection = /*@__PURE__*/(function (Collection) {
  14737. function KeyedCollection(value) {
  14738. return isKeyed(value) ? value : KeyedSeq(value);
  14739. }
  14740. if ( Collection ) KeyedCollection.__proto__ = Collection;
  14741. KeyedCollection.prototype = Object.create( Collection && Collection.prototype );
  14742. KeyedCollection.prototype.constructor = KeyedCollection;
  14743. return KeyedCollection;
  14744. }(Collection));
  14745. var IndexedCollection = /*@__PURE__*/(function (Collection) {
  14746. function IndexedCollection(value) {
  14747. return isIndexed(value) ? value : IndexedSeq(value);
  14748. }
  14749. if ( Collection ) IndexedCollection.__proto__ = Collection;
  14750. IndexedCollection.prototype = Object.create( Collection && Collection.prototype );
  14751. IndexedCollection.prototype.constructor = IndexedCollection;
  14752. return IndexedCollection;
  14753. }(Collection));
  14754. var SetCollection = /*@__PURE__*/(function (Collection) {
  14755. function SetCollection(value) {
  14756. return isCollection(value) && !isAssociative(value) ? value : SetSeq(value);
  14757. }
  14758. if ( Collection ) SetCollection.__proto__ = Collection;
  14759. SetCollection.prototype = Object.create( Collection && Collection.prototype );
  14760. SetCollection.prototype.constructor = SetCollection;
  14761. return SetCollection;
  14762. }(Collection));
  14763. Collection.Keyed = KeyedCollection;
  14764. Collection.Indexed = IndexedCollection;
  14765. Collection.Set = SetCollection;
  14766. var IS_SEQ_SYMBOL = '@@__IMMUTABLE_SEQ__@@';
  14767. function isSeq(maybeSeq) {
  14768. return Boolean(maybeSeq && maybeSeq[IS_SEQ_SYMBOL]);
  14769. }
  14770. var IS_RECORD_SYMBOL = '@@__IMMUTABLE_RECORD__@@';
  14771. function isRecord(maybeRecord) {
  14772. return Boolean(maybeRecord && maybeRecord[IS_RECORD_SYMBOL]);
  14773. }
  14774. function isImmutable(maybeImmutable) {
  14775. return isCollection(maybeImmutable) || isRecord(maybeImmutable);
  14776. }
  14777. var IS_ORDERED_SYMBOL = '@@__IMMUTABLE_ORDERED__@@';
  14778. function isOrdered(maybeOrdered) {
  14779. return Boolean(maybeOrdered && maybeOrdered[IS_ORDERED_SYMBOL]);
  14780. }
  14781. var ITERATE_KEYS = 0;
  14782. var ITERATE_VALUES = 1;
  14783. var ITERATE_ENTRIES = 2;
  14784. var REAL_ITERATOR_SYMBOL = typeof Symbol === 'function' && Symbol.iterator;
  14785. var FAUX_ITERATOR_SYMBOL = '@@iterator';
  14786. var ITERATOR_SYMBOL = REAL_ITERATOR_SYMBOL || FAUX_ITERATOR_SYMBOL;
  14787. var Iterator = function Iterator(next) {
  14788. this.next = next;
  14789. };
  14790. Iterator.prototype.toString = function toString () {
  14791. return '[Iterator]';
  14792. };
  14793. Iterator.KEYS = ITERATE_KEYS;
  14794. Iterator.VALUES = ITERATE_VALUES;
  14795. Iterator.ENTRIES = ITERATE_ENTRIES;
  14796. Iterator.prototype.inspect = Iterator.prototype.toSource = function() {
  14797. return this.toString();
  14798. };
  14799. Iterator.prototype[ITERATOR_SYMBOL] = function() {
  14800. return this;
  14801. };
  14802. function iteratorValue(type, k, v, iteratorResult) {
  14803. var value = type === 0 ? k : type === 1 ? v : [k, v];
  14804. iteratorResult
  14805. ? (iteratorResult.value = value)
  14806. : (iteratorResult = {
  14807. value: value,
  14808. done: false,
  14809. });
  14810. return iteratorResult;
  14811. }
  14812. function iteratorDone() {
  14813. return { value: undefined, done: true };
  14814. }
  14815. function hasIterator(maybeIterable) {
  14816. return !!getIteratorFn(maybeIterable);
  14817. }
  14818. function isIterator(maybeIterator) {
  14819. return maybeIterator && typeof maybeIterator.next === 'function';
  14820. }
  14821. function getIterator(iterable) {
  14822. var iteratorFn = getIteratorFn(iterable);
  14823. return iteratorFn && iteratorFn.call(iterable);
  14824. }
  14825. function getIteratorFn(iterable) {
  14826. var iteratorFn =
  14827. iterable &&
  14828. ((REAL_ITERATOR_SYMBOL && iterable[REAL_ITERATOR_SYMBOL]) ||
  14829. iterable[FAUX_ITERATOR_SYMBOL]);
  14830. if (typeof iteratorFn === 'function') {
  14831. return iteratorFn;
  14832. }
  14833. }
  14834. var hasOwnProperty = Object.prototype.hasOwnProperty;
  14835. function isArrayLike(value) {
  14836. if (Array.isArray(value) || typeof value === 'string') {
  14837. return true;
  14838. }
  14839. return (
  14840. value &&
  14841. typeof value === 'object' &&
  14842. Number.isInteger(value.length) &&
  14843. value.length >= 0 &&
  14844. (value.length === 0
  14845. ? // Only {length: 0} is considered Array-like.
  14846. Object.keys(value).length === 1
  14847. : // An object is only Array-like if it has a property where the last value
  14848. // in the array-like may be found (which could be undefined).
  14849. value.hasOwnProperty(value.length - 1))
  14850. );
  14851. }
  14852. var Seq = /*@__PURE__*/(function (Collection$$1) {
  14853. function Seq(value) {
  14854. return value === null || value === undefined
  14855. ? emptySequence()
  14856. : isImmutable(value)
  14857. ? value.toSeq()
  14858. : seqFromValue(value);
  14859. }
  14860. if ( Collection$$1 ) Seq.__proto__ = Collection$$1;
  14861. Seq.prototype = Object.create( Collection$$1 && Collection$$1.prototype );
  14862. Seq.prototype.constructor = Seq;
  14863. Seq.prototype.toSeq = function toSeq () {
  14864. return this;
  14865. };
  14866. Seq.prototype.toString = function toString () {
  14867. return this.__toString('Seq {', '}');
  14868. };
  14869. Seq.prototype.cacheResult = function cacheResult () {
  14870. if (!this._cache && this.__iterateUncached) {
  14871. this._cache = this.entrySeq().toArray();
  14872. this.size = this._cache.length;
  14873. }
  14874. return this;
  14875. };
  14876. // abstract __iterateUncached(fn, reverse)
  14877. Seq.prototype.__iterate = function __iterate (fn, reverse) {
  14878. var cache = this._cache;
  14879. if (cache) {
  14880. var size = cache.length;
  14881. var i = 0;
  14882. while (i !== size) {
  14883. var entry = cache[reverse ? size - ++i : i++];
  14884. if (fn(entry[1], entry[0], this) === false) {
  14885. break;
  14886. }
  14887. }
  14888. return i;
  14889. }
  14890. return this.__iterateUncached(fn, reverse);
  14891. };
  14892. // abstract __iteratorUncached(type, reverse)
  14893. Seq.prototype.__iterator = function __iterator (type, reverse) {
  14894. var cache = this._cache;
  14895. if (cache) {
  14896. var size = cache.length;
  14897. var i = 0;
  14898. return new Iterator(function () {
  14899. if (i === size) {
  14900. return iteratorDone();
  14901. }
  14902. var entry = cache[reverse ? size - ++i : i++];
  14903. return iteratorValue(type, entry[0], entry[1]);
  14904. });
  14905. }
  14906. return this.__iteratorUncached(type, reverse);
  14907. };
  14908. return Seq;
  14909. }(Collection));
  14910. var KeyedSeq = /*@__PURE__*/(function (Seq) {
  14911. function KeyedSeq(value) {
  14912. return value === null || value === undefined
  14913. ? emptySequence().toKeyedSeq()
  14914. : isCollection(value)
  14915. ? isKeyed(value)
  14916. ? value.toSeq()
  14917. : value.fromEntrySeq()
  14918. : isRecord(value)
  14919. ? value.toSeq()
  14920. : keyedSeqFromValue(value);
  14921. }
  14922. if ( Seq ) KeyedSeq.__proto__ = Seq;
  14923. KeyedSeq.prototype = Object.create( Seq && Seq.prototype );
  14924. KeyedSeq.prototype.constructor = KeyedSeq;
  14925. KeyedSeq.prototype.toKeyedSeq = function toKeyedSeq () {
  14926. return this;
  14927. };
  14928. return KeyedSeq;
  14929. }(Seq));
  14930. var IndexedSeq = /*@__PURE__*/(function (Seq) {
  14931. function IndexedSeq(value) {
  14932. return value === null || value === undefined
  14933. ? emptySequence()
  14934. : isCollection(value)
  14935. ? isKeyed(value)
  14936. ? value.entrySeq()
  14937. : value.toIndexedSeq()
  14938. : isRecord(value)
  14939. ? value.toSeq().entrySeq()
  14940. : indexedSeqFromValue(value);
  14941. }
  14942. if ( Seq ) IndexedSeq.__proto__ = Seq;
  14943. IndexedSeq.prototype = Object.create( Seq && Seq.prototype );
  14944. IndexedSeq.prototype.constructor = IndexedSeq;
  14945. IndexedSeq.of = function of (/*...values*/) {
  14946. return IndexedSeq(arguments);
  14947. };
  14948. IndexedSeq.prototype.toIndexedSeq = function toIndexedSeq () {
  14949. return this;
  14950. };
  14951. IndexedSeq.prototype.toString = function toString () {
  14952. return this.__toString('Seq [', ']');
  14953. };
  14954. return IndexedSeq;
  14955. }(Seq));
  14956. var SetSeq = /*@__PURE__*/(function (Seq) {
  14957. function SetSeq(value) {
  14958. return (isCollection(value) && !isAssociative(value)
  14959. ? value
  14960. : IndexedSeq(value)
  14961. ).toSetSeq();
  14962. }
  14963. if ( Seq ) SetSeq.__proto__ = Seq;
  14964. SetSeq.prototype = Object.create( Seq && Seq.prototype );
  14965. SetSeq.prototype.constructor = SetSeq;
  14966. SetSeq.of = function of (/*...values*/) {
  14967. return SetSeq(arguments);
  14968. };
  14969. SetSeq.prototype.toSetSeq = function toSetSeq () {
  14970. return this;
  14971. };
  14972. return SetSeq;
  14973. }(Seq));
  14974. Seq.isSeq = isSeq;
  14975. Seq.Keyed = KeyedSeq;
  14976. Seq.Set = SetSeq;
  14977. Seq.Indexed = IndexedSeq;
  14978. Seq.prototype[IS_SEQ_SYMBOL] = true;
  14979. // #pragma Root Sequences
  14980. var ArraySeq = /*@__PURE__*/(function (IndexedSeq) {
  14981. function ArraySeq(array) {
  14982. this._array = array;
  14983. this.size = array.length;
  14984. }
  14985. if ( IndexedSeq ) ArraySeq.__proto__ = IndexedSeq;
  14986. ArraySeq.prototype = Object.create( IndexedSeq && IndexedSeq.prototype );
  14987. ArraySeq.prototype.constructor = ArraySeq;
  14988. ArraySeq.prototype.get = function get (index, notSetValue) {
  14989. return this.has(index) ? this._array[wrapIndex(this, index)] : notSetValue;
  14990. };
  14991. ArraySeq.prototype.__iterate = function __iterate (fn, reverse) {
  14992. var array = this._array;
  14993. var size = array.length;
  14994. var i = 0;
  14995. while (i !== size) {
  14996. var ii = reverse ? size - ++i : i++;
  14997. if (fn(array[ii], ii, this) === false) {
  14998. break;
  14999. }
  15000. }
  15001. return i;
  15002. };
  15003. ArraySeq.prototype.__iterator = function __iterator (type, reverse) {
  15004. var array = this._array;
  15005. var size = array.length;
  15006. var i = 0;
  15007. return new Iterator(function () {
  15008. if (i === size) {
  15009. return iteratorDone();
  15010. }
  15011. var ii = reverse ? size - ++i : i++;
  15012. return iteratorValue(type, ii, array[ii]);
  15013. });
  15014. };
  15015. return ArraySeq;
  15016. }(IndexedSeq));
  15017. var ObjectSeq = /*@__PURE__*/(function (KeyedSeq) {
  15018. function ObjectSeq(object) {
  15019. var keys = Object.keys(object);
  15020. this._object = object;
  15021. this._keys = keys;
  15022. this.size = keys.length;
  15023. }
  15024. if ( KeyedSeq ) ObjectSeq.__proto__ = KeyedSeq;
  15025. ObjectSeq.prototype = Object.create( KeyedSeq && KeyedSeq.prototype );
  15026. ObjectSeq.prototype.constructor = ObjectSeq;
  15027. ObjectSeq.prototype.get = function get (key, notSetValue) {
  15028. if (notSetValue !== undefined && !this.has(key)) {
  15029. return notSetValue;
  15030. }
  15031. return this._object[key];
  15032. };
  15033. ObjectSeq.prototype.has = function has (key) {
  15034. return hasOwnProperty.call(this._object, key);
  15035. };
  15036. ObjectSeq.prototype.__iterate = function __iterate (fn, reverse) {
  15037. var object = this._object;
  15038. var keys = this._keys;
  15039. var size = keys.length;
  15040. var i = 0;
  15041. while (i !== size) {
  15042. var key = keys[reverse ? size - ++i : i++];
  15043. if (fn(object[key], key, this) === false) {
  15044. break;
  15045. }
  15046. }
  15047. return i;
  15048. };
  15049. ObjectSeq.prototype.__iterator = function __iterator (type, reverse) {
  15050. var object = this._object;
  15051. var keys = this._keys;
  15052. var size = keys.length;
  15053. var i = 0;
  15054. return new Iterator(function () {
  15055. if (i === size) {
  15056. return iteratorDone();
  15057. }
  15058. var key = keys[reverse ? size - ++i : i++];
  15059. return iteratorValue(type, key, object[key]);
  15060. });
  15061. };
  15062. return ObjectSeq;
  15063. }(KeyedSeq));
  15064. ObjectSeq.prototype[IS_ORDERED_SYMBOL] = true;
  15065. var CollectionSeq = /*@__PURE__*/(function (IndexedSeq) {
  15066. function CollectionSeq(collection) {
  15067. this._collection = collection;
  15068. this.size = collection.length || collection.size;
  15069. }
  15070. if ( IndexedSeq ) CollectionSeq.__proto__ = IndexedSeq;
  15071. CollectionSeq.prototype = Object.create( IndexedSeq && IndexedSeq.prototype );
  15072. CollectionSeq.prototype.constructor = CollectionSeq;
  15073. CollectionSeq.prototype.__iterateUncached = function __iterateUncached (fn, reverse) {
  15074. if (reverse) {
  15075. return this.cacheResult().__iterate(fn, reverse);
  15076. }
  15077. var collection = this._collection;
  15078. var iterator = getIterator(collection);
  15079. var iterations = 0;
  15080. if (isIterator(iterator)) {
  15081. var step;
  15082. while (!(step = iterator.next()).done) {
  15083. if (fn(step.value, iterations++, this) === false) {
  15084. break;
  15085. }
  15086. }
  15087. }
  15088. return iterations;
  15089. };
  15090. CollectionSeq.prototype.__iteratorUncached = function __iteratorUncached (type, reverse) {
  15091. if (reverse) {
  15092. return this.cacheResult().__iterator(type, reverse);
  15093. }
  15094. var collection = this._collection;
  15095. var iterator = getIterator(collection);
  15096. if (!isIterator(iterator)) {
  15097. return new Iterator(iteratorDone);
  15098. }
  15099. var iterations = 0;
  15100. return new Iterator(function () {
  15101. var step = iterator.next();
  15102. return step.done ? step : iteratorValue(type, iterations++, step.value);
  15103. });
  15104. };
  15105. return CollectionSeq;
  15106. }(IndexedSeq));
  15107. // # pragma Helper functions
  15108. var EMPTY_SEQ;
  15109. function emptySequence() {
  15110. return EMPTY_SEQ || (EMPTY_SEQ = new ArraySeq([]));
  15111. }
  15112. function keyedSeqFromValue(value) {
  15113. var seq = Array.isArray(value)
  15114. ? new ArraySeq(value)
  15115. : hasIterator(value)
  15116. ? new CollectionSeq(value)
  15117. : undefined;
  15118. if (seq) {
  15119. return seq.fromEntrySeq();
  15120. }
  15121. if (typeof value === 'object') {
  15122. return new ObjectSeq(value);
  15123. }
  15124. throw new TypeError(
  15125. 'Expected Array or collection object of [k, v] entries, or keyed object: ' +
  15126. value
  15127. );
  15128. }
  15129. function indexedSeqFromValue(value) {
  15130. var seq = maybeIndexedSeqFromValue(value);
  15131. if (seq) {
  15132. return seq;
  15133. }
  15134. throw new TypeError(
  15135. 'Expected Array or collection object of values: ' + value
  15136. );
  15137. }
  15138. function seqFromValue(value) {
  15139. var seq = maybeIndexedSeqFromValue(value);
  15140. if (seq) {
  15141. return seq;
  15142. }
  15143. if (typeof value === 'object') {
  15144. return new ObjectSeq(value);
  15145. }
  15146. throw new TypeError(
  15147. 'Expected Array or collection object of values, or keyed object: ' + value
  15148. );
  15149. }
  15150. function maybeIndexedSeqFromValue(value) {
  15151. return isArrayLike(value)
  15152. ? new ArraySeq(value)
  15153. : hasIterator(value)
  15154. ? new CollectionSeq(value)
  15155. : undefined;
  15156. }
  15157. var IS_MAP_SYMBOL = '@@__IMMUTABLE_MAP__@@';
  15158. function isMap(maybeMap) {
  15159. return Boolean(maybeMap && maybeMap[IS_MAP_SYMBOL]);
  15160. }
  15161. function isOrderedMap(maybeOrderedMap) {
  15162. return isMap(maybeOrderedMap) && isOrdered(maybeOrderedMap);
  15163. }
  15164. function isValueObject(maybeValue) {
  15165. return Boolean(
  15166. maybeValue &&
  15167. typeof maybeValue.equals === 'function' &&
  15168. typeof maybeValue.hashCode === 'function'
  15169. );
  15170. }
  15171. /**
  15172. * An extension of the "same-value" algorithm as [described for use by ES6 Map
  15173. * and Set](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map#Key_equality)
  15174. *
  15175. * NaN is considered the same as NaN, however -0 and 0 are considered the same
  15176. * value, which is different from the algorithm described by
  15177. * [`Object.is`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/is).
  15178. *
  15179. * This is extended further to allow Objects to describe the values they
  15180. * represent, by way of `valueOf` or `equals` (and `hashCode`).
  15181. *
  15182. * Note: because of this extension, the key equality of Immutable.Map and the
  15183. * value equality of Immutable.Set will differ from ES6 Map and Set.
  15184. *
  15185. * ### Defining custom values
  15186. *
  15187. * The easiest way to describe the value an object represents is by implementing
  15188. * `valueOf`. For example, `Date` represents a value by returning a unix
  15189. * timestamp for `valueOf`:
  15190. *
  15191. * var date1 = new Date(1234567890000); // Fri Feb 13 2009 ...
  15192. * var date2 = new Date(1234567890000);
  15193. * date1.valueOf(); // 1234567890000
  15194. * assert( date1 !== date2 );
  15195. * assert( Immutable.is( date1, date2 ) );
  15196. *
  15197. * Note: overriding `valueOf` may have other implications if you use this object
  15198. * where JavaScript expects a primitive, such as implicit string coercion.
  15199. *
  15200. * For more complex types, especially collections, implementing `valueOf` may
  15201. * not be performant. An alternative is to implement `equals` and `hashCode`.
  15202. *
  15203. * `equals` takes another object, presumably of similar type, and returns true
  15204. * if it is equal. Equality is symmetrical, so the same result should be
  15205. * returned if this and the argument are flipped.
  15206. *
  15207. * assert( a.equals(b) === b.equals(a) );
  15208. *
  15209. * `hashCode` returns a 32bit integer number representing the object which will
  15210. * be used to determine how to store the value object in a Map or Set. You must
  15211. * provide both or neither methods, one must not exist without the other.
  15212. *
  15213. * Also, an important relationship between these methods must be upheld: if two
  15214. * values are equal, they *must* return the same hashCode. If the values are not
  15215. * equal, they might have the same hashCode; this is called a hash collision,
  15216. * and while undesirable for performance reasons, it is acceptable.
  15217. *
  15218. * if (a.equals(b)) {
  15219. * assert( a.hashCode() === b.hashCode() );
  15220. * }
  15221. *
  15222. * All Immutable collections are Value Objects: they implement `equals()`
  15223. * and `hashCode()`.
  15224. */
  15225. function is(valueA, valueB) {
  15226. if (valueA === valueB || (valueA !== valueA && valueB !== valueB)) {
  15227. return true;
  15228. }
  15229. if (!valueA || !valueB) {
  15230. return false;
  15231. }
  15232. if (
  15233. typeof valueA.valueOf === 'function' &&
  15234. typeof valueB.valueOf === 'function'
  15235. ) {
  15236. valueA = valueA.valueOf();
  15237. valueB = valueB.valueOf();
  15238. if (valueA === valueB || (valueA !== valueA && valueB !== valueB)) {
  15239. return true;
  15240. }
  15241. if (!valueA || !valueB) {
  15242. return false;
  15243. }
  15244. }
  15245. return !!(
  15246. isValueObject(valueA) &&
  15247. isValueObject(valueB) &&
  15248. valueA.equals(valueB)
  15249. );
  15250. }
  15251. var imul =
  15252. typeof Math.imul === 'function' && Math.imul(0xffffffff, 2) === -2
  15253. ? Math.imul
  15254. : function imul(a, b) {
  15255. a |= 0; // int
  15256. b |= 0; // int
  15257. var c = a & 0xffff;
  15258. var d = b & 0xffff;
  15259. // Shift by 0 fixes the sign on the high part.
  15260. return (c * d + ((((a >>> 16) * d + c * (b >>> 16)) << 16) >>> 0)) | 0; // int
  15261. };
  15262. // v8 has an optimization for storing 31-bit signed numbers.
  15263. // Values which have either 00 or 11 as the high order bits qualify.
  15264. // This function drops the highest order bit in a signed number, maintaining
  15265. // the sign bit.
  15266. function smi(i32) {
  15267. return ((i32 >>> 1) & 0x40000000) | (i32 & 0xbfffffff);
  15268. }
  15269. var defaultValueOf = Object.prototype.valueOf;
  15270. function hash(o) {
  15271. switch (typeof o) {
  15272. case 'boolean':
  15273. // The hash values for built-in constants are a 1 value for each 5-byte
  15274. // shift region expect for the first, which encodes the value. This
  15275. // reduces the odds of a hash collision for these common values.
  15276. return o ? 0x42108421 : 0x42108420;
  15277. case 'number':
  15278. return hashNumber(o);
  15279. case 'string':
  15280. return o.length > STRING_HASH_CACHE_MIN_STRLEN
  15281. ? cachedHashString(o)
  15282. : hashString(o);
  15283. case 'object':
  15284. case 'function':
  15285. if (o === null) {
  15286. return 0x42108422;
  15287. }
  15288. if (typeof o.hashCode === 'function') {
  15289. // Drop any high bits from accidentally long hash codes.
  15290. return smi(o.hashCode(o));
  15291. }
  15292. if (o.valueOf !== defaultValueOf && typeof o.valueOf === 'function') {
  15293. o = o.valueOf(o);
  15294. }
  15295. return hashJSObj(o);
  15296. case 'undefined':
  15297. return 0x42108423;
  15298. default:
  15299. if (typeof o.toString === 'function') {
  15300. return hashString(o.toString());
  15301. }
  15302. throw new Error('Value type ' + typeof o + ' cannot be hashed.');
  15303. }
  15304. }
  15305. // Compress arbitrarily large numbers into smi hashes.
  15306. function hashNumber(n) {
  15307. if (n !== n || n === Infinity) {
  15308. return 0;
  15309. }
  15310. var hash = n | 0;
  15311. if (hash !== n) {
  15312. hash ^= n * 0xffffffff;
  15313. }
  15314. while (n > 0xffffffff) {
  15315. n /= 0xffffffff;
  15316. hash ^= n;
  15317. }
  15318. return smi(hash);
  15319. }
  15320. function cachedHashString(string) {
  15321. var hashed = stringHashCache[string];
  15322. if (hashed === undefined) {
  15323. hashed = hashString(string);
  15324. if (STRING_HASH_CACHE_SIZE === STRING_HASH_CACHE_MAX_SIZE) {
  15325. STRING_HASH_CACHE_SIZE = 0;
  15326. stringHashCache = {};
  15327. }
  15328. STRING_HASH_CACHE_SIZE++;
  15329. stringHashCache[string] = hashed;
  15330. }
  15331. return hashed;
  15332. }
  15333. // http://jsperf.com/hashing-strings
  15334. function hashString(string) {
  15335. // This is the hash from JVM
  15336. // The hash code for a string is computed as
  15337. // s[0] * 31 ^ (n - 1) + s[1] * 31 ^ (n - 2) + ... + s[n - 1],
  15338. // where s[i] is the ith character of the string and n is the length of
  15339. // the string. We "mod" the result to make it between 0 (inclusive) and 2^31
  15340. // (exclusive) by dropping high bits.
  15341. var hashed = 0;
  15342. for (var ii = 0; ii < string.length; ii++) {
  15343. hashed = (31 * hashed + string.charCodeAt(ii)) | 0;
  15344. }
  15345. return smi(hashed);
  15346. }
  15347. function hashJSObj(obj) {
  15348. var hashed;
  15349. if (usingWeakMap) {
  15350. hashed = weakMap.get(obj);
  15351. if (hashed !== undefined) {
  15352. return hashed;
  15353. }
  15354. }
  15355. hashed = obj[UID_HASH_KEY];
  15356. if (hashed !== undefined) {
  15357. return hashed;
  15358. }
  15359. if (!canDefineProperty) {
  15360. hashed = obj.propertyIsEnumerable && obj.propertyIsEnumerable[UID_HASH_KEY];
  15361. if (hashed !== undefined) {
  15362. return hashed;
  15363. }
  15364. hashed = getIENodeHash(obj);
  15365. if (hashed !== undefined) {
  15366. return hashed;
  15367. }
  15368. }
  15369. hashed = ++objHashUID;
  15370. if (objHashUID & 0x40000000) {
  15371. objHashUID = 0;
  15372. }
  15373. if (usingWeakMap) {
  15374. weakMap.set(obj, hashed);
  15375. } else if (isExtensible !== undefined && isExtensible(obj) === false) {
  15376. throw new Error('Non-extensible objects are not allowed as keys.');
  15377. } else if (canDefineProperty) {
  15378. Object.defineProperty(obj, UID_HASH_KEY, {
  15379. enumerable: false,
  15380. configurable: false,
  15381. writable: false,
  15382. value: hashed,
  15383. });
  15384. } else if (
  15385. obj.propertyIsEnumerable !== undefined &&
  15386. obj.propertyIsEnumerable === obj.constructor.prototype.propertyIsEnumerable
  15387. ) {
  15388. // Since we can't define a non-enumerable property on the object
  15389. // we'll hijack one of the less-used non-enumerable properties to
  15390. // save our hash on it. Since this is a function it will not show up in
  15391. // `JSON.stringify` which is what we want.
  15392. obj.propertyIsEnumerable = function() {
  15393. return this.constructor.prototype.propertyIsEnumerable.apply(
  15394. this,
  15395. arguments
  15396. );
  15397. };
  15398. obj.propertyIsEnumerable[UID_HASH_KEY] = hashed;
  15399. } else if (obj.nodeType !== undefined) {
  15400. // At this point we couldn't get the IE `uniqueID` to use as a hash
  15401. // and we couldn't use a non-enumerable property to exploit the
  15402. // dontEnum bug so we simply add the `UID_HASH_KEY` on the node
  15403. // itself.
  15404. obj[UID_HASH_KEY] = hashed;
  15405. } else {
  15406. throw new Error('Unable to set a non-enumerable property on object.');
  15407. }
  15408. return hashed;
  15409. }
  15410. // Get references to ES5 object methods.
  15411. var isExtensible = Object.isExtensible;
  15412. // True if Object.defineProperty works as expected. IE8 fails this test.
  15413. var canDefineProperty = (function() {
  15414. try {
  15415. Object.defineProperty({}, '@', {});
  15416. return true;
  15417. } catch (e) {
  15418. return false;
  15419. }
  15420. })();
  15421. // IE has a `uniqueID` property on DOM nodes. We can construct the hash from it
  15422. // and avoid memory leaks from the IE cloneNode bug.
  15423. function getIENodeHash(node) {
  15424. if (node && node.nodeType > 0) {
  15425. switch (node.nodeType) {
  15426. case 1: // Element
  15427. return node.uniqueID;
  15428. case 9: // Document
  15429. return node.documentElement && node.documentElement.uniqueID;
  15430. }
  15431. }
  15432. }
  15433. // If possible, use a WeakMap.
  15434. var usingWeakMap = typeof WeakMap === 'function';
  15435. var weakMap;
  15436. if (usingWeakMap) {
  15437. weakMap = new WeakMap();
  15438. }
  15439. var objHashUID = 0;
  15440. var UID_HASH_KEY = '__immutablehash__';
  15441. if (typeof Symbol === 'function') {
  15442. UID_HASH_KEY = Symbol(UID_HASH_KEY);
  15443. }
  15444. var STRING_HASH_CACHE_MIN_STRLEN = 16;
  15445. var STRING_HASH_CACHE_MAX_SIZE = 255;
  15446. var STRING_HASH_CACHE_SIZE = 0;
  15447. var stringHashCache = {};
  15448. var ToKeyedSequence = /*@__PURE__*/(function (KeyedSeq$$1) {
  15449. function ToKeyedSequence(indexed, useKeys) {
  15450. this._iter = indexed;
  15451. this._useKeys = useKeys;
  15452. this.size = indexed.size;
  15453. }
  15454. if ( KeyedSeq$$1 ) ToKeyedSequence.__proto__ = KeyedSeq$$1;
  15455. ToKeyedSequence.prototype = Object.create( KeyedSeq$$1 && KeyedSeq$$1.prototype );
  15456. ToKeyedSequence.prototype.constructor = ToKeyedSequence;
  15457. ToKeyedSequence.prototype.get = function get (key, notSetValue) {
  15458. return this._iter.get(key, notSetValue);
  15459. };
  15460. ToKeyedSequence.prototype.has = function has (key) {
  15461. return this._iter.has(key);
  15462. };
  15463. ToKeyedSequence.prototype.valueSeq = function valueSeq () {
  15464. return this._iter.valueSeq();
  15465. };
  15466. ToKeyedSequence.prototype.reverse = function reverse () {
  15467. var this$1 = this;
  15468. var reversedSequence = reverseFactory(this, true);
  15469. if (!this._useKeys) {
  15470. reversedSequence.valueSeq = function () { return this$1._iter.toSeq().reverse(); };
  15471. }
  15472. return reversedSequence;
  15473. };
  15474. ToKeyedSequence.prototype.map = function map (mapper, context) {
  15475. var this$1 = this;
  15476. var mappedSequence = mapFactory(this, mapper, context);
  15477. if (!this._useKeys) {
  15478. mappedSequence.valueSeq = function () { return this$1._iter.toSeq().map(mapper, context); };
  15479. }
  15480. return mappedSequence;
  15481. };
  15482. ToKeyedSequence.prototype.__iterate = function __iterate (fn, reverse) {
  15483. var this$1 = this;
  15484. return this._iter.__iterate(function (v, k) { return fn(v, k, this$1); }, reverse);
  15485. };
  15486. ToKeyedSequence.prototype.__iterator = function __iterator (type, reverse) {
  15487. return this._iter.__iterator(type, reverse);
  15488. };
  15489. return ToKeyedSequence;
  15490. }(KeyedSeq));
  15491. ToKeyedSequence.prototype[IS_ORDERED_SYMBOL] = true;
  15492. var ToIndexedSequence = /*@__PURE__*/(function (IndexedSeq$$1) {
  15493. function ToIndexedSequence(iter) {
  15494. this._iter = iter;
  15495. this.size = iter.size;
  15496. }
  15497. if ( IndexedSeq$$1 ) ToIndexedSequence.__proto__ = IndexedSeq$$1;
  15498. ToIndexedSequence.prototype = Object.create( IndexedSeq$$1 && IndexedSeq$$1.prototype );
  15499. ToIndexedSequence.prototype.constructor = ToIndexedSequence;
  15500. ToIndexedSequence.prototype.includes = function includes (value) {
  15501. return this._iter.includes(value);
  15502. };
  15503. ToIndexedSequence.prototype.__iterate = function __iterate (fn, reverse) {
  15504. var this$1 = this;
  15505. var i = 0;
  15506. reverse && ensureSize(this);
  15507. return this._iter.__iterate(
  15508. function (v) { return fn(v, reverse ? this$1.size - ++i : i++, this$1); },
  15509. reverse
  15510. );
  15511. };
  15512. ToIndexedSequence.prototype.__iterator = function __iterator (type, reverse) {
  15513. var this$1 = this;
  15514. var iterator = this._iter.__iterator(ITERATE_VALUES, reverse);
  15515. var i = 0;
  15516. reverse && ensureSize(this);
  15517. return new Iterator(function () {
  15518. var step = iterator.next();
  15519. return step.done
  15520. ? step
  15521. : iteratorValue(
  15522. type,
  15523. reverse ? this$1.size - ++i : i++,
  15524. step.value,
  15525. step
  15526. );
  15527. });
  15528. };
  15529. return ToIndexedSequence;
  15530. }(IndexedSeq));
  15531. var ToSetSequence = /*@__PURE__*/(function (SetSeq$$1) {
  15532. function ToSetSequence(iter) {
  15533. this._iter = iter;
  15534. this.size = iter.size;
  15535. }
  15536. if ( SetSeq$$1 ) ToSetSequence.__proto__ = SetSeq$$1;
  15537. ToSetSequence.prototype = Object.create( SetSeq$$1 && SetSeq$$1.prototype );
  15538. ToSetSequence.prototype.constructor = ToSetSequence;
  15539. ToSetSequence.prototype.has = function has (key) {
  15540. return this._iter.includes(key);
  15541. };
  15542. ToSetSequence.prototype.__iterate = function __iterate (fn, reverse) {
  15543. var this$1 = this;
  15544. return this._iter.__iterate(function (v) { return fn(v, v, this$1); }, reverse);
  15545. };
  15546. ToSetSequence.prototype.__iterator = function __iterator (type, reverse) {
  15547. var iterator = this._iter.__iterator(ITERATE_VALUES, reverse);
  15548. return new Iterator(function () {
  15549. var step = iterator.next();
  15550. return step.done
  15551. ? step
  15552. : iteratorValue(type, step.value, step.value, step);
  15553. });
  15554. };
  15555. return ToSetSequence;
  15556. }(SetSeq));
  15557. var FromEntriesSequence = /*@__PURE__*/(function (KeyedSeq$$1) {
  15558. function FromEntriesSequence(entries) {
  15559. this._iter = entries;
  15560. this.size = entries.size;
  15561. }
  15562. if ( KeyedSeq$$1 ) FromEntriesSequence.__proto__ = KeyedSeq$$1;
  15563. FromEntriesSequence.prototype = Object.create( KeyedSeq$$1 && KeyedSeq$$1.prototype );
  15564. FromEntriesSequence.prototype.constructor = FromEntriesSequence;
  15565. FromEntriesSequence.prototype.entrySeq = function entrySeq () {
  15566. return this._iter.toSeq();
  15567. };
  15568. FromEntriesSequence.prototype.__iterate = function __iterate (fn, reverse) {
  15569. var this$1 = this;
  15570. return this._iter.__iterate(function (entry) {
  15571. // Check if entry exists first so array access doesn't throw for holes
  15572. // in the parent iteration.
  15573. if (entry) {
  15574. validateEntry(entry);
  15575. var indexedCollection = isCollection(entry);
  15576. return fn(
  15577. indexedCollection ? entry.get(1) : entry[1],
  15578. indexedCollection ? entry.get(0) : entry[0],
  15579. this$1
  15580. );
  15581. }
  15582. }, reverse);
  15583. };
  15584. FromEntriesSequence.prototype.__iterator = function __iterator (type, reverse) {
  15585. var iterator = this._iter.__iterator(ITERATE_VALUES, reverse);
  15586. return new Iterator(function () {
  15587. while (true) {
  15588. var step = iterator.next();
  15589. if (step.done) {
  15590. return step;
  15591. }
  15592. var entry = step.value;
  15593. // Check if entry exists first so array access doesn't throw for holes
  15594. // in the parent iteration.
  15595. if (entry) {
  15596. validateEntry(entry);
  15597. var indexedCollection = isCollection(entry);
  15598. return iteratorValue(
  15599. type,
  15600. indexedCollection ? entry.get(0) : entry[0],
  15601. indexedCollection ? entry.get(1) : entry[1],
  15602. step
  15603. );
  15604. }
  15605. }
  15606. });
  15607. };
  15608. return FromEntriesSequence;
  15609. }(KeyedSeq));
  15610. ToIndexedSequence.prototype.cacheResult = ToKeyedSequence.prototype.cacheResult = ToSetSequence.prototype.cacheResult = FromEntriesSequence.prototype.cacheResult = cacheResultThrough;
  15611. function flipFactory(collection) {
  15612. var flipSequence = makeSequence(collection);
  15613. flipSequence._iter = collection;
  15614. flipSequence.size = collection.size;
  15615. flipSequence.flip = function () { return collection; };
  15616. flipSequence.reverse = function() {
  15617. var reversedSequence = collection.reverse.apply(this); // super.reverse()
  15618. reversedSequence.flip = function () { return collection.reverse(); };
  15619. return reversedSequence;
  15620. };
  15621. flipSequence.has = function (key) { return collection.includes(key); };
  15622. flipSequence.includes = function (key) { return collection.has(key); };
  15623. flipSequence.cacheResult = cacheResultThrough;
  15624. flipSequence.__iterateUncached = function(fn, reverse) {
  15625. var this$1 = this;
  15626. return collection.__iterate(function (v, k) { return fn(k, v, this$1) !== false; }, reverse);
  15627. };
  15628. flipSequence.__iteratorUncached = function(type, reverse) {
  15629. if (type === ITERATE_ENTRIES) {
  15630. var iterator = collection.__iterator(type, reverse);
  15631. return new Iterator(function () {
  15632. var step = iterator.next();
  15633. if (!step.done) {
  15634. var k = step.value[0];
  15635. step.value[0] = step.value[1];
  15636. step.value[1] = k;
  15637. }
  15638. return step;
  15639. });
  15640. }
  15641. return collection.__iterator(
  15642. type === ITERATE_VALUES ? ITERATE_KEYS : ITERATE_VALUES,
  15643. reverse
  15644. );
  15645. };
  15646. return flipSequence;
  15647. }
  15648. function mapFactory(collection, mapper, context) {
  15649. var mappedSequence = makeSequence(collection);
  15650. mappedSequence.size = collection.size;
  15651. mappedSequence.has = function (key) { return collection.has(key); };
  15652. mappedSequence.get = function (key, notSetValue) {
  15653. var v = collection.get(key, NOT_SET);
  15654. return v === NOT_SET
  15655. ? notSetValue
  15656. : mapper.call(context, v, key, collection);
  15657. };
  15658. mappedSequence.__iterateUncached = function(fn, reverse) {
  15659. var this$1 = this;
  15660. return collection.__iterate(
  15661. function (v, k, c) { return fn(mapper.call(context, v, k, c), k, this$1) !== false; },
  15662. reverse
  15663. );
  15664. };
  15665. mappedSequence.__iteratorUncached = function(type, reverse) {
  15666. var iterator = collection.__iterator(ITERATE_ENTRIES, reverse);
  15667. return new Iterator(function () {
  15668. var step = iterator.next();
  15669. if (step.done) {
  15670. return step;
  15671. }
  15672. var entry = step.value;
  15673. var key = entry[0];
  15674. return iteratorValue(
  15675. type,
  15676. key,
  15677. mapper.call(context, entry[1], key, collection),
  15678. step
  15679. );
  15680. });
  15681. };
  15682. return mappedSequence;
  15683. }
  15684. function reverseFactory(collection, useKeys) {
  15685. var this$1 = this;
  15686. var reversedSequence = makeSequence(collection);
  15687. reversedSequence._iter = collection;
  15688. reversedSequence.size = collection.size;
  15689. reversedSequence.reverse = function () { return collection; };
  15690. if (collection.flip) {
  15691. reversedSequence.flip = function() {
  15692. var flipSequence = flipFactory(collection);
  15693. flipSequence.reverse = function () { return collection.flip(); };
  15694. return flipSequence;
  15695. };
  15696. }
  15697. reversedSequence.get = function (key, notSetValue) { return collection.get(useKeys ? key : -1 - key, notSetValue); };
  15698. reversedSequence.has = function (key) { return collection.has(useKeys ? key : -1 - key); };
  15699. reversedSequence.includes = function (value) { return collection.includes(value); };
  15700. reversedSequence.cacheResult = cacheResultThrough;
  15701. reversedSequence.__iterate = function(fn, reverse) {
  15702. var this$1 = this;
  15703. var i = 0;
  15704. reverse && ensureSize(collection);
  15705. return collection.__iterate(
  15706. function (v, k) { return fn(v, useKeys ? k : reverse ? this$1.size - ++i : i++, this$1); },
  15707. !reverse
  15708. );
  15709. };
  15710. reversedSequence.__iterator = function (type, reverse) {
  15711. var i = 0;
  15712. reverse && ensureSize(collection);
  15713. var iterator = collection.__iterator(ITERATE_ENTRIES, !reverse);
  15714. return new Iterator(function () {
  15715. var step = iterator.next();
  15716. if (step.done) {
  15717. return step;
  15718. }
  15719. var entry = step.value;
  15720. return iteratorValue(
  15721. type,
  15722. useKeys ? entry[0] : reverse ? this$1.size - ++i : i++,
  15723. entry[1],
  15724. step
  15725. );
  15726. });
  15727. };
  15728. return reversedSequence;
  15729. }
  15730. function filterFactory(collection, predicate, context, useKeys) {
  15731. var filterSequence = makeSequence(collection);
  15732. if (useKeys) {
  15733. filterSequence.has = function (key) {
  15734. var v = collection.get(key, NOT_SET);
  15735. return v !== NOT_SET && !!predicate.call(context, v, key, collection);
  15736. };
  15737. filterSequence.get = function (key, notSetValue) {
  15738. var v = collection.get(key, NOT_SET);
  15739. return v !== NOT_SET && predicate.call(context, v, key, collection)
  15740. ? v
  15741. : notSetValue;
  15742. };
  15743. }
  15744. filterSequence.__iterateUncached = function(fn, reverse) {
  15745. var this$1 = this;
  15746. var iterations = 0;
  15747. collection.__iterate(function (v, k, c) {
  15748. if (predicate.call(context, v, k, c)) {
  15749. iterations++;
  15750. return fn(v, useKeys ? k : iterations - 1, this$1);
  15751. }
  15752. }, reverse);
  15753. return iterations;
  15754. };
  15755. filterSequence.__iteratorUncached = function(type, reverse) {
  15756. var iterator = collection.__iterator(ITERATE_ENTRIES, reverse);
  15757. var iterations = 0;
  15758. return new Iterator(function () {
  15759. while (true) {
  15760. var step = iterator.next();
  15761. if (step.done) {
  15762. return step;
  15763. }
  15764. var entry = step.value;
  15765. var key = entry[0];
  15766. var value = entry[1];
  15767. if (predicate.call(context, value, key, collection)) {
  15768. return iteratorValue(type, useKeys ? key : iterations++, value, step);
  15769. }
  15770. }
  15771. });
  15772. };
  15773. return filterSequence;
  15774. }
  15775. function countByFactory(collection, grouper, context) {
  15776. var groups = Map().asMutable();
  15777. collection.__iterate(function (v, k) {
  15778. groups.update(grouper.call(context, v, k, collection), 0, function (a) { return a + 1; });
  15779. });
  15780. return groups.asImmutable();
  15781. }
  15782. function groupByFactory(collection, grouper, context) {
  15783. var isKeyedIter = isKeyed(collection);
  15784. var groups = (isOrdered(collection) ? OrderedMap() : Map()).asMutable();
  15785. collection.__iterate(function (v, k) {
  15786. groups.update(
  15787. grouper.call(context, v, k, collection),
  15788. function (a) { return ((a = a || []), a.push(isKeyedIter ? [k, v] : v), a); }
  15789. );
  15790. });
  15791. var coerce = collectionClass(collection);
  15792. return groups.map(function (arr) { return reify(collection, coerce(arr)); }).asImmutable();
  15793. }
  15794. function sliceFactory(collection, begin, end, useKeys) {
  15795. var originalSize = collection.size;
  15796. if (wholeSlice(begin, end, originalSize)) {
  15797. return collection;
  15798. }
  15799. var resolvedBegin = resolveBegin(begin, originalSize);
  15800. var resolvedEnd = resolveEnd(end, originalSize);
  15801. // begin or end will be NaN if they were provided as negative numbers and
  15802. // this collection's size is unknown. In that case, cache first so there is
  15803. // a known size and these do not resolve to NaN.
  15804. if (resolvedBegin !== resolvedBegin || resolvedEnd !== resolvedEnd) {
  15805. return sliceFactory(collection.toSeq().cacheResult(), begin, end, useKeys);
  15806. }
  15807. // Note: resolvedEnd is undefined when the original sequence's length is
  15808. // unknown and this slice did not supply an end and should contain all
  15809. // elements after resolvedBegin.
  15810. // In that case, resolvedSize will be NaN and sliceSize will remain undefined.
  15811. var resolvedSize = resolvedEnd - resolvedBegin;
  15812. var sliceSize;
  15813. if (resolvedSize === resolvedSize) {
  15814. sliceSize = resolvedSize < 0 ? 0 : resolvedSize;
  15815. }
  15816. var sliceSeq = makeSequence(collection);
  15817. // If collection.size is undefined, the size of the realized sliceSeq is
  15818. // unknown at this point unless the number of items to slice is 0
  15819. sliceSeq.size =
  15820. sliceSize === 0 ? sliceSize : (collection.size && sliceSize) || undefined;
  15821. if (!useKeys && isSeq(collection) && sliceSize >= 0) {
  15822. sliceSeq.get = function(index, notSetValue) {
  15823. index = wrapIndex(this, index);
  15824. return index >= 0 && index < sliceSize
  15825. ? collection.get(index + resolvedBegin, notSetValue)
  15826. : notSetValue;
  15827. };
  15828. }
  15829. sliceSeq.__iterateUncached = function(fn, reverse) {
  15830. var this$1 = this;
  15831. if (sliceSize === 0) {
  15832. return 0;
  15833. }
  15834. if (reverse) {
  15835. return this.cacheResult().__iterate(fn, reverse);
  15836. }
  15837. var skipped = 0;
  15838. var isSkipping = true;
  15839. var iterations = 0;
  15840. collection.__iterate(function (v, k) {
  15841. if (!(isSkipping && (isSkipping = skipped++ < resolvedBegin))) {
  15842. iterations++;
  15843. return (
  15844. fn(v, useKeys ? k : iterations - 1, this$1) !== false &&
  15845. iterations !== sliceSize
  15846. );
  15847. }
  15848. });
  15849. return iterations;
  15850. };
  15851. sliceSeq.__iteratorUncached = function(type, reverse) {
  15852. if (sliceSize !== 0 && reverse) {
  15853. return this.cacheResult().__iterator(type, reverse);
  15854. }
  15855. // Don't bother instantiating parent iterator if taking 0.
  15856. if (sliceSize === 0) {
  15857. return new Iterator(iteratorDone);
  15858. }
  15859. var iterator = collection.__iterator(type, reverse);
  15860. var skipped = 0;
  15861. var iterations = 0;
  15862. return new Iterator(function () {
  15863. while (skipped++ < resolvedBegin) {
  15864. iterator.next();
  15865. }
  15866. if (++iterations > sliceSize) {
  15867. return iteratorDone();
  15868. }
  15869. var step = iterator.next();
  15870. if (useKeys || type === ITERATE_VALUES || step.done) {
  15871. return step;
  15872. }
  15873. if (type === ITERATE_KEYS) {
  15874. return iteratorValue(type, iterations - 1, undefined, step);
  15875. }
  15876. return iteratorValue(type, iterations - 1, step.value[1], step);
  15877. });
  15878. };
  15879. return sliceSeq;
  15880. }
  15881. function takeWhileFactory(collection, predicate, context) {
  15882. var takeSequence = makeSequence(collection);
  15883. takeSequence.__iterateUncached = function(fn, reverse) {
  15884. var this$1 = this;
  15885. if (reverse) {
  15886. return this.cacheResult().__iterate(fn, reverse);
  15887. }
  15888. var iterations = 0;
  15889. collection.__iterate(
  15890. function (v, k, c) { return predicate.call(context, v, k, c) && ++iterations && fn(v, k, this$1); }
  15891. );
  15892. return iterations;
  15893. };
  15894. takeSequence.__iteratorUncached = function(type, reverse) {
  15895. var this$1 = this;
  15896. if (reverse) {
  15897. return this.cacheResult().__iterator(type, reverse);
  15898. }
  15899. var iterator = collection.__iterator(ITERATE_ENTRIES, reverse);
  15900. var iterating = true;
  15901. return new Iterator(function () {
  15902. if (!iterating) {
  15903. return iteratorDone();
  15904. }
  15905. var step = iterator.next();
  15906. if (step.done) {
  15907. return step;
  15908. }
  15909. var entry = step.value;
  15910. var k = entry[0];
  15911. var v = entry[1];
  15912. if (!predicate.call(context, v, k, this$1)) {
  15913. iterating = false;
  15914. return iteratorDone();
  15915. }
  15916. return type === ITERATE_ENTRIES ? step : iteratorValue(type, k, v, step);
  15917. });
  15918. };
  15919. return takeSequence;
  15920. }
  15921. function skipWhileFactory(collection, predicate, context, useKeys) {
  15922. var skipSequence = makeSequence(collection);
  15923. skipSequence.__iterateUncached = function(fn, reverse) {
  15924. var this$1 = this;
  15925. if (reverse) {
  15926. return this.cacheResult().__iterate(fn, reverse);
  15927. }
  15928. var isSkipping = true;
  15929. var iterations = 0;
  15930. collection.__iterate(function (v, k, c) {
  15931. if (!(isSkipping && (isSkipping = predicate.call(context, v, k, c)))) {
  15932. iterations++;
  15933. return fn(v, useKeys ? k : iterations - 1, this$1);
  15934. }
  15935. });
  15936. return iterations;
  15937. };
  15938. skipSequence.__iteratorUncached = function(type, reverse) {
  15939. var this$1 = this;
  15940. if (reverse) {
  15941. return this.cacheResult().__iterator(type, reverse);
  15942. }
  15943. var iterator = collection.__iterator(ITERATE_ENTRIES, reverse);
  15944. var skipping = true;
  15945. var iterations = 0;
  15946. return new Iterator(function () {
  15947. var step;
  15948. var k;
  15949. var v;
  15950. do {
  15951. step = iterator.next();
  15952. if (step.done) {
  15953. if (useKeys || type === ITERATE_VALUES) {
  15954. return step;
  15955. }
  15956. if (type === ITERATE_KEYS) {
  15957. return iteratorValue(type, iterations++, undefined, step);
  15958. }
  15959. return iteratorValue(type, iterations++, step.value[1], step);
  15960. }
  15961. var entry = step.value;
  15962. k = entry[0];
  15963. v = entry[1];
  15964. skipping && (skipping = predicate.call(context, v, k, this$1));
  15965. } while (skipping);
  15966. return type === ITERATE_ENTRIES ? step : iteratorValue(type, k, v, step);
  15967. });
  15968. };
  15969. return skipSequence;
  15970. }
  15971. function concatFactory(collection, values) {
  15972. var isKeyedCollection = isKeyed(collection);
  15973. var iters = [collection]
  15974. .concat(values)
  15975. .map(function (v) {
  15976. if (!isCollection(v)) {
  15977. v = isKeyedCollection
  15978. ? keyedSeqFromValue(v)
  15979. : indexedSeqFromValue(Array.isArray(v) ? v : [v]);
  15980. } else if (isKeyedCollection) {
  15981. v = KeyedCollection(v);
  15982. }
  15983. return v;
  15984. })
  15985. .filter(function (v) { return v.size !== 0; });
  15986. if (iters.length === 0) {
  15987. return collection;
  15988. }
  15989. if (iters.length === 1) {
  15990. var singleton = iters[0];
  15991. if (
  15992. singleton === collection ||
  15993. (isKeyedCollection && isKeyed(singleton)) ||
  15994. (isIndexed(collection) && isIndexed(singleton))
  15995. ) {
  15996. return singleton;
  15997. }
  15998. }
  15999. var concatSeq = new ArraySeq(iters);
  16000. if (isKeyedCollection) {
  16001. concatSeq = concatSeq.toKeyedSeq();
  16002. } else if (!isIndexed(collection)) {
  16003. concatSeq = concatSeq.toSetSeq();
  16004. }
  16005. concatSeq = concatSeq.flatten(true);
  16006. concatSeq.size = iters.reduce(function (sum, seq) {
  16007. if (sum !== undefined) {
  16008. var size = seq.size;
  16009. if (size !== undefined) {
  16010. return sum + size;
  16011. }
  16012. }
  16013. }, 0);
  16014. return concatSeq;
  16015. }
  16016. function flattenFactory(collection, depth, useKeys) {
  16017. var flatSequence = makeSequence(collection);
  16018. flatSequence.__iterateUncached = function(fn, reverse) {
  16019. if (reverse) {
  16020. return this.cacheResult().__iterate(fn, reverse);
  16021. }
  16022. var iterations = 0;
  16023. var stopped = false;
  16024. function flatDeep(iter, currentDepth) {
  16025. iter.__iterate(function (v, k) {
  16026. if ((!depth || currentDepth < depth) && isCollection(v)) {
  16027. flatDeep(v, currentDepth + 1);
  16028. } else {
  16029. iterations++;
  16030. if (fn(v, useKeys ? k : iterations - 1, flatSequence) === false) {
  16031. stopped = true;
  16032. }
  16033. }
  16034. return !stopped;
  16035. }, reverse);
  16036. }
  16037. flatDeep(collection, 0);
  16038. return iterations;
  16039. };
  16040. flatSequence.__iteratorUncached = function(type, reverse) {
  16041. if (reverse) {
  16042. return this.cacheResult().__iterator(type, reverse);
  16043. }
  16044. var iterator = collection.__iterator(type, reverse);
  16045. var stack = [];
  16046. var iterations = 0;
  16047. return new Iterator(function () {
  16048. while (iterator) {
  16049. var step = iterator.next();
  16050. if (step.done !== false) {
  16051. iterator = stack.pop();
  16052. continue;
  16053. }
  16054. var v = step.value;
  16055. if (type === ITERATE_ENTRIES) {
  16056. v = v[1];
  16057. }
  16058. if ((!depth || stack.length < depth) && isCollection(v)) {
  16059. stack.push(iterator);
  16060. iterator = v.__iterator(type, reverse);
  16061. } else {
  16062. return useKeys ? step : iteratorValue(type, iterations++, v, step);
  16063. }
  16064. }
  16065. return iteratorDone();
  16066. });
  16067. };
  16068. return flatSequence;
  16069. }
  16070. function flatMapFactory(collection, mapper, context) {
  16071. var coerce = collectionClass(collection);
  16072. return collection
  16073. .toSeq()
  16074. .map(function (v, k) { return coerce(mapper.call(context, v, k, collection)); })
  16075. .flatten(true);
  16076. }
  16077. function interposeFactory(collection, separator) {
  16078. var interposedSequence = makeSequence(collection);
  16079. interposedSequence.size = collection.size && collection.size * 2 - 1;
  16080. interposedSequence.__iterateUncached = function(fn, reverse) {
  16081. var this$1 = this;
  16082. var iterations = 0;
  16083. collection.__iterate(
  16084. function (v) { return (!iterations || fn(separator, iterations++, this$1) !== false) &&
  16085. fn(v, iterations++, this$1) !== false; },
  16086. reverse
  16087. );
  16088. return iterations;
  16089. };
  16090. interposedSequence.__iteratorUncached = function(type, reverse) {
  16091. var iterator = collection.__iterator(ITERATE_VALUES, reverse);
  16092. var iterations = 0;
  16093. var step;
  16094. return new Iterator(function () {
  16095. if (!step || iterations % 2) {
  16096. step = iterator.next();
  16097. if (step.done) {
  16098. return step;
  16099. }
  16100. }
  16101. return iterations % 2
  16102. ? iteratorValue(type, iterations++, separator)
  16103. : iteratorValue(type, iterations++, step.value, step);
  16104. });
  16105. };
  16106. return interposedSequence;
  16107. }
  16108. function sortFactory(collection, comparator, mapper) {
  16109. if (!comparator) {
  16110. comparator = defaultComparator;
  16111. }
  16112. var isKeyedCollection = isKeyed(collection);
  16113. var index = 0;
  16114. var entries = collection
  16115. .toSeq()
  16116. .map(function (v, k) { return [k, v, index++, mapper ? mapper(v, k, collection) : v]; })
  16117. .valueSeq()
  16118. .toArray();
  16119. entries.sort(function (a, b) { return comparator(a[3], b[3]) || a[2] - b[2]; }).forEach(
  16120. isKeyedCollection
  16121. ? function (v, i) {
  16122. entries[i].length = 2;
  16123. }
  16124. : function (v, i) {
  16125. entries[i] = v[1];
  16126. }
  16127. );
  16128. return isKeyedCollection
  16129. ? KeyedSeq(entries)
  16130. : isIndexed(collection)
  16131. ? IndexedSeq(entries)
  16132. : SetSeq(entries);
  16133. }
  16134. function maxFactory(collection, comparator, mapper) {
  16135. if (!comparator) {
  16136. comparator = defaultComparator;
  16137. }
  16138. if (mapper) {
  16139. var entry = collection
  16140. .toSeq()
  16141. .map(function (v, k) { return [v, mapper(v, k, collection)]; })
  16142. .reduce(function (a, b) { return (maxCompare(comparator, a[1], b[1]) ? b : a); });
  16143. return entry && entry[0];
  16144. }
  16145. return collection.reduce(function (a, b) { return (maxCompare(comparator, a, b) ? b : a); });
  16146. }
  16147. function maxCompare(comparator, a, b) {
  16148. var comp = comparator(b, a);
  16149. // b is considered the new max if the comparator declares them equal, but
  16150. // they are not equal and b is in fact a nullish value.
  16151. return (
  16152. (comp === 0 && b !== a && (b === undefined || b === null || b !== b)) ||
  16153. comp > 0
  16154. );
  16155. }
  16156. function zipWithFactory(keyIter, zipper, iters, zipAll) {
  16157. var zipSequence = makeSequence(keyIter);
  16158. var sizes = new ArraySeq(iters).map(function (i) { return i.size; });
  16159. zipSequence.size = zipAll ? sizes.max() : sizes.min();
  16160. // Note: this a generic base implementation of __iterate in terms of
  16161. // __iterator which may be more generically useful in the future.
  16162. zipSequence.__iterate = function(fn, reverse) {
  16163. /* generic:
  16164. var iterator = this.__iterator(ITERATE_ENTRIES, reverse);
  16165. var step;
  16166. var iterations = 0;
  16167. while (!(step = iterator.next()).done) {
  16168. iterations++;
  16169. if (fn(step.value[1], step.value[0], this) === false) {
  16170. break;
  16171. }
  16172. }
  16173. return iterations;
  16174. */
  16175. // indexed:
  16176. var iterator = this.__iterator(ITERATE_VALUES, reverse);
  16177. var step;
  16178. var iterations = 0;
  16179. while (!(step = iterator.next()).done) {
  16180. if (fn(step.value, iterations++, this) === false) {
  16181. break;
  16182. }
  16183. }
  16184. return iterations;
  16185. };
  16186. zipSequence.__iteratorUncached = function(type, reverse) {
  16187. var iterators = iters.map(
  16188. function (i) { return ((i = Collection(i)), getIterator(reverse ? i.reverse() : i)); }
  16189. );
  16190. var iterations = 0;
  16191. var isDone = false;
  16192. return new Iterator(function () {
  16193. var steps;
  16194. if (!isDone) {
  16195. steps = iterators.map(function (i) { return i.next(); });
  16196. isDone = zipAll ? steps.every(function (s) { return s.done; }) : steps.some(function (s) { return s.done; });
  16197. }
  16198. if (isDone) {
  16199. return iteratorDone();
  16200. }
  16201. return iteratorValue(
  16202. type,
  16203. iterations++,
  16204. zipper.apply(null, steps.map(function (s) { return s.value; }))
  16205. );
  16206. });
  16207. };
  16208. return zipSequence;
  16209. }
  16210. // #pragma Helper Functions
  16211. function reify(iter, seq) {
  16212. return iter === seq ? iter : isSeq(iter) ? seq : iter.constructor(seq);
  16213. }
  16214. function validateEntry(entry) {
  16215. if (entry !== Object(entry)) {
  16216. throw new TypeError('Expected [K, V] tuple: ' + entry);
  16217. }
  16218. }
  16219. function collectionClass(collection) {
  16220. return isKeyed(collection)
  16221. ? KeyedCollection
  16222. : isIndexed(collection)
  16223. ? IndexedCollection
  16224. : SetCollection;
  16225. }
  16226. function makeSequence(collection) {
  16227. return Object.create(
  16228. (isKeyed(collection)
  16229. ? KeyedSeq
  16230. : isIndexed(collection)
  16231. ? IndexedSeq
  16232. : SetSeq
  16233. ).prototype
  16234. );
  16235. }
  16236. function cacheResultThrough() {
  16237. if (this._iter.cacheResult) {
  16238. this._iter.cacheResult();
  16239. this.size = this._iter.size;
  16240. return this;
  16241. }
  16242. return Seq.prototype.cacheResult.call(this);
  16243. }
  16244. function defaultComparator(a, b) {
  16245. if (a === undefined && b === undefined) {
  16246. return 0;
  16247. }
  16248. if (a === undefined) {
  16249. return 1;
  16250. }
  16251. if (b === undefined) {
  16252. return -1;
  16253. }
  16254. return a > b ? 1 : a < b ? -1 : 0;
  16255. }
  16256. // http://jsperf.com/copy-array-inline
  16257. function arrCopy(arr, offset) {
  16258. offset = offset || 0;
  16259. var len = Math.max(0, arr.length - offset);
  16260. var newArr = new Array(len);
  16261. for (var ii = 0; ii < len; ii++) {
  16262. newArr[ii] = arr[ii + offset];
  16263. }
  16264. return newArr;
  16265. }
  16266. function invariant(condition, error) {
  16267. if (!condition) { throw new Error(error); }
  16268. }
  16269. function assertNotInfinite(size) {
  16270. invariant(
  16271. size !== Infinity,
  16272. 'Cannot perform this action with an infinite size.'
  16273. );
  16274. }
  16275. function coerceKeyPath(keyPath) {
  16276. if (isArrayLike(keyPath) && typeof keyPath !== 'string') {
  16277. return keyPath;
  16278. }
  16279. if (isOrdered(keyPath)) {
  16280. return keyPath.toArray();
  16281. }
  16282. throw new TypeError(
  16283. 'Invalid keyPath: expected Ordered Collection or Array: ' + keyPath
  16284. );
  16285. }
  16286. function isPlainObj(value) {
  16287. return (
  16288. value &&
  16289. (typeof value.constructor !== 'function' ||
  16290. value.constructor.name === 'Object')
  16291. );
  16292. }
  16293. /**
  16294. * Returns true if the value is a potentially-persistent data structure, either
  16295. * provided by Immutable.js or a plain Array or Object.
  16296. */
  16297. function isDataStructure(value) {
  16298. return (
  16299. typeof value === 'object' &&
  16300. (isImmutable(value) || Array.isArray(value) || isPlainObj(value))
  16301. );
  16302. }
  16303. /**
  16304. * Converts a value to a string, adding quotes if a string was provided.
  16305. */
  16306. function quoteString(value) {
  16307. try {
  16308. return typeof value === 'string' ? JSON.stringify(value) : String(value);
  16309. } catch (_ignoreError) {
  16310. return JSON.stringify(value);
  16311. }
  16312. }
  16313. function has(collection, key) {
  16314. return isImmutable(collection)
  16315. ? collection.has(key)
  16316. : isDataStructure(collection) && hasOwnProperty.call(collection, key);
  16317. }
  16318. function get(collection, key, notSetValue) {
  16319. return isImmutable(collection)
  16320. ? collection.get(key, notSetValue)
  16321. : !has(collection, key)
  16322. ? notSetValue
  16323. : typeof collection.get === 'function'
  16324. ? collection.get(key)
  16325. : collection[key];
  16326. }
  16327. function shallowCopy(from) {
  16328. if (Array.isArray(from)) {
  16329. return arrCopy(from);
  16330. }
  16331. var to = {};
  16332. for (var key in from) {
  16333. if (hasOwnProperty.call(from, key)) {
  16334. to[key] = from[key];
  16335. }
  16336. }
  16337. return to;
  16338. }
  16339. function remove(collection, key) {
  16340. if (!isDataStructure(collection)) {
  16341. throw new TypeError(
  16342. 'Cannot update non-data-structure value: ' + collection
  16343. );
  16344. }
  16345. if (isImmutable(collection)) {
  16346. if (!collection.remove) {
  16347. throw new TypeError(
  16348. 'Cannot update immutable value without .remove() method: ' + collection
  16349. );
  16350. }
  16351. return collection.remove(key);
  16352. }
  16353. if (!hasOwnProperty.call(collection, key)) {
  16354. return collection;
  16355. }
  16356. var collectionCopy = shallowCopy(collection);
  16357. if (Array.isArray(collectionCopy)) {
  16358. collectionCopy.splice(key, 1);
  16359. } else {
  16360. delete collectionCopy[key];
  16361. }
  16362. return collectionCopy;
  16363. }
  16364. function set(collection, key, value) {
  16365. if (!isDataStructure(collection)) {
  16366. throw new TypeError(
  16367. 'Cannot update non-data-structure value: ' + collection
  16368. );
  16369. }
  16370. if (isImmutable(collection)) {
  16371. if (!collection.set) {
  16372. throw new TypeError(
  16373. 'Cannot update immutable value without .set() method: ' + collection
  16374. );
  16375. }
  16376. return collection.set(key, value);
  16377. }
  16378. if (hasOwnProperty.call(collection, key) && value === collection[key]) {
  16379. return collection;
  16380. }
  16381. var collectionCopy = shallowCopy(collection);
  16382. collectionCopy[key] = value;
  16383. return collectionCopy;
  16384. }
  16385. function updateIn(collection, keyPath, notSetValue, updater) {
  16386. if (!updater) {
  16387. updater = notSetValue;
  16388. notSetValue = undefined;
  16389. }
  16390. var updatedValue = updateInDeeply(
  16391. isImmutable(collection),
  16392. collection,
  16393. coerceKeyPath(keyPath),
  16394. 0,
  16395. notSetValue,
  16396. updater
  16397. );
  16398. return updatedValue === NOT_SET ? notSetValue : updatedValue;
  16399. }
  16400. function updateInDeeply(
  16401. inImmutable,
  16402. existing,
  16403. keyPath,
  16404. i,
  16405. notSetValue,
  16406. updater
  16407. ) {
  16408. var wasNotSet = existing === NOT_SET;
  16409. if (i === keyPath.length) {
  16410. var existingValue = wasNotSet ? notSetValue : existing;
  16411. var newValue = updater(existingValue);
  16412. return newValue === existingValue ? existing : newValue;
  16413. }
  16414. if (!wasNotSet && !isDataStructure(existing)) {
  16415. throw new TypeError(
  16416. 'Cannot update within non-data-structure value in path [' +
  16417. keyPath.slice(0, i).map(quoteString) +
  16418. ']: ' +
  16419. existing
  16420. );
  16421. }
  16422. var key = keyPath[i];
  16423. var nextExisting = wasNotSet ? NOT_SET : get(existing, key, NOT_SET);
  16424. var nextUpdated = updateInDeeply(
  16425. nextExisting === NOT_SET ? inImmutable : isImmutable(nextExisting),
  16426. nextExisting,
  16427. keyPath,
  16428. i + 1,
  16429. notSetValue,
  16430. updater
  16431. );
  16432. return nextUpdated === nextExisting
  16433. ? existing
  16434. : nextUpdated === NOT_SET
  16435. ? remove(existing, key)
  16436. : set(
  16437. wasNotSet ? (inImmutable ? emptyMap() : {}) : existing,
  16438. key,
  16439. nextUpdated
  16440. );
  16441. }
  16442. function setIn(collection, keyPath, value) {
  16443. return updateIn(collection, keyPath, NOT_SET, function () { return value; });
  16444. }
  16445. function setIn$1(keyPath, v) {
  16446. return setIn(this, keyPath, v);
  16447. }
  16448. function removeIn(collection, keyPath) {
  16449. return updateIn(collection, keyPath, function () { return NOT_SET; });
  16450. }
  16451. function deleteIn(keyPath) {
  16452. return removeIn(this, keyPath);
  16453. }
  16454. function update(collection, key, notSetValue, updater) {
  16455. return updateIn(collection, [key], notSetValue, updater);
  16456. }
  16457. function update$1(key, notSetValue, updater) {
  16458. return arguments.length === 1
  16459. ? key(this)
  16460. : update(this, key, notSetValue, updater);
  16461. }
  16462. function updateIn$1(keyPath, notSetValue, updater) {
  16463. return updateIn(this, keyPath, notSetValue, updater);
  16464. }
  16465. function merge() {
  16466. var iters = [], len = arguments.length;
  16467. while ( len-- ) iters[ len ] = arguments[ len ];
  16468. return mergeIntoKeyedWith(this, iters);
  16469. }
  16470. function mergeWith(merger) {
  16471. var iters = [], len = arguments.length - 1;
  16472. while ( len-- > 0 ) iters[ len ] = arguments[ len + 1 ];
  16473. if (typeof merger !== 'function') {
  16474. throw new TypeError('Invalid merger function: ' + merger);
  16475. }
  16476. return mergeIntoKeyedWith(this, iters, merger);
  16477. }
  16478. function mergeIntoKeyedWith(collection, collections, merger) {
  16479. var iters = [];
  16480. for (var ii = 0; ii < collections.length; ii++) {
  16481. var collection$1 = KeyedCollection(collections[ii]);
  16482. if (collection$1.size !== 0) {
  16483. iters.push(collection$1);
  16484. }
  16485. }
  16486. if (iters.length === 0) {
  16487. return collection;
  16488. }
  16489. if (
  16490. collection.toSeq().size === 0 &&
  16491. !collection.__ownerID &&
  16492. iters.length === 1
  16493. ) {
  16494. return collection.constructor(iters[0]);
  16495. }
  16496. return collection.withMutations(function (collection) {
  16497. var mergeIntoCollection = merger
  16498. ? function (value, key) {
  16499. update(
  16500. collection,
  16501. key,
  16502. NOT_SET,
  16503. function (oldVal) { return (oldVal === NOT_SET ? value : merger(oldVal, value, key)); }
  16504. );
  16505. }
  16506. : function (value, key) {
  16507. collection.set(key, value);
  16508. };
  16509. for (var ii = 0; ii < iters.length; ii++) {
  16510. iters[ii].forEach(mergeIntoCollection);
  16511. }
  16512. });
  16513. }
  16514. function merge$1(collection) {
  16515. var sources = [], len = arguments.length - 1;
  16516. while ( len-- > 0 ) sources[ len ] = arguments[ len + 1 ];
  16517. return mergeWithSources(collection, sources);
  16518. }
  16519. function mergeWith$1(merger, collection) {
  16520. var sources = [], len = arguments.length - 2;
  16521. while ( len-- > 0 ) sources[ len ] = arguments[ len + 2 ];
  16522. return mergeWithSources(collection, sources, merger);
  16523. }
  16524. function mergeDeep(collection) {
  16525. var sources = [], len = arguments.length - 1;
  16526. while ( len-- > 0 ) sources[ len ] = arguments[ len + 1 ];
  16527. return mergeDeepWithSources(collection, sources);
  16528. }
  16529. function mergeDeepWith(merger, collection) {
  16530. var sources = [], len = arguments.length - 2;
  16531. while ( len-- > 0 ) sources[ len ] = arguments[ len + 2 ];
  16532. return mergeDeepWithSources(collection, sources, merger);
  16533. }
  16534. function mergeDeepWithSources(collection, sources, merger) {
  16535. return mergeWithSources(collection, sources, deepMergerWith(merger));
  16536. }
  16537. function mergeWithSources(collection, sources, merger) {
  16538. if (!isDataStructure(collection)) {
  16539. throw new TypeError(
  16540. 'Cannot merge into non-data-structure value: ' + collection
  16541. );
  16542. }
  16543. if (isImmutable(collection)) {
  16544. return typeof merger === 'function' && collection.mergeWith
  16545. ? collection.mergeWith.apply(collection, [ merger ].concat( sources ))
  16546. : collection.merge
  16547. ? collection.merge.apply(collection, sources)
  16548. : collection.concat.apply(collection, sources);
  16549. }
  16550. var isArray = Array.isArray(collection);
  16551. var merged = collection;
  16552. var Collection$$1 = isArray ? IndexedCollection : KeyedCollection;
  16553. var mergeItem = isArray
  16554. ? function (value) {
  16555. // Copy on write
  16556. if (merged === collection) {
  16557. merged = shallowCopy(merged);
  16558. }
  16559. merged.push(value);
  16560. }
  16561. : function (value, key) {
  16562. var hasVal = hasOwnProperty.call(merged, key);
  16563. var nextVal =
  16564. hasVal && merger ? merger(merged[key], value, key) : value;
  16565. if (!hasVal || nextVal !== merged[key]) {
  16566. // Copy on write
  16567. if (merged === collection) {
  16568. merged = shallowCopy(merged);
  16569. }
  16570. merged[key] = nextVal;
  16571. }
  16572. };
  16573. for (var i = 0; i < sources.length; i++) {
  16574. Collection$$1(sources[i]).forEach(mergeItem);
  16575. }
  16576. return merged;
  16577. }
  16578. function deepMergerWith(merger) {
  16579. function deepMerger(oldValue, newValue, key) {
  16580. return isDataStructure(oldValue) && isDataStructure(newValue)
  16581. ? mergeWithSources(oldValue, [newValue], deepMerger)
  16582. : merger
  16583. ? merger(oldValue, newValue, key)
  16584. : newValue;
  16585. }
  16586. return deepMerger;
  16587. }
  16588. function mergeDeep$1() {
  16589. var iters = [], len = arguments.length;
  16590. while ( len-- ) iters[ len ] = arguments[ len ];
  16591. return mergeDeepWithSources(this, iters);
  16592. }
  16593. function mergeDeepWith$1(merger) {
  16594. var iters = [], len = arguments.length - 1;
  16595. while ( len-- > 0 ) iters[ len ] = arguments[ len + 1 ];
  16596. return mergeDeepWithSources(this, iters, merger);
  16597. }
  16598. function mergeIn(keyPath) {
  16599. var iters = [], len = arguments.length - 1;
  16600. while ( len-- > 0 ) iters[ len ] = arguments[ len + 1 ];
  16601. return updateIn(this, keyPath, emptyMap(), function (m) { return mergeWithSources(m, iters); });
  16602. }
  16603. function mergeDeepIn(keyPath) {
  16604. var iters = [], len = arguments.length - 1;
  16605. while ( len-- > 0 ) iters[ len ] = arguments[ len + 1 ];
  16606. return updateIn(this, keyPath, emptyMap(), function (m) { return mergeDeepWithSources(m, iters); }
  16607. );
  16608. }
  16609. function withMutations(fn) {
  16610. var mutable = this.asMutable();
  16611. fn(mutable);
  16612. return mutable.wasAltered() ? mutable.__ensureOwner(this.__ownerID) : this;
  16613. }
  16614. function asMutable() {
  16615. return this.__ownerID ? this : this.__ensureOwner(new OwnerID());
  16616. }
  16617. function asImmutable() {
  16618. return this.__ensureOwner();
  16619. }
  16620. function wasAltered() {
  16621. return this.__altered;
  16622. }
  16623. var Map = /*@__PURE__*/(function (KeyedCollection$$1) {
  16624. function Map(value) {
  16625. return value === null || value === undefined
  16626. ? emptyMap()
  16627. : isMap(value) && !isOrdered(value)
  16628. ? value
  16629. : emptyMap().withMutations(function (map) {
  16630. var iter = KeyedCollection$$1(value);
  16631. assertNotInfinite(iter.size);
  16632. iter.forEach(function (v, k) { return map.set(k, v); });
  16633. });
  16634. }
  16635. if ( KeyedCollection$$1 ) Map.__proto__ = KeyedCollection$$1;
  16636. Map.prototype = Object.create( KeyedCollection$$1 && KeyedCollection$$1.prototype );
  16637. Map.prototype.constructor = Map;
  16638. Map.of = function of () {
  16639. var keyValues = [], len = arguments.length;
  16640. while ( len-- ) keyValues[ len ] = arguments[ len ];
  16641. return emptyMap().withMutations(function (map) {
  16642. for (var i = 0; i < keyValues.length; i += 2) {
  16643. if (i + 1 >= keyValues.length) {
  16644. throw new Error('Missing value for key: ' + keyValues[i]);
  16645. }
  16646. map.set(keyValues[i], keyValues[i + 1]);
  16647. }
  16648. });
  16649. };
  16650. Map.prototype.toString = function toString () {
  16651. return this.__toString('Map {', '}');
  16652. };
  16653. // @pragma Access
  16654. Map.prototype.get = function get (k, notSetValue) {
  16655. return this._root
  16656. ? this._root.get(0, undefined, k, notSetValue)
  16657. : notSetValue;
  16658. };
  16659. // @pragma Modification
  16660. Map.prototype.set = function set (k, v) {
  16661. return updateMap(this, k, v);
  16662. };
  16663. Map.prototype.remove = function remove (k) {
  16664. return updateMap(this, k, NOT_SET);
  16665. };
  16666. Map.prototype.deleteAll = function deleteAll (keys) {
  16667. var collection = Collection(keys);
  16668. if (collection.size === 0) {
  16669. return this;
  16670. }
  16671. return this.withMutations(function (map) {
  16672. collection.forEach(function (key) { return map.remove(key); });
  16673. });
  16674. };
  16675. Map.prototype.clear = function clear () {
  16676. if (this.size === 0) {
  16677. return this;
  16678. }
  16679. if (this.__ownerID) {
  16680. this.size = 0;
  16681. this._root = null;
  16682. this.__hash = undefined;
  16683. this.__altered = true;
  16684. return this;
  16685. }
  16686. return emptyMap();
  16687. };
  16688. // @pragma Composition
  16689. Map.prototype.sort = function sort (comparator) {
  16690. // Late binding
  16691. return OrderedMap(sortFactory(this, comparator));
  16692. };
  16693. Map.prototype.sortBy = function sortBy (mapper, comparator) {
  16694. // Late binding
  16695. return OrderedMap(sortFactory(this, comparator, mapper));
  16696. };
  16697. Map.prototype.map = function map (mapper, context) {
  16698. return this.withMutations(function (map) {
  16699. map.forEach(function (value, key) {
  16700. map.set(key, mapper.call(context, value, key, map));
  16701. });
  16702. });
  16703. };
  16704. // @pragma Mutability
  16705. Map.prototype.__iterator = function __iterator (type, reverse) {
  16706. return new MapIterator(this, type, reverse);
  16707. };
  16708. Map.prototype.__iterate = function __iterate (fn, reverse) {
  16709. var this$1 = this;
  16710. var iterations = 0;
  16711. this._root &&
  16712. this._root.iterate(function (entry) {
  16713. iterations++;
  16714. return fn(entry[1], entry[0], this$1);
  16715. }, reverse);
  16716. return iterations;
  16717. };
  16718. Map.prototype.__ensureOwner = function __ensureOwner (ownerID) {
  16719. if (ownerID === this.__ownerID) {
  16720. return this;
  16721. }
  16722. if (!ownerID) {
  16723. if (this.size === 0) {
  16724. return emptyMap();
  16725. }
  16726. this.__ownerID = ownerID;
  16727. this.__altered = false;
  16728. return this;
  16729. }
  16730. return makeMap(this.size, this._root, ownerID, this.__hash);
  16731. };
  16732. return Map;
  16733. }(KeyedCollection));
  16734. Map.isMap = isMap;
  16735. var MapPrototype = Map.prototype;
  16736. MapPrototype[IS_MAP_SYMBOL] = true;
  16737. MapPrototype[DELETE] = MapPrototype.remove;
  16738. MapPrototype.removeAll = MapPrototype.deleteAll;
  16739. MapPrototype.setIn = setIn$1;
  16740. MapPrototype.removeIn = MapPrototype.deleteIn = deleteIn;
  16741. MapPrototype.update = update$1;
  16742. MapPrototype.updateIn = updateIn$1;
  16743. MapPrototype.merge = MapPrototype.concat = merge;
  16744. MapPrototype.mergeWith = mergeWith;
  16745. MapPrototype.mergeDeep = mergeDeep$1;
  16746. MapPrototype.mergeDeepWith = mergeDeepWith$1;
  16747. MapPrototype.mergeIn = mergeIn;
  16748. MapPrototype.mergeDeepIn = mergeDeepIn;
  16749. MapPrototype.withMutations = withMutations;
  16750. MapPrototype.wasAltered = wasAltered;
  16751. MapPrototype.asImmutable = asImmutable;
  16752. MapPrototype['@@transducer/init'] = MapPrototype.asMutable = asMutable;
  16753. MapPrototype['@@transducer/step'] = function(result, arr) {
  16754. return result.set(arr[0], arr[1]);
  16755. };
  16756. MapPrototype['@@transducer/result'] = function(obj) {
  16757. return obj.asImmutable();
  16758. };
  16759. // #pragma Trie Nodes
  16760. var ArrayMapNode = function ArrayMapNode(ownerID, entries) {
  16761. this.ownerID = ownerID;
  16762. this.entries = entries;
  16763. };
  16764. ArrayMapNode.prototype.get = function get (shift, keyHash, key, notSetValue) {
  16765. var entries = this.entries;
  16766. for (var ii = 0, len = entries.length; ii < len; ii++) {
  16767. if (is(key, entries[ii][0])) {
  16768. return entries[ii][1];
  16769. }
  16770. }
  16771. return notSetValue;
  16772. };
  16773. ArrayMapNode.prototype.update = function update (ownerID, shift, keyHash, key, value, didChangeSize, didAlter) {
  16774. var removed = value === NOT_SET;
  16775. var entries = this.entries;
  16776. var idx = 0;
  16777. var len = entries.length;
  16778. for (; idx < len; idx++) {
  16779. if (is(key, entries[idx][0])) {
  16780. break;
  16781. }
  16782. }
  16783. var exists = idx < len;
  16784. if (exists ? entries[idx][1] === value : removed) {
  16785. return this;
  16786. }
  16787. SetRef(didAlter);
  16788. (removed || !exists) && SetRef(didChangeSize);
  16789. if (removed && entries.length === 1) {
  16790. return; // undefined
  16791. }
  16792. if (!exists && !removed && entries.length >= MAX_ARRAY_MAP_SIZE) {
  16793. return createNodes(ownerID, entries, key, value);
  16794. }
  16795. var isEditable = ownerID && ownerID === this.ownerID;
  16796. var newEntries = isEditable ? entries : arrCopy(entries);
  16797. if (exists) {
  16798. if (removed) {
  16799. idx === len - 1
  16800. ? newEntries.pop()
  16801. : (newEntries[idx] = newEntries.pop());
  16802. } else {
  16803. newEntries[idx] = [key, value];
  16804. }
  16805. } else {
  16806. newEntries.push([key, value]);
  16807. }
  16808. if (isEditable) {
  16809. this.entries = newEntries;
  16810. return this;
  16811. }
  16812. return new ArrayMapNode(ownerID, newEntries);
  16813. };
  16814. var BitmapIndexedNode = function BitmapIndexedNode(ownerID, bitmap, nodes) {
  16815. this.ownerID = ownerID;
  16816. this.bitmap = bitmap;
  16817. this.nodes = nodes;
  16818. };
  16819. BitmapIndexedNode.prototype.get = function get (shift, keyHash, key, notSetValue) {
  16820. if (keyHash === undefined) {
  16821. keyHash = hash(key);
  16822. }
  16823. var bit = 1 << ((shift === 0 ? keyHash : keyHash >>> shift) & MASK);
  16824. var bitmap = this.bitmap;
  16825. return (bitmap & bit) === 0
  16826. ? notSetValue
  16827. : this.nodes[popCount(bitmap & (bit - 1))].get(
  16828. shift + SHIFT,
  16829. keyHash,
  16830. key,
  16831. notSetValue
  16832. );
  16833. };
  16834. BitmapIndexedNode.prototype.update = function update (ownerID, shift, keyHash, key, value, didChangeSize, didAlter) {
  16835. if (keyHash === undefined) {
  16836. keyHash = hash(key);
  16837. }
  16838. var keyHashFrag = (shift === 0 ? keyHash : keyHash >>> shift) & MASK;
  16839. var bit = 1 << keyHashFrag;
  16840. var bitmap = this.bitmap;
  16841. var exists = (bitmap & bit) !== 0;
  16842. if (!exists && value === NOT_SET) {
  16843. return this;
  16844. }
  16845. var idx = popCount(bitmap & (bit - 1));
  16846. var nodes = this.nodes;
  16847. var node = exists ? nodes[idx] : undefined;
  16848. var newNode = updateNode(
  16849. node,
  16850. ownerID,
  16851. shift + SHIFT,
  16852. keyHash,
  16853. key,
  16854. value,
  16855. didChangeSize,
  16856. didAlter
  16857. );
  16858. if (newNode === node) {
  16859. return this;
  16860. }
  16861. if (!exists && newNode && nodes.length >= MAX_BITMAP_INDEXED_SIZE) {
  16862. return expandNodes(ownerID, nodes, bitmap, keyHashFrag, newNode);
  16863. }
  16864. if (
  16865. exists &&
  16866. !newNode &&
  16867. nodes.length === 2 &&
  16868. isLeafNode(nodes[idx ^ 1])
  16869. ) {
  16870. return nodes[idx ^ 1];
  16871. }
  16872. if (exists && newNode && nodes.length === 1 && isLeafNode(newNode)) {
  16873. return newNode;
  16874. }
  16875. var isEditable = ownerID && ownerID === this.ownerID;
  16876. var newBitmap = exists ? (newNode ? bitmap : bitmap ^ bit) : bitmap | bit;
  16877. var newNodes = exists
  16878. ? newNode
  16879. ? setAt(nodes, idx, newNode, isEditable)
  16880. : spliceOut(nodes, idx, isEditable)
  16881. : spliceIn(nodes, idx, newNode, isEditable);
  16882. if (isEditable) {
  16883. this.bitmap = newBitmap;
  16884. this.nodes = newNodes;
  16885. return this;
  16886. }
  16887. return new BitmapIndexedNode(ownerID, newBitmap, newNodes);
  16888. };
  16889. var HashArrayMapNode = function HashArrayMapNode(ownerID, count, nodes) {
  16890. this.ownerID = ownerID;
  16891. this.count = count;
  16892. this.nodes = nodes;
  16893. };
  16894. HashArrayMapNode.prototype.get = function get (shift, keyHash, key, notSetValue) {
  16895. if (keyHash === undefined) {
  16896. keyHash = hash(key);
  16897. }
  16898. var idx = (shift === 0 ? keyHash : keyHash >>> shift) & MASK;
  16899. var node = this.nodes[idx];
  16900. return node
  16901. ? node.get(shift + SHIFT, keyHash, key, notSetValue)
  16902. : notSetValue;
  16903. };
  16904. HashArrayMapNode.prototype.update = function update (ownerID, shift, keyHash, key, value, didChangeSize, didAlter) {
  16905. if (keyHash === undefined) {
  16906. keyHash = hash(key);
  16907. }
  16908. var idx = (shift === 0 ? keyHash : keyHash >>> shift) & MASK;
  16909. var removed = value === NOT_SET;
  16910. var nodes = this.nodes;
  16911. var node = nodes[idx];
  16912. if (removed && !node) {
  16913. return this;
  16914. }
  16915. var newNode = updateNode(
  16916. node,
  16917. ownerID,
  16918. shift + SHIFT,
  16919. keyHash,
  16920. key,
  16921. value,
  16922. didChangeSize,
  16923. didAlter
  16924. );
  16925. if (newNode === node) {
  16926. return this;
  16927. }
  16928. var newCount = this.count;
  16929. if (!node) {
  16930. newCount++;
  16931. } else if (!newNode) {
  16932. newCount--;
  16933. if (newCount < MIN_HASH_ARRAY_MAP_SIZE) {
  16934. return packNodes(ownerID, nodes, newCount, idx);
  16935. }
  16936. }
  16937. var isEditable = ownerID && ownerID === this.ownerID;
  16938. var newNodes = setAt(nodes, idx, newNode, isEditable);
  16939. if (isEditable) {
  16940. this.count = newCount;
  16941. this.nodes = newNodes;
  16942. return this;
  16943. }
  16944. return new HashArrayMapNode(ownerID, newCount, newNodes);
  16945. };
  16946. var HashCollisionNode = function HashCollisionNode(ownerID, keyHash, entries) {
  16947. this.ownerID = ownerID;
  16948. this.keyHash = keyHash;
  16949. this.entries = entries;
  16950. };
  16951. HashCollisionNode.prototype.get = function get (shift, keyHash, key, notSetValue) {
  16952. var entries = this.entries;
  16953. for (var ii = 0, len = entries.length; ii < len; ii++) {
  16954. if (is(key, entries[ii][0])) {
  16955. return entries[ii][1];
  16956. }
  16957. }
  16958. return notSetValue;
  16959. };
  16960. HashCollisionNode.prototype.update = function update (ownerID, shift, keyHash, key, value, didChangeSize, didAlter) {
  16961. if (keyHash === undefined) {
  16962. keyHash = hash(key);
  16963. }
  16964. var removed = value === NOT_SET;
  16965. if (keyHash !== this.keyHash) {
  16966. if (removed) {
  16967. return this;
  16968. }
  16969. SetRef(didAlter);
  16970. SetRef(didChangeSize);
  16971. return mergeIntoNode(this, ownerID, shift, keyHash, [key, value]);
  16972. }
  16973. var entries = this.entries;
  16974. var idx = 0;
  16975. var len = entries.length;
  16976. for (; idx < len; idx++) {
  16977. if (is(key, entries[idx][0])) {
  16978. break;
  16979. }
  16980. }
  16981. var exists = idx < len;
  16982. if (exists ? entries[idx][1] === value : removed) {
  16983. return this;
  16984. }
  16985. SetRef(didAlter);
  16986. (removed || !exists) && SetRef(didChangeSize);
  16987. if (removed && len === 2) {
  16988. return new ValueNode(ownerID, this.keyHash, entries[idx ^ 1]);
  16989. }
  16990. var isEditable = ownerID && ownerID === this.ownerID;
  16991. var newEntries = isEditable ? entries : arrCopy(entries);
  16992. if (exists) {
  16993. if (removed) {
  16994. idx === len - 1
  16995. ? newEntries.pop()
  16996. : (newEntries[idx] = newEntries.pop());
  16997. } else {
  16998. newEntries[idx] = [key, value];
  16999. }
  17000. } else {
  17001. newEntries.push([key, value]);
  17002. }
  17003. if (isEditable) {
  17004. this.entries = newEntries;
  17005. return this;
  17006. }
  17007. return new HashCollisionNode(ownerID, this.keyHash, newEntries);
  17008. };
  17009. var ValueNode = function ValueNode(ownerID, keyHash, entry) {
  17010. this.ownerID = ownerID;
  17011. this.keyHash = keyHash;
  17012. this.entry = entry;
  17013. };
  17014. ValueNode.prototype.get = function get (shift, keyHash, key, notSetValue) {
  17015. return is(key, this.entry[0]) ? this.entry[1] : notSetValue;
  17016. };
  17017. ValueNode.prototype.update = function update (ownerID, shift, keyHash, key, value, didChangeSize, didAlter) {
  17018. var removed = value === NOT_SET;
  17019. var keyMatch = is(key, this.entry[0]);
  17020. if (keyMatch ? value === this.entry[1] : removed) {
  17021. return this;
  17022. }
  17023. SetRef(didAlter);
  17024. if (removed) {
  17025. SetRef(didChangeSize);
  17026. return; // undefined
  17027. }
  17028. if (keyMatch) {
  17029. if (ownerID && ownerID === this.ownerID) {
  17030. this.entry[1] = value;
  17031. return this;
  17032. }
  17033. return new ValueNode(ownerID, this.keyHash, [key, value]);
  17034. }
  17035. SetRef(didChangeSize);
  17036. return mergeIntoNode(this, ownerID, shift, hash(key), [key, value]);
  17037. };
  17038. // #pragma Iterators
  17039. ArrayMapNode.prototype.iterate = HashCollisionNode.prototype.iterate = function(
  17040. fn,
  17041. reverse
  17042. ) {
  17043. var entries = this.entries;
  17044. for (var ii = 0, maxIndex = entries.length - 1; ii <= maxIndex; ii++) {
  17045. if (fn(entries[reverse ? maxIndex - ii : ii]) === false) {
  17046. return false;
  17047. }
  17048. }
  17049. };
  17050. BitmapIndexedNode.prototype.iterate = HashArrayMapNode.prototype.iterate = function(
  17051. fn,
  17052. reverse
  17053. ) {
  17054. var nodes = this.nodes;
  17055. for (var ii = 0, maxIndex = nodes.length - 1; ii <= maxIndex; ii++) {
  17056. var node = nodes[reverse ? maxIndex - ii : ii];
  17057. if (node && node.iterate(fn, reverse) === false) {
  17058. return false;
  17059. }
  17060. }
  17061. };
  17062. // eslint-disable-next-line no-unused-vars
  17063. ValueNode.prototype.iterate = function(fn, reverse) {
  17064. return fn(this.entry);
  17065. };
  17066. var MapIterator = /*@__PURE__*/(function (Iterator$$1) {
  17067. function MapIterator(map, type, reverse) {
  17068. this._type = type;
  17069. this._reverse = reverse;
  17070. this._stack = map._root && mapIteratorFrame(map._root);
  17071. }
  17072. if ( Iterator$$1 ) MapIterator.__proto__ = Iterator$$1;
  17073. MapIterator.prototype = Object.create( Iterator$$1 && Iterator$$1.prototype );
  17074. MapIterator.prototype.constructor = MapIterator;
  17075. MapIterator.prototype.next = function next () {
  17076. var type = this._type;
  17077. var stack = this._stack;
  17078. while (stack) {
  17079. var node = stack.node;
  17080. var index = stack.index++;
  17081. var maxIndex = (void 0);
  17082. if (node.entry) {
  17083. if (index === 0) {
  17084. return mapIteratorValue(type, node.entry);
  17085. }
  17086. } else if (node.entries) {
  17087. maxIndex = node.entries.length - 1;
  17088. if (index <= maxIndex) {
  17089. return mapIteratorValue(
  17090. type,
  17091. node.entries[this._reverse ? maxIndex - index : index]
  17092. );
  17093. }
  17094. } else {
  17095. maxIndex = node.nodes.length - 1;
  17096. if (index <= maxIndex) {
  17097. var subNode = node.nodes[this._reverse ? maxIndex - index : index];
  17098. if (subNode) {
  17099. if (subNode.entry) {
  17100. return mapIteratorValue(type, subNode.entry);
  17101. }
  17102. stack = this._stack = mapIteratorFrame(subNode, stack);
  17103. }
  17104. continue;
  17105. }
  17106. }
  17107. stack = this._stack = this._stack.__prev;
  17108. }
  17109. return iteratorDone();
  17110. };
  17111. return MapIterator;
  17112. }(Iterator));
  17113. function mapIteratorValue(type, entry) {
  17114. return iteratorValue(type, entry[0], entry[1]);
  17115. }
  17116. function mapIteratorFrame(node, prev) {
  17117. return {
  17118. node: node,
  17119. index: 0,
  17120. __prev: prev,
  17121. };
  17122. }
  17123. function makeMap(size, root, ownerID, hash$$1) {
  17124. var map = Object.create(MapPrototype);
  17125. map.size = size;
  17126. map._root = root;
  17127. map.__ownerID = ownerID;
  17128. map.__hash = hash$$1;
  17129. map.__altered = false;
  17130. return map;
  17131. }
  17132. var EMPTY_MAP;
  17133. function emptyMap() {
  17134. return EMPTY_MAP || (EMPTY_MAP = makeMap(0));
  17135. }
  17136. function updateMap(map, k, v) {
  17137. var newRoot;
  17138. var newSize;
  17139. if (!map._root) {
  17140. if (v === NOT_SET) {
  17141. return map;
  17142. }
  17143. newSize = 1;
  17144. newRoot = new ArrayMapNode(map.__ownerID, [[k, v]]);
  17145. } else {
  17146. var didChangeSize = MakeRef();
  17147. var didAlter = MakeRef();
  17148. newRoot = updateNode(
  17149. map._root,
  17150. map.__ownerID,
  17151. 0,
  17152. undefined,
  17153. k,
  17154. v,
  17155. didChangeSize,
  17156. didAlter
  17157. );
  17158. if (!didAlter.value) {
  17159. return map;
  17160. }
  17161. newSize = map.size + (didChangeSize.value ? (v === NOT_SET ? -1 : 1) : 0);
  17162. }
  17163. if (map.__ownerID) {
  17164. map.size = newSize;
  17165. map._root = newRoot;
  17166. map.__hash = undefined;
  17167. map.__altered = true;
  17168. return map;
  17169. }
  17170. return newRoot ? makeMap(newSize, newRoot) : emptyMap();
  17171. }
  17172. function updateNode(
  17173. node,
  17174. ownerID,
  17175. shift,
  17176. keyHash,
  17177. key,
  17178. value,
  17179. didChangeSize,
  17180. didAlter
  17181. ) {
  17182. if (!node) {
  17183. if (value === NOT_SET) {
  17184. return node;
  17185. }
  17186. SetRef(didAlter);
  17187. SetRef(didChangeSize);
  17188. return new ValueNode(ownerID, keyHash, [key, value]);
  17189. }
  17190. return node.update(
  17191. ownerID,
  17192. shift,
  17193. keyHash,
  17194. key,
  17195. value,
  17196. didChangeSize,
  17197. didAlter
  17198. );
  17199. }
  17200. function isLeafNode(node) {
  17201. return (
  17202. node.constructor === ValueNode || node.constructor === HashCollisionNode
  17203. );
  17204. }
  17205. function mergeIntoNode(node, ownerID, shift, keyHash, entry) {
  17206. if (node.keyHash === keyHash) {
  17207. return new HashCollisionNode(ownerID, keyHash, [node.entry, entry]);
  17208. }
  17209. var idx1 = (shift === 0 ? node.keyHash : node.keyHash >>> shift) & MASK;
  17210. var idx2 = (shift === 0 ? keyHash : keyHash >>> shift) & MASK;
  17211. var newNode;
  17212. var nodes =
  17213. idx1 === idx2
  17214. ? [mergeIntoNode(node, ownerID, shift + SHIFT, keyHash, entry)]
  17215. : ((newNode = new ValueNode(ownerID, keyHash, entry)),
  17216. idx1 < idx2 ? [node, newNode] : [newNode, node]);
  17217. return new BitmapIndexedNode(ownerID, (1 << idx1) | (1 << idx2), nodes);
  17218. }
  17219. function createNodes(ownerID, entries, key, value) {
  17220. if (!ownerID) {
  17221. ownerID = new OwnerID();
  17222. }
  17223. var node = new ValueNode(ownerID, hash(key), [key, value]);
  17224. for (var ii = 0; ii < entries.length; ii++) {
  17225. var entry = entries[ii];
  17226. node = node.update(ownerID, 0, undefined, entry[0], entry[1]);
  17227. }
  17228. return node;
  17229. }
  17230. function packNodes(ownerID, nodes, count, excluding) {
  17231. var bitmap = 0;
  17232. var packedII = 0;
  17233. var packedNodes = new Array(count);
  17234. for (var ii = 0, bit = 1, len = nodes.length; ii < len; ii++, bit <<= 1) {
  17235. var node = nodes[ii];
  17236. if (node !== undefined && ii !== excluding) {
  17237. bitmap |= bit;
  17238. packedNodes[packedII++] = node;
  17239. }
  17240. }
  17241. return new BitmapIndexedNode(ownerID, bitmap, packedNodes);
  17242. }
  17243. function expandNodes(ownerID, nodes, bitmap, including, node) {
  17244. var count = 0;
  17245. var expandedNodes = new Array(SIZE);
  17246. for (var ii = 0; bitmap !== 0; ii++, bitmap >>>= 1) {
  17247. expandedNodes[ii] = bitmap & 1 ? nodes[count++] : undefined;
  17248. }
  17249. expandedNodes[including] = node;
  17250. return new HashArrayMapNode(ownerID, count + 1, expandedNodes);
  17251. }
  17252. function popCount(x) {
  17253. x -= (x >> 1) & 0x55555555;
  17254. x = (x & 0x33333333) + ((x >> 2) & 0x33333333);
  17255. x = (x + (x >> 4)) & 0x0f0f0f0f;
  17256. x += x >> 8;
  17257. x += x >> 16;
  17258. return x & 0x7f;
  17259. }
  17260. function setAt(array, idx, val, canEdit) {
  17261. var newArray = canEdit ? array : arrCopy(array);
  17262. newArray[idx] = val;
  17263. return newArray;
  17264. }
  17265. function spliceIn(array, idx, val, canEdit) {
  17266. var newLen = array.length + 1;
  17267. if (canEdit && idx + 1 === newLen) {
  17268. array[idx] = val;
  17269. return array;
  17270. }
  17271. var newArray = new Array(newLen);
  17272. var after = 0;
  17273. for (var ii = 0; ii < newLen; ii++) {
  17274. if (ii === idx) {
  17275. newArray[ii] = val;
  17276. after = -1;
  17277. } else {
  17278. newArray[ii] = array[ii + after];
  17279. }
  17280. }
  17281. return newArray;
  17282. }
  17283. function spliceOut(array, idx, canEdit) {
  17284. var newLen = array.length - 1;
  17285. if (canEdit && idx === newLen) {
  17286. array.pop();
  17287. return array;
  17288. }
  17289. var newArray = new Array(newLen);
  17290. var after = 0;
  17291. for (var ii = 0; ii < newLen; ii++) {
  17292. if (ii === idx) {
  17293. after = 1;
  17294. }
  17295. newArray[ii] = array[ii + after];
  17296. }
  17297. return newArray;
  17298. }
  17299. var MAX_ARRAY_MAP_SIZE = SIZE / 4;
  17300. var MAX_BITMAP_INDEXED_SIZE = SIZE / 2;
  17301. var MIN_HASH_ARRAY_MAP_SIZE = SIZE / 4;
  17302. var IS_LIST_SYMBOL = '@@__IMMUTABLE_LIST__@@';
  17303. function isList(maybeList) {
  17304. return Boolean(maybeList && maybeList[IS_LIST_SYMBOL]);
  17305. }
  17306. var List = /*@__PURE__*/(function (IndexedCollection$$1) {
  17307. function List(value) {
  17308. var empty = emptyList();
  17309. if (value === null || value === undefined) {
  17310. return empty;
  17311. }
  17312. if (isList(value)) {
  17313. return value;
  17314. }
  17315. var iter = IndexedCollection$$1(value);
  17316. var size = iter.size;
  17317. if (size === 0) {
  17318. return empty;
  17319. }
  17320. assertNotInfinite(size);
  17321. if (size > 0 && size < SIZE) {
  17322. return makeList(0, size, SHIFT, null, new VNode(iter.toArray()));
  17323. }
  17324. return empty.withMutations(function (list) {
  17325. list.setSize(size);
  17326. iter.forEach(function (v, i) { return list.set(i, v); });
  17327. });
  17328. }
  17329. if ( IndexedCollection$$1 ) List.__proto__ = IndexedCollection$$1;
  17330. List.prototype = Object.create( IndexedCollection$$1 && IndexedCollection$$1.prototype );
  17331. List.prototype.constructor = List;
  17332. List.of = function of (/*...values*/) {
  17333. return this(arguments);
  17334. };
  17335. List.prototype.toString = function toString () {
  17336. return this.__toString('List [', ']');
  17337. };
  17338. // @pragma Access
  17339. List.prototype.get = function get (index, notSetValue) {
  17340. index = wrapIndex(this, index);
  17341. if (index >= 0 && index < this.size) {
  17342. index += this._origin;
  17343. var node = listNodeFor(this, index);
  17344. return node && node.array[index & MASK];
  17345. }
  17346. return notSetValue;
  17347. };
  17348. // @pragma Modification
  17349. List.prototype.set = function set (index, value) {
  17350. return updateList(this, index, value);
  17351. };
  17352. List.prototype.remove = function remove (index) {
  17353. return !this.has(index)
  17354. ? this
  17355. : index === 0
  17356. ? this.shift()
  17357. : index === this.size - 1
  17358. ? this.pop()
  17359. : this.splice(index, 1);
  17360. };
  17361. List.prototype.insert = function insert (index, value) {
  17362. return this.splice(index, 0, value);
  17363. };
  17364. List.prototype.clear = function clear () {
  17365. if (this.size === 0) {
  17366. return this;
  17367. }
  17368. if (this.__ownerID) {
  17369. this.size = this._origin = this._capacity = 0;
  17370. this._level = SHIFT;
  17371. this._root = this._tail = null;
  17372. this.__hash = undefined;
  17373. this.__altered = true;
  17374. return this;
  17375. }
  17376. return emptyList();
  17377. };
  17378. List.prototype.push = function push (/*...values*/) {
  17379. var values = arguments;
  17380. var oldSize = this.size;
  17381. return this.withMutations(function (list) {
  17382. setListBounds(list, 0, oldSize + values.length);
  17383. for (var ii = 0; ii < values.length; ii++) {
  17384. list.set(oldSize + ii, values[ii]);
  17385. }
  17386. });
  17387. };
  17388. List.prototype.pop = function pop () {
  17389. return setListBounds(this, 0, -1);
  17390. };
  17391. List.prototype.unshift = function unshift (/*...values*/) {
  17392. var values = arguments;
  17393. return this.withMutations(function (list) {
  17394. setListBounds(list, -values.length);
  17395. for (var ii = 0; ii < values.length; ii++) {
  17396. list.set(ii, values[ii]);
  17397. }
  17398. });
  17399. };
  17400. List.prototype.shift = function shift () {
  17401. return setListBounds(this, 1);
  17402. };
  17403. // @pragma Composition
  17404. List.prototype.concat = function concat (/*...collections*/) {
  17405. var arguments$1 = arguments;
  17406. var seqs = [];
  17407. for (var i = 0; i < arguments.length; i++) {
  17408. var argument = arguments$1[i];
  17409. var seq = IndexedCollection$$1(
  17410. typeof argument !== 'string' && hasIterator(argument)
  17411. ? argument
  17412. : [argument]
  17413. );
  17414. if (seq.size !== 0) {
  17415. seqs.push(seq);
  17416. }
  17417. }
  17418. if (seqs.length === 0) {
  17419. return this;
  17420. }
  17421. if (this.size === 0 && !this.__ownerID && seqs.length === 1) {
  17422. return this.constructor(seqs[0]);
  17423. }
  17424. return this.withMutations(function (list) {
  17425. seqs.forEach(function (seq) { return seq.forEach(function (value) { return list.push(value); }); });
  17426. });
  17427. };
  17428. List.prototype.setSize = function setSize (size) {
  17429. return setListBounds(this, 0, size);
  17430. };
  17431. List.prototype.map = function map (mapper, context) {
  17432. var this$1 = this;
  17433. return this.withMutations(function (list) {
  17434. for (var i = 0; i < this$1.size; i++) {
  17435. list.set(i, mapper.call(context, list.get(i), i, list));
  17436. }
  17437. });
  17438. };
  17439. // @pragma Iteration
  17440. List.prototype.slice = function slice (begin, end) {
  17441. var size = this.size;
  17442. if (wholeSlice(begin, end, size)) {
  17443. return this;
  17444. }
  17445. return setListBounds(
  17446. this,
  17447. resolveBegin(begin, size),
  17448. resolveEnd(end, size)
  17449. );
  17450. };
  17451. List.prototype.__iterator = function __iterator (type, reverse) {
  17452. var index = reverse ? this.size : 0;
  17453. var values = iterateList(this, reverse);
  17454. return new Iterator(function () {
  17455. var value = values();
  17456. return value === DONE
  17457. ? iteratorDone()
  17458. : iteratorValue(type, reverse ? --index : index++, value);
  17459. });
  17460. };
  17461. List.prototype.__iterate = function __iterate (fn, reverse) {
  17462. var index = reverse ? this.size : 0;
  17463. var values = iterateList(this, reverse);
  17464. var value;
  17465. while ((value = values()) !== DONE) {
  17466. if (fn(value, reverse ? --index : index++, this) === false) {
  17467. break;
  17468. }
  17469. }
  17470. return index;
  17471. };
  17472. List.prototype.__ensureOwner = function __ensureOwner (ownerID) {
  17473. if (ownerID === this.__ownerID) {
  17474. return this;
  17475. }
  17476. if (!ownerID) {
  17477. if (this.size === 0) {
  17478. return emptyList();
  17479. }
  17480. this.__ownerID = ownerID;
  17481. this.__altered = false;
  17482. return this;
  17483. }
  17484. return makeList(
  17485. this._origin,
  17486. this._capacity,
  17487. this._level,
  17488. this._root,
  17489. this._tail,
  17490. ownerID,
  17491. this.__hash
  17492. );
  17493. };
  17494. return List;
  17495. }(IndexedCollection));
  17496. List.isList = isList;
  17497. var ListPrototype = List.prototype;
  17498. ListPrototype[IS_LIST_SYMBOL] = true;
  17499. ListPrototype[DELETE] = ListPrototype.remove;
  17500. ListPrototype.merge = ListPrototype.concat;
  17501. ListPrototype.setIn = setIn$1;
  17502. ListPrototype.deleteIn = ListPrototype.removeIn = deleteIn;
  17503. ListPrototype.update = update$1;
  17504. ListPrototype.updateIn = updateIn$1;
  17505. ListPrototype.mergeIn = mergeIn;
  17506. ListPrototype.mergeDeepIn = mergeDeepIn;
  17507. ListPrototype.withMutations = withMutations;
  17508. ListPrototype.wasAltered = wasAltered;
  17509. ListPrototype.asImmutable = asImmutable;
  17510. ListPrototype['@@transducer/init'] = ListPrototype.asMutable = asMutable;
  17511. ListPrototype['@@transducer/step'] = function(result, arr) {
  17512. return result.push(arr);
  17513. };
  17514. ListPrototype['@@transducer/result'] = function(obj) {
  17515. return obj.asImmutable();
  17516. };
  17517. var VNode = function VNode(array, ownerID) {
  17518. this.array = array;
  17519. this.ownerID = ownerID;
  17520. };
  17521. // TODO: seems like these methods are very similar
  17522. VNode.prototype.removeBefore = function removeBefore (ownerID, level, index) {
  17523. if (index === level ? 1 << level : this.array.length === 0) {
  17524. return this;
  17525. }
  17526. var originIndex = (index >>> level) & MASK;
  17527. if (originIndex >= this.array.length) {
  17528. return new VNode([], ownerID);
  17529. }
  17530. var removingFirst = originIndex === 0;
  17531. var newChild;
  17532. if (level > 0) {
  17533. var oldChild = this.array[originIndex];
  17534. newChild =
  17535. oldChild && oldChild.removeBefore(ownerID, level - SHIFT, index);
  17536. if (newChild === oldChild && removingFirst) {
  17537. return this;
  17538. }
  17539. }
  17540. if (removingFirst && !newChild) {
  17541. return this;
  17542. }
  17543. var editable = editableVNode(this, ownerID);
  17544. if (!removingFirst) {
  17545. for (var ii = 0; ii < originIndex; ii++) {
  17546. editable.array[ii] = undefined;
  17547. }
  17548. }
  17549. if (newChild) {
  17550. editable.array[originIndex] = newChild;
  17551. }
  17552. return editable;
  17553. };
  17554. VNode.prototype.removeAfter = function removeAfter (ownerID, level, index) {
  17555. if (index === (level ? 1 << level : 0) || this.array.length === 0) {
  17556. return this;
  17557. }
  17558. var sizeIndex = ((index - 1) >>> level) & MASK;
  17559. if (sizeIndex >= this.array.length) {
  17560. return this;
  17561. }
  17562. var newChild;
  17563. if (level > 0) {
  17564. var oldChild = this.array[sizeIndex];
  17565. newChild =
  17566. oldChild && oldChild.removeAfter(ownerID, level - SHIFT, index);
  17567. if (newChild === oldChild && sizeIndex === this.array.length - 1) {
  17568. return this;
  17569. }
  17570. }
  17571. var editable = editableVNode(this, ownerID);
  17572. editable.array.splice(sizeIndex + 1);
  17573. if (newChild) {
  17574. editable.array[sizeIndex] = newChild;
  17575. }
  17576. return editable;
  17577. };
  17578. var DONE = {};
  17579. function iterateList(list, reverse) {
  17580. var left = list._origin;
  17581. var right = list._capacity;
  17582. var tailPos = getTailOffset(right);
  17583. var tail = list._tail;
  17584. return iterateNodeOrLeaf(list._root, list._level, 0);
  17585. function iterateNodeOrLeaf(node, level, offset) {
  17586. return level === 0
  17587. ? iterateLeaf(node, offset)
  17588. : iterateNode(node, level, offset);
  17589. }
  17590. function iterateLeaf(node, offset) {
  17591. var array = offset === tailPos ? tail && tail.array : node && node.array;
  17592. var from = offset > left ? 0 : left - offset;
  17593. var to = right - offset;
  17594. if (to > SIZE) {
  17595. to = SIZE;
  17596. }
  17597. return function () {
  17598. if (from === to) {
  17599. return DONE;
  17600. }
  17601. var idx = reverse ? --to : from++;
  17602. return array && array[idx];
  17603. };
  17604. }
  17605. function iterateNode(node, level, offset) {
  17606. var values;
  17607. var array = node && node.array;
  17608. var from = offset > left ? 0 : (left - offset) >> level;
  17609. var to = ((right - offset) >> level) + 1;
  17610. if (to > SIZE) {
  17611. to = SIZE;
  17612. }
  17613. return function () {
  17614. while (true) {
  17615. if (values) {
  17616. var value = values();
  17617. if (value !== DONE) {
  17618. return value;
  17619. }
  17620. values = null;
  17621. }
  17622. if (from === to) {
  17623. return DONE;
  17624. }
  17625. var idx = reverse ? --to : from++;
  17626. values = iterateNodeOrLeaf(
  17627. array && array[idx],
  17628. level - SHIFT,
  17629. offset + (idx << level)
  17630. );
  17631. }
  17632. };
  17633. }
  17634. }
  17635. function makeList(origin, capacity, level, root, tail, ownerID, hash) {
  17636. var list = Object.create(ListPrototype);
  17637. list.size = capacity - origin;
  17638. list._origin = origin;
  17639. list._capacity = capacity;
  17640. list._level = level;
  17641. list._root = root;
  17642. list._tail = tail;
  17643. list.__ownerID = ownerID;
  17644. list.__hash = hash;
  17645. list.__altered = false;
  17646. return list;
  17647. }
  17648. var EMPTY_LIST;
  17649. function emptyList() {
  17650. return EMPTY_LIST || (EMPTY_LIST = makeList(0, 0, SHIFT));
  17651. }
  17652. function updateList(list, index, value) {
  17653. index = wrapIndex(list, index);
  17654. if (index !== index) {
  17655. return list;
  17656. }
  17657. if (index >= list.size || index < 0) {
  17658. return list.withMutations(function (list) {
  17659. index < 0
  17660. ? setListBounds(list, index).set(0, value)
  17661. : setListBounds(list, 0, index + 1).set(index, value);
  17662. });
  17663. }
  17664. index += list._origin;
  17665. var newTail = list._tail;
  17666. var newRoot = list._root;
  17667. var didAlter = MakeRef();
  17668. if (index >= getTailOffset(list._capacity)) {
  17669. newTail = updateVNode(newTail, list.__ownerID, 0, index, value, didAlter);
  17670. } else {
  17671. newRoot = updateVNode(
  17672. newRoot,
  17673. list.__ownerID,
  17674. list._level,
  17675. index,
  17676. value,
  17677. didAlter
  17678. );
  17679. }
  17680. if (!didAlter.value) {
  17681. return list;
  17682. }
  17683. if (list.__ownerID) {
  17684. list._root = newRoot;
  17685. list._tail = newTail;
  17686. list.__hash = undefined;
  17687. list.__altered = true;
  17688. return list;
  17689. }
  17690. return makeList(list._origin, list._capacity, list._level, newRoot, newTail);
  17691. }
  17692. function updateVNode(node, ownerID, level, index, value, didAlter) {
  17693. var idx = (index >>> level) & MASK;
  17694. var nodeHas = node && idx < node.array.length;
  17695. if (!nodeHas && value === undefined) {
  17696. return node;
  17697. }
  17698. var newNode;
  17699. if (level > 0) {
  17700. var lowerNode = node && node.array[idx];
  17701. var newLowerNode = updateVNode(
  17702. lowerNode,
  17703. ownerID,
  17704. level - SHIFT,
  17705. index,
  17706. value,
  17707. didAlter
  17708. );
  17709. if (newLowerNode === lowerNode) {
  17710. return node;
  17711. }
  17712. newNode = editableVNode(node, ownerID);
  17713. newNode.array[idx] = newLowerNode;
  17714. return newNode;
  17715. }
  17716. if (nodeHas && node.array[idx] === value) {
  17717. return node;
  17718. }
  17719. if (didAlter) {
  17720. SetRef(didAlter);
  17721. }
  17722. newNode = editableVNode(node, ownerID);
  17723. if (value === undefined && idx === newNode.array.length - 1) {
  17724. newNode.array.pop();
  17725. } else {
  17726. newNode.array[idx] = value;
  17727. }
  17728. return newNode;
  17729. }
  17730. function editableVNode(node, ownerID) {
  17731. if (ownerID && node && ownerID === node.ownerID) {
  17732. return node;
  17733. }
  17734. return new VNode(node ? node.array.slice() : [], ownerID);
  17735. }
  17736. function listNodeFor(list, rawIndex) {
  17737. if (rawIndex >= getTailOffset(list._capacity)) {
  17738. return list._tail;
  17739. }
  17740. if (rawIndex < 1 << (list._level + SHIFT)) {
  17741. var node = list._root;
  17742. var level = list._level;
  17743. while (node && level > 0) {
  17744. node = node.array[(rawIndex >>> level) & MASK];
  17745. level -= SHIFT;
  17746. }
  17747. return node;
  17748. }
  17749. }
  17750. function setListBounds(list, begin, end) {
  17751. // Sanitize begin & end using this shorthand for ToInt32(argument)
  17752. // http://www.ecma-international.org/ecma-262/6.0/#sec-toint32
  17753. if (begin !== undefined) {
  17754. begin |= 0;
  17755. }
  17756. if (end !== undefined) {
  17757. end |= 0;
  17758. }
  17759. var owner = list.__ownerID || new OwnerID();
  17760. var oldOrigin = list._origin;
  17761. var oldCapacity = list._capacity;
  17762. var newOrigin = oldOrigin + begin;
  17763. var newCapacity =
  17764. end === undefined
  17765. ? oldCapacity
  17766. : end < 0
  17767. ? oldCapacity + end
  17768. : oldOrigin + end;
  17769. if (newOrigin === oldOrigin && newCapacity === oldCapacity) {
  17770. return list;
  17771. }
  17772. // If it's going to end after it starts, it's empty.
  17773. if (newOrigin >= newCapacity) {
  17774. return list.clear();
  17775. }
  17776. var newLevel = list._level;
  17777. var newRoot = list._root;
  17778. // New origin might need creating a higher root.
  17779. var offsetShift = 0;
  17780. while (newOrigin + offsetShift < 0) {
  17781. newRoot = new VNode(
  17782. newRoot && newRoot.array.length ? [undefined, newRoot] : [],
  17783. owner
  17784. );
  17785. newLevel += SHIFT;
  17786. offsetShift += 1 << newLevel;
  17787. }
  17788. if (offsetShift) {
  17789. newOrigin += offsetShift;
  17790. oldOrigin += offsetShift;
  17791. newCapacity += offsetShift;
  17792. oldCapacity += offsetShift;
  17793. }
  17794. var oldTailOffset = getTailOffset(oldCapacity);
  17795. var newTailOffset = getTailOffset(newCapacity);
  17796. // New size might need creating a higher root.
  17797. while (newTailOffset >= 1 << (newLevel + SHIFT)) {
  17798. newRoot = new VNode(
  17799. newRoot && newRoot.array.length ? [newRoot] : [],
  17800. owner
  17801. );
  17802. newLevel += SHIFT;
  17803. }
  17804. // Locate or create the new tail.
  17805. var oldTail = list._tail;
  17806. var newTail =
  17807. newTailOffset < oldTailOffset
  17808. ? listNodeFor(list, newCapacity - 1)
  17809. : newTailOffset > oldTailOffset
  17810. ? new VNode([], owner)
  17811. : oldTail;
  17812. // Merge Tail into tree.
  17813. if (
  17814. oldTail &&
  17815. newTailOffset > oldTailOffset &&
  17816. newOrigin < oldCapacity &&
  17817. oldTail.array.length
  17818. ) {
  17819. newRoot = editableVNode(newRoot, owner);
  17820. var node = newRoot;
  17821. for (var level = newLevel; level > SHIFT; level -= SHIFT) {
  17822. var idx = (oldTailOffset >>> level) & MASK;
  17823. node = node.array[idx] = editableVNode(node.array[idx], owner);
  17824. }
  17825. node.array[(oldTailOffset >>> SHIFT) & MASK] = oldTail;
  17826. }
  17827. // If the size has been reduced, there's a chance the tail needs to be trimmed.
  17828. if (newCapacity < oldCapacity) {
  17829. newTail = newTail && newTail.removeAfter(owner, 0, newCapacity);
  17830. }
  17831. // If the new origin is within the tail, then we do not need a root.
  17832. if (newOrigin >= newTailOffset) {
  17833. newOrigin -= newTailOffset;
  17834. newCapacity -= newTailOffset;
  17835. newLevel = SHIFT;
  17836. newRoot = null;
  17837. newTail = newTail && newTail.removeBefore(owner, 0, newOrigin);
  17838. // Otherwise, if the root has been trimmed, garbage collect.
  17839. } else if (newOrigin > oldOrigin || newTailOffset < oldTailOffset) {
  17840. offsetShift = 0;
  17841. // Identify the new top root node of the subtree of the old root.
  17842. while (newRoot) {
  17843. var beginIndex = (newOrigin >>> newLevel) & MASK;
  17844. if ((beginIndex !== newTailOffset >>> newLevel) & MASK) {
  17845. break;
  17846. }
  17847. if (beginIndex) {
  17848. offsetShift += (1 << newLevel) * beginIndex;
  17849. }
  17850. newLevel -= SHIFT;
  17851. newRoot = newRoot.array[beginIndex];
  17852. }
  17853. // Trim the new sides of the new root.
  17854. if (newRoot && newOrigin > oldOrigin) {
  17855. newRoot = newRoot.removeBefore(owner, newLevel, newOrigin - offsetShift);
  17856. }
  17857. if (newRoot && newTailOffset < oldTailOffset) {
  17858. newRoot = newRoot.removeAfter(
  17859. owner,
  17860. newLevel,
  17861. newTailOffset - offsetShift
  17862. );
  17863. }
  17864. if (offsetShift) {
  17865. newOrigin -= offsetShift;
  17866. newCapacity -= offsetShift;
  17867. }
  17868. }
  17869. if (list.__ownerID) {
  17870. list.size = newCapacity - newOrigin;
  17871. list._origin = newOrigin;
  17872. list._capacity = newCapacity;
  17873. list._level = newLevel;
  17874. list._root = newRoot;
  17875. list._tail = newTail;
  17876. list.__hash = undefined;
  17877. list.__altered = true;
  17878. return list;
  17879. }
  17880. return makeList(newOrigin, newCapacity, newLevel, newRoot, newTail);
  17881. }
  17882. function getTailOffset(size) {
  17883. return size < SIZE ? 0 : ((size - 1) >>> SHIFT) << SHIFT;
  17884. }
  17885. var OrderedMap = /*@__PURE__*/(function (Map$$1) {
  17886. function OrderedMap(value) {
  17887. return value === null || value === undefined
  17888. ? emptyOrderedMap()
  17889. : isOrderedMap(value)
  17890. ? value
  17891. : emptyOrderedMap().withMutations(function (map) {
  17892. var iter = KeyedCollection(value);
  17893. assertNotInfinite(iter.size);
  17894. iter.forEach(function (v, k) { return map.set(k, v); });
  17895. });
  17896. }
  17897. if ( Map$$1 ) OrderedMap.__proto__ = Map$$1;
  17898. OrderedMap.prototype = Object.create( Map$$1 && Map$$1.prototype );
  17899. OrderedMap.prototype.constructor = OrderedMap;
  17900. OrderedMap.of = function of (/*...values*/) {
  17901. return this(arguments);
  17902. };
  17903. OrderedMap.prototype.toString = function toString () {
  17904. return this.__toString('OrderedMap {', '}');
  17905. };
  17906. // @pragma Access
  17907. OrderedMap.prototype.get = function get (k, notSetValue) {
  17908. var index = this._map.get(k);
  17909. return index !== undefined ? this._list.get(index)[1] : notSetValue;
  17910. };
  17911. // @pragma Modification
  17912. OrderedMap.prototype.clear = function clear () {
  17913. if (this.size === 0) {
  17914. return this;
  17915. }
  17916. if (this.__ownerID) {
  17917. this.size = 0;
  17918. this._map.clear();
  17919. this._list.clear();
  17920. return this;
  17921. }
  17922. return emptyOrderedMap();
  17923. };
  17924. OrderedMap.prototype.set = function set (k, v) {
  17925. return updateOrderedMap(this, k, v);
  17926. };
  17927. OrderedMap.prototype.remove = function remove (k) {
  17928. return updateOrderedMap(this, k, NOT_SET);
  17929. };
  17930. OrderedMap.prototype.wasAltered = function wasAltered () {
  17931. return this._map.wasAltered() || this._list.wasAltered();
  17932. };
  17933. OrderedMap.prototype.__iterate = function __iterate (fn, reverse) {
  17934. var this$1 = this;
  17935. return this._list.__iterate(
  17936. function (entry) { return entry && fn(entry[1], entry[0], this$1); },
  17937. reverse
  17938. );
  17939. };
  17940. OrderedMap.prototype.__iterator = function __iterator (type, reverse) {
  17941. return this._list.fromEntrySeq().__iterator(type, reverse);
  17942. };
  17943. OrderedMap.prototype.__ensureOwner = function __ensureOwner (ownerID) {
  17944. if (ownerID === this.__ownerID) {
  17945. return this;
  17946. }
  17947. var newMap = this._map.__ensureOwner(ownerID);
  17948. var newList = this._list.__ensureOwner(ownerID);
  17949. if (!ownerID) {
  17950. if (this.size === 0) {
  17951. return emptyOrderedMap();
  17952. }
  17953. this.__ownerID = ownerID;
  17954. this._map = newMap;
  17955. this._list = newList;
  17956. return this;
  17957. }
  17958. return makeOrderedMap(newMap, newList, ownerID, this.__hash);
  17959. };
  17960. return OrderedMap;
  17961. }(Map));
  17962. OrderedMap.isOrderedMap = isOrderedMap;
  17963. OrderedMap.prototype[IS_ORDERED_SYMBOL] = true;
  17964. OrderedMap.prototype[DELETE] = OrderedMap.prototype.remove;
  17965. function makeOrderedMap(map, list, ownerID, hash) {
  17966. var omap = Object.create(OrderedMap.prototype);
  17967. omap.size = map ? map.size : 0;
  17968. omap._map = map;
  17969. omap._list = list;
  17970. omap.__ownerID = ownerID;
  17971. omap.__hash = hash;
  17972. return omap;
  17973. }
  17974. var EMPTY_ORDERED_MAP;
  17975. function emptyOrderedMap() {
  17976. return (
  17977. EMPTY_ORDERED_MAP ||
  17978. (EMPTY_ORDERED_MAP = makeOrderedMap(emptyMap(), emptyList()))
  17979. );
  17980. }
  17981. function updateOrderedMap(omap, k, v) {
  17982. var map = omap._map;
  17983. var list = omap._list;
  17984. var i = map.get(k);
  17985. var has = i !== undefined;
  17986. var newMap;
  17987. var newList;
  17988. if (v === NOT_SET) {
  17989. // removed
  17990. if (!has) {
  17991. return omap;
  17992. }
  17993. if (list.size >= SIZE && list.size >= map.size * 2) {
  17994. newList = list.filter(function (entry, idx) { return entry !== undefined && i !== idx; });
  17995. newMap = newList
  17996. .toKeyedSeq()
  17997. .map(function (entry) { return entry[0]; })
  17998. .flip()
  17999. .toMap();
  18000. if (omap.__ownerID) {
  18001. newMap.__ownerID = newList.__ownerID = omap.__ownerID;
  18002. }
  18003. } else {
  18004. newMap = map.remove(k);
  18005. newList = i === list.size - 1 ? list.pop() : list.set(i, undefined);
  18006. }
  18007. } else if (has) {
  18008. if (v === list.get(i)[1]) {
  18009. return omap;
  18010. }
  18011. newMap = map;
  18012. newList = list.set(i, [k, v]);
  18013. } else {
  18014. newMap = map.set(k, list.size);
  18015. newList = list.set(list.size, [k, v]);
  18016. }
  18017. if (omap.__ownerID) {
  18018. omap.size = newMap.size;
  18019. omap._map = newMap;
  18020. omap._list = newList;
  18021. omap.__hash = undefined;
  18022. return omap;
  18023. }
  18024. return makeOrderedMap(newMap, newList);
  18025. }
  18026. var IS_STACK_SYMBOL = '@@__IMMUTABLE_STACK__@@';
  18027. function isStack(maybeStack) {
  18028. return Boolean(maybeStack && maybeStack[IS_STACK_SYMBOL]);
  18029. }
  18030. var Stack = /*@__PURE__*/(function (IndexedCollection$$1) {
  18031. function Stack(value) {
  18032. return value === null || value === undefined
  18033. ? emptyStack()
  18034. : isStack(value)
  18035. ? value
  18036. : emptyStack().pushAll(value);
  18037. }
  18038. if ( IndexedCollection$$1 ) Stack.__proto__ = IndexedCollection$$1;
  18039. Stack.prototype = Object.create( IndexedCollection$$1 && IndexedCollection$$1.prototype );
  18040. Stack.prototype.constructor = Stack;
  18041. Stack.of = function of (/*...values*/) {
  18042. return this(arguments);
  18043. };
  18044. Stack.prototype.toString = function toString () {
  18045. return this.__toString('Stack [', ']');
  18046. };
  18047. // @pragma Access
  18048. Stack.prototype.get = function get (index, notSetValue) {
  18049. var head = this._head;
  18050. index = wrapIndex(this, index);
  18051. while (head && index--) {
  18052. head = head.next;
  18053. }
  18054. return head ? head.value : notSetValue;
  18055. };
  18056. Stack.prototype.peek = function peek () {
  18057. return this._head && this._head.value;
  18058. };
  18059. // @pragma Modification
  18060. Stack.prototype.push = function push (/*...values*/) {
  18061. var arguments$1 = arguments;
  18062. if (arguments.length === 0) {
  18063. return this;
  18064. }
  18065. var newSize = this.size + arguments.length;
  18066. var head = this._head;
  18067. for (var ii = arguments.length - 1; ii >= 0; ii--) {
  18068. head = {
  18069. value: arguments$1[ii],
  18070. next: head,
  18071. };
  18072. }
  18073. if (this.__ownerID) {
  18074. this.size = newSize;
  18075. this._head = head;
  18076. this.__hash = undefined;
  18077. this.__altered = true;
  18078. return this;
  18079. }
  18080. return makeStack(newSize, head);
  18081. };
  18082. Stack.prototype.pushAll = function pushAll (iter) {
  18083. iter = IndexedCollection$$1(iter);
  18084. if (iter.size === 0) {
  18085. return this;
  18086. }
  18087. if (this.size === 0 && isStack(iter)) {
  18088. return iter;
  18089. }
  18090. assertNotInfinite(iter.size);
  18091. var newSize = this.size;
  18092. var head = this._head;
  18093. iter.__iterate(function (value) {
  18094. newSize++;
  18095. head = {
  18096. value: value,
  18097. next: head,
  18098. };
  18099. }, /* reverse */ true);
  18100. if (this.__ownerID) {
  18101. this.size = newSize;
  18102. this._head = head;
  18103. this.__hash = undefined;
  18104. this.__altered = true;
  18105. return this;
  18106. }
  18107. return makeStack(newSize, head);
  18108. };
  18109. Stack.prototype.pop = function pop () {
  18110. return this.slice(1);
  18111. };
  18112. Stack.prototype.clear = function clear () {
  18113. if (this.size === 0) {
  18114. return this;
  18115. }
  18116. if (this.__ownerID) {
  18117. this.size = 0;
  18118. this._head = undefined;
  18119. this.__hash = undefined;
  18120. this.__altered = true;
  18121. return this;
  18122. }
  18123. return emptyStack();
  18124. };
  18125. Stack.prototype.slice = function slice (begin, end) {
  18126. if (wholeSlice(begin, end, this.size)) {
  18127. return this;
  18128. }
  18129. var resolvedBegin = resolveBegin(begin, this.size);
  18130. var resolvedEnd = resolveEnd(end, this.size);
  18131. if (resolvedEnd !== this.size) {
  18132. // super.slice(begin, end);
  18133. return IndexedCollection$$1.prototype.slice.call(this, begin, end);
  18134. }
  18135. var newSize = this.size - resolvedBegin;
  18136. var head = this._head;
  18137. while (resolvedBegin--) {
  18138. head = head.next;
  18139. }
  18140. if (this.__ownerID) {
  18141. this.size = newSize;
  18142. this._head = head;
  18143. this.__hash = undefined;
  18144. this.__altered = true;
  18145. return this;
  18146. }
  18147. return makeStack(newSize, head);
  18148. };
  18149. // @pragma Mutability
  18150. Stack.prototype.__ensureOwner = function __ensureOwner (ownerID) {
  18151. if (ownerID === this.__ownerID) {
  18152. return this;
  18153. }
  18154. if (!ownerID) {
  18155. if (this.size === 0) {
  18156. return emptyStack();
  18157. }
  18158. this.__ownerID = ownerID;
  18159. this.__altered = false;
  18160. return this;
  18161. }
  18162. return makeStack(this.size, this._head, ownerID, this.__hash);
  18163. };
  18164. // @pragma Iteration
  18165. Stack.prototype.__iterate = function __iterate (fn, reverse) {
  18166. var this$1 = this;
  18167. if (reverse) {
  18168. return new ArraySeq(this.toArray()).__iterate(
  18169. function (v, k) { return fn(v, k, this$1); },
  18170. reverse
  18171. );
  18172. }
  18173. var iterations = 0;
  18174. var node = this._head;
  18175. while (node) {
  18176. if (fn(node.value, iterations++, this) === false) {
  18177. break;
  18178. }
  18179. node = node.next;
  18180. }
  18181. return iterations;
  18182. };
  18183. Stack.prototype.__iterator = function __iterator (type, reverse) {
  18184. if (reverse) {
  18185. return new ArraySeq(this.toArray()).__iterator(type, reverse);
  18186. }
  18187. var iterations = 0;
  18188. var node = this._head;
  18189. return new Iterator(function () {
  18190. if (node) {
  18191. var value = node.value;
  18192. node = node.next;
  18193. return iteratorValue(type, iterations++, value);
  18194. }
  18195. return iteratorDone();
  18196. });
  18197. };
  18198. return Stack;
  18199. }(IndexedCollection));
  18200. Stack.isStack = isStack;
  18201. var StackPrototype = Stack.prototype;
  18202. StackPrototype[IS_STACK_SYMBOL] = true;
  18203. StackPrototype.shift = StackPrototype.pop;
  18204. StackPrototype.unshift = StackPrototype.push;
  18205. StackPrototype.unshiftAll = StackPrototype.pushAll;
  18206. StackPrototype.withMutations = withMutations;
  18207. StackPrototype.wasAltered = wasAltered;
  18208. StackPrototype.asImmutable = asImmutable;
  18209. StackPrototype['@@transducer/init'] = StackPrototype.asMutable = asMutable;
  18210. StackPrototype['@@transducer/step'] = function(result, arr) {
  18211. return result.unshift(arr);
  18212. };
  18213. StackPrototype['@@transducer/result'] = function(obj) {
  18214. return obj.asImmutable();
  18215. };
  18216. function makeStack(size, head, ownerID, hash) {
  18217. var map = Object.create(StackPrototype);
  18218. map.size = size;
  18219. map._head = head;
  18220. map.__ownerID = ownerID;
  18221. map.__hash = hash;
  18222. map.__altered = false;
  18223. return map;
  18224. }
  18225. var EMPTY_STACK;
  18226. function emptyStack() {
  18227. return EMPTY_STACK || (EMPTY_STACK = makeStack(0));
  18228. }
  18229. var IS_SET_SYMBOL = '@@__IMMUTABLE_SET__@@';
  18230. function isSet(maybeSet) {
  18231. return Boolean(maybeSet && maybeSet[IS_SET_SYMBOL]);
  18232. }
  18233. function isOrderedSet(maybeOrderedSet) {
  18234. return isSet(maybeOrderedSet) && isOrdered(maybeOrderedSet);
  18235. }
  18236. function deepEqual(a, b) {
  18237. if (a === b) {
  18238. return true;
  18239. }
  18240. if (
  18241. !isCollection(b) ||
  18242. (a.size !== undefined && b.size !== undefined && a.size !== b.size) ||
  18243. (a.__hash !== undefined &&
  18244. b.__hash !== undefined &&
  18245. a.__hash !== b.__hash) ||
  18246. isKeyed(a) !== isKeyed(b) ||
  18247. isIndexed(a) !== isIndexed(b) ||
  18248. isOrdered(a) !== isOrdered(b)
  18249. ) {
  18250. return false;
  18251. }
  18252. if (a.size === 0 && b.size === 0) {
  18253. return true;
  18254. }
  18255. var notAssociative = !isAssociative(a);
  18256. if (isOrdered(a)) {
  18257. var entries = a.entries();
  18258. return (
  18259. b.every(function (v, k) {
  18260. var entry = entries.next().value;
  18261. return entry && is(entry[1], v) && (notAssociative || is(entry[0], k));
  18262. }) && entries.next().done
  18263. );
  18264. }
  18265. var flipped = false;
  18266. if (a.size === undefined) {
  18267. if (b.size === undefined) {
  18268. if (typeof a.cacheResult === 'function') {
  18269. a.cacheResult();
  18270. }
  18271. } else {
  18272. flipped = true;
  18273. var _ = a;
  18274. a = b;
  18275. b = _;
  18276. }
  18277. }
  18278. var allEqual = true;
  18279. var bSize = b.__iterate(function (v, k) {
  18280. if (
  18281. notAssociative
  18282. ? !a.has(v)
  18283. : flipped
  18284. ? !is(v, a.get(k, NOT_SET))
  18285. : !is(a.get(k, NOT_SET), v)
  18286. ) {
  18287. allEqual = false;
  18288. return false;
  18289. }
  18290. });
  18291. return allEqual && a.size === bSize;
  18292. }
  18293. /**
  18294. * Contributes additional methods to a constructor
  18295. */
  18296. function mixin(ctor, methods) {
  18297. var keyCopier = function (key) {
  18298. ctor.prototype[key] = methods[key];
  18299. };
  18300. Object.keys(methods).forEach(keyCopier);
  18301. Object.getOwnPropertySymbols &&
  18302. Object.getOwnPropertySymbols(methods).forEach(keyCopier);
  18303. return ctor;
  18304. }
  18305. function toJS(value) {
  18306. if (!value || typeof value !== 'object') {
  18307. return value;
  18308. }
  18309. if (!isCollection(value)) {
  18310. if (!isDataStructure(value)) {
  18311. return value;
  18312. }
  18313. value = Seq(value);
  18314. }
  18315. if (isKeyed(value)) {
  18316. var result$1 = {};
  18317. value.__iterate(function (v, k) {
  18318. result$1[k] = toJS(v);
  18319. });
  18320. return result$1;
  18321. }
  18322. var result = [];
  18323. value.__iterate(function (v) {
  18324. result.push(toJS(v));
  18325. });
  18326. return result;
  18327. }
  18328. var Set = /*@__PURE__*/(function (SetCollection$$1) {
  18329. function Set(value) {
  18330. return value === null || value === undefined
  18331. ? emptySet()
  18332. : isSet(value) && !isOrdered(value)
  18333. ? value
  18334. : emptySet().withMutations(function (set) {
  18335. var iter = SetCollection$$1(value);
  18336. assertNotInfinite(iter.size);
  18337. iter.forEach(function (v) { return set.add(v); });
  18338. });
  18339. }
  18340. if ( SetCollection$$1 ) Set.__proto__ = SetCollection$$1;
  18341. Set.prototype = Object.create( SetCollection$$1 && SetCollection$$1.prototype );
  18342. Set.prototype.constructor = Set;
  18343. Set.of = function of (/*...values*/) {
  18344. return this(arguments);
  18345. };
  18346. Set.fromKeys = function fromKeys (value) {
  18347. return this(KeyedCollection(value).keySeq());
  18348. };
  18349. Set.intersect = function intersect (sets) {
  18350. sets = Collection(sets).toArray();
  18351. return sets.length
  18352. ? SetPrototype.intersect.apply(Set(sets.pop()), sets)
  18353. : emptySet();
  18354. };
  18355. Set.union = function union (sets) {
  18356. sets = Collection(sets).toArray();
  18357. return sets.length
  18358. ? SetPrototype.union.apply(Set(sets.pop()), sets)
  18359. : emptySet();
  18360. };
  18361. Set.prototype.toString = function toString () {
  18362. return this.__toString('Set {', '}');
  18363. };
  18364. // @pragma Access
  18365. Set.prototype.has = function has (value) {
  18366. return this._map.has(value);
  18367. };
  18368. // @pragma Modification
  18369. Set.prototype.add = function add (value) {
  18370. return updateSet(this, this._map.set(value, value));
  18371. };
  18372. Set.prototype.remove = function remove (value) {
  18373. return updateSet(this, this._map.remove(value));
  18374. };
  18375. Set.prototype.clear = function clear () {
  18376. return updateSet(this, this._map.clear());
  18377. };
  18378. // @pragma Composition
  18379. Set.prototype.map = function map (mapper, context) {
  18380. var this$1 = this;
  18381. var removes = [];
  18382. var adds = [];
  18383. this.forEach(function (value) {
  18384. var mapped = mapper.call(context, value, value, this$1);
  18385. if (mapped !== value) {
  18386. removes.push(value);
  18387. adds.push(mapped);
  18388. }
  18389. });
  18390. return this.withMutations(function (set) {
  18391. removes.forEach(function (value) { return set.remove(value); });
  18392. adds.forEach(function (value) { return set.add(value); });
  18393. });
  18394. };
  18395. Set.prototype.union = function union () {
  18396. var iters = [], len = arguments.length;
  18397. while ( len-- ) iters[ len ] = arguments[ len ];
  18398. iters = iters.filter(function (x) { return x.size !== 0; });
  18399. if (iters.length === 0) {
  18400. return this;
  18401. }
  18402. if (this.size === 0 && !this.__ownerID && iters.length === 1) {
  18403. return this.constructor(iters[0]);
  18404. }
  18405. return this.withMutations(function (set) {
  18406. for (var ii = 0; ii < iters.length; ii++) {
  18407. SetCollection$$1(iters[ii]).forEach(function (value) { return set.add(value); });
  18408. }
  18409. });
  18410. };
  18411. Set.prototype.intersect = function intersect () {
  18412. var iters = [], len = arguments.length;
  18413. while ( len-- ) iters[ len ] = arguments[ len ];
  18414. if (iters.length === 0) {
  18415. return this;
  18416. }
  18417. iters = iters.map(function (iter) { return SetCollection$$1(iter); });
  18418. var toRemove = [];
  18419. this.forEach(function (value) {
  18420. if (!iters.every(function (iter) { return iter.includes(value); })) {
  18421. toRemove.push(value);
  18422. }
  18423. });
  18424. return this.withMutations(function (set) {
  18425. toRemove.forEach(function (value) {
  18426. set.remove(value);
  18427. });
  18428. });
  18429. };
  18430. Set.prototype.subtract = function subtract () {
  18431. var iters = [], len = arguments.length;
  18432. while ( len-- ) iters[ len ] = arguments[ len ];
  18433. if (iters.length === 0) {
  18434. return this;
  18435. }
  18436. iters = iters.map(function (iter) { return SetCollection$$1(iter); });
  18437. var toRemove = [];
  18438. this.forEach(function (value) {
  18439. if (iters.some(function (iter) { return iter.includes(value); })) {
  18440. toRemove.push(value);
  18441. }
  18442. });
  18443. return this.withMutations(function (set) {
  18444. toRemove.forEach(function (value) {
  18445. set.remove(value);
  18446. });
  18447. });
  18448. };
  18449. Set.prototype.sort = function sort (comparator) {
  18450. // Late binding
  18451. return OrderedSet(sortFactory(this, comparator));
  18452. };
  18453. Set.prototype.sortBy = function sortBy (mapper, comparator) {
  18454. // Late binding
  18455. return OrderedSet(sortFactory(this, comparator, mapper));
  18456. };
  18457. Set.prototype.wasAltered = function wasAltered () {
  18458. return this._map.wasAltered();
  18459. };
  18460. Set.prototype.__iterate = function __iterate (fn, reverse) {
  18461. var this$1 = this;
  18462. return this._map.__iterate(function (k) { return fn(k, k, this$1); }, reverse);
  18463. };
  18464. Set.prototype.__iterator = function __iterator (type, reverse) {
  18465. return this._map.__iterator(type, reverse);
  18466. };
  18467. Set.prototype.__ensureOwner = function __ensureOwner (ownerID) {
  18468. if (ownerID === this.__ownerID) {
  18469. return this;
  18470. }
  18471. var newMap = this._map.__ensureOwner(ownerID);
  18472. if (!ownerID) {
  18473. if (this.size === 0) {
  18474. return this.__empty();
  18475. }
  18476. this.__ownerID = ownerID;
  18477. this._map = newMap;
  18478. return this;
  18479. }
  18480. return this.__make(newMap, ownerID);
  18481. };
  18482. return Set;
  18483. }(SetCollection));
  18484. Set.isSet = isSet;
  18485. var SetPrototype = Set.prototype;
  18486. SetPrototype[IS_SET_SYMBOL] = true;
  18487. SetPrototype[DELETE] = SetPrototype.remove;
  18488. SetPrototype.merge = SetPrototype.concat = SetPrototype.union;
  18489. SetPrototype.withMutations = withMutations;
  18490. SetPrototype.asImmutable = asImmutable;
  18491. SetPrototype['@@transducer/init'] = SetPrototype.asMutable = asMutable;
  18492. SetPrototype['@@transducer/step'] = function(result, arr) {
  18493. return result.add(arr);
  18494. };
  18495. SetPrototype['@@transducer/result'] = function(obj) {
  18496. return obj.asImmutable();
  18497. };
  18498. SetPrototype.__empty = emptySet;
  18499. SetPrototype.__make = makeSet;
  18500. function updateSet(set, newMap) {
  18501. if (set.__ownerID) {
  18502. set.size = newMap.size;
  18503. set._map = newMap;
  18504. return set;
  18505. }
  18506. return newMap === set._map
  18507. ? set
  18508. : newMap.size === 0
  18509. ? set.__empty()
  18510. : set.__make(newMap);
  18511. }
  18512. function makeSet(map, ownerID) {
  18513. var set = Object.create(SetPrototype);
  18514. set.size = map ? map.size : 0;
  18515. set._map = map;
  18516. set.__ownerID = ownerID;
  18517. return set;
  18518. }
  18519. var EMPTY_SET;
  18520. function emptySet() {
  18521. return EMPTY_SET || (EMPTY_SET = makeSet(emptyMap()));
  18522. }
  18523. /**
  18524. * Returns a lazy seq of nums from start (inclusive) to end
  18525. * (exclusive), by step, where start defaults to 0, step to 1, and end to
  18526. * infinity. When start is equal to end, returns empty list.
  18527. */
  18528. var Range = /*@__PURE__*/(function (IndexedSeq$$1) {
  18529. function Range(start, end, step) {
  18530. if (!(this instanceof Range)) {
  18531. return new Range(start, end, step);
  18532. }
  18533. invariant(step !== 0, 'Cannot step a Range by 0');
  18534. start = start || 0;
  18535. if (end === undefined) {
  18536. end = Infinity;
  18537. }
  18538. step = step === undefined ? 1 : Math.abs(step);
  18539. if (end < start) {
  18540. step = -step;
  18541. }
  18542. this._start = start;
  18543. this._end = end;
  18544. this._step = step;
  18545. this.size = Math.max(0, Math.ceil((end - start) / step - 1) + 1);
  18546. if (this.size === 0) {
  18547. if (EMPTY_RANGE) {
  18548. return EMPTY_RANGE;
  18549. }
  18550. EMPTY_RANGE = this;
  18551. }
  18552. }
  18553. if ( IndexedSeq$$1 ) Range.__proto__ = IndexedSeq$$1;
  18554. Range.prototype = Object.create( IndexedSeq$$1 && IndexedSeq$$1.prototype );
  18555. Range.prototype.constructor = Range;
  18556. Range.prototype.toString = function toString () {
  18557. if (this.size === 0) {
  18558. return 'Range []';
  18559. }
  18560. return (
  18561. 'Range [ ' +
  18562. this._start +
  18563. '...' +
  18564. this._end +
  18565. (this._step !== 1 ? ' by ' + this._step : '') +
  18566. ' ]'
  18567. );
  18568. };
  18569. Range.prototype.get = function get (index, notSetValue) {
  18570. return this.has(index)
  18571. ? this._start + wrapIndex(this, index) * this._step
  18572. : notSetValue;
  18573. };
  18574. Range.prototype.includes = function includes (searchValue) {
  18575. var possibleIndex = (searchValue - this._start) / this._step;
  18576. return (
  18577. possibleIndex >= 0 &&
  18578. possibleIndex < this.size &&
  18579. possibleIndex === Math.floor(possibleIndex)
  18580. );
  18581. };
  18582. Range.prototype.slice = function slice (begin, end) {
  18583. if (wholeSlice(begin, end, this.size)) {
  18584. return this;
  18585. }
  18586. begin = resolveBegin(begin, this.size);
  18587. end = resolveEnd(end, this.size);
  18588. if (end <= begin) {
  18589. return new Range(0, 0);
  18590. }
  18591. return new Range(
  18592. this.get(begin, this._end),
  18593. this.get(end, this._end),
  18594. this._step
  18595. );
  18596. };
  18597. Range.prototype.indexOf = function indexOf (searchValue) {
  18598. var offsetValue = searchValue - this._start;
  18599. if (offsetValue % this._step === 0) {
  18600. var index = offsetValue / this._step;
  18601. if (index >= 0 && index < this.size) {
  18602. return index;
  18603. }
  18604. }
  18605. return -1;
  18606. };
  18607. Range.prototype.lastIndexOf = function lastIndexOf (searchValue) {
  18608. return this.indexOf(searchValue);
  18609. };
  18610. Range.prototype.__iterate = function __iterate (fn, reverse) {
  18611. var size = this.size;
  18612. var step = this._step;
  18613. var value = reverse ? this._start + (size - 1) * step : this._start;
  18614. var i = 0;
  18615. while (i !== size) {
  18616. if (fn(value, reverse ? size - ++i : i++, this) === false) {
  18617. break;
  18618. }
  18619. value += reverse ? -step : step;
  18620. }
  18621. return i;
  18622. };
  18623. Range.prototype.__iterator = function __iterator (type, reverse) {
  18624. var size = this.size;
  18625. var step = this._step;
  18626. var value = reverse ? this._start + (size - 1) * step : this._start;
  18627. var i = 0;
  18628. return new Iterator(function () {
  18629. if (i === size) {
  18630. return iteratorDone();
  18631. }
  18632. var v = value;
  18633. value += reverse ? -step : step;
  18634. return iteratorValue(type, reverse ? size - ++i : i++, v);
  18635. });
  18636. };
  18637. Range.prototype.equals = function equals (other) {
  18638. return other instanceof Range
  18639. ? this._start === other._start &&
  18640. this._end === other._end &&
  18641. this._step === other._step
  18642. : deepEqual(this, other);
  18643. };
  18644. return Range;
  18645. }(IndexedSeq));
  18646. var EMPTY_RANGE;
  18647. function getIn(collection, searchKeyPath, notSetValue) {
  18648. var keyPath = coerceKeyPath(searchKeyPath);
  18649. var i = 0;
  18650. while (i !== keyPath.length) {
  18651. collection = get(collection, keyPath[i++], NOT_SET);
  18652. if (collection === NOT_SET) {
  18653. return notSetValue;
  18654. }
  18655. }
  18656. return collection;
  18657. }
  18658. function getIn$1(searchKeyPath, notSetValue) {
  18659. return getIn(this, searchKeyPath, notSetValue);
  18660. }
  18661. function hasIn(collection, keyPath) {
  18662. return getIn(collection, keyPath, NOT_SET) !== NOT_SET;
  18663. }
  18664. function hasIn$1(searchKeyPath) {
  18665. return hasIn(this, searchKeyPath);
  18666. }
  18667. function toObject() {
  18668. assertNotInfinite(this.size);
  18669. var object = {};
  18670. this.__iterate(function (v, k) {
  18671. object[k] = v;
  18672. });
  18673. return object;
  18674. }
  18675. // Note: all of these methods are deprecated.
  18676. Collection.isIterable = isCollection;
  18677. Collection.isKeyed = isKeyed;
  18678. Collection.isIndexed = isIndexed;
  18679. Collection.isAssociative = isAssociative;
  18680. Collection.isOrdered = isOrdered;
  18681. Collection.Iterator = Iterator;
  18682. mixin(Collection, {
  18683. // ### Conversion to other types
  18684. toArray: function toArray() {
  18685. assertNotInfinite(this.size);
  18686. var array = new Array(this.size || 0);
  18687. var useTuples = isKeyed(this);
  18688. var i = 0;
  18689. this.__iterate(function (v, k) {
  18690. // Keyed collections produce an array of tuples.
  18691. array[i++] = useTuples ? [k, v] : v;
  18692. });
  18693. return array;
  18694. },
  18695. toIndexedSeq: function toIndexedSeq() {
  18696. return new ToIndexedSequence(this);
  18697. },
  18698. toJS: function toJS$1() {
  18699. return toJS(this);
  18700. },
  18701. toKeyedSeq: function toKeyedSeq() {
  18702. return new ToKeyedSequence(this, true);
  18703. },
  18704. toMap: function toMap() {
  18705. // Use Late Binding here to solve the circular dependency.
  18706. return Map(this.toKeyedSeq());
  18707. },
  18708. toObject: toObject,
  18709. toOrderedMap: function toOrderedMap() {
  18710. // Use Late Binding here to solve the circular dependency.
  18711. return OrderedMap(this.toKeyedSeq());
  18712. },
  18713. toOrderedSet: function toOrderedSet() {
  18714. // Use Late Binding here to solve the circular dependency.
  18715. return OrderedSet(isKeyed(this) ? this.valueSeq() : this);
  18716. },
  18717. toSet: function toSet() {
  18718. // Use Late Binding here to solve the circular dependency.
  18719. return Set(isKeyed(this) ? this.valueSeq() : this);
  18720. },
  18721. toSetSeq: function toSetSeq() {
  18722. return new ToSetSequence(this);
  18723. },
  18724. toSeq: function toSeq() {
  18725. return isIndexed(this)
  18726. ? this.toIndexedSeq()
  18727. : isKeyed(this)
  18728. ? this.toKeyedSeq()
  18729. : this.toSetSeq();
  18730. },
  18731. toStack: function toStack() {
  18732. // Use Late Binding here to solve the circular dependency.
  18733. return Stack(isKeyed(this) ? this.valueSeq() : this);
  18734. },
  18735. toList: function toList() {
  18736. // Use Late Binding here to solve the circular dependency.
  18737. return List(isKeyed(this) ? this.valueSeq() : this);
  18738. },
  18739. // ### Common JavaScript methods and properties
  18740. toString: function toString() {
  18741. return '[Collection]';
  18742. },
  18743. __toString: function __toString(head, tail) {
  18744. if (this.size === 0) {
  18745. return head + tail;
  18746. }
  18747. return (
  18748. head +
  18749. ' ' +
  18750. this.toSeq()
  18751. .map(this.__toStringMapper)
  18752. .join(', ') +
  18753. ' ' +
  18754. tail
  18755. );
  18756. },
  18757. // ### ES6 Collection methods (ES6 Array and Map)
  18758. concat: function concat() {
  18759. var values = [], len = arguments.length;
  18760. while ( len-- ) values[ len ] = arguments[ len ];
  18761. return reify(this, concatFactory(this, values));
  18762. },
  18763. includes: function includes(searchValue) {
  18764. return this.some(function (value) { return is(value, searchValue); });
  18765. },
  18766. entries: function entries() {
  18767. return this.__iterator(ITERATE_ENTRIES);
  18768. },
  18769. every: function every(predicate, context) {
  18770. assertNotInfinite(this.size);
  18771. var returnValue = true;
  18772. this.__iterate(function (v, k, c) {
  18773. if (!predicate.call(context, v, k, c)) {
  18774. returnValue = false;
  18775. return false;
  18776. }
  18777. });
  18778. return returnValue;
  18779. },
  18780. filter: function filter(predicate, context) {
  18781. return reify(this, filterFactory(this, predicate, context, true));
  18782. },
  18783. find: function find(predicate, context, notSetValue) {
  18784. var entry = this.findEntry(predicate, context);
  18785. return entry ? entry[1] : notSetValue;
  18786. },
  18787. forEach: function forEach(sideEffect, context) {
  18788. assertNotInfinite(this.size);
  18789. return this.__iterate(context ? sideEffect.bind(context) : sideEffect);
  18790. },
  18791. join: function join(separator) {
  18792. assertNotInfinite(this.size);
  18793. separator = separator !== undefined ? '' + separator : ',';
  18794. var joined = '';
  18795. var isFirst = true;
  18796. this.__iterate(function (v) {
  18797. isFirst ? (isFirst = false) : (joined += separator);
  18798. joined += v !== null && v !== undefined ? v.toString() : '';
  18799. });
  18800. return joined;
  18801. },
  18802. keys: function keys() {
  18803. return this.__iterator(ITERATE_KEYS);
  18804. },
  18805. map: function map(mapper, context) {
  18806. return reify(this, mapFactory(this, mapper, context));
  18807. },
  18808. reduce: function reduce$1(reducer, initialReduction, context) {
  18809. return reduce(
  18810. this,
  18811. reducer,
  18812. initialReduction,
  18813. context,
  18814. arguments.length < 2,
  18815. false
  18816. );
  18817. },
  18818. reduceRight: function reduceRight(reducer, initialReduction, context) {
  18819. return reduce(
  18820. this,
  18821. reducer,
  18822. initialReduction,
  18823. context,
  18824. arguments.length < 2,
  18825. true
  18826. );
  18827. },
  18828. reverse: function reverse() {
  18829. return reify(this, reverseFactory(this, true));
  18830. },
  18831. slice: function slice(begin, end) {
  18832. return reify(this, sliceFactory(this, begin, end, true));
  18833. },
  18834. some: function some(predicate, context) {
  18835. return !this.every(not(predicate), context);
  18836. },
  18837. sort: function sort(comparator) {
  18838. return reify(this, sortFactory(this, comparator));
  18839. },
  18840. values: function values() {
  18841. return this.__iterator(ITERATE_VALUES);
  18842. },
  18843. // ### More sequential methods
  18844. butLast: function butLast() {
  18845. return this.slice(0, -1);
  18846. },
  18847. isEmpty: function isEmpty() {
  18848. return this.size !== undefined ? this.size === 0 : !this.some(function () { return true; });
  18849. },
  18850. count: function count(predicate, context) {
  18851. return ensureSize(
  18852. predicate ? this.toSeq().filter(predicate, context) : this
  18853. );
  18854. },
  18855. countBy: function countBy(grouper, context) {
  18856. return countByFactory(this, grouper, context);
  18857. },
  18858. equals: function equals(other) {
  18859. return deepEqual(this, other);
  18860. },
  18861. entrySeq: function entrySeq() {
  18862. var collection = this;
  18863. if (collection._cache) {
  18864. // We cache as an entries array, so we can just return the cache!
  18865. return new ArraySeq(collection._cache);
  18866. }
  18867. var entriesSequence = collection
  18868. .toSeq()
  18869. .map(entryMapper)
  18870. .toIndexedSeq();
  18871. entriesSequence.fromEntrySeq = function () { return collection.toSeq(); };
  18872. return entriesSequence;
  18873. },
  18874. filterNot: function filterNot(predicate, context) {
  18875. return this.filter(not(predicate), context);
  18876. },
  18877. findEntry: function findEntry(predicate, context, notSetValue) {
  18878. var found = notSetValue;
  18879. this.__iterate(function (v, k, c) {
  18880. if (predicate.call(context, v, k, c)) {
  18881. found = [k, v];
  18882. return false;
  18883. }
  18884. });
  18885. return found;
  18886. },
  18887. findKey: function findKey(predicate, context) {
  18888. var entry = this.findEntry(predicate, context);
  18889. return entry && entry[0];
  18890. },
  18891. findLast: function findLast(predicate, context, notSetValue) {
  18892. return this.toKeyedSeq()
  18893. .reverse()
  18894. .find(predicate, context, notSetValue);
  18895. },
  18896. findLastEntry: function findLastEntry(predicate, context, notSetValue) {
  18897. return this.toKeyedSeq()
  18898. .reverse()
  18899. .findEntry(predicate, context, notSetValue);
  18900. },
  18901. findLastKey: function findLastKey(predicate, context) {
  18902. return this.toKeyedSeq()
  18903. .reverse()
  18904. .findKey(predicate, context);
  18905. },
  18906. first: function first(notSetValue) {
  18907. return this.find(returnTrue, null, notSetValue);
  18908. },
  18909. flatMap: function flatMap(mapper, context) {
  18910. return reify(this, flatMapFactory(this, mapper, context));
  18911. },
  18912. flatten: function flatten(depth) {
  18913. return reify(this, flattenFactory(this, depth, true));
  18914. },
  18915. fromEntrySeq: function fromEntrySeq() {
  18916. return new FromEntriesSequence(this);
  18917. },
  18918. get: function get(searchKey, notSetValue) {
  18919. return this.find(function (_, key) { return is(key, searchKey); }, undefined, notSetValue);
  18920. },
  18921. getIn: getIn$1,
  18922. groupBy: function groupBy(grouper, context) {
  18923. return groupByFactory(this, grouper, context);
  18924. },
  18925. has: function has(searchKey) {
  18926. return this.get(searchKey, NOT_SET) !== NOT_SET;
  18927. },
  18928. hasIn: hasIn$1,
  18929. isSubset: function isSubset(iter) {
  18930. iter = typeof iter.includes === 'function' ? iter : Collection(iter);
  18931. return this.every(function (value) { return iter.includes(value); });
  18932. },
  18933. isSuperset: function isSuperset(iter) {
  18934. iter = typeof iter.isSubset === 'function' ? iter : Collection(iter);
  18935. return iter.isSubset(this);
  18936. },
  18937. keyOf: function keyOf(searchValue) {
  18938. return this.findKey(function (value) { return is(value, searchValue); });
  18939. },
  18940. keySeq: function keySeq() {
  18941. return this.toSeq()
  18942. .map(keyMapper)
  18943. .toIndexedSeq();
  18944. },
  18945. last: function last(notSetValue) {
  18946. return this.toSeq()
  18947. .reverse()
  18948. .first(notSetValue);
  18949. },
  18950. lastKeyOf: function lastKeyOf(searchValue) {
  18951. return this.toKeyedSeq()
  18952. .reverse()
  18953. .keyOf(searchValue);
  18954. },
  18955. max: function max(comparator) {
  18956. return maxFactory(this, comparator);
  18957. },
  18958. maxBy: function maxBy(mapper, comparator) {
  18959. return maxFactory(this, comparator, mapper);
  18960. },
  18961. min: function min(comparator) {
  18962. return maxFactory(
  18963. this,
  18964. comparator ? neg(comparator) : defaultNegComparator
  18965. );
  18966. },
  18967. minBy: function minBy(mapper, comparator) {
  18968. return maxFactory(
  18969. this,
  18970. comparator ? neg(comparator) : defaultNegComparator,
  18971. mapper
  18972. );
  18973. },
  18974. rest: function rest() {
  18975. return this.slice(1);
  18976. },
  18977. skip: function skip(amount) {
  18978. return amount === 0 ? this : this.slice(Math.max(0, amount));
  18979. },
  18980. skipLast: function skipLast(amount) {
  18981. return amount === 0 ? this : this.slice(0, -Math.max(0, amount));
  18982. },
  18983. skipWhile: function skipWhile(predicate, context) {
  18984. return reify(this, skipWhileFactory(this, predicate, context, true));
  18985. },
  18986. skipUntil: function skipUntil(predicate, context) {
  18987. return this.skipWhile(not(predicate), context);
  18988. },
  18989. sortBy: function sortBy(mapper, comparator) {
  18990. return reify(this, sortFactory(this, comparator, mapper));
  18991. },
  18992. take: function take(amount) {
  18993. return this.slice(0, Math.max(0, amount));
  18994. },
  18995. takeLast: function takeLast(amount) {
  18996. return this.slice(-Math.max(0, amount));
  18997. },
  18998. takeWhile: function takeWhile(predicate, context) {
  18999. return reify(this, takeWhileFactory(this, predicate, context));
  19000. },
  19001. takeUntil: function takeUntil(predicate, context) {
  19002. return this.takeWhile(not(predicate), context);
  19003. },
  19004. update: function update(fn) {
  19005. return fn(this);
  19006. },
  19007. valueSeq: function valueSeq() {
  19008. return this.toIndexedSeq();
  19009. },
  19010. // ### Hashable Object
  19011. hashCode: function hashCode() {
  19012. return this.__hash || (this.__hash = hashCollection(this));
  19013. },
  19014. // ### Internal
  19015. // abstract __iterate(fn, reverse)
  19016. // abstract __iterator(type, reverse)
  19017. });
  19018. var CollectionPrototype = Collection.prototype;
  19019. CollectionPrototype[IS_COLLECTION_SYMBOL] = true;
  19020. CollectionPrototype[ITERATOR_SYMBOL] = CollectionPrototype.values;
  19021. CollectionPrototype.toJSON = CollectionPrototype.toArray;
  19022. CollectionPrototype.__toStringMapper = quoteString;
  19023. CollectionPrototype.inspect = CollectionPrototype.toSource = function() {
  19024. return this.toString();
  19025. };
  19026. CollectionPrototype.chain = CollectionPrototype.flatMap;
  19027. CollectionPrototype.contains = CollectionPrototype.includes;
  19028. mixin(KeyedCollection, {
  19029. // ### More sequential methods
  19030. flip: function flip() {
  19031. return reify(this, flipFactory(this));
  19032. },
  19033. mapEntries: function mapEntries(mapper, context) {
  19034. var this$1 = this;
  19035. var iterations = 0;
  19036. return reify(
  19037. this,
  19038. this.toSeq()
  19039. .map(function (v, k) { return mapper.call(context, [k, v], iterations++, this$1); })
  19040. .fromEntrySeq()
  19041. );
  19042. },
  19043. mapKeys: function mapKeys(mapper, context) {
  19044. var this$1 = this;
  19045. return reify(
  19046. this,
  19047. this.toSeq()
  19048. .flip()
  19049. .map(function (k, v) { return mapper.call(context, k, v, this$1); })
  19050. .flip()
  19051. );
  19052. },
  19053. });
  19054. var KeyedCollectionPrototype = KeyedCollection.prototype;
  19055. KeyedCollectionPrototype[IS_KEYED_SYMBOL] = true;
  19056. KeyedCollectionPrototype[ITERATOR_SYMBOL] = CollectionPrototype.entries;
  19057. KeyedCollectionPrototype.toJSON = toObject;
  19058. KeyedCollectionPrototype.__toStringMapper = function (v, k) { return quoteString(k) + ': ' + quoteString(v); };
  19059. mixin(IndexedCollection, {
  19060. // ### Conversion to other types
  19061. toKeyedSeq: function toKeyedSeq() {
  19062. return new ToKeyedSequence(this, false);
  19063. },
  19064. // ### ES6 Collection methods (ES6 Array and Map)
  19065. filter: function filter(predicate, context) {
  19066. return reify(this, filterFactory(this, predicate, context, false));
  19067. },
  19068. findIndex: function findIndex(predicate, context) {
  19069. var entry = this.findEntry(predicate, context);
  19070. return entry ? entry[0] : -1;
  19071. },
  19072. indexOf: function indexOf(searchValue) {
  19073. var key = this.keyOf(searchValue);
  19074. return key === undefined ? -1 : key;
  19075. },
  19076. lastIndexOf: function lastIndexOf(searchValue) {
  19077. var key = this.lastKeyOf(searchValue);
  19078. return key === undefined ? -1 : key;
  19079. },
  19080. reverse: function reverse() {
  19081. return reify(this, reverseFactory(this, false));
  19082. },
  19083. slice: function slice(begin, end) {
  19084. return reify(this, sliceFactory(this, begin, end, false));
  19085. },
  19086. splice: function splice(index, removeNum /*, ...values*/) {
  19087. var numArgs = arguments.length;
  19088. removeNum = Math.max(removeNum || 0, 0);
  19089. if (numArgs === 0 || (numArgs === 2 && !removeNum)) {
  19090. return this;
  19091. }
  19092. // If index is negative, it should resolve relative to the size of the
  19093. // collection. However size may be expensive to compute if not cached, so
  19094. // only call count() if the number is in fact negative.
  19095. index = resolveBegin(index, index < 0 ? this.count() : this.size);
  19096. var spliced = this.slice(0, index);
  19097. return reify(
  19098. this,
  19099. numArgs === 1
  19100. ? spliced
  19101. : spliced.concat(arrCopy(arguments, 2), this.slice(index + removeNum))
  19102. );
  19103. },
  19104. // ### More collection methods
  19105. findLastIndex: function findLastIndex(predicate, context) {
  19106. var entry = this.findLastEntry(predicate, context);
  19107. return entry ? entry[0] : -1;
  19108. },
  19109. first: function first(notSetValue) {
  19110. return this.get(0, notSetValue);
  19111. },
  19112. flatten: function flatten(depth) {
  19113. return reify(this, flattenFactory(this, depth, false));
  19114. },
  19115. get: function get(index, notSetValue) {
  19116. index = wrapIndex(this, index);
  19117. return index < 0 ||
  19118. (this.size === Infinity || (this.size !== undefined && index > this.size))
  19119. ? notSetValue
  19120. : this.find(function (_, key) { return key === index; }, undefined, notSetValue);
  19121. },
  19122. has: function has(index) {
  19123. index = wrapIndex(this, index);
  19124. return (
  19125. index >= 0 &&
  19126. (this.size !== undefined
  19127. ? this.size === Infinity || index < this.size
  19128. : this.indexOf(index) !== -1)
  19129. );
  19130. },
  19131. interpose: function interpose(separator) {
  19132. return reify(this, interposeFactory(this, separator));
  19133. },
  19134. interleave: function interleave(/*...collections*/) {
  19135. var collections = [this].concat(arrCopy(arguments));
  19136. var zipped = zipWithFactory(this.toSeq(), IndexedSeq.of, collections);
  19137. var interleaved = zipped.flatten(true);
  19138. if (zipped.size) {
  19139. interleaved.size = zipped.size * collections.length;
  19140. }
  19141. return reify(this, interleaved);
  19142. },
  19143. keySeq: function keySeq() {
  19144. return Range(0, this.size);
  19145. },
  19146. last: function last(notSetValue) {
  19147. return this.get(-1, notSetValue);
  19148. },
  19149. skipWhile: function skipWhile(predicate, context) {
  19150. return reify(this, skipWhileFactory(this, predicate, context, false));
  19151. },
  19152. zip: function zip(/*, ...collections */) {
  19153. var collections = [this].concat(arrCopy(arguments));
  19154. return reify(this, zipWithFactory(this, defaultZipper, collections));
  19155. },
  19156. zipAll: function zipAll(/*, ...collections */) {
  19157. var collections = [this].concat(arrCopy(arguments));
  19158. return reify(this, zipWithFactory(this, defaultZipper, collections, true));
  19159. },
  19160. zipWith: function zipWith(zipper /*, ...collections */) {
  19161. var collections = arrCopy(arguments);
  19162. collections[0] = this;
  19163. return reify(this, zipWithFactory(this, zipper, collections));
  19164. },
  19165. });
  19166. var IndexedCollectionPrototype = IndexedCollection.prototype;
  19167. IndexedCollectionPrototype[IS_INDEXED_SYMBOL] = true;
  19168. IndexedCollectionPrototype[IS_ORDERED_SYMBOL] = true;
  19169. mixin(SetCollection, {
  19170. // ### ES6 Collection methods (ES6 Array and Map)
  19171. get: function get(value, notSetValue) {
  19172. return this.has(value) ? value : notSetValue;
  19173. },
  19174. includes: function includes(value) {
  19175. return this.has(value);
  19176. },
  19177. // ### More sequential methods
  19178. keySeq: function keySeq() {
  19179. return this.valueSeq();
  19180. },
  19181. });
  19182. SetCollection.prototype.has = CollectionPrototype.includes;
  19183. SetCollection.prototype.contains = SetCollection.prototype.includes;
  19184. // Mixin subclasses
  19185. mixin(KeyedSeq, KeyedCollection.prototype);
  19186. mixin(IndexedSeq, IndexedCollection.prototype);
  19187. mixin(SetSeq, SetCollection.prototype);
  19188. // #pragma Helper functions
  19189. function reduce(collection, reducer, reduction, context, useFirst, reverse) {
  19190. assertNotInfinite(collection.size);
  19191. collection.__iterate(function (v, k, c) {
  19192. if (useFirst) {
  19193. useFirst = false;
  19194. reduction = v;
  19195. } else {
  19196. reduction = reducer.call(context, reduction, v, k, c);
  19197. }
  19198. }, reverse);
  19199. return reduction;
  19200. }
  19201. function keyMapper(v, k) {
  19202. return k;
  19203. }
  19204. function entryMapper(v, k) {
  19205. return [k, v];
  19206. }
  19207. function not(predicate) {
  19208. return function() {
  19209. return !predicate.apply(this, arguments);
  19210. };
  19211. }
  19212. function neg(predicate) {
  19213. return function() {
  19214. return -predicate.apply(this, arguments);
  19215. };
  19216. }
  19217. function defaultZipper() {
  19218. return arrCopy(arguments);
  19219. }
  19220. function defaultNegComparator(a, b) {
  19221. return a < b ? 1 : a > b ? -1 : 0;
  19222. }
  19223. function hashCollection(collection) {
  19224. if (collection.size === Infinity) {
  19225. return 0;
  19226. }
  19227. var ordered = isOrdered(collection);
  19228. var keyed = isKeyed(collection);
  19229. var h = ordered ? 1 : 0;
  19230. var size = collection.__iterate(
  19231. keyed
  19232. ? ordered
  19233. ? function (v, k) {
  19234. h = (31 * h + hashMerge(hash(v), hash(k))) | 0;
  19235. }
  19236. : function (v, k) {
  19237. h = (h + hashMerge(hash(v), hash(k))) | 0;
  19238. }
  19239. : ordered
  19240. ? function (v) {
  19241. h = (31 * h + hash(v)) | 0;
  19242. }
  19243. : function (v) {
  19244. h = (h + hash(v)) | 0;
  19245. }
  19246. );
  19247. return murmurHashOfSize(size, h);
  19248. }
  19249. function murmurHashOfSize(size, h) {
  19250. h = imul(h, 0xcc9e2d51);
  19251. h = imul((h << 15) | (h >>> -15), 0x1b873593);
  19252. h = imul((h << 13) | (h >>> -13), 5);
  19253. h = ((h + 0xe6546b64) | 0) ^ size;
  19254. h = imul(h ^ (h >>> 16), 0x85ebca6b);
  19255. h = imul(h ^ (h >>> 13), 0xc2b2ae35);
  19256. h = smi(h ^ (h >>> 16));
  19257. return h;
  19258. }
  19259. function hashMerge(a, b) {
  19260. return (a ^ (b + 0x9e3779b9 + (a << 6) + (a >> 2))) | 0; // int
  19261. }
  19262. var OrderedSet = /*@__PURE__*/(function (Set$$1) {
  19263. function OrderedSet(value) {
  19264. return value === null || value === undefined
  19265. ? emptyOrderedSet()
  19266. : isOrderedSet(value)
  19267. ? value
  19268. : emptyOrderedSet().withMutations(function (set) {
  19269. var iter = SetCollection(value);
  19270. assertNotInfinite(iter.size);
  19271. iter.forEach(function (v) { return set.add(v); });
  19272. });
  19273. }
  19274. if ( Set$$1 ) OrderedSet.__proto__ = Set$$1;
  19275. OrderedSet.prototype = Object.create( Set$$1 && Set$$1.prototype );
  19276. OrderedSet.prototype.constructor = OrderedSet;
  19277. OrderedSet.of = function of (/*...values*/) {
  19278. return this(arguments);
  19279. };
  19280. OrderedSet.fromKeys = function fromKeys (value) {
  19281. return this(KeyedCollection(value).keySeq());
  19282. };
  19283. OrderedSet.prototype.toString = function toString () {
  19284. return this.__toString('OrderedSet {', '}');
  19285. };
  19286. return OrderedSet;
  19287. }(Set));
  19288. OrderedSet.isOrderedSet = isOrderedSet;
  19289. var OrderedSetPrototype = OrderedSet.prototype;
  19290. OrderedSetPrototype[IS_ORDERED_SYMBOL] = true;
  19291. OrderedSetPrototype.zip = IndexedCollectionPrototype.zip;
  19292. OrderedSetPrototype.zipWith = IndexedCollectionPrototype.zipWith;
  19293. OrderedSetPrototype.__empty = emptyOrderedSet;
  19294. OrderedSetPrototype.__make = makeOrderedSet;
  19295. function makeOrderedSet(map, ownerID) {
  19296. var set = Object.create(OrderedSetPrototype);
  19297. set.size = map ? map.size : 0;
  19298. set._map = map;
  19299. set.__ownerID = ownerID;
  19300. return set;
  19301. }
  19302. var EMPTY_ORDERED_SET;
  19303. function emptyOrderedSet() {
  19304. return (
  19305. EMPTY_ORDERED_SET || (EMPTY_ORDERED_SET = makeOrderedSet(emptyOrderedMap()))
  19306. );
  19307. }
  19308. var Record = function Record(defaultValues, name) {
  19309. var hasInitialized;
  19310. var RecordType = function Record(values) {
  19311. var this$1 = this;
  19312. if (values instanceof RecordType) {
  19313. return values;
  19314. }
  19315. if (!(this instanceof RecordType)) {
  19316. return new RecordType(values);
  19317. }
  19318. if (!hasInitialized) {
  19319. hasInitialized = true;
  19320. var keys = Object.keys(defaultValues);
  19321. var indices = (RecordTypePrototype._indices = {});
  19322. // Deprecated: left to attempt not to break any external code which
  19323. // relies on a ._name property existing on record instances.
  19324. // Use Record.getDescriptiveName() instead
  19325. RecordTypePrototype._name = name;
  19326. RecordTypePrototype._keys = keys;
  19327. RecordTypePrototype._defaultValues = defaultValues;
  19328. for (var i = 0; i < keys.length; i++) {
  19329. var propName = keys[i];
  19330. indices[propName] = i;
  19331. if (RecordTypePrototype[propName]) {
  19332. /* eslint-disable no-console */
  19333. typeof console === 'object' &&
  19334. console.warn &&
  19335. console.warn(
  19336. 'Cannot define ' +
  19337. recordName(this) +
  19338. ' with property "' +
  19339. propName +
  19340. '" since that property name is part of the Record API.'
  19341. );
  19342. /* eslint-enable no-console */
  19343. } else {
  19344. setProp(RecordTypePrototype, propName);
  19345. }
  19346. }
  19347. }
  19348. this.__ownerID = undefined;
  19349. this._values = List().withMutations(function (l) {
  19350. l.setSize(this$1._keys.length);
  19351. KeyedCollection(values).forEach(function (v, k) {
  19352. l.set(this$1._indices[k], v === this$1._defaultValues[k] ? undefined : v);
  19353. });
  19354. });
  19355. };
  19356. var RecordTypePrototype = (RecordType.prototype = Object.create(
  19357. RecordPrototype
  19358. ));
  19359. RecordTypePrototype.constructor = RecordType;
  19360. if (name) {
  19361. RecordType.displayName = name;
  19362. }
  19363. return RecordType;
  19364. };
  19365. Record.prototype.toString = function toString () {
  19366. var str = recordName(this) + ' { ';
  19367. var keys = this._keys;
  19368. var k;
  19369. for (var i = 0, l = keys.length; i !== l; i++) {
  19370. k = keys[i];
  19371. str += (i ? ', ' : '') + k + ': ' + quoteString(this.get(k));
  19372. }
  19373. return str + ' }';
  19374. };
  19375. Record.prototype.equals = function equals (other) {
  19376. return (
  19377. this === other ||
  19378. (other &&
  19379. this._keys === other._keys &&
  19380. recordSeq(this).equals(recordSeq(other)))
  19381. );
  19382. };
  19383. Record.prototype.hashCode = function hashCode () {
  19384. return recordSeq(this).hashCode();
  19385. };
  19386. // @pragma Access
  19387. Record.prototype.has = function has (k) {
  19388. return this._indices.hasOwnProperty(k);
  19389. };
  19390. Record.prototype.get = function get (k, notSetValue) {
  19391. if (!this.has(k)) {
  19392. return notSetValue;
  19393. }
  19394. var index = this._indices[k];
  19395. var value = this._values.get(index);
  19396. return value === undefined ? this._defaultValues[k] : value;
  19397. };
  19398. // @pragma Modification
  19399. Record.prototype.set = function set (k, v) {
  19400. if (this.has(k)) {
  19401. var newValues = this._values.set(
  19402. this._indices[k],
  19403. v === this._defaultValues[k] ? undefined : v
  19404. );
  19405. if (newValues !== this._values && !this.__ownerID) {
  19406. return makeRecord(this, newValues);
  19407. }
  19408. }
  19409. return this;
  19410. };
  19411. Record.prototype.remove = function remove (k) {
  19412. return this.set(k);
  19413. };
  19414. Record.prototype.clear = function clear () {
  19415. var newValues = this._values.clear().setSize(this._keys.length);
  19416. return this.__ownerID ? this : makeRecord(this, newValues);
  19417. };
  19418. Record.prototype.wasAltered = function wasAltered () {
  19419. return this._values.wasAltered();
  19420. };
  19421. Record.prototype.toSeq = function toSeq () {
  19422. return recordSeq(this);
  19423. };
  19424. Record.prototype.toJS = function toJS$1 () {
  19425. return toJS(this);
  19426. };
  19427. Record.prototype.entries = function entries () {
  19428. return this.__iterator(ITERATE_ENTRIES);
  19429. };
  19430. Record.prototype.__iterator = function __iterator (type, reverse) {
  19431. return recordSeq(this).__iterator(type, reverse);
  19432. };
  19433. Record.prototype.__iterate = function __iterate (fn, reverse) {
  19434. return recordSeq(this).__iterate(fn, reverse);
  19435. };
  19436. Record.prototype.__ensureOwner = function __ensureOwner (ownerID) {
  19437. if (ownerID === this.__ownerID) {
  19438. return this;
  19439. }
  19440. var newValues = this._values.__ensureOwner(ownerID);
  19441. if (!ownerID) {
  19442. this.__ownerID = ownerID;
  19443. this._values = newValues;
  19444. return this;
  19445. }
  19446. return makeRecord(this, newValues, ownerID);
  19447. };
  19448. Record.isRecord = isRecord;
  19449. Record.getDescriptiveName = recordName;
  19450. var RecordPrototype = Record.prototype;
  19451. RecordPrototype[IS_RECORD_SYMBOL] = true;
  19452. RecordPrototype[DELETE] = RecordPrototype.remove;
  19453. RecordPrototype.deleteIn = RecordPrototype.removeIn = deleteIn;
  19454. RecordPrototype.getIn = getIn$1;
  19455. RecordPrototype.hasIn = CollectionPrototype.hasIn;
  19456. RecordPrototype.merge = merge;
  19457. RecordPrototype.mergeWith = mergeWith;
  19458. RecordPrototype.mergeIn = mergeIn;
  19459. RecordPrototype.mergeDeep = mergeDeep$1;
  19460. RecordPrototype.mergeDeepWith = mergeDeepWith$1;
  19461. RecordPrototype.mergeDeepIn = mergeDeepIn;
  19462. RecordPrototype.setIn = setIn$1;
  19463. RecordPrototype.update = update$1;
  19464. RecordPrototype.updateIn = updateIn$1;
  19465. RecordPrototype.withMutations = withMutations;
  19466. RecordPrototype.asMutable = asMutable;
  19467. RecordPrototype.asImmutable = asImmutable;
  19468. RecordPrototype[ITERATOR_SYMBOL] = RecordPrototype.entries;
  19469. RecordPrototype.toJSON = RecordPrototype.toObject =
  19470. CollectionPrototype.toObject;
  19471. RecordPrototype.inspect = RecordPrototype.toSource = function() {
  19472. return this.toString();
  19473. };
  19474. function makeRecord(likeRecord, values, ownerID) {
  19475. var record = Object.create(Object.getPrototypeOf(likeRecord));
  19476. record._values = values;
  19477. record.__ownerID = ownerID;
  19478. return record;
  19479. }
  19480. function recordName(record) {
  19481. return record.constructor.displayName || record.constructor.name || 'Record';
  19482. }
  19483. function recordSeq(record) {
  19484. return keyedSeqFromValue(record._keys.map(function (k) { return [k, record.get(k)]; }));
  19485. }
  19486. function setProp(prototype, name) {
  19487. try {
  19488. Object.defineProperty(prototype, name, {
  19489. get: function() {
  19490. return this.get(name);
  19491. },
  19492. set: function(value) {
  19493. invariant(this.__ownerID, 'Cannot set on an immutable record.');
  19494. this.set(name, value);
  19495. },
  19496. });
  19497. } catch (error) {
  19498. // Object.defineProperty failed. Probably IE8.
  19499. }
  19500. }
  19501. /**
  19502. * Returns a lazy Seq of `value` repeated `times` times. When `times` is
  19503. * undefined, returns an infinite sequence of `value`.
  19504. */
  19505. var Repeat = /*@__PURE__*/(function (IndexedSeq$$1) {
  19506. function Repeat(value, times) {
  19507. if (!(this instanceof Repeat)) {
  19508. return new Repeat(value, times);
  19509. }
  19510. this._value = value;
  19511. this.size = times === undefined ? Infinity : Math.max(0, times);
  19512. if (this.size === 0) {
  19513. if (EMPTY_REPEAT) {
  19514. return EMPTY_REPEAT;
  19515. }
  19516. EMPTY_REPEAT = this;
  19517. }
  19518. }
  19519. if ( IndexedSeq$$1 ) Repeat.__proto__ = IndexedSeq$$1;
  19520. Repeat.prototype = Object.create( IndexedSeq$$1 && IndexedSeq$$1.prototype );
  19521. Repeat.prototype.constructor = Repeat;
  19522. Repeat.prototype.toString = function toString () {
  19523. if (this.size === 0) {
  19524. return 'Repeat []';
  19525. }
  19526. return 'Repeat [ ' + this._value + ' ' + this.size + ' times ]';
  19527. };
  19528. Repeat.prototype.get = function get (index, notSetValue) {
  19529. return this.has(index) ? this._value : notSetValue;
  19530. };
  19531. Repeat.prototype.includes = function includes (searchValue) {
  19532. return is(this._value, searchValue);
  19533. };
  19534. Repeat.prototype.slice = function slice (begin, end) {
  19535. var size = this.size;
  19536. return wholeSlice(begin, end, size)
  19537. ? this
  19538. : new Repeat(
  19539. this._value,
  19540. resolveEnd(end, size) - resolveBegin(begin, size)
  19541. );
  19542. };
  19543. Repeat.prototype.reverse = function reverse () {
  19544. return this;
  19545. };
  19546. Repeat.prototype.indexOf = function indexOf (searchValue) {
  19547. if (is(this._value, searchValue)) {
  19548. return 0;
  19549. }
  19550. return -1;
  19551. };
  19552. Repeat.prototype.lastIndexOf = function lastIndexOf (searchValue) {
  19553. if (is(this._value, searchValue)) {
  19554. return this.size;
  19555. }
  19556. return -1;
  19557. };
  19558. Repeat.prototype.__iterate = function __iterate (fn, reverse) {
  19559. var size = this.size;
  19560. var i = 0;
  19561. while (i !== size) {
  19562. if (fn(this._value, reverse ? size - ++i : i++, this) === false) {
  19563. break;
  19564. }
  19565. }
  19566. return i;
  19567. };
  19568. Repeat.prototype.__iterator = function __iterator (type, reverse) {
  19569. var this$1 = this;
  19570. var size = this.size;
  19571. var i = 0;
  19572. return new Iterator(
  19573. function () { return i === size
  19574. ? iteratorDone()
  19575. : iteratorValue(type, reverse ? size - ++i : i++, this$1._value); }
  19576. );
  19577. };
  19578. Repeat.prototype.equals = function equals (other) {
  19579. return other instanceof Repeat
  19580. ? is(this._value, other._value)
  19581. : deepEqual(other);
  19582. };
  19583. return Repeat;
  19584. }(IndexedSeq));
  19585. var EMPTY_REPEAT;
  19586. function fromJS(value, converter) {
  19587. return fromJSWith(
  19588. [],
  19589. converter || defaultConverter,
  19590. value,
  19591. '',
  19592. converter && converter.length > 2 ? [] : undefined,
  19593. { '': value }
  19594. );
  19595. }
  19596. function fromJSWith(stack, converter, value, key, keyPath, parentValue) {
  19597. var toSeq = Array.isArray(value)
  19598. ? IndexedSeq
  19599. : isPlainObj(value)
  19600. ? KeyedSeq
  19601. : null;
  19602. if (toSeq) {
  19603. if (~stack.indexOf(value)) {
  19604. throw new TypeError('Cannot convert circular structure to Immutable');
  19605. }
  19606. stack.push(value);
  19607. keyPath && key !== '' && keyPath.push(key);
  19608. var converted = converter.call(
  19609. parentValue,
  19610. key,
  19611. toSeq(value).map(function (v, k) { return fromJSWith(stack, converter, v, k, keyPath, value); }
  19612. ),
  19613. keyPath && keyPath.slice()
  19614. );
  19615. stack.pop();
  19616. keyPath && keyPath.pop();
  19617. return converted;
  19618. }
  19619. return value;
  19620. }
  19621. function defaultConverter(k, v) {
  19622. return isKeyed(v) ? v.toMap() : v.toList();
  19623. }
  19624. var version = "4.0.0-rc.11";
  19625. var Immutable = {
  19626. version: version,
  19627. Collection: Collection,
  19628. // Note: Iterable is deprecated
  19629. Iterable: Collection,
  19630. Seq: Seq,
  19631. Map: Map,
  19632. OrderedMap: OrderedMap,
  19633. List: List,
  19634. Stack: Stack,
  19635. Set: Set,
  19636. OrderedSet: OrderedSet,
  19637. Record: Record,
  19638. Range: Range,
  19639. Repeat: Repeat,
  19640. is: is,
  19641. fromJS: fromJS,
  19642. hash: hash,
  19643. isImmutable: isImmutable,
  19644. isCollection: isCollection,
  19645. isKeyed: isKeyed,
  19646. isIndexed: isIndexed,
  19647. isAssociative: isAssociative,
  19648. isOrdered: isOrdered,
  19649. isValueObject: isValueObject,
  19650. isSeq: isSeq,
  19651. isList: isList,
  19652. isMap: isMap,
  19653. isOrderedMap: isOrderedMap,
  19654. isStack: isStack,
  19655. isSet: isSet,
  19656. isOrderedSet: isOrderedSet,
  19657. isRecord: isRecord,
  19658. get: get,
  19659. getIn: getIn,
  19660. has: has,
  19661. hasIn: hasIn,
  19662. merge: merge$1,
  19663. mergeDeep: mergeDeep,
  19664. mergeWith: mergeWith$1,
  19665. mergeDeepWith: mergeDeepWith,
  19666. remove: remove,
  19667. removeIn: removeIn,
  19668. set: set,
  19669. setIn: setIn,
  19670. update: update,
  19671. updateIn: updateIn,
  19672. };
  19673. // Note: Iterable is deprecated
  19674. var Iterable = Collection;
  19675. exports.default = Immutable;
  19676. exports.version = version;
  19677. exports.Collection = Collection;
  19678. exports.Iterable = Iterable;
  19679. exports.Seq = Seq;
  19680. exports.Map = Map;
  19681. exports.OrderedMap = OrderedMap;
  19682. exports.List = List;
  19683. exports.Stack = Stack;
  19684. exports.Set = Set;
  19685. exports.OrderedSet = OrderedSet;
  19686. exports.Record = Record;
  19687. exports.Range = Range;
  19688. exports.Repeat = Repeat;
  19689. exports.is = is;
  19690. exports.fromJS = fromJS;
  19691. exports.hash = hash;
  19692. exports.isImmutable = isImmutable;
  19693. exports.isCollection = isCollection;
  19694. exports.isKeyed = isKeyed;
  19695. exports.isIndexed = isIndexed;
  19696. exports.isAssociative = isAssociative;
  19697. exports.isOrdered = isOrdered;
  19698. exports.isValueObject = isValueObject;
  19699. exports.get = get;
  19700. exports.getIn = getIn;
  19701. exports.has = has;
  19702. exports.hasIn = hasIn;
  19703. exports.merge = merge$1;
  19704. exports.mergeDeep = mergeDeep;
  19705. exports.mergeWith = mergeWith$1;
  19706. exports.mergeDeepWith = mergeDeepWith;
  19707. exports.remove = remove;
  19708. exports.removeIn = removeIn;
  19709. exports.set = set;
  19710. exports.setIn = setIn;
  19711. exports.update = update;
  19712. exports.updateIn = updateIn;
  19713. Object.defineProperty(exports, '__esModule', { value: true });
  19714. })));
  19715. });
  19716. unwrapExports(immutable$1);
  19717. var draftjsUtils = createCommonjsModule(function (module, exports) {
  19718. !function(t,e){module.exports=e(Draft,immutable$1);}(window,function(n,r){return u={},o.m=i=[function(t,e){t.exports=n;},function(t,e){t.exports=r;},function(t,e,n){t.exports=n(3);},function(t,e,n){n.r(e);var C=n(0),i=n(1);function m(t){var e=t.getSelection(),n=t.getCurrentContent(),r=e.getStartKey(),o=e.getEndKey(),i=n.getBlockMap();return i.toSeq().skipUntil(function(t,e){return e===r}).takeUntil(function(t,e){return e===o}).concat([[o,i.get(o)]])}function a(t){return m(t).toList()}function f(t){if(t)return a(t).get(0)}function r(t){if(t){var n=f(t),e=t.getCurrentContent().getBlockMap().toSeq().toList(),r=0;if(e.forEach(function(t,e){t.get("key")===n.get("key")&&(r=e-1);}),-1<r)return e.get(r)}}function o(t){return t?t.getCurrentContent().getBlockMap().toList():new i.List}function u(t){var e=a(t);if(!e.some(function(t){return t.type!==e.get(0).type}))return e.get(0).type}function c(t){var e=C.RichUtils.tryToRemoveBlockStyle(t);return e?C.EditorState.push(t,e,"change-block-type"):t}function l(t){var e="",n=t.getSelection(),r=n.getAnchorOffset(),o=n.getFocusOffset(),i=a(t);if(0<i.size){if(n.getIsBackward()){var u=r;r=o,o=u;}for(var c=0;c<i.size;c+=1){var f=0===c?r:0,l=c===i.size-1?o:i.get(c).getText().length;e+=i.get(c).getText().slice(f,l);}}return e}function s(t){var e=t.getCurrentContent(),n=t.getSelection(),r=C.Modifier.removeRange(e,n,"forward"),o=r.getSelectionAfter(),i=r.getBlockForKey(o.getStartKey());return r=C.Modifier.insertText(r,o,"\n",i.getInlineStyleAt(o.getStartOffset()),null),C.EditorState.push(t,r,"insert-fragment")}function g(t){var e=C.Modifier.splitBlock(t.getCurrentContent(),t.getSelection());return c(C.EditorState.push(t,e,"split-block"))}function d(t){var e=t.getCurrentContent().getBlockMap().toList(),n=t.getSelection().merge({anchorKey:e.first().get("key"),anchorOffset:0,focusKey:e.last().get("key"),focusOffset:e.last().getLength()}),r=C.Modifier.removeRange(t.getCurrentContent(),n,"forward");return C.EditorState.push(t,r,"remove-range")}function S(t,e){var n=C.Modifier.setBlockData(t.getCurrentContent(),t.getSelection(),e);return C.EditorState.push(t,n,"change-block-data")}function p(t){var r=new i.Map({}),e=a(t);if(e&&0<e.size)for(var n=function(t){var n=e.get(t).getData();if(!n||0===n.size)return r=r.clear(),"break";if(0===t)r=n;else if(r.forEach(function(t,e){n.get(e)&&n.get(e)===t||(r=r.delete(e));}),0===r.size)return r=r.clear(),"break"},o=0;o<e.size;o+=1){if("break"===n(o))break}return r}var y=Object(i.Map)({code:{element:"pre"}}),v=C.DefaultDraftBlockRenderMap.merge(y);function b(t){if(t){var e=t.getType();return "unordered-list-item"===e||"ordered-list-item"===e}return !1}function h(t,e,n){var r,o=t.getSelection();r=o.getIsBackward()?o.getFocusKey():o.getAnchorKey();var i=t.getCurrentContent(),u=i.getBlockForKey(r),c=u.getType();if("unordered-list-item"!==c&&"ordered-list-item"!==c)return t;var f=i.getBlockBefore(r);if(!f)return t;if(f.getType()!==c)return t;var l=u.getDepth();if(1===e&&l===n)return t;var a,s,g,d,S,p,y,v=Math.min(f.getDepth()+1,n),b=(s=e,g=v,d=(a=t).getSelection(),S=a.getCurrentContent(),p=S.getBlockMap(),y=m(a).map(function(t){var e=t.getDepth()+s;return e=Math.max(0,Math.min(e,g)),t.set("depth",e)}),p=p.merge(y),S.merge({blockMap:p,selectionBefore:d,selectionAfter:d}));return C.EditorState.push(t,b,"adjust-depth")}function O(t,e){var n;return 13===(n=e).which&&(n.getModifierState("Shift")||n.getModifierState("Alt")||n.getModifierState("Control"))?t.getSelection().isCollapsed()?C.RichUtils.insertSoftNewline(t):s(t):function(t){var e=t.getSelection();if(e.isCollapsed()){var n=t.getCurrentContent(),r=e.getStartKey(),o=n.getBlockForKey(r);if(!b(o)&&"unstyled"!==o.getType()&&o.getLength()===e.getStartOffset())return g(t);if(b(o)&&0===o.getLength()){var i=o.getDepth();if(0===i)return c(t);if(0<i)return h(t,-1,i)}}}(t)}function k(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable})),n.push.apply(n,r);}return n}function E(t,e,n){return e in t?Object.defineProperty(t,e,{value:n,enumerable:!0,configurable:!0,writable:!0}):t[e]=n,t}function I(t){return (I="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t})(t)}function R(t){var e=t.getSelection();if(e.isCollapsed()){var n={},r=t.getCurrentInlineStyle().toList().toJS();if(r)return ["BOLD","ITALIC","UNDERLINE","STRIKETHROUGH","CODE","SUPERSCRIPT","SUBSCRIPT"].forEach(function(t){n[t]=0<=r.indexOf(t);}),n}var u=e.getStartOffset(),c=e.getEndOffset(),f=a(t);if(0<f.size){var o=function(){for(var n={BOLD:!0,ITALIC:!0,UNDERLINE:!0,STRIKETHROUGH:!0,CODE:!0,SUPERSCRIPT:!0,SUBSCRIPT:!0},r=0;r<f.size;r+=1){var t=0===r?u:0,e=r===f.size-1?c:f.get(r).getText().length;t===e&&0===t?(t=1,e=2):t===e&&--t;for(var o=function(t){var e=f.get(r).getInlineStyleAt(t);["BOLD","ITALIC","UNDERLINE","STRIKETHROUGH","CODE","SUPERSCRIPT","SUBSCRIPT"].forEach(function(t){n[t]=n[t]&&e.get(t)===t;});},i=t;i<e;i+=1)o(i);}return {v:n}}();if("object"===I(o))return o.v}return {}}function B(t){var e,n=t.getSelection(),r=n.getStartOffset(),o=n.getEndOffset();r===o&&0===r?o=1:r===o&&--r;for(var i=f(t),u=r;u<o;u+=1){var c=i.getEntityAt(u);if(!c){e=void 0;break}if(u===r)e=c;else if(e!==c){e=void 0;break}}return e}function T(t,e){var n,r=f(t);return r.findEntityRanges(function(t){return t.get("entity")===e},function(t,e){n={start:t,end:e,text:r.get("text").slice(t,e)};}),n}function P(t,e,n){x[t]["".concat(t.toLowerCase(),"-").concat(n)]=E({},"".concat(e),n);}function j(){return function(e){for(var t=1;t<arguments.length;t++){var n=null!=arguments[t]?arguments[t]:{};t%2?k(Object(n),!0).forEach(function(t){E(e,t,n[t]);}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):k(Object(n)).forEach(function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(n,t));});}return e}({},x.color,{},x.bgcolor,{},x.fontSize,{},x.fontFamily,{CODE:x.CODE,SUPERSCRIPT:x.SUPERSCRIPT,SUBSCRIPT:x.SUBSCRIPT})}var x={color:{},bgcolor:{},fontSize:{},fontFamily:{},CODE:{fontFamily:"monospace",wordWrap:"break-word",background:"#f1f1f1",borderRadius:3,padding:"1px 3px"},SUPERSCRIPT:{fontSize:11,position:"relative",top:-8,display:"inline-flex"},SUBSCRIPT:{fontSize:11,position:"relative",bottom:-8,display:"inline-flex"}};function M(t,e,n){var r=t.getSelection(),o=Object.keys(x[e]).reduce(function(t,e){return C.Modifier.removeInlineStyle(t,r,e)},t.getCurrentContent()),i=C.EditorState.push(t,o,"changeinline-style"),u=t.getCurrentInlineStyle();if(r.isCollapsed()&&(i=u.reduce(function(t,e){return C.RichUtils.toggleInlineStyle(t,e)},i)),"SUPERSCRIPT"===e||"SUBSCRIPT"==e)u.has(n)||(i=C.RichUtils.toggleInlineStyle(i,n));else{var c="bgcolor"===e?"backgroundColor":e;u.has("".concat(c,"-").concat(n))||(i=C.RichUtils.toggleInlineStyle(i,"".concat(e.toLowerCase(),"-").concat(n)),P(e,c,n));}return i}function L(t){t&&t.getCurrentContent().getBlockMap().map(function(t){return t.get("characterList")}).toList().flatten().forEach(function(t){t&&0===t.indexOf("color-")?P("color","color",t.substr(6)):t&&0===t.indexOf("bgcolor-")?P("bgcolor","backgroundColor",t.substr(8)):t&&0===t.indexOf("fontsize-")?P("fontSize","fontSize",+t.substr(9)):t&&0===t.indexOf("fontfamily-")&&P("fontFamily","fontFamily",t.substr(11));});}function U(t,e,n){var r=t.getInlineStyleAt(n).toList().filter(function(t){return t.startsWith(e.toLowerCase())});if(r&&0<r.size)return r.get(0)}function w(r,l){if(r&&l&&0<l.length){var t=function(){var t=r.getSelection(),i={};if(t.isCollapsed())return l.forEach(function(t){i[t]=function(t,e){var n=t.getCurrentInlineStyle().toList().filter(function(t){return t.startsWith(e.toLowerCase())});if(n&&0<n.size)return n.get(0)}(r,t);}),{v:i};var u=t.getStartOffset(),c=t.getEndOffset(),f=a(r);if(0<f.size){for(var e=function(n){var t=0===n?u:0,e=n===f.size-1?c:f.get(n).getText().length;t===e&&0===t?(t=1,e=2):t===e&&--t;for(var r=function(e){e===t?l.forEach(function(t){i[t]=U(f.get(n),t,e);}):l.forEach(function(t){i[t]&&i[t]!==U(f.get(n),t,e)&&(i[t]=void 0);});},o=t;o<e;o+=1)r(o);},n=0;n<f.size;n+=1)e(n);return {v:i}}}();if("object"===I(t))return t.v}return {}}function D(e){var t=e.getCurrentInlineStyle(),n=e.getCurrentContent();return t.forEach(function(t){n=C.Modifier.removeInlineStyle(n,e.getSelection(),t);}),C.EditorState.push(e,n,"change-inline-style")}n.d(e,"isListBlock",function(){return b}),n.d(e,"changeDepth",function(){return h}),n.d(e,"handleNewLine",function(){return O}),n.d(e,"getEntityRange",function(){return T}),n.d(e,"getCustomStyleMap",function(){return j}),n.d(e,"toggleCustomInlineStyle",function(){return M}),n.d(e,"getSelectionEntity",function(){return B}),n.d(e,"extractInlineStyle",function(){return L}),n.d(e,"removeAllInlineStyles",function(){return D}),n.d(e,"getSelectionInlineStyle",function(){return R}),n.d(e,"getSelectionCustomInlineStyle",function(){return w}),n.d(e,"getSelectedBlocksMap",function(){return m}),n.d(e,"getSelectedBlocksList",function(){return a}),n.d(e,"getSelectedBlock",function(){return f}),n.d(e,"getBlockBeforeSelectedBlock",function(){return r}),n.d(e,"getAllBlocks",function(){return o}),n.d(e,"getSelectedBlocksType",function(){return u}),n.d(e,"removeSelectedBlocksStyle",function(){return c}),n.d(e,"getSelectionText",function(){return l}),n.d(e,"addLineBreakRemovingSelection",function(){return s}),n.d(e,"insertNewUnstyledBlock",function(){return g}),n.d(e,"clearEditorContent",function(){return d}),n.d(e,"setBlockData",function(){return S}),n.d(e,"getSelectedBlocksMetadata",function(){return p}),n.d(e,"blockRenderMap",function(){return v});}],o.c=u,o.d=function(t,e,n){o.o(t,e)||Object.defineProperty(t,e,{enumerable:!0,get:n});},o.r=function(t){"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(t,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(t,"__esModule",{value:!0});},o.t=function(e,t){if(1&t&&(e=o(e)),8&t)return e;if(4&t&&"object"==typeof e&&e&&e.__esModule)return e;var n=Object.create(null);if(o.r(n),Object.defineProperty(n,"default",{enumerable:!0,value:e}),2&t&&"string"!=typeof e)for(var r in e)o.d(n,r,function(t){return e[t]}.bind(null,r));return n},o.n=function(t){var e=t&&t.__esModule?function(){return t.default}:function(){return t};return o.d(e,"a",e),e},o.o=function(t,e){return Object.prototype.hasOwnProperty.call(t,e)},o.p="",o(o.s=2);function o(t){if(u[t])return u[t].exports;var e=u[t]={i:t,l:!1,exports:{}};return i[t].call(e.exports,e,e.exports,o),e.l=!0,e.exports}var i,u;});
  19719. });
  19720. unwrapExports(draftjsUtils);
  19721. var draftjsUtils_1 = draftjsUtils.draftjsUtils;
  19722. var interopRequireDefault = createCommonjsModule(function (module) {
  19723. function _interopRequireDefault(obj) {
  19724. return obj && obj.__esModule ? obj : {
  19725. "default": obj
  19726. };
  19727. }
  19728. module.exports = _interopRequireDefault;
  19729. });
  19730. unwrapExports(interopRequireDefault);
  19731. /**
  19732. * Copyright (c) 2013-present, Facebook, Inc.
  19733. *
  19734. * This source code is licensed under the MIT license found in the
  19735. * LICENSE file in the root directory of this source tree.
  19736. */
  19737. /**
  19738. * Use invariant() to assert state which your program assumes to be true.
  19739. *
  19740. * Provide sprintf-style format (only %s is supported) and arguments
  19741. * to provide information about what broke and what you were
  19742. * expecting.
  19743. *
  19744. * The invariant message will be stripped in production, but the invariant
  19745. * will remain to ensure logic does not differ in production.
  19746. */
  19747. var invariant$1 = function(condition, format, a, b, c, d, e, f) {
  19748. if (process.env.NODE_ENV !== 'production') {
  19749. if (format === undefined) {
  19750. throw new Error('invariant requires an error message argument');
  19751. }
  19752. }
  19753. if (!condition) {
  19754. var error;
  19755. if (format === undefined) {
  19756. error = new Error(
  19757. 'Minified exception occurred; use the non-minified dev environment ' +
  19758. 'for the full error message and additional helpful warnings.'
  19759. );
  19760. } else {
  19761. var args = [a, b, c, d, e, f];
  19762. var argIndex = 0;
  19763. error = new Error(
  19764. format.replace(/%s/g, function() { return args[argIndex++]; })
  19765. );
  19766. error.name = 'Invariant Violation';
  19767. }
  19768. error.framesToPop = 1; // we don't care about invariant's own frame
  19769. throw error;
  19770. }
  19771. };
  19772. var browser = invariant$1;
  19773. function _arrayWithoutHoles(arr) {
  19774. if (Array.isArray(arr)) {
  19775. for (var i = 0, arr2 = new Array(arr.length); i < arr.length; i++) {
  19776. arr2[i] = arr[i];
  19777. }
  19778. return arr2;
  19779. }
  19780. }
  19781. var arrayWithoutHoles = _arrayWithoutHoles;
  19782. function _iterableToArray(iter) {
  19783. if (Symbol.iterator in Object(iter) || Object.prototype.toString.call(iter) === "[object Arguments]") return Array.from(iter);
  19784. }
  19785. var iterableToArray = _iterableToArray;
  19786. function _nonIterableSpread() {
  19787. throw new TypeError("Invalid attempt to spread non-iterable instance");
  19788. }
  19789. var nonIterableSpread = _nonIterableSpread;
  19790. function _toConsumableArray(arr) {
  19791. return arrayWithoutHoles(arr) || iterableToArray(arr) || nonIterableSpread();
  19792. }
  19793. var toConsumableArray = _toConsumableArray;
  19794. var updateMutation_1 = createCommonjsModule(function (module, exports) {
  19795. Object.defineProperty(exports, "__esModule", {
  19796. value: true
  19797. });
  19798. exports["default"] = updateMutation;
  19799. function updateMutation(mutation, originalOffset, originalLength, newLength, prefixLength, suffixLength) {
  19800. // three cases we can reasonably adjust - disjoint mutations that
  19801. // happen later on where the offset will need to be changed,
  19802. // mutations that completely contain the new one where we can adjust
  19803. // the length, and mutations that occur partially within the new one.
  19804. var lengthDiff = newLength - originalLength;
  19805. var mutationAfterChange = originalOffset + originalLength <= mutation.offset;
  19806. if (mutationAfterChange) {
  19807. return Object.assign({}, mutation, {
  19808. offset: mutation.offset + lengthDiff
  19809. });
  19810. }
  19811. var mutationContainsChange = originalOffset >= mutation.offset && originalOffset + originalLength <= mutation.offset + mutation.length;
  19812. if (mutationContainsChange) {
  19813. return Object.assign({}, mutation, {
  19814. length: mutation.length + lengthDiff
  19815. });
  19816. }
  19817. var mutationWithinPrefixChange = mutation.offset >= originalOffset && mutation.offset + mutation.length <= originalOffset + originalLength && prefixLength > 0;
  19818. if (mutationWithinPrefixChange) {
  19819. return Object.assign({}, mutation, {
  19820. offset: mutation.offset + prefixLength
  19821. });
  19822. }
  19823. var mutationContainsPrefix = mutation.offset < originalOffset && mutation.offset + mutation.length <= originalOffset + originalLength && mutation.offset + mutation.length > originalOffset && prefixLength > 0;
  19824. if (mutationContainsPrefix) {
  19825. return [Object.assign({}, mutation, {
  19826. length: originalOffset - mutation.offset
  19827. }), Object.assign({}, mutation, {
  19828. offset: originalOffset + prefixLength,
  19829. length: mutation.offset - originalOffset + mutation.length
  19830. })];
  19831. }
  19832. var mutationContainsSuffix = mutation.offset >= originalOffset && mutation.offset + mutation.length > originalOffset + originalLength && originalOffset + originalLength > mutation.offset && suffixLength > 0;
  19833. if (mutationContainsSuffix) {
  19834. return [Object.assign({}, mutation, {
  19835. offset: mutation.offset + prefixLength,
  19836. length: originalOffset + originalLength - mutation.offset
  19837. }), Object.assign({}, mutation, {
  19838. offset: originalOffset + originalLength + prefixLength + suffixLength,
  19839. length: mutation.offset + mutation.length - (originalOffset + originalLength)
  19840. })];
  19841. }
  19842. return mutation;
  19843. }
  19844. });
  19845. unwrapExports(updateMutation_1);
  19846. var rangeSort = createCommonjsModule(function (module, exports) {
  19847. Object.defineProperty(exports, "__esModule", {
  19848. value: true
  19849. });
  19850. exports["default"] = void 0;
  19851. var _default = function _default(r1, r2) {
  19852. if (r1.offset === r2.offset) {
  19853. return r2.length - r1.length;
  19854. }
  19855. return r1.offset - r2.offset;
  19856. };
  19857. exports["default"] = _default;
  19858. });
  19859. unwrapExports(rangeSort);
  19860. var encodeBlock = createCommonjsModule(function (module, exports) {
  19861. Object.defineProperty(exports, "__esModule", {
  19862. value: true
  19863. });
  19864. exports["default"] = void 0;
  19865. var _toConsumableArray2 = interopRequireDefault(toConsumableArray);
  19866. var _updateMutation = interopRequireDefault(updateMutation_1);
  19867. var _rangeSort = interopRequireDefault(rangeSort);
  19868. var ENTITY_MAP = {
  19869. '&': '&amp;',
  19870. '<': '&lt;',
  19871. '>': '&gt;',
  19872. '"': '&quot;',
  19873. "'": '&#x27;',
  19874. '`': '&#x60;',
  19875. '\n': '<br/>'
  19876. };
  19877. var _default = function _default(block) {
  19878. var blockText = (0, _toConsumableArray2["default"])(block.text);
  19879. var entities = block.entityRanges.sort(_rangeSort["default"]);
  19880. var styles = block.inlineStyleRanges.sort(_rangeSort["default"]);
  19881. var resultText = '';
  19882. var _loop = function _loop(index) {
  19883. var _char = blockText[index];
  19884. if (ENTITY_MAP[_char] !== undefined) {
  19885. var encoded = ENTITY_MAP[_char];
  19886. var resultIndex = (0, _toConsumableArray2["default"])(resultText).length;
  19887. resultText += encoded;
  19888. var updateForChar = function updateForChar(mutation) {
  19889. return (0, _updateMutation["default"])(mutation, resultIndex, _char.length, encoded.length, 0, 0);
  19890. };
  19891. entities = entities.map(updateForChar);
  19892. styles = styles.map(updateForChar);
  19893. } else {
  19894. resultText += _char;
  19895. }
  19896. };
  19897. for (var index = 0; index < blockText.length; index++) {
  19898. _loop(index);
  19899. }
  19900. return Object.assign({}, block, {
  19901. text: resultText,
  19902. inlineStyleRanges: styles,
  19903. entityRanges: entities
  19904. });
  19905. };
  19906. exports["default"] = _default;
  19907. });
  19908. unwrapExports(encodeBlock);
  19909. var _typeof_1 = createCommonjsModule(function (module) {
  19910. function _typeof(obj) {
  19911. if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") {
  19912. module.exports = _typeof = function _typeof(obj) {
  19913. return typeof obj;
  19914. };
  19915. } else {
  19916. module.exports = _typeof = function _typeof(obj) {
  19917. return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj;
  19918. };
  19919. }
  19920. return _typeof(obj);
  19921. }
  19922. module.exports = _typeof;
  19923. });
  19924. var splitReactElement_1 = createCommonjsModule(function (module, exports) {
  19925. Object.defineProperty(exports, "__esModule", {
  19926. value: true
  19927. });
  19928. exports["default"] = splitReactElement;
  19929. var _invariant = interopRequireDefault(browser);
  19930. var _react = interopRequireDefault(React);
  19931. var _server = interopRequireDefault(server);
  19932. // see http://w3c.github.io/html/syntax.html#writing-html-documents-elements
  19933. var VOID_TAGS = ['area', 'base', 'br', 'col', 'embed', 'hr', 'img', 'input', 'link', 'meta', 'param', 'source', 'track', 'wbr'];
  19934. function splitReactElement(element) {
  19935. if (VOID_TAGS.indexOf(element.type) !== -1) {
  19936. return _server["default"].renderToStaticMarkup(element);
  19937. }
  19938. var tags = _server["default"].renderToStaticMarkup(_react["default"].cloneElement(element, {}, '\r')).split('\r');
  19939. (0, _invariant["default"])(tags.length > 1, "convertToHTML: Element of type ".concat(element.type, " must render children"));
  19940. (0, _invariant["default"])(tags.length < 3, "convertToHTML: Element of type ".concat(element.type, " cannot use carriage return character"));
  19941. return {
  19942. start: tags[0],
  19943. end: tags[1]
  19944. };
  19945. }
  19946. });
  19947. unwrapExports(splitReactElement_1);
  19948. var getElementHTML_1 = createCommonjsModule(function (module, exports) {
  19949. Object.defineProperty(exports, "__esModule", {
  19950. value: true
  19951. });
  19952. exports["default"] = getElementHTML;
  19953. var _typeof2 = interopRequireDefault(_typeof_1);
  19954. var _invariant = interopRequireDefault(browser);
  19955. var _react = interopRequireDefault(React);
  19956. var _server = interopRequireDefault(server);
  19957. var _splitReactElement = interopRequireDefault(splitReactElement_1);
  19958. function hasChildren(element) {
  19959. return _react["default"].isValidElement(element) && _react["default"].Children.count(element.props.children) > 0;
  19960. }
  19961. function getElementHTML(element) {
  19962. var text = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : null;
  19963. if (element === undefined || element === null) {
  19964. return element;
  19965. }
  19966. if (typeof element === 'string') {
  19967. return element;
  19968. }
  19969. if (_react["default"].isValidElement(element)) {
  19970. if (hasChildren(element)) {
  19971. return _server["default"].renderToStaticMarkup(element);
  19972. }
  19973. var tags = (0, _splitReactElement["default"])(element);
  19974. if (text !== null && (0, _typeof2["default"])(tags) === 'object') {
  19975. var start = tags.start,
  19976. end = tags.end;
  19977. return start + text + end;
  19978. }
  19979. return tags;
  19980. }
  19981. (0, _invariant["default"])(Object.prototype.hasOwnProperty.call(element, 'start') && Object.prototype.hasOwnProperty.call(element, 'end'), 'convertToHTML: received conversion data without either an HTML string, ReactElement or an object with start/end tags');
  19982. if (text !== null) {
  19983. var _start = element.start,
  19984. _end = element.end;
  19985. return _start + text + _end;
  19986. }
  19987. return element;
  19988. }
  19989. });
  19990. unwrapExports(getElementHTML_1);
  19991. var getElementTagLength_1 = createCommonjsModule(function (module, exports) {
  19992. Object.defineProperty(exports, "__esModule", {
  19993. value: true
  19994. });
  19995. exports["default"] = void 0;
  19996. var _typeof2 = interopRequireDefault(_typeof_1);
  19997. var _react = interopRequireDefault(React);
  19998. var _splitReactElement = interopRequireDefault(splitReactElement_1);
  19999. var getElementTagLength = function getElementTagLength(element) {
  20000. var type = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 'start';
  20001. if (_react["default"].isValidElement(element)) {
  20002. var splitElement = (0, _splitReactElement["default"])(element);
  20003. if (typeof splitElement === 'string') {
  20004. return 0;
  20005. }
  20006. var length = splitElement[type].length;
  20007. var child = _react["default"].Children.toArray(element.props.children)[0];
  20008. return length + (child && _react["default"].isValidElement(child) ? getElementTagLength(child, type) : 0);
  20009. }
  20010. if ((0, _typeof2["default"])(element) === 'object') {
  20011. return element[type] ? element[type].length : 0;
  20012. }
  20013. return 0;
  20014. };
  20015. var _default = getElementTagLength;
  20016. exports["default"] = _default;
  20017. });
  20018. unwrapExports(getElementTagLength_1);
  20019. var blockEntities = createCommonjsModule(function (module, exports) {
  20020. Object.defineProperty(exports, "__esModule", {
  20021. value: true
  20022. });
  20023. exports["default"] = void 0;
  20024. var _toConsumableArray2 = interopRequireDefault(toConsumableArray);
  20025. var _updateMutation = interopRequireDefault(updateMutation_1);
  20026. var _rangeSort = interopRequireDefault(rangeSort);
  20027. var _getElementHTML = interopRequireDefault(getElementHTML_1);
  20028. var _getElementTagLength = interopRequireDefault(getElementTagLength_1);
  20029. var converter = function converter() {
  20030. var originalText = arguments.length > 1 ? arguments[1] : undefined;
  20031. return originalText;
  20032. };
  20033. var _default = function _default(block, entityMap) {
  20034. var entityConverter = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : converter;
  20035. var resultText = (0, _toConsumableArray2["default"])(block.text);
  20036. var getEntityHTML = entityConverter;
  20037. if (entityConverter.__isMiddleware) {
  20038. getEntityHTML = entityConverter(converter);
  20039. }
  20040. if (Object.prototype.hasOwnProperty.call(block, 'entityRanges') && block.entityRanges.length > 0) {
  20041. var entities = block.entityRanges.sort(_rangeSort["default"]);
  20042. var styles = block.inlineStyleRanges;
  20043. var _loop = function _loop(index) {
  20044. var entityRange = entities[index];
  20045. var entity = entityMap[entityRange.key];
  20046. var originalText = resultText.slice(entityRange.offset, entityRange.offset + entityRange.length).join('');
  20047. var entityHTML = getEntityHTML(entity, originalText);
  20048. var converted = (0, _toConsumableArray2["default"])((0, _getElementHTML["default"])(entityHTML, originalText) || originalText);
  20049. var prefixLength = (0, _getElementTagLength["default"])(entityHTML, 'start');
  20050. var suffixLength = (0, _getElementTagLength["default"])(entityHTML, 'end');
  20051. var updateLaterMutation = function updateLaterMutation(mutation, mutationIndex) {
  20052. if (mutationIndex > index || Object.prototype.hasOwnProperty.call(mutation, 'style')) {
  20053. return (0, _updateMutation["default"])(mutation, entityRange.offset, entityRange.length, converted.length, prefixLength, suffixLength);
  20054. }
  20055. return mutation;
  20056. };
  20057. var updateLaterMutations = function updateLaterMutations(mutationList) {
  20058. return mutationList.reduce(function (acc, mutation, mutationIndex) {
  20059. var updatedMutation = updateLaterMutation(mutation, mutationIndex);
  20060. if (Array.isArray(updatedMutation)) {
  20061. return acc.concat(updatedMutation);
  20062. }
  20063. return acc.concat([updatedMutation]);
  20064. }, []);
  20065. };
  20066. entities = updateLaterMutations(entities);
  20067. styles = updateLaterMutations(styles);
  20068. resultText = [].concat((0, _toConsumableArray2["default"])(resultText.slice(0, entityRange.offset)), (0, _toConsumableArray2["default"])(converted), (0, _toConsumableArray2["default"])(resultText.slice(entityRange.offset + entityRange.length)));
  20069. };
  20070. for (var index = 0; index < entities.length; index++) {
  20071. _loop(index);
  20072. }
  20073. return Object.assign({}, block, {
  20074. text: resultText.join(''),
  20075. inlineStyleRanges: styles,
  20076. entityRanges: entities
  20077. });
  20078. }
  20079. return block;
  20080. };
  20081. exports["default"] = _default;
  20082. });
  20083. unwrapExports(blockEntities);
  20084. var styleObjectFunction = createCommonjsModule(function (module, exports) {
  20085. Object.defineProperty(exports, "__esModule", {
  20086. value: true
  20087. });
  20088. exports["default"] = void 0;
  20089. var _default = function _default(object) {
  20090. return function (style) {
  20091. if (typeof object === 'function') {
  20092. return object(style);
  20093. }
  20094. return object[style];
  20095. };
  20096. };
  20097. exports["default"] = _default;
  20098. });
  20099. unwrapExports(styleObjectFunction);
  20100. var accumulateFunction = createCommonjsModule(function (module, exports) {
  20101. Object.defineProperty(exports, "__esModule", {
  20102. value: true
  20103. });
  20104. exports["default"] = void 0;
  20105. var _default = function _default(newFn, rest) {
  20106. return function () {
  20107. var newResult = newFn.apply(void 0, arguments);
  20108. if (newResult !== undefined && newResult !== null) {
  20109. return newResult;
  20110. }
  20111. return rest.apply(void 0, arguments);
  20112. };
  20113. };
  20114. exports["default"] = _default;
  20115. });
  20116. unwrapExports(accumulateFunction);
  20117. var defaultInlineHTML_1 = createCommonjsModule(function (module, exports) {
  20118. Object.defineProperty(exports, "__esModule", {
  20119. value: true
  20120. });
  20121. exports["default"] = defaultInlineHTML;
  20122. var _react = interopRequireDefault(React);
  20123. function defaultInlineHTML(style) {
  20124. switch (style) {
  20125. case 'BOLD':
  20126. return _react["default"].createElement("strong", null);
  20127. case 'ITALIC':
  20128. return _react["default"].createElement("em", null);
  20129. case 'UNDERLINE':
  20130. return _react["default"].createElement("u", null);
  20131. case 'CODE':
  20132. return _react["default"].createElement("code", null);
  20133. default:
  20134. return {
  20135. start: '',
  20136. end: ''
  20137. };
  20138. }
  20139. }
  20140. });
  20141. unwrapExports(defaultInlineHTML_1);
  20142. var blockInlineStyles = createCommonjsModule(function (module, exports) {
  20143. Object.defineProperty(exports, "__esModule", {
  20144. value: true
  20145. });
  20146. exports["default"] = void 0;
  20147. var _toConsumableArray2 = interopRequireDefault(toConsumableArray);
  20148. var _invariant = interopRequireDefault(browser);
  20149. var _styleObjectFunction = interopRequireDefault(styleObjectFunction);
  20150. var _accumulateFunction = interopRequireDefault(accumulateFunction);
  20151. var _getElementHTML = interopRequireDefault(getElementHTML_1);
  20152. var _rangeSort = interopRequireDefault(rangeSort);
  20153. var _defaultInlineHTML = interopRequireDefault(defaultInlineHTML_1);
  20154. var subtractStyles = function subtractStyles(original, toRemove) {
  20155. return original.filter(function (el) {
  20156. return !toRemove.some(function (elToRemove) {
  20157. return elToRemove.style === el.style;
  20158. });
  20159. });
  20160. };
  20161. var popEndingStyles = function popEndingStyles(styleStack, endingStyles) {
  20162. return endingStyles.reduceRight(function (stack, style) {
  20163. var styleToRemove = stack[stack.length - 1];
  20164. (0, _invariant["default"])(styleToRemove.style === style.style, "Style ".concat(styleToRemove.style, " to be removed doesn't match expected ").concat(style.style));
  20165. return stack.slice(0, -1);
  20166. }, styleStack);
  20167. };
  20168. var characterStyles = function characterStyles(offset, ranges) {
  20169. return ranges.filter(function (range) {
  20170. return offset >= range.offset && offset < range.offset + range.length;
  20171. });
  20172. };
  20173. var rangeIsSubset = function rangeIsSubset(firstRange, secondRange) {
  20174. // returns true if the second range is a subset of the first
  20175. var secondStartWithinFirst = firstRange.offset <= secondRange.offset;
  20176. var secondEndWithinFirst = firstRange.offset + firstRange.length >= secondRange.offset + secondRange.length;
  20177. return secondStartWithinFirst && secondEndWithinFirst;
  20178. };
  20179. var latestStyleLast = function latestStyleLast(s1, s2) {
  20180. // make sure longer-lasting styles are added first
  20181. var s2endIndex = s2.offset + s2.length;
  20182. var s1endIndex = s1.offset + s1.length;
  20183. return s2endIndex - s1endIndex;
  20184. };
  20185. var getStylesToReset = function getStylesToReset(remainingStyles, newStyles) {
  20186. var i = 0;
  20187. while (i < remainingStyles.length) {
  20188. if (newStyles.every(rangeIsSubset.bind(null, remainingStyles[i]))) {
  20189. i++;
  20190. } else {
  20191. return remainingStyles.slice(i);
  20192. }
  20193. }
  20194. return [];
  20195. };
  20196. var appendStartMarkup = function appendStartMarkup(inlineHTML, string, styleRange) {
  20197. return string + (0, _getElementHTML["default"])(inlineHTML(styleRange.style)).start;
  20198. };
  20199. var prependEndMarkup = function prependEndMarkup(inlineHTML, string, styleRange) {
  20200. return (0, _getElementHTML["default"])(inlineHTML(styleRange.style)).end + string;
  20201. };
  20202. var defaultCustomInlineHTML = function defaultCustomInlineHTML(next) {
  20203. return function (style) {
  20204. return next(style);
  20205. };
  20206. };
  20207. defaultCustomInlineHTML.__isMiddleware = true;
  20208. var _default = function _default(rawBlock) {
  20209. var customInlineHTML = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : defaultCustomInlineHTML;
  20210. (0, _invariant["default"])(rawBlock !== null && rawBlock !== undefined, 'Expected raw block to be non-null');
  20211. var inlineHTML;
  20212. if (customInlineHTML.__isMiddleware === true) {
  20213. inlineHTML = customInlineHTML(_defaultInlineHTML["default"]);
  20214. } else {
  20215. inlineHTML = (0, _accumulateFunction["default"])((0, _styleObjectFunction["default"])(customInlineHTML), (0, _styleObjectFunction["default"])(_defaultInlineHTML["default"]));
  20216. }
  20217. var result = '';
  20218. var styleStack = [];
  20219. var sortedRanges = rawBlock.inlineStyleRanges.sort(_rangeSort["default"]);
  20220. var originalTextArray = (0, _toConsumableArray2["default"])(rawBlock.text);
  20221. for (var i = 0; i < originalTextArray.length; i++) {
  20222. var styles = characterStyles(i, sortedRanges);
  20223. var endingStyles = subtractStyles(styleStack, styles);
  20224. var newStyles = subtractStyles(styles, styleStack);
  20225. var remainingStyles = subtractStyles(styleStack, endingStyles); // reset styles: look for any already existing styles that will need to
  20226. // end before styles that are being added on this character. to solve this
  20227. // close out those current tags and all nested children,
  20228. // then open new ones nested within the new styles.
  20229. var resetStyles = getStylesToReset(remainingStyles, newStyles);
  20230. var openingStyles = resetStyles.concat(newStyles).sort(latestStyleLast);
  20231. var openingStyleTags = openingStyles.reduce(appendStartMarkup.bind(null, inlineHTML), '');
  20232. var endingStyleTags = endingStyles.concat(resetStyles).reduce(prependEndMarkup.bind(null, inlineHTML), '');
  20233. result += endingStyleTags + openingStyleTags + originalTextArray[i];
  20234. styleStack = popEndingStyles(styleStack, resetStyles.concat(endingStyles));
  20235. styleStack = styleStack.concat(openingStyles);
  20236. (0, _invariant["default"])(styleStack.length === styles.length, "Character ".concat(i, ": ").concat(styleStack.length - styles.length, " styles left on stack that should no longer be there"));
  20237. }
  20238. result = styleStack.reduceRight(function (res, openStyle) {
  20239. return res + (0, _getElementHTML["default"])(inlineHTML(openStyle.style)).end;
  20240. }, result);
  20241. return result;
  20242. };
  20243. exports["default"] = _default;
  20244. });
  20245. unwrapExports(blockInlineStyles);
  20246. var blockTypeObjectFunction = createCommonjsModule(function (module, exports) {
  20247. Object.defineProperty(exports, "__esModule", {
  20248. value: true
  20249. });
  20250. exports["default"] = void 0;
  20251. var _default = function _default(typeObject) {
  20252. return function (block) {
  20253. if (typeof typeObject === 'function') {
  20254. // handle case where typeObject is already a function
  20255. return typeObject(block);
  20256. }
  20257. return typeObject[block.type];
  20258. };
  20259. };
  20260. exports["default"] = _default;
  20261. });
  20262. unwrapExports(blockTypeObjectFunction);
  20263. var getBlockTags_1 = createCommonjsModule(function (module, exports) {
  20264. Object.defineProperty(exports, "__esModule", {
  20265. value: true
  20266. });
  20267. exports["default"] = getBlockTags;
  20268. var _invariant = interopRequireDefault(browser);
  20269. var _react = interopRequireDefault(React);
  20270. var _server = interopRequireDefault(server);
  20271. var _splitReactElement = interopRequireDefault(splitReactElement_1);
  20272. function hasChildren(element) {
  20273. return _react["default"].isValidElement(element) && _react["default"].Children.count(element.props.children) > 0;
  20274. }
  20275. function getBlockTags(blockHTML) {
  20276. (0, _invariant["default"])(blockHTML !== null && blockHTML !== undefined, 'Expected block HTML value to be non-null');
  20277. if (typeof blockHTML === 'string') {
  20278. return blockHTML;
  20279. }
  20280. if (_react["default"].isValidElement(blockHTML)) {
  20281. if (hasChildren(blockHTML)) {
  20282. return _server["default"].renderToStaticMarkup(blockHTML);
  20283. }
  20284. return (0, _splitReactElement["default"])(blockHTML);
  20285. }
  20286. if (Object.prototype.hasOwnProperty.call(blockHTML, 'element') && _react["default"].isValidElement(blockHTML.element)) {
  20287. return Object.assign({}, blockHTML, (0, _splitReactElement["default"])(blockHTML.element));
  20288. }
  20289. (0, _invariant["default"])(Object.prototype.hasOwnProperty.call(blockHTML, 'start') && Object.prototype.hasOwnProperty.call(blockHTML, 'end'), 'convertToHTML: received block information without either a ReactElement or an object with start/end tags');
  20290. return blockHTML;
  20291. }
  20292. });
  20293. unwrapExports(getBlockTags_1);
  20294. var getNestedBlockTags_1 = createCommonjsModule(function (module, exports) {
  20295. Object.defineProperty(exports, "__esModule", {
  20296. value: true
  20297. });
  20298. exports["default"] = getNestedBlockTags;
  20299. var _invariant = interopRequireDefault(browser);
  20300. var _react = interopRequireDefault(React);
  20301. var _splitReactElement2 = interopRequireDefault(splitReactElement_1);
  20302. function getNestedBlockTags(blockHTML) {
  20303. (0, _invariant["default"])(blockHTML !== null && blockHTML !== undefined, 'Expected block HTML value to be non-null');
  20304. if (_react["default"].isValidElement(blockHTML.nest)) {
  20305. var _splitReactElement = (0, _splitReactElement2["default"])(blockHTML.nest),
  20306. start = _splitReactElement.start,
  20307. end = _splitReactElement.end;
  20308. return Object.assign({}, blockHTML, {
  20309. nestStart: start,
  20310. nestEnd: end
  20311. });
  20312. }
  20313. (0, _invariant["default"])(Object.prototype.hasOwnProperty.call(blockHTML, 'nestStart') && Object.prototype.hasOwnProperty.call(blockHTML, 'nestEnd'), 'convertToHTML: received block information without either a ReactElement or an object with start/end tags');
  20314. return blockHTML;
  20315. }
  20316. });
  20317. unwrapExports(getNestedBlockTags_1);
  20318. var defaultBlockHTML = createCommonjsModule(function (module, exports) {
  20319. Object.defineProperty(exports, "__esModule", {
  20320. value: true
  20321. });
  20322. exports["default"] = void 0;
  20323. var _react = interopRequireDefault(React);
  20324. var _default = {
  20325. unstyled: _react["default"].createElement("p", null),
  20326. paragraph: _react["default"].createElement("p", null),
  20327. 'header-one': _react["default"].createElement("h1", null),
  20328. 'header-two': _react["default"].createElement("h2", null),
  20329. 'header-three': _react["default"].createElement("h3", null),
  20330. 'header-four': _react["default"].createElement("h4", null),
  20331. 'header-five': _react["default"].createElement("h5", null),
  20332. 'header-six': _react["default"].createElement("h6", null),
  20333. blockquote: _react["default"].createElement("blockquote", null),
  20334. 'unordered-list-item': {
  20335. element: _react["default"].createElement("li", null),
  20336. nest: _react["default"].createElement("ul", null)
  20337. },
  20338. 'ordered-list-item': {
  20339. element: _react["default"].createElement("li", null),
  20340. nest: _react["default"].createElement("ol", null)
  20341. },
  20342. media: _react["default"].createElement("figure", null),
  20343. atomic: _react["default"].createElement("figure", null)
  20344. };
  20345. exports["default"] = _default;
  20346. });
  20347. unwrapExports(defaultBlockHTML);
  20348. var convertToHTML_1 = createCommonjsModule(function (module, exports) {
  20349. Object.defineProperty(exports, "__esModule", {
  20350. value: true
  20351. });
  20352. exports["default"] = void 0;
  20353. var _invariant = interopRequireDefault(browser);
  20354. var _react = interopRequireDefault(React);
  20355. var _server = interopRequireDefault(server);
  20356. var _encodeBlock = interopRequireDefault(encodeBlock);
  20357. var _blockEntities = interopRequireDefault(blockEntities);
  20358. var _blockInlineStyles = interopRequireDefault(blockInlineStyles);
  20359. var _accumulateFunction = interopRequireDefault(accumulateFunction);
  20360. var _blockTypeObjectFunction = interopRequireDefault(blockTypeObjectFunction);
  20361. var _getBlockTags = interopRequireDefault(getBlockTags_1);
  20362. var _getNestedBlockTags = interopRequireDefault(getNestedBlockTags_1);
  20363. var _defaultBlockHTML = interopRequireDefault(defaultBlockHTML);
  20364. // import Immutable from 'immutable'; // eslint-disable-line no-unused-vars
  20365. var defaultEntityToHTML = function defaultEntityToHTML(entity, originalText) {
  20366. return originalText;
  20367. };
  20368. var convertToHTML = function convertToHTML(_ref) {
  20369. var _ref$styleToHTML = _ref.styleToHTML,
  20370. styleToHTML = _ref$styleToHTML === void 0 ? {} : _ref$styleToHTML,
  20371. _ref$blockToHTML = _ref.blockToHTML,
  20372. blockToHTML = _ref$blockToHTML === void 0 ? {} : _ref$blockToHTML,
  20373. _ref$entityToHTML = _ref.entityToHTML,
  20374. entityToHTML = _ref$entityToHTML === void 0 ? defaultEntityToHTML : _ref$entityToHTML;
  20375. return function (contentState) {
  20376. (0, _invariant["default"])(contentState !== null && contentState !== undefined, 'Expected contentState to be non-null');
  20377. var getBlockHTML;
  20378. if (blockToHTML.__isMiddleware === true) {
  20379. getBlockHTML = blockToHTML((0, _blockTypeObjectFunction["default"])(_defaultBlockHTML["default"]));
  20380. } else {
  20381. getBlockHTML = (0, _accumulateFunction["default"])((0, _blockTypeObjectFunction["default"])(blockToHTML), (0, _blockTypeObjectFunction["default"])(_defaultBlockHTML["default"]));
  20382. }
  20383. var rawState = (0, Draft.convertToRaw)(contentState);
  20384. var listStack = [];
  20385. var result = rawState.blocks.map(function (block) {
  20386. var type = block.type,
  20387. depth = block.depth;
  20388. var closeNestTags = '';
  20389. var openNestTags = '';
  20390. var blockHTMLResult = getBlockHTML(block);
  20391. if (!blockHTMLResult) {
  20392. throw new Error("convertToHTML: missing HTML definition for block with type ".concat(block.type));
  20393. }
  20394. if (!blockHTMLResult.nest) {
  20395. // this block can't be nested, so reset all nesting if necessary
  20396. closeNestTags = listStack.reduceRight(function (string, nestedBlock) {
  20397. return string + (0, _getNestedBlockTags["default"])(getBlockHTML(nestedBlock)).nestEnd;
  20398. }, '');
  20399. listStack = [];
  20400. } else {
  20401. while (depth + 1 !== listStack.length || type !== listStack[depth].type) {
  20402. if (depth + 1 === listStack.length) {
  20403. // depth is right but doesn't match type
  20404. var blockToClose = listStack[depth];
  20405. closeNestTags += (0, _getNestedBlockTags["default"])(getBlockHTML(blockToClose)).nestEnd;
  20406. openNestTags += (0, _getNestedBlockTags["default"])(getBlockHTML(block)).nestStart;
  20407. listStack[depth] = block;
  20408. } else if (depth + 1 < listStack.length) {
  20409. var _blockToClose = listStack[listStack.length - 1];
  20410. closeNestTags += (0, _getNestedBlockTags["default"])(getBlockHTML(_blockToClose)).nestEnd;
  20411. listStack = listStack.slice(0, -1);
  20412. } else {
  20413. openNestTags += (0, _getNestedBlockTags["default"])(getBlockHTML(block)).nestStart;
  20414. listStack.push(block);
  20415. }
  20416. }
  20417. }
  20418. var innerHTML = (0, _blockInlineStyles["default"])((0, _blockEntities["default"])((0, _encodeBlock["default"])(block), rawState.entityMap, entityToHTML), styleToHTML);
  20419. var blockHTML = (0, _getBlockTags["default"])(getBlockHTML(block));
  20420. var html;
  20421. if (typeof blockHTML === 'string') {
  20422. html = blockHTML;
  20423. } else {
  20424. html = blockHTML.start + innerHTML + blockHTML.end;
  20425. }
  20426. if (innerHTML.length === 0 && Object.prototype.hasOwnProperty.call(blockHTML, 'empty')) {
  20427. if (_react["default"].isValidElement(blockHTML.empty)) {
  20428. html = _server["default"].renderToStaticMarkup(blockHTML.empty);
  20429. } else {
  20430. html = blockHTML.empty;
  20431. }
  20432. }
  20433. return closeNestTags + openNestTags + html;
  20434. }).join('');
  20435. result = listStack.reduce(function (res, nestBlock) {
  20436. return res + (0, _getNestedBlockTags["default"])(getBlockHTML(nestBlock)).nestEnd;
  20437. }, result);
  20438. return result;
  20439. };
  20440. };
  20441. var _default = function _default() {
  20442. for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
  20443. args[_key] = arguments[_key];
  20444. }
  20445. if (args.length === 1 && Object.prototype.hasOwnProperty.call(args[0], '_map') && args[0].getBlockMap != null) {
  20446. // skip higher-order function and use defaults
  20447. return convertToHTML({}).apply(void 0, args);
  20448. }
  20449. return convertToHTML.apply(void 0, args);
  20450. };
  20451. exports["default"] = _default;
  20452. });
  20453. unwrapExports(convertToHTML_1);
  20454. var immutable$2 = createCommonjsModule(function (module, exports) {
  20455. /**
  20456. * Copyright (c) 2014-2015, Facebook, Inc.
  20457. * All rights reserved.
  20458. *
  20459. * This source code is licensed under the BSD-style license found in the
  20460. * LICENSE file in the root directory of this source tree. An additional grant
  20461. * of patent rights can be found in the PATENTS file in the same directory.
  20462. */
  20463. (function (global, factory) {
  20464. module.exports = factory() ;
  20465. }(commonjsGlobal, function () {var SLICE$0 = Array.prototype.slice;
  20466. function createClass(ctor, superClass) {
  20467. if (superClass) {
  20468. ctor.prototype = Object.create(superClass.prototype);
  20469. }
  20470. ctor.prototype.constructor = ctor;
  20471. }
  20472. function Iterable(value) {
  20473. return isIterable(value) ? value : Seq(value);
  20474. }
  20475. createClass(KeyedIterable, Iterable);
  20476. function KeyedIterable(value) {
  20477. return isKeyed(value) ? value : KeyedSeq(value);
  20478. }
  20479. createClass(IndexedIterable, Iterable);
  20480. function IndexedIterable(value) {
  20481. return isIndexed(value) ? value : IndexedSeq(value);
  20482. }
  20483. createClass(SetIterable, Iterable);
  20484. function SetIterable(value) {
  20485. return isIterable(value) && !isAssociative(value) ? value : SetSeq(value);
  20486. }
  20487. function isIterable(maybeIterable) {
  20488. return !!(maybeIterable && maybeIterable[IS_ITERABLE_SENTINEL]);
  20489. }
  20490. function isKeyed(maybeKeyed) {
  20491. return !!(maybeKeyed && maybeKeyed[IS_KEYED_SENTINEL]);
  20492. }
  20493. function isIndexed(maybeIndexed) {
  20494. return !!(maybeIndexed && maybeIndexed[IS_INDEXED_SENTINEL]);
  20495. }
  20496. function isAssociative(maybeAssociative) {
  20497. return isKeyed(maybeAssociative) || isIndexed(maybeAssociative);
  20498. }
  20499. function isOrdered(maybeOrdered) {
  20500. return !!(maybeOrdered && maybeOrdered[IS_ORDERED_SENTINEL]);
  20501. }
  20502. Iterable.isIterable = isIterable;
  20503. Iterable.isKeyed = isKeyed;
  20504. Iterable.isIndexed = isIndexed;
  20505. Iterable.isAssociative = isAssociative;
  20506. Iterable.isOrdered = isOrdered;
  20507. Iterable.Keyed = KeyedIterable;
  20508. Iterable.Indexed = IndexedIterable;
  20509. Iterable.Set = SetIterable;
  20510. var IS_ITERABLE_SENTINEL = '@@__IMMUTABLE_ITERABLE__@@';
  20511. var IS_KEYED_SENTINEL = '@@__IMMUTABLE_KEYED__@@';
  20512. var IS_INDEXED_SENTINEL = '@@__IMMUTABLE_INDEXED__@@';
  20513. var IS_ORDERED_SENTINEL = '@@__IMMUTABLE_ORDERED__@@';
  20514. // Used for setting prototype methods that IE8 chokes on.
  20515. var DELETE = 'delete';
  20516. // Constants describing the size of trie nodes.
  20517. var SHIFT = 5; // Resulted in best performance after ______?
  20518. var SIZE = 1 << SHIFT;
  20519. var MASK = SIZE - 1;
  20520. // A consistent shared value representing "not set" which equals nothing other
  20521. // than itself, and nothing that could be provided externally.
  20522. var NOT_SET = {};
  20523. // Boolean references, Rough equivalent of `bool &`.
  20524. var CHANGE_LENGTH = { value: false };
  20525. var DID_ALTER = { value: false };
  20526. function MakeRef(ref) {
  20527. ref.value = false;
  20528. return ref;
  20529. }
  20530. function SetRef(ref) {
  20531. ref && (ref.value = true);
  20532. }
  20533. // A function which returns a value representing an "owner" for transient writes
  20534. // to tries. The return value will only ever equal itself, and will not equal
  20535. // the return of any subsequent call of this function.
  20536. function OwnerID() {}
  20537. // http://jsperf.com/copy-array-inline
  20538. function arrCopy(arr, offset) {
  20539. offset = offset || 0;
  20540. var len = Math.max(0, arr.length - offset);
  20541. var newArr = new Array(len);
  20542. for (var ii = 0; ii < len; ii++) {
  20543. newArr[ii] = arr[ii + offset];
  20544. }
  20545. return newArr;
  20546. }
  20547. function ensureSize(iter) {
  20548. if (iter.size === undefined) {
  20549. iter.size = iter.__iterate(returnTrue);
  20550. }
  20551. return iter.size;
  20552. }
  20553. function wrapIndex(iter, index) {
  20554. // This implements "is array index" which the ECMAString spec defines as:
  20555. //
  20556. // A String property name P is an array index if and only if
  20557. // ToString(ToUint32(P)) is equal to P and ToUint32(P) is not equal
  20558. // to 2^32−1.
  20559. //
  20560. // http://www.ecma-international.org/ecma-262/6.0/#sec-array-exotic-objects
  20561. if (typeof index !== 'number') {
  20562. var uint32Index = index >>> 0; // N >>> 0 is shorthand for ToUint32
  20563. if ('' + uint32Index !== index || uint32Index === 4294967295) {
  20564. return NaN;
  20565. }
  20566. index = uint32Index;
  20567. }
  20568. return index < 0 ? ensureSize(iter) + index : index;
  20569. }
  20570. function returnTrue() {
  20571. return true;
  20572. }
  20573. function wholeSlice(begin, end, size) {
  20574. return (begin === 0 || (size !== undefined && begin <= -size)) &&
  20575. (end === undefined || (size !== undefined && end >= size));
  20576. }
  20577. function resolveBegin(begin, size) {
  20578. return resolveIndex(begin, size, 0);
  20579. }
  20580. function resolveEnd(end, size) {
  20581. return resolveIndex(end, size, size);
  20582. }
  20583. function resolveIndex(index, size, defaultIndex) {
  20584. return index === undefined ?
  20585. defaultIndex :
  20586. index < 0 ?
  20587. Math.max(0, size + index) :
  20588. size === undefined ?
  20589. index :
  20590. Math.min(size, index);
  20591. }
  20592. /* global Symbol */
  20593. var ITERATE_KEYS = 0;
  20594. var ITERATE_VALUES = 1;
  20595. var ITERATE_ENTRIES = 2;
  20596. var REAL_ITERATOR_SYMBOL = typeof Symbol === 'function' && Symbol.iterator;
  20597. var FAUX_ITERATOR_SYMBOL = '@@iterator';
  20598. var ITERATOR_SYMBOL = REAL_ITERATOR_SYMBOL || FAUX_ITERATOR_SYMBOL;
  20599. function Iterator(next) {
  20600. this.next = next;
  20601. }
  20602. Iterator.prototype.toString = function() {
  20603. return '[Iterator]';
  20604. };
  20605. Iterator.KEYS = ITERATE_KEYS;
  20606. Iterator.VALUES = ITERATE_VALUES;
  20607. Iterator.ENTRIES = ITERATE_ENTRIES;
  20608. Iterator.prototype.inspect =
  20609. Iterator.prototype.toSource = function () { return this.toString(); };
  20610. Iterator.prototype[ITERATOR_SYMBOL] = function () {
  20611. return this;
  20612. };
  20613. function iteratorValue(type, k, v, iteratorResult) {
  20614. var value = type === 0 ? k : type === 1 ? v : [k, v];
  20615. iteratorResult ? (iteratorResult.value = value) : (iteratorResult = {
  20616. value: value, done: false
  20617. });
  20618. return iteratorResult;
  20619. }
  20620. function iteratorDone() {
  20621. return { value: undefined, done: true };
  20622. }
  20623. function hasIterator(maybeIterable) {
  20624. return !!getIteratorFn(maybeIterable);
  20625. }
  20626. function isIterator(maybeIterator) {
  20627. return maybeIterator && typeof maybeIterator.next === 'function';
  20628. }
  20629. function getIterator(iterable) {
  20630. var iteratorFn = getIteratorFn(iterable);
  20631. return iteratorFn && iteratorFn.call(iterable);
  20632. }
  20633. function getIteratorFn(iterable) {
  20634. var iteratorFn = iterable && (
  20635. (REAL_ITERATOR_SYMBOL && iterable[REAL_ITERATOR_SYMBOL]) ||
  20636. iterable[FAUX_ITERATOR_SYMBOL]
  20637. );
  20638. if (typeof iteratorFn === 'function') {
  20639. return iteratorFn;
  20640. }
  20641. }
  20642. function isArrayLike(value) {
  20643. return value && typeof value.length === 'number';
  20644. }
  20645. createClass(Seq, Iterable);
  20646. function Seq(value) {
  20647. return value === null || value === undefined ? emptySequence() :
  20648. isIterable(value) ? value.toSeq() : seqFromValue(value);
  20649. }
  20650. Seq.of = function(/*...values*/) {
  20651. return Seq(arguments);
  20652. };
  20653. Seq.prototype.toSeq = function() {
  20654. return this;
  20655. };
  20656. Seq.prototype.toString = function() {
  20657. return this.__toString('Seq {', '}');
  20658. };
  20659. Seq.prototype.cacheResult = function() {
  20660. if (!this._cache && this.__iterateUncached) {
  20661. this._cache = this.entrySeq().toArray();
  20662. this.size = this._cache.length;
  20663. }
  20664. return this;
  20665. };
  20666. // abstract __iterateUncached(fn, reverse)
  20667. Seq.prototype.__iterate = function(fn, reverse) {
  20668. return seqIterate(this, fn, reverse, true);
  20669. };
  20670. // abstract __iteratorUncached(type, reverse)
  20671. Seq.prototype.__iterator = function(type, reverse) {
  20672. return seqIterator(this, type, reverse, true);
  20673. };
  20674. createClass(KeyedSeq, Seq);
  20675. function KeyedSeq(value) {
  20676. return value === null || value === undefined ?
  20677. emptySequence().toKeyedSeq() :
  20678. isIterable(value) ?
  20679. (isKeyed(value) ? value.toSeq() : value.fromEntrySeq()) :
  20680. keyedSeqFromValue(value);
  20681. }
  20682. KeyedSeq.prototype.toKeyedSeq = function() {
  20683. return this;
  20684. };
  20685. createClass(IndexedSeq, Seq);
  20686. function IndexedSeq(value) {
  20687. return value === null || value === undefined ? emptySequence() :
  20688. !isIterable(value) ? indexedSeqFromValue(value) :
  20689. isKeyed(value) ? value.entrySeq() : value.toIndexedSeq();
  20690. }
  20691. IndexedSeq.of = function(/*...values*/) {
  20692. return IndexedSeq(arguments);
  20693. };
  20694. IndexedSeq.prototype.toIndexedSeq = function() {
  20695. return this;
  20696. };
  20697. IndexedSeq.prototype.toString = function() {
  20698. return this.__toString('Seq [', ']');
  20699. };
  20700. IndexedSeq.prototype.__iterate = function(fn, reverse) {
  20701. return seqIterate(this, fn, reverse, false);
  20702. };
  20703. IndexedSeq.prototype.__iterator = function(type, reverse) {
  20704. return seqIterator(this, type, reverse, false);
  20705. };
  20706. createClass(SetSeq, Seq);
  20707. function SetSeq(value) {
  20708. return (
  20709. value === null || value === undefined ? emptySequence() :
  20710. !isIterable(value) ? indexedSeqFromValue(value) :
  20711. isKeyed(value) ? value.entrySeq() : value
  20712. ).toSetSeq();
  20713. }
  20714. SetSeq.of = function(/*...values*/) {
  20715. return SetSeq(arguments);
  20716. };
  20717. SetSeq.prototype.toSetSeq = function() {
  20718. return this;
  20719. };
  20720. Seq.isSeq = isSeq;
  20721. Seq.Keyed = KeyedSeq;
  20722. Seq.Set = SetSeq;
  20723. Seq.Indexed = IndexedSeq;
  20724. var IS_SEQ_SENTINEL = '@@__IMMUTABLE_SEQ__@@';
  20725. Seq.prototype[IS_SEQ_SENTINEL] = true;
  20726. createClass(ArraySeq, IndexedSeq);
  20727. function ArraySeq(array) {
  20728. this._array = array;
  20729. this.size = array.length;
  20730. }
  20731. ArraySeq.prototype.get = function(index, notSetValue) {
  20732. return this.has(index) ? this._array[wrapIndex(this, index)] : notSetValue;
  20733. };
  20734. ArraySeq.prototype.__iterate = function(fn, reverse) {
  20735. var array = this._array;
  20736. var maxIndex = array.length - 1;
  20737. for (var ii = 0; ii <= maxIndex; ii++) {
  20738. if (fn(array[reverse ? maxIndex - ii : ii], ii, this) === false) {
  20739. return ii + 1;
  20740. }
  20741. }
  20742. return ii;
  20743. };
  20744. ArraySeq.prototype.__iterator = function(type, reverse) {
  20745. var array = this._array;
  20746. var maxIndex = array.length - 1;
  20747. var ii = 0;
  20748. return new Iterator(function()
  20749. {return ii > maxIndex ?
  20750. iteratorDone() :
  20751. iteratorValue(type, ii, array[reverse ? maxIndex - ii++ : ii++])}
  20752. );
  20753. };
  20754. createClass(ObjectSeq, KeyedSeq);
  20755. function ObjectSeq(object) {
  20756. var keys = Object.keys(object);
  20757. this._object = object;
  20758. this._keys = keys;
  20759. this.size = keys.length;
  20760. }
  20761. ObjectSeq.prototype.get = function(key, notSetValue) {
  20762. if (notSetValue !== undefined && !this.has(key)) {
  20763. return notSetValue;
  20764. }
  20765. return this._object[key];
  20766. };
  20767. ObjectSeq.prototype.has = function(key) {
  20768. return this._object.hasOwnProperty(key);
  20769. };
  20770. ObjectSeq.prototype.__iterate = function(fn, reverse) {
  20771. var object = this._object;
  20772. var keys = this._keys;
  20773. var maxIndex = keys.length - 1;
  20774. for (var ii = 0; ii <= maxIndex; ii++) {
  20775. var key = keys[reverse ? maxIndex - ii : ii];
  20776. if (fn(object[key], key, this) === false) {
  20777. return ii + 1;
  20778. }
  20779. }
  20780. return ii;
  20781. };
  20782. ObjectSeq.prototype.__iterator = function(type, reverse) {
  20783. var object = this._object;
  20784. var keys = this._keys;
  20785. var maxIndex = keys.length - 1;
  20786. var ii = 0;
  20787. return new Iterator(function() {
  20788. var key = keys[reverse ? maxIndex - ii : ii];
  20789. return ii++ > maxIndex ?
  20790. iteratorDone() :
  20791. iteratorValue(type, key, object[key]);
  20792. });
  20793. };
  20794. ObjectSeq.prototype[IS_ORDERED_SENTINEL] = true;
  20795. createClass(IterableSeq, IndexedSeq);
  20796. function IterableSeq(iterable) {
  20797. this._iterable = iterable;
  20798. this.size = iterable.length || iterable.size;
  20799. }
  20800. IterableSeq.prototype.__iterateUncached = function(fn, reverse) {
  20801. if (reverse) {
  20802. return this.cacheResult().__iterate(fn, reverse);
  20803. }
  20804. var iterable = this._iterable;
  20805. var iterator = getIterator(iterable);
  20806. var iterations = 0;
  20807. if (isIterator(iterator)) {
  20808. var step;
  20809. while (!(step = iterator.next()).done) {
  20810. if (fn(step.value, iterations++, this) === false) {
  20811. break;
  20812. }
  20813. }
  20814. }
  20815. return iterations;
  20816. };
  20817. IterableSeq.prototype.__iteratorUncached = function(type, reverse) {
  20818. if (reverse) {
  20819. return this.cacheResult().__iterator(type, reverse);
  20820. }
  20821. var iterable = this._iterable;
  20822. var iterator = getIterator(iterable);
  20823. if (!isIterator(iterator)) {
  20824. return new Iterator(iteratorDone);
  20825. }
  20826. var iterations = 0;
  20827. return new Iterator(function() {
  20828. var step = iterator.next();
  20829. return step.done ? step : iteratorValue(type, iterations++, step.value);
  20830. });
  20831. };
  20832. createClass(IteratorSeq, IndexedSeq);
  20833. function IteratorSeq(iterator) {
  20834. this._iterator = iterator;
  20835. this._iteratorCache = [];
  20836. }
  20837. IteratorSeq.prototype.__iterateUncached = function(fn, reverse) {
  20838. if (reverse) {
  20839. return this.cacheResult().__iterate(fn, reverse);
  20840. }
  20841. var iterator = this._iterator;
  20842. var cache = this._iteratorCache;
  20843. var iterations = 0;
  20844. while (iterations < cache.length) {
  20845. if (fn(cache[iterations], iterations++, this) === false) {
  20846. return iterations;
  20847. }
  20848. }
  20849. var step;
  20850. while (!(step = iterator.next()).done) {
  20851. var val = step.value;
  20852. cache[iterations] = val;
  20853. if (fn(val, iterations++, this) === false) {
  20854. break;
  20855. }
  20856. }
  20857. return iterations;
  20858. };
  20859. IteratorSeq.prototype.__iteratorUncached = function(type, reverse) {
  20860. if (reverse) {
  20861. return this.cacheResult().__iterator(type, reverse);
  20862. }
  20863. var iterator = this._iterator;
  20864. var cache = this._iteratorCache;
  20865. var iterations = 0;
  20866. return new Iterator(function() {
  20867. if (iterations >= cache.length) {
  20868. var step = iterator.next();
  20869. if (step.done) {
  20870. return step;
  20871. }
  20872. cache[iterations] = step.value;
  20873. }
  20874. return iteratorValue(type, iterations, cache[iterations++]);
  20875. });
  20876. };
  20877. // # pragma Helper functions
  20878. function isSeq(maybeSeq) {
  20879. return !!(maybeSeq && maybeSeq[IS_SEQ_SENTINEL]);
  20880. }
  20881. var EMPTY_SEQ;
  20882. function emptySequence() {
  20883. return EMPTY_SEQ || (EMPTY_SEQ = new ArraySeq([]));
  20884. }
  20885. function keyedSeqFromValue(value) {
  20886. var seq =
  20887. Array.isArray(value) ? new ArraySeq(value).fromEntrySeq() :
  20888. isIterator(value) ? new IteratorSeq(value).fromEntrySeq() :
  20889. hasIterator(value) ? new IterableSeq(value).fromEntrySeq() :
  20890. typeof value === 'object' ? new ObjectSeq(value) :
  20891. undefined;
  20892. if (!seq) {
  20893. throw new TypeError(
  20894. 'Expected Array or iterable object of [k, v] entries, '+
  20895. 'or keyed object: ' + value
  20896. );
  20897. }
  20898. return seq;
  20899. }
  20900. function indexedSeqFromValue(value) {
  20901. var seq = maybeIndexedSeqFromValue(value);
  20902. if (!seq) {
  20903. throw new TypeError(
  20904. 'Expected Array or iterable object of values: ' + value
  20905. );
  20906. }
  20907. return seq;
  20908. }
  20909. function seqFromValue(value) {
  20910. var seq = maybeIndexedSeqFromValue(value) ||
  20911. (typeof value === 'object' && new ObjectSeq(value));
  20912. if (!seq) {
  20913. throw new TypeError(
  20914. 'Expected Array or iterable object of values, or keyed object: ' + value
  20915. );
  20916. }
  20917. return seq;
  20918. }
  20919. function maybeIndexedSeqFromValue(value) {
  20920. return (
  20921. isArrayLike(value) ? new ArraySeq(value) :
  20922. isIterator(value) ? new IteratorSeq(value) :
  20923. hasIterator(value) ? new IterableSeq(value) :
  20924. undefined
  20925. );
  20926. }
  20927. function seqIterate(seq, fn, reverse, useKeys) {
  20928. var cache = seq._cache;
  20929. if (cache) {
  20930. var maxIndex = cache.length - 1;
  20931. for (var ii = 0; ii <= maxIndex; ii++) {
  20932. var entry = cache[reverse ? maxIndex - ii : ii];
  20933. if (fn(entry[1], useKeys ? entry[0] : ii, seq) === false) {
  20934. return ii + 1;
  20935. }
  20936. }
  20937. return ii;
  20938. }
  20939. return seq.__iterateUncached(fn, reverse);
  20940. }
  20941. function seqIterator(seq, type, reverse, useKeys) {
  20942. var cache = seq._cache;
  20943. if (cache) {
  20944. var maxIndex = cache.length - 1;
  20945. var ii = 0;
  20946. return new Iterator(function() {
  20947. var entry = cache[reverse ? maxIndex - ii : ii];
  20948. return ii++ > maxIndex ?
  20949. iteratorDone() :
  20950. iteratorValue(type, useKeys ? entry[0] : ii - 1, entry[1]);
  20951. });
  20952. }
  20953. return seq.__iteratorUncached(type, reverse);
  20954. }
  20955. function fromJS(json, converter) {
  20956. return converter ?
  20957. fromJSWith(converter, json, '', {'': json}) :
  20958. fromJSDefault(json);
  20959. }
  20960. function fromJSWith(converter, json, key, parentJSON) {
  20961. if (Array.isArray(json)) {
  20962. return converter.call(parentJSON, key, IndexedSeq(json).map(function(v, k) {return fromJSWith(converter, v, k, json)}));
  20963. }
  20964. if (isPlainObj(json)) {
  20965. return converter.call(parentJSON, key, KeyedSeq(json).map(function(v, k) {return fromJSWith(converter, v, k, json)}));
  20966. }
  20967. return json;
  20968. }
  20969. function fromJSDefault(json) {
  20970. if (Array.isArray(json)) {
  20971. return IndexedSeq(json).map(fromJSDefault).toList();
  20972. }
  20973. if (isPlainObj(json)) {
  20974. return KeyedSeq(json).map(fromJSDefault).toMap();
  20975. }
  20976. return json;
  20977. }
  20978. function isPlainObj(value) {
  20979. return value && (value.constructor === Object || value.constructor === undefined);
  20980. }
  20981. /**
  20982. * An extension of the "same-value" algorithm as [described for use by ES6 Map
  20983. * and Set](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map#Key_equality)
  20984. *
  20985. * NaN is considered the same as NaN, however -0 and 0 are considered the same
  20986. * value, which is different from the algorithm described by
  20987. * [`Object.is`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/is).
  20988. *
  20989. * This is extended further to allow Objects to describe the values they
  20990. * represent, by way of `valueOf` or `equals` (and `hashCode`).
  20991. *
  20992. * Note: because of this extension, the key equality of Immutable.Map and the
  20993. * value equality of Immutable.Set will differ from ES6 Map and Set.
  20994. *
  20995. * ### Defining custom values
  20996. *
  20997. * The easiest way to describe the value an object represents is by implementing
  20998. * `valueOf`. For example, `Date` represents a value by returning a unix
  20999. * timestamp for `valueOf`:
  21000. *
  21001. * var date1 = new Date(1234567890000); // Fri Feb 13 2009 ...
  21002. * var date2 = new Date(1234567890000);
  21003. * date1.valueOf(); // 1234567890000
  21004. * assert( date1 !== date2 );
  21005. * assert( Immutable.is( date1, date2 ) );
  21006. *
  21007. * Note: overriding `valueOf` may have other implications if you use this object
  21008. * where JavaScript expects a primitive, such as implicit string coercion.
  21009. *
  21010. * For more complex types, especially collections, implementing `valueOf` may
  21011. * not be performant. An alternative is to implement `equals` and `hashCode`.
  21012. *
  21013. * `equals` takes another object, presumably of similar type, and returns true
  21014. * if the it is equal. Equality is symmetrical, so the same result should be
  21015. * returned if this and the argument are flipped.
  21016. *
  21017. * assert( a.equals(b) === b.equals(a) );
  21018. *
  21019. * `hashCode` returns a 32bit integer number representing the object which will
  21020. * be used to determine how to store the value object in a Map or Set. You must
  21021. * provide both or neither methods, one must not exist without the other.
  21022. *
  21023. * Also, an important relationship between these methods must be upheld: if two
  21024. * values are equal, they *must* return the same hashCode. If the values are not
  21025. * equal, they might have the same hashCode; this is called a hash collision,
  21026. * and while undesirable for performance reasons, it is acceptable.
  21027. *
  21028. * if (a.equals(b)) {
  21029. * assert( a.hashCode() === b.hashCode() );
  21030. * }
  21031. *
  21032. * All Immutable collections implement `equals` and `hashCode`.
  21033. *
  21034. */
  21035. function is(valueA, valueB) {
  21036. if (valueA === valueB || (valueA !== valueA && valueB !== valueB)) {
  21037. return true;
  21038. }
  21039. if (!valueA || !valueB) {
  21040. return false;
  21041. }
  21042. if (typeof valueA.valueOf === 'function' &&
  21043. typeof valueB.valueOf === 'function') {
  21044. valueA = valueA.valueOf();
  21045. valueB = valueB.valueOf();
  21046. if (valueA === valueB || (valueA !== valueA && valueB !== valueB)) {
  21047. return true;
  21048. }
  21049. if (!valueA || !valueB) {
  21050. return false;
  21051. }
  21052. }
  21053. if (typeof valueA.equals === 'function' &&
  21054. typeof valueB.equals === 'function' &&
  21055. valueA.equals(valueB)) {
  21056. return true;
  21057. }
  21058. return false;
  21059. }
  21060. function deepEqual(a, b) {
  21061. if (a === b) {
  21062. return true;
  21063. }
  21064. if (
  21065. !isIterable(b) ||
  21066. a.size !== undefined && b.size !== undefined && a.size !== b.size ||
  21067. a.__hash !== undefined && b.__hash !== undefined && a.__hash !== b.__hash ||
  21068. isKeyed(a) !== isKeyed(b) ||
  21069. isIndexed(a) !== isIndexed(b) ||
  21070. isOrdered(a) !== isOrdered(b)
  21071. ) {
  21072. return false;
  21073. }
  21074. if (a.size === 0 && b.size === 0) {
  21075. return true;
  21076. }
  21077. var notAssociative = !isAssociative(a);
  21078. if (isOrdered(a)) {
  21079. var entries = a.entries();
  21080. return b.every(function(v, k) {
  21081. var entry = entries.next().value;
  21082. return entry && is(entry[1], v) && (notAssociative || is(entry[0], k));
  21083. }) && entries.next().done;
  21084. }
  21085. var flipped = false;
  21086. if (a.size === undefined) {
  21087. if (b.size === undefined) {
  21088. if (typeof a.cacheResult === 'function') {
  21089. a.cacheResult();
  21090. }
  21091. } else {
  21092. flipped = true;
  21093. var _ = a;
  21094. a = b;
  21095. b = _;
  21096. }
  21097. }
  21098. var allEqual = true;
  21099. var bSize = b.__iterate(function(v, k) {
  21100. if (notAssociative ? !a.has(v) :
  21101. flipped ? !is(v, a.get(k, NOT_SET)) : !is(a.get(k, NOT_SET), v)) {
  21102. allEqual = false;
  21103. return false;
  21104. }
  21105. });
  21106. return allEqual && a.size === bSize;
  21107. }
  21108. createClass(Repeat, IndexedSeq);
  21109. function Repeat(value, times) {
  21110. if (!(this instanceof Repeat)) {
  21111. return new Repeat(value, times);
  21112. }
  21113. this._value = value;
  21114. this.size = times === undefined ? Infinity : Math.max(0, times);
  21115. if (this.size === 0) {
  21116. if (EMPTY_REPEAT) {
  21117. return EMPTY_REPEAT;
  21118. }
  21119. EMPTY_REPEAT = this;
  21120. }
  21121. }
  21122. Repeat.prototype.toString = function() {
  21123. if (this.size === 0) {
  21124. return 'Repeat []';
  21125. }
  21126. return 'Repeat [ ' + this._value + ' ' + this.size + ' times ]';
  21127. };
  21128. Repeat.prototype.get = function(index, notSetValue) {
  21129. return this.has(index) ? this._value : notSetValue;
  21130. };
  21131. Repeat.prototype.includes = function(searchValue) {
  21132. return is(this._value, searchValue);
  21133. };
  21134. Repeat.prototype.slice = function(begin, end) {
  21135. var size = this.size;
  21136. return wholeSlice(begin, end, size) ? this :
  21137. new Repeat(this._value, resolveEnd(end, size) - resolveBegin(begin, size));
  21138. };
  21139. Repeat.prototype.reverse = function() {
  21140. return this;
  21141. };
  21142. Repeat.prototype.indexOf = function(searchValue) {
  21143. if (is(this._value, searchValue)) {
  21144. return 0;
  21145. }
  21146. return -1;
  21147. };
  21148. Repeat.prototype.lastIndexOf = function(searchValue) {
  21149. if (is(this._value, searchValue)) {
  21150. return this.size;
  21151. }
  21152. return -1;
  21153. };
  21154. Repeat.prototype.__iterate = function(fn, reverse) {
  21155. for (var ii = 0; ii < this.size; ii++) {
  21156. if (fn(this._value, ii, this) === false) {
  21157. return ii + 1;
  21158. }
  21159. }
  21160. return ii;
  21161. };
  21162. Repeat.prototype.__iterator = function(type, reverse) {var this$0 = this;
  21163. var ii = 0;
  21164. return new Iterator(function()
  21165. {return ii < this$0.size ? iteratorValue(type, ii++, this$0._value) : iteratorDone()}
  21166. );
  21167. };
  21168. Repeat.prototype.equals = function(other) {
  21169. return other instanceof Repeat ?
  21170. is(this._value, other._value) :
  21171. deepEqual(other);
  21172. };
  21173. var EMPTY_REPEAT;
  21174. function invariant(condition, error) {
  21175. if (!condition) throw new Error(error);
  21176. }
  21177. createClass(Range, IndexedSeq);
  21178. function Range(start, end, step) {
  21179. if (!(this instanceof Range)) {
  21180. return new Range(start, end, step);
  21181. }
  21182. invariant(step !== 0, 'Cannot step a Range by 0');
  21183. start = start || 0;
  21184. if (end === undefined) {
  21185. end = Infinity;
  21186. }
  21187. step = step === undefined ? 1 : Math.abs(step);
  21188. if (end < start) {
  21189. step = -step;
  21190. }
  21191. this._start = start;
  21192. this._end = end;
  21193. this._step = step;
  21194. this.size = Math.max(0, Math.ceil((end - start) / step - 1) + 1);
  21195. if (this.size === 0) {
  21196. if (EMPTY_RANGE) {
  21197. return EMPTY_RANGE;
  21198. }
  21199. EMPTY_RANGE = this;
  21200. }
  21201. }
  21202. Range.prototype.toString = function() {
  21203. if (this.size === 0) {
  21204. return 'Range []';
  21205. }
  21206. return 'Range [ ' +
  21207. this._start + '...' + this._end +
  21208. (this._step > 1 ? ' by ' + this._step : '') +
  21209. ' ]';
  21210. };
  21211. Range.prototype.get = function(index, notSetValue) {
  21212. return this.has(index) ?
  21213. this._start + wrapIndex(this, index) * this._step :
  21214. notSetValue;
  21215. };
  21216. Range.prototype.includes = function(searchValue) {
  21217. var possibleIndex = (searchValue - this._start) / this._step;
  21218. return possibleIndex >= 0 &&
  21219. possibleIndex < this.size &&
  21220. possibleIndex === Math.floor(possibleIndex);
  21221. };
  21222. Range.prototype.slice = function(begin, end) {
  21223. if (wholeSlice(begin, end, this.size)) {
  21224. return this;
  21225. }
  21226. begin = resolveBegin(begin, this.size);
  21227. end = resolveEnd(end, this.size);
  21228. if (end <= begin) {
  21229. return new Range(0, 0);
  21230. }
  21231. return new Range(this.get(begin, this._end), this.get(end, this._end), this._step);
  21232. };
  21233. Range.prototype.indexOf = function(searchValue) {
  21234. var offsetValue = searchValue - this._start;
  21235. if (offsetValue % this._step === 0) {
  21236. var index = offsetValue / this._step;
  21237. if (index >= 0 && index < this.size) {
  21238. return index
  21239. }
  21240. }
  21241. return -1;
  21242. };
  21243. Range.prototype.lastIndexOf = function(searchValue) {
  21244. return this.indexOf(searchValue);
  21245. };
  21246. Range.prototype.__iterate = function(fn, reverse) {
  21247. var maxIndex = this.size - 1;
  21248. var step = this._step;
  21249. var value = reverse ? this._start + maxIndex * step : this._start;
  21250. for (var ii = 0; ii <= maxIndex; ii++) {
  21251. if (fn(value, ii, this) === false) {
  21252. return ii + 1;
  21253. }
  21254. value += reverse ? -step : step;
  21255. }
  21256. return ii;
  21257. };
  21258. Range.prototype.__iterator = function(type, reverse) {
  21259. var maxIndex = this.size - 1;
  21260. var step = this._step;
  21261. var value = reverse ? this._start + maxIndex * step : this._start;
  21262. var ii = 0;
  21263. return new Iterator(function() {
  21264. var v = value;
  21265. value += reverse ? -step : step;
  21266. return ii > maxIndex ? iteratorDone() : iteratorValue(type, ii++, v);
  21267. });
  21268. };
  21269. Range.prototype.equals = function(other) {
  21270. return other instanceof Range ?
  21271. this._start === other._start &&
  21272. this._end === other._end &&
  21273. this._step === other._step :
  21274. deepEqual(this, other);
  21275. };
  21276. var EMPTY_RANGE;
  21277. createClass(Collection, Iterable);
  21278. function Collection() {
  21279. throw TypeError('Abstract');
  21280. }
  21281. createClass(KeyedCollection, Collection);function KeyedCollection() {}
  21282. createClass(IndexedCollection, Collection);function IndexedCollection() {}
  21283. createClass(SetCollection, Collection);function SetCollection() {}
  21284. Collection.Keyed = KeyedCollection;
  21285. Collection.Indexed = IndexedCollection;
  21286. Collection.Set = SetCollection;
  21287. var imul =
  21288. typeof Math.imul === 'function' && Math.imul(0xffffffff, 2) === -2 ?
  21289. Math.imul :
  21290. function imul(a, b) {
  21291. a = a | 0; // int
  21292. b = b | 0; // int
  21293. var c = a & 0xffff;
  21294. var d = b & 0xffff;
  21295. // Shift by 0 fixes the sign on the high part.
  21296. return (c * d) + ((((a >>> 16) * d + c * (b >>> 16)) << 16) >>> 0) | 0; // int
  21297. };
  21298. // v8 has an optimization for storing 31-bit signed numbers.
  21299. // Values which have either 00 or 11 as the high order bits qualify.
  21300. // This function drops the highest order bit in a signed number, maintaining
  21301. // the sign bit.
  21302. function smi(i32) {
  21303. return ((i32 >>> 1) & 0x40000000) | (i32 & 0xBFFFFFFF);
  21304. }
  21305. function hash(o) {
  21306. if (o === false || o === null || o === undefined) {
  21307. return 0;
  21308. }
  21309. if (typeof o.valueOf === 'function') {
  21310. o = o.valueOf();
  21311. if (o === false || o === null || o === undefined) {
  21312. return 0;
  21313. }
  21314. }
  21315. if (o === true) {
  21316. return 1;
  21317. }
  21318. var type = typeof o;
  21319. if (type === 'number') {
  21320. var h = o | 0;
  21321. if (h !== o) {
  21322. h ^= o * 0xFFFFFFFF;
  21323. }
  21324. while (o > 0xFFFFFFFF) {
  21325. o /= 0xFFFFFFFF;
  21326. h ^= o;
  21327. }
  21328. return smi(h);
  21329. }
  21330. if (type === 'string') {
  21331. return o.length > STRING_HASH_CACHE_MIN_STRLEN ? cachedHashString(o) : hashString(o);
  21332. }
  21333. if (typeof o.hashCode === 'function') {
  21334. return o.hashCode();
  21335. }
  21336. if (type === 'object') {
  21337. return hashJSObj(o);
  21338. }
  21339. if (typeof o.toString === 'function') {
  21340. return hashString(o.toString());
  21341. }
  21342. throw new Error('Value type ' + type + ' cannot be hashed.');
  21343. }
  21344. function cachedHashString(string) {
  21345. var hash = stringHashCache[string];
  21346. if (hash === undefined) {
  21347. hash = hashString(string);
  21348. if (STRING_HASH_CACHE_SIZE === STRING_HASH_CACHE_MAX_SIZE) {
  21349. STRING_HASH_CACHE_SIZE = 0;
  21350. stringHashCache = {};
  21351. }
  21352. STRING_HASH_CACHE_SIZE++;
  21353. stringHashCache[string] = hash;
  21354. }
  21355. return hash;
  21356. }
  21357. // http://jsperf.com/hashing-strings
  21358. function hashString(string) {
  21359. // This is the hash from JVM
  21360. // The hash code for a string is computed as
  21361. // s[0] * 31 ^ (n - 1) + s[1] * 31 ^ (n - 2) + ... + s[n - 1],
  21362. // where s[i] is the ith character of the string and n is the length of
  21363. // the string. We "mod" the result to make it between 0 (inclusive) and 2^31
  21364. // (exclusive) by dropping high bits.
  21365. var hash = 0;
  21366. for (var ii = 0; ii < string.length; ii++) {
  21367. hash = 31 * hash + string.charCodeAt(ii) | 0;
  21368. }
  21369. return smi(hash);
  21370. }
  21371. function hashJSObj(obj) {
  21372. var hash;
  21373. if (usingWeakMap) {
  21374. hash = weakMap.get(obj);
  21375. if (hash !== undefined) {
  21376. return hash;
  21377. }
  21378. }
  21379. hash = obj[UID_HASH_KEY];
  21380. if (hash !== undefined) {
  21381. return hash;
  21382. }
  21383. if (!canDefineProperty) {
  21384. hash = obj.propertyIsEnumerable && obj.propertyIsEnumerable[UID_HASH_KEY];
  21385. if (hash !== undefined) {
  21386. return hash;
  21387. }
  21388. hash = getIENodeHash(obj);
  21389. if (hash !== undefined) {
  21390. return hash;
  21391. }
  21392. }
  21393. hash = ++objHashUID;
  21394. if (objHashUID & 0x40000000) {
  21395. objHashUID = 0;
  21396. }
  21397. if (usingWeakMap) {
  21398. weakMap.set(obj, hash);
  21399. } else if (isExtensible !== undefined && isExtensible(obj) === false) {
  21400. throw new Error('Non-extensible objects are not allowed as keys.');
  21401. } else if (canDefineProperty) {
  21402. Object.defineProperty(obj, UID_HASH_KEY, {
  21403. 'enumerable': false,
  21404. 'configurable': false,
  21405. 'writable': false,
  21406. 'value': hash
  21407. });
  21408. } else if (obj.propertyIsEnumerable !== undefined &&
  21409. obj.propertyIsEnumerable === obj.constructor.prototype.propertyIsEnumerable) {
  21410. // Since we can't define a non-enumerable property on the object
  21411. // we'll hijack one of the less-used non-enumerable properties to
  21412. // save our hash on it. Since this is a function it will not show up in
  21413. // `JSON.stringify` which is what we want.
  21414. obj.propertyIsEnumerable = function() {
  21415. return this.constructor.prototype.propertyIsEnumerable.apply(this, arguments);
  21416. };
  21417. obj.propertyIsEnumerable[UID_HASH_KEY] = hash;
  21418. } else if (obj.nodeType !== undefined) {
  21419. // At this point we couldn't get the IE `uniqueID` to use as a hash
  21420. // and we couldn't use a non-enumerable property to exploit the
  21421. // dontEnum bug so we simply add the `UID_HASH_KEY` on the node
  21422. // itself.
  21423. obj[UID_HASH_KEY] = hash;
  21424. } else {
  21425. throw new Error('Unable to set a non-enumerable property on object.');
  21426. }
  21427. return hash;
  21428. }
  21429. // Get references to ES5 object methods.
  21430. var isExtensible = Object.isExtensible;
  21431. // True if Object.defineProperty works as expected. IE8 fails this test.
  21432. var canDefineProperty = (function() {
  21433. try {
  21434. Object.defineProperty({}, '@', {});
  21435. return true;
  21436. } catch (e) {
  21437. return false;
  21438. }
  21439. }());
  21440. // IE has a `uniqueID` property on DOM nodes. We can construct the hash from it
  21441. // and avoid memory leaks from the IE cloneNode bug.
  21442. function getIENodeHash(node) {
  21443. if (node && node.nodeType > 0) {
  21444. switch (node.nodeType) {
  21445. case 1: // Element
  21446. return node.uniqueID;
  21447. case 9: // Document
  21448. return node.documentElement && node.documentElement.uniqueID;
  21449. }
  21450. }
  21451. }
  21452. // If possible, use a WeakMap.
  21453. var usingWeakMap = typeof WeakMap === 'function';
  21454. var weakMap;
  21455. if (usingWeakMap) {
  21456. weakMap = new WeakMap();
  21457. }
  21458. var objHashUID = 0;
  21459. var UID_HASH_KEY = '__immutablehash__';
  21460. if (typeof Symbol === 'function') {
  21461. UID_HASH_KEY = Symbol(UID_HASH_KEY);
  21462. }
  21463. var STRING_HASH_CACHE_MIN_STRLEN = 16;
  21464. var STRING_HASH_CACHE_MAX_SIZE = 255;
  21465. var STRING_HASH_CACHE_SIZE = 0;
  21466. var stringHashCache = {};
  21467. function assertNotInfinite(size) {
  21468. invariant(
  21469. size !== Infinity,
  21470. 'Cannot perform this action with an infinite size.'
  21471. );
  21472. }
  21473. createClass(Map, KeyedCollection);
  21474. // @pragma Construction
  21475. function Map(value) {
  21476. return value === null || value === undefined ? emptyMap() :
  21477. isMap(value) && !isOrdered(value) ? value :
  21478. emptyMap().withMutations(function(map ) {
  21479. var iter = KeyedIterable(value);
  21480. assertNotInfinite(iter.size);
  21481. iter.forEach(function(v, k) {return map.set(k, v)});
  21482. });
  21483. }
  21484. Map.prototype.toString = function() {
  21485. return this.__toString('Map {', '}');
  21486. };
  21487. // @pragma Access
  21488. Map.prototype.get = function(k, notSetValue) {
  21489. return this._root ?
  21490. this._root.get(0, undefined, k, notSetValue) :
  21491. notSetValue;
  21492. };
  21493. // @pragma Modification
  21494. Map.prototype.set = function(k, v) {
  21495. return updateMap(this, k, v);
  21496. };
  21497. Map.prototype.setIn = function(keyPath, v) {
  21498. return this.updateIn(keyPath, NOT_SET, function() {return v});
  21499. };
  21500. Map.prototype.remove = function(k) {
  21501. return updateMap(this, k, NOT_SET);
  21502. };
  21503. Map.prototype.deleteIn = function(keyPath) {
  21504. return this.updateIn(keyPath, function() {return NOT_SET});
  21505. };
  21506. Map.prototype.update = function(k, notSetValue, updater) {
  21507. return arguments.length === 1 ?
  21508. k(this) :
  21509. this.updateIn([k], notSetValue, updater);
  21510. };
  21511. Map.prototype.updateIn = function(keyPath, notSetValue, updater) {
  21512. if (!updater) {
  21513. updater = notSetValue;
  21514. notSetValue = undefined;
  21515. }
  21516. var updatedValue = updateInDeepMap(
  21517. this,
  21518. forceIterator(keyPath),
  21519. notSetValue,
  21520. updater
  21521. );
  21522. return updatedValue === NOT_SET ? undefined : updatedValue;
  21523. };
  21524. Map.prototype.clear = function() {
  21525. if (this.size === 0) {
  21526. return this;
  21527. }
  21528. if (this.__ownerID) {
  21529. this.size = 0;
  21530. this._root = null;
  21531. this.__hash = undefined;
  21532. this.__altered = true;
  21533. return this;
  21534. }
  21535. return emptyMap();
  21536. };
  21537. // @pragma Composition
  21538. Map.prototype.merge = function(/*...iters*/) {
  21539. return mergeIntoMapWith(this, undefined, arguments);
  21540. };
  21541. Map.prototype.mergeWith = function(merger) {var iters = SLICE$0.call(arguments, 1);
  21542. return mergeIntoMapWith(this, merger, iters);
  21543. };
  21544. Map.prototype.mergeIn = function(keyPath) {var iters = SLICE$0.call(arguments, 1);
  21545. return this.updateIn(
  21546. keyPath,
  21547. emptyMap(),
  21548. function(m ) {return typeof m.merge === 'function' ?
  21549. m.merge.apply(m, iters) :
  21550. iters[iters.length - 1]}
  21551. );
  21552. };
  21553. Map.prototype.mergeDeep = function(/*...iters*/) {
  21554. return mergeIntoMapWith(this, deepMerger, arguments);
  21555. };
  21556. Map.prototype.mergeDeepWith = function(merger) {var iters = SLICE$0.call(arguments, 1);
  21557. return mergeIntoMapWith(this, deepMergerWith(merger), iters);
  21558. };
  21559. Map.prototype.mergeDeepIn = function(keyPath) {var iters = SLICE$0.call(arguments, 1);
  21560. return this.updateIn(
  21561. keyPath,
  21562. emptyMap(),
  21563. function(m ) {return typeof m.mergeDeep === 'function' ?
  21564. m.mergeDeep.apply(m, iters) :
  21565. iters[iters.length - 1]}
  21566. );
  21567. };
  21568. Map.prototype.sort = function(comparator) {
  21569. // Late binding
  21570. return OrderedMap(sortFactory(this, comparator));
  21571. };
  21572. Map.prototype.sortBy = function(mapper, comparator) {
  21573. // Late binding
  21574. return OrderedMap(sortFactory(this, comparator, mapper));
  21575. };
  21576. // @pragma Mutability
  21577. Map.prototype.withMutations = function(fn) {
  21578. var mutable = this.asMutable();
  21579. fn(mutable);
  21580. return mutable.wasAltered() ? mutable.__ensureOwner(this.__ownerID) : this;
  21581. };
  21582. Map.prototype.asMutable = function() {
  21583. return this.__ownerID ? this : this.__ensureOwner(new OwnerID());
  21584. };
  21585. Map.prototype.asImmutable = function() {
  21586. return this.__ensureOwner();
  21587. };
  21588. Map.prototype.wasAltered = function() {
  21589. return this.__altered;
  21590. };
  21591. Map.prototype.__iterator = function(type, reverse) {
  21592. return new MapIterator(this, type, reverse);
  21593. };
  21594. Map.prototype.__iterate = function(fn, reverse) {var this$0 = this;
  21595. var iterations = 0;
  21596. this._root && this._root.iterate(function(entry ) {
  21597. iterations++;
  21598. return fn(entry[1], entry[0], this$0);
  21599. }, reverse);
  21600. return iterations;
  21601. };
  21602. Map.prototype.__ensureOwner = function(ownerID) {
  21603. if (ownerID === this.__ownerID) {
  21604. return this;
  21605. }
  21606. if (!ownerID) {
  21607. this.__ownerID = ownerID;
  21608. this.__altered = false;
  21609. return this;
  21610. }
  21611. return makeMap(this.size, this._root, ownerID, this.__hash);
  21612. };
  21613. function isMap(maybeMap) {
  21614. return !!(maybeMap && maybeMap[IS_MAP_SENTINEL]);
  21615. }
  21616. Map.isMap = isMap;
  21617. var IS_MAP_SENTINEL = '@@__IMMUTABLE_MAP__@@';
  21618. var MapPrototype = Map.prototype;
  21619. MapPrototype[IS_MAP_SENTINEL] = true;
  21620. MapPrototype[DELETE] = MapPrototype.remove;
  21621. MapPrototype.removeIn = MapPrototype.deleteIn;
  21622. // #pragma Trie Nodes
  21623. function ArrayMapNode(ownerID, entries) {
  21624. this.ownerID = ownerID;
  21625. this.entries = entries;
  21626. }
  21627. ArrayMapNode.prototype.get = function(shift, keyHash, key, notSetValue) {
  21628. var entries = this.entries;
  21629. for (var ii = 0, len = entries.length; ii < len; ii++) {
  21630. if (is(key, entries[ii][0])) {
  21631. return entries[ii][1];
  21632. }
  21633. }
  21634. return notSetValue;
  21635. };
  21636. ArrayMapNode.prototype.update = function(ownerID, shift, keyHash, key, value, didChangeSize, didAlter) {
  21637. var removed = value === NOT_SET;
  21638. var entries = this.entries;
  21639. var idx = 0;
  21640. for (var len = entries.length; idx < len; idx++) {
  21641. if (is(key, entries[idx][0])) {
  21642. break;
  21643. }
  21644. }
  21645. var exists = idx < len;
  21646. if (exists ? entries[idx][1] === value : removed) {
  21647. return this;
  21648. }
  21649. SetRef(didAlter);
  21650. (removed || !exists) && SetRef(didChangeSize);
  21651. if (removed && entries.length === 1) {
  21652. return; // undefined
  21653. }
  21654. if (!exists && !removed && entries.length >= MAX_ARRAY_MAP_SIZE) {
  21655. return createNodes(ownerID, entries, key, value);
  21656. }
  21657. var isEditable = ownerID && ownerID === this.ownerID;
  21658. var newEntries = isEditable ? entries : arrCopy(entries);
  21659. if (exists) {
  21660. if (removed) {
  21661. idx === len - 1 ? newEntries.pop() : (newEntries[idx] = newEntries.pop());
  21662. } else {
  21663. newEntries[idx] = [key, value];
  21664. }
  21665. } else {
  21666. newEntries.push([key, value]);
  21667. }
  21668. if (isEditable) {
  21669. this.entries = newEntries;
  21670. return this;
  21671. }
  21672. return new ArrayMapNode(ownerID, newEntries);
  21673. };
  21674. function BitmapIndexedNode(ownerID, bitmap, nodes) {
  21675. this.ownerID = ownerID;
  21676. this.bitmap = bitmap;
  21677. this.nodes = nodes;
  21678. }
  21679. BitmapIndexedNode.prototype.get = function(shift, keyHash, key, notSetValue) {
  21680. if (keyHash === undefined) {
  21681. keyHash = hash(key);
  21682. }
  21683. var bit = (1 << ((shift === 0 ? keyHash : keyHash >>> shift) & MASK));
  21684. var bitmap = this.bitmap;
  21685. return (bitmap & bit) === 0 ? notSetValue :
  21686. this.nodes[popCount(bitmap & (bit - 1))].get(shift + SHIFT, keyHash, key, notSetValue);
  21687. };
  21688. BitmapIndexedNode.prototype.update = function(ownerID, shift, keyHash, key, value, didChangeSize, didAlter) {
  21689. if (keyHash === undefined) {
  21690. keyHash = hash(key);
  21691. }
  21692. var keyHashFrag = (shift === 0 ? keyHash : keyHash >>> shift) & MASK;
  21693. var bit = 1 << keyHashFrag;
  21694. var bitmap = this.bitmap;
  21695. var exists = (bitmap & bit) !== 0;
  21696. if (!exists && value === NOT_SET) {
  21697. return this;
  21698. }
  21699. var idx = popCount(bitmap & (bit - 1));
  21700. var nodes = this.nodes;
  21701. var node = exists ? nodes[idx] : undefined;
  21702. var newNode = updateNode(node, ownerID, shift + SHIFT, keyHash, key, value, didChangeSize, didAlter);
  21703. if (newNode === node) {
  21704. return this;
  21705. }
  21706. if (!exists && newNode && nodes.length >= MAX_BITMAP_INDEXED_SIZE) {
  21707. return expandNodes(ownerID, nodes, bitmap, keyHashFrag, newNode);
  21708. }
  21709. if (exists && !newNode && nodes.length === 2 && isLeafNode(nodes[idx ^ 1])) {
  21710. return nodes[idx ^ 1];
  21711. }
  21712. if (exists && newNode && nodes.length === 1 && isLeafNode(newNode)) {
  21713. return newNode;
  21714. }
  21715. var isEditable = ownerID && ownerID === this.ownerID;
  21716. var newBitmap = exists ? newNode ? bitmap : bitmap ^ bit : bitmap | bit;
  21717. var newNodes = exists ? newNode ?
  21718. setIn(nodes, idx, newNode, isEditable) :
  21719. spliceOut(nodes, idx, isEditable) :
  21720. spliceIn(nodes, idx, newNode, isEditable);
  21721. if (isEditable) {
  21722. this.bitmap = newBitmap;
  21723. this.nodes = newNodes;
  21724. return this;
  21725. }
  21726. return new BitmapIndexedNode(ownerID, newBitmap, newNodes);
  21727. };
  21728. function HashArrayMapNode(ownerID, count, nodes) {
  21729. this.ownerID = ownerID;
  21730. this.count = count;
  21731. this.nodes = nodes;
  21732. }
  21733. HashArrayMapNode.prototype.get = function(shift, keyHash, key, notSetValue) {
  21734. if (keyHash === undefined) {
  21735. keyHash = hash(key);
  21736. }
  21737. var idx = (shift === 0 ? keyHash : keyHash >>> shift) & MASK;
  21738. var node = this.nodes[idx];
  21739. return node ? node.get(shift + SHIFT, keyHash, key, notSetValue) : notSetValue;
  21740. };
  21741. HashArrayMapNode.prototype.update = function(ownerID, shift, keyHash, key, value, didChangeSize, didAlter) {
  21742. if (keyHash === undefined) {
  21743. keyHash = hash(key);
  21744. }
  21745. var idx = (shift === 0 ? keyHash : keyHash >>> shift) & MASK;
  21746. var removed = value === NOT_SET;
  21747. var nodes = this.nodes;
  21748. var node = nodes[idx];
  21749. if (removed && !node) {
  21750. return this;
  21751. }
  21752. var newNode = updateNode(node, ownerID, shift + SHIFT, keyHash, key, value, didChangeSize, didAlter);
  21753. if (newNode === node) {
  21754. return this;
  21755. }
  21756. var newCount = this.count;
  21757. if (!node) {
  21758. newCount++;
  21759. } else if (!newNode) {
  21760. newCount--;
  21761. if (newCount < MIN_HASH_ARRAY_MAP_SIZE) {
  21762. return packNodes(ownerID, nodes, newCount, idx);
  21763. }
  21764. }
  21765. var isEditable = ownerID && ownerID === this.ownerID;
  21766. var newNodes = setIn(nodes, idx, newNode, isEditable);
  21767. if (isEditable) {
  21768. this.count = newCount;
  21769. this.nodes = newNodes;
  21770. return this;
  21771. }
  21772. return new HashArrayMapNode(ownerID, newCount, newNodes);
  21773. };
  21774. function HashCollisionNode(ownerID, keyHash, entries) {
  21775. this.ownerID = ownerID;
  21776. this.keyHash = keyHash;
  21777. this.entries = entries;
  21778. }
  21779. HashCollisionNode.prototype.get = function(shift, keyHash, key, notSetValue) {
  21780. var entries = this.entries;
  21781. for (var ii = 0, len = entries.length; ii < len; ii++) {
  21782. if (is(key, entries[ii][0])) {
  21783. return entries[ii][1];
  21784. }
  21785. }
  21786. return notSetValue;
  21787. };
  21788. HashCollisionNode.prototype.update = function(ownerID, shift, keyHash, key, value, didChangeSize, didAlter) {
  21789. if (keyHash === undefined) {
  21790. keyHash = hash(key);
  21791. }
  21792. var removed = value === NOT_SET;
  21793. if (keyHash !== this.keyHash) {
  21794. if (removed) {
  21795. return this;
  21796. }
  21797. SetRef(didAlter);
  21798. SetRef(didChangeSize);
  21799. return mergeIntoNode(this, ownerID, shift, keyHash, [key, value]);
  21800. }
  21801. var entries = this.entries;
  21802. var idx = 0;
  21803. for (var len = entries.length; idx < len; idx++) {
  21804. if (is(key, entries[idx][0])) {
  21805. break;
  21806. }
  21807. }
  21808. var exists = idx < len;
  21809. if (exists ? entries[idx][1] === value : removed) {
  21810. return this;
  21811. }
  21812. SetRef(didAlter);
  21813. (removed || !exists) && SetRef(didChangeSize);
  21814. if (removed && len === 2) {
  21815. return new ValueNode(ownerID, this.keyHash, entries[idx ^ 1]);
  21816. }
  21817. var isEditable = ownerID && ownerID === this.ownerID;
  21818. var newEntries = isEditable ? entries : arrCopy(entries);
  21819. if (exists) {
  21820. if (removed) {
  21821. idx === len - 1 ? newEntries.pop() : (newEntries[idx] = newEntries.pop());
  21822. } else {
  21823. newEntries[idx] = [key, value];
  21824. }
  21825. } else {
  21826. newEntries.push([key, value]);
  21827. }
  21828. if (isEditable) {
  21829. this.entries = newEntries;
  21830. return this;
  21831. }
  21832. return new HashCollisionNode(ownerID, this.keyHash, newEntries);
  21833. };
  21834. function ValueNode(ownerID, keyHash, entry) {
  21835. this.ownerID = ownerID;
  21836. this.keyHash = keyHash;
  21837. this.entry = entry;
  21838. }
  21839. ValueNode.prototype.get = function(shift, keyHash, key, notSetValue) {
  21840. return is(key, this.entry[0]) ? this.entry[1] : notSetValue;
  21841. };
  21842. ValueNode.prototype.update = function(ownerID, shift, keyHash, key, value, didChangeSize, didAlter) {
  21843. var removed = value === NOT_SET;
  21844. var keyMatch = is(key, this.entry[0]);
  21845. if (keyMatch ? value === this.entry[1] : removed) {
  21846. return this;
  21847. }
  21848. SetRef(didAlter);
  21849. if (removed) {
  21850. SetRef(didChangeSize);
  21851. return; // undefined
  21852. }
  21853. if (keyMatch) {
  21854. if (ownerID && ownerID === this.ownerID) {
  21855. this.entry[1] = value;
  21856. return this;
  21857. }
  21858. return new ValueNode(ownerID, this.keyHash, [key, value]);
  21859. }
  21860. SetRef(didChangeSize);
  21861. return mergeIntoNode(this, ownerID, shift, hash(key), [key, value]);
  21862. };
  21863. // #pragma Iterators
  21864. ArrayMapNode.prototype.iterate =
  21865. HashCollisionNode.prototype.iterate = function (fn, reverse) {
  21866. var entries = this.entries;
  21867. for (var ii = 0, maxIndex = entries.length - 1; ii <= maxIndex; ii++) {
  21868. if (fn(entries[reverse ? maxIndex - ii : ii]) === false) {
  21869. return false;
  21870. }
  21871. }
  21872. };
  21873. BitmapIndexedNode.prototype.iterate =
  21874. HashArrayMapNode.prototype.iterate = function (fn, reverse) {
  21875. var nodes = this.nodes;
  21876. for (var ii = 0, maxIndex = nodes.length - 1; ii <= maxIndex; ii++) {
  21877. var node = nodes[reverse ? maxIndex - ii : ii];
  21878. if (node && node.iterate(fn, reverse) === false) {
  21879. return false;
  21880. }
  21881. }
  21882. };
  21883. ValueNode.prototype.iterate = function (fn, reverse) {
  21884. return fn(this.entry);
  21885. };
  21886. createClass(MapIterator, Iterator);
  21887. function MapIterator(map, type, reverse) {
  21888. this._type = type;
  21889. this._reverse = reverse;
  21890. this._stack = map._root && mapIteratorFrame(map._root);
  21891. }
  21892. MapIterator.prototype.next = function() {
  21893. var type = this._type;
  21894. var stack = this._stack;
  21895. while (stack) {
  21896. var node = stack.node;
  21897. var index = stack.index++;
  21898. var maxIndex;
  21899. if (node.entry) {
  21900. if (index === 0) {
  21901. return mapIteratorValue(type, node.entry);
  21902. }
  21903. } else if (node.entries) {
  21904. maxIndex = node.entries.length - 1;
  21905. if (index <= maxIndex) {
  21906. return mapIteratorValue(type, node.entries[this._reverse ? maxIndex - index : index]);
  21907. }
  21908. } else {
  21909. maxIndex = node.nodes.length - 1;
  21910. if (index <= maxIndex) {
  21911. var subNode = node.nodes[this._reverse ? maxIndex - index : index];
  21912. if (subNode) {
  21913. if (subNode.entry) {
  21914. return mapIteratorValue(type, subNode.entry);
  21915. }
  21916. stack = this._stack = mapIteratorFrame(subNode, stack);
  21917. }
  21918. continue;
  21919. }
  21920. }
  21921. stack = this._stack = this._stack.__prev;
  21922. }
  21923. return iteratorDone();
  21924. };
  21925. function mapIteratorValue(type, entry) {
  21926. return iteratorValue(type, entry[0], entry[1]);
  21927. }
  21928. function mapIteratorFrame(node, prev) {
  21929. return {
  21930. node: node,
  21931. index: 0,
  21932. __prev: prev
  21933. };
  21934. }
  21935. function makeMap(size, root, ownerID, hash) {
  21936. var map = Object.create(MapPrototype);
  21937. map.size = size;
  21938. map._root = root;
  21939. map.__ownerID = ownerID;
  21940. map.__hash = hash;
  21941. map.__altered = false;
  21942. return map;
  21943. }
  21944. var EMPTY_MAP;
  21945. function emptyMap() {
  21946. return EMPTY_MAP || (EMPTY_MAP = makeMap(0));
  21947. }
  21948. function updateMap(map, k, v) {
  21949. var newRoot;
  21950. var newSize;
  21951. if (!map._root) {
  21952. if (v === NOT_SET) {
  21953. return map;
  21954. }
  21955. newSize = 1;
  21956. newRoot = new ArrayMapNode(map.__ownerID, [[k, v]]);
  21957. } else {
  21958. var didChangeSize = MakeRef(CHANGE_LENGTH);
  21959. var didAlter = MakeRef(DID_ALTER);
  21960. newRoot = updateNode(map._root, map.__ownerID, 0, undefined, k, v, didChangeSize, didAlter);
  21961. if (!didAlter.value) {
  21962. return map;
  21963. }
  21964. newSize = map.size + (didChangeSize.value ? v === NOT_SET ? -1 : 1 : 0);
  21965. }
  21966. if (map.__ownerID) {
  21967. map.size = newSize;
  21968. map._root = newRoot;
  21969. map.__hash = undefined;
  21970. map.__altered = true;
  21971. return map;
  21972. }
  21973. return newRoot ? makeMap(newSize, newRoot) : emptyMap();
  21974. }
  21975. function updateNode(node, ownerID, shift, keyHash, key, value, didChangeSize, didAlter) {
  21976. if (!node) {
  21977. if (value === NOT_SET) {
  21978. return node;
  21979. }
  21980. SetRef(didAlter);
  21981. SetRef(didChangeSize);
  21982. return new ValueNode(ownerID, keyHash, [key, value]);
  21983. }
  21984. return node.update(ownerID, shift, keyHash, key, value, didChangeSize, didAlter);
  21985. }
  21986. function isLeafNode(node) {
  21987. return node.constructor === ValueNode || node.constructor === HashCollisionNode;
  21988. }
  21989. function mergeIntoNode(node, ownerID, shift, keyHash, entry) {
  21990. if (node.keyHash === keyHash) {
  21991. return new HashCollisionNode(ownerID, keyHash, [node.entry, entry]);
  21992. }
  21993. var idx1 = (shift === 0 ? node.keyHash : node.keyHash >>> shift) & MASK;
  21994. var idx2 = (shift === 0 ? keyHash : keyHash >>> shift) & MASK;
  21995. var newNode;
  21996. var nodes = idx1 === idx2 ?
  21997. [mergeIntoNode(node, ownerID, shift + SHIFT, keyHash, entry)] :
  21998. ((newNode = new ValueNode(ownerID, keyHash, entry)), idx1 < idx2 ? [node, newNode] : [newNode, node]);
  21999. return new BitmapIndexedNode(ownerID, (1 << idx1) | (1 << idx2), nodes);
  22000. }
  22001. function createNodes(ownerID, entries, key, value) {
  22002. if (!ownerID) {
  22003. ownerID = new OwnerID();
  22004. }
  22005. var node = new ValueNode(ownerID, hash(key), [key, value]);
  22006. for (var ii = 0; ii < entries.length; ii++) {
  22007. var entry = entries[ii];
  22008. node = node.update(ownerID, 0, undefined, entry[0], entry[1]);
  22009. }
  22010. return node;
  22011. }
  22012. function packNodes(ownerID, nodes, count, excluding) {
  22013. var bitmap = 0;
  22014. var packedII = 0;
  22015. var packedNodes = new Array(count);
  22016. for (var ii = 0, bit = 1, len = nodes.length; ii < len; ii++, bit <<= 1) {
  22017. var node = nodes[ii];
  22018. if (node !== undefined && ii !== excluding) {
  22019. bitmap |= bit;
  22020. packedNodes[packedII++] = node;
  22021. }
  22022. }
  22023. return new BitmapIndexedNode(ownerID, bitmap, packedNodes);
  22024. }
  22025. function expandNodes(ownerID, nodes, bitmap, including, node) {
  22026. var count = 0;
  22027. var expandedNodes = new Array(SIZE);
  22028. for (var ii = 0; bitmap !== 0; ii++, bitmap >>>= 1) {
  22029. expandedNodes[ii] = bitmap & 1 ? nodes[count++] : undefined;
  22030. }
  22031. expandedNodes[including] = node;
  22032. return new HashArrayMapNode(ownerID, count + 1, expandedNodes);
  22033. }
  22034. function mergeIntoMapWith(map, merger, iterables) {
  22035. var iters = [];
  22036. for (var ii = 0; ii < iterables.length; ii++) {
  22037. var value = iterables[ii];
  22038. var iter = KeyedIterable(value);
  22039. if (!isIterable(value)) {
  22040. iter = iter.map(function(v ) {return fromJS(v)});
  22041. }
  22042. iters.push(iter);
  22043. }
  22044. return mergeIntoCollectionWith(map, merger, iters);
  22045. }
  22046. function deepMerger(existing, value, key) {
  22047. return existing && existing.mergeDeep && isIterable(value) ?
  22048. existing.mergeDeep(value) :
  22049. is(existing, value) ? existing : value;
  22050. }
  22051. function deepMergerWith(merger) {
  22052. return function(existing, value, key) {
  22053. if (existing && existing.mergeDeepWith && isIterable(value)) {
  22054. return existing.mergeDeepWith(merger, value);
  22055. }
  22056. var nextValue = merger(existing, value, key);
  22057. return is(existing, nextValue) ? existing : nextValue;
  22058. };
  22059. }
  22060. function mergeIntoCollectionWith(collection, merger, iters) {
  22061. iters = iters.filter(function(x ) {return x.size !== 0});
  22062. if (iters.length === 0) {
  22063. return collection;
  22064. }
  22065. if (collection.size === 0 && !collection.__ownerID && iters.length === 1) {
  22066. return collection.constructor(iters[0]);
  22067. }
  22068. return collection.withMutations(function(collection ) {
  22069. var mergeIntoMap = merger ?
  22070. function(value, key) {
  22071. collection.update(key, NOT_SET, function(existing )
  22072. {return existing === NOT_SET ? value : merger(existing, value, key)}
  22073. );
  22074. } :
  22075. function(value, key) {
  22076. collection.set(key, value);
  22077. };
  22078. for (var ii = 0; ii < iters.length; ii++) {
  22079. iters[ii].forEach(mergeIntoMap);
  22080. }
  22081. });
  22082. }
  22083. function updateInDeepMap(existing, keyPathIter, notSetValue, updater) {
  22084. var isNotSet = existing === NOT_SET;
  22085. var step = keyPathIter.next();
  22086. if (step.done) {
  22087. var existingValue = isNotSet ? notSetValue : existing;
  22088. var newValue = updater(existingValue);
  22089. return newValue === existingValue ? existing : newValue;
  22090. }
  22091. invariant(
  22092. isNotSet || (existing && existing.set),
  22093. 'invalid keyPath'
  22094. );
  22095. var key = step.value;
  22096. var nextExisting = isNotSet ? NOT_SET : existing.get(key, NOT_SET);
  22097. var nextUpdated = updateInDeepMap(
  22098. nextExisting,
  22099. keyPathIter,
  22100. notSetValue,
  22101. updater
  22102. );
  22103. return nextUpdated === nextExisting ? existing :
  22104. nextUpdated === NOT_SET ? existing.remove(key) :
  22105. (isNotSet ? emptyMap() : existing).set(key, nextUpdated);
  22106. }
  22107. function popCount(x) {
  22108. x = x - ((x >> 1) & 0x55555555);
  22109. x = (x & 0x33333333) + ((x >> 2) & 0x33333333);
  22110. x = (x + (x >> 4)) & 0x0f0f0f0f;
  22111. x = x + (x >> 8);
  22112. x = x + (x >> 16);
  22113. return x & 0x7f;
  22114. }
  22115. function setIn(array, idx, val, canEdit) {
  22116. var newArray = canEdit ? array : arrCopy(array);
  22117. newArray[idx] = val;
  22118. return newArray;
  22119. }
  22120. function spliceIn(array, idx, val, canEdit) {
  22121. var newLen = array.length + 1;
  22122. if (canEdit && idx + 1 === newLen) {
  22123. array[idx] = val;
  22124. return array;
  22125. }
  22126. var newArray = new Array(newLen);
  22127. var after = 0;
  22128. for (var ii = 0; ii < newLen; ii++) {
  22129. if (ii === idx) {
  22130. newArray[ii] = val;
  22131. after = -1;
  22132. } else {
  22133. newArray[ii] = array[ii + after];
  22134. }
  22135. }
  22136. return newArray;
  22137. }
  22138. function spliceOut(array, idx, canEdit) {
  22139. var newLen = array.length - 1;
  22140. if (canEdit && idx === newLen) {
  22141. array.pop();
  22142. return array;
  22143. }
  22144. var newArray = new Array(newLen);
  22145. var after = 0;
  22146. for (var ii = 0; ii < newLen; ii++) {
  22147. if (ii === idx) {
  22148. after = 1;
  22149. }
  22150. newArray[ii] = array[ii + after];
  22151. }
  22152. return newArray;
  22153. }
  22154. var MAX_ARRAY_MAP_SIZE = SIZE / 4;
  22155. var MAX_BITMAP_INDEXED_SIZE = SIZE / 2;
  22156. var MIN_HASH_ARRAY_MAP_SIZE = SIZE / 4;
  22157. createClass(List, IndexedCollection);
  22158. // @pragma Construction
  22159. function List(value) {
  22160. var empty = emptyList();
  22161. if (value === null || value === undefined) {
  22162. return empty;
  22163. }
  22164. if (isList(value)) {
  22165. return value;
  22166. }
  22167. var iter = IndexedIterable(value);
  22168. var size = iter.size;
  22169. if (size === 0) {
  22170. return empty;
  22171. }
  22172. assertNotInfinite(size);
  22173. if (size > 0 && size < SIZE) {
  22174. return makeList(0, size, SHIFT, null, new VNode(iter.toArray()));
  22175. }
  22176. return empty.withMutations(function(list ) {
  22177. list.setSize(size);
  22178. iter.forEach(function(v, i) {return list.set(i, v)});
  22179. });
  22180. }
  22181. List.of = function(/*...values*/) {
  22182. return this(arguments);
  22183. };
  22184. List.prototype.toString = function() {
  22185. return this.__toString('List [', ']');
  22186. };
  22187. // @pragma Access
  22188. List.prototype.get = function(index, notSetValue) {
  22189. index = wrapIndex(this, index);
  22190. if (index >= 0 && index < this.size) {
  22191. index += this._origin;
  22192. var node = listNodeFor(this, index);
  22193. return node && node.array[index & MASK];
  22194. }
  22195. return notSetValue;
  22196. };
  22197. // @pragma Modification
  22198. List.prototype.set = function(index, value) {
  22199. return updateList(this, index, value);
  22200. };
  22201. List.prototype.remove = function(index) {
  22202. return !this.has(index) ? this :
  22203. index === 0 ? this.shift() :
  22204. index === this.size - 1 ? this.pop() :
  22205. this.splice(index, 1);
  22206. };
  22207. List.prototype.insert = function(index, value) {
  22208. return this.splice(index, 0, value);
  22209. };
  22210. List.prototype.clear = function() {
  22211. if (this.size === 0) {
  22212. return this;
  22213. }
  22214. if (this.__ownerID) {
  22215. this.size = this._origin = this._capacity = 0;
  22216. this._level = SHIFT;
  22217. this._root = this._tail = null;
  22218. this.__hash = undefined;
  22219. this.__altered = true;
  22220. return this;
  22221. }
  22222. return emptyList();
  22223. };
  22224. List.prototype.push = function(/*...values*/) {
  22225. var values = arguments;
  22226. var oldSize = this.size;
  22227. return this.withMutations(function(list ) {
  22228. setListBounds(list, 0, oldSize + values.length);
  22229. for (var ii = 0; ii < values.length; ii++) {
  22230. list.set(oldSize + ii, values[ii]);
  22231. }
  22232. });
  22233. };
  22234. List.prototype.pop = function() {
  22235. return setListBounds(this, 0, -1);
  22236. };
  22237. List.prototype.unshift = function(/*...values*/) {
  22238. var values = arguments;
  22239. return this.withMutations(function(list ) {
  22240. setListBounds(list, -values.length);
  22241. for (var ii = 0; ii < values.length; ii++) {
  22242. list.set(ii, values[ii]);
  22243. }
  22244. });
  22245. };
  22246. List.prototype.shift = function() {
  22247. return setListBounds(this, 1);
  22248. };
  22249. // @pragma Composition
  22250. List.prototype.merge = function(/*...iters*/) {
  22251. return mergeIntoListWith(this, undefined, arguments);
  22252. };
  22253. List.prototype.mergeWith = function(merger) {var iters = SLICE$0.call(arguments, 1);
  22254. return mergeIntoListWith(this, merger, iters);
  22255. };
  22256. List.prototype.mergeDeep = function(/*...iters*/) {
  22257. return mergeIntoListWith(this, deepMerger, arguments);
  22258. };
  22259. List.prototype.mergeDeepWith = function(merger) {var iters = SLICE$0.call(arguments, 1);
  22260. return mergeIntoListWith(this, deepMergerWith(merger), iters);
  22261. };
  22262. List.prototype.setSize = function(size) {
  22263. return setListBounds(this, 0, size);
  22264. };
  22265. // @pragma Iteration
  22266. List.prototype.slice = function(begin, end) {
  22267. var size = this.size;
  22268. if (wholeSlice(begin, end, size)) {
  22269. return this;
  22270. }
  22271. return setListBounds(
  22272. this,
  22273. resolveBegin(begin, size),
  22274. resolveEnd(end, size)
  22275. );
  22276. };
  22277. List.prototype.__iterator = function(type, reverse) {
  22278. var index = 0;
  22279. var values = iterateList(this, reverse);
  22280. return new Iterator(function() {
  22281. var value = values();
  22282. return value === DONE ?
  22283. iteratorDone() :
  22284. iteratorValue(type, index++, value);
  22285. });
  22286. };
  22287. List.prototype.__iterate = function(fn, reverse) {
  22288. var index = 0;
  22289. var values = iterateList(this, reverse);
  22290. var value;
  22291. while ((value = values()) !== DONE) {
  22292. if (fn(value, index++, this) === false) {
  22293. break;
  22294. }
  22295. }
  22296. return index;
  22297. };
  22298. List.prototype.__ensureOwner = function(ownerID) {
  22299. if (ownerID === this.__ownerID) {
  22300. return this;
  22301. }
  22302. if (!ownerID) {
  22303. this.__ownerID = ownerID;
  22304. return this;
  22305. }
  22306. return makeList(this._origin, this._capacity, this._level, this._root, this._tail, ownerID, this.__hash);
  22307. };
  22308. function isList(maybeList) {
  22309. return !!(maybeList && maybeList[IS_LIST_SENTINEL]);
  22310. }
  22311. List.isList = isList;
  22312. var IS_LIST_SENTINEL = '@@__IMMUTABLE_LIST__@@';
  22313. var ListPrototype = List.prototype;
  22314. ListPrototype[IS_LIST_SENTINEL] = true;
  22315. ListPrototype[DELETE] = ListPrototype.remove;
  22316. ListPrototype.setIn = MapPrototype.setIn;
  22317. ListPrototype.deleteIn =
  22318. ListPrototype.removeIn = MapPrototype.removeIn;
  22319. ListPrototype.update = MapPrototype.update;
  22320. ListPrototype.updateIn = MapPrototype.updateIn;
  22321. ListPrototype.mergeIn = MapPrototype.mergeIn;
  22322. ListPrototype.mergeDeepIn = MapPrototype.mergeDeepIn;
  22323. ListPrototype.withMutations = MapPrototype.withMutations;
  22324. ListPrototype.asMutable = MapPrototype.asMutable;
  22325. ListPrototype.asImmutable = MapPrototype.asImmutable;
  22326. ListPrototype.wasAltered = MapPrototype.wasAltered;
  22327. function VNode(array, ownerID) {
  22328. this.array = array;
  22329. this.ownerID = ownerID;
  22330. }
  22331. // TODO: seems like these methods are very similar
  22332. VNode.prototype.removeBefore = function(ownerID, level, index) {
  22333. if (index === level ? 1 << level : this.array.length === 0) {
  22334. return this;
  22335. }
  22336. var originIndex = (index >>> level) & MASK;
  22337. if (originIndex >= this.array.length) {
  22338. return new VNode([], ownerID);
  22339. }
  22340. var removingFirst = originIndex === 0;
  22341. var newChild;
  22342. if (level > 0) {
  22343. var oldChild = this.array[originIndex];
  22344. newChild = oldChild && oldChild.removeBefore(ownerID, level - SHIFT, index);
  22345. if (newChild === oldChild && removingFirst) {
  22346. return this;
  22347. }
  22348. }
  22349. if (removingFirst && !newChild) {
  22350. return this;
  22351. }
  22352. var editable = editableVNode(this, ownerID);
  22353. if (!removingFirst) {
  22354. for (var ii = 0; ii < originIndex; ii++) {
  22355. editable.array[ii] = undefined;
  22356. }
  22357. }
  22358. if (newChild) {
  22359. editable.array[originIndex] = newChild;
  22360. }
  22361. return editable;
  22362. };
  22363. VNode.prototype.removeAfter = function(ownerID, level, index) {
  22364. if (index === (level ? 1 << level : 0) || this.array.length === 0) {
  22365. return this;
  22366. }
  22367. var sizeIndex = ((index - 1) >>> level) & MASK;
  22368. if (sizeIndex >= this.array.length) {
  22369. return this;
  22370. }
  22371. var newChild;
  22372. if (level > 0) {
  22373. var oldChild = this.array[sizeIndex];
  22374. newChild = oldChild && oldChild.removeAfter(ownerID, level - SHIFT, index);
  22375. if (newChild === oldChild && sizeIndex === this.array.length - 1) {
  22376. return this;
  22377. }
  22378. }
  22379. var editable = editableVNode(this, ownerID);
  22380. editable.array.splice(sizeIndex + 1);
  22381. if (newChild) {
  22382. editable.array[sizeIndex] = newChild;
  22383. }
  22384. return editable;
  22385. };
  22386. var DONE = {};
  22387. function iterateList(list, reverse) {
  22388. var left = list._origin;
  22389. var right = list._capacity;
  22390. var tailPos = getTailOffset(right);
  22391. var tail = list._tail;
  22392. return iterateNodeOrLeaf(list._root, list._level, 0);
  22393. function iterateNodeOrLeaf(node, level, offset) {
  22394. return level === 0 ?
  22395. iterateLeaf(node, offset) :
  22396. iterateNode(node, level, offset);
  22397. }
  22398. function iterateLeaf(node, offset) {
  22399. var array = offset === tailPos ? tail && tail.array : node && node.array;
  22400. var from = offset > left ? 0 : left - offset;
  22401. var to = right - offset;
  22402. if (to > SIZE) {
  22403. to = SIZE;
  22404. }
  22405. return function() {
  22406. if (from === to) {
  22407. return DONE;
  22408. }
  22409. var idx = reverse ? --to : from++;
  22410. return array && array[idx];
  22411. };
  22412. }
  22413. function iterateNode(node, level, offset) {
  22414. var values;
  22415. var array = node && node.array;
  22416. var from = offset > left ? 0 : (left - offset) >> level;
  22417. var to = ((right - offset) >> level) + 1;
  22418. if (to > SIZE) {
  22419. to = SIZE;
  22420. }
  22421. return function() {
  22422. do {
  22423. if (values) {
  22424. var value = values();
  22425. if (value !== DONE) {
  22426. return value;
  22427. }
  22428. values = null;
  22429. }
  22430. if (from === to) {
  22431. return DONE;
  22432. }
  22433. var idx = reverse ? --to : from++;
  22434. values = iterateNodeOrLeaf(
  22435. array && array[idx], level - SHIFT, offset + (idx << level)
  22436. );
  22437. } while (true);
  22438. };
  22439. }
  22440. }
  22441. function makeList(origin, capacity, level, root, tail, ownerID, hash) {
  22442. var list = Object.create(ListPrototype);
  22443. list.size = capacity - origin;
  22444. list._origin = origin;
  22445. list._capacity = capacity;
  22446. list._level = level;
  22447. list._root = root;
  22448. list._tail = tail;
  22449. list.__ownerID = ownerID;
  22450. list.__hash = hash;
  22451. list.__altered = false;
  22452. return list;
  22453. }
  22454. var EMPTY_LIST;
  22455. function emptyList() {
  22456. return EMPTY_LIST || (EMPTY_LIST = makeList(0, 0, SHIFT));
  22457. }
  22458. function updateList(list, index, value) {
  22459. index = wrapIndex(list, index);
  22460. if (index !== index) {
  22461. return list;
  22462. }
  22463. if (index >= list.size || index < 0) {
  22464. return list.withMutations(function(list ) {
  22465. index < 0 ?
  22466. setListBounds(list, index).set(0, value) :
  22467. setListBounds(list, 0, index + 1).set(index, value);
  22468. });
  22469. }
  22470. index += list._origin;
  22471. var newTail = list._tail;
  22472. var newRoot = list._root;
  22473. var didAlter = MakeRef(DID_ALTER);
  22474. if (index >= getTailOffset(list._capacity)) {
  22475. newTail = updateVNode(newTail, list.__ownerID, 0, index, value, didAlter);
  22476. } else {
  22477. newRoot = updateVNode(newRoot, list.__ownerID, list._level, index, value, didAlter);
  22478. }
  22479. if (!didAlter.value) {
  22480. return list;
  22481. }
  22482. if (list.__ownerID) {
  22483. list._root = newRoot;
  22484. list._tail = newTail;
  22485. list.__hash = undefined;
  22486. list.__altered = true;
  22487. return list;
  22488. }
  22489. return makeList(list._origin, list._capacity, list._level, newRoot, newTail);
  22490. }
  22491. function updateVNode(node, ownerID, level, index, value, didAlter) {
  22492. var idx = (index >>> level) & MASK;
  22493. var nodeHas = node && idx < node.array.length;
  22494. if (!nodeHas && value === undefined) {
  22495. return node;
  22496. }
  22497. var newNode;
  22498. if (level > 0) {
  22499. var lowerNode = node && node.array[idx];
  22500. var newLowerNode = updateVNode(lowerNode, ownerID, level - SHIFT, index, value, didAlter);
  22501. if (newLowerNode === lowerNode) {
  22502. return node;
  22503. }
  22504. newNode = editableVNode(node, ownerID);
  22505. newNode.array[idx] = newLowerNode;
  22506. return newNode;
  22507. }
  22508. if (nodeHas && node.array[idx] === value) {
  22509. return node;
  22510. }
  22511. SetRef(didAlter);
  22512. newNode = editableVNode(node, ownerID);
  22513. if (value === undefined && idx === newNode.array.length - 1) {
  22514. newNode.array.pop();
  22515. } else {
  22516. newNode.array[idx] = value;
  22517. }
  22518. return newNode;
  22519. }
  22520. function editableVNode(node, ownerID) {
  22521. if (ownerID && node && ownerID === node.ownerID) {
  22522. return node;
  22523. }
  22524. return new VNode(node ? node.array.slice() : [], ownerID);
  22525. }
  22526. function listNodeFor(list, rawIndex) {
  22527. if (rawIndex >= getTailOffset(list._capacity)) {
  22528. return list._tail;
  22529. }
  22530. if (rawIndex < 1 << (list._level + SHIFT)) {
  22531. var node = list._root;
  22532. var level = list._level;
  22533. while (node && level > 0) {
  22534. node = node.array[(rawIndex >>> level) & MASK];
  22535. level -= SHIFT;
  22536. }
  22537. return node;
  22538. }
  22539. }
  22540. function setListBounds(list, begin, end) {
  22541. // Sanitize begin & end using this shorthand for ToInt32(argument)
  22542. // http://www.ecma-international.org/ecma-262/6.0/#sec-toint32
  22543. if (begin !== undefined) {
  22544. begin = begin | 0;
  22545. }
  22546. if (end !== undefined) {
  22547. end = end | 0;
  22548. }
  22549. var owner = list.__ownerID || new OwnerID();
  22550. var oldOrigin = list._origin;
  22551. var oldCapacity = list._capacity;
  22552. var newOrigin = oldOrigin + begin;
  22553. var newCapacity = end === undefined ? oldCapacity : end < 0 ? oldCapacity + end : oldOrigin + end;
  22554. if (newOrigin === oldOrigin && newCapacity === oldCapacity) {
  22555. return list;
  22556. }
  22557. // If it's going to end after it starts, it's empty.
  22558. if (newOrigin >= newCapacity) {
  22559. return list.clear();
  22560. }
  22561. var newLevel = list._level;
  22562. var newRoot = list._root;
  22563. // New origin might need creating a higher root.
  22564. var offsetShift = 0;
  22565. while (newOrigin + offsetShift < 0) {
  22566. newRoot = new VNode(newRoot && newRoot.array.length ? [undefined, newRoot] : [], owner);
  22567. newLevel += SHIFT;
  22568. offsetShift += 1 << newLevel;
  22569. }
  22570. if (offsetShift) {
  22571. newOrigin += offsetShift;
  22572. oldOrigin += offsetShift;
  22573. newCapacity += offsetShift;
  22574. oldCapacity += offsetShift;
  22575. }
  22576. var oldTailOffset = getTailOffset(oldCapacity);
  22577. var newTailOffset = getTailOffset(newCapacity);
  22578. // New size might need creating a higher root.
  22579. while (newTailOffset >= 1 << (newLevel + SHIFT)) {
  22580. newRoot = new VNode(newRoot && newRoot.array.length ? [newRoot] : [], owner);
  22581. newLevel += SHIFT;
  22582. }
  22583. // Locate or create the new tail.
  22584. var oldTail = list._tail;
  22585. var newTail = newTailOffset < oldTailOffset ?
  22586. listNodeFor(list, newCapacity - 1) :
  22587. newTailOffset > oldTailOffset ? new VNode([], owner) : oldTail;
  22588. // Merge Tail into tree.
  22589. if (oldTail && newTailOffset > oldTailOffset && newOrigin < oldCapacity && oldTail.array.length) {
  22590. newRoot = editableVNode(newRoot, owner);
  22591. var node = newRoot;
  22592. for (var level = newLevel; level > SHIFT; level -= SHIFT) {
  22593. var idx = (oldTailOffset >>> level) & MASK;
  22594. node = node.array[idx] = editableVNode(node.array[idx], owner);
  22595. }
  22596. node.array[(oldTailOffset >>> SHIFT) & MASK] = oldTail;
  22597. }
  22598. // If the size has been reduced, there's a chance the tail needs to be trimmed.
  22599. if (newCapacity < oldCapacity) {
  22600. newTail = newTail && newTail.removeAfter(owner, 0, newCapacity);
  22601. }
  22602. // If the new origin is within the tail, then we do not need a root.
  22603. if (newOrigin >= newTailOffset) {
  22604. newOrigin -= newTailOffset;
  22605. newCapacity -= newTailOffset;
  22606. newLevel = SHIFT;
  22607. newRoot = null;
  22608. newTail = newTail && newTail.removeBefore(owner, 0, newOrigin);
  22609. // Otherwise, if the root has been trimmed, garbage collect.
  22610. } else if (newOrigin > oldOrigin || newTailOffset < oldTailOffset) {
  22611. offsetShift = 0;
  22612. // Identify the new top root node of the subtree of the old root.
  22613. while (newRoot) {
  22614. var beginIndex = (newOrigin >>> newLevel) & MASK;
  22615. if (beginIndex !== (newTailOffset >>> newLevel) & MASK) {
  22616. break;
  22617. }
  22618. if (beginIndex) {
  22619. offsetShift += (1 << newLevel) * beginIndex;
  22620. }
  22621. newLevel -= SHIFT;
  22622. newRoot = newRoot.array[beginIndex];
  22623. }
  22624. // Trim the new sides of the new root.
  22625. if (newRoot && newOrigin > oldOrigin) {
  22626. newRoot = newRoot.removeBefore(owner, newLevel, newOrigin - offsetShift);
  22627. }
  22628. if (newRoot && newTailOffset < oldTailOffset) {
  22629. newRoot = newRoot.removeAfter(owner, newLevel, newTailOffset - offsetShift);
  22630. }
  22631. if (offsetShift) {
  22632. newOrigin -= offsetShift;
  22633. newCapacity -= offsetShift;
  22634. }
  22635. }
  22636. if (list.__ownerID) {
  22637. list.size = newCapacity - newOrigin;
  22638. list._origin = newOrigin;
  22639. list._capacity = newCapacity;
  22640. list._level = newLevel;
  22641. list._root = newRoot;
  22642. list._tail = newTail;
  22643. list.__hash = undefined;
  22644. list.__altered = true;
  22645. return list;
  22646. }
  22647. return makeList(newOrigin, newCapacity, newLevel, newRoot, newTail);
  22648. }
  22649. function mergeIntoListWith(list, merger, iterables) {
  22650. var iters = [];
  22651. var maxSize = 0;
  22652. for (var ii = 0; ii < iterables.length; ii++) {
  22653. var value = iterables[ii];
  22654. var iter = IndexedIterable(value);
  22655. if (iter.size > maxSize) {
  22656. maxSize = iter.size;
  22657. }
  22658. if (!isIterable(value)) {
  22659. iter = iter.map(function(v ) {return fromJS(v)});
  22660. }
  22661. iters.push(iter);
  22662. }
  22663. if (maxSize > list.size) {
  22664. list = list.setSize(maxSize);
  22665. }
  22666. return mergeIntoCollectionWith(list, merger, iters);
  22667. }
  22668. function getTailOffset(size) {
  22669. return size < SIZE ? 0 : (((size - 1) >>> SHIFT) << SHIFT);
  22670. }
  22671. createClass(OrderedMap, Map);
  22672. // @pragma Construction
  22673. function OrderedMap(value) {
  22674. return value === null || value === undefined ? emptyOrderedMap() :
  22675. isOrderedMap(value) ? value :
  22676. emptyOrderedMap().withMutations(function(map ) {
  22677. var iter = KeyedIterable(value);
  22678. assertNotInfinite(iter.size);
  22679. iter.forEach(function(v, k) {return map.set(k, v)});
  22680. });
  22681. }
  22682. OrderedMap.of = function(/*...values*/) {
  22683. return this(arguments);
  22684. };
  22685. OrderedMap.prototype.toString = function() {
  22686. return this.__toString('OrderedMap {', '}');
  22687. };
  22688. // @pragma Access
  22689. OrderedMap.prototype.get = function(k, notSetValue) {
  22690. var index = this._map.get(k);
  22691. return index !== undefined ? this._list.get(index)[1] : notSetValue;
  22692. };
  22693. // @pragma Modification
  22694. OrderedMap.prototype.clear = function() {
  22695. if (this.size === 0) {
  22696. return this;
  22697. }
  22698. if (this.__ownerID) {
  22699. this.size = 0;
  22700. this._map.clear();
  22701. this._list.clear();
  22702. return this;
  22703. }
  22704. return emptyOrderedMap();
  22705. };
  22706. OrderedMap.prototype.set = function(k, v) {
  22707. return updateOrderedMap(this, k, v);
  22708. };
  22709. OrderedMap.prototype.remove = function(k) {
  22710. return updateOrderedMap(this, k, NOT_SET);
  22711. };
  22712. OrderedMap.prototype.wasAltered = function() {
  22713. return this._map.wasAltered() || this._list.wasAltered();
  22714. };
  22715. OrderedMap.prototype.__iterate = function(fn, reverse) {var this$0 = this;
  22716. return this._list.__iterate(
  22717. function(entry ) {return entry && fn(entry[1], entry[0], this$0)},
  22718. reverse
  22719. );
  22720. };
  22721. OrderedMap.prototype.__iterator = function(type, reverse) {
  22722. return this._list.fromEntrySeq().__iterator(type, reverse);
  22723. };
  22724. OrderedMap.prototype.__ensureOwner = function(ownerID) {
  22725. if (ownerID === this.__ownerID) {
  22726. return this;
  22727. }
  22728. var newMap = this._map.__ensureOwner(ownerID);
  22729. var newList = this._list.__ensureOwner(ownerID);
  22730. if (!ownerID) {
  22731. this.__ownerID = ownerID;
  22732. this._map = newMap;
  22733. this._list = newList;
  22734. return this;
  22735. }
  22736. return makeOrderedMap(newMap, newList, ownerID, this.__hash);
  22737. };
  22738. function isOrderedMap(maybeOrderedMap) {
  22739. return isMap(maybeOrderedMap) && isOrdered(maybeOrderedMap);
  22740. }
  22741. OrderedMap.isOrderedMap = isOrderedMap;
  22742. OrderedMap.prototype[IS_ORDERED_SENTINEL] = true;
  22743. OrderedMap.prototype[DELETE] = OrderedMap.prototype.remove;
  22744. function makeOrderedMap(map, list, ownerID, hash) {
  22745. var omap = Object.create(OrderedMap.prototype);
  22746. omap.size = map ? map.size : 0;
  22747. omap._map = map;
  22748. omap._list = list;
  22749. omap.__ownerID = ownerID;
  22750. omap.__hash = hash;
  22751. return omap;
  22752. }
  22753. var EMPTY_ORDERED_MAP;
  22754. function emptyOrderedMap() {
  22755. return EMPTY_ORDERED_MAP || (EMPTY_ORDERED_MAP = makeOrderedMap(emptyMap(), emptyList()));
  22756. }
  22757. function updateOrderedMap(omap, k, v) {
  22758. var map = omap._map;
  22759. var list = omap._list;
  22760. var i = map.get(k);
  22761. var has = i !== undefined;
  22762. var newMap;
  22763. var newList;
  22764. if (v === NOT_SET) { // removed
  22765. if (!has) {
  22766. return omap;
  22767. }
  22768. if (list.size >= SIZE && list.size >= map.size * 2) {
  22769. newList = list.filter(function(entry, idx) {return entry !== undefined && i !== idx});
  22770. newMap = newList.toKeyedSeq().map(function(entry ) {return entry[0]}).flip().toMap();
  22771. if (omap.__ownerID) {
  22772. newMap.__ownerID = newList.__ownerID = omap.__ownerID;
  22773. }
  22774. } else {
  22775. newMap = map.remove(k);
  22776. newList = i === list.size - 1 ? list.pop() : list.set(i, undefined);
  22777. }
  22778. } else {
  22779. if (has) {
  22780. if (v === list.get(i)[1]) {
  22781. return omap;
  22782. }
  22783. newMap = map;
  22784. newList = list.set(i, [k, v]);
  22785. } else {
  22786. newMap = map.set(k, list.size);
  22787. newList = list.set(list.size, [k, v]);
  22788. }
  22789. }
  22790. if (omap.__ownerID) {
  22791. omap.size = newMap.size;
  22792. omap._map = newMap;
  22793. omap._list = newList;
  22794. omap.__hash = undefined;
  22795. return omap;
  22796. }
  22797. return makeOrderedMap(newMap, newList);
  22798. }
  22799. createClass(ToKeyedSequence, KeyedSeq);
  22800. function ToKeyedSequence(indexed, useKeys) {
  22801. this._iter = indexed;
  22802. this._useKeys = useKeys;
  22803. this.size = indexed.size;
  22804. }
  22805. ToKeyedSequence.prototype.get = function(key, notSetValue) {
  22806. return this._iter.get(key, notSetValue);
  22807. };
  22808. ToKeyedSequence.prototype.has = function(key) {
  22809. return this._iter.has(key);
  22810. };
  22811. ToKeyedSequence.prototype.valueSeq = function() {
  22812. return this._iter.valueSeq();
  22813. };
  22814. ToKeyedSequence.prototype.reverse = function() {var this$0 = this;
  22815. var reversedSequence = reverseFactory(this, true);
  22816. if (!this._useKeys) {
  22817. reversedSequence.valueSeq = function() {return this$0._iter.toSeq().reverse()};
  22818. }
  22819. return reversedSequence;
  22820. };
  22821. ToKeyedSequence.prototype.map = function(mapper, context) {var this$0 = this;
  22822. var mappedSequence = mapFactory(this, mapper, context);
  22823. if (!this._useKeys) {
  22824. mappedSequence.valueSeq = function() {return this$0._iter.toSeq().map(mapper, context)};
  22825. }
  22826. return mappedSequence;
  22827. };
  22828. ToKeyedSequence.prototype.__iterate = function(fn, reverse) {var this$0 = this;
  22829. var ii;
  22830. return this._iter.__iterate(
  22831. this._useKeys ?
  22832. function(v, k) {return fn(v, k, this$0)} :
  22833. ((ii = reverse ? resolveSize(this) : 0),
  22834. function(v ) {return fn(v, reverse ? --ii : ii++, this$0)}),
  22835. reverse
  22836. );
  22837. };
  22838. ToKeyedSequence.prototype.__iterator = function(type, reverse) {
  22839. if (this._useKeys) {
  22840. return this._iter.__iterator(type, reverse);
  22841. }
  22842. var iterator = this._iter.__iterator(ITERATE_VALUES, reverse);
  22843. var ii = reverse ? resolveSize(this) : 0;
  22844. return new Iterator(function() {
  22845. var step = iterator.next();
  22846. return step.done ? step :
  22847. iteratorValue(type, reverse ? --ii : ii++, step.value, step);
  22848. });
  22849. };
  22850. ToKeyedSequence.prototype[IS_ORDERED_SENTINEL] = true;
  22851. createClass(ToIndexedSequence, IndexedSeq);
  22852. function ToIndexedSequence(iter) {
  22853. this._iter = iter;
  22854. this.size = iter.size;
  22855. }
  22856. ToIndexedSequence.prototype.includes = function(value) {
  22857. return this._iter.includes(value);
  22858. };
  22859. ToIndexedSequence.prototype.__iterate = function(fn, reverse) {var this$0 = this;
  22860. var iterations = 0;
  22861. return this._iter.__iterate(function(v ) {return fn(v, iterations++, this$0)}, reverse);
  22862. };
  22863. ToIndexedSequence.prototype.__iterator = function(type, reverse) {
  22864. var iterator = this._iter.__iterator(ITERATE_VALUES, reverse);
  22865. var iterations = 0;
  22866. return new Iterator(function() {
  22867. var step = iterator.next();
  22868. return step.done ? step :
  22869. iteratorValue(type, iterations++, step.value, step)
  22870. });
  22871. };
  22872. createClass(ToSetSequence, SetSeq);
  22873. function ToSetSequence(iter) {
  22874. this._iter = iter;
  22875. this.size = iter.size;
  22876. }
  22877. ToSetSequence.prototype.has = function(key) {
  22878. return this._iter.includes(key);
  22879. };
  22880. ToSetSequence.prototype.__iterate = function(fn, reverse) {var this$0 = this;
  22881. return this._iter.__iterate(function(v ) {return fn(v, v, this$0)}, reverse);
  22882. };
  22883. ToSetSequence.prototype.__iterator = function(type, reverse) {
  22884. var iterator = this._iter.__iterator(ITERATE_VALUES, reverse);
  22885. return new Iterator(function() {
  22886. var step = iterator.next();
  22887. return step.done ? step :
  22888. iteratorValue(type, step.value, step.value, step);
  22889. });
  22890. };
  22891. createClass(FromEntriesSequence, KeyedSeq);
  22892. function FromEntriesSequence(entries) {
  22893. this._iter = entries;
  22894. this.size = entries.size;
  22895. }
  22896. FromEntriesSequence.prototype.entrySeq = function() {
  22897. return this._iter.toSeq();
  22898. };
  22899. FromEntriesSequence.prototype.__iterate = function(fn, reverse) {var this$0 = this;
  22900. return this._iter.__iterate(function(entry ) {
  22901. // Check if entry exists first so array access doesn't throw for holes
  22902. // in the parent iteration.
  22903. if (entry) {
  22904. validateEntry(entry);
  22905. var indexedIterable = isIterable(entry);
  22906. return fn(
  22907. indexedIterable ? entry.get(1) : entry[1],
  22908. indexedIterable ? entry.get(0) : entry[0],
  22909. this$0
  22910. );
  22911. }
  22912. }, reverse);
  22913. };
  22914. FromEntriesSequence.prototype.__iterator = function(type, reverse) {
  22915. var iterator = this._iter.__iterator(ITERATE_VALUES, reverse);
  22916. return new Iterator(function() {
  22917. while (true) {
  22918. var step = iterator.next();
  22919. if (step.done) {
  22920. return step;
  22921. }
  22922. var entry = step.value;
  22923. // Check if entry exists first so array access doesn't throw for holes
  22924. // in the parent iteration.
  22925. if (entry) {
  22926. validateEntry(entry);
  22927. var indexedIterable = isIterable(entry);
  22928. return iteratorValue(
  22929. type,
  22930. indexedIterable ? entry.get(0) : entry[0],
  22931. indexedIterable ? entry.get(1) : entry[1],
  22932. step
  22933. );
  22934. }
  22935. }
  22936. });
  22937. };
  22938. ToIndexedSequence.prototype.cacheResult =
  22939. ToKeyedSequence.prototype.cacheResult =
  22940. ToSetSequence.prototype.cacheResult =
  22941. FromEntriesSequence.prototype.cacheResult =
  22942. cacheResultThrough;
  22943. function flipFactory(iterable) {
  22944. var flipSequence = makeSequence(iterable);
  22945. flipSequence._iter = iterable;
  22946. flipSequence.size = iterable.size;
  22947. flipSequence.flip = function() {return iterable};
  22948. flipSequence.reverse = function () {
  22949. var reversedSequence = iterable.reverse.apply(this); // super.reverse()
  22950. reversedSequence.flip = function() {return iterable.reverse()};
  22951. return reversedSequence;
  22952. };
  22953. flipSequence.has = function(key ) {return iterable.includes(key)};
  22954. flipSequence.includes = function(key ) {return iterable.has(key)};
  22955. flipSequence.cacheResult = cacheResultThrough;
  22956. flipSequence.__iterateUncached = function (fn, reverse) {var this$0 = this;
  22957. return iterable.__iterate(function(v, k) {return fn(k, v, this$0) !== false}, reverse);
  22958. };
  22959. flipSequence.__iteratorUncached = function(type, reverse) {
  22960. if (type === ITERATE_ENTRIES) {
  22961. var iterator = iterable.__iterator(type, reverse);
  22962. return new Iterator(function() {
  22963. var step = iterator.next();
  22964. if (!step.done) {
  22965. var k = step.value[0];
  22966. step.value[0] = step.value[1];
  22967. step.value[1] = k;
  22968. }
  22969. return step;
  22970. });
  22971. }
  22972. return iterable.__iterator(
  22973. type === ITERATE_VALUES ? ITERATE_KEYS : ITERATE_VALUES,
  22974. reverse
  22975. );
  22976. };
  22977. return flipSequence;
  22978. }
  22979. function mapFactory(iterable, mapper, context) {
  22980. var mappedSequence = makeSequence(iterable);
  22981. mappedSequence.size = iterable.size;
  22982. mappedSequence.has = function(key ) {return iterable.has(key)};
  22983. mappedSequence.get = function(key, notSetValue) {
  22984. var v = iterable.get(key, NOT_SET);
  22985. return v === NOT_SET ?
  22986. notSetValue :
  22987. mapper.call(context, v, key, iterable);
  22988. };
  22989. mappedSequence.__iterateUncached = function (fn, reverse) {var this$0 = this;
  22990. return iterable.__iterate(
  22991. function(v, k, c) {return fn(mapper.call(context, v, k, c), k, this$0) !== false},
  22992. reverse
  22993. );
  22994. };
  22995. mappedSequence.__iteratorUncached = function (type, reverse) {
  22996. var iterator = iterable.__iterator(ITERATE_ENTRIES, reverse);
  22997. return new Iterator(function() {
  22998. var step = iterator.next();
  22999. if (step.done) {
  23000. return step;
  23001. }
  23002. var entry = step.value;
  23003. var key = entry[0];
  23004. return iteratorValue(
  23005. type,
  23006. key,
  23007. mapper.call(context, entry[1], key, iterable),
  23008. step
  23009. );
  23010. });
  23011. };
  23012. return mappedSequence;
  23013. }
  23014. function reverseFactory(iterable, useKeys) {
  23015. var reversedSequence = makeSequence(iterable);
  23016. reversedSequence._iter = iterable;
  23017. reversedSequence.size = iterable.size;
  23018. reversedSequence.reverse = function() {return iterable};
  23019. if (iterable.flip) {
  23020. reversedSequence.flip = function () {
  23021. var flipSequence = flipFactory(iterable);
  23022. flipSequence.reverse = function() {return iterable.flip()};
  23023. return flipSequence;
  23024. };
  23025. }
  23026. reversedSequence.get = function(key, notSetValue)
  23027. {return iterable.get(useKeys ? key : -1 - key, notSetValue)};
  23028. reversedSequence.has = function(key )
  23029. {return iterable.has(useKeys ? key : -1 - key)};
  23030. reversedSequence.includes = function(value ) {return iterable.includes(value)};
  23031. reversedSequence.cacheResult = cacheResultThrough;
  23032. reversedSequence.__iterate = function (fn, reverse) {var this$0 = this;
  23033. return iterable.__iterate(function(v, k) {return fn(v, k, this$0)}, !reverse);
  23034. };
  23035. reversedSequence.__iterator =
  23036. function(type, reverse) {return iterable.__iterator(type, !reverse)};
  23037. return reversedSequence;
  23038. }
  23039. function filterFactory(iterable, predicate, context, useKeys) {
  23040. var filterSequence = makeSequence(iterable);
  23041. if (useKeys) {
  23042. filterSequence.has = function(key ) {
  23043. var v = iterable.get(key, NOT_SET);
  23044. return v !== NOT_SET && !!predicate.call(context, v, key, iterable);
  23045. };
  23046. filterSequence.get = function(key, notSetValue) {
  23047. var v = iterable.get(key, NOT_SET);
  23048. return v !== NOT_SET && predicate.call(context, v, key, iterable) ?
  23049. v : notSetValue;
  23050. };
  23051. }
  23052. filterSequence.__iterateUncached = function (fn, reverse) {var this$0 = this;
  23053. var iterations = 0;
  23054. iterable.__iterate(function(v, k, c) {
  23055. if (predicate.call(context, v, k, c)) {
  23056. iterations++;
  23057. return fn(v, useKeys ? k : iterations - 1, this$0);
  23058. }
  23059. }, reverse);
  23060. return iterations;
  23061. };
  23062. filterSequence.__iteratorUncached = function (type, reverse) {
  23063. var iterator = iterable.__iterator(ITERATE_ENTRIES, reverse);
  23064. var iterations = 0;
  23065. return new Iterator(function() {
  23066. while (true) {
  23067. var step = iterator.next();
  23068. if (step.done) {
  23069. return step;
  23070. }
  23071. var entry = step.value;
  23072. var key = entry[0];
  23073. var value = entry[1];
  23074. if (predicate.call(context, value, key, iterable)) {
  23075. return iteratorValue(type, useKeys ? key : iterations++, value, step);
  23076. }
  23077. }
  23078. });
  23079. };
  23080. return filterSequence;
  23081. }
  23082. function countByFactory(iterable, grouper, context) {
  23083. var groups = Map().asMutable();
  23084. iterable.__iterate(function(v, k) {
  23085. groups.update(
  23086. grouper.call(context, v, k, iterable),
  23087. 0,
  23088. function(a ) {return a + 1}
  23089. );
  23090. });
  23091. return groups.asImmutable();
  23092. }
  23093. function groupByFactory(iterable, grouper, context) {
  23094. var isKeyedIter = isKeyed(iterable);
  23095. var groups = (isOrdered(iterable) ? OrderedMap() : Map()).asMutable();
  23096. iterable.__iterate(function(v, k) {
  23097. groups.update(
  23098. grouper.call(context, v, k, iterable),
  23099. function(a ) {return (a = a || [], a.push(isKeyedIter ? [k, v] : v), a)}
  23100. );
  23101. });
  23102. var coerce = iterableClass(iterable);
  23103. return groups.map(function(arr ) {return reify(iterable, coerce(arr))});
  23104. }
  23105. function sliceFactory(iterable, begin, end, useKeys) {
  23106. var originalSize = iterable.size;
  23107. // Sanitize begin & end using this shorthand for ToInt32(argument)
  23108. // http://www.ecma-international.org/ecma-262/6.0/#sec-toint32
  23109. if (begin !== undefined) {
  23110. begin = begin | 0;
  23111. }
  23112. if (end !== undefined) {
  23113. end = end | 0;
  23114. }
  23115. if (wholeSlice(begin, end, originalSize)) {
  23116. return iterable;
  23117. }
  23118. var resolvedBegin = resolveBegin(begin, originalSize);
  23119. var resolvedEnd = resolveEnd(end, originalSize);
  23120. // begin or end will be NaN if they were provided as negative numbers and
  23121. // this iterable's size is unknown. In that case, cache first so there is
  23122. // a known size and these do not resolve to NaN.
  23123. if (resolvedBegin !== resolvedBegin || resolvedEnd !== resolvedEnd) {
  23124. return sliceFactory(iterable.toSeq().cacheResult(), begin, end, useKeys);
  23125. }
  23126. // Note: resolvedEnd is undefined when the original sequence's length is
  23127. // unknown and this slice did not supply an end and should contain all
  23128. // elements after resolvedBegin.
  23129. // In that case, resolvedSize will be NaN and sliceSize will remain undefined.
  23130. var resolvedSize = resolvedEnd - resolvedBegin;
  23131. var sliceSize;
  23132. if (resolvedSize === resolvedSize) {
  23133. sliceSize = resolvedSize < 0 ? 0 : resolvedSize;
  23134. }
  23135. var sliceSeq = makeSequence(iterable);
  23136. // If iterable.size is undefined, the size of the realized sliceSeq is
  23137. // unknown at this point unless the number of items to slice is 0
  23138. sliceSeq.size = sliceSize === 0 ? sliceSize : iterable.size && sliceSize || undefined;
  23139. if (!useKeys && isSeq(iterable) && sliceSize >= 0) {
  23140. sliceSeq.get = function (index, notSetValue) {
  23141. index = wrapIndex(this, index);
  23142. return index >= 0 && index < sliceSize ?
  23143. iterable.get(index + resolvedBegin, notSetValue) :
  23144. notSetValue;
  23145. };
  23146. }
  23147. sliceSeq.__iterateUncached = function(fn, reverse) {var this$0 = this;
  23148. if (sliceSize === 0) {
  23149. return 0;
  23150. }
  23151. if (reverse) {
  23152. return this.cacheResult().__iterate(fn, reverse);
  23153. }
  23154. var skipped = 0;
  23155. var isSkipping = true;
  23156. var iterations = 0;
  23157. iterable.__iterate(function(v, k) {
  23158. if (!(isSkipping && (isSkipping = skipped++ < resolvedBegin))) {
  23159. iterations++;
  23160. return fn(v, useKeys ? k : iterations - 1, this$0) !== false &&
  23161. iterations !== sliceSize;
  23162. }
  23163. });
  23164. return iterations;
  23165. };
  23166. sliceSeq.__iteratorUncached = function(type, reverse) {
  23167. if (sliceSize !== 0 && reverse) {
  23168. return this.cacheResult().__iterator(type, reverse);
  23169. }
  23170. // Don't bother instantiating parent iterator if taking 0.
  23171. var iterator = sliceSize !== 0 && iterable.__iterator(type, reverse);
  23172. var skipped = 0;
  23173. var iterations = 0;
  23174. return new Iterator(function() {
  23175. while (skipped++ < resolvedBegin) {
  23176. iterator.next();
  23177. }
  23178. if (++iterations > sliceSize) {
  23179. return iteratorDone();
  23180. }
  23181. var step = iterator.next();
  23182. if (useKeys || type === ITERATE_VALUES) {
  23183. return step;
  23184. } else if (type === ITERATE_KEYS) {
  23185. return iteratorValue(type, iterations - 1, undefined, step);
  23186. } else {
  23187. return iteratorValue(type, iterations - 1, step.value[1], step);
  23188. }
  23189. });
  23190. };
  23191. return sliceSeq;
  23192. }
  23193. function takeWhileFactory(iterable, predicate, context) {
  23194. var takeSequence = makeSequence(iterable);
  23195. takeSequence.__iterateUncached = function(fn, reverse) {var this$0 = this;
  23196. if (reverse) {
  23197. return this.cacheResult().__iterate(fn, reverse);
  23198. }
  23199. var iterations = 0;
  23200. iterable.__iterate(function(v, k, c)
  23201. {return predicate.call(context, v, k, c) && ++iterations && fn(v, k, this$0)}
  23202. );
  23203. return iterations;
  23204. };
  23205. takeSequence.__iteratorUncached = function(type, reverse) {var this$0 = this;
  23206. if (reverse) {
  23207. return this.cacheResult().__iterator(type, reverse);
  23208. }
  23209. var iterator = iterable.__iterator(ITERATE_ENTRIES, reverse);
  23210. var iterating = true;
  23211. return new Iterator(function() {
  23212. if (!iterating) {
  23213. return iteratorDone();
  23214. }
  23215. var step = iterator.next();
  23216. if (step.done) {
  23217. return step;
  23218. }
  23219. var entry = step.value;
  23220. var k = entry[0];
  23221. var v = entry[1];
  23222. if (!predicate.call(context, v, k, this$0)) {
  23223. iterating = false;
  23224. return iteratorDone();
  23225. }
  23226. return type === ITERATE_ENTRIES ? step :
  23227. iteratorValue(type, k, v, step);
  23228. });
  23229. };
  23230. return takeSequence;
  23231. }
  23232. function skipWhileFactory(iterable, predicate, context, useKeys) {
  23233. var skipSequence = makeSequence(iterable);
  23234. skipSequence.__iterateUncached = function (fn, reverse) {var this$0 = this;
  23235. if (reverse) {
  23236. return this.cacheResult().__iterate(fn, reverse);
  23237. }
  23238. var isSkipping = true;
  23239. var iterations = 0;
  23240. iterable.__iterate(function(v, k, c) {
  23241. if (!(isSkipping && (isSkipping = predicate.call(context, v, k, c)))) {
  23242. iterations++;
  23243. return fn(v, useKeys ? k : iterations - 1, this$0);
  23244. }
  23245. });
  23246. return iterations;
  23247. };
  23248. skipSequence.__iteratorUncached = function(type, reverse) {var this$0 = this;
  23249. if (reverse) {
  23250. return this.cacheResult().__iterator(type, reverse);
  23251. }
  23252. var iterator = iterable.__iterator(ITERATE_ENTRIES, reverse);
  23253. var skipping = true;
  23254. var iterations = 0;
  23255. return new Iterator(function() {
  23256. var step, k, v;
  23257. do {
  23258. step = iterator.next();
  23259. if (step.done) {
  23260. if (useKeys || type === ITERATE_VALUES) {
  23261. return step;
  23262. } else if (type === ITERATE_KEYS) {
  23263. return iteratorValue(type, iterations++, undefined, step);
  23264. } else {
  23265. return iteratorValue(type, iterations++, step.value[1], step);
  23266. }
  23267. }
  23268. var entry = step.value;
  23269. k = entry[0];
  23270. v = entry[1];
  23271. skipping && (skipping = predicate.call(context, v, k, this$0));
  23272. } while (skipping);
  23273. return type === ITERATE_ENTRIES ? step :
  23274. iteratorValue(type, k, v, step);
  23275. });
  23276. };
  23277. return skipSequence;
  23278. }
  23279. function concatFactory(iterable, values) {
  23280. var isKeyedIterable = isKeyed(iterable);
  23281. var iters = [iterable].concat(values).map(function(v ) {
  23282. if (!isIterable(v)) {
  23283. v = isKeyedIterable ?
  23284. keyedSeqFromValue(v) :
  23285. indexedSeqFromValue(Array.isArray(v) ? v : [v]);
  23286. } else if (isKeyedIterable) {
  23287. v = KeyedIterable(v);
  23288. }
  23289. return v;
  23290. }).filter(function(v ) {return v.size !== 0});
  23291. if (iters.length === 0) {
  23292. return iterable;
  23293. }
  23294. if (iters.length === 1) {
  23295. var singleton = iters[0];
  23296. if (singleton === iterable ||
  23297. isKeyedIterable && isKeyed(singleton) ||
  23298. isIndexed(iterable) && isIndexed(singleton)) {
  23299. return singleton;
  23300. }
  23301. }
  23302. var concatSeq = new ArraySeq(iters);
  23303. if (isKeyedIterable) {
  23304. concatSeq = concatSeq.toKeyedSeq();
  23305. } else if (!isIndexed(iterable)) {
  23306. concatSeq = concatSeq.toSetSeq();
  23307. }
  23308. concatSeq = concatSeq.flatten(true);
  23309. concatSeq.size = iters.reduce(
  23310. function(sum, seq) {
  23311. if (sum !== undefined) {
  23312. var size = seq.size;
  23313. if (size !== undefined) {
  23314. return sum + size;
  23315. }
  23316. }
  23317. },
  23318. 0
  23319. );
  23320. return concatSeq;
  23321. }
  23322. function flattenFactory(iterable, depth, useKeys) {
  23323. var flatSequence = makeSequence(iterable);
  23324. flatSequence.__iterateUncached = function(fn, reverse) {
  23325. var iterations = 0;
  23326. var stopped = false;
  23327. function flatDeep(iter, currentDepth) {var this$0 = this;
  23328. iter.__iterate(function(v, k) {
  23329. if ((!depth || currentDepth < depth) && isIterable(v)) {
  23330. flatDeep(v, currentDepth + 1);
  23331. } else if (fn(v, useKeys ? k : iterations++, this$0) === false) {
  23332. stopped = true;
  23333. }
  23334. return !stopped;
  23335. }, reverse);
  23336. }
  23337. flatDeep(iterable, 0);
  23338. return iterations;
  23339. };
  23340. flatSequence.__iteratorUncached = function(type, reverse) {
  23341. var iterator = iterable.__iterator(type, reverse);
  23342. var stack = [];
  23343. var iterations = 0;
  23344. return new Iterator(function() {
  23345. while (iterator) {
  23346. var step = iterator.next();
  23347. if (step.done !== false) {
  23348. iterator = stack.pop();
  23349. continue;
  23350. }
  23351. var v = step.value;
  23352. if (type === ITERATE_ENTRIES) {
  23353. v = v[1];
  23354. }
  23355. if ((!depth || stack.length < depth) && isIterable(v)) {
  23356. stack.push(iterator);
  23357. iterator = v.__iterator(type, reverse);
  23358. } else {
  23359. return useKeys ? step : iteratorValue(type, iterations++, v, step);
  23360. }
  23361. }
  23362. return iteratorDone();
  23363. });
  23364. };
  23365. return flatSequence;
  23366. }
  23367. function flatMapFactory(iterable, mapper, context) {
  23368. var coerce = iterableClass(iterable);
  23369. return iterable.toSeq().map(
  23370. function(v, k) {return coerce(mapper.call(context, v, k, iterable))}
  23371. ).flatten(true);
  23372. }
  23373. function interposeFactory(iterable, separator) {
  23374. var interposedSequence = makeSequence(iterable);
  23375. interposedSequence.size = iterable.size && iterable.size * 2 -1;
  23376. interposedSequence.__iterateUncached = function(fn, reverse) {var this$0 = this;
  23377. var iterations = 0;
  23378. iterable.__iterate(function(v, k)
  23379. {return (!iterations || fn(separator, iterations++, this$0) !== false) &&
  23380. fn(v, iterations++, this$0) !== false},
  23381. reverse
  23382. );
  23383. return iterations;
  23384. };
  23385. interposedSequence.__iteratorUncached = function(type, reverse) {
  23386. var iterator = iterable.__iterator(ITERATE_VALUES, reverse);
  23387. var iterations = 0;
  23388. var step;
  23389. return new Iterator(function() {
  23390. if (!step || iterations % 2) {
  23391. step = iterator.next();
  23392. if (step.done) {
  23393. return step;
  23394. }
  23395. }
  23396. return iterations % 2 ?
  23397. iteratorValue(type, iterations++, separator) :
  23398. iteratorValue(type, iterations++, step.value, step);
  23399. });
  23400. };
  23401. return interposedSequence;
  23402. }
  23403. function sortFactory(iterable, comparator, mapper) {
  23404. if (!comparator) {
  23405. comparator = defaultComparator;
  23406. }
  23407. var isKeyedIterable = isKeyed(iterable);
  23408. var index = 0;
  23409. var entries = iterable.toSeq().map(
  23410. function(v, k) {return [k, v, index++, mapper ? mapper(v, k, iterable) : v]}
  23411. ).toArray();
  23412. entries.sort(function(a, b) {return comparator(a[3], b[3]) || a[2] - b[2]}).forEach(
  23413. isKeyedIterable ?
  23414. function(v, i) { entries[i].length = 2; } :
  23415. function(v, i) { entries[i] = v[1]; }
  23416. );
  23417. return isKeyedIterable ? KeyedSeq(entries) :
  23418. isIndexed(iterable) ? IndexedSeq(entries) :
  23419. SetSeq(entries);
  23420. }
  23421. function maxFactory(iterable, comparator, mapper) {
  23422. if (!comparator) {
  23423. comparator = defaultComparator;
  23424. }
  23425. if (mapper) {
  23426. var entry = iterable.toSeq()
  23427. .map(function(v, k) {return [v, mapper(v, k, iterable)]})
  23428. .reduce(function(a, b) {return maxCompare(comparator, a[1], b[1]) ? b : a});
  23429. return entry && entry[0];
  23430. } else {
  23431. return iterable.reduce(function(a, b) {return maxCompare(comparator, a, b) ? b : a});
  23432. }
  23433. }
  23434. function maxCompare(comparator, a, b) {
  23435. var comp = comparator(b, a);
  23436. // b is considered the new max if the comparator declares them equal, but
  23437. // they are not equal and b is in fact a nullish value.
  23438. return (comp === 0 && b !== a && (b === undefined || b === null || b !== b)) || comp > 0;
  23439. }
  23440. function zipWithFactory(keyIter, zipper, iters) {
  23441. var zipSequence = makeSequence(keyIter);
  23442. zipSequence.size = new ArraySeq(iters).map(function(i ) {return i.size}).min();
  23443. // Note: this a generic base implementation of __iterate in terms of
  23444. // __iterator which may be more generically useful in the future.
  23445. zipSequence.__iterate = function(fn, reverse) {
  23446. /* generic:
  23447. var iterator = this.__iterator(ITERATE_ENTRIES, reverse);
  23448. var step;
  23449. var iterations = 0;
  23450. while (!(step = iterator.next()).done) {
  23451. iterations++;
  23452. if (fn(step.value[1], step.value[0], this) === false) {
  23453. break;
  23454. }
  23455. }
  23456. return iterations;
  23457. */
  23458. // indexed:
  23459. var iterator = this.__iterator(ITERATE_VALUES, reverse);
  23460. var step;
  23461. var iterations = 0;
  23462. while (!(step = iterator.next()).done) {
  23463. if (fn(step.value, iterations++, this) === false) {
  23464. break;
  23465. }
  23466. }
  23467. return iterations;
  23468. };
  23469. zipSequence.__iteratorUncached = function(type, reverse) {
  23470. var iterators = iters.map(function(i )
  23471. {return (i = Iterable(i), getIterator(reverse ? i.reverse() : i))}
  23472. );
  23473. var iterations = 0;
  23474. var isDone = false;
  23475. return new Iterator(function() {
  23476. var steps;
  23477. if (!isDone) {
  23478. steps = iterators.map(function(i ) {return i.next()});
  23479. isDone = steps.some(function(s ) {return s.done});
  23480. }
  23481. if (isDone) {
  23482. return iteratorDone();
  23483. }
  23484. return iteratorValue(
  23485. type,
  23486. iterations++,
  23487. zipper.apply(null, steps.map(function(s ) {return s.value}))
  23488. );
  23489. });
  23490. };
  23491. return zipSequence
  23492. }
  23493. // #pragma Helper Functions
  23494. function reify(iter, seq) {
  23495. return isSeq(iter) ? seq : iter.constructor(seq);
  23496. }
  23497. function validateEntry(entry) {
  23498. if (entry !== Object(entry)) {
  23499. throw new TypeError('Expected [K, V] tuple: ' + entry);
  23500. }
  23501. }
  23502. function resolveSize(iter) {
  23503. assertNotInfinite(iter.size);
  23504. return ensureSize(iter);
  23505. }
  23506. function iterableClass(iterable) {
  23507. return isKeyed(iterable) ? KeyedIterable :
  23508. isIndexed(iterable) ? IndexedIterable :
  23509. SetIterable;
  23510. }
  23511. function makeSequence(iterable) {
  23512. return Object.create(
  23513. (
  23514. isKeyed(iterable) ? KeyedSeq :
  23515. isIndexed(iterable) ? IndexedSeq :
  23516. SetSeq
  23517. ).prototype
  23518. );
  23519. }
  23520. function cacheResultThrough() {
  23521. if (this._iter.cacheResult) {
  23522. this._iter.cacheResult();
  23523. this.size = this._iter.size;
  23524. return this;
  23525. } else {
  23526. return Seq.prototype.cacheResult.call(this);
  23527. }
  23528. }
  23529. function defaultComparator(a, b) {
  23530. return a > b ? 1 : a < b ? -1 : 0;
  23531. }
  23532. function forceIterator(keyPath) {
  23533. var iter = getIterator(keyPath);
  23534. if (!iter) {
  23535. // Array might not be iterable in this environment, so we need a fallback
  23536. // to our wrapped type.
  23537. if (!isArrayLike(keyPath)) {
  23538. throw new TypeError('Expected iterable or array-like: ' + keyPath);
  23539. }
  23540. iter = getIterator(Iterable(keyPath));
  23541. }
  23542. return iter;
  23543. }
  23544. createClass(Record, KeyedCollection);
  23545. function Record(defaultValues, name) {
  23546. var hasInitialized;
  23547. var RecordType = function Record(values) {
  23548. if (values instanceof RecordType) {
  23549. return values;
  23550. }
  23551. if (!(this instanceof RecordType)) {
  23552. return new RecordType(values);
  23553. }
  23554. if (!hasInitialized) {
  23555. hasInitialized = true;
  23556. var keys = Object.keys(defaultValues);
  23557. setProps(RecordTypePrototype, keys);
  23558. RecordTypePrototype.size = keys.length;
  23559. RecordTypePrototype._name = name;
  23560. RecordTypePrototype._keys = keys;
  23561. RecordTypePrototype._defaultValues = defaultValues;
  23562. }
  23563. this._map = Map(values);
  23564. };
  23565. var RecordTypePrototype = RecordType.prototype = Object.create(RecordPrototype);
  23566. RecordTypePrototype.constructor = RecordType;
  23567. return RecordType;
  23568. }
  23569. Record.prototype.toString = function() {
  23570. return this.__toString(recordName(this) + ' {', '}');
  23571. };
  23572. // @pragma Access
  23573. Record.prototype.has = function(k) {
  23574. return this._defaultValues.hasOwnProperty(k);
  23575. };
  23576. Record.prototype.get = function(k, notSetValue) {
  23577. if (!this.has(k)) {
  23578. return notSetValue;
  23579. }
  23580. var defaultVal = this._defaultValues[k];
  23581. return this._map ? this._map.get(k, defaultVal) : defaultVal;
  23582. };
  23583. // @pragma Modification
  23584. Record.prototype.clear = function() {
  23585. if (this.__ownerID) {
  23586. this._map && this._map.clear();
  23587. return this;
  23588. }
  23589. var RecordType = this.constructor;
  23590. return RecordType._empty || (RecordType._empty = makeRecord(this, emptyMap()));
  23591. };
  23592. Record.prototype.set = function(k, v) {
  23593. if (!this.has(k)) {
  23594. throw new Error('Cannot set unknown key "' + k + '" on ' + recordName(this));
  23595. }
  23596. var newMap = this._map && this._map.set(k, v);
  23597. if (this.__ownerID || newMap === this._map) {
  23598. return this;
  23599. }
  23600. return makeRecord(this, newMap);
  23601. };
  23602. Record.prototype.remove = function(k) {
  23603. if (!this.has(k)) {
  23604. return this;
  23605. }
  23606. var newMap = this._map && this._map.remove(k);
  23607. if (this.__ownerID || newMap === this._map) {
  23608. return this;
  23609. }
  23610. return makeRecord(this, newMap);
  23611. };
  23612. Record.prototype.wasAltered = function() {
  23613. return this._map.wasAltered();
  23614. };
  23615. Record.prototype.__iterator = function(type, reverse) {var this$0 = this;
  23616. return KeyedIterable(this._defaultValues).map(function(_, k) {return this$0.get(k)}).__iterator(type, reverse);
  23617. };
  23618. Record.prototype.__iterate = function(fn, reverse) {var this$0 = this;
  23619. return KeyedIterable(this._defaultValues).map(function(_, k) {return this$0.get(k)}).__iterate(fn, reverse);
  23620. };
  23621. Record.prototype.__ensureOwner = function(ownerID) {
  23622. if (ownerID === this.__ownerID) {
  23623. return this;
  23624. }
  23625. var newMap = this._map && this._map.__ensureOwner(ownerID);
  23626. if (!ownerID) {
  23627. this.__ownerID = ownerID;
  23628. this._map = newMap;
  23629. return this;
  23630. }
  23631. return makeRecord(this, newMap, ownerID);
  23632. };
  23633. var RecordPrototype = Record.prototype;
  23634. RecordPrototype[DELETE] = RecordPrototype.remove;
  23635. RecordPrototype.deleteIn =
  23636. RecordPrototype.removeIn = MapPrototype.removeIn;
  23637. RecordPrototype.merge = MapPrototype.merge;
  23638. RecordPrototype.mergeWith = MapPrototype.mergeWith;
  23639. RecordPrototype.mergeIn = MapPrototype.mergeIn;
  23640. RecordPrototype.mergeDeep = MapPrototype.mergeDeep;
  23641. RecordPrototype.mergeDeepWith = MapPrototype.mergeDeepWith;
  23642. RecordPrototype.mergeDeepIn = MapPrototype.mergeDeepIn;
  23643. RecordPrototype.setIn = MapPrototype.setIn;
  23644. RecordPrototype.update = MapPrototype.update;
  23645. RecordPrototype.updateIn = MapPrototype.updateIn;
  23646. RecordPrototype.withMutations = MapPrototype.withMutations;
  23647. RecordPrototype.asMutable = MapPrototype.asMutable;
  23648. RecordPrototype.asImmutable = MapPrototype.asImmutable;
  23649. function makeRecord(likeRecord, map, ownerID) {
  23650. var record = Object.create(Object.getPrototypeOf(likeRecord));
  23651. record._map = map;
  23652. record.__ownerID = ownerID;
  23653. return record;
  23654. }
  23655. function recordName(record) {
  23656. return record._name || record.constructor.name || 'Record';
  23657. }
  23658. function setProps(prototype, names) {
  23659. try {
  23660. names.forEach(setProp.bind(undefined, prototype));
  23661. } catch (error) {
  23662. // Object.defineProperty failed. Probably IE8.
  23663. }
  23664. }
  23665. function setProp(prototype, name) {
  23666. Object.defineProperty(prototype, name, {
  23667. get: function() {
  23668. return this.get(name);
  23669. },
  23670. set: function(value) {
  23671. invariant(this.__ownerID, 'Cannot set on an immutable record.');
  23672. this.set(name, value);
  23673. }
  23674. });
  23675. }
  23676. createClass(Set, SetCollection);
  23677. // @pragma Construction
  23678. function Set(value) {
  23679. return value === null || value === undefined ? emptySet() :
  23680. isSet(value) && !isOrdered(value) ? value :
  23681. emptySet().withMutations(function(set ) {
  23682. var iter = SetIterable(value);
  23683. assertNotInfinite(iter.size);
  23684. iter.forEach(function(v ) {return set.add(v)});
  23685. });
  23686. }
  23687. Set.of = function(/*...values*/) {
  23688. return this(arguments);
  23689. };
  23690. Set.fromKeys = function(value) {
  23691. return this(KeyedIterable(value).keySeq());
  23692. };
  23693. Set.prototype.toString = function() {
  23694. return this.__toString('Set {', '}');
  23695. };
  23696. // @pragma Access
  23697. Set.prototype.has = function(value) {
  23698. return this._map.has(value);
  23699. };
  23700. // @pragma Modification
  23701. Set.prototype.add = function(value) {
  23702. return updateSet(this, this._map.set(value, true));
  23703. };
  23704. Set.prototype.remove = function(value) {
  23705. return updateSet(this, this._map.remove(value));
  23706. };
  23707. Set.prototype.clear = function() {
  23708. return updateSet(this, this._map.clear());
  23709. };
  23710. // @pragma Composition
  23711. Set.prototype.union = function() {var iters = SLICE$0.call(arguments, 0);
  23712. iters = iters.filter(function(x ) {return x.size !== 0});
  23713. if (iters.length === 0) {
  23714. return this;
  23715. }
  23716. if (this.size === 0 && !this.__ownerID && iters.length === 1) {
  23717. return this.constructor(iters[0]);
  23718. }
  23719. return this.withMutations(function(set ) {
  23720. for (var ii = 0; ii < iters.length; ii++) {
  23721. SetIterable(iters[ii]).forEach(function(value ) {return set.add(value)});
  23722. }
  23723. });
  23724. };
  23725. Set.prototype.intersect = function() {var iters = SLICE$0.call(arguments, 0);
  23726. if (iters.length === 0) {
  23727. return this;
  23728. }
  23729. iters = iters.map(function(iter ) {return SetIterable(iter)});
  23730. var originalSet = this;
  23731. return this.withMutations(function(set ) {
  23732. originalSet.forEach(function(value ) {
  23733. if (!iters.every(function(iter ) {return iter.includes(value)})) {
  23734. set.remove(value);
  23735. }
  23736. });
  23737. });
  23738. };
  23739. Set.prototype.subtract = function() {var iters = SLICE$0.call(arguments, 0);
  23740. if (iters.length === 0) {
  23741. return this;
  23742. }
  23743. iters = iters.map(function(iter ) {return SetIterable(iter)});
  23744. var originalSet = this;
  23745. return this.withMutations(function(set ) {
  23746. originalSet.forEach(function(value ) {
  23747. if (iters.some(function(iter ) {return iter.includes(value)})) {
  23748. set.remove(value);
  23749. }
  23750. });
  23751. });
  23752. };
  23753. Set.prototype.merge = function() {
  23754. return this.union.apply(this, arguments);
  23755. };
  23756. Set.prototype.mergeWith = function(merger) {var iters = SLICE$0.call(arguments, 1);
  23757. return this.union.apply(this, iters);
  23758. };
  23759. Set.prototype.sort = function(comparator) {
  23760. // Late binding
  23761. return OrderedSet(sortFactory(this, comparator));
  23762. };
  23763. Set.prototype.sortBy = function(mapper, comparator) {
  23764. // Late binding
  23765. return OrderedSet(sortFactory(this, comparator, mapper));
  23766. };
  23767. Set.prototype.wasAltered = function() {
  23768. return this._map.wasAltered();
  23769. };
  23770. Set.prototype.__iterate = function(fn, reverse) {var this$0 = this;
  23771. return this._map.__iterate(function(_, k) {return fn(k, k, this$0)}, reverse);
  23772. };
  23773. Set.prototype.__iterator = function(type, reverse) {
  23774. return this._map.map(function(_, k) {return k}).__iterator(type, reverse);
  23775. };
  23776. Set.prototype.__ensureOwner = function(ownerID) {
  23777. if (ownerID === this.__ownerID) {
  23778. return this;
  23779. }
  23780. var newMap = this._map.__ensureOwner(ownerID);
  23781. if (!ownerID) {
  23782. this.__ownerID = ownerID;
  23783. this._map = newMap;
  23784. return this;
  23785. }
  23786. return this.__make(newMap, ownerID);
  23787. };
  23788. function isSet(maybeSet) {
  23789. return !!(maybeSet && maybeSet[IS_SET_SENTINEL]);
  23790. }
  23791. Set.isSet = isSet;
  23792. var IS_SET_SENTINEL = '@@__IMMUTABLE_SET__@@';
  23793. var SetPrototype = Set.prototype;
  23794. SetPrototype[IS_SET_SENTINEL] = true;
  23795. SetPrototype[DELETE] = SetPrototype.remove;
  23796. SetPrototype.mergeDeep = SetPrototype.merge;
  23797. SetPrototype.mergeDeepWith = SetPrototype.mergeWith;
  23798. SetPrototype.withMutations = MapPrototype.withMutations;
  23799. SetPrototype.asMutable = MapPrototype.asMutable;
  23800. SetPrototype.asImmutable = MapPrototype.asImmutable;
  23801. SetPrototype.__empty = emptySet;
  23802. SetPrototype.__make = makeSet;
  23803. function updateSet(set, newMap) {
  23804. if (set.__ownerID) {
  23805. set.size = newMap.size;
  23806. set._map = newMap;
  23807. return set;
  23808. }
  23809. return newMap === set._map ? set :
  23810. newMap.size === 0 ? set.__empty() :
  23811. set.__make(newMap);
  23812. }
  23813. function makeSet(map, ownerID) {
  23814. var set = Object.create(SetPrototype);
  23815. set.size = map ? map.size : 0;
  23816. set._map = map;
  23817. set.__ownerID = ownerID;
  23818. return set;
  23819. }
  23820. var EMPTY_SET;
  23821. function emptySet() {
  23822. return EMPTY_SET || (EMPTY_SET = makeSet(emptyMap()));
  23823. }
  23824. createClass(OrderedSet, Set);
  23825. // @pragma Construction
  23826. function OrderedSet(value) {
  23827. return value === null || value === undefined ? emptyOrderedSet() :
  23828. isOrderedSet(value) ? value :
  23829. emptyOrderedSet().withMutations(function(set ) {
  23830. var iter = SetIterable(value);
  23831. assertNotInfinite(iter.size);
  23832. iter.forEach(function(v ) {return set.add(v)});
  23833. });
  23834. }
  23835. OrderedSet.of = function(/*...values*/) {
  23836. return this(arguments);
  23837. };
  23838. OrderedSet.fromKeys = function(value) {
  23839. return this(KeyedIterable(value).keySeq());
  23840. };
  23841. OrderedSet.prototype.toString = function() {
  23842. return this.__toString('OrderedSet {', '}');
  23843. };
  23844. function isOrderedSet(maybeOrderedSet) {
  23845. return isSet(maybeOrderedSet) && isOrdered(maybeOrderedSet);
  23846. }
  23847. OrderedSet.isOrderedSet = isOrderedSet;
  23848. var OrderedSetPrototype = OrderedSet.prototype;
  23849. OrderedSetPrototype[IS_ORDERED_SENTINEL] = true;
  23850. OrderedSetPrototype.__empty = emptyOrderedSet;
  23851. OrderedSetPrototype.__make = makeOrderedSet;
  23852. function makeOrderedSet(map, ownerID) {
  23853. var set = Object.create(OrderedSetPrototype);
  23854. set.size = map ? map.size : 0;
  23855. set._map = map;
  23856. set.__ownerID = ownerID;
  23857. return set;
  23858. }
  23859. var EMPTY_ORDERED_SET;
  23860. function emptyOrderedSet() {
  23861. return EMPTY_ORDERED_SET || (EMPTY_ORDERED_SET = makeOrderedSet(emptyOrderedMap()));
  23862. }
  23863. createClass(Stack, IndexedCollection);
  23864. // @pragma Construction
  23865. function Stack(value) {
  23866. return value === null || value === undefined ? emptyStack() :
  23867. isStack(value) ? value :
  23868. emptyStack().unshiftAll(value);
  23869. }
  23870. Stack.of = function(/*...values*/) {
  23871. return this(arguments);
  23872. };
  23873. Stack.prototype.toString = function() {
  23874. return this.__toString('Stack [', ']');
  23875. };
  23876. // @pragma Access
  23877. Stack.prototype.get = function(index, notSetValue) {
  23878. var head = this._head;
  23879. index = wrapIndex(this, index);
  23880. while (head && index--) {
  23881. head = head.next;
  23882. }
  23883. return head ? head.value : notSetValue;
  23884. };
  23885. Stack.prototype.peek = function() {
  23886. return this._head && this._head.value;
  23887. };
  23888. // @pragma Modification
  23889. Stack.prototype.push = function(/*...values*/) {
  23890. if (arguments.length === 0) {
  23891. return this;
  23892. }
  23893. var newSize = this.size + arguments.length;
  23894. var head = this._head;
  23895. for (var ii = arguments.length - 1; ii >= 0; ii--) {
  23896. head = {
  23897. value: arguments[ii],
  23898. next: head
  23899. };
  23900. }
  23901. if (this.__ownerID) {
  23902. this.size = newSize;
  23903. this._head = head;
  23904. this.__hash = undefined;
  23905. this.__altered = true;
  23906. return this;
  23907. }
  23908. return makeStack(newSize, head);
  23909. };
  23910. Stack.prototype.pushAll = function(iter) {
  23911. iter = IndexedIterable(iter);
  23912. if (iter.size === 0) {
  23913. return this;
  23914. }
  23915. assertNotInfinite(iter.size);
  23916. var newSize = this.size;
  23917. var head = this._head;
  23918. iter.reverse().forEach(function(value ) {
  23919. newSize++;
  23920. head = {
  23921. value: value,
  23922. next: head
  23923. };
  23924. });
  23925. if (this.__ownerID) {
  23926. this.size = newSize;
  23927. this._head = head;
  23928. this.__hash = undefined;
  23929. this.__altered = true;
  23930. return this;
  23931. }
  23932. return makeStack(newSize, head);
  23933. };
  23934. Stack.prototype.pop = function() {
  23935. return this.slice(1);
  23936. };
  23937. Stack.prototype.unshift = function(/*...values*/) {
  23938. return this.push.apply(this, arguments);
  23939. };
  23940. Stack.prototype.unshiftAll = function(iter) {
  23941. return this.pushAll(iter);
  23942. };
  23943. Stack.prototype.shift = function() {
  23944. return this.pop.apply(this, arguments);
  23945. };
  23946. Stack.prototype.clear = function() {
  23947. if (this.size === 0) {
  23948. return this;
  23949. }
  23950. if (this.__ownerID) {
  23951. this.size = 0;
  23952. this._head = undefined;
  23953. this.__hash = undefined;
  23954. this.__altered = true;
  23955. return this;
  23956. }
  23957. return emptyStack();
  23958. };
  23959. Stack.prototype.slice = function(begin, end) {
  23960. if (wholeSlice(begin, end, this.size)) {
  23961. return this;
  23962. }
  23963. var resolvedBegin = resolveBegin(begin, this.size);
  23964. var resolvedEnd = resolveEnd(end, this.size);
  23965. if (resolvedEnd !== this.size) {
  23966. // super.slice(begin, end);
  23967. return IndexedCollection.prototype.slice.call(this, begin, end);
  23968. }
  23969. var newSize = this.size - resolvedBegin;
  23970. var head = this._head;
  23971. while (resolvedBegin--) {
  23972. head = head.next;
  23973. }
  23974. if (this.__ownerID) {
  23975. this.size = newSize;
  23976. this._head = head;
  23977. this.__hash = undefined;
  23978. this.__altered = true;
  23979. return this;
  23980. }
  23981. return makeStack(newSize, head);
  23982. };
  23983. // @pragma Mutability
  23984. Stack.prototype.__ensureOwner = function(ownerID) {
  23985. if (ownerID === this.__ownerID) {
  23986. return this;
  23987. }
  23988. if (!ownerID) {
  23989. this.__ownerID = ownerID;
  23990. this.__altered = false;
  23991. return this;
  23992. }
  23993. return makeStack(this.size, this._head, ownerID, this.__hash);
  23994. };
  23995. // @pragma Iteration
  23996. Stack.prototype.__iterate = function(fn, reverse) {
  23997. if (reverse) {
  23998. return this.reverse().__iterate(fn);
  23999. }
  24000. var iterations = 0;
  24001. var node = this._head;
  24002. while (node) {
  24003. if (fn(node.value, iterations++, this) === false) {
  24004. break;
  24005. }
  24006. node = node.next;
  24007. }
  24008. return iterations;
  24009. };
  24010. Stack.prototype.__iterator = function(type, reverse) {
  24011. if (reverse) {
  24012. return this.reverse().__iterator(type);
  24013. }
  24014. var iterations = 0;
  24015. var node = this._head;
  24016. return new Iterator(function() {
  24017. if (node) {
  24018. var value = node.value;
  24019. node = node.next;
  24020. return iteratorValue(type, iterations++, value);
  24021. }
  24022. return iteratorDone();
  24023. });
  24024. };
  24025. function isStack(maybeStack) {
  24026. return !!(maybeStack && maybeStack[IS_STACK_SENTINEL]);
  24027. }
  24028. Stack.isStack = isStack;
  24029. var IS_STACK_SENTINEL = '@@__IMMUTABLE_STACK__@@';
  24030. var StackPrototype = Stack.prototype;
  24031. StackPrototype[IS_STACK_SENTINEL] = true;
  24032. StackPrototype.withMutations = MapPrototype.withMutations;
  24033. StackPrototype.asMutable = MapPrototype.asMutable;
  24034. StackPrototype.asImmutable = MapPrototype.asImmutable;
  24035. StackPrototype.wasAltered = MapPrototype.wasAltered;
  24036. function makeStack(size, head, ownerID, hash) {
  24037. var map = Object.create(StackPrototype);
  24038. map.size = size;
  24039. map._head = head;
  24040. map.__ownerID = ownerID;
  24041. map.__hash = hash;
  24042. map.__altered = false;
  24043. return map;
  24044. }
  24045. var EMPTY_STACK;
  24046. function emptyStack() {
  24047. return EMPTY_STACK || (EMPTY_STACK = makeStack(0));
  24048. }
  24049. /**
  24050. * Contributes additional methods to a constructor
  24051. */
  24052. function mixin(ctor, methods) {
  24053. var keyCopier = function(key ) { ctor.prototype[key] = methods[key]; };
  24054. Object.keys(methods).forEach(keyCopier);
  24055. Object.getOwnPropertySymbols &&
  24056. Object.getOwnPropertySymbols(methods).forEach(keyCopier);
  24057. return ctor;
  24058. }
  24059. Iterable.Iterator = Iterator;
  24060. mixin(Iterable, {
  24061. // ### Conversion to other types
  24062. toArray: function() {
  24063. assertNotInfinite(this.size);
  24064. var array = new Array(this.size || 0);
  24065. this.valueSeq().__iterate(function(v, i) { array[i] = v; });
  24066. return array;
  24067. },
  24068. toIndexedSeq: function() {
  24069. return new ToIndexedSequence(this);
  24070. },
  24071. toJS: function() {
  24072. return this.toSeq().map(
  24073. function(value ) {return value && typeof value.toJS === 'function' ? value.toJS() : value}
  24074. ).__toJS();
  24075. },
  24076. toJSON: function() {
  24077. return this.toSeq().map(
  24078. function(value ) {return value && typeof value.toJSON === 'function' ? value.toJSON() : value}
  24079. ).__toJS();
  24080. },
  24081. toKeyedSeq: function() {
  24082. return new ToKeyedSequence(this, true);
  24083. },
  24084. toMap: function() {
  24085. // Use Late Binding here to solve the circular dependency.
  24086. return Map(this.toKeyedSeq());
  24087. },
  24088. toObject: function() {
  24089. assertNotInfinite(this.size);
  24090. var object = {};
  24091. this.__iterate(function(v, k) { object[k] = v; });
  24092. return object;
  24093. },
  24094. toOrderedMap: function() {
  24095. // Use Late Binding here to solve the circular dependency.
  24096. return OrderedMap(this.toKeyedSeq());
  24097. },
  24098. toOrderedSet: function() {
  24099. // Use Late Binding here to solve the circular dependency.
  24100. return OrderedSet(isKeyed(this) ? this.valueSeq() : this);
  24101. },
  24102. toSet: function() {
  24103. // Use Late Binding here to solve the circular dependency.
  24104. return Set(isKeyed(this) ? this.valueSeq() : this);
  24105. },
  24106. toSetSeq: function() {
  24107. return new ToSetSequence(this);
  24108. },
  24109. toSeq: function() {
  24110. return isIndexed(this) ? this.toIndexedSeq() :
  24111. isKeyed(this) ? this.toKeyedSeq() :
  24112. this.toSetSeq();
  24113. },
  24114. toStack: function() {
  24115. // Use Late Binding here to solve the circular dependency.
  24116. return Stack(isKeyed(this) ? this.valueSeq() : this);
  24117. },
  24118. toList: function() {
  24119. // Use Late Binding here to solve the circular dependency.
  24120. return List(isKeyed(this) ? this.valueSeq() : this);
  24121. },
  24122. // ### Common JavaScript methods and properties
  24123. toString: function() {
  24124. return '[Iterable]';
  24125. },
  24126. __toString: function(head, tail) {
  24127. if (this.size === 0) {
  24128. return head + tail;
  24129. }
  24130. return head + ' ' + this.toSeq().map(this.__toStringMapper).join(', ') + ' ' + tail;
  24131. },
  24132. // ### ES6 Collection methods (ES6 Array and Map)
  24133. concat: function() {var values = SLICE$0.call(arguments, 0);
  24134. return reify(this, concatFactory(this, values));
  24135. },
  24136. includes: function(searchValue) {
  24137. return this.some(function(value ) {return is(value, searchValue)});
  24138. },
  24139. entries: function() {
  24140. return this.__iterator(ITERATE_ENTRIES);
  24141. },
  24142. every: function(predicate, context) {
  24143. assertNotInfinite(this.size);
  24144. var returnValue = true;
  24145. this.__iterate(function(v, k, c) {
  24146. if (!predicate.call(context, v, k, c)) {
  24147. returnValue = false;
  24148. return false;
  24149. }
  24150. });
  24151. return returnValue;
  24152. },
  24153. filter: function(predicate, context) {
  24154. return reify(this, filterFactory(this, predicate, context, true));
  24155. },
  24156. find: function(predicate, context, notSetValue) {
  24157. var entry = this.findEntry(predicate, context);
  24158. return entry ? entry[1] : notSetValue;
  24159. },
  24160. findEntry: function(predicate, context) {
  24161. var found;
  24162. this.__iterate(function(v, k, c) {
  24163. if (predicate.call(context, v, k, c)) {
  24164. found = [k, v];
  24165. return false;
  24166. }
  24167. });
  24168. return found;
  24169. },
  24170. findLastEntry: function(predicate, context) {
  24171. return this.toSeq().reverse().findEntry(predicate, context);
  24172. },
  24173. forEach: function(sideEffect, context) {
  24174. assertNotInfinite(this.size);
  24175. return this.__iterate(context ? sideEffect.bind(context) : sideEffect);
  24176. },
  24177. join: function(separator) {
  24178. assertNotInfinite(this.size);
  24179. separator = separator !== undefined ? '' + separator : ',';
  24180. var joined = '';
  24181. var isFirst = true;
  24182. this.__iterate(function(v ) {
  24183. isFirst ? (isFirst = false) : (joined += separator);
  24184. joined += v !== null && v !== undefined ? v.toString() : '';
  24185. });
  24186. return joined;
  24187. },
  24188. keys: function() {
  24189. return this.__iterator(ITERATE_KEYS);
  24190. },
  24191. map: function(mapper, context) {
  24192. return reify(this, mapFactory(this, mapper, context));
  24193. },
  24194. reduce: function(reducer, initialReduction, context) {
  24195. assertNotInfinite(this.size);
  24196. var reduction;
  24197. var useFirst;
  24198. if (arguments.length < 2) {
  24199. useFirst = true;
  24200. } else {
  24201. reduction = initialReduction;
  24202. }
  24203. this.__iterate(function(v, k, c) {
  24204. if (useFirst) {
  24205. useFirst = false;
  24206. reduction = v;
  24207. } else {
  24208. reduction = reducer.call(context, reduction, v, k, c);
  24209. }
  24210. });
  24211. return reduction;
  24212. },
  24213. reduceRight: function(reducer, initialReduction, context) {
  24214. var reversed = this.toKeyedSeq().reverse();
  24215. return reversed.reduce.apply(reversed, arguments);
  24216. },
  24217. reverse: function() {
  24218. return reify(this, reverseFactory(this, true));
  24219. },
  24220. slice: function(begin, end) {
  24221. return reify(this, sliceFactory(this, begin, end, true));
  24222. },
  24223. some: function(predicate, context) {
  24224. return !this.every(not(predicate), context);
  24225. },
  24226. sort: function(comparator) {
  24227. return reify(this, sortFactory(this, comparator));
  24228. },
  24229. values: function() {
  24230. return this.__iterator(ITERATE_VALUES);
  24231. },
  24232. // ### More sequential methods
  24233. butLast: function() {
  24234. return this.slice(0, -1);
  24235. },
  24236. isEmpty: function() {
  24237. return this.size !== undefined ? this.size === 0 : !this.some(function() {return true});
  24238. },
  24239. count: function(predicate, context) {
  24240. return ensureSize(
  24241. predicate ? this.toSeq().filter(predicate, context) : this
  24242. );
  24243. },
  24244. countBy: function(grouper, context) {
  24245. return countByFactory(this, grouper, context);
  24246. },
  24247. equals: function(other) {
  24248. return deepEqual(this, other);
  24249. },
  24250. entrySeq: function() {
  24251. var iterable = this;
  24252. if (iterable._cache) {
  24253. // We cache as an entries array, so we can just return the cache!
  24254. return new ArraySeq(iterable._cache);
  24255. }
  24256. var entriesSequence = iterable.toSeq().map(entryMapper).toIndexedSeq();
  24257. entriesSequence.fromEntrySeq = function() {return iterable.toSeq()};
  24258. return entriesSequence;
  24259. },
  24260. filterNot: function(predicate, context) {
  24261. return this.filter(not(predicate), context);
  24262. },
  24263. findLast: function(predicate, context, notSetValue) {
  24264. return this.toKeyedSeq().reverse().find(predicate, context, notSetValue);
  24265. },
  24266. first: function() {
  24267. return this.find(returnTrue);
  24268. },
  24269. flatMap: function(mapper, context) {
  24270. return reify(this, flatMapFactory(this, mapper, context));
  24271. },
  24272. flatten: function(depth) {
  24273. return reify(this, flattenFactory(this, depth, true));
  24274. },
  24275. fromEntrySeq: function() {
  24276. return new FromEntriesSequence(this);
  24277. },
  24278. get: function(searchKey, notSetValue) {
  24279. return this.find(function(_, key) {return is(key, searchKey)}, undefined, notSetValue);
  24280. },
  24281. getIn: function(searchKeyPath, notSetValue) {
  24282. var nested = this;
  24283. // Note: in an ES6 environment, we would prefer:
  24284. // for (var key of searchKeyPath) {
  24285. var iter = forceIterator(searchKeyPath);
  24286. var step;
  24287. while (!(step = iter.next()).done) {
  24288. var key = step.value;
  24289. nested = nested && nested.get ? nested.get(key, NOT_SET) : NOT_SET;
  24290. if (nested === NOT_SET) {
  24291. return notSetValue;
  24292. }
  24293. }
  24294. return nested;
  24295. },
  24296. groupBy: function(grouper, context) {
  24297. return groupByFactory(this, grouper, context);
  24298. },
  24299. has: function(searchKey) {
  24300. return this.get(searchKey, NOT_SET) !== NOT_SET;
  24301. },
  24302. hasIn: function(searchKeyPath) {
  24303. return this.getIn(searchKeyPath, NOT_SET) !== NOT_SET;
  24304. },
  24305. isSubset: function(iter) {
  24306. iter = typeof iter.includes === 'function' ? iter : Iterable(iter);
  24307. return this.every(function(value ) {return iter.includes(value)});
  24308. },
  24309. isSuperset: function(iter) {
  24310. iter = typeof iter.isSubset === 'function' ? iter : Iterable(iter);
  24311. return iter.isSubset(this);
  24312. },
  24313. keySeq: function() {
  24314. return this.toSeq().map(keyMapper).toIndexedSeq();
  24315. },
  24316. last: function() {
  24317. return this.toSeq().reverse().first();
  24318. },
  24319. max: function(comparator) {
  24320. return maxFactory(this, comparator);
  24321. },
  24322. maxBy: function(mapper, comparator) {
  24323. return maxFactory(this, comparator, mapper);
  24324. },
  24325. min: function(comparator) {
  24326. return maxFactory(this, comparator ? neg(comparator) : defaultNegComparator);
  24327. },
  24328. minBy: function(mapper, comparator) {
  24329. return maxFactory(this, comparator ? neg(comparator) : defaultNegComparator, mapper);
  24330. },
  24331. rest: function() {
  24332. return this.slice(1);
  24333. },
  24334. skip: function(amount) {
  24335. return this.slice(Math.max(0, amount));
  24336. },
  24337. skipLast: function(amount) {
  24338. return reify(this, this.toSeq().reverse().skip(amount).reverse());
  24339. },
  24340. skipWhile: function(predicate, context) {
  24341. return reify(this, skipWhileFactory(this, predicate, context, true));
  24342. },
  24343. skipUntil: function(predicate, context) {
  24344. return this.skipWhile(not(predicate), context);
  24345. },
  24346. sortBy: function(mapper, comparator) {
  24347. return reify(this, sortFactory(this, comparator, mapper));
  24348. },
  24349. take: function(amount) {
  24350. return this.slice(0, Math.max(0, amount));
  24351. },
  24352. takeLast: function(amount) {
  24353. return reify(this, this.toSeq().reverse().take(amount).reverse());
  24354. },
  24355. takeWhile: function(predicate, context) {
  24356. return reify(this, takeWhileFactory(this, predicate, context));
  24357. },
  24358. takeUntil: function(predicate, context) {
  24359. return this.takeWhile(not(predicate), context);
  24360. },
  24361. valueSeq: function() {
  24362. return this.toIndexedSeq();
  24363. },
  24364. // ### Hashable Object
  24365. hashCode: function() {
  24366. return this.__hash || (this.__hash = hashIterable(this));
  24367. }
  24368. // ### Internal
  24369. // abstract __iterate(fn, reverse)
  24370. // abstract __iterator(type, reverse)
  24371. });
  24372. // var IS_ITERABLE_SENTINEL = '@@__IMMUTABLE_ITERABLE__@@';
  24373. // var IS_KEYED_SENTINEL = '@@__IMMUTABLE_KEYED__@@';
  24374. // var IS_INDEXED_SENTINEL = '@@__IMMUTABLE_INDEXED__@@';
  24375. // var IS_ORDERED_SENTINEL = '@@__IMMUTABLE_ORDERED__@@';
  24376. var IterablePrototype = Iterable.prototype;
  24377. IterablePrototype[IS_ITERABLE_SENTINEL] = true;
  24378. IterablePrototype[ITERATOR_SYMBOL] = IterablePrototype.values;
  24379. IterablePrototype.__toJS = IterablePrototype.toArray;
  24380. IterablePrototype.__toStringMapper = quoteString;
  24381. IterablePrototype.inspect =
  24382. IterablePrototype.toSource = function() { return this.toString(); };
  24383. IterablePrototype.chain = IterablePrototype.flatMap;
  24384. IterablePrototype.contains = IterablePrototype.includes;
  24385. // Temporary warning about using length
  24386. (function () {
  24387. try {
  24388. Object.defineProperty(IterablePrototype, 'length', {
  24389. get: function () {
  24390. if (!Iterable.noLengthWarning) {
  24391. var stack;
  24392. try {
  24393. throw new Error();
  24394. } catch (error) {
  24395. stack = error.stack;
  24396. }
  24397. if (stack.indexOf('_wrapObject') === -1) {
  24398. console && console.warn && console.warn(
  24399. 'iterable.length has been deprecated, '+
  24400. 'use iterable.size or iterable.count(). '+
  24401. 'This warning will become a silent error in a future version. ' +
  24402. stack
  24403. );
  24404. return this.size;
  24405. }
  24406. }
  24407. }
  24408. });
  24409. } catch (e) {}
  24410. })();
  24411. mixin(KeyedIterable, {
  24412. // ### More sequential methods
  24413. flip: function() {
  24414. return reify(this, flipFactory(this));
  24415. },
  24416. findKey: function(predicate, context) {
  24417. var entry = this.findEntry(predicate, context);
  24418. return entry && entry[0];
  24419. },
  24420. findLastKey: function(predicate, context) {
  24421. return this.toSeq().reverse().findKey(predicate, context);
  24422. },
  24423. keyOf: function(searchValue) {
  24424. return this.findKey(function(value ) {return is(value, searchValue)});
  24425. },
  24426. lastKeyOf: function(searchValue) {
  24427. return this.findLastKey(function(value ) {return is(value, searchValue)});
  24428. },
  24429. mapEntries: function(mapper, context) {var this$0 = this;
  24430. var iterations = 0;
  24431. return reify(this,
  24432. this.toSeq().map(
  24433. function(v, k) {return mapper.call(context, [k, v], iterations++, this$0)}
  24434. ).fromEntrySeq()
  24435. );
  24436. },
  24437. mapKeys: function(mapper, context) {var this$0 = this;
  24438. return reify(this,
  24439. this.toSeq().flip().map(
  24440. function(k, v) {return mapper.call(context, k, v, this$0)}
  24441. ).flip()
  24442. );
  24443. }
  24444. });
  24445. var KeyedIterablePrototype = KeyedIterable.prototype;
  24446. KeyedIterablePrototype[IS_KEYED_SENTINEL] = true;
  24447. KeyedIterablePrototype[ITERATOR_SYMBOL] = IterablePrototype.entries;
  24448. KeyedIterablePrototype.__toJS = IterablePrototype.toObject;
  24449. KeyedIterablePrototype.__toStringMapper = function(v, k) {return JSON.stringify(k) + ': ' + quoteString(v)};
  24450. mixin(IndexedIterable, {
  24451. // ### Conversion to other types
  24452. toKeyedSeq: function() {
  24453. return new ToKeyedSequence(this, false);
  24454. },
  24455. // ### ES6 Collection methods (ES6 Array and Map)
  24456. filter: function(predicate, context) {
  24457. return reify(this, filterFactory(this, predicate, context, false));
  24458. },
  24459. findIndex: function(predicate, context) {
  24460. var entry = this.findEntry(predicate, context);
  24461. return entry ? entry[0] : -1;
  24462. },
  24463. indexOf: function(searchValue) {
  24464. var key = this.toKeyedSeq().keyOf(searchValue);
  24465. return key === undefined ? -1 : key;
  24466. },
  24467. lastIndexOf: function(searchValue) {
  24468. var key = this.toKeyedSeq().reverse().keyOf(searchValue);
  24469. return key === undefined ? -1 : key;
  24470. // var index =
  24471. // return this.toSeq().reverse().indexOf(searchValue);
  24472. },
  24473. reverse: function() {
  24474. return reify(this, reverseFactory(this, false));
  24475. },
  24476. slice: function(begin, end) {
  24477. return reify(this, sliceFactory(this, begin, end, false));
  24478. },
  24479. splice: function(index, removeNum /*, ...values*/) {
  24480. var numArgs = arguments.length;
  24481. removeNum = Math.max(removeNum | 0, 0);
  24482. if (numArgs === 0 || (numArgs === 2 && !removeNum)) {
  24483. return this;
  24484. }
  24485. // If index is negative, it should resolve relative to the size of the
  24486. // collection. However size may be expensive to compute if not cached, so
  24487. // only call count() if the number is in fact negative.
  24488. index = resolveBegin(index, index < 0 ? this.count() : this.size);
  24489. var spliced = this.slice(0, index);
  24490. return reify(
  24491. this,
  24492. numArgs === 1 ?
  24493. spliced :
  24494. spliced.concat(arrCopy(arguments, 2), this.slice(index + removeNum))
  24495. );
  24496. },
  24497. // ### More collection methods
  24498. findLastIndex: function(predicate, context) {
  24499. var key = this.toKeyedSeq().findLastKey(predicate, context);
  24500. return key === undefined ? -1 : key;
  24501. },
  24502. first: function() {
  24503. return this.get(0);
  24504. },
  24505. flatten: function(depth) {
  24506. return reify(this, flattenFactory(this, depth, false));
  24507. },
  24508. get: function(index, notSetValue) {
  24509. index = wrapIndex(this, index);
  24510. return (index < 0 || (this.size === Infinity ||
  24511. (this.size !== undefined && index > this.size))) ?
  24512. notSetValue :
  24513. this.find(function(_, key) {return key === index}, undefined, notSetValue);
  24514. },
  24515. has: function(index) {
  24516. index = wrapIndex(this, index);
  24517. return index >= 0 && (this.size !== undefined ?
  24518. this.size === Infinity || index < this.size :
  24519. this.indexOf(index) !== -1
  24520. );
  24521. },
  24522. interpose: function(separator) {
  24523. return reify(this, interposeFactory(this, separator));
  24524. },
  24525. interleave: function(/*...iterables*/) {
  24526. var iterables = [this].concat(arrCopy(arguments));
  24527. var zipped = zipWithFactory(this.toSeq(), IndexedSeq.of, iterables);
  24528. var interleaved = zipped.flatten(true);
  24529. if (zipped.size) {
  24530. interleaved.size = zipped.size * iterables.length;
  24531. }
  24532. return reify(this, interleaved);
  24533. },
  24534. last: function() {
  24535. return this.get(-1);
  24536. },
  24537. skipWhile: function(predicate, context) {
  24538. return reify(this, skipWhileFactory(this, predicate, context, false));
  24539. },
  24540. zip: function(/*, ...iterables */) {
  24541. var iterables = [this].concat(arrCopy(arguments));
  24542. return reify(this, zipWithFactory(this, defaultZipper, iterables));
  24543. },
  24544. zipWith: function(zipper/*, ...iterables */) {
  24545. var iterables = arrCopy(arguments);
  24546. iterables[0] = this;
  24547. return reify(this, zipWithFactory(this, zipper, iterables));
  24548. }
  24549. });
  24550. IndexedIterable.prototype[IS_INDEXED_SENTINEL] = true;
  24551. IndexedIterable.prototype[IS_ORDERED_SENTINEL] = true;
  24552. mixin(SetIterable, {
  24553. // ### ES6 Collection methods (ES6 Array and Map)
  24554. get: function(value, notSetValue) {
  24555. return this.has(value) ? value : notSetValue;
  24556. },
  24557. includes: function(value) {
  24558. return this.has(value);
  24559. },
  24560. // ### More sequential methods
  24561. keySeq: function() {
  24562. return this.valueSeq();
  24563. }
  24564. });
  24565. SetIterable.prototype.has = IterablePrototype.includes;
  24566. // Mixin subclasses
  24567. mixin(KeyedSeq, KeyedIterable.prototype);
  24568. mixin(IndexedSeq, IndexedIterable.prototype);
  24569. mixin(SetSeq, SetIterable.prototype);
  24570. mixin(KeyedCollection, KeyedIterable.prototype);
  24571. mixin(IndexedCollection, IndexedIterable.prototype);
  24572. mixin(SetCollection, SetIterable.prototype);
  24573. // #pragma Helper functions
  24574. function keyMapper(v, k) {
  24575. return k;
  24576. }
  24577. function entryMapper(v, k) {
  24578. return [k, v];
  24579. }
  24580. function not(predicate) {
  24581. return function() {
  24582. return !predicate.apply(this, arguments);
  24583. }
  24584. }
  24585. function neg(predicate) {
  24586. return function() {
  24587. return -predicate.apply(this, arguments);
  24588. }
  24589. }
  24590. function quoteString(value) {
  24591. return typeof value === 'string' ? JSON.stringify(value) : value;
  24592. }
  24593. function defaultZipper() {
  24594. return arrCopy(arguments);
  24595. }
  24596. function defaultNegComparator(a, b) {
  24597. return a < b ? 1 : a > b ? -1 : 0;
  24598. }
  24599. function hashIterable(iterable) {
  24600. if (iterable.size === Infinity) {
  24601. return 0;
  24602. }
  24603. var ordered = isOrdered(iterable);
  24604. var keyed = isKeyed(iterable);
  24605. var h = ordered ? 1 : 0;
  24606. var size = iterable.__iterate(
  24607. keyed ?
  24608. ordered ?
  24609. function(v, k) { h = 31 * h + hashMerge(hash(v), hash(k)) | 0; } :
  24610. function(v, k) { h = h + hashMerge(hash(v), hash(k)) | 0; } :
  24611. ordered ?
  24612. function(v ) { h = 31 * h + hash(v) | 0; } :
  24613. function(v ) { h = h + hash(v) | 0; }
  24614. );
  24615. return murmurHashOfSize(size, h);
  24616. }
  24617. function murmurHashOfSize(size, h) {
  24618. h = imul(h, 0xCC9E2D51);
  24619. h = imul(h << 15 | h >>> -15, 0x1B873593);
  24620. h = imul(h << 13 | h >>> -13, 5);
  24621. h = (h + 0xE6546B64 | 0) ^ size;
  24622. h = imul(h ^ h >>> 16, 0x85EBCA6B);
  24623. h = imul(h ^ h >>> 13, 0xC2B2AE35);
  24624. h = smi(h ^ h >>> 16);
  24625. return h;
  24626. }
  24627. function hashMerge(a, b) {
  24628. return a ^ b + 0x9E3779B9 + (a << 6) + (a >> 2) | 0; // int
  24629. }
  24630. var Immutable = {
  24631. Iterable: Iterable,
  24632. Seq: Seq,
  24633. Collection: Collection,
  24634. Map: Map,
  24635. OrderedMap: OrderedMap,
  24636. List: List,
  24637. Stack: Stack,
  24638. Set: Set,
  24639. OrderedSet: OrderedSet,
  24640. Record: Record,
  24641. Range: Range,
  24642. Repeat: Repeat,
  24643. is: is,
  24644. fromJS: fromJS
  24645. };
  24646. return Immutable;
  24647. }));
  24648. });
  24649. var parseHTML_1 = createCommonjsModule(function (module, exports) {
  24650. Object.defineProperty(exports, "__esModule", {
  24651. value: true
  24652. });
  24653. exports["default"] = parseHTML;
  24654. var fallback = function fallback(html) {
  24655. var doc = document.implementation.createHTMLDocument('');
  24656. doc.documentElement.innerHTML = html;
  24657. return doc;
  24658. };
  24659. function parseHTML(html) {
  24660. var doc;
  24661. if (typeof DOMParser !== 'undefined') {
  24662. var parser = new DOMParser();
  24663. doc = parser.parseFromString(html, 'text/html');
  24664. if (doc === null || doc.body === null) {
  24665. doc = fallback(html);
  24666. }
  24667. } else {
  24668. doc = fallback(html);
  24669. }
  24670. return doc.body;
  24671. }
  24672. });
  24673. unwrapExports(parseHTML_1);
  24674. var convertFromHTML_1 = createCommonjsModule(function (module, exports) {
  24675. Object.defineProperty(exports, "__esModule", {
  24676. value: true
  24677. });
  24678. exports["default"] = void 0;
  24679. var _parseHTML = interopRequireDefault(parseHTML_1);
  24680. var _rangeSort = interopRequireDefault(rangeSort);
  24681. /**
  24682. * Copyright (c) 2013-present, Facebook, Inc.
  24683. * All rights reserved.
  24684. *
  24685. * Copyright (c) 2013-present, Facebook, Inc.
  24686. * All rights reserved.
  24687. *
  24688. * This source code is licensed under the BSD-style license found in the
  24689. * LICENSE file in the /src directory of this source tree. An additional grant
  24690. * of patent rights can be found in the PATENTS file in the same directory.
  24691. */
  24692. var NBSP = '&nbsp;';
  24693. var SPACE = ' '; // Arbitrary max indent
  24694. var MAX_DEPTH = 4; // used for replacing characters in HTML
  24695. /* eslint-disable no-control-regex */
  24696. var REGEX_CR = new RegExp('\r', 'g');
  24697. var REGEX_LF = new RegExp('\n', 'g');
  24698. var REGEX_NBSP = new RegExp(NBSP, 'g');
  24699. var REGEX_BLOCK_DELIMITER = new RegExp('\r', 'g');
  24700. /* eslint-enable no-control-regex */
  24701. // Block tag flow is different because LIs do not have
  24702. // a deterministic style ;_;
  24703. var blockTags = ['p', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'li', 'blockquote', 'pre'];
  24704. var inlineTags = {
  24705. b: 'BOLD',
  24706. code: 'CODE',
  24707. del: 'STRIKETHROUGH',
  24708. em: 'ITALIC',
  24709. i: 'ITALIC',
  24710. s: 'STRIKETHROUGH',
  24711. strike: 'STRIKETHROUGH',
  24712. strong: 'BOLD',
  24713. u: 'UNDERLINE'
  24714. };
  24715. var handleMiddleware = function handleMiddleware(maybeMiddleware, base) {
  24716. if (maybeMiddleware && maybeMiddleware.__isMiddleware === true) {
  24717. return maybeMiddleware(base);
  24718. }
  24719. return maybeMiddleware;
  24720. };
  24721. var defaultHTMLToBlock = function defaultHTMLToBlock(nodeName, node, lastList) {
  24722. return undefined;
  24723. };
  24724. var defaultHTMLToStyle = function defaultHTMLToStyle(nodeName, node, currentStyle) {
  24725. return currentStyle;
  24726. };
  24727. var defaultHTMLToEntity = function defaultHTMLToEntity(nodeName, node) {
  24728. return undefined;
  24729. };
  24730. var defaultTextToEntity = function defaultTextToEntity(text) {
  24731. return [];
  24732. };
  24733. var nullthrows = function nullthrows(x) {
  24734. if (x != null) {
  24735. return x;
  24736. }
  24737. throw new Error('Got unexpected null or undefined');
  24738. };
  24739. var sanitizeDraftText = function sanitizeDraftText(input) {
  24740. return input.replace(REGEX_BLOCK_DELIMITER, '');
  24741. };
  24742. function getEmptyChunk() {
  24743. return {
  24744. text: '',
  24745. inlines: [],
  24746. entities: [],
  24747. blocks: []
  24748. };
  24749. }
  24750. function getWhitespaceChunk(inEntity) {
  24751. var entities = new Array(1);
  24752. if (inEntity) {
  24753. entities[0] = inEntity;
  24754. }
  24755. return {
  24756. text: SPACE,
  24757. inlines: [(0, immutable$2.OrderedSet)()],
  24758. entities: entities,
  24759. blocks: []
  24760. };
  24761. }
  24762. function getSoftNewlineChunk(block, depth) {
  24763. var flat = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false;
  24764. var data = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : (0, immutable$2.Map)();
  24765. if (flat === true) {
  24766. return {
  24767. text: '\r',
  24768. inlines: [(0, immutable$2.OrderedSet)()],
  24769. entities: new Array(1),
  24770. blocks: [{
  24771. type: block,
  24772. data: data,
  24773. depth: Math.max(0, Math.min(MAX_DEPTH, depth))
  24774. }],
  24775. isNewline: true
  24776. };
  24777. }
  24778. return {
  24779. text: '\n',
  24780. inlines: [(0, immutable$2.OrderedSet)()],
  24781. entities: new Array(1),
  24782. blocks: []
  24783. };
  24784. }
  24785. function getBlockDividerChunk(block, depth) {
  24786. var data = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : (0, immutable$2.Map)();
  24787. return {
  24788. text: '\r',
  24789. inlines: [(0, immutable$2.OrderedSet)()],
  24790. entities: new Array(1),
  24791. blocks: [{
  24792. type: block,
  24793. data: data,
  24794. depth: Math.max(0, Math.min(MAX_DEPTH, depth))
  24795. }]
  24796. };
  24797. }
  24798. function getBlockTypeForTag(tag, lastList) {
  24799. switch (tag) {
  24800. case 'h1':
  24801. return 'header-one';
  24802. case 'h2':
  24803. return 'header-two';
  24804. case 'h3':
  24805. return 'header-three';
  24806. case 'h4':
  24807. return 'header-four';
  24808. case 'h5':
  24809. return 'header-five';
  24810. case 'h6':
  24811. return 'header-six';
  24812. case 'li':
  24813. if (lastList === 'ol') {
  24814. return 'ordered-list-item';
  24815. }
  24816. return 'unordered-list-item';
  24817. case 'blockquote':
  24818. return 'blockquote';
  24819. case 'pre':
  24820. return 'code-block';
  24821. case 'div':
  24822. case 'p':
  24823. return 'unstyled';
  24824. default:
  24825. return null;
  24826. }
  24827. }
  24828. function baseCheckBlockType(nodeName, node, lastList) {
  24829. return getBlockTypeForTag(nodeName, lastList);
  24830. }
  24831. function processInlineTag(tag, node, currentStyle) {
  24832. var styleToCheck = inlineTags[tag];
  24833. if (styleToCheck) {
  24834. currentStyle = currentStyle.add(styleToCheck).toOrderedSet();
  24835. } else if (node instanceof HTMLElement) {
  24836. var htmlElement = node;
  24837. currentStyle = currentStyle.withMutations(function (style) {
  24838. if (htmlElement.style.fontWeight === 'bold') {
  24839. style.add('BOLD');
  24840. }
  24841. if (htmlElement.style.fontStyle === 'italic') {
  24842. style.add('ITALIC');
  24843. }
  24844. if (htmlElement.style.textDecoration === 'underline') {
  24845. style.add('UNDERLINE');
  24846. }
  24847. if (htmlElement.style.textDecoration === 'line-through') {
  24848. style.add('STRIKETHROUGH');
  24849. }
  24850. }).toOrderedSet();
  24851. }
  24852. return currentStyle;
  24853. }
  24854. function baseProcessInlineTag(tag, node) {
  24855. var inlineStyles = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : (0, immutable$2.OrderedSet)();
  24856. return processInlineTag(tag, node, inlineStyles);
  24857. }
  24858. function joinChunks(A, B) {
  24859. var flat = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false;
  24860. // Sometimes two blocks will touch in the DOM and we need to strip the
  24861. // extra delimiter to preserve niceness.
  24862. var firstInB = B.text.slice(0, 1);
  24863. var lastInA = A.text.slice(-1);
  24864. var adjacentDividers = lastInA === '\r' && firstInB === '\r';
  24865. var isJoiningBlocks = A.text !== '\r' && B.text !== '\r'; // when joining two full blocks like this we want to pop one divider
  24866. var addingNewlineToEmptyBlock = A.text === '\r' && !A.isNewline && B.isNewline; // when joining a newline to an empty block we want to remove the newline
  24867. if (adjacentDividers && (isJoiningBlocks || addingNewlineToEmptyBlock)) {
  24868. A.text = A.text.slice(0, -1);
  24869. A.inlines.pop();
  24870. A.entities.pop();
  24871. A.blocks.pop();
  24872. } // Kill whitespace after blocks if flat mode is on
  24873. if (A.text.slice(-1) === '\r' && flat === true) {
  24874. if (B.text === SPACE || B.text === '\n') {
  24875. return A;
  24876. } else if (firstInB === SPACE || firstInB === '\n') {
  24877. B.text = B.text.slice(1);
  24878. B.inlines.shift();
  24879. B.entities.shift();
  24880. }
  24881. }
  24882. var isNewline = A.text.length === 0 && B.isNewline;
  24883. return {
  24884. text: A.text + B.text,
  24885. inlines: A.inlines.concat(B.inlines),
  24886. entities: A.entities.concat(B.entities),
  24887. blocks: A.blocks.concat(B.blocks),
  24888. isNewline: isNewline
  24889. };
  24890. }
  24891. /*
  24892. * Check to see if we have anything like <p> <blockquote> <h1>... to create
  24893. * block tags from. If we do, we can use those and ignore <div> tags. If we
  24894. * don't, we can treat <div> tags as meaningful (unstyled) blocks.
  24895. */
  24896. function containsSemanticBlockMarkup(html) {
  24897. return blockTags.some(function (tag) {
  24898. return html.indexOf("<".concat(tag)) !== -1;
  24899. });
  24900. }
  24901. function genFragment(node, inlineStyle, lastList, inBlock, fragmentBlockTags, depth, processCustomInlineStyles, checkEntityNode, checkEntityText, checkBlockType, createEntity, getEntity, mergeEntityData, replaceEntityData, options, inEntity) {
  24902. var nodeName = node.nodeName.toLowerCase();
  24903. var newBlock = false;
  24904. var nextBlockType = 'unstyled'; // Base Case
  24905. if (nodeName === '#text') {
  24906. var text = node.textContent;
  24907. if (text.trim() === '' && inBlock === null) {
  24908. return getEmptyChunk();
  24909. }
  24910. if (text.trim() === '' && inBlock !== 'code-block') {
  24911. return getWhitespaceChunk(inEntity);
  24912. }
  24913. if (inBlock !== 'code-block') {
  24914. // Can't use empty string because MSWord
  24915. text = text.replace(REGEX_LF, SPACE);
  24916. }
  24917. var entities = Array(text.length).fill(inEntity);
  24918. var offsetChange = 0;
  24919. var textEntities = checkEntityText(text, createEntity, getEntity, mergeEntityData, replaceEntityData).sort(_rangeSort["default"]);
  24920. textEntities.forEach(function (_ref) {
  24921. var entity = _ref.entity,
  24922. offset = _ref.offset,
  24923. length = _ref.length,
  24924. result = _ref.result;
  24925. var adjustedOffset = offset + offsetChange;
  24926. if (result === null || result === undefined) {
  24927. result = text.substr(adjustedOffset, length);
  24928. }
  24929. var textArray = text.split('');
  24930. textArray.splice.bind(textArray, adjustedOffset, length).apply(textArray, result.split(''));
  24931. text = textArray.join('');
  24932. entities.splice.bind(entities, adjustedOffset, length).apply(entities, Array(result.length).fill(entity));
  24933. offsetChange += result.length - length;
  24934. });
  24935. return {
  24936. text: text,
  24937. inlines: Array(text.length).fill(inlineStyle),
  24938. entities: entities,
  24939. blocks: []
  24940. };
  24941. } // BR tags
  24942. if (nodeName === 'br') {
  24943. var _blockType = inBlock;
  24944. if (_blockType === null) {
  24945. // BR tag is at top level, treat it as an unstyled block
  24946. return getSoftNewlineChunk('unstyled', depth, true);
  24947. }
  24948. return getSoftNewlineChunk(_blockType || 'unstyled', depth, options.flat);
  24949. }
  24950. var chunk = getEmptyChunk();
  24951. var newChunk = null; // Inline tags
  24952. inlineStyle = processInlineTag(nodeName, node, inlineStyle);
  24953. inlineStyle = processCustomInlineStyles(nodeName, node, inlineStyle); // Handle lists
  24954. if (nodeName === 'ul' || nodeName === 'ol') {
  24955. if (lastList) {
  24956. depth += 1;
  24957. }
  24958. lastList = nodeName;
  24959. inBlock = null;
  24960. } // Block Tags
  24961. var blockInfo = checkBlockType(nodeName, node, lastList, inBlock);
  24962. var blockType;
  24963. var blockDataMap;
  24964. if (blockInfo === false) {
  24965. return getEmptyChunk();
  24966. }
  24967. blockInfo = blockInfo || {};
  24968. if (typeof blockInfo === 'string') {
  24969. blockType = blockInfo;
  24970. blockDataMap = (0, immutable$2.Map)();
  24971. } else {
  24972. blockType = typeof blockInfo === 'string' ? blockInfo : blockInfo.type;
  24973. blockDataMap = blockInfo.data ? (0, immutable$2.Map)(blockInfo.data) : (0, immutable$2.Map)();
  24974. }
  24975. if (!inBlock && (fragmentBlockTags.indexOf(nodeName) !== -1 || blockType)) {
  24976. chunk = getBlockDividerChunk(blockType || getBlockTypeForTag(nodeName, lastList), depth, blockDataMap);
  24977. inBlock = blockType || getBlockTypeForTag(nodeName, lastList);
  24978. newBlock = true;
  24979. } else if (lastList && (inBlock === 'ordered-list-item' || inBlock === 'unordered-list-item') && nodeName === 'li') {
  24980. var listItemBlockType = getBlockTypeForTag(nodeName, lastList);
  24981. chunk = getBlockDividerChunk(listItemBlockType, depth);
  24982. inBlock = listItemBlockType;
  24983. newBlock = true;
  24984. nextBlockType = lastList === 'ul' ? 'unordered-list-item' : 'ordered-list-item';
  24985. } else if (inBlock && inBlock !== 'atomic' && blockType === 'atomic') {
  24986. inBlock = blockType;
  24987. newBlock = true;
  24988. chunk = getSoftNewlineChunk(blockType, depth, true, // atomic blocks within non-atomic blocks must always be split out
  24989. blockDataMap);
  24990. } // Recurse through children
  24991. var child = node.firstChild; // hack to allow conversion of atomic blocks from HTML (e.g. <figure><img
  24992. // src="..." /></figure>). since metadata must be stored on an entity text
  24993. // must exist for the entity to apply to. the way chunks are joined strips
  24994. // whitespace at the end so it cannot be a space character.
  24995. if (child == null && inEntity && (blockType === 'atomic' || inBlock === 'atomic')) {
  24996. child = document.createTextNode('a');
  24997. }
  24998. if (child != null) {
  24999. nodeName = child.nodeName.toLowerCase();
  25000. }
  25001. var entityId = null;
  25002. while (child) {
  25003. entityId = checkEntityNode(nodeName, child, createEntity, getEntity, mergeEntityData, replaceEntityData);
  25004. newChunk = genFragment(child, inlineStyle, lastList, inBlock, fragmentBlockTags, depth, processCustomInlineStyles, checkEntityNode, checkEntityText, checkBlockType, createEntity, getEntity, mergeEntityData, replaceEntityData, options, entityId || inEntity);
  25005. chunk = joinChunks(chunk, newChunk, options.flat);
  25006. var sibling = child.nextSibling; // Put in a newline to break up blocks inside blocks
  25007. if (sibling && fragmentBlockTags.indexOf(nodeName) >= 0 && inBlock) {
  25008. var newBlockInfo = checkBlockType(nodeName, child, lastList, inBlock);
  25009. var newBlockType = void 0;
  25010. var newBlockData = void 0;
  25011. if (newBlockInfo !== false) {
  25012. newBlockInfo = newBlockInfo || {};
  25013. if (typeof newBlockInfo === 'string') {
  25014. newBlockType = newBlockInfo;
  25015. newBlockData = (0, immutable$2.Map)();
  25016. } else {
  25017. newBlockType = newBlockInfo.type || getBlockTypeForTag(nodeName, lastList);
  25018. newBlockData = newBlockInfo.data ? (0, immutable$2.Map)(newBlockInfo.data) : (0, immutable$2.Map)();
  25019. }
  25020. chunk = joinChunks(chunk, getSoftNewlineChunk(newBlockType, depth, options.flat, newBlockData), options.flat);
  25021. }
  25022. }
  25023. if (sibling) {
  25024. nodeName = sibling.nodeName.toLowerCase();
  25025. }
  25026. child = sibling;
  25027. }
  25028. if (newBlock) {
  25029. chunk = joinChunks(chunk, getBlockDividerChunk(nextBlockType, depth, (0, immutable$2.Map)()), options.flat);
  25030. }
  25031. return chunk;
  25032. }
  25033. function getChunkForHTML(html, processCustomInlineStyles, checkEntityNode, checkEntityText, checkBlockType, createEntity, getEntity, mergeEntityData, replaceEntityData, options, DOMBuilder) {
  25034. html = html.trim().replace(REGEX_CR, '').replace(REGEX_NBSP, SPACE);
  25035. var safeBody = DOMBuilder(html);
  25036. if (!safeBody) {
  25037. return null;
  25038. } // Sometimes we aren't dealing with content that contains nice semantic
  25039. // tags. In this case, use divs to separate everything out into paragraphs
  25040. // and hope for the best.
  25041. var workingBlocks = containsSemanticBlockMarkup(html) ? blockTags.concat(['div']) : ['div']; // Start with -1 block depth to offset the fact that we are passing in a fake
  25042. // UL block to sta rt with.
  25043. var chunk = genFragment(safeBody, (0, immutable$2.OrderedSet)(), 'ul', null, workingBlocks, -1, processCustomInlineStyles, checkEntityNode, checkEntityText, checkBlockType, createEntity, getEntity, mergeEntityData, replaceEntityData, options); // join with previous block to prevent weirdness on paste
  25044. if (chunk.text.indexOf('\r') === 0) {
  25045. chunk = {
  25046. text: chunk.text.slice(1),
  25047. inlines: chunk.inlines.slice(1),
  25048. entities: chunk.entities.slice(1),
  25049. blocks: chunk.blocks
  25050. };
  25051. } // Kill block delimiter at the end
  25052. if (chunk.text.slice(-1) === '\r') {
  25053. chunk.text = chunk.text.slice(0, -1);
  25054. chunk.inlines = chunk.inlines.slice(0, -1);
  25055. chunk.entities = chunk.entities.slice(0, -1);
  25056. chunk.blocks.pop();
  25057. } // If we saw no block tags, put an unstyled one in
  25058. if (chunk.blocks.length === 0) {
  25059. chunk.blocks.push({
  25060. type: 'unstyled',
  25061. data: (0, immutable$2.Map)(),
  25062. depth: 0
  25063. });
  25064. } // Sometimes we start with text that isn't in a block, which is then
  25065. // followed by blocks. Need to fix up the blocks to add in
  25066. // an unstyled block for this content
  25067. if (chunk.text.split('\r').length === chunk.blocks.length + 1) {
  25068. chunk.blocks.unshift({
  25069. type: 'unstyled',
  25070. data: (0, immutable$2.Map)(),
  25071. depth: 0
  25072. });
  25073. }
  25074. return chunk;
  25075. }
  25076. function convertFromHTMLtoContentBlocks(html, processCustomInlineStyles, checkEntityNode, checkEntityText, checkBlockType, createEntity, getEntity, mergeEntityData, replaceEntityData, options, DOMBuilder, generateKey) {
  25077. // Be ABSOLUTELY SURE that the dom builder you pass hare won't execute
  25078. // arbitrary code in whatever environment you're running this in. For an
  25079. // example of how we try to do this in-browser, see getSafeBodyFromHTML.
  25080. var chunk = getChunkForHTML(html, processCustomInlineStyles, checkEntityNode, checkEntityText, checkBlockType, createEntity, getEntity, mergeEntityData, replaceEntityData, options, DOMBuilder);
  25081. if (chunk == null) {
  25082. return [];
  25083. }
  25084. var start = 0;
  25085. return chunk.text.split('\r').map(function (textBlock, blockIndex) {
  25086. // Make absolutely certain that our text is acceptable.
  25087. textBlock = sanitizeDraftText(textBlock);
  25088. var end = start + textBlock.length;
  25089. var inlines = nullthrows(chunk).inlines.slice(start, end);
  25090. var entities = nullthrows(chunk).entities.slice(start, end);
  25091. var characterList = (0, immutable$2.List)(inlines.map(function (style, entityIndex) {
  25092. var data = {
  25093. style: style,
  25094. entity: null
  25095. };
  25096. if (entities[entityIndex]) {
  25097. data.entity = entities[entityIndex];
  25098. }
  25099. return Draft.CharacterMetadata.create(data);
  25100. }));
  25101. start = end + 1;
  25102. return new Draft.ContentBlock({
  25103. key: generateKey(),
  25104. type: nullthrows(chunk).blocks[blockIndex].type,
  25105. data: nullthrows(chunk).blocks[blockIndex].data,
  25106. depth: nullthrows(chunk).blocks[blockIndex].depth,
  25107. text: textBlock,
  25108. characterList: characterList
  25109. });
  25110. });
  25111. }
  25112. var convertFromHTML = function convertFromHTML(_ref2) {
  25113. var _ref2$htmlToStyle = _ref2.htmlToStyle,
  25114. htmlToStyle = _ref2$htmlToStyle === void 0 ? defaultHTMLToStyle : _ref2$htmlToStyle,
  25115. _ref2$htmlToEntity = _ref2.htmlToEntity,
  25116. htmlToEntity = _ref2$htmlToEntity === void 0 ? defaultHTMLToEntity : _ref2$htmlToEntity,
  25117. _ref2$textToEntity = _ref2.textToEntity,
  25118. textToEntity = _ref2$textToEntity === void 0 ? defaultTextToEntity : _ref2$textToEntity,
  25119. _ref2$htmlToBlock = _ref2.htmlToBlock,
  25120. htmlToBlock = _ref2$htmlToBlock === void 0 ? defaultHTMLToBlock : _ref2$htmlToBlock;
  25121. return function (html) {
  25122. var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {
  25123. flat: false
  25124. };
  25125. var DOMBuilder = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : _parseHTML["default"];
  25126. var generateKey = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : Draft.genKey;
  25127. var contentState = Draft.ContentState.createFromText('');
  25128. var createEntityWithContentState = function createEntityWithContentState() {
  25129. if (contentState.createEntity) {
  25130. var _contentState;
  25131. contentState = (_contentState = contentState).createEntity.apply(_contentState, arguments);
  25132. return contentState.getLastCreatedEntityKey();
  25133. }
  25134. return Draft.Entity.create.apply(Draft.Entity, arguments);
  25135. };
  25136. var getEntityWithContentState = function getEntityWithContentState() {
  25137. if (contentState.getEntity) {
  25138. var _contentState2;
  25139. return (_contentState2 = contentState).getEntity.apply(_contentState2, arguments);
  25140. }
  25141. return Draft.Entity.get.apply(Draft.Entity, arguments);
  25142. };
  25143. var mergeEntityDataWithContentState = function mergeEntityDataWithContentState() {
  25144. if (contentState.mergeEntityData) {
  25145. var _contentState3;
  25146. contentState = (_contentState3 = contentState).mergeEntityData.apply(_contentState3, arguments);
  25147. return;
  25148. }
  25149. Draft.Entity.mergeData.apply(Draft.Entity, arguments);
  25150. };
  25151. var replaceEntityDataWithContentState = function replaceEntityDataWithContentState() {
  25152. if (contentState.replaceEntityData) {
  25153. var _contentState4;
  25154. contentState = (_contentState4 = contentState).replaceEntityData.apply(_contentState4, arguments);
  25155. return;
  25156. }
  25157. Draft.Entity.replaceData.apply(Draft.Entity, arguments);
  25158. };
  25159. var contentBlocks = convertFromHTMLtoContentBlocks(html, handleMiddleware(htmlToStyle, baseProcessInlineTag), handleMiddleware(htmlToEntity, defaultHTMLToEntity), handleMiddleware(textToEntity, defaultTextToEntity), handleMiddleware(htmlToBlock, baseCheckBlockType), createEntityWithContentState, getEntityWithContentState, mergeEntityDataWithContentState, replaceEntityDataWithContentState, options, DOMBuilder, generateKey);
  25160. var blockMap = Draft.BlockMapBuilder.createFromArray(contentBlocks);
  25161. var firstBlockKey = contentBlocks[0].getKey();
  25162. return contentState.merge({
  25163. blockMap: blockMap,
  25164. selectionBefore: Draft.SelectionState.createEmpty(firstBlockKey),
  25165. selectionAfter: Draft.SelectionState.createEmpty(firstBlockKey)
  25166. });
  25167. };
  25168. };
  25169. var _default = function _default() {
  25170. if (arguments.length >= 1 && typeof (arguments.length <= 0 ? undefined : arguments[0]) === 'string') {
  25171. return convertFromHTML({}).apply(void 0, arguments);
  25172. }
  25173. return convertFromHTML.apply(void 0, arguments);
  25174. };
  25175. exports["default"] = _default;
  25176. });
  25177. unwrapExports(convertFromHTML_1);
  25178. var lib = createCommonjsModule(function (module, exports) {
  25179. Object.defineProperty(exports, "__esModule", {
  25180. value: true
  25181. });
  25182. Object.defineProperty(exports, "convertToHTML", {
  25183. enumerable: true,
  25184. get: function get() {
  25185. return _convertToHTML["default"];
  25186. }
  25187. });
  25188. Object.defineProperty(exports, "convertFromHTML", {
  25189. enumerable: true,
  25190. get: function get() {
  25191. return _convertFromHTML["default"];
  25192. }
  25193. });
  25194. Object.defineProperty(exports, "parseHTML", {
  25195. enumerable: true,
  25196. get: function get() {
  25197. return _parseHTML["default"];
  25198. }
  25199. });
  25200. var _convertToHTML = interopRequireDefault(convertToHTML_1);
  25201. var _convertFromHTML = interopRequireDefault(convertFromHTML_1);
  25202. var _parseHTML = interopRequireDefault(parseHTML_1);
  25203. });
  25204. unwrapExports(lib);
  25205. var configs = createCommonjsModule(function (module, exports) {
  25206. Object.defineProperty(exports, "__esModule", {
  25207. value: true
  25208. });
  25209. exports.getFromHTMLConfig = exports.getToHTMLConfig = exports.blocks = exports.getHexColor = exports.defaultFontFamilies = exports.namedColors = undefined;
  25210. var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };
  25211. var _react2 = _interopRequireDefault(React);
  25212. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  25213. function _objectWithoutProperties(obj, keys) { var target = {}; for (var i in obj) { if (keys.indexOf(i) >= 0) continue; if (!Object.prototype.hasOwnProperty.call(obj, i)) continue; target[i] = obj[i]; } return target; }
  25214. var namedColors = exports.namedColors = {
  25215. "aliceblue": "#f0f8ff",
  25216. "antiquewhite": "#faebd7",
  25217. "aqua": "#00ffff",
  25218. "aquamarine": "#7fffd4",
  25219. "azure": "#f0ffff",
  25220. "beige": "#f5f5dc",
  25221. "bisque": "#ffe4c4",
  25222. "black": "#000000",
  25223. "blanchedalmond": "#ffebcd",
  25224. "blue": "#0000ff",
  25225. "blueviolet": "#8a2be2",
  25226. "brown": "#a52a2a",
  25227. "burlywood": "#deb887",
  25228. "cadetblue": "#5f9ea0",
  25229. "chartreuse": "#7fff00",
  25230. "chocolate": "#d2691e",
  25231. "coral": "#ff7f50",
  25232. "cornflowerblue": "#6495ed",
  25233. "cornsilk": "#fff8dc",
  25234. "crimson": "#dc143c",
  25235. "cyan": "#00ffff",
  25236. "darkblue": "#00008b",
  25237. "darkcyan": "#008b8b",
  25238. "darkgoldenrod": "#b8860b",
  25239. "darkgray": "#a9a9a9",
  25240. "darkgreen": "#006400",
  25241. "darkkhaki": "#bdb76b",
  25242. "darkmagenta": "#8b008b",
  25243. "darkolivegreen": "#556b2f",
  25244. "darkorange": "#ff8c00",
  25245. "darkorchid": "#9932cc",
  25246. "darkred": "#8b0000",
  25247. "darksalmon": "#e9967a",
  25248. "darkseagreen": "#8fbc8f",
  25249. "darkslateblue": "#483d8b",
  25250. "darkslategray": "#2f4f4f",
  25251. "darkturquoise": "#00ced1",
  25252. "darkviolet": "#9400d3",
  25253. "deeppink": "#ff1493",
  25254. "deepskyblue": "#00bfff",
  25255. "dimgray": "#696969",
  25256. "dodgerblue": "#1e90ff",
  25257. "firebrick": "#b22222",
  25258. "floralwhite": "#fffaf0",
  25259. "forestgreen": "#228b22",
  25260. "fuchsia": "#ff00ff",
  25261. "gainsboro": "#dcdcdc",
  25262. "ghostwhite": "#f8f8ff",
  25263. "gold": "#ffd700",
  25264. "goldenrod": "#daa520",
  25265. "gray": "#808080",
  25266. "green": "#008000",
  25267. "greenyellow": "#adff2f",
  25268. "honeydew": "#f0fff0",
  25269. "hotpink": "#ff69b4",
  25270. "indianred ": "#cd5c5c",
  25271. "indigo": "#4b0082",
  25272. "ivory": "#fffff0",
  25273. "khaki": "#f0e68c",
  25274. "lavender": "#e6e6fa",
  25275. "lavenderblush": "#fff0f5",
  25276. "lawngreen": "#7cfc00",
  25277. "lemonchiffon": "#fffacd",
  25278. "lightblue": "#add8e6",
  25279. "lightcoral": "#f08080",
  25280. "lightcyan": "#e0ffff",
  25281. "lightgoldenrodyellow": "#fafad2",
  25282. "lightgrey": "#d3d3d3",
  25283. "lightgreen": "#90ee90",
  25284. "lightpink": "#ffb6c1",
  25285. "lightsalmon": "#ffa07a",
  25286. "lightseagreen": "#20b2aa",
  25287. "lightskyblue": "#87cefa",
  25288. "lightslategray": "#778899",
  25289. "lightsteelblue": "#b0c4de",
  25290. "lightyellow": "#ffffe0",
  25291. "lime": "#00ff00",
  25292. "limegreen": "#32cd32",
  25293. "linen": "#faf0e6",
  25294. "magenta": "#ff00ff",
  25295. "maroon": "#800000",
  25296. "mediumaquamarine": "#66cdaa",
  25297. "mediumblue": "#0000cd",
  25298. "mediumorchid": "#ba55d3",
  25299. "mediumpurple": "#9370d8",
  25300. "mediumseagreen": "#3cb371",
  25301. "mediumslateblue": "#7b68ee",
  25302. "mediumspringgreen": "#00fa9a",
  25303. "mediumturquoise": "#48d1cc",
  25304. "mediumvioletred": "#c71585",
  25305. "midnightblue": "#191970",
  25306. "mintcream": "#f5fffa",
  25307. "mistyrose": "#ffe4e1",
  25308. "moccasin": "#ffe4b5",
  25309. "navajowhite": "#ffdead",
  25310. "navy": "#000080",
  25311. "oldlace": "#fdf5e6",
  25312. "olive": "#808000",
  25313. "olivedrab": "#6b8e23",
  25314. "orange": "#ffa500",
  25315. "orangered": "#ff4500",
  25316. "orchid": "#da70d6",
  25317. "palegoldenrod": "#eee8aa",
  25318. "palegreen": "#98fb98",
  25319. "paleturquoise": "#afeeee",
  25320. "palevioletred": "#d87093",
  25321. "papayawhip": "#ffefd5",
  25322. "peachpuff": "#ffdab9",
  25323. "peru": "#cd853f",
  25324. "pink": "#ffc0cb",
  25325. "plum": "#dda0dd",
  25326. "powderblue": "#b0e0e6",
  25327. "purple": "#800080",
  25328. "rebeccapurple": "#663399",
  25329. "red": "#ff0000",
  25330. "rosybrown": "#bc8f8f",
  25331. "royalblue": "#4169e1",
  25332. "saddlebrown": "#8b4513",
  25333. "salmon": "#fa8072",
  25334. "sandybrown": "#f4a460",
  25335. "seagreen": "#2e8b57",
  25336. "seashell": "#fff5ee",
  25337. "sienna": "#a0522d",
  25338. "silver": "#c0c0c0",
  25339. "skyblue": "#87ceeb",
  25340. "slateblue": "#6a5acd",
  25341. "slategray": "#708090",
  25342. "snow": "#fffafa",
  25343. "springgreen": "#00ff7f",
  25344. "steelblue": "#4682b4",
  25345. "tan": "#d2b48c",
  25346. "teal": "#008080",
  25347. "thistle": "#d8bfd8",
  25348. "tomato": "#ff6347",
  25349. "turquoise": "#40e0d0",
  25350. "violet": "#ee82ee",
  25351. "wheat": "#f5deb3",
  25352. "white": "#ffffff",
  25353. "whitesmoke": "#f5f5f5",
  25354. "yellow": "#ffff00",
  25355. "yellowgreen": "#9acd32"
  25356. };
  25357. var getStyleValue = function getStyleValue(style) {
  25358. return style.split('-')[1];
  25359. };
  25360. var defaultUnitExportFn = function defaultUnitExportFn(unit) {
  25361. return unit + 'px';
  25362. };
  25363. var defaultUnitImportFn = function defaultUnitImportFn(unit) {
  25364. return unit.replace('px', '');
  25365. };
  25366. var ignoredNodeAttributes = ['style'];
  25367. var ignoredEntityNodeAttributes = ['style', 'href', 'target', 'alt', 'title', 'id', 'controls', 'autoplay', 'loop', 'poster'];
  25368. var spreadNodeAttributes = function spreadNodeAttributes(attributesObject) {
  25369. return Object.keys(attributesObject).reduce(function (attributeString, attributeName) {
  25370. return attributeString + " " + attributeName + "=\"" + attributesObject[attributeName] + "\"";
  25371. }, '').replace(/^\s$/, '');
  25372. };
  25373. var defaultFontFamilies = exports.defaultFontFamilies = [{
  25374. name: 'Araial',
  25375. family: 'Arial, Helvetica, sans-serif'
  25376. }, {
  25377. name: 'Georgia',
  25378. family: 'Georgia, serif'
  25379. }, {
  25380. name: 'Impact',
  25381. family: 'Impact, serif'
  25382. }, {
  25383. name: 'Monospace',
  25384. family: '"Courier New", Courier, monospace'
  25385. }, {
  25386. name: 'Tahoma',
  25387. family: "tahoma, arial, 'Hiragino Sans GB', 宋体, sans-serif"
  25388. }];
  25389. var getHexColor = exports.getHexColor = function getHexColor(color) {
  25390. color = color.replace('color:', '').replace(';', '').replace(' ', '');
  25391. if (/^#([0-9a-fA-F]{6}|[0-9a-fA-F]{3})$/.test(color)) {
  25392. return color;
  25393. } else if (namedColors[color]) {
  25394. return namedColors[color];
  25395. } else if (color.indexOf('rgb') === 0) {
  25396. var rgbArray = color.split(',');
  25397. var convertedColor = rgbArray.length < 3 ? null : '#' + [rgbArray[0], rgbArray[1], rgbArray[2]].map(function (x) {
  25398. var hex = parseInt(x.replace(/\D/g, ''), 10).toString(16);
  25399. return hex.length === 1 ? '0' + hex : hex;
  25400. }).join('');
  25401. return (/^#([0-9a-fA-F]{6}|[0-9a-fA-F]{3})$/.test(convertedColor) ? convertedColor : null
  25402. );
  25403. } else {
  25404. return null;
  25405. }
  25406. };
  25407. var blocks = exports.blocks = {
  25408. 'header-one': 'h1',
  25409. 'header-two': 'h2',
  25410. 'header-three': 'h3',
  25411. 'header-four': 'h4',
  25412. 'header-five': 'h5',
  25413. 'header-six': 'h6',
  25414. 'unstyled': 'p',
  25415. 'blockquote': 'blockquote'
  25416. };
  25417. var blockTypes = Object.keys(blocks);
  25418. var blockNames = blockTypes.map(function (key) {
  25419. return blocks[key];
  25420. });
  25421. var convertAtomicBlock = function convertAtomicBlock(block, contentState, blockNodeAttributes) {
  25422. if (!block || !block.key) {
  25423. return _react2.default.createElement("p", null);
  25424. }
  25425. var contentBlock = contentState.getBlockForKey(block.key);
  25426. var className = blockNodeAttributes.class,
  25427. nodeAttrAsProps = _objectWithoutProperties(blockNodeAttributes, ["class"]);
  25428. nodeAttrAsProps.className = className;
  25429. if (!contentBlock) {
  25430. return _react2.default.createElement("p", null);
  25431. }
  25432. var entityKey = contentBlock.getEntityAt(0);
  25433. if (!entityKey) {
  25434. return _react2.default.createElement("p", null);
  25435. }
  25436. var entity = contentState.getEntity(entityKey);
  25437. var mediaType = entity.getType().toLowerCase();
  25438. var _block$data = block.data,
  25439. float = _block$data.float,
  25440. alignment = _block$data.alignment;
  25441. var _entity$getData = entity.getData(),
  25442. url = _entity$getData.url,
  25443. link = _entity$getData.link,
  25444. link_target = _entity$getData.link_target,
  25445. width = _entity$getData.width,
  25446. height = _entity$getData.height,
  25447. meta = _entity$getData.meta;
  25448. if (mediaType === 'image') {
  25449. var imageWrapStyle = {};
  25450. var styledClassName = '';
  25451. if (float) {
  25452. imageWrapStyle.float = float;
  25453. styledClassName += ' float-' + float;
  25454. } else if (alignment) {
  25455. imageWrapStyle.textAlign = alignment;
  25456. styledClassName += ' align-' + alignment;
  25457. }
  25458. if (link) {
  25459. return _react2.default.createElement(
  25460. "div",
  25461. { className: "media-wrap image-wrap" + styledClassName, style: imageWrapStyle },
  25462. _react2.default.createElement(
  25463. "a",
  25464. { style: { display: 'inline-block' }, href: link, target: link_target },
  25465. _react2.default.createElement("img", _extends({}, nodeAttrAsProps, meta, { src: url, width: width, height: height, style: { width: width, height: height } }))
  25466. )
  25467. );
  25468. } else {
  25469. return _react2.default.createElement(
  25470. "div",
  25471. { className: "media-wrap image-wrap" + styledClassName, style: imageWrapStyle },
  25472. _react2.default.createElement("img", _extends({}, nodeAttrAsProps, meta, { src: url, width: width, height: height, style: { width: width, height: height } }))
  25473. );
  25474. }
  25475. } else if (mediaType === 'audio') {
  25476. return _react2.default.createElement(
  25477. "div",
  25478. { className: "media-wrap audio-wrap" },
  25479. _react2.default.createElement("audio", _extends({ controls: true }, nodeAttrAsProps, meta, { src: url }))
  25480. );
  25481. } else if (mediaType === 'video') {
  25482. return _react2.default.createElement(
  25483. "div",
  25484. { className: "media-wrap video-wrap" },
  25485. _react2.default.createElement("video", _extends({ controls: true }, nodeAttrAsProps, meta, { src: url, width: width, height: height }))
  25486. );
  25487. } else if (mediaType === 'embed') {
  25488. return _react2.default.createElement(
  25489. "div",
  25490. { className: "media-wrap embed-wrap" },
  25491. _react2.default.createElement("div", { dangerouslySetInnerHTML: { __html: url } })
  25492. );
  25493. } else if (mediaType === 'hr') {
  25494. return _react2.default.createElement("hr", null);
  25495. } else {
  25496. return _react2.default.createElement("p", null);
  25497. }
  25498. };
  25499. var entityToHTML = function entityToHTML(options) {
  25500. return function (entity, originalText) {
  25501. var entityExportFn = options.entityExportFn;
  25502. var entityType = entity.type.toLowerCase();
  25503. if (entityExportFn) {
  25504. var customOutput = entityExportFn(entity, originalText);
  25505. if (customOutput) {
  25506. return customOutput;
  25507. }
  25508. }
  25509. if (entityType === 'link') {
  25510. var _ref = entity.data.nodeAttributes || {},
  25511. className = _ref.class,
  25512. nodeAttrAsProps = _objectWithoutProperties(_ref, ["class"]);
  25513. nodeAttrAsProps.className = className;
  25514. return _react2.default.createElement("a", _extends({ href: entity.data.href, target: entity.data.target }, nodeAttrAsProps));
  25515. }
  25516. };
  25517. };
  25518. var styleToHTML = function styleToHTML(options) {
  25519. return function (style) {
  25520. var unitExportFn = options.unitExportFn || defaultUnitExportFn;
  25521. if (options.styleExportFn) {
  25522. var customOutput = options.styleExportFn(style, options);
  25523. if (customOutput) {
  25524. return customOutput;
  25525. }
  25526. }
  25527. style = style.toLowerCase();
  25528. if (style === 'strikethrough') {
  25529. return _react2.default.createElement("span", { style: { textDecoration: 'line-through' } });
  25530. } else if (style === 'superscript') {
  25531. return _react2.default.createElement("sup", null);
  25532. } else if (style === 'subscript') {
  25533. return _react2.default.createElement("sub", null);
  25534. } else if (style.indexOf('color-') === 0) {
  25535. return _react2.default.createElement("span", { style: { color: '#' + getStyleValue(style) } });
  25536. } else if (style.indexOf('bgcolor-') === 0) {
  25537. return _react2.default.createElement("span", { style: { backgroundColor: '#' + getStyleValue(style) } });
  25538. } else if (style.indexOf('fontsize-') === 0) {
  25539. return _react2.default.createElement("span", { style: { fontSize: unitExportFn(getStyleValue(style), 'font-size', 'html') } });
  25540. } else if (style.indexOf('lineheight-') === 0) {
  25541. return _react2.default.createElement("span", { style: { lineHeight: unitExportFn(getStyleValue(style), 'line-height', 'html') } });
  25542. } else if (style.indexOf('letterspacing-') === 0) {
  25543. return _react2.default.createElement("span", { style: { letterSpacing: unitExportFn(getStyleValue(style), 'letter-spacing', 'html') } });
  25544. } else if (style.indexOf('fontfamily-') === 0) {
  25545. var fontFamily = options.fontFamilies.find(function (item) {
  25546. return item.name.toLowerCase() === getStyleValue(style);
  25547. });
  25548. if (!fontFamily) return;
  25549. return _react2.default.createElement("span", { style: { fontFamily: fontFamily.family } });
  25550. }
  25551. };
  25552. };
  25553. var blockToHTML = function blockToHTML(options) {
  25554. return function (block) {
  25555. var blockExportFn = options.blockExportFn,
  25556. contentState = options.contentState;
  25557. if (blockExportFn) {
  25558. var customOutput = blockExportFn(contentState, block);
  25559. if (customOutput) {
  25560. return customOutput;
  25561. }
  25562. }
  25563. var blockStyle = '';
  25564. var blockType = block.type.toLowerCase();
  25565. var _block$data2 = block.data,
  25566. textAlign = _block$data2.textAlign,
  25567. textIndent = _block$data2.textIndent,
  25568. _block$data2$nodeAttr = _block$data2.nodeAttributes,
  25569. nodeAttributes = _block$data2$nodeAttr === undefined ? {} : _block$data2$nodeAttr;
  25570. var attributeString = spreadNodeAttributes(nodeAttributes);
  25571. if (textAlign || textIndent) {
  25572. blockStyle = ' style="';
  25573. if (textAlign) {
  25574. blockStyle += "text-align:" + textAlign + ";";
  25575. }
  25576. if (textIndent && !isNaN(textIndent) && textIndent > 0) {
  25577. blockStyle += "text-indent:" + textIndent * 2 + "em;";
  25578. }
  25579. blockStyle += '"';
  25580. }
  25581. if (blockType === 'atomic') {
  25582. return convertAtomicBlock(block, contentState, nodeAttributes);
  25583. } else if (blockType === 'code-block') {
  25584. var previousBlock = contentState.getBlockBefore(block.key);
  25585. var nextBlock = contentState.getBlockAfter(block.key);
  25586. var previousBlockType = previousBlock && previousBlock.getType();
  25587. var nextBlockType = nextBlock && nextBlock.getType();
  25588. var start = '';
  25589. var end = '';
  25590. if (previousBlockType !== 'code-block') {
  25591. start = "<pre" + attributeString + "><code>";
  25592. } else {
  25593. start = '';
  25594. }
  25595. if (nextBlockType !== 'code-block') {
  25596. end = '</code></pre>';
  25597. } else {
  25598. end = '<br/>';
  25599. }
  25600. return { start: start, end: end };
  25601. } else if (blocks[blockType]) {
  25602. return {
  25603. start: "<" + blocks[blockType] + blockStyle + attributeString + ">",
  25604. end: "</" + blocks[blockType] + ">"
  25605. };
  25606. } else if (blockType === 'unordered-list-item') {
  25607. return {
  25608. start: "<li" + blockStyle + attributeString + ">",
  25609. end: '</li>',
  25610. nest: _react2.default.createElement("ul", null)
  25611. };
  25612. } else if (blockType === 'ordered-list-item') {
  25613. return {
  25614. start: "<li" + blockStyle + attributeString + ">",
  25615. end: '</li>',
  25616. nest: _react2.default.createElement("ol", null)
  25617. };
  25618. }
  25619. };
  25620. };
  25621. var htmlToStyle = function htmlToStyle(options, source) {
  25622. return function (nodeName, node, currentStyle) {
  25623. if (!node || !node.style) {
  25624. return currentStyle;
  25625. }
  25626. var unitImportFn = options.unitImportFn || defaultUnitImportFn;
  25627. var newStyle = currentStyle;
  25628. [].forEach.call(node.style, function (style) {
  25629. if (nodeName === 'span' && style === 'color') {
  25630. var color = getHexColor(node.style.color);
  25631. newStyle = color ? newStyle.add('COLOR-' + color.replace('#', '').toUpperCase()) : newStyle;
  25632. } else if (nodeName === 'span' && style === 'background-color') {
  25633. var _color = getHexColor(node.style.backgroundColor);
  25634. newStyle = _color ? newStyle.add('BGCOLOR-' + _color.replace('#', '').toUpperCase()) : newStyle;
  25635. } else if (nodeName === 'span' && style === 'font-size') {
  25636. newStyle = newStyle.add('FONTSIZE-' + unitImportFn(node.style.fontSize, 'font-size', source));
  25637. } else if (nodeName === 'span' && style === 'line-height' && !isNaN(parseFloat(node.style.lineHeight, 10))) {
  25638. newStyle = newStyle.add('LINEHEIGHT-' + unitImportFn(node.style.lineHeight, 'line-height', source));
  25639. } else if (nodeName === 'span' && style === 'letter-spacing' && !isNaN(parseFloat(node.style.letterSpacing, 10))) {
  25640. newStyle = newStyle.add('LETTERSPACING-' + unitImportFn(node.style.letterSpacing, 'letter-spacing', source));
  25641. } else if (nodeName === 'span' && style === 'text-decoration') {
  25642. if (node.style.textDecoration === 'line-through') {
  25643. newStyle = newStyle.add('STRIKETHROUGH');
  25644. } else if (node.style.textDecoration === 'underline') {
  25645. newStyle = newStyle.add('UNDERLINE');
  25646. }
  25647. } else if (nodeName === 'span' && style === 'font-family') {
  25648. var fontFamily = options.fontFamilies.find(function (item) {
  25649. return item.family.toLowerCase() === node.style.fontFamily.toLowerCase();
  25650. });
  25651. if (!fontFamily) return;
  25652. newStyle = newStyle.add('FONTFAMILY-' + fontFamily.name.toUpperCase());
  25653. }
  25654. });
  25655. if (nodeName === 'sup') {
  25656. newStyle = newStyle.add('SUPERSCRIPT');
  25657. } else if (nodeName === 'sub') {
  25658. newStyle = newStyle.add('SUBSCRIPT');
  25659. }
  25660. options.styleImportFn && (newStyle = options.styleImportFn(nodeName, node, newStyle, source) || newStyle);
  25661. return newStyle;
  25662. };
  25663. };
  25664. var htmlToEntity = function htmlToEntity(options, source) {
  25665. return function (nodeName, node, createEntity) {
  25666. if (options && options.entityImportFn) {
  25667. var customInput = options.entityImportFn(nodeName, node, createEntity, source);
  25668. if (customInput) {
  25669. return customInput;
  25670. }
  25671. }
  25672. nodeName = nodeName.toLowerCase();
  25673. var alt = node.alt,
  25674. title = node.title,
  25675. id = node.id,
  25676. controls = node.controls,
  25677. autoplay = node.autoplay,
  25678. loop = node.loop,
  25679. poster = node.poster;
  25680. var meta = {};
  25681. var nodeAttributes = {};
  25682. id && (meta.id = id);
  25683. alt && (meta.alt = alt);
  25684. title && (meta.title = title);
  25685. controls && (meta.controls = controls);
  25686. autoplay && (meta.autoPlay = autoplay);
  25687. loop && (meta.loop = loop);
  25688. poster && (meta.poster = poster);
  25689. node.attributes && Object.keys(node.attributes).forEach(function (key) {
  25690. var attr = node.attributes[key];
  25691. ignoredEntityNodeAttributes.indexOf(attr.name) === -1 && (nodeAttributes[attr.name] = attr.value);
  25692. });
  25693. if (nodeName === 'a' && !node.querySelectorAll('img').length) {
  25694. var href = node.getAttribute('href');
  25695. var _target = node.getAttribute('target');
  25696. return createEntity('LINK', 'MUTABLE', { href: href, target: _target, nodeAttributes: nodeAttributes });
  25697. } else if (nodeName === 'audio') {
  25698. return createEntity('AUDIO', 'IMMUTABLE', { url: node.getAttribute('src'), meta: meta, nodeAttributes: nodeAttributes });
  25699. } else if (nodeName === 'video') {
  25700. return createEntity('VIDEO', 'IMMUTABLE', { url: node.getAttribute('src'), meta: meta, nodeAttributes: nodeAttributes });
  25701. } else if (nodeName === 'img') {
  25702. var parentNode = node.parentNode;
  25703. var entityData = { meta: meta };
  25704. var _node$style = node.style,
  25705. width = _node$style.width,
  25706. height = _node$style.height;
  25707. entityData.url = node.getAttribute('src');
  25708. width && (entityData.width = width);
  25709. height && (entityData.height = height);
  25710. if (parentNode.nodeName.toLowerCase() === 'a') {
  25711. entityData.link = parentNode.getAttribute('href');
  25712. entityData.link_target = parentNode.getAttribute('target');
  25713. }
  25714. return createEntity('IMAGE', 'IMMUTABLE', entityData);
  25715. } else if (nodeName === 'hr') {
  25716. return createEntity('HR', 'IMMUTABLE', {});
  25717. } else if (node.parentNode && node.parentNode.classList.contains('embed-wrap')) {
  25718. var embedContent = node.innerHTML || node.outerHTML;
  25719. if (embedContent) {
  25720. return createEntity('EMBED', 'IMMUTABLE', {
  25721. url: embedContent
  25722. });
  25723. }
  25724. }
  25725. };
  25726. };
  25727. var htmlToBlock = function htmlToBlock(options, source) {
  25728. return function (nodeName, node) {
  25729. if (options && options.blockImportFn) {
  25730. var customInput = options.blockImportFn(nodeName, node, source);
  25731. if (customInput) {
  25732. return customInput;
  25733. }
  25734. }
  25735. var nodeAttributes = {};
  25736. var nodeStyle = node.style || {};
  25737. node.attributes && Object.keys(node.attributes).forEach(function (key) {
  25738. var attr = node.attributes[key];
  25739. ignoredNodeAttributes.indexOf(attr.name) === -1 && (nodeAttributes[attr.name] = attr.value);
  25740. });
  25741. if (node.classList && node.classList.contains('media-wrap')) {
  25742. return {
  25743. type: 'atomic',
  25744. data: {
  25745. nodeAttributes: nodeAttributes,
  25746. float: nodeStyle.float,
  25747. alignment: nodeStyle.textAlign
  25748. }
  25749. };
  25750. } else if (nodeName === 'img') {
  25751. return {
  25752. type: 'atomic',
  25753. data: {
  25754. nodeAttributes: nodeAttributes,
  25755. float: nodeStyle.float,
  25756. alignment: nodeStyle.textAlign
  25757. }
  25758. };
  25759. } else if (nodeName === 'hr') {
  25760. return {
  25761. type: 'atomic',
  25762. data: { nodeAttributes: nodeAttributes }
  25763. };
  25764. } else if (nodeName === 'pre') {
  25765. node.innerHTML = node.innerHTML.replace(/<code(.*?)>/g, '').replace(/<\/code>/g, '');
  25766. return {
  25767. type: 'code-block',
  25768. data: { nodeAttributes: nodeAttributes }
  25769. };
  25770. } else if (blockNames.indexOf(nodeName) !== -1) {
  25771. var blockData = { nodeAttributes: nodeAttributes };
  25772. if (nodeStyle.textAlign) {
  25773. blockData.textAlign = nodeStyle.textAlign;
  25774. }
  25775. if (nodeStyle.textIndent) {
  25776. blockData.textIndent = /^\d+em$/.test(nodeStyle.textIndent) ? Math.ceil(parseInt(nodeStyle.textIndent, 10) / 2) : 1;
  25777. }
  25778. return {
  25779. type: blockTypes[blockNames.indexOf(nodeName)],
  25780. data: blockData
  25781. };
  25782. }
  25783. };
  25784. };
  25785. var getToHTMLConfig = exports.getToHTMLConfig = function getToHTMLConfig(options) {
  25786. return {
  25787. styleToHTML: styleToHTML(options),
  25788. entityToHTML: entityToHTML(options),
  25789. blockToHTML: blockToHTML(options)
  25790. };
  25791. };
  25792. var getFromHTMLConfig = exports.getFromHTMLConfig = function getFromHTMLConfig(options) {
  25793. var source = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 'unknow';
  25794. return {
  25795. htmlToStyle: htmlToStyle(options, source),
  25796. htmlToEntity: htmlToEntity(options, source),
  25797. htmlToBlock: htmlToBlock(options, source)
  25798. };
  25799. };
  25800. });
  25801. unwrapExports(configs);
  25802. var configs_1 = configs.getFromHTMLConfig;
  25803. var configs_2 = configs.getToHTMLConfig;
  25804. var configs_3 = configs.blocks;
  25805. var configs_4 = configs.getHexColor;
  25806. var configs_5 = configs.defaultFontFamilies;
  25807. var configs_6 = configs.namedColors;
  25808. var dist = createCommonjsModule(function (module, exports) {
  25809. Object.defineProperty(exports, "__esModule", {
  25810. value: true
  25811. });
  25812. exports.convertRawToEditorState = exports.convertEditorStateToRaw = exports.convertHTMLToEditorState = exports.convertEditorStateToHTML = exports.convertHTMLToRaw = exports.convertRawToHTML = undefined;
  25813. var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };
  25814. var defaultConvertOptions = {
  25815. fontFamilies: configs.defaultFontFamilies
  25816. };
  25817. var convertRawToHTML = exports.convertRawToHTML = function convertRawToHTML(rawContent, options) {
  25818. options = _extends({}, defaultConvertOptions, options);
  25819. try {
  25820. var contentState = (0, Draft.convertFromRaw)(rawContent);
  25821. options.contentState = contentState;
  25822. return (0, lib.convertToHTML)((0, configs.getToHTMLConfig)(options))(contentState);
  25823. } catch (error) {
  25824. console.warn(error);
  25825. return '';
  25826. }
  25827. };
  25828. var convertHTMLToRaw = exports.convertHTMLToRaw = function convertHTMLToRaw(HTMLString, options, source) {
  25829. options = _extends({}, defaultConvertOptions, options);
  25830. try {
  25831. var contentState = (0, lib.convertFromHTML)((0, configs.getFromHTMLConfig)(options, source))(HTMLString);
  25832. return (0, Draft.convertToRaw)(contentState);
  25833. } catch (error) {
  25834. console.warn(error);
  25835. return {};
  25836. }
  25837. };
  25838. var convertEditorStateToHTML = exports.convertEditorStateToHTML = function convertEditorStateToHTML(editorState, options) {
  25839. options = _extends({}, defaultConvertOptions, options);
  25840. try {
  25841. var contentState = editorState.getCurrentContent();
  25842. options.contentState = contentState;
  25843. return (0, lib.convertToHTML)((0, configs.getToHTMLConfig)(options))(contentState);
  25844. } catch (error) {
  25845. console.warn(error);
  25846. return '';
  25847. }
  25848. };
  25849. var convertHTMLToEditorState = exports.convertHTMLToEditorState = function convertHTMLToEditorState(HTMLString, editorDecorators, options, source) {
  25850. options = _extends({}, defaultConvertOptions, options);
  25851. try {
  25852. return Draft.EditorState.createWithContent((0, lib.convertFromHTML)((0, configs.getFromHTMLConfig)(options, source))(HTMLString), editorDecorators);
  25853. } catch (error) {
  25854. console.warn(error);
  25855. return Draft.EditorState.createEmpty(editorDecorators);
  25856. }
  25857. };
  25858. var convertEditorStateToRaw = exports.convertEditorStateToRaw = function convertEditorStateToRaw(editorState) {
  25859. return (0, Draft.convertToRaw)(editorState.getCurrentContent());
  25860. };
  25861. var convertRawToEditorState = exports.convertRawToEditorState = function convertRawToEditorState(rawContent, editorDecorators) {
  25862. try {
  25863. return Draft.EditorState.createWithContent((0, Draft.convertFromRaw)(rawContent), editorDecorators);
  25864. } catch (error) {
  25865. console.warn(error);
  25866. return Draft.EditorState.createEmpty(editorDecorators);
  25867. }
  25868. };
  25869. });
  25870. unwrapExports(dist);
  25871. var dist_1 = dist.convertRawToEditorState;
  25872. var dist_2 = dist.convertEditorStateToRaw;
  25873. var dist_3 = dist.convertHTMLToEditorState;
  25874. var dist_4 = dist.convertEditorStateToHTML;
  25875. var dist_5 = dist.convertHTMLToRaw;
  25876. var dist_6 = dist.convertRawToHTML;
  25877. var content = createCommonjsModule(function (module, exports) {
  25878. Object.defineProperty(exports, "__esModule", {
  25879. value: true
  25880. });
  25881. exports.redo = exports.undo = exports.handleKeyCommand = exports.clear = exports.setMediaPosition = exports.removeMedia = exports.setMediaData = exports.insertMedias = exports.insertHorizontalLine = exports.insertAtomicBlock = exports.insertHTML = exports.insertText = exports.toggleSelectionLetterSpacing = exports.toggleSelectionFontFamily = exports.toggleSelectionLineHeight = exports.toggleSelectionFontSize = exports.toggleSelectionBackgroundColor = exports.toggleSelectionColor = exports.decreaseSelectionIndent = exports.increaseSelectionIndent = exports.toggleSelectionIndent = exports.toggleSelectionAlignment = exports.removeSelectionInlineStyles = exports.toggleSelectionInlineStyle = exports.selectionHasInlineStyle = exports.getSelectionInlineStyle = exports.toggleSelectionLink = exports.toggleSelectionEntity = exports.getSelectionEntityData = exports.getSelectionEntityType = exports.toggleSelectionBlockType = exports.getSelectionText = exports.getSelectionBlockType = exports.getSelectionBlockData = exports.setSelectionBlockData = exports.getSelectedBlocks = exports.updateEachCharacterOfSelection = exports.getSelectionBlock = exports.removeBlock = exports.selectNextBlock = exports.selectBlock = exports.selectionContainsStrictBlock = exports.selectionContainsBlockType = exports.isSelectionCollapsed = exports.createEditorState = exports.createEmptyEditorState = exports.isEditorState = exports.registerStrictBlockType = undefined;
  25882. var _immutable2 = _interopRequireDefault(immutable$1);
  25883. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  25884. var strictBlockTypes = ['atomic'];
  25885. var registerStrictBlockType = exports.registerStrictBlockType = function registerStrictBlockType(blockType) {
  25886. strictBlockTypes.indexOf(blockType) === -1 && strictBlockTypes.push(blockType);
  25887. };
  25888. var isEditorState = exports.isEditorState = function isEditorState(editorState) {
  25889. return editorState instanceof Draft.EditorState;
  25890. };
  25891. var createEmptyEditorState = exports.createEmptyEditorState = function createEmptyEditorState(editorDecorators) {
  25892. return Draft.EditorState.createEmpty(editorDecorators);
  25893. };
  25894. var createEditorState = exports.createEditorState = function createEditorState(contentState, editorDecorators) {
  25895. return Draft.EditorState.createWithContent(contentState, editorDecorators);
  25896. };
  25897. var isSelectionCollapsed = exports.isSelectionCollapsed = function isSelectionCollapsed(editorState) {
  25898. return editorState.getSelection().isCollapsed();
  25899. };
  25900. var selectionContainsBlockType = exports.selectionContainsBlockType = function selectionContainsBlockType(editorState, blockType) {
  25901. return getSelectedBlocks(editorState).find(function (block) {
  25902. return block.getType() === blockType;
  25903. });
  25904. };
  25905. var selectionContainsStrictBlock = exports.selectionContainsStrictBlock = function selectionContainsStrictBlock(editorState) {
  25906. return getSelectedBlocks(editorState).find(function (block) {
  25907. return ~strictBlockTypes.indexOf(block.getType());
  25908. });
  25909. };
  25910. var selectBlock = exports.selectBlock = function selectBlock(editorState, block) {
  25911. var blockKey = block.getKey();
  25912. return Draft.EditorState.forceSelection(editorState, new Draft.SelectionState({
  25913. anchorKey: blockKey,
  25914. anchorOffset: 0,
  25915. focusKey: blockKey,
  25916. focusOffset: block.getLength()
  25917. }));
  25918. };
  25919. var selectNextBlock = exports.selectNextBlock = function selectNextBlock(editorState, block) {
  25920. var nextBlock = editorState.getCurrentContent().getBlockAfter(block.getKey());
  25921. return nextBlock ? selectBlock(editorState, nextBlock) : editorState;
  25922. };
  25923. var removeBlock = exports.removeBlock = function removeBlock(editorState, block) {
  25924. var lastSelection = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : null;
  25925. var nextContentState = void 0,
  25926. nextEditorState = void 0;
  25927. var blockKey = block.getKey();
  25928. nextContentState = Draft.Modifier.removeRange(editorState.getCurrentContent(), new Draft.SelectionState({
  25929. anchorKey: blockKey,
  25930. anchorOffset: 0,
  25931. focusKey: blockKey,
  25932. focusOffset: block.getLength()
  25933. }), 'backward');
  25934. nextContentState = Draft.Modifier.setBlockType(nextContentState, nextContentState.getSelectionAfter(), 'unstyled');
  25935. nextEditorState = Draft.EditorState.push(editorState, nextContentState, 'remove-range');
  25936. return Draft.EditorState.forceSelection(nextEditorState, lastSelection || nextContentState.getSelectionAfter());
  25937. };
  25938. var getSelectionBlock = exports.getSelectionBlock = function getSelectionBlock(editorState) {
  25939. return editorState.getCurrentContent().getBlockForKey(editorState.getSelection().getAnchorKey());
  25940. };
  25941. var updateEachCharacterOfSelection = exports.updateEachCharacterOfSelection = function updateEachCharacterOfSelection(editorState, callback) {
  25942. var selectionState = editorState.getSelection();
  25943. var contentState = editorState.getCurrentContent();
  25944. var contentBlocks = contentState.getBlockMap();
  25945. var selectedBlocks = getSelectedBlocks(editorState);
  25946. if (selectedBlocks.length === 0) {
  25947. return editorState;
  25948. }
  25949. var startKey = selectionState.getStartKey();
  25950. var startOffset = selectionState.getStartOffset();
  25951. var endKey = selectionState.getEndKey();
  25952. var endOffset = selectionState.getEndOffset();
  25953. var nextContentBlocks = contentBlocks.map(function (block) {
  25954. if (selectedBlocks.indexOf(block) === -1) {
  25955. return block;
  25956. }
  25957. var blockKey = block.getKey();
  25958. var charactersList = block.getCharacterList();
  25959. var nextCharactersList = null;
  25960. if (blockKey === startKey && blockKey === endKey) {
  25961. nextCharactersList = charactersList.map(function (character, index) {
  25962. if (index >= startOffset && index < endOffset) {
  25963. return callback(character);
  25964. }
  25965. return character;
  25966. });
  25967. } else if (blockKey === startKey) {
  25968. nextCharactersList = charactersList.map(function (character, index) {
  25969. if (index >= startOffset) {
  25970. return callback(character);
  25971. }
  25972. return character;
  25973. });
  25974. } else if (blockKey === endKey) {
  25975. nextCharactersList = charactersList.map(function (character, index) {
  25976. if (index < endOffset) {
  25977. return callback(character);
  25978. }
  25979. return character;
  25980. });
  25981. } else {
  25982. nextCharactersList = charactersList.map(function (character) {
  25983. return callback(character);
  25984. });
  25985. }
  25986. return block.merge({
  25987. 'characterList': nextCharactersList
  25988. });
  25989. });
  25990. return Draft.EditorState.push(editorState, contentState.merge({
  25991. blockMap: nextContentBlocks,
  25992. selectionBefore: selectionState,
  25993. selectionAfter: selectionState
  25994. }), 'update-selection-character-list');
  25995. };
  25996. var getSelectedBlocks = exports.getSelectedBlocks = function getSelectedBlocks(editorState) {
  25997. var selectionState = editorState.getSelection();
  25998. var contentState = editorState.getCurrentContent();
  25999. var startKey = selectionState.getStartKey();
  26000. var endKey = selectionState.getEndKey();
  26001. var isSameBlock = startKey === endKey;
  26002. var startingBlock = contentState.getBlockForKey(startKey);
  26003. var selectedBlocks = [startingBlock];
  26004. if (!isSameBlock) {
  26005. var blockKey = startKey;
  26006. while (blockKey !== endKey) {
  26007. var nextBlock = contentState.getBlockAfter(blockKey);
  26008. selectedBlocks.push(nextBlock);
  26009. blockKey = nextBlock.getKey();
  26010. }
  26011. }
  26012. return selectedBlocks;
  26013. };
  26014. var setSelectionBlockData = exports.setSelectionBlockData = function setSelectionBlockData(editorState, blockData, override) {
  26015. var newBlockData = override ? blockData : Object.assign({}, getSelectionBlockData(editorState).toJS(), blockData);
  26016. Object.keys(newBlockData).forEach(function (key) {
  26017. if (newBlockData.hasOwnProperty(key) && newBlockData[key] === undefined) {
  26018. delete newBlockData[key];
  26019. }
  26020. });
  26021. return (0, draftjsUtils.setBlockData)(editorState, newBlockData);
  26022. };
  26023. var getSelectionBlockData = exports.getSelectionBlockData = function getSelectionBlockData(editorState, name) {
  26024. var blockData = getSelectionBlock(editorState).getData();
  26025. return name ? blockData.get(name) : blockData;
  26026. };
  26027. var getSelectionBlockType = exports.getSelectionBlockType = function getSelectionBlockType(editorState) {
  26028. return getSelectionBlock(editorState).getType();
  26029. };
  26030. var getSelectionText = exports.getSelectionText = function getSelectionText(editorState) {
  26031. var selectionState = editorState.getSelection();
  26032. var contentState = editorState.getCurrentContent();
  26033. if (selectionState.isCollapsed() || getSelectionBlockType(editorState) === 'atomic') {
  26034. return '';
  26035. }
  26036. var anchorKey = selectionState.getAnchorKey();
  26037. var currentContentBlock = contentState.getBlockForKey(anchorKey);
  26038. var start = selectionState.getStartOffset();
  26039. var end = selectionState.getEndOffset();
  26040. return currentContentBlock.getText().slice(start, end);
  26041. };
  26042. var toggleSelectionBlockType = exports.toggleSelectionBlockType = function toggleSelectionBlockType(editorState, blockType) {
  26043. if (selectionContainsStrictBlock(editorState)) {
  26044. return editorState;
  26045. }
  26046. return Draft.RichUtils.toggleBlockType(editorState, blockType);
  26047. };
  26048. var getSelectionEntityType = exports.getSelectionEntityType = function getSelectionEntityType(editorState) {
  26049. var entityKey = (0, draftjsUtils.getSelectionEntity)(editorState);
  26050. if (entityKey) {
  26051. var entity = editorState.getCurrentContent().getEntity(entityKey);
  26052. return entity ? entity.get('type') : null;
  26053. }
  26054. return null;
  26055. };
  26056. var getSelectionEntityData = exports.getSelectionEntityData = function getSelectionEntityData(editorState, type) {
  26057. var entityKey = (0, draftjsUtils.getSelectionEntity)(editorState);
  26058. if (entityKey) {
  26059. var entity = editorState.getCurrentContent().getEntity(entityKey);
  26060. if (entity && entity.get('type') === type) {
  26061. return entity.getData();
  26062. } else {
  26063. return {};
  26064. }
  26065. } else {
  26066. return {};
  26067. }
  26068. };
  26069. var toggleSelectionEntity = exports.toggleSelectionEntity = function toggleSelectionEntity(editorState, entity) {
  26070. var contentState = editorState.getCurrentContent();
  26071. var selectionState = editorState.getSelection();
  26072. if (selectionState.isCollapsed() || getSelectionBlockType(editorState) === 'atomic') {
  26073. return editorState;
  26074. }
  26075. if (!entity || !entity.type || getSelectionEntityType(editorState) === entity.type) {
  26076. return Draft.EditorState.push(editorState, Draft.Modifier.applyEntity(contentState, selectionState, null), 'apply-entity');
  26077. }
  26078. try {
  26079. var nextContentState = contentState.createEntity(entity.type, entity.mutability, entity.data);
  26080. var entityKey = nextContentState.getLastCreatedEntityKey();
  26081. var nextEditorState = Draft.EditorState.set(editorState, {
  26082. currentContent: nextContentState
  26083. });
  26084. return Draft.EditorState.push(nextEditorState, Draft.Modifier.applyEntity(nextContentState, selectionState, entityKey), 'apply-entity');
  26085. } catch (error) {
  26086. console.warn(error);
  26087. return editorState;
  26088. }
  26089. };
  26090. var toggleSelectionLink = exports.toggleSelectionLink = function toggleSelectionLink(editorState, href, target) {
  26091. var contentState = editorState.getCurrentContent();
  26092. var selectionState = editorState.getSelection();
  26093. var entityData = { href: href, target: target };
  26094. if (selectionState.isCollapsed() || getSelectionBlockType(editorState) === 'atomic') {
  26095. return editorState;
  26096. }
  26097. if (href === false) {
  26098. return Draft.RichUtils.toggleLink(editorState, selectionState, null);
  26099. }
  26100. if (href === null) {
  26101. delete entityData.href;
  26102. }
  26103. try {
  26104. var nextContentState = contentState.createEntity('LINK', 'MUTABLE', entityData);
  26105. var entityKey = nextContentState.getLastCreatedEntityKey();
  26106. var nextEditorState = Draft.EditorState.set(editorState, {
  26107. currentContent: nextContentState
  26108. });
  26109. nextEditorState = Draft.RichUtils.toggleLink(nextEditorState, selectionState, entityKey);
  26110. nextEditorState = Draft.EditorState.forceSelection(nextEditorState, selectionState.merge({
  26111. anchorOffset: selectionState.getEndOffset(),
  26112. focusOffset: selectionState.getEndOffset()
  26113. }));
  26114. nextEditorState = Draft.EditorState.push(nextEditorState, Draft.Modifier.insertText(nextEditorState.getCurrentContent(), nextEditorState.getSelection(), ''), 'insert-text');
  26115. return nextEditorState;
  26116. } catch (error) {
  26117. console.warn(error);
  26118. return editorState;
  26119. }
  26120. };
  26121. var getSelectionInlineStyle = exports.getSelectionInlineStyle = function getSelectionInlineStyle(editorState) {
  26122. return editorState.getCurrentInlineStyle();
  26123. };
  26124. var selectionHasInlineStyle = exports.selectionHasInlineStyle = function selectionHasInlineStyle(editorState, style) {
  26125. return getSelectionInlineStyle(editorState).has(style.toUpperCase());
  26126. };
  26127. var toggleSelectionInlineStyle = exports.toggleSelectionInlineStyle = function toggleSelectionInlineStyle(editorState, style) {
  26128. var prefix = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : '';
  26129. var nextEditorState = editorState;
  26130. style = prefix + style.toUpperCase();
  26131. if (prefix) {
  26132. nextEditorState = updateEachCharacterOfSelection(nextEditorState, function (characterMetadata) {
  26133. return characterMetadata.toJS().style.reduce(function (characterMetadata, characterStyle) {
  26134. if (characterStyle.indexOf(prefix) === 0 && style !== characterStyle) {
  26135. return Draft.CharacterMetadata.removeStyle(characterMetadata, characterStyle);
  26136. } else {
  26137. return characterMetadata;
  26138. }
  26139. }, characterMetadata);
  26140. });
  26141. }
  26142. return Draft.RichUtils.toggleInlineStyle(nextEditorState, style);
  26143. };
  26144. var removeSelectionInlineStyles = exports.removeSelectionInlineStyles = function removeSelectionInlineStyles(editorState) {
  26145. return updateEachCharacterOfSelection(editorState, function (characterMetadata) {
  26146. return characterMetadata.merge({
  26147. style: _immutable2.default.OrderedSet([])
  26148. });
  26149. });
  26150. };
  26151. var toggleSelectionAlignment = exports.toggleSelectionAlignment = function toggleSelectionAlignment(editorState, alignment) {
  26152. return setSelectionBlockData(editorState, {
  26153. textAlign: getSelectionBlockData(editorState, 'textAlign') !== alignment ? alignment : undefined
  26154. });
  26155. };
  26156. var toggleSelectionIndent = exports.toggleSelectionIndent = function toggleSelectionIndent(editorState, textIndent) {
  26157. var maxIndent = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 6;
  26158. return textIndent < 0 || textIndent > maxIndent || isNaN(textIndent) ? editorState : setSelectionBlockData(editorState, {
  26159. textIndent: textIndent || undefined
  26160. });
  26161. };
  26162. var increaseSelectionIndent = exports.increaseSelectionIndent = function increaseSelectionIndent(editorState) {
  26163. var maxIndent = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 6;
  26164. var currentIndent = getSelectionBlockData(editorState, 'textIndent') || 0;
  26165. return toggleSelectionIndent(editorState, currentIndent + 1, maxIndent);
  26166. };
  26167. var decreaseSelectionIndent = exports.decreaseSelectionIndent = function decreaseSelectionIndent(editorState) {
  26168. var currentIndent = getSelectionBlockData(editorState, 'textIndent') || 0;
  26169. return toggleSelectionIndent(editorState, currentIndent - 1);
  26170. };
  26171. var toggleSelectionColor = exports.toggleSelectionColor = function toggleSelectionColor(editorState, color) {
  26172. return toggleSelectionInlineStyle(editorState, color.replace('#', ''), 'COLOR-');
  26173. };
  26174. var toggleSelectionBackgroundColor = exports.toggleSelectionBackgroundColor = function toggleSelectionBackgroundColor(editorState, color) {
  26175. return toggleSelectionInlineStyle(editorState, color.replace('#', ''), 'BGCOLOR-');
  26176. };
  26177. var toggleSelectionFontSize = exports.toggleSelectionFontSize = function toggleSelectionFontSize(editorState, fontSize) {
  26178. return toggleSelectionInlineStyle(editorState, fontSize, 'FONTSIZE-');
  26179. };
  26180. var toggleSelectionLineHeight = exports.toggleSelectionLineHeight = function toggleSelectionLineHeight(editorState, lineHeight) {
  26181. return toggleSelectionInlineStyle(editorState, lineHeight, 'LINEHEIGHT-');
  26182. };
  26183. var toggleSelectionFontFamily = exports.toggleSelectionFontFamily = function toggleSelectionFontFamily(editorState, fontFamily) {
  26184. return toggleSelectionInlineStyle(editorState, fontFamily, 'FONTFAMILY-');
  26185. };
  26186. var toggleSelectionLetterSpacing = exports.toggleSelectionLetterSpacing = function toggleSelectionLetterSpacing(editorState, letterSpacing) {
  26187. return toggleSelectionInlineStyle(editorState, letterSpacing, 'LETTERSPACING-');
  26188. };
  26189. var insertText = exports.insertText = function insertText(editorState, text, inlineStyle, entity) {
  26190. var selectionState = editorState.getSelection();
  26191. var currentSelectedBlockType = getSelectionBlockType(editorState);
  26192. if (currentSelectedBlockType === 'atomic') {
  26193. return editorState;
  26194. }
  26195. var entityKey = void 0;
  26196. var contentState = editorState.getCurrentContent();
  26197. if (entity && entity.type) {
  26198. contentState = contentState.createEntity(entity.type, entity.mutability || 'MUTABLE', entity.data || entityData);
  26199. entityKey = contentState.getLastCreatedEntityKey();
  26200. }
  26201. if (!selectionState.isCollapsed()) {
  26202. return Draft.EditorState.push(editorState, Draft.Modifier.replaceText(contentState, selectionState, text, inlineStyle, entityKey), 'replace-text');
  26203. } else {
  26204. return Draft.EditorState.push(editorState, Draft.Modifier.insertText(contentState, selectionState, text, inlineStyle, entityKey), 'insert-text');
  26205. }
  26206. };
  26207. var insertHTML = exports.insertHTML = function insertHTML(editorState, htmlString, source) {
  26208. if (!htmlString) {
  26209. return editorState;
  26210. }
  26211. var selectionState = editorState.getSelection();
  26212. var contentState = editorState.getCurrentContent();
  26213. var options = editorState.convertOptions || {};
  26214. try {
  26215. var _convertFromRaw = (0, Draft.convertFromRaw)((0, dist.convertHTMLToRaw)(htmlString, options, source)),
  26216. blockMap = _convertFromRaw.blockMap;
  26217. return Draft.EditorState.push(editorState, Draft.Modifier.replaceWithFragment(contentState, selectionState, blockMap), 'insert-fragment');
  26218. } catch (error) {
  26219. console.warn(error);
  26220. return editorState;
  26221. }
  26222. };
  26223. var insertAtomicBlock = exports.insertAtomicBlock = function insertAtomicBlock(editorState, type) {
  26224. var immutable = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : true;
  26225. var data = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : {};
  26226. if (selectionContainsStrictBlock(editorState)) {
  26227. return insertAtomicBlock(selectNextBlock(editorState, getSelectionBlock(editorState)), type, immutable, data);
  26228. }
  26229. var selectionState = editorState.getSelection();
  26230. var contentState = editorState.getCurrentContent();
  26231. if (!selectionState.isCollapsed() || getSelectionBlockType(editorState) === 'atomic') {
  26232. return editorState;
  26233. }
  26234. var contentStateWithEntity = contentState.createEntity(type, immutable ? 'IMMUTABLE' : 'MUTABLE', data);
  26235. var entityKey = contentStateWithEntity.getLastCreatedEntityKey();
  26236. var newEditorState = Draft.AtomicBlockUtils.insertAtomicBlock(editorState, entityKey, ' ');
  26237. return newEditorState;
  26238. };
  26239. var insertHorizontalLine = exports.insertHorizontalLine = function insertHorizontalLine(editorState) {
  26240. return insertAtomicBlock(editorState, 'HR');
  26241. };
  26242. var insertMedias = exports.insertMedias = function insertMedias(editorState) {
  26243. var medias = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : [];
  26244. if (!medias.length) {
  26245. return editorState;
  26246. }
  26247. return medias.reduce(function (editorState, media) {
  26248. var url = media.url,
  26249. link = media.link,
  26250. link_target = media.link_target,
  26251. name = media.name,
  26252. type = media.type,
  26253. width = media.width,
  26254. height = media.height,
  26255. meta = media.meta;
  26256. return insertAtomicBlock(editorState, type, true, { url: url, link: link, link_target: link_target, name: name, type: type, width: width, height: height, meta: meta });
  26257. }, editorState);
  26258. };
  26259. var setMediaData = exports.setMediaData = function setMediaData(editorState, entityKey, data) {
  26260. return Draft.EditorState.push(editorState, editorState.getCurrentContent().mergeEntityData(entityKey, data), 'change-block-data');
  26261. };
  26262. var removeMedia = exports.removeMedia = function removeMedia(editorState, mediaBlock) {
  26263. return removeBlock(editorState, mediaBlock);
  26264. };
  26265. var setMediaPosition = exports.setMediaPosition = function setMediaPosition(editorState, mediaBlock, position) {
  26266. var newPosition = {};
  26267. var float = position.float,
  26268. alignment = position.alignment;
  26269. if (typeof float !== 'undefined') {
  26270. newPosition.float = mediaBlock.getData().get('float') === float ? null : float;
  26271. }
  26272. if (typeof alignment !== 'undefined') {
  26273. newPosition.alignment = mediaBlock.getData().get('alignment') === alignment ? null : alignment;
  26274. }
  26275. return setSelectionBlockData(selectBlock(editorState, mediaBlock), newPosition);
  26276. };
  26277. var clear = exports.clear = function clear(editorState) {
  26278. var contentState = editorState.getCurrentContent();
  26279. var firstBlock = contentState.getFirstBlock();
  26280. var lastBlock = contentState.getLastBlock();
  26281. var allSelected = new Draft.SelectionState({
  26282. anchorKey: firstBlock.getKey(),
  26283. anchorOffset: 0,
  26284. focusKey: lastBlock.getKey(),
  26285. focusOffset: lastBlock.getLength(),
  26286. hasFocus: true
  26287. });
  26288. return Draft.RichUtils.toggleBlockType(Draft.EditorState.push(editorState, Draft.Modifier.removeRange(contentState, allSelected, 'backward'), 'remove-range'), 'unstyled');
  26289. };
  26290. var handleKeyCommand = exports.handleKeyCommand = function handleKeyCommand(editorState, command) {
  26291. return Draft.RichUtils.handleKeyCommand(editorState, command);
  26292. };
  26293. var undo = exports.undo = function undo(editorState) {
  26294. return Draft.EditorState.undo(editorState);
  26295. };
  26296. var redo = exports.redo = function redo(editorState) {
  26297. return Draft.EditorState.redo(editorState);
  26298. };
  26299. });
  26300. unwrapExports(content);
  26301. var content_1 = content.redo;
  26302. var content_2 = content.undo;
  26303. var content_3 = content.handleKeyCommand;
  26304. var content_4 = content.clear;
  26305. var content_5 = content.setMediaPosition;
  26306. var content_6 = content.removeMedia;
  26307. var content_7 = content.setMediaData;
  26308. var content_8 = content.insertMedias;
  26309. var content_9 = content.insertHorizontalLine;
  26310. var content_10 = content.insertAtomicBlock;
  26311. var content_11 = content.insertHTML;
  26312. var content_12 = content.insertText;
  26313. var content_13 = content.toggleSelectionLetterSpacing;
  26314. var content_14 = content.toggleSelectionFontFamily;
  26315. var content_15 = content.toggleSelectionLineHeight;
  26316. var content_16 = content.toggleSelectionFontSize;
  26317. var content_17 = content.toggleSelectionBackgroundColor;
  26318. var content_18 = content.toggleSelectionColor;
  26319. var content_19 = content.decreaseSelectionIndent;
  26320. var content_20 = content.increaseSelectionIndent;
  26321. var content_21 = content.toggleSelectionIndent;
  26322. var content_22 = content.toggleSelectionAlignment;
  26323. var content_23 = content.removeSelectionInlineStyles;
  26324. var content_24 = content.toggleSelectionInlineStyle;
  26325. var content_25 = content.selectionHasInlineStyle;
  26326. var content_26 = content.getSelectionInlineStyle;
  26327. var content_27 = content.toggleSelectionLink;
  26328. var content_28 = content.toggleSelectionEntity;
  26329. var content_29 = content.getSelectionEntityData;
  26330. var content_30 = content.getSelectionEntityType;
  26331. var content_31 = content.toggleSelectionBlockType;
  26332. var content_32 = content.getSelectionText;
  26333. var content_33 = content.getSelectionBlockType;
  26334. var content_34 = content.getSelectionBlockData;
  26335. var content_35 = content.setSelectionBlockData;
  26336. var content_36 = content.getSelectedBlocks;
  26337. var content_37 = content.updateEachCharacterOfSelection;
  26338. var content_38 = content.getSelectionBlock;
  26339. var content_39 = content.removeBlock;
  26340. var content_40 = content.selectNextBlock;
  26341. var content_41 = content.selectBlock;
  26342. var content_42 = content.selectionContainsStrictBlock;
  26343. var content_43 = content.selectionContainsBlockType;
  26344. var content_44 = content.isSelectionCollapsed;
  26345. var content_45 = content.createEditorState;
  26346. var content_46 = content.createEmptyEditorState;
  26347. var content_47 = content.isEditorState;
  26348. var content_48 = content.registerStrictBlockType;
  26349. var base = createCommonjsModule(function (module, exports) {
  26350. Object.defineProperty(exports, "__esModule", {
  26351. value: true
  26352. });
  26353. var braftUniqueIndex = 0;
  26354. var UniqueIndex = exports.UniqueIndex = function UniqueIndex() {
  26355. return braftUniqueIndex += 1;
  26356. };
  26357. });
  26358. unwrapExports(base);
  26359. var base_1 = base.UniqueIndex;
  26360. var color = createCommonjsModule(function (module, exports) {
  26361. Object.defineProperty(exports, "__esModule", {
  26362. value: true
  26363. });
  26364. var _namedColors = {
  26365. "aliceblue": "#f0f8ff",
  26366. "antiquewhite": "#faebd7",
  26367. "aqua": "#00ffff",
  26368. "aquamarine": "#7fffd4",
  26369. "azure": "#f0ffff",
  26370. "beige": "#f5f5dc",
  26371. "bisque": "#ffe4c4",
  26372. "black": "#000000",
  26373. "blanchedalmond": "#ffebcd",
  26374. "blue": "#0000ff",
  26375. "blueviolet": "#8a2be2",
  26376. "brown": "#a52a2a",
  26377. "burlywood": "#deb887",
  26378. "cadetblue": "#5f9ea0",
  26379. "chartreuse": "#7fff00",
  26380. "chocolate": "#d2691e",
  26381. "coral": "#ff7f50",
  26382. "cornflowerblue": "#6495ed",
  26383. "cornsilk": "#fff8dc",
  26384. "crimson": "#dc143c",
  26385. "cyan": "#00ffff",
  26386. "darkblue": "#00008b",
  26387. "darkcyan": "#008b8b",
  26388. "darkgoldenrod": "#b8860b",
  26389. "darkgray": "#a9a9a9",
  26390. "darkgreen": "#006400",
  26391. "darkkhaki": "#bdb76b",
  26392. "darkmagenta": "#8b008b",
  26393. "darkolivegreen": "#556b2f",
  26394. "darkorange": "#ff8c00",
  26395. "darkorchid": "#9932cc",
  26396. "darkred": "#8b0000",
  26397. "darksalmon": "#e9967a",
  26398. "darkseagreen": "#8fbc8f",
  26399. "darkslateblue": "#483d8b",
  26400. "darkslategray": "#2f4f4f",
  26401. "darkturquoise": "#00ced1",
  26402. "darkviolet": "#9400d3",
  26403. "deeppink": "#ff1493",
  26404. "deepskyblue": "#00bfff",
  26405. "dimgray": "#696969",
  26406. "dodgerblue": "#1e90ff",
  26407. "firebrick": "#b22222",
  26408. "floralwhite": "#fffaf0",
  26409. "forestgreen": "#228b22",
  26410. "fuchsia": "#ff00ff",
  26411. "gainsboro": "#dcdcdc",
  26412. "ghostwhite": "#f8f8ff",
  26413. "gold": "#ffd700",
  26414. "goldenrod": "#daa520",
  26415. "gray": "#808080",
  26416. "green": "#008000",
  26417. "greenyellow": "#adff2f",
  26418. "honeydew": "#f0fff0",
  26419. "hotpink": "#ff69b4",
  26420. "indianred ": "#cd5c5c",
  26421. "indigo": "#4b0082",
  26422. "ivory": "#fffff0",
  26423. "khaki": "#f0e68c",
  26424. "lavender": "#e6e6fa",
  26425. "lavenderblush": "#fff0f5",
  26426. "lawngreen": "#7cfc00",
  26427. "lemonchiffon": "#fffacd",
  26428. "lightblue": "#add8e6",
  26429. "lightcoral": "#f08080",
  26430. "lightcyan": "#e0ffff",
  26431. "lightgoldenrodyellow": "#fafad2",
  26432. "lightgrey": "#d3d3d3",
  26433. "lightgreen": "#90ee90",
  26434. "lightpink": "#ffb6c1",
  26435. "lightsalmon": "#ffa07a",
  26436. "lightseagreen": "#20b2aa",
  26437. "lightskyblue": "#87cefa",
  26438. "lightslategray": "#778899",
  26439. "lightsteelblue": "#b0c4de",
  26440. "lightyellow": "#ffffe0",
  26441. "lime": "#00ff00",
  26442. "limegreen": "#32cd32",
  26443. "linen": "#faf0e6",
  26444. "magenta": "#ff00ff",
  26445. "maroon": "#800000",
  26446. "mediumaquamarine": "#66cdaa",
  26447. "mediumblue": "#0000cd",
  26448. "mediumorchid": "#ba55d3",
  26449. "mediumpurple": "#9370d8",
  26450. "mediumseagreen": "#3cb371",
  26451. "mediumslateblue": "#7b68ee",
  26452. "mediumspringgreen": "#00fa9a",
  26453. "mediumturquoise": "#48d1cc",
  26454. "mediumvioletred": "#c71585",
  26455. "midnightblue": "#191970",
  26456. "mintcream": "#f5fffa",
  26457. "mistyrose": "#ffe4e1",
  26458. "moccasin": "#ffe4b5",
  26459. "navajowhite": "#ffdead",
  26460. "navy": "#000080",
  26461. "oldlace": "#fdf5e6",
  26462. "olive": "#808000",
  26463. "olivedrab": "#6b8e23",
  26464. "orange": "#ffa500",
  26465. "orangered": "#ff4500",
  26466. "orchid": "#da70d6",
  26467. "palegoldenrod": "#eee8aa",
  26468. "palegreen": "#98fb98",
  26469. "paleturquoise": "#afeeee",
  26470. "palevioletred": "#d87093",
  26471. "papayawhip": "#ffefd5",
  26472. "peachpuff": "#ffdab9",
  26473. "peru": "#cd853f",
  26474. "pink": "#ffc0cb",
  26475. "plum": "#dda0dd",
  26476. "powderblue": "#b0e0e6",
  26477. "purple": "#800080",
  26478. "rebeccapurple": "#663399",
  26479. "red": "#ff0000",
  26480. "rosybrown": "#bc8f8f",
  26481. "royalblue": "#4169e1",
  26482. "saddlebrown": "#8b4513",
  26483. "salmon": "#fa8072",
  26484. "sandybrown": "#f4a460",
  26485. "seagreen": "#2e8b57",
  26486. "seashell": "#fff5ee",
  26487. "sienna": "#a0522d",
  26488. "silver": "#c0c0c0",
  26489. "skyblue": "#87ceeb",
  26490. "slateblue": "#6a5acd",
  26491. "slategray": "#708090",
  26492. "snow": "#fffafa",
  26493. "springgreen": "#00ff7f",
  26494. "steelblue": "#4682b4",
  26495. "tan": "#d2b48c",
  26496. "teal": "#008080",
  26497. "thistle": "#d8bfd8",
  26498. "tomato": "#ff6347",
  26499. "turquoise": "#40e0d0",
  26500. "violet": "#ee82ee",
  26501. "wheat": "#f5deb3",
  26502. "white": "#ffffff",
  26503. "whitesmoke": "#f5f5f5",
  26504. "yellow": "#ffff00",
  26505. "yellowgreen": "#9acd32"
  26506. };
  26507. var _getHexColor = function _getHexColor(color) {
  26508. color = color.replace('color:', '').replace(';', '').replace(' ', '');
  26509. if (/^#([0-9a-fA-F]{6}|[0-9a-fA-F]{3})$/.test(color)) {
  26510. return color;
  26511. } else if (namedColors[color]) {
  26512. return namedColors[color];
  26513. } else if (color.indexOf('rgb') === 0) {
  26514. var rgbArray = color.split(',');
  26515. var convertedColor = rgbArray.length < 3 ? null : '#' + [rgbArray[0], rgbArray[1], rgbArray[2]].map(function (x) {
  26516. var hex = parseInt(x.replace(/\D/g, ''), 10).toString(16);
  26517. return hex.length === 1 ? '0' + hex : hex;
  26518. }).join('');
  26519. return (/^#([0-9a-fA-F]{6}|[0-9a-fA-F]{3})$/.test(convertedColor) ? convertedColor : null
  26520. );
  26521. } else {
  26522. return null;
  26523. }
  26524. };
  26525. var namedColors = exports.namedColors = _namedColors;
  26526. var getHexColor = exports.getHexColor = _getHexColor;
  26527. var detectColorsFromHTMLString = exports.detectColorsFromHTMLString = function detectColorsFromHTMLString(html) {
  26528. return typeof html !== 'string' ? [] : (html.match(/color:[^;]{3,24};/g) || []).map(getHexColor).filter(function (color) {
  26529. return color;
  26530. });
  26531. };
  26532. var detectColorsFromDraftState = exports.detectColorsFromDraftState = function detectColorsFromDraftState(draftState) {
  26533. var result = [];
  26534. if (!draftState || !draftState.blocks || !draftState.blocks.length) {
  26535. return result;
  26536. }
  26537. draftState.blocks.forEach(function (block) {
  26538. if (block && block.inlineStyleRanges && block.inlineStyleRanges.length) {
  26539. block.inlineStyleRanges.forEach(function (inlineStyle) {
  26540. if (inlineStyle.style && inlineStyle.style.indexOf('COLOR-') >= 0) {
  26541. result.push('#' + inlineStyle.style.split('COLOR-')[1]);
  26542. }
  26543. });
  26544. }
  26545. });
  26546. return result.filter(function (color) {
  26547. return color;
  26548. });
  26549. };
  26550. });
  26551. unwrapExports(color);
  26552. var color_1 = color.namedColors;
  26553. var color_2 = color.getHexColor;
  26554. var color_3 = color.detectColorsFromHTMLString;
  26555. var color_4 = color.detectColorsFromDraftState;
  26556. var dist$1 = createCommonjsModule(function (module, exports) {
  26557. Object.defineProperty(exports, "__esModule", {
  26558. value: true
  26559. });
  26560. exports.ColorUtils = exports.BaseUtils = exports.ContentUtils = undefined;
  26561. var _ContentUtils = _interopRequireWildcard(content);
  26562. var _BaseUtils = _interopRequireWildcard(base);
  26563. var _ColorUtils = _interopRequireWildcard(color);
  26564. function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } }
  26565. var ContentUtils = exports.ContentUtils = _ContentUtils;
  26566. var BaseUtils = exports.BaseUtils = _BaseUtils;
  26567. var ColorUtils = exports.ColorUtils = _ColorUtils;
  26568. });
  26569. unwrapExports(dist$1);
  26570. var dist_1$1 = dist$1.ColorUtils;
  26571. var dist_2$1 = dist$1.BaseUtils;
  26572. var dist_3$1 = dist$1.ContentUtils;
  26573. var immutable$3 = createCommonjsModule(function (module, exports) {
  26574. /**
  26575. * Copyright (c) 2014-2015, Facebook, Inc.
  26576. * All rights reserved.
  26577. *
  26578. * This source code is licensed under the BSD-style license found in the
  26579. * LICENSE file in the root directory of this source tree. An additional grant
  26580. * of patent rights can be found in the PATENTS file in the same directory.
  26581. */
  26582. (function (global, factory) {
  26583. module.exports = factory() ;
  26584. }(commonjsGlobal, function () {var SLICE$0 = Array.prototype.slice;
  26585. function createClass(ctor, superClass) {
  26586. if (superClass) {
  26587. ctor.prototype = Object.create(superClass.prototype);
  26588. }
  26589. ctor.prototype.constructor = ctor;
  26590. }
  26591. function Iterable(value) {
  26592. return isIterable(value) ? value : Seq(value);
  26593. }
  26594. createClass(KeyedIterable, Iterable);
  26595. function KeyedIterable(value) {
  26596. return isKeyed(value) ? value : KeyedSeq(value);
  26597. }
  26598. createClass(IndexedIterable, Iterable);
  26599. function IndexedIterable(value) {
  26600. return isIndexed(value) ? value : IndexedSeq(value);
  26601. }
  26602. createClass(SetIterable, Iterable);
  26603. function SetIterable(value) {
  26604. return isIterable(value) && !isAssociative(value) ? value : SetSeq(value);
  26605. }
  26606. function isIterable(maybeIterable) {
  26607. return !!(maybeIterable && maybeIterable[IS_ITERABLE_SENTINEL]);
  26608. }
  26609. function isKeyed(maybeKeyed) {
  26610. return !!(maybeKeyed && maybeKeyed[IS_KEYED_SENTINEL]);
  26611. }
  26612. function isIndexed(maybeIndexed) {
  26613. return !!(maybeIndexed && maybeIndexed[IS_INDEXED_SENTINEL]);
  26614. }
  26615. function isAssociative(maybeAssociative) {
  26616. return isKeyed(maybeAssociative) || isIndexed(maybeAssociative);
  26617. }
  26618. function isOrdered(maybeOrdered) {
  26619. return !!(maybeOrdered && maybeOrdered[IS_ORDERED_SENTINEL]);
  26620. }
  26621. Iterable.isIterable = isIterable;
  26622. Iterable.isKeyed = isKeyed;
  26623. Iterable.isIndexed = isIndexed;
  26624. Iterable.isAssociative = isAssociative;
  26625. Iterable.isOrdered = isOrdered;
  26626. Iterable.Keyed = KeyedIterable;
  26627. Iterable.Indexed = IndexedIterable;
  26628. Iterable.Set = SetIterable;
  26629. var IS_ITERABLE_SENTINEL = '@@__IMMUTABLE_ITERABLE__@@';
  26630. var IS_KEYED_SENTINEL = '@@__IMMUTABLE_KEYED__@@';
  26631. var IS_INDEXED_SENTINEL = '@@__IMMUTABLE_INDEXED__@@';
  26632. var IS_ORDERED_SENTINEL = '@@__IMMUTABLE_ORDERED__@@';
  26633. // Used for setting prototype methods that IE8 chokes on.
  26634. var DELETE = 'delete';
  26635. // Constants describing the size of trie nodes.
  26636. var SHIFT = 5; // Resulted in best performance after ______?
  26637. var SIZE = 1 << SHIFT;
  26638. var MASK = SIZE - 1;
  26639. // A consistent shared value representing "not set" which equals nothing other
  26640. // than itself, and nothing that could be provided externally.
  26641. var NOT_SET = {};
  26642. // Boolean references, Rough equivalent of `bool &`.
  26643. var CHANGE_LENGTH = { value: false };
  26644. var DID_ALTER = { value: false };
  26645. function MakeRef(ref) {
  26646. ref.value = false;
  26647. return ref;
  26648. }
  26649. function SetRef(ref) {
  26650. ref && (ref.value = true);
  26651. }
  26652. // A function which returns a value representing an "owner" for transient writes
  26653. // to tries. The return value will only ever equal itself, and will not equal
  26654. // the return of any subsequent call of this function.
  26655. function OwnerID() {}
  26656. // http://jsperf.com/copy-array-inline
  26657. function arrCopy(arr, offset) {
  26658. offset = offset || 0;
  26659. var len = Math.max(0, arr.length - offset);
  26660. var newArr = new Array(len);
  26661. for (var ii = 0; ii < len; ii++) {
  26662. newArr[ii] = arr[ii + offset];
  26663. }
  26664. return newArr;
  26665. }
  26666. function ensureSize(iter) {
  26667. if (iter.size === undefined) {
  26668. iter.size = iter.__iterate(returnTrue);
  26669. }
  26670. return iter.size;
  26671. }
  26672. function wrapIndex(iter, index) {
  26673. // This implements "is array index" which the ECMAString spec defines as:
  26674. //
  26675. // A String property name P is an array index if and only if
  26676. // ToString(ToUint32(P)) is equal to P and ToUint32(P) is not equal
  26677. // to 2^32−1.
  26678. //
  26679. // http://www.ecma-international.org/ecma-262/6.0/#sec-array-exotic-objects
  26680. if (typeof index !== 'number') {
  26681. var uint32Index = index >>> 0; // N >>> 0 is shorthand for ToUint32
  26682. if ('' + uint32Index !== index || uint32Index === 4294967295) {
  26683. return NaN;
  26684. }
  26685. index = uint32Index;
  26686. }
  26687. return index < 0 ? ensureSize(iter) + index : index;
  26688. }
  26689. function returnTrue() {
  26690. return true;
  26691. }
  26692. function wholeSlice(begin, end, size) {
  26693. return (begin === 0 || (size !== undefined && begin <= -size)) &&
  26694. (end === undefined || (size !== undefined && end >= size));
  26695. }
  26696. function resolveBegin(begin, size) {
  26697. return resolveIndex(begin, size, 0);
  26698. }
  26699. function resolveEnd(end, size) {
  26700. return resolveIndex(end, size, size);
  26701. }
  26702. function resolveIndex(index, size, defaultIndex) {
  26703. return index === undefined ?
  26704. defaultIndex :
  26705. index < 0 ?
  26706. Math.max(0, size + index) :
  26707. size === undefined ?
  26708. index :
  26709. Math.min(size, index);
  26710. }
  26711. /* global Symbol */
  26712. var ITERATE_KEYS = 0;
  26713. var ITERATE_VALUES = 1;
  26714. var ITERATE_ENTRIES = 2;
  26715. var REAL_ITERATOR_SYMBOL = typeof Symbol === 'function' && Symbol.iterator;
  26716. var FAUX_ITERATOR_SYMBOL = '@@iterator';
  26717. var ITERATOR_SYMBOL = REAL_ITERATOR_SYMBOL || FAUX_ITERATOR_SYMBOL;
  26718. function Iterator(next) {
  26719. this.next = next;
  26720. }
  26721. Iterator.prototype.toString = function() {
  26722. return '[Iterator]';
  26723. };
  26724. Iterator.KEYS = ITERATE_KEYS;
  26725. Iterator.VALUES = ITERATE_VALUES;
  26726. Iterator.ENTRIES = ITERATE_ENTRIES;
  26727. Iterator.prototype.inspect =
  26728. Iterator.prototype.toSource = function () { return this.toString(); };
  26729. Iterator.prototype[ITERATOR_SYMBOL] = function () {
  26730. return this;
  26731. };
  26732. function iteratorValue(type, k, v, iteratorResult) {
  26733. var value = type === 0 ? k : type === 1 ? v : [k, v];
  26734. iteratorResult ? (iteratorResult.value = value) : (iteratorResult = {
  26735. value: value, done: false
  26736. });
  26737. return iteratorResult;
  26738. }
  26739. function iteratorDone() {
  26740. return { value: undefined, done: true };
  26741. }
  26742. function hasIterator(maybeIterable) {
  26743. return !!getIteratorFn(maybeIterable);
  26744. }
  26745. function isIterator(maybeIterator) {
  26746. return maybeIterator && typeof maybeIterator.next === 'function';
  26747. }
  26748. function getIterator(iterable) {
  26749. var iteratorFn = getIteratorFn(iterable);
  26750. return iteratorFn && iteratorFn.call(iterable);
  26751. }
  26752. function getIteratorFn(iterable) {
  26753. var iteratorFn = iterable && (
  26754. (REAL_ITERATOR_SYMBOL && iterable[REAL_ITERATOR_SYMBOL]) ||
  26755. iterable[FAUX_ITERATOR_SYMBOL]
  26756. );
  26757. if (typeof iteratorFn === 'function') {
  26758. return iteratorFn;
  26759. }
  26760. }
  26761. function isArrayLike(value) {
  26762. return value && typeof value.length === 'number';
  26763. }
  26764. createClass(Seq, Iterable);
  26765. function Seq(value) {
  26766. return value === null || value === undefined ? emptySequence() :
  26767. isIterable(value) ? value.toSeq() : seqFromValue(value);
  26768. }
  26769. Seq.of = function(/*...values*/) {
  26770. return Seq(arguments);
  26771. };
  26772. Seq.prototype.toSeq = function() {
  26773. return this;
  26774. };
  26775. Seq.prototype.toString = function() {
  26776. return this.__toString('Seq {', '}');
  26777. };
  26778. Seq.prototype.cacheResult = function() {
  26779. if (!this._cache && this.__iterateUncached) {
  26780. this._cache = this.entrySeq().toArray();
  26781. this.size = this._cache.length;
  26782. }
  26783. return this;
  26784. };
  26785. // abstract __iterateUncached(fn, reverse)
  26786. Seq.prototype.__iterate = function(fn, reverse) {
  26787. return seqIterate(this, fn, reverse, true);
  26788. };
  26789. // abstract __iteratorUncached(type, reverse)
  26790. Seq.prototype.__iterator = function(type, reverse) {
  26791. return seqIterator(this, type, reverse, true);
  26792. };
  26793. createClass(KeyedSeq, Seq);
  26794. function KeyedSeq(value) {
  26795. return value === null || value === undefined ?
  26796. emptySequence().toKeyedSeq() :
  26797. isIterable(value) ?
  26798. (isKeyed(value) ? value.toSeq() : value.fromEntrySeq()) :
  26799. keyedSeqFromValue(value);
  26800. }
  26801. KeyedSeq.prototype.toKeyedSeq = function() {
  26802. return this;
  26803. };
  26804. createClass(IndexedSeq, Seq);
  26805. function IndexedSeq(value) {
  26806. return value === null || value === undefined ? emptySequence() :
  26807. !isIterable(value) ? indexedSeqFromValue(value) :
  26808. isKeyed(value) ? value.entrySeq() : value.toIndexedSeq();
  26809. }
  26810. IndexedSeq.of = function(/*...values*/) {
  26811. return IndexedSeq(arguments);
  26812. };
  26813. IndexedSeq.prototype.toIndexedSeq = function() {
  26814. return this;
  26815. };
  26816. IndexedSeq.prototype.toString = function() {
  26817. return this.__toString('Seq [', ']');
  26818. };
  26819. IndexedSeq.prototype.__iterate = function(fn, reverse) {
  26820. return seqIterate(this, fn, reverse, false);
  26821. };
  26822. IndexedSeq.prototype.__iterator = function(type, reverse) {
  26823. return seqIterator(this, type, reverse, false);
  26824. };
  26825. createClass(SetSeq, Seq);
  26826. function SetSeq(value) {
  26827. return (
  26828. value === null || value === undefined ? emptySequence() :
  26829. !isIterable(value) ? indexedSeqFromValue(value) :
  26830. isKeyed(value) ? value.entrySeq() : value
  26831. ).toSetSeq();
  26832. }
  26833. SetSeq.of = function(/*...values*/) {
  26834. return SetSeq(arguments);
  26835. };
  26836. SetSeq.prototype.toSetSeq = function() {
  26837. return this;
  26838. };
  26839. Seq.isSeq = isSeq;
  26840. Seq.Keyed = KeyedSeq;
  26841. Seq.Set = SetSeq;
  26842. Seq.Indexed = IndexedSeq;
  26843. var IS_SEQ_SENTINEL = '@@__IMMUTABLE_SEQ__@@';
  26844. Seq.prototype[IS_SEQ_SENTINEL] = true;
  26845. createClass(ArraySeq, IndexedSeq);
  26846. function ArraySeq(array) {
  26847. this._array = array;
  26848. this.size = array.length;
  26849. }
  26850. ArraySeq.prototype.get = function(index, notSetValue) {
  26851. return this.has(index) ? this._array[wrapIndex(this, index)] : notSetValue;
  26852. };
  26853. ArraySeq.prototype.__iterate = function(fn, reverse) {
  26854. var array = this._array;
  26855. var maxIndex = array.length - 1;
  26856. for (var ii = 0; ii <= maxIndex; ii++) {
  26857. if (fn(array[reverse ? maxIndex - ii : ii], ii, this) === false) {
  26858. return ii + 1;
  26859. }
  26860. }
  26861. return ii;
  26862. };
  26863. ArraySeq.prototype.__iterator = function(type, reverse) {
  26864. var array = this._array;
  26865. var maxIndex = array.length - 1;
  26866. var ii = 0;
  26867. return new Iterator(function()
  26868. {return ii > maxIndex ?
  26869. iteratorDone() :
  26870. iteratorValue(type, ii, array[reverse ? maxIndex - ii++ : ii++])}
  26871. );
  26872. };
  26873. createClass(ObjectSeq, KeyedSeq);
  26874. function ObjectSeq(object) {
  26875. var keys = Object.keys(object);
  26876. this._object = object;
  26877. this._keys = keys;
  26878. this.size = keys.length;
  26879. }
  26880. ObjectSeq.prototype.get = function(key, notSetValue) {
  26881. if (notSetValue !== undefined && !this.has(key)) {
  26882. return notSetValue;
  26883. }
  26884. return this._object[key];
  26885. };
  26886. ObjectSeq.prototype.has = function(key) {
  26887. return this._object.hasOwnProperty(key);
  26888. };
  26889. ObjectSeq.prototype.__iterate = function(fn, reverse) {
  26890. var object = this._object;
  26891. var keys = this._keys;
  26892. var maxIndex = keys.length - 1;
  26893. for (var ii = 0; ii <= maxIndex; ii++) {
  26894. var key = keys[reverse ? maxIndex - ii : ii];
  26895. if (fn(object[key], key, this) === false) {
  26896. return ii + 1;
  26897. }
  26898. }
  26899. return ii;
  26900. };
  26901. ObjectSeq.prototype.__iterator = function(type, reverse) {
  26902. var object = this._object;
  26903. var keys = this._keys;
  26904. var maxIndex = keys.length - 1;
  26905. var ii = 0;
  26906. return new Iterator(function() {
  26907. var key = keys[reverse ? maxIndex - ii : ii];
  26908. return ii++ > maxIndex ?
  26909. iteratorDone() :
  26910. iteratorValue(type, key, object[key]);
  26911. });
  26912. };
  26913. ObjectSeq.prototype[IS_ORDERED_SENTINEL] = true;
  26914. createClass(IterableSeq, IndexedSeq);
  26915. function IterableSeq(iterable) {
  26916. this._iterable = iterable;
  26917. this.size = iterable.length || iterable.size;
  26918. }
  26919. IterableSeq.prototype.__iterateUncached = function(fn, reverse) {
  26920. if (reverse) {
  26921. return this.cacheResult().__iterate(fn, reverse);
  26922. }
  26923. var iterable = this._iterable;
  26924. var iterator = getIterator(iterable);
  26925. var iterations = 0;
  26926. if (isIterator(iterator)) {
  26927. var step;
  26928. while (!(step = iterator.next()).done) {
  26929. if (fn(step.value, iterations++, this) === false) {
  26930. break;
  26931. }
  26932. }
  26933. }
  26934. return iterations;
  26935. };
  26936. IterableSeq.prototype.__iteratorUncached = function(type, reverse) {
  26937. if (reverse) {
  26938. return this.cacheResult().__iterator(type, reverse);
  26939. }
  26940. var iterable = this._iterable;
  26941. var iterator = getIterator(iterable);
  26942. if (!isIterator(iterator)) {
  26943. return new Iterator(iteratorDone);
  26944. }
  26945. var iterations = 0;
  26946. return new Iterator(function() {
  26947. var step = iterator.next();
  26948. return step.done ? step : iteratorValue(type, iterations++, step.value);
  26949. });
  26950. };
  26951. createClass(IteratorSeq, IndexedSeq);
  26952. function IteratorSeq(iterator) {
  26953. this._iterator = iterator;
  26954. this._iteratorCache = [];
  26955. }
  26956. IteratorSeq.prototype.__iterateUncached = function(fn, reverse) {
  26957. if (reverse) {
  26958. return this.cacheResult().__iterate(fn, reverse);
  26959. }
  26960. var iterator = this._iterator;
  26961. var cache = this._iteratorCache;
  26962. var iterations = 0;
  26963. while (iterations < cache.length) {
  26964. if (fn(cache[iterations], iterations++, this) === false) {
  26965. return iterations;
  26966. }
  26967. }
  26968. var step;
  26969. while (!(step = iterator.next()).done) {
  26970. var val = step.value;
  26971. cache[iterations] = val;
  26972. if (fn(val, iterations++, this) === false) {
  26973. break;
  26974. }
  26975. }
  26976. return iterations;
  26977. };
  26978. IteratorSeq.prototype.__iteratorUncached = function(type, reverse) {
  26979. if (reverse) {
  26980. return this.cacheResult().__iterator(type, reverse);
  26981. }
  26982. var iterator = this._iterator;
  26983. var cache = this._iteratorCache;
  26984. var iterations = 0;
  26985. return new Iterator(function() {
  26986. if (iterations >= cache.length) {
  26987. var step = iterator.next();
  26988. if (step.done) {
  26989. return step;
  26990. }
  26991. cache[iterations] = step.value;
  26992. }
  26993. return iteratorValue(type, iterations, cache[iterations++]);
  26994. });
  26995. };
  26996. // # pragma Helper functions
  26997. function isSeq(maybeSeq) {
  26998. return !!(maybeSeq && maybeSeq[IS_SEQ_SENTINEL]);
  26999. }
  27000. var EMPTY_SEQ;
  27001. function emptySequence() {
  27002. return EMPTY_SEQ || (EMPTY_SEQ = new ArraySeq([]));
  27003. }
  27004. function keyedSeqFromValue(value) {
  27005. var seq =
  27006. Array.isArray(value) ? new ArraySeq(value).fromEntrySeq() :
  27007. isIterator(value) ? new IteratorSeq(value).fromEntrySeq() :
  27008. hasIterator(value) ? new IterableSeq(value).fromEntrySeq() :
  27009. typeof value === 'object' ? new ObjectSeq(value) :
  27010. undefined;
  27011. if (!seq) {
  27012. throw new TypeError(
  27013. 'Expected Array or iterable object of [k, v] entries, '+
  27014. 'or keyed object: ' + value
  27015. );
  27016. }
  27017. return seq;
  27018. }
  27019. function indexedSeqFromValue(value) {
  27020. var seq = maybeIndexedSeqFromValue(value);
  27021. if (!seq) {
  27022. throw new TypeError(
  27023. 'Expected Array or iterable object of values: ' + value
  27024. );
  27025. }
  27026. return seq;
  27027. }
  27028. function seqFromValue(value) {
  27029. var seq = maybeIndexedSeqFromValue(value) ||
  27030. (typeof value === 'object' && new ObjectSeq(value));
  27031. if (!seq) {
  27032. throw new TypeError(
  27033. 'Expected Array or iterable object of values, or keyed object: ' + value
  27034. );
  27035. }
  27036. return seq;
  27037. }
  27038. function maybeIndexedSeqFromValue(value) {
  27039. return (
  27040. isArrayLike(value) ? new ArraySeq(value) :
  27041. isIterator(value) ? new IteratorSeq(value) :
  27042. hasIterator(value) ? new IterableSeq(value) :
  27043. undefined
  27044. );
  27045. }
  27046. function seqIterate(seq, fn, reverse, useKeys) {
  27047. var cache = seq._cache;
  27048. if (cache) {
  27049. var maxIndex = cache.length - 1;
  27050. for (var ii = 0; ii <= maxIndex; ii++) {
  27051. var entry = cache[reverse ? maxIndex - ii : ii];
  27052. if (fn(entry[1], useKeys ? entry[0] : ii, seq) === false) {
  27053. return ii + 1;
  27054. }
  27055. }
  27056. return ii;
  27057. }
  27058. return seq.__iterateUncached(fn, reverse);
  27059. }
  27060. function seqIterator(seq, type, reverse, useKeys) {
  27061. var cache = seq._cache;
  27062. if (cache) {
  27063. var maxIndex = cache.length - 1;
  27064. var ii = 0;
  27065. return new Iterator(function() {
  27066. var entry = cache[reverse ? maxIndex - ii : ii];
  27067. return ii++ > maxIndex ?
  27068. iteratorDone() :
  27069. iteratorValue(type, useKeys ? entry[0] : ii - 1, entry[1]);
  27070. });
  27071. }
  27072. return seq.__iteratorUncached(type, reverse);
  27073. }
  27074. function fromJS(json, converter) {
  27075. return converter ?
  27076. fromJSWith(converter, json, '', {'': json}) :
  27077. fromJSDefault(json);
  27078. }
  27079. function fromJSWith(converter, json, key, parentJSON) {
  27080. if (Array.isArray(json)) {
  27081. return converter.call(parentJSON, key, IndexedSeq(json).map(function(v, k) {return fromJSWith(converter, v, k, json)}));
  27082. }
  27083. if (isPlainObj(json)) {
  27084. return converter.call(parentJSON, key, KeyedSeq(json).map(function(v, k) {return fromJSWith(converter, v, k, json)}));
  27085. }
  27086. return json;
  27087. }
  27088. function fromJSDefault(json) {
  27089. if (Array.isArray(json)) {
  27090. return IndexedSeq(json).map(fromJSDefault).toList();
  27091. }
  27092. if (isPlainObj(json)) {
  27093. return KeyedSeq(json).map(fromJSDefault).toMap();
  27094. }
  27095. return json;
  27096. }
  27097. function isPlainObj(value) {
  27098. return value && (value.constructor === Object || value.constructor === undefined);
  27099. }
  27100. /**
  27101. * An extension of the "same-value" algorithm as [described for use by ES6 Map
  27102. * and Set](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map#Key_equality)
  27103. *
  27104. * NaN is considered the same as NaN, however -0 and 0 are considered the same
  27105. * value, which is different from the algorithm described by
  27106. * [`Object.is`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/is).
  27107. *
  27108. * This is extended further to allow Objects to describe the values they
  27109. * represent, by way of `valueOf` or `equals` (and `hashCode`).
  27110. *
  27111. * Note: because of this extension, the key equality of Immutable.Map and the
  27112. * value equality of Immutable.Set will differ from ES6 Map and Set.
  27113. *
  27114. * ### Defining custom values
  27115. *
  27116. * The easiest way to describe the value an object represents is by implementing
  27117. * `valueOf`. For example, `Date` represents a value by returning a unix
  27118. * timestamp for `valueOf`:
  27119. *
  27120. * var date1 = new Date(1234567890000); // Fri Feb 13 2009 ...
  27121. * var date2 = new Date(1234567890000);
  27122. * date1.valueOf(); // 1234567890000
  27123. * assert( date1 !== date2 );
  27124. * assert( Immutable.is( date1, date2 ) );
  27125. *
  27126. * Note: overriding `valueOf` may have other implications if you use this object
  27127. * where JavaScript expects a primitive, such as implicit string coercion.
  27128. *
  27129. * For more complex types, especially collections, implementing `valueOf` may
  27130. * not be performant. An alternative is to implement `equals` and `hashCode`.
  27131. *
  27132. * `equals` takes another object, presumably of similar type, and returns true
  27133. * if the it is equal. Equality is symmetrical, so the same result should be
  27134. * returned if this and the argument are flipped.
  27135. *
  27136. * assert( a.equals(b) === b.equals(a) );
  27137. *
  27138. * `hashCode` returns a 32bit integer number representing the object which will
  27139. * be used to determine how to store the value object in a Map or Set. You must
  27140. * provide both or neither methods, one must not exist without the other.
  27141. *
  27142. * Also, an important relationship between these methods must be upheld: if two
  27143. * values are equal, they *must* return the same hashCode. If the values are not
  27144. * equal, they might have the same hashCode; this is called a hash collision,
  27145. * and while undesirable for performance reasons, it is acceptable.
  27146. *
  27147. * if (a.equals(b)) {
  27148. * assert( a.hashCode() === b.hashCode() );
  27149. * }
  27150. *
  27151. * All Immutable collections implement `equals` and `hashCode`.
  27152. *
  27153. */
  27154. function is(valueA, valueB) {
  27155. if (valueA === valueB || (valueA !== valueA && valueB !== valueB)) {
  27156. return true;
  27157. }
  27158. if (!valueA || !valueB) {
  27159. return false;
  27160. }
  27161. if (typeof valueA.valueOf === 'function' &&
  27162. typeof valueB.valueOf === 'function') {
  27163. valueA = valueA.valueOf();
  27164. valueB = valueB.valueOf();
  27165. if (valueA === valueB || (valueA !== valueA && valueB !== valueB)) {
  27166. return true;
  27167. }
  27168. if (!valueA || !valueB) {
  27169. return false;
  27170. }
  27171. }
  27172. if (typeof valueA.equals === 'function' &&
  27173. typeof valueB.equals === 'function' &&
  27174. valueA.equals(valueB)) {
  27175. return true;
  27176. }
  27177. return false;
  27178. }
  27179. function deepEqual(a, b) {
  27180. if (a === b) {
  27181. return true;
  27182. }
  27183. if (
  27184. !isIterable(b) ||
  27185. a.size !== undefined && b.size !== undefined && a.size !== b.size ||
  27186. a.__hash !== undefined && b.__hash !== undefined && a.__hash !== b.__hash ||
  27187. isKeyed(a) !== isKeyed(b) ||
  27188. isIndexed(a) !== isIndexed(b) ||
  27189. isOrdered(a) !== isOrdered(b)
  27190. ) {
  27191. return false;
  27192. }
  27193. if (a.size === 0 && b.size === 0) {
  27194. return true;
  27195. }
  27196. var notAssociative = !isAssociative(a);
  27197. if (isOrdered(a)) {
  27198. var entries = a.entries();
  27199. return b.every(function(v, k) {
  27200. var entry = entries.next().value;
  27201. return entry && is(entry[1], v) && (notAssociative || is(entry[0], k));
  27202. }) && entries.next().done;
  27203. }
  27204. var flipped = false;
  27205. if (a.size === undefined) {
  27206. if (b.size === undefined) {
  27207. if (typeof a.cacheResult === 'function') {
  27208. a.cacheResult();
  27209. }
  27210. } else {
  27211. flipped = true;
  27212. var _ = a;
  27213. a = b;
  27214. b = _;
  27215. }
  27216. }
  27217. var allEqual = true;
  27218. var bSize = b.__iterate(function(v, k) {
  27219. if (notAssociative ? !a.has(v) :
  27220. flipped ? !is(v, a.get(k, NOT_SET)) : !is(a.get(k, NOT_SET), v)) {
  27221. allEqual = false;
  27222. return false;
  27223. }
  27224. });
  27225. return allEqual && a.size === bSize;
  27226. }
  27227. createClass(Repeat, IndexedSeq);
  27228. function Repeat(value, times) {
  27229. if (!(this instanceof Repeat)) {
  27230. return new Repeat(value, times);
  27231. }
  27232. this._value = value;
  27233. this.size = times === undefined ? Infinity : Math.max(0, times);
  27234. if (this.size === 0) {
  27235. if (EMPTY_REPEAT) {
  27236. return EMPTY_REPEAT;
  27237. }
  27238. EMPTY_REPEAT = this;
  27239. }
  27240. }
  27241. Repeat.prototype.toString = function() {
  27242. if (this.size === 0) {
  27243. return 'Repeat []';
  27244. }
  27245. return 'Repeat [ ' + this._value + ' ' + this.size + ' times ]';
  27246. };
  27247. Repeat.prototype.get = function(index, notSetValue) {
  27248. return this.has(index) ? this._value : notSetValue;
  27249. };
  27250. Repeat.prototype.includes = function(searchValue) {
  27251. return is(this._value, searchValue);
  27252. };
  27253. Repeat.prototype.slice = function(begin, end) {
  27254. var size = this.size;
  27255. return wholeSlice(begin, end, size) ? this :
  27256. new Repeat(this._value, resolveEnd(end, size) - resolveBegin(begin, size));
  27257. };
  27258. Repeat.prototype.reverse = function() {
  27259. return this;
  27260. };
  27261. Repeat.prototype.indexOf = function(searchValue) {
  27262. if (is(this._value, searchValue)) {
  27263. return 0;
  27264. }
  27265. return -1;
  27266. };
  27267. Repeat.prototype.lastIndexOf = function(searchValue) {
  27268. if (is(this._value, searchValue)) {
  27269. return this.size;
  27270. }
  27271. return -1;
  27272. };
  27273. Repeat.prototype.__iterate = function(fn, reverse) {
  27274. for (var ii = 0; ii < this.size; ii++) {
  27275. if (fn(this._value, ii, this) === false) {
  27276. return ii + 1;
  27277. }
  27278. }
  27279. return ii;
  27280. };
  27281. Repeat.prototype.__iterator = function(type, reverse) {var this$0 = this;
  27282. var ii = 0;
  27283. return new Iterator(function()
  27284. {return ii < this$0.size ? iteratorValue(type, ii++, this$0._value) : iteratorDone()}
  27285. );
  27286. };
  27287. Repeat.prototype.equals = function(other) {
  27288. return other instanceof Repeat ?
  27289. is(this._value, other._value) :
  27290. deepEqual(other);
  27291. };
  27292. var EMPTY_REPEAT;
  27293. function invariant(condition, error) {
  27294. if (!condition) throw new Error(error);
  27295. }
  27296. createClass(Range, IndexedSeq);
  27297. function Range(start, end, step) {
  27298. if (!(this instanceof Range)) {
  27299. return new Range(start, end, step);
  27300. }
  27301. invariant(step !== 0, 'Cannot step a Range by 0');
  27302. start = start || 0;
  27303. if (end === undefined) {
  27304. end = Infinity;
  27305. }
  27306. step = step === undefined ? 1 : Math.abs(step);
  27307. if (end < start) {
  27308. step = -step;
  27309. }
  27310. this._start = start;
  27311. this._end = end;
  27312. this._step = step;
  27313. this.size = Math.max(0, Math.ceil((end - start) / step - 1) + 1);
  27314. if (this.size === 0) {
  27315. if (EMPTY_RANGE) {
  27316. return EMPTY_RANGE;
  27317. }
  27318. EMPTY_RANGE = this;
  27319. }
  27320. }
  27321. Range.prototype.toString = function() {
  27322. if (this.size === 0) {
  27323. return 'Range []';
  27324. }
  27325. return 'Range [ ' +
  27326. this._start + '...' + this._end +
  27327. (this._step > 1 ? ' by ' + this._step : '') +
  27328. ' ]';
  27329. };
  27330. Range.prototype.get = function(index, notSetValue) {
  27331. return this.has(index) ?
  27332. this._start + wrapIndex(this, index) * this._step :
  27333. notSetValue;
  27334. };
  27335. Range.prototype.includes = function(searchValue) {
  27336. var possibleIndex = (searchValue - this._start) / this._step;
  27337. return possibleIndex >= 0 &&
  27338. possibleIndex < this.size &&
  27339. possibleIndex === Math.floor(possibleIndex);
  27340. };
  27341. Range.prototype.slice = function(begin, end) {
  27342. if (wholeSlice(begin, end, this.size)) {
  27343. return this;
  27344. }
  27345. begin = resolveBegin(begin, this.size);
  27346. end = resolveEnd(end, this.size);
  27347. if (end <= begin) {
  27348. return new Range(0, 0);
  27349. }
  27350. return new Range(this.get(begin, this._end), this.get(end, this._end), this._step);
  27351. };
  27352. Range.prototype.indexOf = function(searchValue) {
  27353. var offsetValue = searchValue - this._start;
  27354. if (offsetValue % this._step === 0) {
  27355. var index = offsetValue / this._step;
  27356. if (index >= 0 && index < this.size) {
  27357. return index
  27358. }
  27359. }
  27360. return -1;
  27361. };
  27362. Range.prototype.lastIndexOf = function(searchValue) {
  27363. return this.indexOf(searchValue);
  27364. };
  27365. Range.prototype.__iterate = function(fn, reverse) {
  27366. var maxIndex = this.size - 1;
  27367. var step = this._step;
  27368. var value = reverse ? this._start + maxIndex * step : this._start;
  27369. for (var ii = 0; ii <= maxIndex; ii++) {
  27370. if (fn(value, ii, this) === false) {
  27371. return ii + 1;
  27372. }
  27373. value += reverse ? -step : step;
  27374. }
  27375. return ii;
  27376. };
  27377. Range.prototype.__iterator = function(type, reverse) {
  27378. var maxIndex = this.size - 1;
  27379. var step = this._step;
  27380. var value = reverse ? this._start + maxIndex * step : this._start;
  27381. var ii = 0;
  27382. return new Iterator(function() {
  27383. var v = value;
  27384. value += reverse ? -step : step;
  27385. return ii > maxIndex ? iteratorDone() : iteratorValue(type, ii++, v);
  27386. });
  27387. };
  27388. Range.prototype.equals = function(other) {
  27389. return other instanceof Range ?
  27390. this._start === other._start &&
  27391. this._end === other._end &&
  27392. this._step === other._step :
  27393. deepEqual(this, other);
  27394. };
  27395. var EMPTY_RANGE;
  27396. createClass(Collection, Iterable);
  27397. function Collection() {
  27398. throw TypeError('Abstract');
  27399. }
  27400. createClass(KeyedCollection, Collection);function KeyedCollection() {}
  27401. createClass(IndexedCollection, Collection);function IndexedCollection() {}
  27402. createClass(SetCollection, Collection);function SetCollection() {}
  27403. Collection.Keyed = KeyedCollection;
  27404. Collection.Indexed = IndexedCollection;
  27405. Collection.Set = SetCollection;
  27406. var imul =
  27407. typeof Math.imul === 'function' && Math.imul(0xffffffff, 2) === -2 ?
  27408. Math.imul :
  27409. function imul(a, b) {
  27410. a = a | 0; // int
  27411. b = b | 0; // int
  27412. var c = a & 0xffff;
  27413. var d = b & 0xffff;
  27414. // Shift by 0 fixes the sign on the high part.
  27415. return (c * d) + ((((a >>> 16) * d + c * (b >>> 16)) << 16) >>> 0) | 0; // int
  27416. };
  27417. // v8 has an optimization for storing 31-bit signed numbers.
  27418. // Values which have either 00 or 11 as the high order bits qualify.
  27419. // This function drops the highest order bit in a signed number, maintaining
  27420. // the sign bit.
  27421. function smi(i32) {
  27422. return ((i32 >>> 1) & 0x40000000) | (i32 & 0xBFFFFFFF);
  27423. }
  27424. function hash(o) {
  27425. if (o === false || o === null || o === undefined) {
  27426. return 0;
  27427. }
  27428. if (typeof o.valueOf === 'function') {
  27429. o = o.valueOf();
  27430. if (o === false || o === null || o === undefined) {
  27431. return 0;
  27432. }
  27433. }
  27434. if (o === true) {
  27435. return 1;
  27436. }
  27437. var type = typeof o;
  27438. if (type === 'number') {
  27439. var h = o | 0;
  27440. if (h !== o) {
  27441. h ^= o * 0xFFFFFFFF;
  27442. }
  27443. while (o > 0xFFFFFFFF) {
  27444. o /= 0xFFFFFFFF;
  27445. h ^= o;
  27446. }
  27447. return smi(h);
  27448. }
  27449. if (type === 'string') {
  27450. return o.length > STRING_HASH_CACHE_MIN_STRLEN ? cachedHashString(o) : hashString(o);
  27451. }
  27452. if (typeof o.hashCode === 'function') {
  27453. return o.hashCode();
  27454. }
  27455. if (type === 'object') {
  27456. return hashJSObj(o);
  27457. }
  27458. if (typeof o.toString === 'function') {
  27459. return hashString(o.toString());
  27460. }
  27461. throw new Error('Value type ' + type + ' cannot be hashed.');
  27462. }
  27463. function cachedHashString(string) {
  27464. var hash = stringHashCache[string];
  27465. if (hash === undefined) {
  27466. hash = hashString(string);
  27467. if (STRING_HASH_CACHE_SIZE === STRING_HASH_CACHE_MAX_SIZE) {
  27468. STRING_HASH_CACHE_SIZE = 0;
  27469. stringHashCache = {};
  27470. }
  27471. STRING_HASH_CACHE_SIZE++;
  27472. stringHashCache[string] = hash;
  27473. }
  27474. return hash;
  27475. }
  27476. // http://jsperf.com/hashing-strings
  27477. function hashString(string) {
  27478. // This is the hash from JVM
  27479. // The hash code for a string is computed as
  27480. // s[0] * 31 ^ (n - 1) + s[1] * 31 ^ (n - 2) + ... + s[n - 1],
  27481. // where s[i] is the ith character of the string and n is the length of
  27482. // the string. We "mod" the result to make it between 0 (inclusive) and 2^31
  27483. // (exclusive) by dropping high bits.
  27484. var hash = 0;
  27485. for (var ii = 0; ii < string.length; ii++) {
  27486. hash = 31 * hash + string.charCodeAt(ii) | 0;
  27487. }
  27488. return smi(hash);
  27489. }
  27490. function hashJSObj(obj) {
  27491. var hash;
  27492. if (usingWeakMap) {
  27493. hash = weakMap.get(obj);
  27494. if (hash !== undefined) {
  27495. return hash;
  27496. }
  27497. }
  27498. hash = obj[UID_HASH_KEY];
  27499. if (hash !== undefined) {
  27500. return hash;
  27501. }
  27502. if (!canDefineProperty) {
  27503. hash = obj.propertyIsEnumerable && obj.propertyIsEnumerable[UID_HASH_KEY];
  27504. if (hash !== undefined) {
  27505. return hash;
  27506. }
  27507. hash = getIENodeHash(obj);
  27508. if (hash !== undefined) {
  27509. return hash;
  27510. }
  27511. }
  27512. hash = ++objHashUID;
  27513. if (objHashUID & 0x40000000) {
  27514. objHashUID = 0;
  27515. }
  27516. if (usingWeakMap) {
  27517. weakMap.set(obj, hash);
  27518. } else if (isExtensible !== undefined && isExtensible(obj) === false) {
  27519. throw new Error('Non-extensible objects are not allowed as keys.');
  27520. } else if (canDefineProperty) {
  27521. Object.defineProperty(obj, UID_HASH_KEY, {
  27522. 'enumerable': false,
  27523. 'configurable': false,
  27524. 'writable': false,
  27525. 'value': hash
  27526. });
  27527. } else if (obj.propertyIsEnumerable !== undefined &&
  27528. obj.propertyIsEnumerable === obj.constructor.prototype.propertyIsEnumerable) {
  27529. // Since we can't define a non-enumerable property on the object
  27530. // we'll hijack one of the less-used non-enumerable properties to
  27531. // save our hash on it. Since this is a function it will not show up in
  27532. // `JSON.stringify` which is what we want.
  27533. obj.propertyIsEnumerable = function() {
  27534. return this.constructor.prototype.propertyIsEnumerable.apply(this, arguments);
  27535. };
  27536. obj.propertyIsEnumerable[UID_HASH_KEY] = hash;
  27537. } else if (obj.nodeType !== undefined) {
  27538. // At this point we couldn't get the IE `uniqueID` to use as a hash
  27539. // and we couldn't use a non-enumerable property to exploit the
  27540. // dontEnum bug so we simply add the `UID_HASH_KEY` on the node
  27541. // itself.
  27542. obj[UID_HASH_KEY] = hash;
  27543. } else {
  27544. throw new Error('Unable to set a non-enumerable property on object.');
  27545. }
  27546. return hash;
  27547. }
  27548. // Get references to ES5 object methods.
  27549. var isExtensible = Object.isExtensible;
  27550. // True if Object.defineProperty works as expected. IE8 fails this test.
  27551. var canDefineProperty = (function() {
  27552. try {
  27553. Object.defineProperty({}, '@', {});
  27554. return true;
  27555. } catch (e) {
  27556. return false;
  27557. }
  27558. }());
  27559. // IE has a `uniqueID` property on DOM nodes. We can construct the hash from it
  27560. // and avoid memory leaks from the IE cloneNode bug.
  27561. function getIENodeHash(node) {
  27562. if (node && node.nodeType > 0) {
  27563. switch (node.nodeType) {
  27564. case 1: // Element
  27565. return node.uniqueID;
  27566. case 9: // Document
  27567. return node.documentElement && node.documentElement.uniqueID;
  27568. }
  27569. }
  27570. }
  27571. // If possible, use a WeakMap.
  27572. var usingWeakMap = typeof WeakMap === 'function';
  27573. var weakMap;
  27574. if (usingWeakMap) {
  27575. weakMap = new WeakMap();
  27576. }
  27577. var objHashUID = 0;
  27578. var UID_HASH_KEY = '__immutablehash__';
  27579. if (typeof Symbol === 'function') {
  27580. UID_HASH_KEY = Symbol(UID_HASH_KEY);
  27581. }
  27582. var STRING_HASH_CACHE_MIN_STRLEN = 16;
  27583. var STRING_HASH_CACHE_MAX_SIZE = 255;
  27584. var STRING_HASH_CACHE_SIZE = 0;
  27585. var stringHashCache = {};
  27586. function assertNotInfinite(size) {
  27587. invariant(
  27588. size !== Infinity,
  27589. 'Cannot perform this action with an infinite size.'
  27590. );
  27591. }
  27592. createClass(Map, KeyedCollection);
  27593. // @pragma Construction
  27594. function Map(value) {
  27595. return value === null || value === undefined ? emptyMap() :
  27596. isMap(value) && !isOrdered(value) ? value :
  27597. emptyMap().withMutations(function(map ) {
  27598. var iter = KeyedIterable(value);
  27599. assertNotInfinite(iter.size);
  27600. iter.forEach(function(v, k) {return map.set(k, v)});
  27601. });
  27602. }
  27603. Map.prototype.toString = function() {
  27604. return this.__toString('Map {', '}');
  27605. };
  27606. // @pragma Access
  27607. Map.prototype.get = function(k, notSetValue) {
  27608. return this._root ?
  27609. this._root.get(0, undefined, k, notSetValue) :
  27610. notSetValue;
  27611. };
  27612. // @pragma Modification
  27613. Map.prototype.set = function(k, v) {
  27614. return updateMap(this, k, v);
  27615. };
  27616. Map.prototype.setIn = function(keyPath, v) {
  27617. return this.updateIn(keyPath, NOT_SET, function() {return v});
  27618. };
  27619. Map.prototype.remove = function(k) {
  27620. return updateMap(this, k, NOT_SET);
  27621. };
  27622. Map.prototype.deleteIn = function(keyPath) {
  27623. return this.updateIn(keyPath, function() {return NOT_SET});
  27624. };
  27625. Map.prototype.update = function(k, notSetValue, updater) {
  27626. return arguments.length === 1 ?
  27627. k(this) :
  27628. this.updateIn([k], notSetValue, updater);
  27629. };
  27630. Map.prototype.updateIn = function(keyPath, notSetValue, updater) {
  27631. if (!updater) {
  27632. updater = notSetValue;
  27633. notSetValue = undefined;
  27634. }
  27635. var updatedValue = updateInDeepMap(
  27636. this,
  27637. forceIterator(keyPath),
  27638. notSetValue,
  27639. updater
  27640. );
  27641. return updatedValue === NOT_SET ? undefined : updatedValue;
  27642. };
  27643. Map.prototype.clear = function() {
  27644. if (this.size === 0) {
  27645. return this;
  27646. }
  27647. if (this.__ownerID) {
  27648. this.size = 0;
  27649. this._root = null;
  27650. this.__hash = undefined;
  27651. this.__altered = true;
  27652. return this;
  27653. }
  27654. return emptyMap();
  27655. };
  27656. // @pragma Composition
  27657. Map.prototype.merge = function(/*...iters*/) {
  27658. return mergeIntoMapWith(this, undefined, arguments);
  27659. };
  27660. Map.prototype.mergeWith = function(merger) {var iters = SLICE$0.call(arguments, 1);
  27661. return mergeIntoMapWith(this, merger, iters);
  27662. };
  27663. Map.prototype.mergeIn = function(keyPath) {var iters = SLICE$0.call(arguments, 1);
  27664. return this.updateIn(
  27665. keyPath,
  27666. emptyMap(),
  27667. function(m ) {return typeof m.merge === 'function' ?
  27668. m.merge.apply(m, iters) :
  27669. iters[iters.length - 1]}
  27670. );
  27671. };
  27672. Map.prototype.mergeDeep = function(/*...iters*/) {
  27673. return mergeIntoMapWith(this, deepMerger, arguments);
  27674. };
  27675. Map.prototype.mergeDeepWith = function(merger) {var iters = SLICE$0.call(arguments, 1);
  27676. return mergeIntoMapWith(this, deepMergerWith(merger), iters);
  27677. };
  27678. Map.prototype.mergeDeepIn = function(keyPath) {var iters = SLICE$0.call(arguments, 1);
  27679. return this.updateIn(
  27680. keyPath,
  27681. emptyMap(),
  27682. function(m ) {return typeof m.mergeDeep === 'function' ?
  27683. m.mergeDeep.apply(m, iters) :
  27684. iters[iters.length - 1]}
  27685. );
  27686. };
  27687. Map.prototype.sort = function(comparator) {
  27688. // Late binding
  27689. return OrderedMap(sortFactory(this, comparator));
  27690. };
  27691. Map.prototype.sortBy = function(mapper, comparator) {
  27692. // Late binding
  27693. return OrderedMap(sortFactory(this, comparator, mapper));
  27694. };
  27695. // @pragma Mutability
  27696. Map.prototype.withMutations = function(fn) {
  27697. var mutable = this.asMutable();
  27698. fn(mutable);
  27699. return mutable.wasAltered() ? mutable.__ensureOwner(this.__ownerID) : this;
  27700. };
  27701. Map.prototype.asMutable = function() {
  27702. return this.__ownerID ? this : this.__ensureOwner(new OwnerID());
  27703. };
  27704. Map.prototype.asImmutable = function() {
  27705. return this.__ensureOwner();
  27706. };
  27707. Map.prototype.wasAltered = function() {
  27708. return this.__altered;
  27709. };
  27710. Map.prototype.__iterator = function(type, reverse) {
  27711. return new MapIterator(this, type, reverse);
  27712. };
  27713. Map.prototype.__iterate = function(fn, reverse) {var this$0 = this;
  27714. var iterations = 0;
  27715. this._root && this._root.iterate(function(entry ) {
  27716. iterations++;
  27717. return fn(entry[1], entry[0], this$0);
  27718. }, reverse);
  27719. return iterations;
  27720. };
  27721. Map.prototype.__ensureOwner = function(ownerID) {
  27722. if (ownerID === this.__ownerID) {
  27723. return this;
  27724. }
  27725. if (!ownerID) {
  27726. this.__ownerID = ownerID;
  27727. this.__altered = false;
  27728. return this;
  27729. }
  27730. return makeMap(this.size, this._root, ownerID, this.__hash);
  27731. };
  27732. function isMap(maybeMap) {
  27733. return !!(maybeMap && maybeMap[IS_MAP_SENTINEL]);
  27734. }
  27735. Map.isMap = isMap;
  27736. var IS_MAP_SENTINEL = '@@__IMMUTABLE_MAP__@@';
  27737. var MapPrototype = Map.prototype;
  27738. MapPrototype[IS_MAP_SENTINEL] = true;
  27739. MapPrototype[DELETE] = MapPrototype.remove;
  27740. MapPrototype.removeIn = MapPrototype.deleteIn;
  27741. // #pragma Trie Nodes
  27742. function ArrayMapNode(ownerID, entries) {
  27743. this.ownerID = ownerID;
  27744. this.entries = entries;
  27745. }
  27746. ArrayMapNode.prototype.get = function(shift, keyHash, key, notSetValue) {
  27747. var entries = this.entries;
  27748. for (var ii = 0, len = entries.length; ii < len; ii++) {
  27749. if (is(key, entries[ii][0])) {
  27750. return entries[ii][1];
  27751. }
  27752. }
  27753. return notSetValue;
  27754. };
  27755. ArrayMapNode.prototype.update = function(ownerID, shift, keyHash, key, value, didChangeSize, didAlter) {
  27756. var removed = value === NOT_SET;
  27757. var entries = this.entries;
  27758. var idx = 0;
  27759. for (var len = entries.length; idx < len; idx++) {
  27760. if (is(key, entries[idx][0])) {
  27761. break;
  27762. }
  27763. }
  27764. var exists = idx < len;
  27765. if (exists ? entries[idx][1] === value : removed) {
  27766. return this;
  27767. }
  27768. SetRef(didAlter);
  27769. (removed || !exists) && SetRef(didChangeSize);
  27770. if (removed && entries.length === 1) {
  27771. return; // undefined
  27772. }
  27773. if (!exists && !removed && entries.length >= MAX_ARRAY_MAP_SIZE) {
  27774. return createNodes(ownerID, entries, key, value);
  27775. }
  27776. var isEditable = ownerID && ownerID === this.ownerID;
  27777. var newEntries = isEditable ? entries : arrCopy(entries);
  27778. if (exists) {
  27779. if (removed) {
  27780. idx === len - 1 ? newEntries.pop() : (newEntries[idx] = newEntries.pop());
  27781. } else {
  27782. newEntries[idx] = [key, value];
  27783. }
  27784. } else {
  27785. newEntries.push([key, value]);
  27786. }
  27787. if (isEditable) {
  27788. this.entries = newEntries;
  27789. return this;
  27790. }
  27791. return new ArrayMapNode(ownerID, newEntries);
  27792. };
  27793. function BitmapIndexedNode(ownerID, bitmap, nodes) {
  27794. this.ownerID = ownerID;
  27795. this.bitmap = bitmap;
  27796. this.nodes = nodes;
  27797. }
  27798. BitmapIndexedNode.prototype.get = function(shift, keyHash, key, notSetValue) {
  27799. if (keyHash === undefined) {
  27800. keyHash = hash(key);
  27801. }
  27802. var bit = (1 << ((shift === 0 ? keyHash : keyHash >>> shift) & MASK));
  27803. var bitmap = this.bitmap;
  27804. return (bitmap & bit) === 0 ? notSetValue :
  27805. this.nodes[popCount(bitmap & (bit - 1))].get(shift + SHIFT, keyHash, key, notSetValue);
  27806. };
  27807. BitmapIndexedNode.prototype.update = function(ownerID, shift, keyHash, key, value, didChangeSize, didAlter) {
  27808. if (keyHash === undefined) {
  27809. keyHash = hash(key);
  27810. }
  27811. var keyHashFrag = (shift === 0 ? keyHash : keyHash >>> shift) & MASK;
  27812. var bit = 1 << keyHashFrag;
  27813. var bitmap = this.bitmap;
  27814. var exists = (bitmap & bit) !== 0;
  27815. if (!exists && value === NOT_SET) {
  27816. return this;
  27817. }
  27818. var idx = popCount(bitmap & (bit - 1));
  27819. var nodes = this.nodes;
  27820. var node = exists ? nodes[idx] : undefined;
  27821. var newNode = updateNode(node, ownerID, shift + SHIFT, keyHash, key, value, didChangeSize, didAlter);
  27822. if (newNode === node) {
  27823. return this;
  27824. }
  27825. if (!exists && newNode && nodes.length >= MAX_BITMAP_INDEXED_SIZE) {
  27826. return expandNodes(ownerID, nodes, bitmap, keyHashFrag, newNode);
  27827. }
  27828. if (exists && !newNode && nodes.length === 2 && isLeafNode(nodes[idx ^ 1])) {
  27829. return nodes[idx ^ 1];
  27830. }
  27831. if (exists && newNode && nodes.length === 1 && isLeafNode(newNode)) {
  27832. return newNode;
  27833. }
  27834. var isEditable = ownerID && ownerID === this.ownerID;
  27835. var newBitmap = exists ? newNode ? bitmap : bitmap ^ bit : bitmap | bit;
  27836. var newNodes = exists ? newNode ?
  27837. setIn(nodes, idx, newNode, isEditable) :
  27838. spliceOut(nodes, idx, isEditable) :
  27839. spliceIn(nodes, idx, newNode, isEditable);
  27840. if (isEditable) {
  27841. this.bitmap = newBitmap;
  27842. this.nodes = newNodes;
  27843. return this;
  27844. }
  27845. return new BitmapIndexedNode(ownerID, newBitmap, newNodes);
  27846. };
  27847. function HashArrayMapNode(ownerID, count, nodes) {
  27848. this.ownerID = ownerID;
  27849. this.count = count;
  27850. this.nodes = nodes;
  27851. }
  27852. HashArrayMapNode.prototype.get = function(shift, keyHash, key, notSetValue) {
  27853. if (keyHash === undefined) {
  27854. keyHash = hash(key);
  27855. }
  27856. var idx = (shift === 0 ? keyHash : keyHash >>> shift) & MASK;
  27857. var node = this.nodes[idx];
  27858. return node ? node.get(shift + SHIFT, keyHash, key, notSetValue) : notSetValue;
  27859. };
  27860. HashArrayMapNode.prototype.update = function(ownerID, shift, keyHash, key, value, didChangeSize, didAlter) {
  27861. if (keyHash === undefined) {
  27862. keyHash = hash(key);
  27863. }
  27864. var idx = (shift === 0 ? keyHash : keyHash >>> shift) & MASK;
  27865. var removed = value === NOT_SET;
  27866. var nodes = this.nodes;
  27867. var node = nodes[idx];
  27868. if (removed && !node) {
  27869. return this;
  27870. }
  27871. var newNode = updateNode(node, ownerID, shift + SHIFT, keyHash, key, value, didChangeSize, didAlter);
  27872. if (newNode === node) {
  27873. return this;
  27874. }
  27875. var newCount = this.count;
  27876. if (!node) {
  27877. newCount++;
  27878. } else if (!newNode) {
  27879. newCount--;
  27880. if (newCount < MIN_HASH_ARRAY_MAP_SIZE) {
  27881. return packNodes(ownerID, nodes, newCount, idx);
  27882. }
  27883. }
  27884. var isEditable = ownerID && ownerID === this.ownerID;
  27885. var newNodes = setIn(nodes, idx, newNode, isEditable);
  27886. if (isEditable) {
  27887. this.count = newCount;
  27888. this.nodes = newNodes;
  27889. return this;
  27890. }
  27891. return new HashArrayMapNode(ownerID, newCount, newNodes);
  27892. };
  27893. function HashCollisionNode(ownerID, keyHash, entries) {
  27894. this.ownerID = ownerID;
  27895. this.keyHash = keyHash;
  27896. this.entries = entries;
  27897. }
  27898. HashCollisionNode.prototype.get = function(shift, keyHash, key, notSetValue) {
  27899. var entries = this.entries;
  27900. for (var ii = 0, len = entries.length; ii < len; ii++) {
  27901. if (is(key, entries[ii][0])) {
  27902. return entries[ii][1];
  27903. }
  27904. }
  27905. return notSetValue;
  27906. };
  27907. HashCollisionNode.prototype.update = function(ownerID, shift, keyHash, key, value, didChangeSize, didAlter) {
  27908. if (keyHash === undefined) {
  27909. keyHash = hash(key);
  27910. }
  27911. var removed = value === NOT_SET;
  27912. if (keyHash !== this.keyHash) {
  27913. if (removed) {
  27914. return this;
  27915. }
  27916. SetRef(didAlter);
  27917. SetRef(didChangeSize);
  27918. return mergeIntoNode(this, ownerID, shift, keyHash, [key, value]);
  27919. }
  27920. var entries = this.entries;
  27921. var idx = 0;
  27922. for (var len = entries.length; idx < len; idx++) {
  27923. if (is(key, entries[idx][0])) {
  27924. break;
  27925. }
  27926. }
  27927. var exists = idx < len;
  27928. if (exists ? entries[idx][1] === value : removed) {
  27929. return this;
  27930. }
  27931. SetRef(didAlter);
  27932. (removed || !exists) && SetRef(didChangeSize);
  27933. if (removed && len === 2) {
  27934. return new ValueNode(ownerID, this.keyHash, entries[idx ^ 1]);
  27935. }
  27936. var isEditable = ownerID && ownerID === this.ownerID;
  27937. var newEntries = isEditable ? entries : arrCopy(entries);
  27938. if (exists) {
  27939. if (removed) {
  27940. idx === len - 1 ? newEntries.pop() : (newEntries[idx] = newEntries.pop());
  27941. } else {
  27942. newEntries[idx] = [key, value];
  27943. }
  27944. } else {
  27945. newEntries.push([key, value]);
  27946. }
  27947. if (isEditable) {
  27948. this.entries = newEntries;
  27949. return this;
  27950. }
  27951. return new HashCollisionNode(ownerID, this.keyHash, newEntries);
  27952. };
  27953. function ValueNode(ownerID, keyHash, entry) {
  27954. this.ownerID = ownerID;
  27955. this.keyHash = keyHash;
  27956. this.entry = entry;
  27957. }
  27958. ValueNode.prototype.get = function(shift, keyHash, key, notSetValue) {
  27959. return is(key, this.entry[0]) ? this.entry[1] : notSetValue;
  27960. };
  27961. ValueNode.prototype.update = function(ownerID, shift, keyHash, key, value, didChangeSize, didAlter) {
  27962. var removed = value === NOT_SET;
  27963. var keyMatch = is(key, this.entry[0]);
  27964. if (keyMatch ? value === this.entry[1] : removed) {
  27965. return this;
  27966. }
  27967. SetRef(didAlter);
  27968. if (removed) {
  27969. SetRef(didChangeSize);
  27970. return; // undefined
  27971. }
  27972. if (keyMatch) {
  27973. if (ownerID && ownerID === this.ownerID) {
  27974. this.entry[1] = value;
  27975. return this;
  27976. }
  27977. return new ValueNode(ownerID, this.keyHash, [key, value]);
  27978. }
  27979. SetRef(didChangeSize);
  27980. return mergeIntoNode(this, ownerID, shift, hash(key), [key, value]);
  27981. };
  27982. // #pragma Iterators
  27983. ArrayMapNode.prototype.iterate =
  27984. HashCollisionNode.prototype.iterate = function (fn, reverse) {
  27985. var entries = this.entries;
  27986. for (var ii = 0, maxIndex = entries.length - 1; ii <= maxIndex; ii++) {
  27987. if (fn(entries[reverse ? maxIndex - ii : ii]) === false) {
  27988. return false;
  27989. }
  27990. }
  27991. };
  27992. BitmapIndexedNode.prototype.iterate =
  27993. HashArrayMapNode.prototype.iterate = function (fn, reverse) {
  27994. var nodes = this.nodes;
  27995. for (var ii = 0, maxIndex = nodes.length - 1; ii <= maxIndex; ii++) {
  27996. var node = nodes[reverse ? maxIndex - ii : ii];
  27997. if (node && node.iterate(fn, reverse) === false) {
  27998. return false;
  27999. }
  28000. }
  28001. };
  28002. ValueNode.prototype.iterate = function (fn, reverse) {
  28003. return fn(this.entry);
  28004. };
  28005. createClass(MapIterator, Iterator);
  28006. function MapIterator(map, type, reverse) {
  28007. this._type = type;
  28008. this._reverse = reverse;
  28009. this._stack = map._root && mapIteratorFrame(map._root);
  28010. }
  28011. MapIterator.prototype.next = function() {
  28012. var type = this._type;
  28013. var stack = this._stack;
  28014. while (stack) {
  28015. var node = stack.node;
  28016. var index = stack.index++;
  28017. var maxIndex;
  28018. if (node.entry) {
  28019. if (index === 0) {
  28020. return mapIteratorValue(type, node.entry);
  28021. }
  28022. } else if (node.entries) {
  28023. maxIndex = node.entries.length - 1;
  28024. if (index <= maxIndex) {
  28025. return mapIteratorValue(type, node.entries[this._reverse ? maxIndex - index : index]);
  28026. }
  28027. } else {
  28028. maxIndex = node.nodes.length - 1;
  28029. if (index <= maxIndex) {
  28030. var subNode = node.nodes[this._reverse ? maxIndex - index : index];
  28031. if (subNode) {
  28032. if (subNode.entry) {
  28033. return mapIteratorValue(type, subNode.entry);
  28034. }
  28035. stack = this._stack = mapIteratorFrame(subNode, stack);
  28036. }
  28037. continue;
  28038. }
  28039. }
  28040. stack = this._stack = this._stack.__prev;
  28041. }
  28042. return iteratorDone();
  28043. };
  28044. function mapIteratorValue(type, entry) {
  28045. return iteratorValue(type, entry[0], entry[1]);
  28046. }
  28047. function mapIteratorFrame(node, prev) {
  28048. return {
  28049. node: node,
  28050. index: 0,
  28051. __prev: prev
  28052. };
  28053. }
  28054. function makeMap(size, root, ownerID, hash) {
  28055. var map = Object.create(MapPrototype);
  28056. map.size = size;
  28057. map._root = root;
  28058. map.__ownerID = ownerID;
  28059. map.__hash = hash;
  28060. map.__altered = false;
  28061. return map;
  28062. }
  28063. var EMPTY_MAP;
  28064. function emptyMap() {
  28065. return EMPTY_MAP || (EMPTY_MAP = makeMap(0));
  28066. }
  28067. function updateMap(map, k, v) {
  28068. var newRoot;
  28069. var newSize;
  28070. if (!map._root) {
  28071. if (v === NOT_SET) {
  28072. return map;
  28073. }
  28074. newSize = 1;
  28075. newRoot = new ArrayMapNode(map.__ownerID, [[k, v]]);
  28076. } else {
  28077. var didChangeSize = MakeRef(CHANGE_LENGTH);
  28078. var didAlter = MakeRef(DID_ALTER);
  28079. newRoot = updateNode(map._root, map.__ownerID, 0, undefined, k, v, didChangeSize, didAlter);
  28080. if (!didAlter.value) {
  28081. return map;
  28082. }
  28083. newSize = map.size + (didChangeSize.value ? v === NOT_SET ? -1 : 1 : 0);
  28084. }
  28085. if (map.__ownerID) {
  28086. map.size = newSize;
  28087. map._root = newRoot;
  28088. map.__hash = undefined;
  28089. map.__altered = true;
  28090. return map;
  28091. }
  28092. return newRoot ? makeMap(newSize, newRoot) : emptyMap();
  28093. }
  28094. function updateNode(node, ownerID, shift, keyHash, key, value, didChangeSize, didAlter) {
  28095. if (!node) {
  28096. if (value === NOT_SET) {
  28097. return node;
  28098. }
  28099. SetRef(didAlter);
  28100. SetRef(didChangeSize);
  28101. return new ValueNode(ownerID, keyHash, [key, value]);
  28102. }
  28103. return node.update(ownerID, shift, keyHash, key, value, didChangeSize, didAlter);
  28104. }
  28105. function isLeafNode(node) {
  28106. return node.constructor === ValueNode || node.constructor === HashCollisionNode;
  28107. }
  28108. function mergeIntoNode(node, ownerID, shift, keyHash, entry) {
  28109. if (node.keyHash === keyHash) {
  28110. return new HashCollisionNode(ownerID, keyHash, [node.entry, entry]);
  28111. }
  28112. var idx1 = (shift === 0 ? node.keyHash : node.keyHash >>> shift) & MASK;
  28113. var idx2 = (shift === 0 ? keyHash : keyHash >>> shift) & MASK;
  28114. var newNode;
  28115. var nodes = idx1 === idx2 ?
  28116. [mergeIntoNode(node, ownerID, shift + SHIFT, keyHash, entry)] :
  28117. ((newNode = new ValueNode(ownerID, keyHash, entry)), idx1 < idx2 ? [node, newNode] : [newNode, node]);
  28118. return new BitmapIndexedNode(ownerID, (1 << idx1) | (1 << idx2), nodes);
  28119. }
  28120. function createNodes(ownerID, entries, key, value) {
  28121. if (!ownerID) {
  28122. ownerID = new OwnerID();
  28123. }
  28124. var node = new ValueNode(ownerID, hash(key), [key, value]);
  28125. for (var ii = 0; ii < entries.length; ii++) {
  28126. var entry = entries[ii];
  28127. node = node.update(ownerID, 0, undefined, entry[0], entry[1]);
  28128. }
  28129. return node;
  28130. }
  28131. function packNodes(ownerID, nodes, count, excluding) {
  28132. var bitmap = 0;
  28133. var packedII = 0;
  28134. var packedNodes = new Array(count);
  28135. for (var ii = 0, bit = 1, len = nodes.length; ii < len; ii++, bit <<= 1) {
  28136. var node = nodes[ii];
  28137. if (node !== undefined && ii !== excluding) {
  28138. bitmap |= bit;
  28139. packedNodes[packedII++] = node;
  28140. }
  28141. }
  28142. return new BitmapIndexedNode(ownerID, bitmap, packedNodes);
  28143. }
  28144. function expandNodes(ownerID, nodes, bitmap, including, node) {
  28145. var count = 0;
  28146. var expandedNodes = new Array(SIZE);
  28147. for (var ii = 0; bitmap !== 0; ii++, bitmap >>>= 1) {
  28148. expandedNodes[ii] = bitmap & 1 ? nodes[count++] : undefined;
  28149. }
  28150. expandedNodes[including] = node;
  28151. return new HashArrayMapNode(ownerID, count + 1, expandedNodes);
  28152. }
  28153. function mergeIntoMapWith(map, merger, iterables) {
  28154. var iters = [];
  28155. for (var ii = 0; ii < iterables.length; ii++) {
  28156. var value = iterables[ii];
  28157. var iter = KeyedIterable(value);
  28158. if (!isIterable(value)) {
  28159. iter = iter.map(function(v ) {return fromJS(v)});
  28160. }
  28161. iters.push(iter);
  28162. }
  28163. return mergeIntoCollectionWith(map, merger, iters);
  28164. }
  28165. function deepMerger(existing, value, key) {
  28166. return existing && existing.mergeDeep && isIterable(value) ?
  28167. existing.mergeDeep(value) :
  28168. is(existing, value) ? existing : value;
  28169. }
  28170. function deepMergerWith(merger) {
  28171. return function(existing, value, key) {
  28172. if (existing && existing.mergeDeepWith && isIterable(value)) {
  28173. return existing.mergeDeepWith(merger, value);
  28174. }
  28175. var nextValue = merger(existing, value, key);
  28176. return is(existing, nextValue) ? existing : nextValue;
  28177. };
  28178. }
  28179. function mergeIntoCollectionWith(collection, merger, iters) {
  28180. iters = iters.filter(function(x ) {return x.size !== 0});
  28181. if (iters.length === 0) {
  28182. return collection;
  28183. }
  28184. if (collection.size === 0 && !collection.__ownerID && iters.length === 1) {
  28185. return collection.constructor(iters[0]);
  28186. }
  28187. return collection.withMutations(function(collection ) {
  28188. var mergeIntoMap = merger ?
  28189. function(value, key) {
  28190. collection.update(key, NOT_SET, function(existing )
  28191. {return existing === NOT_SET ? value : merger(existing, value, key)}
  28192. );
  28193. } :
  28194. function(value, key) {
  28195. collection.set(key, value);
  28196. };
  28197. for (var ii = 0; ii < iters.length; ii++) {
  28198. iters[ii].forEach(mergeIntoMap);
  28199. }
  28200. });
  28201. }
  28202. function updateInDeepMap(existing, keyPathIter, notSetValue, updater) {
  28203. var isNotSet = existing === NOT_SET;
  28204. var step = keyPathIter.next();
  28205. if (step.done) {
  28206. var existingValue = isNotSet ? notSetValue : existing;
  28207. var newValue = updater(existingValue);
  28208. return newValue === existingValue ? existing : newValue;
  28209. }
  28210. invariant(
  28211. isNotSet || (existing && existing.set),
  28212. 'invalid keyPath'
  28213. );
  28214. var key = step.value;
  28215. var nextExisting = isNotSet ? NOT_SET : existing.get(key, NOT_SET);
  28216. var nextUpdated = updateInDeepMap(
  28217. nextExisting,
  28218. keyPathIter,
  28219. notSetValue,
  28220. updater
  28221. );
  28222. return nextUpdated === nextExisting ? existing :
  28223. nextUpdated === NOT_SET ? existing.remove(key) :
  28224. (isNotSet ? emptyMap() : existing).set(key, nextUpdated);
  28225. }
  28226. function popCount(x) {
  28227. x = x - ((x >> 1) & 0x55555555);
  28228. x = (x & 0x33333333) + ((x >> 2) & 0x33333333);
  28229. x = (x + (x >> 4)) & 0x0f0f0f0f;
  28230. x = x + (x >> 8);
  28231. x = x + (x >> 16);
  28232. return x & 0x7f;
  28233. }
  28234. function setIn(array, idx, val, canEdit) {
  28235. var newArray = canEdit ? array : arrCopy(array);
  28236. newArray[idx] = val;
  28237. return newArray;
  28238. }
  28239. function spliceIn(array, idx, val, canEdit) {
  28240. var newLen = array.length + 1;
  28241. if (canEdit && idx + 1 === newLen) {
  28242. array[idx] = val;
  28243. return array;
  28244. }
  28245. var newArray = new Array(newLen);
  28246. var after = 0;
  28247. for (var ii = 0; ii < newLen; ii++) {
  28248. if (ii === idx) {
  28249. newArray[ii] = val;
  28250. after = -1;
  28251. } else {
  28252. newArray[ii] = array[ii + after];
  28253. }
  28254. }
  28255. return newArray;
  28256. }
  28257. function spliceOut(array, idx, canEdit) {
  28258. var newLen = array.length - 1;
  28259. if (canEdit && idx === newLen) {
  28260. array.pop();
  28261. return array;
  28262. }
  28263. var newArray = new Array(newLen);
  28264. var after = 0;
  28265. for (var ii = 0; ii < newLen; ii++) {
  28266. if (ii === idx) {
  28267. after = 1;
  28268. }
  28269. newArray[ii] = array[ii + after];
  28270. }
  28271. return newArray;
  28272. }
  28273. var MAX_ARRAY_MAP_SIZE = SIZE / 4;
  28274. var MAX_BITMAP_INDEXED_SIZE = SIZE / 2;
  28275. var MIN_HASH_ARRAY_MAP_SIZE = SIZE / 4;
  28276. createClass(List, IndexedCollection);
  28277. // @pragma Construction
  28278. function List(value) {
  28279. var empty = emptyList();
  28280. if (value === null || value === undefined) {
  28281. return empty;
  28282. }
  28283. if (isList(value)) {
  28284. return value;
  28285. }
  28286. var iter = IndexedIterable(value);
  28287. var size = iter.size;
  28288. if (size === 0) {
  28289. return empty;
  28290. }
  28291. assertNotInfinite(size);
  28292. if (size > 0 && size < SIZE) {
  28293. return makeList(0, size, SHIFT, null, new VNode(iter.toArray()));
  28294. }
  28295. return empty.withMutations(function(list ) {
  28296. list.setSize(size);
  28297. iter.forEach(function(v, i) {return list.set(i, v)});
  28298. });
  28299. }
  28300. List.of = function(/*...values*/) {
  28301. return this(arguments);
  28302. };
  28303. List.prototype.toString = function() {
  28304. return this.__toString('List [', ']');
  28305. };
  28306. // @pragma Access
  28307. List.prototype.get = function(index, notSetValue) {
  28308. index = wrapIndex(this, index);
  28309. if (index >= 0 && index < this.size) {
  28310. index += this._origin;
  28311. var node = listNodeFor(this, index);
  28312. return node && node.array[index & MASK];
  28313. }
  28314. return notSetValue;
  28315. };
  28316. // @pragma Modification
  28317. List.prototype.set = function(index, value) {
  28318. return updateList(this, index, value);
  28319. };
  28320. List.prototype.remove = function(index) {
  28321. return !this.has(index) ? this :
  28322. index === 0 ? this.shift() :
  28323. index === this.size - 1 ? this.pop() :
  28324. this.splice(index, 1);
  28325. };
  28326. List.prototype.insert = function(index, value) {
  28327. return this.splice(index, 0, value);
  28328. };
  28329. List.prototype.clear = function() {
  28330. if (this.size === 0) {
  28331. return this;
  28332. }
  28333. if (this.__ownerID) {
  28334. this.size = this._origin = this._capacity = 0;
  28335. this._level = SHIFT;
  28336. this._root = this._tail = null;
  28337. this.__hash = undefined;
  28338. this.__altered = true;
  28339. return this;
  28340. }
  28341. return emptyList();
  28342. };
  28343. List.prototype.push = function(/*...values*/) {
  28344. var values = arguments;
  28345. var oldSize = this.size;
  28346. return this.withMutations(function(list ) {
  28347. setListBounds(list, 0, oldSize + values.length);
  28348. for (var ii = 0; ii < values.length; ii++) {
  28349. list.set(oldSize + ii, values[ii]);
  28350. }
  28351. });
  28352. };
  28353. List.prototype.pop = function() {
  28354. return setListBounds(this, 0, -1);
  28355. };
  28356. List.prototype.unshift = function(/*...values*/) {
  28357. var values = arguments;
  28358. return this.withMutations(function(list ) {
  28359. setListBounds(list, -values.length);
  28360. for (var ii = 0; ii < values.length; ii++) {
  28361. list.set(ii, values[ii]);
  28362. }
  28363. });
  28364. };
  28365. List.prototype.shift = function() {
  28366. return setListBounds(this, 1);
  28367. };
  28368. // @pragma Composition
  28369. List.prototype.merge = function(/*...iters*/) {
  28370. return mergeIntoListWith(this, undefined, arguments);
  28371. };
  28372. List.prototype.mergeWith = function(merger) {var iters = SLICE$0.call(arguments, 1);
  28373. return mergeIntoListWith(this, merger, iters);
  28374. };
  28375. List.prototype.mergeDeep = function(/*...iters*/) {
  28376. return mergeIntoListWith(this, deepMerger, arguments);
  28377. };
  28378. List.prototype.mergeDeepWith = function(merger) {var iters = SLICE$0.call(arguments, 1);
  28379. return mergeIntoListWith(this, deepMergerWith(merger), iters);
  28380. };
  28381. List.prototype.setSize = function(size) {
  28382. return setListBounds(this, 0, size);
  28383. };
  28384. // @pragma Iteration
  28385. List.prototype.slice = function(begin, end) {
  28386. var size = this.size;
  28387. if (wholeSlice(begin, end, size)) {
  28388. return this;
  28389. }
  28390. return setListBounds(
  28391. this,
  28392. resolveBegin(begin, size),
  28393. resolveEnd(end, size)
  28394. );
  28395. };
  28396. List.prototype.__iterator = function(type, reverse) {
  28397. var index = 0;
  28398. var values = iterateList(this, reverse);
  28399. return new Iterator(function() {
  28400. var value = values();
  28401. return value === DONE ?
  28402. iteratorDone() :
  28403. iteratorValue(type, index++, value);
  28404. });
  28405. };
  28406. List.prototype.__iterate = function(fn, reverse) {
  28407. var index = 0;
  28408. var values = iterateList(this, reverse);
  28409. var value;
  28410. while ((value = values()) !== DONE) {
  28411. if (fn(value, index++, this) === false) {
  28412. break;
  28413. }
  28414. }
  28415. return index;
  28416. };
  28417. List.prototype.__ensureOwner = function(ownerID) {
  28418. if (ownerID === this.__ownerID) {
  28419. return this;
  28420. }
  28421. if (!ownerID) {
  28422. this.__ownerID = ownerID;
  28423. return this;
  28424. }
  28425. return makeList(this._origin, this._capacity, this._level, this._root, this._tail, ownerID, this.__hash);
  28426. };
  28427. function isList(maybeList) {
  28428. return !!(maybeList && maybeList[IS_LIST_SENTINEL]);
  28429. }
  28430. List.isList = isList;
  28431. var IS_LIST_SENTINEL = '@@__IMMUTABLE_LIST__@@';
  28432. var ListPrototype = List.prototype;
  28433. ListPrototype[IS_LIST_SENTINEL] = true;
  28434. ListPrototype[DELETE] = ListPrototype.remove;
  28435. ListPrototype.setIn = MapPrototype.setIn;
  28436. ListPrototype.deleteIn =
  28437. ListPrototype.removeIn = MapPrototype.removeIn;
  28438. ListPrototype.update = MapPrototype.update;
  28439. ListPrototype.updateIn = MapPrototype.updateIn;
  28440. ListPrototype.mergeIn = MapPrototype.mergeIn;
  28441. ListPrototype.mergeDeepIn = MapPrototype.mergeDeepIn;
  28442. ListPrototype.withMutations = MapPrototype.withMutations;
  28443. ListPrototype.asMutable = MapPrototype.asMutable;
  28444. ListPrototype.asImmutable = MapPrototype.asImmutable;
  28445. ListPrototype.wasAltered = MapPrototype.wasAltered;
  28446. function VNode(array, ownerID) {
  28447. this.array = array;
  28448. this.ownerID = ownerID;
  28449. }
  28450. // TODO: seems like these methods are very similar
  28451. VNode.prototype.removeBefore = function(ownerID, level, index) {
  28452. if (index === level ? 1 << level : this.array.length === 0) {
  28453. return this;
  28454. }
  28455. var originIndex = (index >>> level) & MASK;
  28456. if (originIndex >= this.array.length) {
  28457. return new VNode([], ownerID);
  28458. }
  28459. var removingFirst = originIndex === 0;
  28460. var newChild;
  28461. if (level > 0) {
  28462. var oldChild = this.array[originIndex];
  28463. newChild = oldChild && oldChild.removeBefore(ownerID, level - SHIFT, index);
  28464. if (newChild === oldChild && removingFirst) {
  28465. return this;
  28466. }
  28467. }
  28468. if (removingFirst && !newChild) {
  28469. return this;
  28470. }
  28471. var editable = editableVNode(this, ownerID);
  28472. if (!removingFirst) {
  28473. for (var ii = 0; ii < originIndex; ii++) {
  28474. editable.array[ii] = undefined;
  28475. }
  28476. }
  28477. if (newChild) {
  28478. editable.array[originIndex] = newChild;
  28479. }
  28480. return editable;
  28481. };
  28482. VNode.prototype.removeAfter = function(ownerID, level, index) {
  28483. if (index === (level ? 1 << level : 0) || this.array.length === 0) {
  28484. return this;
  28485. }
  28486. var sizeIndex = ((index - 1) >>> level) & MASK;
  28487. if (sizeIndex >= this.array.length) {
  28488. return this;
  28489. }
  28490. var newChild;
  28491. if (level > 0) {
  28492. var oldChild = this.array[sizeIndex];
  28493. newChild = oldChild && oldChild.removeAfter(ownerID, level - SHIFT, index);
  28494. if (newChild === oldChild && sizeIndex === this.array.length - 1) {
  28495. return this;
  28496. }
  28497. }
  28498. var editable = editableVNode(this, ownerID);
  28499. editable.array.splice(sizeIndex + 1);
  28500. if (newChild) {
  28501. editable.array[sizeIndex] = newChild;
  28502. }
  28503. return editable;
  28504. };
  28505. var DONE = {};
  28506. function iterateList(list, reverse) {
  28507. var left = list._origin;
  28508. var right = list._capacity;
  28509. var tailPos = getTailOffset(right);
  28510. var tail = list._tail;
  28511. return iterateNodeOrLeaf(list._root, list._level, 0);
  28512. function iterateNodeOrLeaf(node, level, offset) {
  28513. return level === 0 ?
  28514. iterateLeaf(node, offset) :
  28515. iterateNode(node, level, offset);
  28516. }
  28517. function iterateLeaf(node, offset) {
  28518. var array = offset === tailPos ? tail && tail.array : node && node.array;
  28519. var from = offset > left ? 0 : left - offset;
  28520. var to = right - offset;
  28521. if (to > SIZE) {
  28522. to = SIZE;
  28523. }
  28524. return function() {
  28525. if (from === to) {
  28526. return DONE;
  28527. }
  28528. var idx = reverse ? --to : from++;
  28529. return array && array[idx];
  28530. };
  28531. }
  28532. function iterateNode(node, level, offset) {
  28533. var values;
  28534. var array = node && node.array;
  28535. var from = offset > left ? 0 : (left - offset) >> level;
  28536. var to = ((right - offset) >> level) + 1;
  28537. if (to > SIZE) {
  28538. to = SIZE;
  28539. }
  28540. return function() {
  28541. do {
  28542. if (values) {
  28543. var value = values();
  28544. if (value !== DONE) {
  28545. return value;
  28546. }
  28547. values = null;
  28548. }
  28549. if (from === to) {
  28550. return DONE;
  28551. }
  28552. var idx = reverse ? --to : from++;
  28553. values = iterateNodeOrLeaf(
  28554. array && array[idx], level - SHIFT, offset + (idx << level)
  28555. );
  28556. } while (true);
  28557. };
  28558. }
  28559. }
  28560. function makeList(origin, capacity, level, root, tail, ownerID, hash) {
  28561. var list = Object.create(ListPrototype);
  28562. list.size = capacity - origin;
  28563. list._origin = origin;
  28564. list._capacity = capacity;
  28565. list._level = level;
  28566. list._root = root;
  28567. list._tail = tail;
  28568. list.__ownerID = ownerID;
  28569. list.__hash = hash;
  28570. list.__altered = false;
  28571. return list;
  28572. }
  28573. var EMPTY_LIST;
  28574. function emptyList() {
  28575. return EMPTY_LIST || (EMPTY_LIST = makeList(0, 0, SHIFT));
  28576. }
  28577. function updateList(list, index, value) {
  28578. index = wrapIndex(list, index);
  28579. if (index !== index) {
  28580. return list;
  28581. }
  28582. if (index >= list.size || index < 0) {
  28583. return list.withMutations(function(list ) {
  28584. index < 0 ?
  28585. setListBounds(list, index).set(0, value) :
  28586. setListBounds(list, 0, index + 1).set(index, value);
  28587. });
  28588. }
  28589. index += list._origin;
  28590. var newTail = list._tail;
  28591. var newRoot = list._root;
  28592. var didAlter = MakeRef(DID_ALTER);
  28593. if (index >= getTailOffset(list._capacity)) {
  28594. newTail = updateVNode(newTail, list.__ownerID, 0, index, value, didAlter);
  28595. } else {
  28596. newRoot = updateVNode(newRoot, list.__ownerID, list._level, index, value, didAlter);
  28597. }
  28598. if (!didAlter.value) {
  28599. return list;
  28600. }
  28601. if (list.__ownerID) {
  28602. list._root = newRoot;
  28603. list._tail = newTail;
  28604. list.__hash = undefined;
  28605. list.__altered = true;
  28606. return list;
  28607. }
  28608. return makeList(list._origin, list._capacity, list._level, newRoot, newTail);
  28609. }
  28610. function updateVNode(node, ownerID, level, index, value, didAlter) {
  28611. var idx = (index >>> level) & MASK;
  28612. var nodeHas = node && idx < node.array.length;
  28613. if (!nodeHas && value === undefined) {
  28614. return node;
  28615. }
  28616. var newNode;
  28617. if (level > 0) {
  28618. var lowerNode = node && node.array[idx];
  28619. var newLowerNode = updateVNode(lowerNode, ownerID, level - SHIFT, index, value, didAlter);
  28620. if (newLowerNode === lowerNode) {
  28621. return node;
  28622. }
  28623. newNode = editableVNode(node, ownerID);
  28624. newNode.array[idx] = newLowerNode;
  28625. return newNode;
  28626. }
  28627. if (nodeHas && node.array[idx] === value) {
  28628. return node;
  28629. }
  28630. SetRef(didAlter);
  28631. newNode = editableVNode(node, ownerID);
  28632. if (value === undefined && idx === newNode.array.length - 1) {
  28633. newNode.array.pop();
  28634. } else {
  28635. newNode.array[idx] = value;
  28636. }
  28637. return newNode;
  28638. }
  28639. function editableVNode(node, ownerID) {
  28640. if (ownerID && node && ownerID === node.ownerID) {
  28641. return node;
  28642. }
  28643. return new VNode(node ? node.array.slice() : [], ownerID);
  28644. }
  28645. function listNodeFor(list, rawIndex) {
  28646. if (rawIndex >= getTailOffset(list._capacity)) {
  28647. return list._tail;
  28648. }
  28649. if (rawIndex < 1 << (list._level + SHIFT)) {
  28650. var node = list._root;
  28651. var level = list._level;
  28652. while (node && level > 0) {
  28653. node = node.array[(rawIndex >>> level) & MASK];
  28654. level -= SHIFT;
  28655. }
  28656. return node;
  28657. }
  28658. }
  28659. function setListBounds(list, begin, end) {
  28660. // Sanitize begin & end using this shorthand for ToInt32(argument)
  28661. // http://www.ecma-international.org/ecma-262/6.0/#sec-toint32
  28662. if (begin !== undefined) {
  28663. begin = begin | 0;
  28664. }
  28665. if (end !== undefined) {
  28666. end = end | 0;
  28667. }
  28668. var owner = list.__ownerID || new OwnerID();
  28669. var oldOrigin = list._origin;
  28670. var oldCapacity = list._capacity;
  28671. var newOrigin = oldOrigin + begin;
  28672. var newCapacity = end === undefined ? oldCapacity : end < 0 ? oldCapacity + end : oldOrigin + end;
  28673. if (newOrigin === oldOrigin && newCapacity === oldCapacity) {
  28674. return list;
  28675. }
  28676. // If it's going to end after it starts, it's empty.
  28677. if (newOrigin >= newCapacity) {
  28678. return list.clear();
  28679. }
  28680. var newLevel = list._level;
  28681. var newRoot = list._root;
  28682. // New origin might need creating a higher root.
  28683. var offsetShift = 0;
  28684. while (newOrigin + offsetShift < 0) {
  28685. newRoot = new VNode(newRoot && newRoot.array.length ? [undefined, newRoot] : [], owner);
  28686. newLevel += SHIFT;
  28687. offsetShift += 1 << newLevel;
  28688. }
  28689. if (offsetShift) {
  28690. newOrigin += offsetShift;
  28691. oldOrigin += offsetShift;
  28692. newCapacity += offsetShift;
  28693. oldCapacity += offsetShift;
  28694. }
  28695. var oldTailOffset = getTailOffset(oldCapacity);
  28696. var newTailOffset = getTailOffset(newCapacity);
  28697. // New size might need creating a higher root.
  28698. while (newTailOffset >= 1 << (newLevel + SHIFT)) {
  28699. newRoot = new VNode(newRoot && newRoot.array.length ? [newRoot] : [], owner);
  28700. newLevel += SHIFT;
  28701. }
  28702. // Locate or create the new tail.
  28703. var oldTail = list._tail;
  28704. var newTail = newTailOffset < oldTailOffset ?
  28705. listNodeFor(list, newCapacity - 1) :
  28706. newTailOffset > oldTailOffset ? new VNode([], owner) : oldTail;
  28707. // Merge Tail into tree.
  28708. if (oldTail && newTailOffset > oldTailOffset && newOrigin < oldCapacity && oldTail.array.length) {
  28709. newRoot = editableVNode(newRoot, owner);
  28710. var node = newRoot;
  28711. for (var level = newLevel; level > SHIFT; level -= SHIFT) {
  28712. var idx = (oldTailOffset >>> level) & MASK;
  28713. node = node.array[idx] = editableVNode(node.array[idx], owner);
  28714. }
  28715. node.array[(oldTailOffset >>> SHIFT) & MASK] = oldTail;
  28716. }
  28717. // If the size has been reduced, there's a chance the tail needs to be trimmed.
  28718. if (newCapacity < oldCapacity) {
  28719. newTail = newTail && newTail.removeAfter(owner, 0, newCapacity);
  28720. }
  28721. // If the new origin is within the tail, then we do not need a root.
  28722. if (newOrigin >= newTailOffset) {
  28723. newOrigin -= newTailOffset;
  28724. newCapacity -= newTailOffset;
  28725. newLevel = SHIFT;
  28726. newRoot = null;
  28727. newTail = newTail && newTail.removeBefore(owner, 0, newOrigin);
  28728. // Otherwise, if the root has been trimmed, garbage collect.
  28729. } else if (newOrigin > oldOrigin || newTailOffset < oldTailOffset) {
  28730. offsetShift = 0;
  28731. // Identify the new top root node of the subtree of the old root.
  28732. while (newRoot) {
  28733. var beginIndex = (newOrigin >>> newLevel) & MASK;
  28734. if (beginIndex !== (newTailOffset >>> newLevel) & MASK) {
  28735. break;
  28736. }
  28737. if (beginIndex) {
  28738. offsetShift += (1 << newLevel) * beginIndex;
  28739. }
  28740. newLevel -= SHIFT;
  28741. newRoot = newRoot.array[beginIndex];
  28742. }
  28743. // Trim the new sides of the new root.
  28744. if (newRoot && newOrigin > oldOrigin) {
  28745. newRoot = newRoot.removeBefore(owner, newLevel, newOrigin - offsetShift);
  28746. }
  28747. if (newRoot && newTailOffset < oldTailOffset) {
  28748. newRoot = newRoot.removeAfter(owner, newLevel, newTailOffset - offsetShift);
  28749. }
  28750. if (offsetShift) {
  28751. newOrigin -= offsetShift;
  28752. newCapacity -= offsetShift;
  28753. }
  28754. }
  28755. if (list.__ownerID) {
  28756. list.size = newCapacity - newOrigin;
  28757. list._origin = newOrigin;
  28758. list._capacity = newCapacity;
  28759. list._level = newLevel;
  28760. list._root = newRoot;
  28761. list._tail = newTail;
  28762. list.__hash = undefined;
  28763. list.__altered = true;
  28764. return list;
  28765. }
  28766. return makeList(newOrigin, newCapacity, newLevel, newRoot, newTail);
  28767. }
  28768. function mergeIntoListWith(list, merger, iterables) {
  28769. var iters = [];
  28770. var maxSize = 0;
  28771. for (var ii = 0; ii < iterables.length; ii++) {
  28772. var value = iterables[ii];
  28773. var iter = IndexedIterable(value);
  28774. if (iter.size > maxSize) {
  28775. maxSize = iter.size;
  28776. }
  28777. if (!isIterable(value)) {
  28778. iter = iter.map(function(v ) {return fromJS(v)});
  28779. }
  28780. iters.push(iter);
  28781. }
  28782. if (maxSize > list.size) {
  28783. list = list.setSize(maxSize);
  28784. }
  28785. return mergeIntoCollectionWith(list, merger, iters);
  28786. }
  28787. function getTailOffset(size) {
  28788. return size < SIZE ? 0 : (((size - 1) >>> SHIFT) << SHIFT);
  28789. }
  28790. createClass(OrderedMap, Map);
  28791. // @pragma Construction
  28792. function OrderedMap(value) {
  28793. return value === null || value === undefined ? emptyOrderedMap() :
  28794. isOrderedMap(value) ? value :
  28795. emptyOrderedMap().withMutations(function(map ) {
  28796. var iter = KeyedIterable(value);
  28797. assertNotInfinite(iter.size);
  28798. iter.forEach(function(v, k) {return map.set(k, v)});
  28799. });
  28800. }
  28801. OrderedMap.of = function(/*...values*/) {
  28802. return this(arguments);
  28803. };
  28804. OrderedMap.prototype.toString = function() {
  28805. return this.__toString('OrderedMap {', '}');
  28806. };
  28807. // @pragma Access
  28808. OrderedMap.prototype.get = function(k, notSetValue) {
  28809. var index = this._map.get(k);
  28810. return index !== undefined ? this._list.get(index)[1] : notSetValue;
  28811. };
  28812. // @pragma Modification
  28813. OrderedMap.prototype.clear = function() {
  28814. if (this.size === 0) {
  28815. return this;
  28816. }
  28817. if (this.__ownerID) {
  28818. this.size = 0;
  28819. this._map.clear();
  28820. this._list.clear();
  28821. return this;
  28822. }
  28823. return emptyOrderedMap();
  28824. };
  28825. OrderedMap.prototype.set = function(k, v) {
  28826. return updateOrderedMap(this, k, v);
  28827. };
  28828. OrderedMap.prototype.remove = function(k) {
  28829. return updateOrderedMap(this, k, NOT_SET);
  28830. };
  28831. OrderedMap.prototype.wasAltered = function() {
  28832. return this._map.wasAltered() || this._list.wasAltered();
  28833. };
  28834. OrderedMap.prototype.__iterate = function(fn, reverse) {var this$0 = this;
  28835. return this._list.__iterate(
  28836. function(entry ) {return entry && fn(entry[1], entry[0], this$0)},
  28837. reverse
  28838. );
  28839. };
  28840. OrderedMap.prototype.__iterator = function(type, reverse) {
  28841. return this._list.fromEntrySeq().__iterator(type, reverse);
  28842. };
  28843. OrderedMap.prototype.__ensureOwner = function(ownerID) {
  28844. if (ownerID === this.__ownerID) {
  28845. return this;
  28846. }
  28847. var newMap = this._map.__ensureOwner(ownerID);
  28848. var newList = this._list.__ensureOwner(ownerID);
  28849. if (!ownerID) {
  28850. this.__ownerID = ownerID;
  28851. this._map = newMap;
  28852. this._list = newList;
  28853. return this;
  28854. }
  28855. return makeOrderedMap(newMap, newList, ownerID, this.__hash);
  28856. };
  28857. function isOrderedMap(maybeOrderedMap) {
  28858. return isMap(maybeOrderedMap) && isOrdered(maybeOrderedMap);
  28859. }
  28860. OrderedMap.isOrderedMap = isOrderedMap;
  28861. OrderedMap.prototype[IS_ORDERED_SENTINEL] = true;
  28862. OrderedMap.prototype[DELETE] = OrderedMap.prototype.remove;
  28863. function makeOrderedMap(map, list, ownerID, hash) {
  28864. var omap = Object.create(OrderedMap.prototype);
  28865. omap.size = map ? map.size : 0;
  28866. omap._map = map;
  28867. omap._list = list;
  28868. omap.__ownerID = ownerID;
  28869. omap.__hash = hash;
  28870. return omap;
  28871. }
  28872. var EMPTY_ORDERED_MAP;
  28873. function emptyOrderedMap() {
  28874. return EMPTY_ORDERED_MAP || (EMPTY_ORDERED_MAP = makeOrderedMap(emptyMap(), emptyList()));
  28875. }
  28876. function updateOrderedMap(omap, k, v) {
  28877. var map = omap._map;
  28878. var list = omap._list;
  28879. var i = map.get(k);
  28880. var has = i !== undefined;
  28881. var newMap;
  28882. var newList;
  28883. if (v === NOT_SET) { // removed
  28884. if (!has) {
  28885. return omap;
  28886. }
  28887. if (list.size >= SIZE && list.size >= map.size * 2) {
  28888. newList = list.filter(function(entry, idx) {return entry !== undefined && i !== idx});
  28889. newMap = newList.toKeyedSeq().map(function(entry ) {return entry[0]}).flip().toMap();
  28890. if (omap.__ownerID) {
  28891. newMap.__ownerID = newList.__ownerID = omap.__ownerID;
  28892. }
  28893. } else {
  28894. newMap = map.remove(k);
  28895. newList = i === list.size - 1 ? list.pop() : list.set(i, undefined);
  28896. }
  28897. } else {
  28898. if (has) {
  28899. if (v === list.get(i)[1]) {
  28900. return omap;
  28901. }
  28902. newMap = map;
  28903. newList = list.set(i, [k, v]);
  28904. } else {
  28905. newMap = map.set(k, list.size);
  28906. newList = list.set(list.size, [k, v]);
  28907. }
  28908. }
  28909. if (omap.__ownerID) {
  28910. omap.size = newMap.size;
  28911. omap._map = newMap;
  28912. omap._list = newList;
  28913. omap.__hash = undefined;
  28914. return omap;
  28915. }
  28916. return makeOrderedMap(newMap, newList);
  28917. }
  28918. createClass(ToKeyedSequence, KeyedSeq);
  28919. function ToKeyedSequence(indexed, useKeys) {
  28920. this._iter = indexed;
  28921. this._useKeys = useKeys;
  28922. this.size = indexed.size;
  28923. }
  28924. ToKeyedSequence.prototype.get = function(key, notSetValue) {
  28925. return this._iter.get(key, notSetValue);
  28926. };
  28927. ToKeyedSequence.prototype.has = function(key) {
  28928. return this._iter.has(key);
  28929. };
  28930. ToKeyedSequence.prototype.valueSeq = function() {
  28931. return this._iter.valueSeq();
  28932. };
  28933. ToKeyedSequence.prototype.reverse = function() {var this$0 = this;
  28934. var reversedSequence = reverseFactory(this, true);
  28935. if (!this._useKeys) {
  28936. reversedSequence.valueSeq = function() {return this$0._iter.toSeq().reverse()};
  28937. }
  28938. return reversedSequence;
  28939. };
  28940. ToKeyedSequence.prototype.map = function(mapper, context) {var this$0 = this;
  28941. var mappedSequence = mapFactory(this, mapper, context);
  28942. if (!this._useKeys) {
  28943. mappedSequence.valueSeq = function() {return this$0._iter.toSeq().map(mapper, context)};
  28944. }
  28945. return mappedSequence;
  28946. };
  28947. ToKeyedSequence.prototype.__iterate = function(fn, reverse) {var this$0 = this;
  28948. var ii;
  28949. return this._iter.__iterate(
  28950. this._useKeys ?
  28951. function(v, k) {return fn(v, k, this$0)} :
  28952. ((ii = reverse ? resolveSize(this) : 0),
  28953. function(v ) {return fn(v, reverse ? --ii : ii++, this$0)}),
  28954. reverse
  28955. );
  28956. };
  28957. ToKeyedSequence.prototype.__iterator = function(type, reverse) {
  28958. if (this._useKeys) {
  28959. return this._iter.__iterator(type, reverse);
  28960. }
  28961. var iterator = this._iter.__iterator(ITERATE_VALUES, reverse);
  28962. var ii = reverse ? resolveSize(this) : 0;
  28963. return new Iterator(function() {
  28964. var step = iterator.next();
  28965. return step.done ? step :
  28966. iteratorValue(type, reverse ? --ii : ii++, step.value, step);
  28967. });
  28968. };
  28969. ToKeyedSequence.prototype[IS_ORDERED_SENTINEL] = true;
  28970. createClass(ToIndexedSequence, IndexedSeq);
  28971. function ToIndexedSequence(iter) {
  28972. this._iter = iter;
  28973. this.size = iter.size;
  28974. }
  28975. ToIndexedSequence.prototype.includes = function(value) {
  28976. return this._iter.includes(value);
  28977. };
  28978. ToIndexedSequence.prototype.__iterate = function(fn, reverse) {var this$0 = this;
  28979. var iterations = 0;
  28980. return this._iter.__iterate(function(v ) {return fn(v, iterations++, this$0)}, reverse);
  28981. };
  28982. ToIndexedSequence.prototype.__iterator = function(type, reverse) {
  28983. var iterator = this._iter.__iterator(ITERATE_VALUES, reverse);
  28984. var iterations = 0;
  28985. return new Iterator(function() {
  28986. var step = iterator.next();
  28987. return step.done ? step :
  28988. iteratorValue(type, iterations++, step.value, step)
  28989. });
  28990. };
  28991. createClass(ToSetSequence, SetSeq);
  28992. function ToSetSequence(iter) {
  28993. this._iter = iter;
  28994. this.size = iter.size;
  28995. }
  28996. ToSetSequence.prototype.has = function(key) {
  28997. return this._iter.includes(key);
  28998. };
  28999. ToSetSequence.prototype.__iterate = function(fn, reverse) {var this$0 = this;
  29000. return this._iter.__iterate(function(v ) {return fn(v, v, this$0)}, reverse);
  29001. };
  29002. ToSetSequence.prototype.__iterator = function(type, reverse) {
  29003. var iterator = this._iter.__iterator(ITERATE_VALUES, reverse);
  29004. return new Iterator(function() {
  29005. var step = iterator.next();
  29006. return step.done ? step :
  29007. iteratorValue(type, step.value, step.value, step);
  29008. });
  29009. };
  29010. createClass(FromEntriesSequence, KeyedSeq);
  29011. function FromEntriesSequence(entries) {
  29012. this._iter = entries;
  29013. this.size = entries.size;
  29014. }
  29015. FromEntriesSequence.prototype.entrySeq = function() {
  29016. return this._iter.toSeq();
  29017. };
  29018. FromEntriesSequence.prototype.__iterate = function(fn, reverse) {var this$0 = this;
  29019. return this._iter.__iterate(function(entry ) {
  29020. // Check if entry exists first so array access doesn't throw for holes
  29021. // in the parent iteration.
  29022. if (entry) {
  29023. validateEntry(entry);
  29024. var indexedIterable = isIterable(entry);
  29025. return fn(
  29026. indexedIterable ? entry.get(1) : entry[1],
  29027. indexedIterable ? entry.get(0) : entry[0],
  29028. this$0
  29029. );
  29030. }
  29031. }, reverse);
  29032. };
  29033. FromEntriesSequence.prototype.__iterator = function(type, reverse) {
  29034. var iterator = this._iter.__iterator(ITERATE_VALUES, reverse);
  29035. return new Iterator(function() {
  29036. while (true) {
  29037. var step = iterator.next();
  29038. if (step.done) {
  29039. return step;
  29040. }
  29041. var entry = step.value;
  29042. // Check if entry exists first so array access doesn't throw for holes
  29043. // in the parent iteration.
  29044. if (entry) {
  29045. validateEntry(entry);
  29046. var indexedIterable = isIterable(entry);
  29047. return iteratorValue(
  29048. type,
  29049. indexedIterable ? entry.get(0) : entry[0],
  29050. indexedIterable ? entry.get(1) : entry[1],
  29051. step
  29052. );
  29053. }
  29054. }
  29055. });
  29056. };
  29057. ToIndexedSequence.prototype.cacheResult =
  29058. ToKeyedSequence.prototype.cacheResult =
  29059. ToSetSequence.prototype.cacheResult =
  29060. FromEntriesSequence.prototype.cacheResult =
  29061. cacheResultThrough;
  29062. function flipFactory(iterable) {
  29063. var flipSequence = makeSequence(iterable);
  29064. flipSequence._iter = iterable;
  29065. flipSequence.size = iterable.size;
  29066. flipSequence.flip = function() {return iterable};
  29067. flipSequence.reverse = function () {
  29068. var reversedSequence = iterable.reverse.apply(this); // super.reverse()
  29069. reversedSequence.flip = function() {return iterable.reverse()};
  29070. return reversedSequence;
  29071. };
  29072. flipSequence.has = function(key ) {return iterable.includes(key)};
  29073. flipSequence.includes = function(key ) {return iterable.has(key)};
  29074. flipSequence.cacheResult = cacheResultThrough;
  29075. flipSequence.__iterateUncached = function (fn, reverse) {var this$0 = this;
  29076. return iterable.__iterate(function(v, k) {return fn(k, v, this$0) !== false}, reverse);
  29077. };
  29078. flipSequence.__iteratorUncached = function(type, reverse) {
  29079. if (type === ITERATE_ENTRIES) {
  29080. var iterator = iterable.__iterator(type, reverse);
  29081. return new Iterator(function() {
  29082. var step = iterator.next();
  29083. if (!step.done) {
  29084. var k = step.value[0];
  29085. step.value[0] = step.value[1];
  29086. step.value[1] = k;
  29087. }
  29088. return step;
  29089. });
  29090. }
  29091. return iterable.__iterator(
  29092. type === ITERATE_VALUES ? ITERATE_KEYS : ITERATE_VALUES,
  29093. reverse
  29094. );
  29095. };
  29096. return flipSequence;
  29097. }
  29098. function mapFactory(iterable, mapper, context) {
  29099. var mappedSequence = makeSequence(iterable);
  29100. mappedSequence.size = iterable.size;
  29101. mappedSequence.has = function(key ) {return iterable.has(key)};
  29102. mappedSequence.get = function(key, notSetValue) {
  29103. var v = iterable.get(key, NOT_SET);
  29104. return v === NOT_SET ?
  29105. notSetValue :
  29106. mapper.call(context, v, key, iterable);
  29107. };
  29108. mappedSequence.__iterateUncached = function (fn, reverse) {var this$0 = this;
  29109. return iterable.__iterate(
  29110. function(v, k, c) {return fn(mapper.call(context, v, k, c), k, this$0) !== false},
  29111. reverse
  29112. );
  29113. };
  29114. mappedSequence.__iteratorUncached = function (type, reverse) {
  29115. var iterator = iterable.__iterator(ITERATE_ENTRIES, reverse);
  29116. return new Iterator(function() {
  29117. var step = iterator.next();
  29118. if (step.done) {
  29119. return step;
  29120. }
  29121. var entry = step.value;
  29122. var key = entry[0];
  29123. return iteratorValue(
  29124. type,
  29125. key,
  29126. mapper.call(context, entry[1], key, iterable),
  29127. step
  29128. );
  29129. });
  29130. };
  29131. return mappedSequence;
  29132. }
  29133. function reverseFactory(iterable, useKeys) {
  29134. var reversedSequence = makeSequence(iterable);
  29135. reversedSequence._iter = iterable;
  29136. reversedSequence.size = iterable.size;
  29137. reversedSequence.reverse = function() {return iterable};
  29138. if (iterable.flip) {
  29139. reversedSequence.flip = function () {
  29140. var flipSequence = flipFactory(iterable);
  29141. flipSequence.reverse = function() {return iterable.flip()};
  29142. return flipSequence;
  29143. };
  29144. }
  29145. reversedSequence.get = function(key, notSetValue)
  29146. {return iterable.get(useKeys ? key : -1 - key, notSetValue)};
  29147. reversedSequence.has = function(key )
  29148. {return iterable.has(useKeys ? key : -1 - key)};
  29149. reversedSequence.includes = function(value ) {return iterable.includes(value)};
  29150. reversedSequence.cacheResult = cacheResultThrough;
  29151. reversedSequence.__iterate = function (fn, reverse) {var this$0 = this;
  29152. return iterable.__iterate(function(v, k) {return fn(v, k, this$0)}, !reverse);
  29153. };
  29154. reversedSequence.__iterator =
  29155. function(type, reverse) {return iterable.__iterator(type, !reverse)};
  29156. return reversedSequence;
  29157. }
  29158. function filterFactory(iterable, predicate, context, useKeys) {
  29159. var filterSequence = makeSequence(iterable);
  29160. if (useKeys) {
  29161. filterSequence.has = function(key ) {
  29162. var v = iterable.get(key, NOT_SET);
  29163. return v !== NOT_SET && !!predicate.call(context, v, key, iterable);
  29164. };
  29165. filterSequence.get = function(key, notSetValue) {
  29166. var v = iterable.get(key, NOT_SET);
  29167. return v !== NOT_SET && predicate.call(context, v, key, iterable) ?
  29168. v : notSetValue;
  29169. };
  29170. }
  29171. filterSequence.__iterateUncached = function (fn, reverse) {var this$0 = this;
  29172. var iterations = 0;
  29173. iterable.__iterate(function(v, k, c) {
  29174. if (predicate.call(context, v, k, c)) {
  29175. iterations++;
  29176. return fn(v, useKeys ? k : iterations - 1, this$0);
  29177. }
  29178. }, reverse);
  29179. return iterations;
  29180. };
  29181. filterSequence.__iteratorUncached = function (type, reverse) {
  29182. var iterator = iterable.__iterator(ITERATE_ENTRIES, reverse);
  29183. var iterations = 0;
  29184. return new Iterator(function() {
  29185. while (true) {
  29186. var step = iterator.next();
  29187. if (step.done) {
  29188. return step;
  29189. }
  29190. var entry = step.value;
  29191. var key = entry[0];
  29192. var value = entry[1];
  29193. if (predicate.call(context, value, key, iterable)) {
  29194. return iteratorValue(type, useKeys ? key : iterations++, value, step);
  29195. }
  29196. }
  29197. });
  29198. };
  29199. return filterSequence;
  29200. }
  29201. function countByFactory(iterable, grouper, context) {
  29202. var groups = Map().asMutable();
  29203. iterable.__iterate(function(v, k) {
  29204. groups.update(
  29205. grouper.call(context, v, k, iterable),
  29206. 0,
  29207. function(a ) {return a + 1}
  29208. );
  29209. });
  29210. return groups.asImmutable();
  29211. }
  29212. function groupByFactory(iterable, grouper, context) {
  29213. var isKeyedIter = isKeyed(iterable);
  29214. var groups = (isOrdered(iterable) ? OrderedMap() : Map()).asMutable();
  29215. iterable.__iterate(function(v, k) {
  29216. groups.update(
  29217. grouper.call(context, v, k, iterable),
  29218. function(a ) {return (a = a || [], a.push(isKeyedIter ? [k, v] : v), a)}
  29219. );
  29220. });
  29221. var coerce = iterableClass(iterable);
  29222. return groups.map(function(arr ) {return reify(iterable, coerce(arr))});
  29223. }
  29224. function sliceFactory(iterable, begin, end, useKeys) {
  29225. var originalSize = iterable.size;
  29226. // Sanitize begin & end using this shorthand for ToInt32(argument)
  29227. // http://www.ecma-international.org/ecma-262/6.0/#sec-toint32
  29228. if (begin !== undefined) {
  29229. begin = begin | 0;
  29230. }
  29231. if (end !== undefined) {
  29232. end = end | 0;
  29233. }
  29234. if (wholeSlice(begin, end, originalSize)) {
  29235. return iterable;
  29236. }
  29237. var resolvedBegin = resolveBegin(begin, originalSize);
  29238. var resolvedEnd = resolveEnd(end, originalSize);
  29239. // begin or end will be NaN if they were provided as negative numbers and
  29240. // this iterable's size is unknown. In that case, cache first so there is
  29241. // a known size and these do not resolve to NaN.
  29242. if (resolvedBegin !== resolvedBegin || resolvedEnd !== resolvedEnd) {
  29243. return sliceFactory(iterable.toSeq().cacheResult(), begin, end, useKeys);
  29244. }
  29245. // Note: resolvedEnd is undefined when the original sequence's length is
  29246. // unknown and this slice did not supply an end and should contain all
  29247. // elements after resolvedBegin.
  29248. // In that case, resolvedSize will be NaN and sliceSize will remain undefined.
  29249. var resolvedSize = resolvedEnd - resolvedBegin;
  29250. var sliceSize;
  29251. if (resolvedSize === resolvedSize) {
  29252. sliceSize = resolvedSize < 0 ? 0 : resolvedSize;
  29253. }
  29254. var sliceSeq = makeSequence(iterable);
  29255. // If iterable.size is undefined, the size of the realized sliceSeq is
  29256. // unknown at this point unless the number of items to slice is 0
  29257. sliceSeq.size = sliceSize === 0 ? sliceSize : iterable.size && sliceSize || undefined;
  29258. if (!useKeys && isSeq(iterable) && sliceSize >= 0) {
  29259. sliceSeq.get = function (index, notSetValue) {
  29260. index = wrapIndex(this, index);
  29261. return index >= 0 && index < sliceSize ?
  29262. iterable.get(index + resolvedBegin, notSetValue) :
  29263. notSetValue;
  29264. };
  29265. }
  29266. sliceSeq.__iterateUncached = function(fn, reverse) {var this$0 = this;
  29267. if (sliceSize === 0) {
  29268. return 0;
  29269. }
  29270. if (reverse) {
  29271. return this.cacheResult().__iterate(fn, reverse);
  29272. }
  29273. var skipped = 0;
  29274. var isSkipping = true;
  29275. var iterations = 0;
  29276. iterable.__iterate(function(v, k) {
  29277. if (!(isSkipping && (isSkipping = skipped++ < resolvedBegin))) {
  29278. iterations++;
  29279. return fn(v, useKeys ? k : iterations - 1, this$0) !== false &&
  29280. iterations !== sliceSize;
  29281. }
  29282. });
  29283. return iterations;
  29284. };
  29285. sliceSeq.__iteratorUncached = function(type, reverse) {
  29286. if (sliceSize !== 0 && reverse) {
  29287. return this.cacheResult().__iterator(type, reverse);
  29288. }
  29289. // Don't bother instantiating parent iterator if taking 0.
  29290. var iterator = sliceSize !== 0 && iterable.__iterator(type, reverse);
  29291. var skipped = 0;
  29292. var iterations = 0;
  29293. return new Iterator(function() {
  29294. while (skipped++ < resolvedBegin) {
  29295. iterator.next();
  29296. }
  29297. if (++iterations > sliceSize) {
  29298. return iteratorDone();
  29299. }
  29300. var step = iterator.next();
  29301. if (useKeys || type === ITERATE_VALUES) {
  29302. return step;
  29303. } else if (type === ITERATE_KEYS) {
  29304. return iteratorValue(type, iterations - 1, undefined, step);
  29305. } else {
  29306. return iteratorValue(type, iterations - 1, step.value[1], step);
  29307. }
  29308. });
  29309. };
  29310. return sliceSeq;
  29311. }
  29312. function takeWhileFactory(iterable, predicate, context) {
  29313. var takeSequence = makeSequence(iterable);
  29314. takeSequence.__iterateUncached = function(fn, reverse) {var this$0 = this;
  29315. if (reverse) {
  29316. return this.cacheResult().__iterate(fn, reverse);
  29317. }
  29318. var iterations = 0;
  29319. iterable.__iterate(function(v, k, c)
  29320. {return predicate.call(context, v, k, c) && ++iterations && fn(v, k, this$0)}
  29321. );
  29322. return iterations;
  29323. };
  29324. takeSequence.__iteratorUncached = function(type, reverse) {var this$0 = this;
  29325. if (reverse) {
  29326. return this.cacheResult().__iterator(type, reverse);
  29327. }
  29328. var iterator = iterable.__iterator(ITERATE_ENTRIES, reverse);
  29329. var iterating = true;
  29330. return new Iterator(function() {
  29331. if (!iterating) {
  29332. return iteratorDone();
  29333. }
  29334. var step = iterator.next();
  29335. if (step.done) {
  29336. return step;
  29337. }
  29338. var entry = step.value;
  29339. var k = entry[0];
  29340. var v = entry[1];
  29341. if (!predicate.call(context, v, k, this$0)) {
  29342. iterating = false;
  29343. return iteratorDone();
  29344. }
  29345. return type === ITERATE_ENTRIES ? step :
  29346. iteratorValue(type, k, v, step);
  29347. });
  29348. };
  29349. return takeSequence;
  29350. }
  29351. function skipWhileFactory(iterable, predicate, context, useKeys) {
  29352. var skipSequence = makeSequence(iterable);
  29353. skipSequence.__iterateUncached = function (fn, reverse) {var this$0 = this;
  29354. if (reverse) {
  29355. return this.cacheResult().__iterate(fn, reverse);
  29356. }
  29357. var isSkipping = true;
  29358. var iterations = 0;
  29359. iterable.__iterate(function(v, k, c) {
  29360. if (!(isSkipping && (isSkipping = predicate.call(context, v, k, c)))) {
  29361. iterations++;
  29362. return fn(v, useKeys ? k : iterations - 1, this$0);
  29363. }
  29364. });
  29365. return iterations;
  29366. };
  29367. skipSequence.__iteratorUncached = function(type, reverse) {var this$0 = this;
  29368. if (reverse) {
  29369. return this.cacheResult().__iterator(type, reverse);
  29370. }
  29371. var iterator = iterable.__iterator(ITERATE_ENTRIES, reverse);
  29372. var skipping = true;
  29373. var iterations = 0;
  29374. return new Iterator(function() {
  29375. var step, k, v;
  29376. do {
  29377. step = iterator.next();
  29378. if (step.done) {
  29379. if (useKeys || type === ITERATE_VALUES) {
  29380. return step;
  29381. } else if (type === ITERATE_KEYS) {
  29382. return iteratorValue(type, iterations++, undefined, step);
  29383. } else {
  29384. return iteratorValue(type, iterations++, step.value[1], step);
  29385. }
  29386. }
  29387. var entry = step.value;
  29388. k = entry[0];
  29389. v = entry[1];
  29390. skipping && (skipping = predicate.call(context, v, k, this$0));
  29391. } while (skipping);
  29392. return type === ITERATE_ENTRIES ? step :
  29393. iteratorValue(type, k, v, step);
  29394. });
  29395. };
  29396. return skipSequence;
  29397. }
  29398. function concatFactory(iterable, values) {
  29399. var isKeyedIterable = isKeyed(iterable);
  29400. var iters = [iterable].concat(values).map(function(v ) {
  29401. if (!isIterable(v)) {
  29402. v = isKeyedIterable ?
  29403. keyedSeqFromValue(v) :
  29404. indexedSeqFromValue(Array.isArray(v) ? v : [v]);
  29405. } else if (isKeyedIterable) {
  29406. v = KeyedIterable(v);
  29407. }
  29408. return v;
  29409. }).filter(function(v ) {return v.size !== 0});
  29410. if (iters.length === 0) {
  29411. return iterable;
  29412. }
  29413. if (iters.length === 1) {
  29414. var singleton = iters[0];
  29415. if (singleton === iterable ||
  29416. isKeyedIterable && isKeyed(singleton) ||
  29417. isIndexed(iterable) && isIndexed(singleton)) {
  29418. return singleton;
  29419. }
  29420. }
  29421. var concatSeq = new ArraySeq(iters);
  29422. if (isKeyedIterable) {
  29423. concatSeq = concatSeq.toKeyedSeq();
  29424. } else if (!isIndexed(iterable)) {
  29425. concatSeq = concatSeq.toSetSeq();
  29426. }
  29427. concatSeq = concatSeq.flatten(true);
  29428. concatSeq.size = iters.reduce(
  29429. function(sum, seq) {
  29430. if (sum !== undefined) {
  29431. var size = seq.size;
  29432. if (size !== undefined) {
  29433. return sum + size;
  29434. }
  29435. }
  29436. },
  29437. 0
  29438. );
  29439. return concatSeq;
  29440. }
  29441. function flattenFactory(iterable, depth, useKeys) {
  29442. var flatSequence = makeSequence(iterable);
  29443. flatSequence.__iterateUncached = function(fn, reverse) {
  29444. var iterations = 0;
  29445. var stopped = false;
  29446. function flatDeep(iter, currentDepth) {var this$0 = this;
  29447. iter.__iterate(function(v, k) {
  29448. if ((!depth || currentDepth < depth) && isIterable(v)) {
  29449. flatDeep(v, currentDepth + 1);
  29450. } else if (fn(v, useKeys ? k : iterations++, this$0) === false) {
  29451. stopped = true;
  29452. }
  29453. return !stopped;
  29454. }, reverse);
  29455. }
  29456. flatDeep(iterable, 0);
  29457. return iterations;
  29458. };
  29459. flatSequence.__iteratorUncached = function(type, reverse) {
  29460. var iterator = iterable.__iterator(type, reverse);
  29461. var stack = [];
  29462. var iterations = 0;
  29463. return new Iterator(function() {
  29464. while (iterator) {
  29465. var step = iterator.next();
  29466. if (step.done !== false) {
  29467. iterator = stack.pop();
  29468. continue;
  29469. }
  29470. var v = step.value;
  29471. if (type === ITERATE_ENTRIES) {
  29472. v = v[1];
  29473. }
  29474. if ((!depth || stack.length < depth) && isIterable(v)) {
  29475. stack.push(iterator);
  29476. iterator = v.__iterator(type, reverse);
  29477. } else {
  29478. return useKeys ? step : iteratorValue(type, iterations++, v, step);
  29479. }
  29480. }
  29481. return iteratorDone();
  29482. });
  29483. };
  29484. return flatSequence;
  29485. }
  29486. function flatMapFactory(iterable, mapper, context) {
  29487. var coerce = iterableClass(iterable);
  29488. return iterable.toSeq().map(
  29489. function(v, k) {return coerce(mapper.call(context, v, k, iterable))}
  29490. ).flatten(true);
  29491. }
  29492. function interposeFactory(iterable, separator) {
  29493. var interposedSequence = makeSequence(iterable);
  29494. interposedSequence.size = iterable.size && iterable.size * 2 -1;
  29495. interposedSequence.__iterateUncached = function(fn, reverse) {var this$0 = this;
  29496. var iterations = 0;
  29497. iterable.__iterate(function(v, k)
  29498. {return (!iterations || fn(separator, iterations++, this$0) !== false) &&
  29499. fn(v, iterations++, this$0) !== false},
  29500. reverse
  29501. );
  29502. return iterations;
  29503. };
  29504. interposedSequence.__iteratorUncached = function(type, reverse) {
  29505. var iterator = iterable.__iterator(ITERATE_VALUES, reverse);
  29506. var iterations = 0;
  29507. var step;
  29508. return new Iterator(function() {
  29509. if (!step || iterations % 2) {
  29510. step = iterator.next();
  29511. if (step.done) {
  29512. return step;
  29513. }
  29514. }
  29515. return iterations % 2 ?
  29516. iteratorValue(type, iterations++, separator) :
  29517. iteratorValue(type, iterations++, step.value, step);
  29518. });
  29519. };
  29520. return interposedSequence;
  29521. }
  29522. function sortFactory(iterable, comparator, mapper) {
  29523. if (!comparator) {
  29524. comparator = defaultComparator;
  29525. }
  29526. var isKeyedIterable = isKeyed(iterable);
  29527. var index = 0;
  29528. var entries = iterable.toSeq().map(
  29529. function(v, k) {return [k, v, index++, mapper ? mapper(v, k, iterable) : v]}
  29530. ).toArray();
  29531. entries.sort(function(a, b) {return comparator(a[3], b[3]) || a[2] - b[2]}).forEach(
  29532. isKeyedIterable ?
  29533. function(v, i) { entries[i].length = 2; } :
  29534. function(v, i) { entries[i] = v[1]; }
  29535. );
  29536. return isKeyedIterable ? KeyedSeq(entries) :
  29537. isIndexed(iterable) ? IndexedSeq(entries) :
  29538. SetSeq(entries);
  29539. }
  29540. function maxFactory(iterable, comparator, mapper) {
  29541. if (!comparator) {
  29542. comparator = defaultComparator;
  29543. }
  29544. if (mapper) {
  29545. var entry = iterable.toSeq()
  29546. .map(function(v, k) {return [v, mapper(v, k, iterable)]})
  29547. .reduce(function(a, b) {return maxCompare(comparator, a[1], b[1]) ? b : a});
  29548. return entry && entry[0];
  29549. } else {
  29550. return iterable.reduce(function(a, b) {return maxCompare(comparator, a, b) ? b : a});
  29551. }
  29552. }
  29553. function maxCompare(comparator, a, b) {
  29554. var comp = comparator(b, a);
  29555. // b is considered the new max if the comparator declares them equal, but
  29556. // they are not equal and b is in fact a nullish value.
  29557. return (comp === 0 && b !== a && (b === undefined || b === null || b !== b)) || comp > 0;
  29558. }
  29559. function zipWithFactory(keyIter, zipper, iters) {
  29560. var zipSequence = makeSequence(keyIter);
  29561. zipSequence.size = new ArraySeq(iters).map(function(i ) {return i.size}).min();
  29562. // Note: this a generic base implementation of __iterate in terms of
  29563. // __iterator which may be more generically useful in the future.
  29564. zipSequence.__iterate = function(fn, reverse) {
  29565. /* generic:
  29566. var iterator = this.__iterator(ITERATE_ENTRIES, reverse);
  29567. var step;
  29568. var iterations = 0;
  29569. while (!(step = iterator.next()).done) {
  29570. iterations++;
  29571. if (fn(step.value[1], step.value[0], this) === false) {
  29572. break;
  29573. }
  29574. }
  29575. return iterations;
  29576. */
  29577. // indexed:
  29578. var iterator = this.__iterator(ITERATE_VALUES, reverse);
  29579. var step;
  29580. var iterations = 0;
  29581. while (!(step = iterator.next()).done) {
  29582. if (fn(step.value, iterations++, this) === false) {
  29583. break;
  29584. }
  29585. }
  29586. return iterations;
  29587. };
  29588. zipSequence.__iteratorUncached = function(type, reverse) {
  29589. var iterators = iters.map(function(i )
  29590. {return (i = Iterable(i), getIterator(reverse ? i.reverse() : i))}
  29591. );
  29592. var iterations = 0;
  29593. var isDone = false;
  29594. return new Iterator(function() {
  29595. var steps;
  29596. if (!isDone) {
  29597. steps = iterators.map(function(i ) {return i.next()});
  29598. isDone = steps.some(function(s ) {return s.done});
  29599. }
  29600. if (isDone) {
  29601. return iteratorDone();
  29602. }
  29603. return iteratorValue(
  29604. type,
  29605. iterations++,
  29606. zipper.apply(null, steps.map(function(s ) {return s.value}))
  29607. );
  29608. });
  29609. };
  29610. return zipSequence
  29611. }
  29612. // #pragma Helper Functions
  29613. function reify(iter, seq) {
  29614. return isSeq(iter) ? seq : iter.constructor(seq);
  29615. }
  29616. function validateEntry(entry) {
  29617. if (entry !== Object(entry)) {
  29618. throw new TypeError('Expected [K, V] tuple: ' + entry);
  29619. }
  29620. }
  29621. function resolveSize(iter) {
  29622. assertNotInfinite(iter.size);
  29623. return ensureSize(iter);
  29624. }
  29625. function iterableClass(iterable) {
  29626. return isKeyed(iterable) ? KeyedIterable :
  29627. isIndexed(iterable) ? IndexedIterable :
  29628. SetIterable;
  29629. }
  29630. function makeSequence(iterable) {
  29631. return Object.create(
  29632. (
  29633. isKeyed(iterable) ? KeyedSeq :
  29634. isIndexed(iterable) ? IndexedSeq :
  29635. SetSeq
  29636. ).prototype
  29637. );
  29638. }
  29639. function cacheResultThrough() {
  29640. if (this._iter.cacheResult) {
  29641. this._iter.cacheResult();
  29642. this.size = this._iter.size;
  29643. return this;
  29644. } else {
  29645. return Seq.prototype.cacheResult.call(this);
  29646. }
  29647. }
  29648. function defaultComparator(a, b) {
  29649. return a > b ? 1 : a < b ? -1 : 0;
  29650. }
  29651. function forceIterator(keyPath) {
  29652. var iter = getIterator(keyPath);
  29653. if (!iter) {
  29654. // Array might not be iterable in this environment, so we need a fallback
  29655. // to our wrapped type.
  29656. if (!isArrayLike(keyPath)) {
  29657. throw new TypeError('Expected iterable or array-like: ' + keyPath);
  29658. }
  29659. iter = getIterator(Iterable(keyPath));
  29660. }
  29661. return iter;
  29662. }
  29663. createClass(Record, KeyedCollection);
  29664. function Record(defaultValues, name) {
  29665. var hasInitialized;
  29666. var RecordType = function Record(values) {
  29667. if (values instanceof RecordType) {
  29668. return values;
  29669. }
  29670. if (!(this instanceof RecordType)) {
  29671. return new RecordType(values);
  29672. }
  29673. if (!hasInitialized) {
  29674. hasInitialized = true;
  29675. var keys = Object.keys(defaultValues);
  29676. setProps(RecordTypePrototype, keys);
  29677. RecordTypePrototype.size = keys.length;
  29678. RecordTypePrototype._name = name;
  29679. RecordTypePrototype._keys = keys;
  29680. RecordTypePrototype._defaultValues = defaultValues;
  29681. }
  29682. this._map = Map(values);
  29683. };
  29684. var RecordTypePrototype = RecordType.prototype = Object.create(RecordPrototype);
  29685. RecordTypePrototype.constructor = RecordType;
  29686. return RecordType;
  29687. }
  29688. Record.prototype.toString = function() {
  29689. return this.__toString(recordName(this) + ' {', '}');
  29690. };
  29691. // @pragma Access
  29692. Record.prototype.has = function(k) {
  29693. return this._defaultValues.hasOwnProperty(k);
  29694. };
  29695. Record.prototype.get = function(k, notSetValue) {
  29696. if (!this.has(k)) {
  29697. return notSetValue;
  29698. }
  29699. var defaultVal = this._defaultValues[k];
  29700. return this._map ? this._map.get(k, defaultVal) : defaultVal;
  29701. };
  29702. // @pragma Modification
  29703. Record.prototype.clear = function() {
  29704. if (this.__ownerID) {
  29705. this._map && this._map.clear();
  29706. return this;
  29707. }
  29708. var RecordType = this.constructor;
  29709. return RecordType._empty || (RecordType._empty = makeRecord(this, emptyMap()));
  29710. };
  29711. Record.prototype.set = function(k, v) {
  29712. if (!this.has(k)) {
  29713. throw new Error('Cannot set unknown key "' + k + '" on ' + recordName(this));
  29714. }
  29715. var newMap = this._map && this._map.set(k, v);
  29716. if (this.__ownerID || newMap === this._map) {
  29717. return this;
  29718. }
  29719. return makeRecord(this, newMap);
  29720. };
  29721. Record.prototype.remove = function(k) {
  29722. if (!this.has(k)) {
  29723. return this;
  29724. }
  29725. var newMap = this._map && this._map.remove(k);
  29726. if (this.__ownerID || newMap === this._map) {
  29727. return this;
  29728. }
  29729. return makeRecord(this, newMap);
  29730. };
  29731. Record.prototype.wasAltered = function() {
  29732. return this._map.wasAltered();
  29733. };
  29734. Record.prototype.__iterator = function(type, reverse) {var this$0 = this;
  29735. return KeyedIterable(this._defaultValues).map(function(_, k) {return this$0.get(k)}).__iterator(type, reverse);
  29736. };
  29737. Record.prototype.__iterate = function(fn, reverse) {var this$0 = this;
  29738. return KeyedIterable(this._defaultValues).map(function(_, k) {return this$0.get(k)}).__iterate(fn, reverse);
  29739. };
  29740. Record.prototype.__ensureOwner = function(ownerID) {
  29741. if (ownerID === this.__ownerID) {
  29742. return this;
  29743. }
  29744. var newMap = this._map && this._map.__ensureOwner(ownerID);
  29745. if (!ownerID) {
  29746. this.__ownerID = ownerID;
  29747. this._map = newMap;
  29748. return this;
  29749. }
  29750. return makeRecord(this, newMap, ownerID);
  29751. };
  29752. var RecordPrototype = Record.prototype;
  29753. RecordPrototype[DELETE] = RecordPrototype.remove;
  29754. RecordPrototype.deleteIn =
  29755. RecordPrototype.removeIn = MapPrototype.removeIn;
  29756. RecordPrototype.merge = MapPrototype.merge;
  29757. RecordPrototype.mergeWith = MapPrototype.mergeWith;
  29758. RecordPrototype.mergeIn = MapPrototype.mergeIn;
  29759. RecordPrototype.mergeDeep = MapPrototype.mergeDeep;
  29760. RecordPrototype.mergeDeepWith = MapPrototype.mergeDeepWith;
  29761. RecordPrototype.mergeDeepIn = MapPrototype.mergeDeepIn;
  29762. RecordPrototype.setIn = MapPrototype.setIn;
  29763. RecordPrototype.update = MapPrototype.update;
  29764. RecordPrototype.updateIn = MapPrototype.updateIn;
  29765. RecordPrototype.withMutations = MapPrototype.withMutations;
  29766. RecordPrototype.asMutable = MapPrototype.asMutable;
  29767. RecordPrototype.asImmutable = MapPrototype.asImmutable;
  29768. function makeRecord(likeRecord, map, ownerID) {
  29769. var record = Object.create(Object.getPrototypeOf(likeRecord));
  29770. record._map = map;
  29771. record.__ownerID = ownerID;
  29772. return record;
  29773. }
  29774. function recordName(record) {
  29775. return record._name || record.constructor.name || 'Record';
  29776. }
  29777. function setProps(prototype, names) {
  29778. try {
  29779. names.forEach(setProp.bind(undefined, prototype));
  29780. } catch (error) {
  29781. // Object.defineProperty failed. Probably IE8.
  29782. }
  29783. }
  29784. function setProp(prototype, name) {
  29785. Object.defineProperty(prototype, name, {
  29786. get: function() {
  29787. return this.get(name);
  29788. },
  29789. set: function(value) {
  29790. invariant(this.__ownerID, 'Cannot set on an immutable record.');
  29791. this.set(name, value);
  29792. }
  29793. });
  29794. }
  29795. createClass(Set, SetCollection);
  29796. // @pragma Construction
  29797. function Set(value) {
  29798. return value === null || value === undefined ? emptySet() :
  29799. isSet(value) && !isOrdered(value) ? value :
  29800. emptySet().withMutations(function(set ) {
  29801. var iter = SetIterable(value);
  29802. assertNotInfinite(iter.size);
  29803. iter.forEach(function(v ) {return set.add(v)});
  29804. });
  29805. }
  29806. Set.of = function(/*...values*/) {
  29807. return this(arguments);
  29808. };
  29809. Set.fromKeys = function(value) {
  29810. return this(KeyedIterable(value).keySeq());
  29811. };
  29812. Set.prototype.toString = function() {
  29813. return this.__toString('Set {', '}');
  29814. };
  29815. // @pragma Access
  29816. Set.prototype.has = function(value) {
  29817. return this._map.has(value);
  29818. };
  29819. // @pragma Modification
  29820. Set.prototype.add = function(value) {
  29821. return updateSet(this, this._map.set(value, true));
  29822. };
  29823. Set.prototype.remove = function(value) {
  29824. return updateSet(this, this._map.remove(value));
  29825. };
  29826. Set.prototype.clear = function() {
  29827. return updateSet(this, this._map.clear());
  29828. };
  29829. // @pragma Composition
  29830. Set.prototype.union = function() {var iters = SLICE$0.call(arguments, 0);
  29831. iters = iters.filter(function(x ) {return x.size !== 0});
  29832. if (iters.length === 0) {
  29833. return this;
  29834. }
  29835. if (this.size === 0 && !this.__ownerID && iters.length === 1) {
  29836. return this.constructor(iters[0]);
  29837. }
  29838. return this.withMutations(function(set ) {
  29839. for (var ii = 0; ii < iters.length; ii++) {
  29840. SetIterable(iters[ii]).forEach(function(value ) {return set.add(value)});
  29841. }
  29842. });
  29843. };
  29844. Set.prototype.intersect = function() {var iters = SLICE$0.call(arguments, 0);
  29845. if (iters.length === 0) {
  29846. return this;
  29847. }
  29848. iters = iters.map(function(iter ) {return SetIterable(iter)});
  29849. var originalSet = this;
  29850. return this.withMutations(function(set ) {
  29851. originalSet.forEach(function(value ) {
  29852. if (!iters.every(function(iter ) {return iter.includes(value)})) {
  29853. set.remove(value);
  29854. }
  29855. });
  29856. });
  29857. };
  29858. Set.prototype.subtract = function() {var iters = SLICE$0.call(arguments, 0);
  29859. if (iters.length === 0) {
  29860. return this;
  29861. }
  29862. iters = iters.map(function(iter ) {return SetIterable(iter)});
  29863. var originalSet = this;
  29864. return this.withMutations(function(set ) {
  29865. originalSet.forEach(function(value ) {
  29866. if (iters.some(function(iter ) {return iter.includes(value)})) {
  29867. set.remove(value);
  29868. }
  29869. });
  29870. });
  29871. };
  29872. Set.prototype.merge = function() {
  29873. return this.union.apply(this, arguments);
  29874. };
  29875. Set.prototype.mergeWith = function(merger) {var iters = SLICE$0.call(arguments, 1);
  29876. return this.union.apply(this, iters);
  29877. };
  29878. Set.prototype.sort = function(comparator) {
  29879. // Late binding
  29880. return OrderedSet(sortFactory(this, comparator));
  29881. };
  29882. Set.prototype.sortBy = function(mapper, comparator) {
  29883. // Late binding
  29884. return OrderedSet(sortFactory(this, comparator, mapper));
  29885. };
  29886. Set.prototype.wasAltered = function() {
  29887. return this._map.wasAltered();
  29888. };
  29889. Set.prototype.__iterate = function(fn, reverse) {var this$0 = this;
  29890. return this._map.__iterate(function(_, k) {return fn(k, k, this$0)}, reverse);
  29891. };
  29892. Set.prototype.__iterator = function(type, reverse) {
  29893. return this._map.map(function(_, k) {return k}).__iterator(type, reverse);
  29894. };
  29895. Set.prototype.__ensureOwner = function(ownerID) {
  29896. if (ownerID === this.__ownerID) {
  29897. return this;
  29898. }
  29899. var newMap = this._map.__ensureOwner(ownerID);
  29900. if (!ownerID) {
  29901. this.__ownerID = ownerID;
  29902. this._map = newMap;
  29903. return this;
  29904. }
  29905. return this.__make(newMap, ownerID);
  29906. };
  29907. function isSet(maybeSet) {
  29908. return !!(maybeSet && maybeSet[IS_SET_SENTINEL]);
  29909. }
  29910. Set.isSet = isSet;
  29911. var IS_SET_SENTINEL = '@@__IMMUTABLE_SET__@@';
  29912. var SetPrototype = Set.prototype;
  29913. SetPrototype[IS_SET_SENTINEL] = true;
  29914. SetPrototype[DELETE] = SetPrototype.remove;
  29915. SetPrototype.mergeDeep = SetPrototype.merge;
  29916. SetPrototype.mergeDeepWith = SetPrototype.mergeWith;
  29917. SetPrototype.withMutations = MapPrototype.withMutations;
  29918. SetPrototype.asMutable = MapPrototype.asMutable;
  29919. SetPrototype.asImmutable = MapPrototype.asImmutable;
  29920. SetPrototype.__empty = emptySet;
  29921. SetPrototype.__make = makeSet;
  29922. function updateSet(set, newMap) {
  29923. if (set.__ownerID) {
  29924. set.size = newMap.size;
  29925. set._map = newMap;
  29926. return set;
  29927. }
  29928. return newMap === set._map ? set :
  29929. newMap.size === 0 ? set.__empty() :
  29930. set.__make(newMap);
  29931. }
  29932. function makeSet(map, ownerID) {
  29933. var set = Object.create(SetPrototype);
  29934. set.size = map ? map.size : 0;
  29935. set._map = map;
  29936. set.__ownerID = ownerID;
  29937. return set;
  29938. }
  29939. var EMPTY_SET;
  29940. function emptySet() {
  29941. return EMPTY_SET || (EMPTY_SET = makeSet(emptyMap()));
  29942. }
  29943. createClass(OrderedSet, Set);
  29944. // @pragma Construction
  29945. function OrderedSet(value) {
  29946. return value === null || value === undefined ? emptyOrderedSet() :
  29947. isOrderedSet(value) ? value :
  29948. emptyOrderedSet().withMutations(function(set ) {
  29949. var iter = SetIterable(value);
  29950. assertNotInfinite(iter.size);
  29951. iter.forEach(function(v ) {return set.add(v)});
  29952. });
  29953. }
  29954. OrderedSet.of = function(/*...values*/) {
  29955. return this(arguments);
  29956. };
  29957. OrderedSet.fromKeys = function(value) {
  29958. return this(KeyedIterable(value).keySeq());
  29959. };
  29960. OrderedSet.prototype.toString = function() {
  29961. return this.__toString('OrderedSet {', '}');
  29962. };
  29963. function isOrderedSet(maybeOrderedSet) {
  29964. return isSet(maybeOrderedSet) && isOrdered(maybeOrderedSet);
  29965. }
  29966. OrderedSet.isOrderedSet = isOrderedSet;
  29967. var OrderedSetPrototype = OrderedSet.prototype;
  29968. OrderedSetPrototype[IS_ORDERED_SENTINEL] = true;
  29969. OrderedSetPrototype.__empty = emptyOrderedSet;
  29970. OrderedSetPrototype.__make = makeOrderedSet;
  29971. function makeOrderedSet(map, ownerID) {
  29972. var set = Object.create(OrderedSetPrototype);
  29973. set.size = map ? map.size : 0;
  29974. set._map = map;
  29975. set.__ownerID = ownerID;
  29976. return set;
  29977. }
  29978. var EMPTY_ORDERED_SET;
  29979. function emptyOrderedSet() {
  29980. return EMPTY_ORDERED_SET || (EMPTY_ORDERED_SET = makeOrderedSet(emptyOrderedMap()));
  29981. }
  29982. createClass(Stack, IndexedCollection);
  29983. // @pragma Construction
  29984. function Stack(value) {
  29985. return value === null || value === undefined ? emptyStack() :
  29986. isStack(value) ? value :
  29987. emptyStack().unshiftAll(value);
  29988. }
  29989. Stack.of = function(/*...values*/) {
  29990. return this(arguments);
  29991. };
  29992. Stack.prototype.toString = function() {
  29993. return this.__toString('Stack [', ']');
  29994. };
  29995. // @pragma Access
  29996. Stack.prototype.get = function(index, notSetValue) {
  29997. var head = this._head;
  29998. index = wrapIndex(this, index);
  29999. while (head && index--) {
  30000. head = head.next;
  30001. }
  30002. return head ? head.value : notSetValue;
  30003. };
  30004. Stack.prototype.peek = function() {
  30005. return this._head && this._head.value;
  30006. };
  30007. // @pragma Modification
  30008. Stack.prototype.push = function(/*...values*/) {
  30009. if (arguments.length === 0) {
  30010. return this;
  30011. }
  30012. var newSize = this.size + arguments.length;
  30013. var head = this._head;
  30014. for (var ii = arguments.length - 1; ii >= 0; ii--) {
  30015. head = {
  30016. value: arguments[ii],
  30017. next: head
  30018. };
  30019. }
  30020. if (this.__ownerID) {
  30021. this.size = newSize;
  30022. this._head = head;
  30023. this.__hash = undefined;
  30024. this.__altered = true;
  30025. return this;
  30026. }
  30027. return makeStack(newSize, head);
  30028. };
  30029. Stack.prototype.pushAll = function(iter) {
  30030. iter = IndexedIterable(iter);
  30031. if (iter.size === 0) {
  30032. return this;
  30033. }
  30034. assertNotInfinite(iter.size);
  30035. var newSize = this.size;
  30036. var head = this._head;
  30037. iter.reverse().forEach(function(value ) {
  30038. newSize++;
  30039. head = {
  30040. value: value,
  30041. next: head
  30042. };
  30043. });
  30044. if (this.__ownerID) {
  30045. this.size = newSize;
  30046. this._head = head;
  30047. this.__hash = undefined;
  30048. this.__altered = true;
  30049. return this;
  30050. }
  30051. return makeStack(newSize, head);
  30052. };
  30053. Stack.prototype.pop = function() {
  30054. return this.slice(1);
  30055. };
  30056. Stack.prototype.unshift = function(/*...values*/) {
  30057. return this.push.apply(this, arguments);
  30058. };
  30059. Stack.prototype.unshiftAll = function(iter) {
  30060. return this.pushAll(iter);
  30061. };
  30062. Stack.prototype.shift = function() {
  30063. return this.pop.apply(this, arguments);
  30064. };
  30065. Stack.prototype.clear = function() {
  30066. if (this.size === 0) {
  30067. return this;
  30068. }
  30069. if (this.__ownerID) {
  30070. this.size = 0;
  30071. this._head = undefined;
  30072. this.__hash = undefined;
  30073. this.__altered = true;
  30074. return this;
  30075. }
  30076. return emptyStack();
  30077. };
  30078. Stack.prototype.slice = function(begin, end) {
  30079. if (wholeSlice(begin, end, this.size)) {
  30080. return this;
  30081. }
  30082. var resolvedBegin = resolveBegin(begin, this.size);
  30083. var resolvedEnd = resolveEnd(end, this.size);
  30084. if (resolvedEnd !== this.size) {
  30085. // super.slice(begin, end);
  30086. return IndexedCollection.prototype.slice.call(this, begin, end);
  30087. }
  30088. var newSize = this.size - resolvedBegin;
  30089. var head = this._head;
  30090. while (resolvedBegin--) {
  30091. head = head.next;
  30092. }
  30093. if (this.__ownerID) {
  30094. this.size = newSize;
  30095. this._head = head;
  30096. this.__hash = undefined;
  30097. this.__altered = true;
  30098. return this;
  30099. }
  30100. return makeStack(newSize, head);
  30101. };
  30102. // @pragma Mutability
  30103. Stack.prototype.__ensureOwner = function(ownerID) {
  30104. if (ownerID === this.__ownerID) {
  30105. return this;
  30106. }
  30107. if (!ownerID) {
  30108. this.__ownerID = ownerID;
  30109. this.__altered = false;
  30110. return this;
  30111. }
  30112. return makeStack(this.size, this._head, ownerID, this.__hash);
  30113. };
  30114. // @pragma Iteration
  30115. Stack.prototype.__iterate = function(fn, reverse) {
  30116. if (reverse) {
  30117. return this.reverse().__iterate(fn);
  30118. }
  30119. var iterations = 0;
  30120. var node = this._head;
  30121. while (node) {
  30122. if (fn(node.value, iterations++, this) === false) {
  30123. break;
  30124. }
  30125. node = node.next;
  30126. }
  30127. return iterations;
  30128. };
  30129. Stack.prototype.__iterator = function(type, reverse) {
  30130. if (reverse) {
  30131. return this.reverse().__iterator(type);
  30132. }
  30133. var iterations = 0;
  30134. var node = this._head;
  30135. return new Iterator(function() {
  30136. if (node) {
  30137. var value = node.value;
  30138. node = node.next;
  30139. return iteratorValue(type, iterations++, value);
  30140. }
  30141. return iteratorDone();
  30142. });
  30143. };
  30144. function isStack(maybeStack) {
  30145. return !!(maybeStack && maybeStack[IS_STACK_SENTINEL]);
  30146. }
  30147. Stack.isStack = isStack;
  30148. var IS_STACK_SENTINEL = '@@__IMMUTABLE_STACK__@@';
  30149. var StackPrototype = Stack.prototype;
  30150. StackPrototype[IS_STACK_SENTINEL] = true;
  30151. StackPrototype.withMutations = MapPrototype.withMutations;
  30152. StackPrototype.asMutable = MapPrototype.asMutable;
  30153. StackPrototype.asImmutable = MapPrototype.asImmutable;
  30154. StackPrototype.wasAltered = MapPrototype.wasAltered;
  30155. function makeStack(size, head, ownerID, hash) {
  30156. var map = Object.create(StackPrototype);
  30157. map.size = size;
  30158. map._head = head;
  30159. map.__ownerID = ownerID;
  30160. map.__hash = hash;
  30161. map.__altered = false;
  30162. return map;
  30163. }
  30164. var EMPTY_STACK;
  30165. function emptyStack() {
  30166. return EMPTY_STACK || (EMPTY_STACK = makeStack(0));
  30167. }
  30168. /**
  30169. * Contributes additional methods to a constructor
  30170. */
  30171. function mixin(ctor, methods) {
  30172. var keyCopier = function(key ) { ctor.prototype[key] = methods[key]; };
  30173. Object.keys(methods).forEach(keyCopier);
  30174. Object.getOwnPropertySymbols &&
  30175. Object.getOwnPropertySymbols(methods).forEach(keyCopier);
  30176. return ctor;
  30177. }
  30178. Iterable.Iterator = Iterator;
  30179. mixin(Iterable, {
  30180. // ### Conversion to other types
  30181. toArray: function() {
  30182. assertNotInfinite(this.size);
  30183. var array = new Array(this.size || 0);
  30184. this.valueSeq().__iterate(function(v, i) { array[i] = v; });
  30185. return array;
  30186. },
  30187. toIndexedSeq: function() {
  30188. return new ToIndexedSequence(this);
  30189. },
  30190. toJS: function() {
  30191. return this.toSeq().map(
  30192. function(value ) {return value && typeof value.toJS === 'function' ? value.toJS() : value}
  30193. ).__toJS();
  30194. },
  30195. toJSON: function() {
  30196. return this.toSeq().map(
  30197. function(value ) {return value && typeof value.toJSON === 'function' ? value.toJSON() : value}
  30198. ).__toJS();
  30199. },
  30200. toKeyedSeq: function() {
  30201. return new ToKeyedSequence(this, true);
  30202. },
  30203. toMap: function() {
  30204. // Use Late Binding here to solve the circular dependency.
  30205. return Map(this.toKeyedSeq());
  30206. },
  30207. toObject: function() {
  30208. assertNotInfinite(this.size);
  30209. var object = {};
  30210. this.__iterate(function(v, k) { object[k] = v; });
  30211. return object;
  30212. },
  30213. toOrderedMap: function() {
  30214. // Use Late Binding here to solve the circular dependency.
  30215. return OrderedMap(this.toKeyedSeq());
  30216. },
  30217. toOrderedSet: function() {
  30218. // Use Late Binding here to solve the circular dependency.
  30219. return OrderedSet(isKeyed(this) ? this.valueSeq() : this);
  30220. },
  30221. toSet: function() {
  30222. // Use Late Binding here to solve the circular dependency.
  30223. return Set(isKeyed(this) ? this.valueSeq() : this);
  30224. },
  30225. toSetSeq: function() {
  30226. return new ToSetSequence(this);
  30227. },
  30228. toSeq: function() {
  30229. return isIndexed(this) ? this.toIndexedSeq() :
  30230. isKeyed(this) ? this.toKeyedSeq() :
  30231. this.toSetSeq();
  30232. },
  30233. toStack: function() {
  30234. // Use Late Binding here to solve the circular dependency.
  30235. return Stack(isKeyed(this) ? this.valueSeq() : this);
  30236. },
  30237. toList: function() {
  30238. // Use Late Binding here to solve the circular dependency.
  30239. return List(isKeyed(this) ? this.valueSeq() : this);
  30240. },
  30241. // ### Common JavaScript methods and properties
  30242. toString: function() {
  30243. return '[Iterable]';
  30244. },
  30245. __toString: function(head, tail) {
  30246. if (this.size === 0) {
  30247. return head + tail;
  30248. }
  30249. return head + ' ' + this.toSeq().map(this.__toStringMapper).join(', ') + ' ' + tail;
  30250. },
  30251. // ### ES6 Collection methods (ES6 Array and Map)
  30252. concat: function() {var values = SLICE$0.call(arguments, 0);
  30253. return reify(this, concatFactory(this, values));
  30254. },
  30255. includes: function(searchValue) {
  30256. return this.some(function(value ) {return is(value, searchValue)});
  30257. },
  30258. entries: function() {
  30259. return this.__iterator(ITERATE_ENTRIES);
  30260. },
  30261. every: function(predicate, context) {
  30262. assertNotInfinite(this.size);
  30263. var returnValue = true;
  30264. this.__iterate(function(v, k, c) {
  30265. if (!predicate.call(context, v, k, c)) {
  30266. returnValue = false;
  30267. return false;
  30268. }
  30269. });
  30270. return returnValue;
  30271. },
  30272. filter: function(predicate, context) {
  30273. return reify(this, filterFactory(this, predicate, context, true));
  30274. },
  30275. find: function(predicate, context, notSetValue) {
  30276. var entry = this.findEntry(predicate, context);
  30277. return entry ? entry[1] : notSetValue;
  30278. },
  30279. findEntry: function(predicate, context) {
  30280. var found;
  30281. this.__iterate(function(v, k, c) {
  30282. if (predicate.call(context, v, k, c)) {
  30283. found = [k, v];
  30284. return false;
  30285. }
  30286. });
  30287. return found;
  30288. },
  30289. findLastEntry: function(predicate, context) {
  30290. return this.toSeq().reverse().findEntry(predicate, context);
  30291. },
  30292. forEach: function(sideEffect, context) {
  30293. assertNotInfinite(this.size);
  30294. return this.__iterate(context ? sideEffect.bind(context) : sideEffect);
  30295. },
  30296. join: function(separator) {
  30297. assertNotInfinite(this.size);
  30298. separator = separator !== undefined ? '' + separator : ',';
  30299. var joined = '';
  30300. var isFirst = true;
  30301. this.__iterate(function(v ) {
  30302. isFirst ? (isFirst = false) : (joined += separator);
  30303. joined += v !== null && v !== undefined ? v.toString() : '';
  30304. });
  30305. return joined;
  30306. },
  30307. keys: function() {
  30308. return this.__iterator(ITERATE_KEYS);
  30309. },
  30310. map: function(mapper, context) {
  30311. return reify(this, mapFactory(this, mapper, context));
  30312. },
  30313. reduce: function(reducer, initialReduction, context) {
  30314. assertNotInfinite(this.size);
  30315. var reduction;
  30316. var useFirst;
  30317. if (arguments.length < 2) {
  30318. useFirst = true;
  30319. } else {
  30320. reduction = initialReduction;
  30321. }
  30322. this.__iterate(function(v, k, c) {
  30323. if (useFirst) {
  30324. useFirst = false;
  30325. reduction = v;
  30326. } else {
  30327. reduction = reducer.call(context, reduction, v, k, c);
  30328. }
  30329. });
  30330. return reduction;
  30331. },
  30332. reduceRight: function(reducer, initialReduction, context) {
  30333. var reversed = this.toKeyedSeq().reverse();
  30334. return reversed.reduce.apply(reversed, arguments);
  30335. },
  30336. reverse: function() {
  30337. return reify(this, reverseFactory(this, true));
  30338. },
  30339. slice: function(begin, end) {
  30340. return reify(this, sliceFactory(this, begin, end, true));
  30341. },
  30342. some: function(predicate, context) {
  30343. return !this.every(not(predicate), context);
  30344. },
  30345. sort: function(comparator) {
  30346. return reify(this, sortFactory(this, comparator));
  30347. },
  30348. values: function() {
  30349. return this.__iterator(ITERATE_VALUES);
  30350. },
  30351. // ### More sequential methods
  30352. butLast: function() {
  30353. return this.slice(0, -1);
  30354. },
  30355. isEmpty: function() {
  30356. return this.size !== undefined ? this.size === 0 : !this.some(function() {return true});
  30357. },
  30358. count: function(predicate, context) {
  30359. return ensureSize(
  30360. predicate ? this.toSeq().filter(predicate, context) : this
  30361. );
  30362. },
  30363. countBy: function(grouper, context) {
  30364. return countByFactory(this, grouper, context);
  30365. },
  30366. equals: function(other) {
  30367. return deepEqual(this, other);
  30368. },
  30369. entrySeq: function() {
  30370. var iterable = this;
  30371. if (iterable._cache) {
  30372. // We cache as an entries array, so we can just return the cache!
  30373. return new ArraySeq(iterable._cache);
  30374. }
  30375. var entriesSequence = iterable.toSeq().map(entryMapper).toIndexedSeq();
  30376. entriesSequence.fromEntrySeq = function() {return iterable.toSeq()};
  30377. return entriesSequence;
  30378. },
  30379. filterNot: function(predicate, context) {
  30380. return this.filter(not(predicate), context);
  30381. },
  30382. findLast: function(predicate, context, notSetValue) {
  30383. return this.toKeyedSeq().reverse().find(predicate, context, notSetValue);
  30384. },
  30385. first: function() {
  30386. return this.find(returnTrue);
  30387. },
  30388. flatMap: function(mapper, context) {
  30389. return reify(this, flatMapFactory(this, mapper, context));
  30390. },
  30391. flatten: function(depth) {
  30392. return reify(this, flattenFactory(this, depth, true));
  30393. },
  30394. fromEntrySeq: function() {
  30395. return new FromEntriesSequence(this);
  30396. },
  30397. get: function(searchKey, notSetValue) {
  30398. return this.find(function(_, key) {return is(key, searchKey)}, undefined, notSetValue);
  30399. },
  30400. getIn: function(searchKeyPath, notSetValue) {
  30401. var nested = this;
  30402. // Note: in an ES6 environment, we would prefer:
  30403. // for (var key of searchKeyPath) {
  30404. var iter = forceIterator(searchKeyPath);
  30405. var step;
  30406. while (!(step = iter.next()).done) {
  30407. var key = step.value;
  30408. nested = nested && nested.get ? nested.get(key, NOT_SET) : NOT_SET;
  30409. if (nested === NOT_SET) {
  30410. return notSetValue;
  30411. }
  30412. }
  30413. return nested;
  30414. },
  30415. groupBy: function(grouper, context) {
  30416. return groupByFactory(this, grouper, context);
  30417. },
  30418. has: function(searchKey) {
  30419. return this.get(searchKey, NOT_SET) !== NOT_SET;
  30420. },
  30421. hasIn: function(searchKeyPath) {
  30422. return this.getIn(searchKeyPath, NOT_SET) !== NOT_SET;
  30423. },
  30424. isSubset: function(iter) {
  30425. iter = typeof iter.includes === 'function' ? iter : Iterable(iter);
  30426. return this.every(function(value ) {return iter.includes(value)});
  30427. },
  30428. isSuperset: function(iter) {
  30429. iter = typeof iter.isSubset === 'function' ? iter : Iterable(iter);
  30430. return iter.isSubset(this);
  30431. },
  30432. keySeq: function() {
  30433. return this.toSeq().map(keyMapper).toIndexedSeq();
  30434. },
  30435. last: function() {
  30436. return this.toSeq().reverse().first();
  30437. },
  30438. max: function(comparator) {
  30439. return maxFactory(this, comparator);
  30440. },
  30441. maxBy: function(mapper, comparator) {
  30442. return maxFactory(this, comparator, mapper);
  30443. },
  30444. min: function(comparator) {
  30445. return maxFactory(this, comparator ? neg(comparator) : defaultNegComparator);
  30446. },
  30447. minBy: function(mapper, comparator) {
  30448. return maxFactory(this, comparator ? neg(comparator) : defaultNegComparator, mapper);
  30449. },
  30450. rest: function() {
  30451. return this.slice(1);
  30452. },
  30453. skip: function(amount) {
  30454. return this.slice(Math.max(0, amount));
  30455. },
  30456. skipLast: function(amount) {
  30457. return reify(this, this.toSeq().reverse().skip(amount).reverse());
  30458. },
  30459. skipWhile: function(predicate, context) {
  30460. return reify(this, skipWhileFactory(this, predicate, context, true));
  30461. },
  30462. skipUntil: function(predicate, context) {
  30463. return this.skipWhile(not(predicate), context);
  30464. },
  30465. sortBy: function(mapper, comparator) {
  30466. return reify(this, sortFactory(this, comparator, mapper));
  30467. },
  30468. take: function(amount) {
  30469. return this.slice(0, Math.max(0, amount));
  30470. },
  30471. takeLast: function(amount) {
  30472. return reify(this, this.toSeq().reverse().take(amount).reverse());
  30473. },
  30474. takeWhile: function(predicate, context) {
  30475. return reify(this, takeWhileFactory(this, predicate, context));
  30476. },
  30477. takeUntil: function(predicate, context) {
  30478. return this.takeWhile(not(predicate), context);
  30479. },
  30480. valueSeq: function() {
  30481. return this.toIndexedSeq();
  30482. },
  30483. // ### Hashable Object
  30484. hashCode: function() {
  30485. return this.__hash || (this.__hash = hashIterable(this));
  30486. }
  30487. // ### Internal
  30488. // abstract __iterate(fn, reverse)
  30489. // abstract __iterator(type, reverse)
  30490. });
  30491. // var IS_ITERABLE_SENTINEL = '@@__IMMUTABLE_ITERABLE__@@';
  30492. // var IS_KEYED_SENTINEL = '@@__IMMUTABLE_KEYED__@@';
  30493. // var IS_INDEXED_SENTINEL = '@@__IMMUTABLE_INDEXED__@@';
  30494. // var IS_ORDERED_SENTINEL = '@@__IMMUTABLE_ORDERED__@@';
  30495. var IterablePrototype = Iterable.prototype;
  30496. IterablePrototype[IS_ITERABLE_SENTINEL] = true;
  30497. IterablePrototype[ITERATOR_SYMBOL] = IterablePrototype.values;
  30498. IterablePrototype.__toJS = IterablePrototype.toArray;
  30499. IterablePrototype.__toStringMapper = quoteString;
  30500. IterablePrototype.inspect =
  30501. IterablePrototype.toSource = function() { return this.toString(); };
  30502. IterablePrototype.chain = IterablePrototype.flatMap;
  30503. IterablePrototype.contains = IterablePrototype.includes;
  30504. // Temporary warning about using length
  30505. (function () {
  30506. try {
  30507. Object.defineProperty(IterablePrototype, 'length', {
  30508. get: function () {
  30509. if (!Iterable.noLengthWarning) {
  30510. var stack;
  30511. try {
  30512. throw new Error();
  30513. } catch (error) {
  30514. stack = error.stack;
  30515. }
  30516. if (stack.indexOf('_wrapObject') === -1) {
  30517. console && console.warn && console.warn(
  30518. 'iterable.length has been deprecated, '+
  30519. 'use iterable.size or iterable.count(). '+
  30520. 'This warning will become a silent error in a future version. ' +
  30521. stack
  30522. );
  30523. return this.size;
  30524. }
  30525. }
  30526. }
  30527. });
  30528. } catch (e) {}
  30529. })();
  30530. mixin(KeyedIterable, {
  30531. // ### More sequential methods
  30532. flip: function() {
  30533. return reify(this, flipFactory(this));
  30534. },
  30535. findKey: function(predicate, context) {
  30536. var entry = this.findEntry(predicate, context);
  30537. return entry && entry[0];
  30538. },
  30539. findLastKey: function(predicate, context) {
  30540. return this.toSeq().reverse().findKey(predicate, context);
  30541. },
  30542. keyOf: function(searchValue) {
  30543. return this.findKey(function(value ) {return is(value, searchValue)});
  30544. },
  30545. lastKeyOf: function(searchValue) {
  30546. return this.findLastKey(function(value ) {return is(value, searchValue)});
  30547. },
  30548. mapEntries: function(mapper, context) {var this$0 = this;
  30549. var iterations = 0;
  30550. return reify(this,
  30551. this.toSeq().map(
  30552. function(v, k) {return mapper.call(context, [k, v], iterations++, this$0)}
  30553. ).fromEntrySeq()
  30554. );
  30555. },
  30556. mapKeys: function(mapper, context) {var this$0 = this;
  30557. return reify(this,
  30558. this.toSeq().flip().map(
  30559. function(k, v) {return mapper.call(context, k, v, this$0)}
  30560. ).flip()
  30561. );
  30562. }
  30563. });
  30564. var KeyedIterablePrototype = KeyedIterable.prototype;
  30565. KeyedIterablePrototype[IS_KEYED_SENTINEL] = true;
  30566. KeyedIterablePrototype[ITERATOR_SYMBOL] = IterablePrototype.entries;
  30567. KeyedIterablePrototype.__toJS = IterablePrototype.toObject;
  30568. KeyedIterablePrototype.__toStringMapper = function(v, k) {return JSON.stringify(k) + ': ' + quoteString(v)};
  30569. mixin(IndexedIterable, {
  30570. // ### Conversion to other types
  30571. toKeyedSeq: function() {
  30572. return new ToKeyedSequence(this, false);
  30573. },
  30574. // ### ES6 Collection methods (ES6 Array and Map)
  30575. filter: function(predicate, context) {
  30576. return reify(this, filterFactory(this, predicate, context, false));
  30577. },
  30578. findIndex: function(predicate, context) {
  30579. var entry = this.findEntry(predicate, context);
  30580. return entry ? entry[0] : -1;
  30581. },
  30582. indexOf: function(searchValue) {
  30583. var key = this.toKeyedSeq().keyOf(searchValue);
  30584. return key === undefined ? -1 : key;
  30585. },
  30586. lastIndexOf: function(searchValue) {
  30587. var key = this.toKeyedSeq().reverse().keyOf(searchValue);
  30588. return key === undefined ? -1 : key;
  30589. // var index =
  30590. // return this.toSeq().reverse().indexOf(searchValue);
  30591. },
  30592. reverse: function() {
  30593. return reify(this, reverseFactory(this, false));
  30594. },
  30595. slice: function(begin, end) {
  30596. return reify(this, sliceFactory(this, begin, end, false));
  30597. },
  30598. splice: function(index, removeNum /*, ...values*/) {
  30599. var numArgs = arguments.length;
  30600. removeNum = Math.max(removeNum | 0, 0);
  30601. if (numArgs === 0 || (numArgs === 2 && !removeNum)) {
  30602. return this;
  30603. }
  30604. // If index is negative, it should resolve relative to the size of the
  30605. // collection. However size may be expensive to compute if not cached, so
  30606. // only call count() if the number is in fact negative.
  30607. index = resolveBegin(index, index < 0 ? this.count() : this.size);
  30608. var spliced = this.slice(0, index);
  30609. return reify(
  30610. this,
  30611. numArgs === 1 ?
  30612. spliced :
  30613. spliced.concat(arrCopy(arguments, 2), this.slice(index + removeNum))
  30614. );
  30615. },
  30616. // ### More collection methods
  30617. findLastIndex: function(predicate, context) {
  30618. var key = this.toKeyedSeq().findLastKey(predicate, context);
  30619. return key === undefined ? -1 : key;
  30620. },
  30621. first: function() {
  30622. return this.get(0);
  30623. },
  30624. flatten: function(depth) {
  30625. return reify(this, flattenFactory(this, depth, false));
  30626. },
  30627. get: function(index, notSetValue) {
  30628. index = wrapIndex(this, index);
  30629. return (index < 0 || (this.size === Infinity ||
  30630. (this.size !== undefined && index > this.size))) ?
  30631. notSetValue :
  30632. this.find(function(_, key) {return key === index}, undefined, notSetValue);
  30633. },
  30634. has: function(index) {
  30635. index = wrapIndex(this, index);
  30636. return index >= 0 && (this.size !== undefined ?
  30637. this.size === Infinity || index < this.size :
  30638. this.indexOf(index) !== -1
  30639. );
  30640. },
  30641. interpose: function(separator) {
  30642. return reify(this, interposeFactory(this, separator));
  30643. },
  30644. interleave: function(/*...iterables*/) {
  30645. var iterables = [this].concat(arrCopy(arguments));
  30646. var zipped = zipWithFactory(this.toSeq(), IndexedSeq.of, iterables);
  30647. var interleaved = zipped.flatten(true);
  30648. if (zipped.size) {
  30649. interleaved.size = zipped.size * iterables.length;
  30650. }
  30651. return reify(this, interleaved);
  30652. },
  30653. last: function() {
  30654. return this.get(-1);
  30655. },
  30656. skipWhile: function(predicate, context) {
  30657. return reify(this, skipWhileFactory(this, predicate, context, false));
  30658. },
  30659. zip: function(/*, ...iterables */) {
  30660. var iterables = [this].concat(arrCopy(arguments));
  30661. return reify(this, zipWithFactory(this, defaultZipper, iterables));
  30662. },
  30663. zipWith: function(zipper/*, ...iterables */) {
  30664. var iterables = arrCopy(arguments);
  30665. iterables[0] = this;
  30666. return reify(this, zipWithFactory(this, zipper, iterables));
  30667. }
  30668. });
  30669. IndexedIterable.prototype[IS_INDEXED_SENTINEL] = true;
  30670. IndexedIterable.prototype[IS_ORDERED_SENTINEL] = true;
  30671. mixin(SetIterable, {
  30672. // ### ES6 Collection methods (ES6 Array and Map)
  30673. get: function(value, notSetValue) {
  30674. return this.has(value) ? value : notSetValue;
  30675. },
  30676. includes: function(value) {
  30677. return this.has(value);
  30678. },
  30679. // ### More sequential methods
  30680. keySeq: function() {
  30681. return this.valueSeq();
  30682. }
  30683. });
  30684. SetIterable.prototype.has = IterablePrototype.includes;
  30685. // Mixin subclasses
  30686. mixin(KeyedSeq, KeyedIterable.prototype);
  30687. mixin(IndexedSeq, IndexedIterable.prototype);
  30688. mixin(SetSeq, SetIterable.prototype);
  30689. mixin(KeyedCollection, KeyedIterable.prototype);
  30690. mixin(IndexedCollection, IndexedIterable.prototype);
  30691. mixin(SetCollection, SetIterable.prototype);
  30692. // #pragma Helper functions
  30693. function keyMapper(v, k) {
  30694. return k;
  30695. }
  30696. function entryMapper(v, k) {
  30697. return [k, v];
  30698. }
  30699. function not(predicate) {
  30700. return function() {
  30701. return !predicate.apply(this, arguments);
  30702. }
  30703. }
  30704. function neg(predicate) {
  30705. return function() {
  30706. return -predicate.apply(this, arguments);
  30707. }
  30708. }
  30709. function quoteString(value) {
  30710. return typeof value === 'string' ? JSON.stringify(value) : value;
  30711. }
  30712. function defaultZipper() {
  30713. return arrCopy(arguments);
  30714. }
  30715. function defaultNegComparator(a, b) {
  30716. return a < b ? 1 : a > b ? -1 : 0;
  30717. }
  30718. function hashIterable(iterable) {
  30719. if (iterable.size === Infinity) {
  30720. return 0;
  30721. }
  30722. var ordered = isOrdered(iterable);
  30723. var keyed = isKeyed(iterable);
  30724. var h = ordered ? 1 : 0;
  30725. var size = iterable.__iterate(
  30726. keyed ?
  30727. ordered ?
  30728. function(v, k) { h = 31 * h + hashMerge(hash(v), hash(k)) | 0; } :
  30729. function(v, k) { h = h + hashMerge(hash(v), hash(k)) | 0; } :
  30730. ordered ?
  30731. function(v ) { h = 31 * h + hash(v) | 0; } :
  30732. function(v ) { h = h + hash(v) | 0; }
  30733. );
  30734. return murmurHashOfSize(size, h);
  30735. }
  30736. function murmurHashOfSize(size, h) {
  30737. h = imul(h, 0xCC9E2D51);
  30738. h = imul(h << 15 | h >>> -15, 0x1B873593);
  30739. h = imul(h << 13 | h >>> -13, 5);
  30740. h = (h + 0xE6546B64 | 0) ^ size;
  30741. h = imul(h ^ h >>> 16, 0x85EBCA6B);
  30742. h = imul(h ^ h >>> 13, 0xC2B2AE35);
  30743. h = smi(h ^ h >>> 16);
  30744. return h;
  30745. }
  30746. function hashMerge(a, b) {
  30747. return a ^ b + 0x9E3779B9 + (a << 6) + (a >> 2) | 0; // int
  30748. }
  30749. var Immutable = {
  30750. Iterable: Iterable,
  30751. Seq: Seq,
  30752. Collection: Collection,
  30753. Map: Map,
  30754. OrderedMap: OrderedMap,
  30755. List: List,
  30756. Stack: Stack,
  30757. Set: Set,
  30758. OrderedSet: OrderedSet,
  30759. Record: Record,
  30760. Range: Range,
  30761. Repeat: Repeat,
  30762. is: is,
  30763. fromJS: fromJS
  30764. };
  30765. return Immutable;
  30766. }));
  30767. });
  30768. var dist$2 = createCommonjsModule(function (module, exports) {
  30769. (function webpackUniversalModuleDefinition(root, factory) {
  30770. module.exports = factory(React);
  30771. })(window, function(__WEBPACK_EXTERNAL_MODULE__2__) {
  30772. return /******/ (function(modules) { // webpackBootstrap
  30773. /******/ // The module cache
  30774. /******/ var installedModules = {};
  30775. /******/
  30776. /******/ // The require function
  30777. /******/ function __webpack_require__(moduleId) {
  30778. /******/
  30779. /******/ // Check if module is in cache
  30780. /******/ if(installedModules[moduleId]) {
  30781. /******/ return installedModules[moduleId].exports;
  30782. /******/ }
  30783. /******/ // Create a new module (and put it into the cache)
  30784. /******/ var module = installedModules[moduleId] = {
  30785. /******/ i: moduleId,
  30786. /******/ l: false,
  30787. /******/ exports: {}
  30788. /******/ };
  30789. /******/
  30790. /******/ // Execute the module function
  30791. /******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);
  30792. /******/
  30793. /******/ // Flag the module as loaded
  30794. /******/ module.l = true;
  30795. /******/
  30796. /******/ // Return the exports of the module
  30797. /******/ return module.exports;
  30798. /******/ }
  30799. /******/
  30800. /******/
  30801. /******/ // expose the modules object (__webpack_modules__)
  30802. /******/ __webpack_require__.m = modules;
  30803. /******/
  30804. /******/ // expose the module cache
  30805. /******/ __webpack_require__.c = installedModules;
  30806. /******/
  30807. /******/ // define getter function for harmony exports
  30808. /******/ __webpack_require__.d = function(exports, name, getter) {
  30809. /******/ if(!__webpack_require__.o(exports, name)) {
  30810. /******/ Object.defineProperty(exports, name, { enumerable: true, get: getter });
  30811. /******/ }
  30812. /******/ };
  30813. /******/
  30814. /******/ // define __esModule on exports
  30815. /******/ __webpack_require__.r = function(exports) {
  30816. /******/ if(typeof Symbol !== 'undefined' && Symbol.toStringTag) {
  30817. /******/ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
  30818. /******/ }
  30819. /******/ Object.defineProperty(exports, '__esModule', { value: true });
  30820. /******/ };
  30821. /******/
  30822. /******/ // create a fake namespace object
  30823. /******/ // mode & 1: value is a module id, require it
  30824. /******/ // mode & 2: merge all properties of value into the ns
  30825. /******/ // mode & 4: return value when already ns object
  30826. /******/ // mode & 8|1: behave like require
  30827. /******/ __webpack_require__.t = function(value, mode) {
  30828. /******/ if(mode & 1) value = __webpack_require__(value);
  30829. /******/ if(mode & 8) return value;
  30830. /******/ if((mode & 4) && typeof value === 'object' && value && value.__esModule) return value;
  30831. /******/ var ns = Object.create(null);
  30832. /******/ __webpack_require__.r(ns);
  30833. /******/ Object.defineProperty(ns, 'default', { enumerable: true, value: value });
  30834. /******/ if(mode & 2 && typeof value != 'string') for(var key in value) __webpack_require__.d(ns, key, function(key) { return value[key]; }.bind(null, key));
  30835. /******/ return ns;
  30836. /******/ };
  30837. /******/
  30838. /******/ // getDefaultExport function for compatibility with non-harmony modules
  30839. /******/ __webpack_require__.n = function(module) {
  30840. /******/ var getter = module && module.__esModule ?
  30841. /******/ function getDefault() { return module['default']; } :
  30842. /******/ function getModuleExports() { return module; };
  30843. /******/ __webpack_require__.d(getter, 'a', getter);
  30844. /******/ return getter;
  30845. /******/ };
  30846. /******/
  30847. /******/ // Object.prototype.hasOwnProperty.call
  30848. /******/ __webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); };
  30849. /******/
  30850. /******/ // __webpack_public_path__
  30851. /******/ __webpack_require__.p = "/";
  30852. /******/
  30853. /******/
  30854. /******/ // Load entry module and return exports
  30855. /******/ return __webpack_require__(__webpack_require__.s = 20);
  30856. /******/ })
  30857. /************************************************************************/
  30858. /******/ ([
  30859. /* 0 */
  30860. /***/ (function(module, exports, __webpack_require__) {
  30861. Object.defineProperty(exports, "__esModule", {
  30862. value: true
  30863. });
  30864. var compressImage = exports.compressImage = function compressImage(url) {
  30865. var width = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 1280;
  30866. var height = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 800;
  30867. return new Promise(function (resolve, reject) {
  30868. var image = new Image();
  30869. image.src = url;
  30870. image.onerror = function (error) {
  30871. reject(error);
  30872. };
  30873. image.onload = function () {
  30874. try {
  30875. var compressCanvas = document.createElement('canvas');
  30876. var scale = this.width > width || this.height > height ? this.width > this.height ? width / this.width : height / this.height : 1;
  30877. compressCanvas.width = this.width * scale;
  30878. compressCanvas.height = this.height * scale;
  30879. var canvasContext = compressCanvas.getContext('2d');
  30880. canvasContext.drawImage(this, 0, 0, compressCanvas.width, compressCanvas.height);
  30881. resolve({
  30882. url: compressCanvas.toDataURL('image/png', 1),
  30883. width: compressCanvas.width,
  30884. height: compressCanvas.height
  30885. });
  30886. } catch (error) {
  30887. reject(error);
  30888. }
  30889. };
  30890. });
  30891. };
  30892. /***/ }),
  30893. /* 1 */
  30894. /***/ (function(module, exports, __webpack_require__) {
  30895. Object.defineProperty(exports, "__esModule", {
  30896. value: true
  30897. });
  30898. var UniqueIndex = exports.UniqueIndex = function UniqueIndex() {
  30899. if (isNaN(window.__BRAFT_MM_UNIQUE_INDEX__)) {
  30900. window.__BRAFT_MM_UNIQUE_INDEX__ = 1;
  30901. } else {
  30902. window.__BRAFT_MM_UNIQUE_INDEX__ += 1;
  30903. }
  30904. return window.__BRAFT_MM_UNIQUE_INDEX__;
  30905. };
  30906. /***/ }),
  30907. /* 2 */
  30908. /***/ (function(module, exports) {
  30909. module.exports = __WEBPACK_EXTERNAL_MODULE__2__;
  30910. /***/ }),
  30911. /* 3 */
  30912. /***/ (function(module, exports, __webpack_require__) {
  30913. Object.defineProperty(exports, "__esModule", {
  30914. value: true
  30915. });
  30916. exports.default = {
  30917. remove: 'Kaldır',
  30918. cancel: 'İptal',
  30919. confirm: 'Onayla',
  30920. insert: 'Seçilenleri ekle',
  30921. width: 'Genişlik',
  30922. height: 'Yükseklik',
  30923. image: 'Resim',
  30924. video: 'Görüntü',
  30925. audio: 'Ses',
  30926. embed: 'Nesne göm',
  30927. caption: 'Kitaplık',
  30928. dragTip: 'Tıkla ya da dosya sürükle',
  30929. dropTip: 'Yüklemek için sürükleyin',
  30930. selectAll: 'Tümünü seç',
  30931. deselect: 'Seçimi kaldır',
  30932. removeSelected: 'Seçilenleri kaldır',
  30933. externalInputPlaceHolder: 'Kaynak adı|Kaynak bağlantısı',
  30934. externalInputTip: 'Kaynak asını ve bağlantısını "|" ile ayırın ve Enter\' a basın.',
  30935. addLocalFile: 'Yerel\' den ekle',
  30936. addExternalSource: 'Harici kaynaktan ekle',
  30937. unnamedItem: 'Adlandırılmamış giriş',
  30938. confirmInsert: 'Seçilenleri ekle'
  30939. };
  30940. /***/ }),
  30941. /* 4 */
  30942. /***/ (function(module, exports, __webpack_require__) {
  30943. Object.defineProperty(exports, "__esModule", {
  30944. value: true
  30945. });
  30946. exports.default = {
  30947. remove: '削除する',
  30948. cancel: 'キャンセル',
  30949. confirm: '確認する',
  30950. insert: '選択したアイテムを挿入',
  30951. width: '幅',
  30952. height: '身長',
  30953. image: '絵',
  30954. video: 'ビデオ',
  30955. audio: '音声',
  30956. embed: '埋め込みメディア',
  30957. caption: 'メディアライブラリー',
  30958. dragTip: 'ファイルをこの位置までクリックまたはドラッグします',
  30959. dropTip: 'アップロードするマウスを放します',
  30960. selectAll: 'すべて選択',
  30961. deselect: '選択を解除',
  30962. removeSelected: '選択したアイテムを削除',
  30963. externalInputPlaceHolder: 'リソース名|リソースアドレス',
  30964. externalInputTip: 'リソース名とリソースアドレスは "|"で区切ります。',
  30965. addLocalFile: 'ローカルリソースを追加する',
  30966. addExternalSource: 'ネットワークリソースを追加する',
  30967. unnamedItem: '名前のないアイテム',
  30968. confirmInsert: '選択したアイテムを挿入'
  30969. };
  30970. /***/ }),
  30971. /* 5 */
  30972. /***/ (function(module, exports, __webpack_require__) {
  30973. Object.defineProperty(exports, "__esModule", {
  30974. value: true
  30975. });
  30976. exports.default = {
  30977. remove: '삭제',
  30978. cancel: '취소',
  30979. confirm: '확인',
  30980. insert: '선택한항목삽입',
  30981. width: '너비',
  30982. height: '높이',
  30983. image: '그림',
  30984. video: '비디오',
  30985. audio: '오디오',
  30986. embed: '임베디드미디어',
  30987. caption: '미디어라이브러리',
  30988. dragTip: '파일을 클릭하거나이 지점으로 드래그하십시오.',
  30989. dropTip: '업로드하려면마우스를놓으십시오.',
  30990. selectAll: '모두 선택',
  30991. deselect: '선택 취소',
  30992. removeSelected: '선택한 항목 삭제',
  30993. externalInputPlaceHolder: '리소스 이름 | 리소스 주소',
  30994. externalInputTip: '자원 이름과 자원 주소를 "|"',
  30995. addLocalFile: '로컬 리소스 추가',
  30996. addExternalSource: '네트워크 리소스 추가',
  30997. unnamedItem: '이름없는 항목',
  30998. confirmInsert: '선택한 항목 삽입'
  30999. };
  31000. /***/ }),
  31001. /* 6 */
  31002. /***/ (function(module, exports, __webpack_require__) {
  31003. Object.defineProperty(exports, "__esModule", {
  31004. value: true
  31005. });
  31006. exports.default = {
  31007. remove: 'Usuń',
  31008. cancel: 'Anuluj',
  31009. confirm: 'Potwierdź',
  31010. insert: 'Wstaw wybrane elementy',
  31011. width: 'Szerokość',
  31012. height: 'Wysokość',
  31013. image: 'Obraz',
  31014. video: 'Wideo',
  31015. audio: 'Dźwięk',
  31016. embed: 'Obiekt',
  31017. caption: 'Biblioteka mediów',
  31018. dragTip: 'Kliknij lub przenieś tu pliki',
  31019. dropTip: 'Upuść aby dodać plik',
  31020. selectAll: 'Zaznacz wszystko',
  31021. deselect: 'Odznacz',
  31022. removeSelected: 'Usuń wybrane',
  31023. externalInputPlaceHolder: 'Nazwa źródła|Adres URL',
  31024. externalInputTip: 'Oddziel nazwę i adres URL źródła z pomocą "|", Potwierdź Enter-em',
  31025. addLocalFile: 'Dodaj z komputera',
  31026. addExternalSource: 'Dodaj z Internetu',
  31027. unnamedItem: 'Bez nazwy',
  31028. confirmInsert: 'Dodaj wybrane elementy'
  31029. };
  31030. /***/ }),
  31031. /* 7 */
  31032. /***/ (function(module, exports, __webpack_require__) {
  31033. Object.defineProperty(exports, "__esModule", {
  31034. value: true
  31035. });
  31036. exports.default = {
  31037. remove: '删除',
  31038. cancel: '取消',
  31039. confirm: '确认',
  31040. insert: '插入所选项目',
  31041. width: '宽度',
  31042. height: '高度',
  31043. image: '图片',
  31044. video: '视频',
  31045. audio: '音频',
  31046. embed: '嵌入式媒体',
  31047. caption: '媒体库',
  31048. dragTip: '点击或拖动文件至此',
  31049. dropTip: '放开鼠标以上传',
  31050. selectAll: '选择全部',
  31051. deselect: '取消选择',
  31052. removeSelected: '删除选中项目',
  31053. externalInputPlaceHolder: '资源名称|资源地址',
  31054. externalInputTip: '使用“|”分隔资源名称和资源地址',
  31055. addLocalFile: '添加本地资源',
  31056. addExternalSource: '添加网络资源',
  31057. unnamedItem: '未命名项目',
  31058. confirmInsert: '插入选中项目'
  31059. };
  31060. /***/ }),
  31061. /* 8 */
  31062. /***/ (function(module, exports, __webpack_require__) {
  31063. Object.defineProperty(exports, "__esModule", {
  31064. value: true
  31065. });
  31066. exports.default = {
  31067. remove: '删除',
  31068. cancel: '取消',
  31069. confirm: '确认',
  31070. insert: '插入所选项目',
  31071. width: '宽度',
  31072. height: '高度',
  31073. image: '图片',
  31074. video: '视频',
  31075. audio: '音频',
  31076. embed: '嵌入式媒体',
  31077. caption: '媒体库',
  31078. dragTip: '点击或拖动文件至此',
  31079. dropTip: '放开鼠标以上传',
  31080. selectAll: '选择全部',
  31081. deselect: '取消选择',
  31082. removeSelected: '删除选中项目',
  31083. externalInputPlaceHolder: '资源名称|资源地址',
  31084. externalInputTip: '使用“|”分隔资源名称和资源地址',
  31085. addLocalFile: '添加本地资源',
  31086. addExternalSource: '添加网络资源',
  31087. unnamedItem: '未命名项目',
  31088. confirmInsert: '插入选中项目'
  31089. };
  31090. /***/ }),
  31091. /* 9 */
  31092. /***/ (function(module, exports, __webpack_require__) {
  31093. Object.defineProperty(exports, "__esModule", {
  31094. value: true
  31095. });
  31096. exports.default = {
  31097. remove: 'Remove',
  31098. cancel: 'Cancel',
  31099. confirm: 'Confirm',
  31100. insert: 'Insert Selected Items',
  31101. width: 'Width',
  31102. height: 'Height',
  31103. image: 'Image',
  31104. video: 'Video',
  31105. audio: 'Audio',
  31106. embed: 'Embed',
  31107. caption: 'Media Library',
  31108. dragTip: 'Click Or Drag Files Here',
  31109. dropTip: 'Drop To Upload',
  31110. selectAll: 'Select All',
  31111. deselect: 'Deselect',
  31112. removeSelected: 'Remove Selected Items',
  31113. externalInputPlaceHolder: 'Source Name|Source URL',
  31114. externalInputTip: 'Split source name and source URL with "|", confirm by hit Enter.',
  31115. addLocalFile: 'Add from local',
  31116. addExternalSource: 'Add from Internet',
  31117. unnamedItem: 'Unnamed Item',
  31118. confirmInsert: 'Insert selected items'
  31119. };
  31120. /***/ }),
  31121. /* 10 */
  31122. /***/ (function(module, exports, __webpack_require__) {
  31123. Object.defineProperty(exports, "__esModule", {
  31124. value: true
  31125. });
  31126. var _en = __webpack_require__(9);
  31127. var _en2 = _interopRequireDefault(_en);
  31128. var _zh = __webpack_require__(8);
  31129. var _zh2 = _interopRequireDefault(_zh);
  31130. var _zhHant = __webpack_require__(7);
  31131. var _zhHant2 = _interopRequireDefault(_zhHant);
  31132. var _pl = __webpack_require__(6);
  31133. var _pl2 = _interopRequireDefault(_pl);
  31134. var _kr = __webpack_require__(5);
  31135. var _kr2 = _interopRequireDefault(_kr);
  31136. var _jpn = __webpack_require__(4);
  31137. var _jpn2 = _interopRequireDefault(_jpn);
  31138. var _tr = __webpack_require__(3);
  31139. var _tr2 = _interopRequireDefault(_tr);
  31140. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  31141. exports.default = {
  31142. "en": _en2.default,
  31143. "zh": _zh2.default,
  31144. "zh-hant": _zhHant2.default,
  31145. "pl": _pl2.default,
  31146. "kr": _kr2.default,
  31147. "jpn": _jpn2.default,
  31148. "tr": _tr2.default
  31149. };
  31150. /***/ }),
  31151. /* 11 */
  31152. /***/ (function(module, exports) {
  31153. /**
  31154. * When source maps are enabled, `style-loader` uses a link element with a data-uri to
  31155. * embed the css on the page. This breaks all relative urls because now they are relative to a
  31156. * bundle instead of the current page.
  31157. *
  31158. * One solution is to only use full urls, but that may be impossible.
  31159. *
  31160. * Instead, this function "fixes" the relative urls to be absolute according to the current page location.
  31161. *
  31162. * A rudimentary test suite is located at `test/fixUrls.js` and can be run via the `npm test` command.
  31163. *
  31164. */
  31165. module.exports = function (css) {
  31166. // get current location
  31167. var location = typeof window !== "undefined" && window.location;
  31168. if (!location) {
  31169. throw new Error("fixUrls requires window.location");
  31170. }
  31171. // blank or null?
  31172. if (!css || typeof css !== "string") {
  31173. return css;
  31174. }
  31175. var baseUrl = location.protocol + "//" + location.host;
  31176. var currentDir = baseUrl + location.pathname.replace(/\/[^\/]*$/, "/");
  31177. // convert each url(...)
  31178. /*
  31179. This regular expression is just a way to recursively match brackets within
  31180. a string.
  31181. /url\s*\( = Match on the word "url" with any whitespace after it and then a parens
  31182. ( = Start a capturing group
  31183. (?: = Start a non-capturing group
  31184. [^)(] = Match anything that isn't a parentheses
  31185. | = OR
  31186. \( = Match a start parentheses
  31187. (?: = Start another non-capturing groups
  31188. [^)(]+ = Match anything that isn't a parentheses
  31189. | = OR
  31190. \( = Match a start parentheses
  31191. [^)(]* = Match anything that isn't a parentheses
  31192. \) = Match a end parentheses
  31193. ) = End Group
  31194. *\) = Match anything and then a close parens
  31195. ) = Close non-capturing group
  31196. * = Match anything
  31197. ) = Close capturing group
  31198. \) = Match a close parens
  31199. /gi = Get all matches, not the first. Be case insensitive.
  31200. */
  31201. var fixedCss = css.replace(/url\s*\(((?:[^)(]|\((?:[^)(]+|\([^)(]*\))*\))*)\)/gi, function(fullMatch, origUrl) {
  31202. // strip quotes (if they exist)
  31203. var unquotedOrigUrl = origUrl
  31204. .trim()
  31205. .replace(/^"(.*)"$/, function(o, $1){ return $1; })
  31206. .replace(/^'(.*)'$/, function(o, $1){ return $1; });
  31207. // already a full url? no change
  31208. if (/^(#|data:|http:\/\/|https:\/\/|file:\/\/\/|\s*$)/i.test(unquotedOrigUrl)) {
  31209. return fullMatch;
  31210. }
  31211. // convert the url to a full url
  31212. var newUrl;
  31213. if (unquotedOrigUrl.indexOf("//") === 0) {
  31214. //TODO: should we add protocol?
  31215. newUrl = unquotedOrigUrl;
  31216. } else if (unquotedOrigUrl.indexOf("/") === 0) {
  31217. // path should be relative to the base url
  31218. newUrl = baseUrl + unquotedOrigUrl; // already starts with '/'
  31219. } else {
  31220. // path should be relative to current directory
  31221. newUrl = currentDir + unquotedOrigUrl.replace(/^\.\//, ""); // Strip leading './'
  31222. }
  31223. // send back the fixed url(...)
  31224. return "url(" + JSON.stringify(newUrl) + ")";
  31225. });
  31226. // send back the fixed css
  31227. return fixedCss;
  31228. };
  31229. /***/ }),
  31230. /* 12 */
  31231. /***/ (function(module, exports, __webpack_require__) {
  31232. /*
  31233. MIT License http://www.opensource.org/licenses/mit-license.php
  31234. Author Tobias Koppers @sokra
  31235. */
  31236. var stylesInDom = {};
  31237. var memoize = function (fn) {
  31238. var memo;
  31239. return function () {
  31240. if (typeof memo === "undefined") memo = fn.apply(this, arguments);
  31241. return memo;
  31242. };
  31243. };
  31244. var isOldIE = memoize(function () {
  31245. // Test for IE <= 9 as proposed by Browserhacks
  31246. // @see http://browserhacks.com/#hack-e71d8692f65334173fee715c222cb805
  31247. // Tests for existence of standard globals is to allow style-loader
  31248. // to operate correctly into non-standard environments
  31249. // @see https://github.com/webpack-contrib/style-loader/issues/177
  31250. return window && document && document.all && !window.atob;
  31251. });
  31252. var getTarget = function (target) {
  31253. return document.querySelector(target);
  31254. };
  31255. var getElement = (function (fn) {
  31256. var memo = {};
  31257. return function(target) {
  31258. // If passing function in options, then use it for resolve "head" element.
  31259. // Useful for Shadow Root style i.e
  31260. // {
  31261. // insertInto: function () { return document.querySelector("#foo").shadowRoot }
  31262. // }
  31263. if (typeof target === 'function') {
  31264. return target();
  31265. }
  31266. if (typeof memo[target] === "undefined") {
  31267. var styleTarget = getTarget.call(this, target);
  31268. // Special case to return head of iframe instead of iframe itself
  31269. if (window.HTMLIFrameElement && styleTarget instanceof window.HTMLIFrameElement) {
  31270. try {
  31271. // This will throw an exception if access to iframe is blocked
  31272. // due to cross-origin restrictions
  31273. styleTarget = styleTarget.contentDocument.head;
  31274. } catch(e) {
  31275. styleTarget = null;
  31276. }
  31277. }
  31278. memo[target] = styleTarget;
  31279. }
  31280. return memo[target]
  31281. };
  31282. })();
  31283. var singleton = null;
  31284. var singletonCounter = 0;
  31285. var stylesInsertedAtTop = [];
  31286. var fixUrls = __webpack_require__(11);
  31287. module.exports = function(list, options) {
  31288. if (typeof DEBUG !== "undefined" && DEBUG) {
  31289. if (typeof document !== "object") throw new Error("The style-loader cannot be used in a non-browser environment");
  31290. }
  31291. options = options || {};
  31292. options.attrs = typeof options.attrs === "object" ? options.attrs : {};
  31293. // Force single-tag solution on IE6-9, which has a hard limit on the # of <style>
  31294. // tags it will allow on a page
  31295. if (!options.singleton && typeof options.singleton !== "boolean") options.singleton = isOldIE();
  31296. // By default, add <style> tags to the <head> element
  31297. if (!options.insertInto) options.insertInto = "head";
  31298. // By default, add <style> tags to the bottom of the target
  31299. if (!options.insertAt) options.insertAt = "bottom";
  31300. var styles = listToStyles(list, options);
  31301. addStylesToDom(styles, options);
  31302. return function update (newList) {
  31303. var mayRemove = [];
  31304. for (var i = 0; i < styles.length; i++) {
  31305. var item = styles[i];
  31306. var domStyle = stylesInDom[item.id];
  31307. domStyle.refs--;
  31308. mayRemove.push(domStyle);
  31309. }
  31310. if(newList) {
  31311. var newStyles = listToStyles(newList, options);
  31312. addStylesToDom(newStyles, options);
  31313. }
  31314. for (var i = 0; i < mayRemove.length; i++) {
  31315. var domStyle = mayRemove[i];
  31316. if(domStyle.refs === 0) {
  31317. for (var j = 0; j < domStyle.parts.length; j++) domStyle.parts[j]();
  31318. delete stylesInDom[domStyle.id];
  31319. }
  31320. }
  31321. };
  31322. };
  31323. function addStylesToDom (styles, options) {
  31324. for (var i = 0; i < styles.length; i++) {
  31325. var item = styles[i];
  31326. var domStyle = stylesInDom[item.id];
  31327. if(domStyle) {
  31328. domStyle.refs++;
  31329. for(var j = 0; j < domStyle.parts.length; j++) {
  31330. domStyle.parts[j](item.parts[j]);
  31331. }
  31332. for(; j < item.parts.length; j++) {
  31333. domStyle.parts.push(addStyle(item.parts[j], options));
  31334. }
  31335. } else {
  31336. var parts = [];
  31337. for(var j = 0; j < item.parts.length; j++) {
  31338. parts.push(addStyle(item.parts[j], options));
  31339. }
  31340. stylesInDom[item.id] = {id: item.id, refs: 1, parts: parts};
  31341. }
  31342. }
  31343. }
  31344. function listToStyles (list, options) {
  31345. var styles = [];
  31346. var newStyles = {};
  31347. for (var i = 0; i < list.length; i++) {
  31348. var item = list[i];
  31349. var id = options.base ? item[0] + options.base : item[0];
  31350. var css = item[1];
  31351. var media = item[2];
  31352. var sourceMap = item[3];
  31353. var part = {css: css, media: media, sourceMap: sourceMap};
  31354. if(!newStyles[id]) styles.push(newStyles[id] = {id: id, parts: [part]});
  31355. else newStyles[id].parts.push(part);
  31356. }
  31357. return styles;
  31358. }
  31359. function insertStyleElement (options, style) {
  31360. var target = getElement(options.insertInto);
  31361. if (!target) {
  31362. throw new Error("Couldn't find a style target. This probably means that the value for the 'insertInto' parameter is invalid.");
  31363. }
  31364. var lastStyleElementInsertedAtTop = stylesInsertedAtTop[stylesInsertedAtTop.length - 1];
  31365. if (options.insertAt === "top") {
  31366. if (!lastStyleElementInsertedAtTop) {
  31367. target.insertBefore(style, target.firstChild);
  31368. } else if (lastStyleElementInsertedAtTop.nextSibling) {
  31369. target.insertBefore(style, lastStyleElementInsertedAtTop.nextSibling);
  31370. } else {
  31371. target.appendChild(style);
  31372. }
  31373. stylesInsertedAtTop.push(style);
  31374. } else if (options.insertAt === "bottom") {
  31375. target.appendChild(style);
  31376. } else if (typeof options.insertAt === "object" && options.insertAt.before) {
  31377. var nextSibling = getElement(options.insertInto + " " + options.insertAt.before);
  31378. target.insertBefore(style, nextSibling);
  31379. } else {
  31380. throw new Error("[Style Loader]\n\n Invalid value for parameter 'insertAt' ('options.insertAt') found.\n Must be 'top', 'bottom', or Object.\n (https://github.com/webpack-contrib/style-loader#insertat)\n");
  31381. }
  31382. }
  31383. function removeStyleElement (style) {
  31384. if (style.parentNode === null) return false;
  31385. style.parentNode.removeChild(style);
  31386. var idx = stylesInsertedAtTop.indexOf(style);
  31387. if(idx >= 0) {
  31388. stylesInsertedAtTop.splice(idx, 1);
  31389. }
  31390. }
  31391. function createStyleElement (options) {
  31392. var style = document.createElement("style");
  31393. if(options.attrs.type === undefined) {
  31394. options.attrs.type = "text/css";
  31395. }
  31396. addAttrs(style, options.attrs);
  31397. insertStyleElement(options, style);
  31398. return style;
  31399. }
  31400. function createLinkElement (options) {
  31401. var link = document.createElement("link");
  31402. if(options.attrs.type === undefined) {
  31403. options.attrs.type = "text/css";
  31404. }
  31405. options.attrs.rel = "stylesheet";
  31406. addAttrs(link, options.attrs);
  31407. insertStyleElement(options, link);
  31408. return link;
  31409. }
  31410. function addAttrs (el, attrs) {
  31411. Object.keys(attrs).forEach(function (key) {
  31412. el.setAttribute(key, attrs[key]);
  31413. });
  31414. }
  31415. function addStyle (obj, options) {
  31416. var style, update, remove, result;
  31417. // If a transform function was defined, run it on the css
  31418. if (options.transform && obj.css) {
  31419. result = options.transform(obj.css);
  31420. if (result) {
  31421. // If transform returns a value, use that instead of the original css.
  31422. // This allows running runtime transformations on the css.
  31423. obj.css = result;
  31424. } else {
  31425. // If the transform function returns a falsy value, don't add this css.
  31426. // This allows conditional loading of css
  31427. return function() {
  31428. // noop
  31429. };
  31430. }
  31431. }
  31432. if (options.singleton) {
  31433. var styleIndex = singletonCounter++;
  31434. style = singleton || (singleton = createStyleElement(options));
  31435. update = applyToSingletonTag.bind(null, style, styleIndex, false);
  31436. remove = applyToSingletonTag.bind(null, style, styleIndex, true);
  31437. } else if (
  31438. obj.sourceMap &&
  31439. typeof URL === "function" &&
  31440. typeof URL.createObjectURL === "function" &&
  31441. typeof URL.revokeObjectURL === "function" &&
  31442. typeof Blob === "function" &&
  31443. typeof btoa === "function"
  31444. ) {
  31445. style = createLinkElement(options);
  31446. update = updateLink.bind(null, style, options);
  31447. remove = function () {
  31448. removeStyleElement(style);
  31449. if(style.href) URL.revokeObjectURL(style.href);
  31450. };
  31451. } else {
  31452. style = createStyleElement(options);
  31453. update = applyToTag.bind(null, style);
  31454. remove = function () {
  31455. removeStyleElement(style);
  31456. };
  31457. }
  31458. update(obj);
  31459. return function updateStyle (newObj) {
  31460. if (newObj) {
  31461. if (
  31462. newObj.css === obj.css &&
  31463. newObj.media === obj.media &&
  31464. newObj.sourceMap === obj.sourceMap
  31465. ) {
  31466. return;
  31467. }
  31468. update(obj = newObj);
  31469. } else {
  31470. remove();
  31471. }
  31472. };
  31473. }
  31474. var replaceText = (function () {
  31475. var textStore = [];
  31476. return function (index, replacement) {
  31477. textStore[index] = replacement;
  31478. return textStore.filter(Boolean).join('\n');
  31479. };
  31480. })();
  31481. function applyToSingletonTag (style, index, remove, obj) {
  31482. var css = remove ? "" : obj.css;
  31483. if (style.styleSheet) {
  31484. style.styleSheet.cssText = replaceText(index, css);
  31485. } else {
  31486. var cssNode = document.createTextNode(css);
  31487. var childNodes = style.childNodes;
  31488. if (childNodes[index]) style.removeChild(childNodes[index]);
  31489. if (childNodes.length) {
  31490. style.insertBefore(cssNode, childNodes[index]);
  31491. } else {
  31492. style.appendChild(cssNode);
  31493. }
  31494. }
  31495. }
  31496. function applyToTag (style, obj) {
  31497. var css = obj.css;
  31498. var media = obj.media;
  31499. if(media) {
  31500. style.setAttribute("media", media);
  31501. }
  31502. if(style.styleSheet) {
  31503. style.styleSheet.cssText = css;
  31504. } else {
  31505. while(style.firstChild) {
  31506. style.removeChild(style.firstChild);
  31507. }
  31508. style.appendChild(document.createTextNode(css));
  31509. }
  31510. }
  31511. function updateLink (link, options, obj) {
  31512. var css = obj.css;
  31513. var sourceMap = obj.sourceMap;
  31514. /*
  31515. If convertToAbsoluteUrls isn't defined, but sourcemaps are enabled
  31516. and there is no publicPath defined then lets turn convertToAbsoluteUrls
  31517. on by default. Otherwise default to the convertToAbsoluteUrls option
  31518. directly
  31519. */
  31520. var autoFixUrls = options.convertToAbsoluteUrls === undefined && sourceMap;
  31521. if (options.convertToAbsoluteUrls || autoFixUrls) {
  31522. css = fixUrls(css);
  31523. }
  31524. if (sourceMap) {
  31525. // http://stackoverflow.com/a/26603875
  31526. css += "\n/*# sourceMappingURL=data:application/json;base64," + btoa(unescape(encodeURIComponent(JSON.stringify(sourceMap)))) + " */";
  31527. }
  31528. var blob = new Blob([css], { type: "text/css" });
  31529. var oldSrc = link.href;
  31530. link.href = URL.createObjectURL(blob);
  31531. if(oldSrc) URL.revokeObjectURL(oldSrc);
  31532. }
  31533. /***/ }),
  31534. /* 13 */
  31535. /***/ (function(module, exports) {
  31536. module.exports = "data:font/ttf;base64,AAEAAAALAIAAAwAwT1MvMg8SBsIAAAC8AAAAYGNtYXBWNv1DAAABHAAAANRnYXNwAAAAEAAAAfAAAAAIZ2x5ZtZLKCQAAAH4AAAPTGhlYWQT25ZrAAARRAAAADZoaGVhB8ID3gAAEXwAAAAkaG10eGoAC+sAABGgAAAAdGxvY2EqcC3wAAASFAAAADxtYXhwACcAewAAElAAAAAgbmFtZZlKCfsAABJwAAABhnBvc3QAAwAAAAAT+AAAACAAAwPsAZAABQAAApkCzAAAAI8CmQLMAAAB6wAzAQkAAAAAAAAAAAAAAAAAAAABEAAAAAAAAAAAAAAAAAAAAABAAADprAPA/8AAQAPAAEAAAAABAAAAAAAAAAAAAAAgAAAAAAADAAAAAwAAABwAAQADAAAAHAADAAEAAAAcAAQAuAAAACoAIAAEAAoAAQAg4DTgN+BC4V3iQ+gN6Mno/ukD6QjpD+kT6RjpHOkm6YDprP/9//8AAAAAACDgNOA34ELhXeJD6A3oyej+6QHpB+kO6RHpFukc6SbpgOms//3//wAB/+Mf0B/OH8Qeqh3FF/wXQRcNFwsXCBcDFwIXABb9FvQWmxZwAAMAAQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABAAH//wAPAAEAAAAAAAAAAAACAAA3OQEAAAAAAQAAAAAAAAAAAAIAADc5AQAAAAABAAAAAAAAAAAAAgAANzkBAAAAAAIBAACBAwAC1QADAAcAAAEzESMhETMRAlaqqv6qqgLV/awCVP2sAAABAVYAgQMqAtUAAgAACQIBVgHU/iwC1f7W/tYAAQCqACsDVgOBAC4AAAEyFx4BFxYVFAcOAQcGIyInLgEnJjUzFBceARcWMzI3PgE3NjU0Jy4BJyYjFSc3AgBGPz5dGxsbG10+PkdGPz5dGxtWFBRFLy81NS8vRRQUFBRFLy811tYC1RsbXD4+Rkc+Pl0bGxsbXT4+RzYuL0UUFBQURS8uNjUvLkYUFKzW1gAAAwBWAAEDqgNVABsANwA7AAAlMjc+ATc2NTQnLgEnJiMiBw4BBwYVFBceARcWEzIXHgEXFhUUBw4BBwYjIicuAScmNTQ3PgE3NgMhFSECAEY/Pl0bGxsbXT4+R0Y/Pl0bGxsbXT4+R1hOTnMiISEic05NWVhOTnMiISEic05NfQGs/lRVGxtdPj5HRj4/XRsbGxtdPz5GRz4+XRsbAwAiIXRNTlhZTU50ISEhIXROTVlYTk10ISL+gFQAAAABAKoAAQOAA1UAHwAAATMRIREUBisBIiY1ESE1IxUUBiMhIiY9ATQ2MyEyFhUDAID+qhgSVhIYAaoqGBL+ABIaGhICABIYAwH+qv6AEhgYEgHWqioSGhoSqhIYGBIAAAABAIAAAwOAA1UAMwAAJTIWFRQGIyImNTwBNyUOASMiJjU0NjMyFhclLgE1NDYzMhYVFAYjIiYnBR4BFRQGBwU+AQMAM0lJMzNJAv7SEiwaNExLNRktEgEsAQNLNTRMSzUZLRL+1AEDAgIBMBAs/UkzM0tLMwcPBrAREUs1NEwSEK4HDwg0TEw0NUsTEbAIDwcIDwewDxEAAAMAVgArA6oDVQACAAYAGgAALQI3FTM1FyERFAYjISImNREhNTQ2OwEyFhUBgAFA/sAqrFQBADAk/VQkMAEAMCSsJDCr1qrWVlZW/dYkMjIkAipWJDAwJAAEAIAAgQOAAtUAAwAHAAsADwAAEyEVIRU1IRUBNSEVJTUhFYADAP0AAwD9AAMA/QADAALVVKxWVv6sVFSqVlYABABVACIDqwN3AAQAIQA9AEIAACUzESMREyIHDgEHBhUUFx4BFxYzMjc+ATc2NTQnLgEnJiMRIicuAScmNTQ3PgE3NjMyFx4BFxYVFAcOAQcGAzM1IxUB1VZWK1hOTnQhIiIhdE5OWFhOTnQhIiIhdE5OWEc+Pl0aGxsaXT4+R0c+Pl0aGxsaXT4+clZW9wEA/wACgCEic05OWFlNTnQhIiIhdE5NWVhOTnMiIf0AGxtdPj5HRj8+XBsbGxtcPj9GRz4+XRsbAdZVVQAABABVACIDqwN3AAQAIQA9AFIAACUzNSMVEyIHDgEHBhUUFx4BFxYzMjc+ATc2NTQnLgEnJiMRIicuAScmNTQ3PgE3NjMyFx4BFxYVFAcOAQcGAyIGFTM0NjMyFhUUBhUzNDY1NCYjAdVWVitYTk50ISIiIXROTlhYTk50ISIiIXROTlhHPj5dGhsbGl0+PkdHPj5dGhsbGl0+PkdHZFYyIyMygFaAZEfNVVUCqiEic05OWFlNTnQhIiIhdE5NWVhOTnMiIf0AGxtdPj5HRj8+XBsbGxtcPj9GRz4+XRsbAlZkRyMyMiNALWhIPVBHZAAAAgBVAM0DqwLNAAUACwAAASc3JwkBJTcnNwkBAZHExDz/AAEAARrExDwBAP8AAQnExDz/AP8APMTEPP8A/wAAAAMAVQAiA6sDdwAcACsAOgAAASIHDgEHBhUUFx4BFxYzMjc+ATc2NTQnLgEnJiMBNDc+ATc2MzIWFwEuATUBIiYnAR4BFRQHDgEHBiMCAFhOTXQiIiIidE1OWFhOTXQiIiIidE1OWP6rGxtcPj9GOmot/iIjJQFVOmotAd4jJRsbXD4/RgN3ISJ0Tk1YWE5OdCEiIiF0Tk5YWE1OdCIh/lZGPj5dGxslI/4iLWo6/qomIwHeLWs5Rz4+XRsbAAAAAAMAgADNA4ACzQADAAcACwAANyE1ITUhNSE1FSE1gAMA/QADAP0AAwDNVYBV1lZWAAEAZAAlA1wDXABEAAABERQHBgcGBwYjIicmJyYnJjU0NzY3Njc2MzIXEQURFAcGBwYHBiMiJyYnJicmNTQ3Njc2NzYzMhcRNDc2NyU2MzIXFhUDXBERGhkaGRYXGRoZGhEREREaGRoZFzMr/oURERoZGhkXFhkaGRoRERERGhkaGRY0KwoJDwGbBggUDg4DLP3WGBQTCgsFBQUFCwoTFBgZExQKCwUFEwEKdv6iGRMTCwsFBQUFCwsTExkZExMLCgYFEwHeDw0MBX8CDg4UAAAEAHUAQgOJA1YALwA8AGIAeAAAAS4BBw4BJy4BJy4BBwYiJyYGBw4BJyYGBxQVHAEVFBUeATM2MzoBMzIzMjY3PAE1BSImNTQ2MzIWFRQGJyUqASM8ATU6ATMUFhUUFxwBFQYHFAYHDgEnLgE3PgE3OgEzPAE1BT4BNzoBMxQWBw4BJy4BNz4BNzoBMwKBARkZChUJCxcEFEMvBw8HHikMDCgdFyILCxgWNDM0ZzQzNBsaAf77L0FBMDBAQDEBtx8/IDRoNgEBAQENCxVFICIlBgc3JAcNCf7OAQICEyQTAwUFSiMmOAIBOiYHEAkCzhcaAQEBAwIJCC0fCAEBBhgbGxYGBBMVKCgpUCgoKQ8VARcaSpRK7T8uMEA/LzBAARchPyAKEgkzMjNmMjMzFCwRIBAOD0IjJjQDN2053QwUCi5dLSUsBgVEJig+BAAAAAAEAAAAAAQAA0AAGwAzAE8AUwAAARQXHgEXFjMyNz4BNzY1NCcuAScmIyIHDgEHBgEjLgEjISIGByMiBhURFBYzITI2NRE0JgEiJy4BJyY1NDc+ATc2MzIXHgEXFhUUBw4BBwYBIzUzATAQETgmJisrJiY4ERAQETgmJisrJiY4ERACkOAMJDD/ADAkDOAaJiYaA4AaJib+Jjs0M00XFhYXTTM0Ozs0M00XFhYXTTM0AYWAgAFgKyYmOBEQEBE4JiYrKyYmOBEQEBE4JiYBNTBQUDAmGv3AGiYmGgJAGib9hBYXTTM0Ozs0M00XFhYXTTM0Ozs0M00XFgG8QAABAJEAogOAAt4ABgAAAScHFwEnAQGAszzvAgA8/jwBGrM87wIAPP48AAAAAAEA4gCAAx4CyQAmAAABNzY0JyYiDwEnJiIHBhQfAQcGFBceATMyNj8BFx4BMzI2NzY0LwECPOINDQwkDOLiDCQMDQ3i4g0NBhAICBAG4uIGEAgIEAYNDeIBq+IMIw0MDOLiDAwNIwzi4g0jDAcGBgfh4QcGBgcMIw3iAAACAIAAYwNqA00AIgAvAAABIyc+ATU0Jy4BJyYjIgcOAQcGFRQXHgEXFjMyNjcXFRc3JyEiJjU0NjMyFhUUBiMClSEMHyQWFkszMjo5MzJLFhYWFksyMzk0XCUL1j/V/wBPcXFPUHBwUAF3DCRdMzoyM0sWFhYWSzMyOjkyM0sWFiQfDCLUP9VxT1BwcFBPcQACAGQAIgOcA3cATQBZAAABPgE1NCYnNz4BLwEuAQ8BLgEvAS4BKwEiBg8BDgEHJyYGDwEGFh8BDgEVFBYXBw4BHwEeAT8BHgEfAR4BOwEyNj8BPgE3FxY2PwE2JicFIiY1NDYzMhYVFAYDPQECAgFaBgMEVQQPB2oRJBQQAQwIqggMARAUJBFqBw8EVQQDBloBAgIBWgYDBFUEDwdqESQUEAEMCKoIDAEQFCQRagcPBFUEAwb+aT5XVz4+V1cBowoVCwsUC0YFDweUBwUDKgwVCHIHCgoHcggVDCoDBQeUBw8FRgsVCgsVCkYFEAeTBwUCKw0VCHEICgoIcQgVDSsDBgeTBxAFJlg+PldXPj5YAAEA1QCiAysC9wALAAABIREjESE1IREzESEDK/8AVv8AAQBWAQABov8AAQBVAQD/AAAAAAAJAAAAQAQAA0AAAwAHAAsADwATABcAGwAfACIAABMRIREBIzUzNSM1MzUjNTMBIREhEyM1MzUjNTM1IzUzBRElAAQA/MCAgICAgIACQP4AAgDAgICAgICA/cABAANA/QADAP1AgICAgID9gAKA/YCAgICAgID+gMAAAAAABgBA/8ADwAPAABkAIQA5AEcAVQBjAAABLgEnLgEnLgEjISIGFREUFjMhMjY1ETQmJyceARcjNR4BExQGIyEiJjURNDYzMDM6ATMyMRUUFjsBAyEiJjU0NjMhMhYVFAYnISImNTQ2MyEyFhUUBichIiY1NDYzITIWFRQGA5YRLRkaMxcnKQv+ECEvLyEC4CEvDhyFFyUNmhEphgkH/SAHCQkHTU66TU4TDeCg/kANExMNAcANExMN/kANExMNAcANExMN/kANExMNAcANExMC2xczGhktERwOLyH8oCEvLyECcAspJzYXKRGaDSX86AcJCQcDYAcJ4A0T/gATDQ0TEw0NE4ATDQ0TEw0NE4ATDQ0TEw0NEwAAAAcAAP/ABAADRgALABcAIwAvADsARwBTAAAlNDYzMhYVFAYjIiYBNDYzMhYVFAYjIiYlNDYzMhYVFAYjIiYBNDYzMhYVFAYjIiYBNDYzMhYVFAYjIiYlNDYzMhYVFAYjIiYBNDYzMhYVFAYjIiYBoDgoKDg4KCg4/mA4KCg4OCgoOANAOCgoODgoKDj9OjgoKDg4KCg4Akw4KCg4OCgoOP20OCgoODgoKDgCTDgoKDg4KCg4ICg4OCgoODgByCg4OCgoODgoKDg4KCg4OAFOKDg4KCg4OP3cKDg4KCg4OCgoODgoKDg4AnQoODgoKDg4AAUAfAAAA4QDVQAiAC0AOABGAFQAAAEjNTQmKwEiBh0BIyIGFRQWOwERFBYzITI2NREzMjY1NCYjJTQ2OwEyFh0BIzUBFAYjISImNREhEQEiBh0BFBYzMjY9ATQmMyIGHQEUFjMyNj0BNCYDXZtEMJwwRJsQFxcQJ0QwAYQwRCcQFxcQ/i8WEJwQFugBXRcQ/nwQFwHS/skQFhYQEBcXjBAXFxAQFhYCuicwREQwJxcQEBb+BzBERDAB+RYQEBcnEBcXECcn/ZMQFhYQAfn+BwGEFxDoEBcXEOgQFxcQ6BAXFxDoEBcAAAABAAAAAQAANAmLwV8PPPUACwQAAAAAANheKPcAAAAA2F4o9wAA/8AEAAPAAAAACAACAAAAAAAAAAEAAAPA/8AAAAQAAAAAAAQAAAEAAAAAAAAAAAAAAAAAAAAdBAAAAAAAAAAAAAAAAgAAAAQAAQAEAAFWBAAAqgQAAFYEAACqBAAAgAQAAFYEAACABAAAVQQAAFUEAABVBAAAVQQAAIAEAABkBAAAdQQAAAAEAACRBAAA4gQAAIAEAABkBAAA1QQAAAAEAABABAAAAAQAAHwAAAAAAAoAFAAeADIAQACIAOYBFgFiAY4BrgIUAowCrAMMAyQDjAQ0BLIEyAUGBU4F1gXwBi4GugcyB6YAAQAAAB0AeQAJAAAAAAACAAAAAAAAAAAAAAAAAAAAAAAAAA4ArgABAAAAAAABAAcAAAABAAAAAAACAAcAYAABAAAAAAADAAcANgABAAAAAAAEAAcAdQABAAAAAAAFAAsAFQABAAAAAAAGAAcASwABAAAAAAAKABoAigADAAEECQABAA4ABwADAAEECQACAA4AZwADAAEECQADAA4APQADAAEECQAEAA4AfAADAAEECQAFABYAIAADAAEECQAGAA4AUgADAAEECQAKADQApGljb21vb24AaQBjAG8AbQBvAG8AblZlcnNpb24gMS4wAFYAZQByAHMAaQBvAG4AIAAxAC4AMGljb21vb24AaQBjAG8AbQBvAG8Abmljb21vb24AaQBjAG8AbQBvAG8AblJlZ3VsYXIAUgBlAGcAdQBsAGEAcmljb21vb24AaQBjAG8AbQBvAG8AbkZvbnQgZ2VuZXJhdGVkIGJ5IEljb01vb24uAEYAbwBuAHQAIABnAGUAbgBlAHIAYQB0AGUAZAAgAGIAeQAgAEkAYwBvAE0AbwBvAG4ALgAAAAMAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=";
  31537. /***/ }),
  31538. /* 14 */
  31539. /***/ (function(module, exports) {
  31540. /*
  31541. MIT License http://www.opensource.org/licenses/mit-license.php
  31542. Author Tobias Koppers @sokra
  31543. */
  31544. // css base code, injected by the css-loader
  31545. module.exports = function(useSourceMap) {
  31546. var list = [];
  31547. // return the list of modules as css string
  31548. list.toString = function toString() {
  31549. return this.map(function (item) {
  31550. var content = cssWithMappingToString(item, useSourceMap);
  31551. if(item[2]) {
  31552. return "@media " + item[2] + "{" + content + "}";
  31553. } else {
  31554. return content;
  31555. }
  31556. }).join("");
  31557. };
  31558. // import a list of modules into the list
  31559. list.i = function(modules, mediaQuery) {
  31560. if(typeof modules === "string")
  31561. modules = [[null, modules, ""]];
  31562. var alreadyImportedModules = {};
  31563. for(var i = 0; i < this.length; i++) {
  31564. var id = this[i][0];
  31565. if(typeof id === "number")
  31566. alreadyImportedModules[id] = true;
  31567. }
  31568. for(i = 0; i < modules.length; i++) {
  31569. var item = modules[i];
  31570. // skip already imported module
  31571. // this implementation is not 100% perfect for weird media query combinations
  31572. // when a module is imported multiple times with different media queries.
  31573. // I hope this will never occur (Hey this way we have smaller bundles)
  31574. if(typeof item[0] !== "number" || !alreadyImportedModules[item[0]]) {
  31575. if(mediaQuery && !item[2]) {
  31576. item[2] = mediaQuery;
  31577. } else if(mediaQuery) {
  31578. item[2] = "(" + item[2] + ") and (" + mediaQuery + ")";
  31579. }
  31580. list.push(item);
  31581. }
  31582. }
  31583. };
  31584. return list;
  31585. };
  31586. function cssWithMappingToString(item, useSourceMap) {
  31587. var content = item[1] || '';
  31588. var cssMapping = item[3];
  31589. if (!cssMapping) {
  31590. return content;
  31591. }
  31592. if (useSourceMap && typeof btoa === 'function') {
  31593. var sourceMapping = toComment(cssMapping);
  31594. var sourceURLs = cssMapping.sources.map(function (source) {
  31595. return '/*# sourceURL=' + cssMapping.sourceRoot + source + ' */'
  31596. });
  31597. return [content].concat(sourceURLs).concat([sourceMapping]).join('\n');
  31598. }
  31599. return [content].join('\n');
  31600. }
  31601. // Adapted from convert-source-map (MIT)
  31602. function toComment(sourceMap) {
  31603. // eslint-disable-next-line no-undef
  31604. var base64 = btoa(unescape(encodeURIComponent(JSON.stringify(sourceMap))));
  31605. var data = 'sourceMappingURL=data:application/json;charset=utf-8;base64,' + base64;
  31606. return '/*# ' + data + ' */';
  31607. }
  31608. /***/ }),
  31609. /* 15 */
  31610. /***/ (function(module, exports) {
  31611. module.exports = function escape(url) {
  31612. if (typeof url !== 'string') {
  31613. return url
  31614. }
  31615. // If url is already wrapped in quotes, remove them
  31616. if (/^['"].*['"]$/.test(url)) {
  31617. url = url.slice(1, -1);
  31618. }
  31619. // Should url be wrapped?
  31620. // See https://drafts.csswg.org/css-values-3/#urls
  31621. if (/["'() \t\n]/.test(url)) {
  31622. return '"' + url.replace(/"/g, '\\"').replace(/\n/g, '\\n') + '"'
  31623. }
  31624. return url
  31625. };
  31626. /***/ }),
  31627. /* 16 */
  31628. /***/ (function(module, exports, __webpack_require__) {
  31629. var escape = __webpack_require__(15);
  31630. exports = module.exports = __webpack_require__(14)(false);
  31631. // imports
  31632. // module
  31633. exports.push([module.i, "@font-face {\n font-family: 'bf-icons';\n src: url(" + escape(__webpack_require__(13)) + ") format(\"truetype\");\n font-weight: normal;\n font-style: normal; }\n\n.braft-finder [class^=\"braft-icon-\"], .braft-finder [class*=\" braft-icon-\"] {\n /* use !important to prevent issues with browser extensions that change fonts */\n font-family: 'bf-icons' !important;\n font-style: normal;\n font-weight: normal;\n font-variant: normal;\n text-transform: none;\n /* Better Font Rendering =========== */\n -webkit-font-smoothing: antialiased;\n -moz-osx-font-smoothing: grayscale; }\n\n.braft-finder .braft-icon-code:before {\n content: \"\\E903\"; }\n\n.braft-finder .braft-icon-pause:before {\n content: \"\\E034\"; }\n\n.braft-finder .braft-icon-play_arrow:before {\n content: \"\\E037\"; }\n\n.braft-finder .braft-icon-bin:before {\n content: \"\\E9AC\"; }\n\n.braft-finder .braft-icon-replay:before {\n content: \"\\E042\"; }\n\n.braft-finder .braft-icon-close:before {\n content: \"\\E913\"; }\n\n.braft-finder .braft-icon-music:before {\n content: \"\\E90E\"; }\n\n.braft-finder .braft-icon-camera:before {\n content: \"\\E911\"; }\n\n.braft-finder .braft-icon-file-text:before {\n content: \"\\E926\"; }\n\n.braft-finder .braft-icon-film:before {\n content: \"\\E91C\"; }\n\n.braft-finder .braft-icon-paste:before {\n content: \"\\E92D\"; }\n\n.braft-finder .braft-icon-spinner:before {\n content: \"\\E980\"; }\n\n.braft-finder .braft-icon-media:before {\n content: \"\\E90F\"; }\n\n.braft-finder .braft-icon-add:before {\n content: \"\\E918\"; }\n\n.braft-finder .braft-icon-done:before {\n content: \"\\E912\"; }\n\n.braft-finder .braft-icon-drop-down:before {\n content: \"\\E906\"; }\n\n.braft-finder .braft-icon-drop-up:before {\n content: \"\\E909\"; }\n\n.braft-finder .braft-icon-help:before {\n content: \"\\E902\"; }\n\n.braft-finder .braft-icon-info:before {\n content: \"\\E901\"; }\n\n.braft-finder .braft-icon-menu:before {\n content: \"\\E908\"; }\n\n.pull-left {\n float: left; }\n\n.pull-right {\n float: right; }\n\n.braft-finder .bf-uploader {\n position: relative;\n height: 370px;\n margin: 0; }\n .braft-finder .bf-uploader.draging .bf-list-wrap,\n .braft-finder .bf-uploader.draging .bf-add-external {\n pointer-events: none; }\n .braft-finder .bf-uploader input::-webkit-input-placeholder {\n color: #ccc; }\n .braft-finder .bf-uploader input::-moz-placeholder {\n color: #ccc; }\n .braft-finder .bf-uploader input::-ms-input-placeholder {\n color: #ccc; }\n\n.braft-finder .bf-list-wrap {\n position: relative;\n height: 370px; }\n\n.braft-finder .bf-list-tools {\n z-index: 1;\n position: absolute;\n top: 0;\n right: 0;\n left: 0;\n height: 20px;\n padding: 0 15px;\n background-color: #fff; }\n .braft-finder .bf-list-tools span {\n height: 26px;\n font-size: 12px;\n line-height: 20px;\n cursor: pointer;\n user-select: none; }\n .braft-finder .bf-list-tools span[disabled] {\n opacity: .3;\n pointer-events: none; }\n .braft-finder .bf-list-tools .bf-select-all,\n .braft-finder .bf-list-tools .bf-deselect-all {\n float: left;\n margin-right: 5px;\n color: #bbb; }\n .braft-finder .bf-list-tools .bf-select-all:hover,\n .braft-finder .bf-list-tools .bf-deselect-all:hover {\n color: #3498db; }\n .braft-finder .bf-list-tools .bf-remove-selected {\n float: right;\n color: #e74c3c; }\n .braft-finder .bf-list-tools .bf-remove-selected:hover {\n color: #c92e1e; }\n\n.braft-finder .bf-list {\n position: absolute;\n z-index: 1;\n top: 30px;\n right: 0;\n left: 0;\n bottom: 0;\n margin: 0;\n padding: 0 10px;\n list-style: none;\n overflow: auto; }\n .braft-finder .bf-list::-webkit-scrollbar {\n width: 5px;\n height: 5px;\n background-color: #fff; }\n .braft-finder .bf-list::-webkit-scrollbar-track {\n background-color: #fff; }\n .braft-finder .bf-list::-webkit-scrollbar-thumb {\n background-color: rgba(0, 0, 0, 0.1); }\n\n.braft-finder .bf-item,\n.braft-finder .bf-add-item {\n position: relative;\n display: block;\n float: left;\n width: 113px;\n height: 113px;\n margin: 5px;\n overflow: hidden;\n border-radius: 3px; }\n\n.braft-finder .bf-item.uploading {\n pointer-events: none; }\n\n.braft-finder .bf-item.error::before {\n display: block;\n content: \"\\E901\"; }\n\n.braft-finder .bf-item.error::after {\n position: absolute;\n z-index: 1;\n top: 0;\n right: 0;\n bottom: 0;\n left: 0;\n background-color: rgba(231, 76, 60, 0.8);\n content: ''; }\n\n.braft-finder .bf-item.error:hover::after {\n background-color: rgba(231, 76, 60, 0.9); }\n\n.braft-finder .bf-item.error .bf-item-uploading {\n display: none; }\n\n.braft-finder .bf-add-item {\n background-color: #ecedef;\n color: #999; }\n .braft-finder .bf-add-item:hover {\n background-color: #e1e2e3; }\n .braft-finder .bf-add-item i {\n display: block;\n width: 113px;\n height: 113px;\n font-size: 48px;\n line-height: 113px;\n text-align: center; }\n .braft-finder .bf-add-item input {\n position: absolute;\n top: 0;\n left: 0;\n width: 100%;\n height: 100%;\n opacity: 0;\n cursor: pointer; }\n\n.braft-finder .bf-item::before {\n display: none;\n position: absolute;\n z-index: 2;\n top: 0;\n left: 0;\n width: 113px;\n height: 113px;\n color: #fff;\n font-size: 48px;\n font-family: 'bf-icons';\n line-height: 113px;\n text-align: center; }\n\n.braft-finder .bf-item::after {\n position: absolute;\n z-index: 1;\n top: 0;\n right: 0;\n bottom: 0;\n left: 0;\n background-color: rgba(52, 152, 219, 0);\n content: ''; }\n\n.braft-finder .bf-item:hover::after {\n background-color: rgba(52, 152, 219, 0.3); }\n\n.braft-finder .bf-item:hover .bf-item-remove {\n display: block; }\n\n.braft-finder .bf-item.active::before {\n display: block;\n content: \"\\E912\"; }\n\n.braft-finder .bf-item.active::after {\n background-color: rgba(52, 152, 219, 0.6); }\n\n.braft-finder .bf-item.active:hover::after {\n background-color: rgba(52, 152, 219, 0.8); }\n\n.braft-finder .bf-item.active:hover .bf-item-remove {\n display: none; }\n\n.braft-finder .bf-item-uploading {\n box-sizing: border-box;\n position: absolute;\n z-index: 3;\n top: 52px;\n left: 10px;\n width: 93px;\n height: 10px;\n overflow: hidden;\n background-color: rgba(255, 255, 255, 0.3);\n border-radius: 5px;\n box-shadow: 0 0 0 100px rgba(0, 0, 0, 0.5); }\n\n.braft-finder .bf-item-uploading-bar {\n height: 10px;\n background-color: #3498db;\n border-radius: 0; }\n\n.braft-finder .bf-item-remove {\n display: none;\n position: absolute;\n z-index: 2;\n top: 0;\n right: 0;\n width: 28px;\n height: 28px;\n color: #fff;\n font-size: 18px;\n line-height: 28px;\n text-align: center;\n cursor: pointer; }\n .braft-finder .bf-item-remove:hover {\n color: #e74c3c; }\n\n.braft-finder .bf-item-title {\n display: none;\n box-sizing: border-box;\n position: absolute;\n z-index: 2;\n bottom: 0;\n left: 0;\n width: 100%;\n height: 40px;\n padding: 0 5px;\n overflow: hidden;\n background-image: linear-gradient(rgba(0, 0, 0, 0), black);\n color: #fff;\n font-size: 12px;\n line-height: 55px;\n text-align: center;\n text-overflow: ellipsis;\n white-space: nowrap; }\n\n.braft-finder .bf-image {\n width: 100%;\n height: 100%;\n background-color: #eee;\n user-select: none; }\n .braft-finder .bf-image img {\n display: block;\n width: 100%;\n height: 100%;\n object-fit: cover; }\n\n.braft-finder .bf-video {\n background-color: #8e44ad; }\n\n.braft-finder .bf-audio {\n background-color: #f39c12; }\n\n.braft-finder .bf-embed {\n background-color: #f1c40f; }\n\n.braft-finder .bf-icon {\n display: block;\n width: 113px;\n height: 113px;\n overflow: hidden;\n color: #fff;\n text-align: center;\n text-decoration: none; }\n .braft-finder .bf-icon i, .braft-finder .bf-icon span {\n display: block; }\n .braft-finder .bf-icon i {\n margin-top: 35px;\n font-size: 24px; }\n .braft-finder .bf-icon span {\n width: 103px;\n margin: 10px auto;\n overflow: hidden;\n font-size: 12px;\n text-overflow: ellipsis;\n white-space: nowrap; }\n\n.braft-finder .bf-drag-uploader {\n box-sizing: border-box;\n position: absolute;\n z-index: 2;\n top: 0;\n right: 15px;\n left: 15px;\n height: 100%;\n background-color: #fff;\n border: dashed 1px #bbb;\n text-align: center;\n opacity: 0;\n pointer-events: none; }\n .braft-finder .bf-drag-uploader:hover, .braft-finder .bf-drag-uploader.draging {\n background-color: #f1f2f3; }\n .braft-finder .bf-drag-uploader.active {\n opacity: 1;\n pointer-events: auto; }\n\n.braft-finder .bf-uploader-buttons {\n height: 370px;\n margin: auto;\n text-align: center; }\n\n.braft-finder .bf-drag-tip {\n display: inline-block;\n margin-top: 150px;\n color: #ccc;\n text-align: center;\n font-size: 28px;\n font-weight: normal;\n line-height: 40px; }\n .braft-finder .bf-drag-tip input {\n position: absolute;\n top: 0;\n right: 0;\n bottom: 0;\n left: 0;\n width: 100%;\n height: 100%;\n opacity: 0;\n color: #fff;\n text-indent: -100px;\n cursor: pointer; }\n\n.braft-finder .bf-manager-footer {\n height: 36px;\n margin: 10px 0;\n padding: 0 15px; }\n .braft-finder .bf-manager-footer .button {\n float: right;\n height: 36px;\n margin-left: 5px;\n padding: 0 35px;\n font-size: 12px;\n font-weight: 700;\n border: none;\n border-radius: 3px;\n cursor: pointer; }\n .braft-finder .bf-manager-footer .button-insert {\n color: #fff;\n background-color: #3498db; }\n .braft-finder .bf-manager-footer .button-insert:hover {\n background-color: #2084c7; }\n .braft-finder .bf-manager-footer .button-insert[disabled] {\n opacity: .3;\n pointer-events: none;\n filter: grayscale(0.4); }\n .braft-finder .bf-manager-footer .button-cancel {\n color: #999;\n background-color: #e8e8e9; }\n .braft-finder .bf-manager-footer .button-cancel:hover {\n background-color: #d8d8d9; }\n\n.braft-finder .bf-toggle-external-form {\n color: #666;\n font-size: 12px;\n line-height: 36px; }\n .braft-finder .bf-toggle-external-form span {\n color: #bbb;\n line-height: 16px;\n cursor: pointer;\n user-select: none; }\n .braft-finder .bf-toggle-external-form span:hover {\n color: #3498db; }\n .braft-finder .bf-toggle-external-form span i {\n position: relative;\n top: 2px;\n font-size: 16px; }\n\n.braft-finder .bf-add-external {\n position: absolute;\n z-index: 3;\n top: 0;\n right: 0;\n bottom: 0;\n left: 0;\n background-color: #fff; }\n .braft-finder .bf-add-external input {\n border: solid 1px rgba(0, 0, 0, 0.3);\n border: solid 0.5px rgba(0, 0, 0, 0.3);\n box-shadow: none; }\n .braft-finder .bf-add-external input:focus {\n border-color: #3498db;\n box-shadow: none; }\n\n.braft-finder .bf-external-form {\n width: 500px;\n max-width: 90%;\n margin: 91px auto 0 auto; }\n\n.braft-finder .bf-external-input {\n position: relative;\n width: 100%;\n height: 40px;\n margin-bottom: 10px; }\n .braft-finder .bf-external-input div {\n position: absolute;\n top: 0;\n right: 85px;\n left: 0;\n height: 40px; }\n .braft-finder .bf-external-input input,\n .braft-finder .bf-external-input textarea {\n display: block;\n box-sizing: border-box;\n width: 100%;\n height: 40px;\n padding: 0 10px;\n border: none;\n border-radius: 3px;\n outline: none;\n box-shadow: inset 0 0 0 1px rgba(0, 0, 0, 0.3);\n color: #999;\n font-size: 18px; }\n .braft-finder .bf-external-input input:focus,\n .braft-finder .bf-external-input textarea:focus {\n box-shadow: inset 0 0 0 1px #3498db; }\n .braft-finder .bf-external-input textarea {\n height: 100px;\n font-size: 14px; }\n .braft-finder .bf-external-input button {\n position: absolute;\n top: 0;\n right: 0;\n width: 80px;\n height: 40px;\n background-color: #3498db;\n border: none;\n border-radius: 3px;\n color: #fff;\n font-size: 14px;\n font-weight: bold;\n cursor: pointer; }\n .braft-finder .bf-external-input button:disabled {\n opacity: .3;\n pointer-events: none;\n filter: grayscale(0.4); }\n .braft-finder .bf-external-input button:hover {\n background-color: #2084c7; }\n\n.braft-finder .bf-switch-external-type {\n overflow: hidden;\n text-align: center; }\n .braft-finder .bf-switch-external-type button {\n width: auto;\n height: 30px;\n margin: 10px 5px;\n padding: 0 10px;\n background-color: #e8e9ea;\n border: none;\n border-radius: 3px;\n color: #999;\n font-size: 12px;\n cursor: pointer; }\n .braft-finder .bf-switch-external-type button:hover {\n background-color: #d8d9da; }\n .braft-finder .bf-switch-external-type button:only-child {\n display: none; }\n .braft-finder .bf-switch-external-type[data-type=\"IMAGE\"] [data-type=\"IMAGE\"],\n .braft-finder .bf-switch-external-type[data-type=\"VIDEO\"] [data-type=\"VIDEO\"],\n .braft-finder .bf-switch-external-type[data-type=\"AUDIO\"] [data-type=\"AUDIO\"],\n .braft-finder .bf-switch-external-type[data-type=\"EMBED\"] [data-type=\"EMBED\"],\n .braft-finder .bf-switch-external-type[data-type=\"FILE\"] [data-type=\"FILE\"] {\n background-color: #3498db;\n color: #fff; }\n\n.braft-finder .bf-external-tip {\n display: block;\n margin-top: 15px;\n color: #ccc;\n font-size: 12px;\n text-align: center; }\n", ""]);
  31634. // exports
  31635. /***/ }),
  31636. /* 17 */
  31637. /***/ (function(module, exports, __webpack_require__) {
  31638. var content = __webpack_require__(16);
  31639. if(typeof content === 'string') content = [[module.i, content, '']];
  31640. var transform;
  31641. var options = {"hmr":true};
  31642. options.transform = transform;
  31643. options.insertInto = undefined;
  31644. var update = __webpack_require__(12)(content, options);
  31645. if(content.locals) module.exports = content.locals;
  31646. /***/ }),
  31647. /* 18 */
  31648. /***/ (function(module, exports, __webpack_require__) {
  31649. Object.defineProperty(exports, "__esModule", {
  31650. value: true
  31651. });
  31652. var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };
  31653. var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
  31654. __webpack_require__(17);
  31655. var _react = __webpack_require__(2);
  31656. var _react2 = _interopRequireDefault(_react);
  31657. var _base = __webpack_require__(1);
  31658. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  31659. function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  31660. function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }
  31661. function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
  31662. var defaultAccepts = {
  31663. image: 'image/png,image/jpeg,image/gif,image/webp,image/apng,image/svg',
  31664. video: 'video/mp4',
  31665. audio: 'audio/mp3'
  31666. };
  31667. var BraftFinderView = function (_React$Component) {
  31668. _inherits(BraftFinderView, _React$Component);
  31669. function BraftFinderView(props) {
  31670. _classCallCheck(this, BraftFinderView);
  31671. var _this = _possibleConstructorReturn(this, (BraftFinderView.__proto__ || Object.getPrototypeOf(BraftFinderView)).call(this, props));
  31672. _this.toggleSelectItem = function (event) {
  31673. var itemId = event.currentTarget.dataset.id;
  31674. var item = _this.controller.getMediaItem(itemId);
  31675. if (!item) {
  31676. return false;
  31677. }
  31678. if (item.selected) {
  31679. if (!_this.props.onBeforeDeselect || _this.props.onBeforeDeselect([item], _this.controller.getItems()) !== false) {
  31680. _this.controller.deselectMediaItem(itemId);
  31681. _this.props.onDeselect && _this.props.onDeselect([item], _this.controller.getItems());
  31682. }
  31683. } else {
  31684. if (!_this.props.onBeforeSelect || _this.props.onBeforeSelect([item], _this.controller.getItems()) !== false) {
  31685. _this.controller.selectMediaItem(itemId);
  31686. _this.props.onSelect && _this.props.onSelect([item], _this.controller.getItems());
  31687. }
  31688. }
  31689. };
  31690. _this.removeItem = function (event) {
  31691. var itemId = event.currentTarget.dataset.id;
  31692. var item = _this.controller.getMediaItem(itemId);
  31693. if (!item) {
  31694. return false;
  31695. }
  31696. if (!_this.props.onBeforeRemove || _this.props.onBeforeRemove([item], _this.controller.getItems()) !== false) {
  31697. _this.controller.removeMediaItem(itemId);
  31698. _this.props.onRemove && _this.props.onRemove([item], _this.controller.getItems());
  31699. }
  31700. event.stopPropagation();
  31701. };
  31702. _this.selectAllItems = function () {
  31703. var allItems = _this.controller.getItems();
  31704. if (!_this.props.onBeforeSelect || _this.props.onBeforeSelect(allItems, allItems) !== false) {
  31705. _this.controller.selectAllItems();
  31706. _this.props.onSelect && _this.props.onSelect(allItems, allItems);
  31707. }
  31708. };
  31709. _this.deselectAllItems = function () {
  31710. var allItems = _this.controller.getItems();
  31711. if (!_this.props.onBeforeDeselect || _this.props.onBeforeDeselect(allItems, allItems) !== false) {
  31712. _this.controller.deselectAllItems();
  31713. _this.props.onDeselect && _this.props.onDeselect(allItems, allItems);
  31714. }
  31715. };
  31716. _this.removeSelectedItems = function () {
  31717. var selectedItems = _this.controller.getSelectedItems();
  31718. if (!_this.props.onBeforeRemove || _this.props.onBeforeRemove(selectedItems, _this.controller.getItems()) !== false) {
  31719. _this.controller.removeSelectedItems();
  31720. _this.props.onRemove && _this.props.onRemove(selectedItems, _this.controller.getItems());
  31721. }
  31722. };
  31723. _this.handleDragLeave = function (event) {
  31724. event.preventDefault();
  31725. _this.dragCounter--;
  31726. _this.dragCounter === 0 && _this.setState({
  31727. draging: false
  31728. });
  31729. };
  31730. _this.handleDragDrop = function (event) {
  31731. event.preventDefault();
  31732. _this.dragCounter = 0;
  31733. _this.setState({ draging: false });
  31734. _this.reslovePickedFiles(event);
  31735. };
  31736. _this.handleDragEnter = function (event) {
  31737. event.preventDefault();
  31738. _this.dragCounter++;
  31739. _this.setState({ draging: true });
  31740. };
  31741. _this.reslovePickedFiles = function (event) {
  31742. event.persist();
  31743. var _ref = event.type === 'drop' ? event.dataTransfer : event.target,
  31744. files = _ref.files;
  31745. if (_this.props.onFileSelect) {
  31746. var result = _this.props.onFileSelect(files);
  31747. if (result === false) {
  31748. return false;
  31749. } else if (result instanceof FileList || result instanceof Array) {
  31750. files = result;
  31751. }
  31752. }
  31753. var accepts = _extends({}, defaultAccepts, _this.props.accepts);
  31754. _this.controller.resolveFiles({
  31755. files: files,
  31756. onItemReady: function onItemReady(_ref2) {
  31757. var id = _ref2.id;
  31758. return _this.controller.selectMediaItem(id);
  31759. },
  31760. onAllReady: function onAllReady() {
  31761. return event.target.value = null;
  31762. }
  31763. }, 0, accepts);
  31764. };
  31765. _this.inputExternal = function (event) {
  31766. _this.setState({
  31767. external: _extends({}, _this.state.external, {
  31768. url: event.target.value
  31769. })
  31770. });
  31771. };
  31772. _this.switchExternalType = function (event) {
  31773. _this.setState({
  31774. external: _extends({}, _this.state.external, { type: event.target.dataset.type })
  31775. });
  31776. };
  31777. _this.confirmAddExternal = function (event) {
  31778. if (event.target.nodeName.toLowerCase() === 'button' || event.keyCode === 13) {
  31779. var _this$state$external = _this.state.external,
  31780. url = _this$state$external.url,
  31781. type = _this$state$external.type;
  31782. url = url.split('|');
  31783. var name = url.length > 1 ? url[0] : _this.props.language.unnamedItem;
  31784. url = url.length > 1 ? url[1] : url[0];
  31785. var thumbnail = type === 'IMAGE' ? url : null;
  31786. _this.controller.addItems([{
  31787. thumbnail: thumbnail, url: url, name: name, type: type,
  31788. id: new Date().getTime() + '_' + (0, _base.UniqueIndex)(),
  31789. uploading: false,
  31790. uploadProgress: 1,
  31791. selected: true
  31792. }]);
  31793. _this.setState({
  31794. showExternalForm: false,
  31795. external: {
  31796. url: '',
  31797. type: 'IMAGE'
  31798. }
  31799. });
  31800. }
  31801. };
  31802. _this.toggleExternalForm = function () {
  31803. _this.setState({
  31804. showExternalForm: !_this.state.showExternalForm
  31805. });
  31806. };
  31807. _this.cancelInsert = function () {
  31808. _this.props.onCancel && _this.props.onCancel();
  31809. };
  31810. _this.confirmInsert = function () {
  31811. var selectedItems = _this.controller.getSelectedItems();
  31812. if (_this.props.onBeforeInsert) {
  31813. var filteredItems = _this.props.onBeforeInsert(selectedItems);
  31814. if (filteredItems && filteredItems instanceof Array) {
  31815. _this.controller.deselectAllItems();
  31816. _this.props.onInsert && _this.props.onInsert(filteredItems);
  31817. } else if (filteredItems !== false) {
  31818. _this.controller.deselectAllItems();
  31819. _this.props.onInsert && _this.props.onInsert(selectedItems);
  31820. }
  31821. } else {
  31822. _this.controller.deselectAllItems();
  31823. _this.props.onInsert && _this.props.onInsert(selectedItems);
  31824. }
  31825. };
  31826. _this.dragCounter = 0;
  31827. _this.controller = _this.props.controller;
  31828. var initialItems = _this.controller.getItems();
  31829. _this.state = {
  31830. draging: false,
  31831. error: false,
  31832. confirmable: initialItems.find(function (_ref3) {
  31833. var selected = _ref3.selected;
  31834. return selected;
  31835. }),
  31836. external: {
  31837. url: '',
  31838. type: 'IMAGE'
  31839. },
  31840. fileAccept: '',
  31841. showExternalForm: false,
  31842. allowExternal: false,
  31843. items: initialItems
  31844. };
  31845. _this.changeListenerId = _this.controller.onChange(function (items) {
  31846. _this.setState({ items: items, confirmable: items.find(function (_ref4) {
  31847. var selected = _ref4.selected;
  31848. return selected;
  31849. }) });
  31850. _this.props.onChange && _this.props.onChange(items);
  31851. });
  31852. return _this;
  31853. }
  31854. _createClass(BraftFinderView, [{
  31855. key: 'mapPropsToState',
  31856. value: function mapPropsToState(props) {
  31857. var accepts = props.accepts,
  31858. externals = props.externals;
  31859. accepts = _extends({}, defaultAccepts, accepts);
  31860. var fileAccept = !accepts ? [defaultAccepts.image, defaultAccepts.video, defaultAccepts.audio].join(',') : [accepts.image, accepts.video, accepts.audio].filter(function (item) {
  31861. return item;
  31862. }).join(',');
  31863. var external = {
  31864. url: '',
  31865. type: externals.image ? 'IMAGE' : externals.audio ? 'AUDIO' : externals.video ? 'VIDEO' : externals.embed ? 'EMBED' : ''
  31866. };
  31867. return {
  31868. fileAccept: fileAccept,
  31869. external: external,
  31870. allowExternal: externals && (externals.image || externals.audio || externals.video || externals.embed)
  31871. };
  31872. }
  31873. }, {
  31874. key: 'componentDidMount',
  31875. value: function componentDidMount() {
  31876. this.setState(this.mapPropsToState(this.props));
  31877. }
  31878. }, {
  31879. key: 'componentWillReceiveProps',
  31880. value: function componentWillReceiveProps(nextProps) {
  31881. this.setState(this.mapPropsToState(nextProps));
  31882. }
  31883. }, {
  31884. key: 'componentWillUnmount',
  31885. value: function componentWillUnmount() {
  31886. this.controller.offChange(this.changeListenerId);
  31887. }
  31888. }, {
  31889. key: 'render',
  31890. value: function render() {
  31891. var _props = this.props,
  31892. language = _props.language,
  31893. externals = _props.externals;
  31894. var _state = this.state,
  31895. items = _state.items,
  31896. draging = _state.draging,
  31897. confirmable = _state.confirmable,
  31898. fileAccept = _state.fileAccept,
  31899. external = _state.external,
  31900. showExternalForm = _state.showExternalForm,
  31901. allowExternal = _state.allowExternal;
  31902. return _react2.default.createElement(
  31903. 'div',
  31904. { className: 'braft-finder' },
  31905. _react2.default.createElement(
  31906. 'div',
  31907. {
  31908. onDragEnter: this.handleDragEnter,
  31909. onDragOver: this.handleDragEnter,
  31910. onDragLeave: this.handleDragLeave,
  31911. onDrop: this.handleDragDrop,
  31912. className: 'bf-uploader'
  31913. },
  31914. _react2.default.createElement(
  31915. 'div',
  31916. { className: "bf-drag-uploader " + (draging || !items.length ? 'active ' : ' ') + (draging ? 'draging' : '') },
  31917. _react2.default.createElement(
  31918. 'span',
  31919. { className: 'bf-drag-tip' },
  31920. _react2.default.createElement('input', { accept: fileAccept, onChange: this.reslovePickedFiles, multiple: true, type: 'file' }),
  31921. draging ? language.dropTip : language.dragTip
  31922. )
  31923. ),
  31924. items.length ? _react2.default.createElement(
  31925. 'div',
  31926. { className: 'bf-list-wrap' },
  31927. _react2.default.createElement(
  31928. 'div',
  31929. { className: 'bf-list-tools' },
  31930. _react2.default.createElement(
  31931. 'span',
  31932. { onClick: this.selectAllItems, className: 'bf-select-all' },
  31933. _react2.default.createElement('i', { className: 'braft-icon-done' }),
  31934. ' ',
  31935. language.selectAll
  31936. ),
  31937. _react2.default.createElement(
  31938. 'span',
  31939. { onClick: this.deselectAllItems, disabled: !confirmable, className: 'bf-deselect-all' },
  31940. _react2.default.createElement('i', { className: 'braft-icon-close' }),
  31941. ' ',
  31942. language.deselect
  31943. ),
  31944. _react2.default.createElement(
  31945. 'span',
  31946. { onClick: this.removeSelectedItems, disabled: !confirmable, className: 'bf-remove-selected' },
  31947. _react2.default.createElement('i', { className: 'braft-icon-bin' }),
  31948. ' ',
  31949. language.removeSelected
  31950. )
  31951. ),
  31952. this.buildItemList()
  31953. ) : null,
  31954. showExternalForm && allowExternal ? _react2.default.createElement(
  31955. 'div',
  31956. { className: 'bf-add-external' },
  31957. _react2.default.createElement(
  31958. 'div',
  31959. { className: 'bf-external-form' },
  31960. _react2.default.createElement(
  31961. 'div',
  31962. { className: 'bf-external-input' },
  31963. _react2.default.createElement(
  31964. 'div',
  31965. null,
  31966. _react2.default.createElement('input', { onKeyDown: this.confirmAddExternal, value: external.url, onChange: this.inputExternal, placeholder: language.externalInputPlaceHolder })
  31967. ),
  31968. _react2.default.createElement(
  31969. 'button',
  31970. { type: 'button', onClick: this.confirmAddExternal, disabled: !external.url.trim().length },
  31971. language.confirm
  31972. )
  31973. ),
  31974. _react2.default.createElement(
  31975. 'div',
  31976. { 'data-type': external.type, className: 'bf-switch-external-type' },
  31977. externals.image ? _react2.default.createElement(
  31978. 'button',
  31979. { type: 'button', onClick: this.switchExternalType, 'data-type': 'IMAGE' },
  31980. language.image
  31981. ) : null,
  31982. externals.audio ? _react2.default.createElement(
  31983. 'button',
  31984. { type: 'button', onClick: this.switchExternalType, 'data-type': 'AUDIO' },
  31985. language.audio
  31986. ) : null,
  31987. externals.video ? _react2.default.createElement(
  31988. 'button',
  31989. { type: 'button', onClick: this.switchExternalType, 'data-type': 'VIDEO' },
  31990. language.video
  31991. ) : null,
  31992. externals.embed ? _react2.default.createElement(
  31993. 'button',
  31994. { type: 'button', onClick: this.switchExternalType, 'data-type': 'EMBED' },
  31995. language.embed
  31996. ) : null
  31997. ),
  31998. _react2.default.createElement(
  31999. 'span',
  32000. { className: 'bf-external-tip' },
  32001. language.externalInputTip
  32002. )
  32003. )
  32004. ) : null
  32005. ),
  32006. _react2.default.createElement(
  32007. 'footer',
  32008. { className: 'bf-manager-footer' },
  32009. _react2.default.createElement(
  32010. 'div',
  32011. { className: 'pull-left' },
  32012. allowExternal ? _react2.default.createElement(
  32013. 'span',
  32014. {
  32015. onClick: this.toggleExternalForm,
  32016. className: 'bf-toggle-external-form'
  32017. },
  32018. showExternalForm ? _react2.default.createElement(
  32019. 'span',
  32020. { className: 'bf-bottom-text' },
  32021. _react2.default.createElement('i', { className: 'braft-icon-add' }),
  32022. ' ',
  32023. language.addLocalFile
  32024. ) : _react2.default.createElement(
  32025. 'span',
  32026. { className: 'bf-bottom-text' },
  32027. _react2.default.createElement('i', { className: 'braft-icon-add' }),
  32028. ' ',
  32029. language.addExternalSource
  32030. )
  32031. ) : null
  32032. ),
  32033. _react2.default.createElement(
  32034. 'div',
  32035. { className: 'pull-right' },
  32036. _react2.default.createElement(
  32037. 'button',
  32038. { onClick: this.confirmInsert, className: 'button button-insert', disabled: !confirmable },
  32039. language.insert
  32040. ),
  32041. _react2.default.createElement(
  32042. 'button',
  32043. { onClick: this.cancelInsert, className: 'button button-cancel' },
  32044. language.cancel
  32045. )
  32046. )
  32047. )
  32048. );
  32049. }
  32050. }, {
  32051. key: 'buildItemList',
  32052. value: function buildItemList() {
  32053. var _this2 = this;
  32054. return _react2.default.createElement(
  32055. 'ul',
  32056. { className: 'bf-list' },
  32057. _react2.default.createElement(
  32058. 'li',
  32059. { className: 'bf-add-item' },
  32060. _react2.default.createElement('i', { className: 'braft-icon-add' }),
  32061. _react2.default.createElement('input', { accept: this.state.fileAccept, onChange: this.reslovePickedFiles, multiple: true, type: 'file' })
  32062. ),
  32063. this.state.items.map(function (item, index) {
  32064. var previewerComponents = null;
  32065. var progressMarker = item.uploading && !_this2.props.hideProgress ? _react2.default.createElement(
  32066. 'div',
  32067. { className: 'bf-item-uploading' },
  32068. _react2.default.createElement('div', { className: 'bf-item-uploading-bar', style: { width: item.uploadProgress / 1 + '%' } })
  32069. ) : '';
  32070. switch (item.type) {
  32071. case 'IMAGE':
  32072. previewerComponents = _react2.default.createElement(
  32073. 'div',
  32074. { className: 'bf-image' },
  32075. progressMarker,
  32076. _react2.default.createElement('img', { src: item.thumbnail || item.url })
  32077. );
  32078. break;
  32079. case 'VIDEO':
  32080. previewerComponents = _react2.default.createElement(
  32081. 'div',
  32082. { className: 'bf-icon bf-video', title: item.url },
  32083. progressMarker,
  32084. _react2.default.createElement('i', { className: 'braft-icon-film' }),
  32085. _react2.default.createElement(
  32086. 'span',
  32087. null,
  32088. item.name || item.url
  32089. )
  32090. );
  32091. break;
  32092. case 'AUDIO':
  32093. previewerComponents = _react2.default.createElement(
  32094. 'div',
  32095. { className: 'bf-icon bf-audio', title: item.url },
  32096. progressMarker,
  32097. _react2.default.createElement('i', { className: 'braft-icon-music' }),
  32098. _react2.default.createElement(
  32099. 'span',
  32100. null,
  32101. item.name || item.url
  32102. )
  32103. );
  32104. break;
  32105. case 'EMBED':
  32106. previewerComponents = _react2.default.createElement(
  32107. 'div',
  32108. { className: 'bf-icon bf-embed', title: item.url },
  32109. progressMarker,
  32110. _react2.default.createElement('i', { className: 'braft-icon-code' }),
  32111. _react2.default.createElement(
  32112. 'span',
  32113. null,
  32114. item.name || _this2.props.language.embed
  32115. )
  32116. );
  32117. break;
  32118. default:
  32119. previewerComponents = _react2.default.createElement(
  32120. 'a',
  32121. { className: 'bf-icon bf-file', title: item.url, href: item.url },
  32122. progressMarker,
  32123. _react2.default.createElement('i', { className: 'braft-icon-file-text' }),
  32124. _react2.default.createElement(
  32125. 'span',
  32126. null,
  32127. item.name || item.url
  32128. )
  32129. );
  32130. break;
  32131. }
  32132. var className = ['bf-item'];
  32133. item.selected && className.push('active');
  32134. item.uploading && className.push('uploading');
  32135. item.error && className.push('error');
  32136. return _react2.default.createElement(
  32137. 'li',
  32138. {
  32139. key: index,
  32140. title: item.name,
  32141. 'data-id': item.id,
  32142. className: className.join(' '),
  32143. onClick: _this2.toggleSelectItem
  32144. },
  32145. previewerComponents,
  32146. _react2.default.createElement('span', { 'data-id': item.id, onClick: _this2.removeItem, className: 'bf-item-remove braft-icon-close' }),
  32147. _react2.default.createElement(
  32148. 'span',
  32149. { className: 'bf-item-title' },
  32150. item.name
  32151. )
  32152. );
  32153. })
  32154. );
  32155. }
  32156. }]);
  32157. return BraftFinderView;
  32158. }(_react2.default.Component);
  32159. BraftFinderView.defaultProps = {
  32160. accepts: defaultAccepts,
  32161. externals: {
  32162. image: true,
  32163. video: true,
  32164. audio: true,
  32165. embed: true
  32166. }
  32167. };
  32168. exports.default = BraftFinderView;
  32169. /***/ }),
  32170. /* 19 */
  32171. /***/ (function(module, exports, __webpack_require__) {
  32172. Object.defineProperty(exports, "__esModule", {
  32173. value: true
  32174. });
  32175. var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };
  32176. var _base = __webpack_require__(1);
  32177. var _image = __webpack_require__(0);
  32178. function _toConsumableArray(arr) { if (Array.isArray(arr)) { for (var i = 0, arr2 = Array(arr.length); i < arr.length; i++) { arr2[i] = arr[i]; } return arr2; } else { return Array.from(arr); } }
  32179. function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  32180. var defaultValidator = function defaultValidator() {
  32181. return true;
  32182. };
  32183. var BraftFinderController = function BraftFinderController() {
  32184. var props = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
  32185. _classCallCheck(this, BraftFinderController);
  32186. _initialiseProps.call(this);
  32187. this.items = props.items || [];
  32188. this.uploadFn = props.uploader;
  32189. this.validateFn = props.validator || defaultValidator;
  32190. this.changeListeners = [];
  32191. }
  32192. // resolvePastedFiles ({ clipboardData }, callback) {
  32193. // if (clipboardData && clipboardData.items && clipboardData.items[0].type.indexOf('image') > -1) {
  32194. // this.uploadImage(clipboardData.items[0].getAsFile(), callback)
  32195. // }
  32196. // }
  32197. ;
  32198. var _initialiseProps = function _initialiseProps() {
  32199. var _this = this;
  32200. this.setProps = function () {
  32201. var props = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
  32202. _this.items = props.items || _this.items || [];
  32203. _this.uploadFn = props.uploader;
  32204. _this.validateFn = props.validator || defaultValidator;
  32205. };
  32206. this.getMediaItem = function (id) {
  32207. return _this.items.find(function (item) {
  32208. return item.id === id;
  32209. });
  32210. };
  32211. this.getSelectedItems = function () {
  32212. return _this.items.filter(function (item) {
  32213. return item.selected;
  32214. });
  32215. };
  32216. this.getItems = function () {
  32217. return _this.items;
  32218. };
  32219. this.setItems = function (items) {
  32220. _this.items = items.map(function (item) {
  32221. return _extends({}, item, { id: item.id.toString() });
  32222. }) || [];
  32223. _this.applyChange();
  32224. _this.uploadItems();
  32225. };
  32226. this.addMediaItem = function (item) {
  32227. _this.addItems([item]);
  32228. };
  32229. this.addItems = function (items) {
  32230. _this.items = [].concat(_toConsumableArray(_this.items), _toConsumableArray(items.map(function (item) {
  32231. return _extends({}, item, { id: item.id.toString() });
  32232. })));
  32233. _this.applyChange();
  32234. _this.uploadItems();
  32235. };
  32236. this.selectMediaItem = function (id) {
  32237. var item = _this.getMediaItem(id);
  32238. if (item && (item.uploading || item.error)) {
  32239. return false;
  32240. }
  32241. _this.setMediaItemState(id, {
  32242. selected: true
  32243. });
  32244. };
  32245. this.selectAllItems = function () {
  32246. _this.items = _this.items.filter(function (item) {
  32247. return !item.error && !item.uploading;
  32248. }).map(function (item) {
  32249. return _extends({}, item, { selected: true });
  32250. });
  32251. _this.applyChange();
  32252. };
  32253. this.deselectMediaItem = function (id) {
  32254. _this.setMediaItemState(id, {
  32255. selected: false
  32256. });
  32257. };
  32258. this.deselectAllItems = function () {
  32259. _this.items = _this.items.map(function (item) {
  32260. return _extends({}, item, { selected: false });
  32261. });
  32262. _this.applyChange();
  32263. };
  32264. this.removeMediaItem = function (id) {
  32265. _this.items = _this.items.filter(function (item) {
  32266. return item.id !== id;
  32267. });
  32268. _this.applyChange();
  32269. };
  32270. this.removeItems = function () {
  32271. var ids = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : [];
  32272. _this.items = _this.items.filter(function (item) {
  32273. return !ids.includes(item.id);
  32274. });
  32275. _this.applyChange();
  32276. };
  32277. this.removeSelectedItems = function () {
  32278. _this.items = _this.items.filter(function (item) {
  32279. return !item.selected;
  32280. });
  32281. _this.applyChange();
  32282. };
  32283. this.removeErrorItems = function () {
  32284. _this.items = _this.items.filter(function (item) {
  32285. return !item.error;
  32286. });
  32287. _this.applyChange();
  32288. };
  32289. this.removeAllItems = function () {
  32290. _this.items = [];
  32291. _this.applyChange();
  32292. };
  32293. this.setMediaItemState = function (id, state) {
  32294. _this.items = _this.items.map(function (item) {
  32295. return item.id === id ? _extends({}, item, state) : item;
  32296. });
  32297. _this.applyChange();
  32298. };
  32299. this.reuploadErrorItems = function () {
  32300. _this.uploadItems(true);
  32301. };
  32302. this.uploadItems = function () {
  32303. var ignoreError = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : false;
  32304. _this.items.forEach(function (item, index) {
  32305. if (item.uploading || item.url) {
  32306. return false;
  32307. }
  32308. if (!ignoreError && item.error) {
  32309. return false;
  32310. }
  32311. if (item.type === 'IMAGE') {
  32312. _this.createThumbnail(item);
  32313. _this.uploadFn = _this.uploadFn || _this.createInlineImage;
  32314. } else if (!_this.uploadFn) {
  32315. _this.setMediaItemState(item.id, { error: 1 });
  32316. return false;
  32317. }
  32318. _this.setMediaItemState(item.id, {
  32319. uploading: true,
  32320. uploadProgress: 0,
  32321. error: 0
  32322. });
  32323. _this.uploadFn({
  32324. id: item.id,
  32325. file: item.file,
  32326. success: function success(res) {
  32327. _this.handleUploadSuccess(item.id, res);
  32328. },
  32329. progress: function progress(_progress) {
  32330. _this.setMediaItemState(item.id, {
  32331. uploading: true,
  32332. uploadProgress: _progress
  32333. });
  32334. },
  32335. error: function error(_error) {
  32336. _this.setMediaItemState(item.id, {
  32337. uploading: false,
  32338. error: 2
  32339. });
  32340. }
  32341. });
  32342. });
  32343. };
  32344. this.createThumbnail = function (_ref) {
  32345. var id = _ref.id,
  32346. file = _ref.file;
  32347. (0, _image.compressImage)(URL.createObjectURL(file), 226, 226).then(function (result) {
  32348. _this.setMediaItemState(id, { thumbnail: result.url });
  32349. });
  32350. };
  32351. this.createInlineImage = function (param) {
  32352. (0, _image.compressImage)(URL.createObjectURL(param.file), 1280, 800).then(function (result) {
  32353. param.success({ url: result.url });
  32354. }).catch(function (error) {
  32355. param.error(error);
  32356. });
  32357. };
  32358. this.handleUploadSuccess = function (id, data) {
  32359. _this.setMediaItemState(id, _extends({}, data, {
  32360. file: null,
  32361. uploadProgress: 1,
  32362. uploading: false,
  32363. selected: false
  32364. }));
  32365. var item = _this.getMediaItem(data.id || id);
  32366. item.onReady && item.onReady(item);
  32367. };
  32368. this.applyChange = function () {
  32369. _this.changeListeners.forEach(function (_ref2) {
  32370. var callback = _ref2.callback;
  32371. return callback(_this.items);
  32372. });
  32373. };
  32374. this.uploadImage = function (file, callback) {
  32375. var fileId = new Date().getTime() + '_' + (0, _base.UniqueIndex)();
  32376. _this.addMediaItem({
  32377. type: 'IMAGE',
  32378. id: fileId,
  32379. file: file,
  32380. name: fileId,
  32381. size: file.size,
  32382. uploadProgress: 0,
  32383. uploading: false,
  32384. selected: false,
  32385. error: 0,
  32386. onReady: callback
  32387. });
  32388. };
  32389. this.uploadImageRecursively = function (files, callback) {
  32390. var index = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 0;
  32391. if (files[index] && files[index].type.indexOf('image') > -1) {
  32392. _this.uploadImage(files[index], function (image) {
  32393. callback && callback(image);
  32394. index < files.length - 1 && _this.uploadImageRecursively(files, callback, index + 1);
  32395. });
  32396. } else {
  32397. index < files.length - 1 && _this.uploadImageRecursively(files, callback, index + 1);
  32398. }
  32399. };
  32400. this.addResolvedFiles = function (param, index, accepts) {
  32401. var data = {
  32402. id: new Date().getTime() + '_' + (0, _base.UniqueIndex)(),
  32403. file: param.files[index],
  32404. name: param.files[index].name,
  32405. size: param.files[index].size,
  32406. uploadProgress: 0,
  32407. uploading: false,
  32408. selected: false,
  32409. error: 0,
  32410. onReady: function onReady(item) {
  32411. param.onItemReady && param.onItemReady(item);
  32412. }
  32413. };
  32414. if (param.files[index].type.indexOf('image/') === 0 && accepts.image) {
  32415. data.type = 'IMAGE';
  32416. _this.addMediaItem(data);
  32417. } else if (param.files[index].type.indexOf('video/') === 0 && accepts.video) {
  32418. data.type = 'VIDEO';
  32419. _this.addMediaItem(data);
  32420. } else if (param.files[index].type.indexOf('audio/') === 0 && accepts.audio) {
  32421. data.type = 'AUDIO';
  32422. _this.addMediaItem(data);
  32423. }
  32424. setTimeout(function () {
  32425. _this.resolveFiles(param, index + 1, accepts);
  32426. }, 60);
  32427. };
  32428. this.resolveFiles = function (param, index, accepts) {
  32429. if (index < param.files.length) {
  32430. var validateResult = _this.validateFn(param.files[index]);
  32431. if (validateResult instanceof Promise) {
  32432. validateResult.then(function () {
  32433. _this.addResolvedFiles(param, index, accepts);
  32434. });
  32435. } else if (validateResult) {
  32436. _this.addResolvedFiles(param, index, accepts);
  32437. }
  32438. } else {
  32439. param.onAllReady && param.onAllReady();
  32440. }
  32441. };
  32442. this.onChange = function (callback) {
  32443. var listenerId = (0, _base.UniqueIndex)();
  32444. _this.changeListeners.push({
  32445. id: listenerId,
  32446. callback: callback
  32447. });
  32448. return listenerId;
  32449. };
  32450. this.offChange = function (listenerId) {
  32451. _this.changeListeners = _this.changeListeners.filter(function (_ref3) {
  32452. var id = _ref3.id;
  32453. return id !== listenerId;
  32454. });
  32455. };
  32456. };
  32457. exports.default = BraftFinderController;
  32458. /***/ }),
  32459. /* 20 */
  32460. /***/ (function(module, exports, __webpack_require__) {
  32461. Object.defineProperty(exports, "__esModule", {
  32462. value: true
  32463. });
  32464. exports.ImageUtils = undefined;
  32465. var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };
  32466. var _react = __webpack_require__(2);
  32467. var _react2 = _interopRequireDefault(_react);
  32468. var _controller = __webpack_require__(19);
  32469. var _controller2 = _interopRequireDefault(_controller);
  32470. var _view = __webpack_require__(18);
  32471. var _view2 = _interopRequireDefault(_view);
  32472. var _languages = __webpack_require__(10);
  32473. var _languages2 = _interopRequireDefault(_languages);
  32474. var _image = __webpack_require__(0);
  32475. var ImageUtils = _interopRequireWildcard(_image);
  32476. function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } }
  32477. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  32478. function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  32479. function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }
  32480. function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
  32481. var BraftFinder = function (_FinderController) {
  32482. _inherits(BraftFinder, _FinderController);
  32483. function BraftFinder(props) {
  32484. _classCallCheck(this, BraftFinder);
  32485. var _this = _possibleConstructorReturn(this, (BraftFinder.__proto__ || Object.getPrototypeOf(BraftFinder)).call(this, props));
  32486. _initialiseProps.call(_this);
  32487. _this.superProps = props;
  32488. return _this;
  32489. }
  32490. return BraftFinder;
  32491. }(_controller2.default);
  32492. var _initialiseProps = function _initialiseProps() {
  32493. var _this2 = this;
  32494. this.ReactComponent = function () {
  32495. var props = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
  32496. var componentProps = _extends({}, _this2.superProps, props);
  32497. var language = (typeof componentProps.language === 'function' ? componentProps.language(_languages2.default, 'braft-finder') : _languages2.default[componentProps.language]) || _languages2.default['zh'];
  32498. return _react2.default.createElement(_view2.default, _extends({}, componentProps, {
  32499. language: language,
  32500. controller: _this2
  32501. }));
  32502. };
  32503. };
  32504. exports.default = BraftFinder;
  32505. exports.ImageUtils = ImageUtils;
  32506. /***/ })
  32507. /******/ ]);
  32508. });
  32509. });
  32510. unwrapExports(dist$2);
  32511. var draftjsUtils$1 = createCommonjsModule(function (module, exports) {
  32512. !function(e,t){module.exports=t(Draft,immutable$3);}("undefined"!=typeof self?self:commonjsGlobal,function(e,t){return function(e){function t(r){if(n[r])return n[r].exports;var o=n[r]={i:r,l:!1,exports:{}};return e[r].call(o.exports,o,o.exports,t),o.l=!0,o.exports}var n={};return t.m=e,t.c=n,t.d=function(e,n,r){t.o(e,n)||Object.defineProperty(e,n,{configurable:!1,enumerable:!0,get:r});},t.n=function(e){var n=e&&e.__esModule?function(){return e.default}:function(){return e};return t.d(n,"a",n),n},t.o=function(e,t){return Object.prototype.hasOwnProperty.call(e,t)},t.p="",t(t.s=3)}([function(t,n){t.exports=e;},function(e,t,n){function r(e){var t=e.getSelection(),n=e.getCurrentContent(),r=t.getStartKey(),o=t.getEndKey(),i=n.getBlockMap();return i.toSeq().skipUntil(function(e,t){return t===r}).takeUntil(function(e,t){return t===o}).concat([[o,i.get(o)]])}function o(e){return r(e).toList()}function i(e){if(e)return o(e).get(0)}function l(e){if(e){var t=i(e),n=e.getCurrentContent(),r=n.getBlockMap().toSeq().toList(),o=0;if(r.forEach(function(e,n){e.get("key")===t.get("key")&&(o=n-1);}),o>-1)return r.get(o)}}function c(e){return e?e.getCurrentContent().getBlockMap().toList():new v.List}function a(e){var t=o(e);if(!t.some(function(e){return e.type!==t.get(0).type}))return t.get(0).type}function f(e){var t=p.RichUtils.tryToRemoveBlockStyle(e);return t?p.EditorState.push(e,t,"change-block-type"):e}function u(e){var t="",n=e.getSelection(),r=n.getAnchorOffset(),i=n.getFocusOffset(),l=o(e);if(l.size>0){if(n.getIsBackward()){var c=r;r=i,i=c;}for(var a=0;a<l.size;a+=1){var f=0===a?r:0,u=a===l.size-1?i:l.get(a).getText().length;t+=l.get(a).getText().slice(f,u);}}return t}function s(e){var t=e.getCurrentContent(),n=e.getSelection(),r=p.Modifier.removeRange(t,n,"forward"),o=r.getSelectionAfter(),i=r.getBlockForKey(o.getStartKey());return r=p.Modifier.insertText(r,o,"\n",i.getInlineStyleAt(o.getStartOffset()),null),p.EditorState.push(e,r,"insert-fragment")}function g(e){var t=p.Modifier.splitBlock(e.getCurrentContent(),e.getSelection());return f(p.EditorState.push(e,t,"split-block"))}function d(e){var t=e.getCurrentContent().getBlockMap().toList(),n=e.getSelection().merge({anchorKey:t.first().get("key"),anchorOffset:0,focusKey:t.last().get("key"),focusOffset:t.last().getLength()}),r=p.Modifier.removeRange(e.getCurrentContent(),n,"forward");return p.EditorState.push(e,r,"remove-range")}function S(e,t){var n=p.Modifier.setBlockData(e.getCurrentContent(),e.getSelection(),t);return p.EditorState.push(e,n,"change-block-data")}function y(e){var t=new v.Map({}),n=o(e);if(n&&n.size>0)for(var r=0;r<n.size;r+=1){var i=function(e){var r=n.get(e).getData();if(!r||0===r.size)return t=t.clear(),"break";if(0===e)t=r;else if(t.forEach(function(e,n){r.get(n)&&r.get(n)===e||(t=t.delete(n));}),0===t.size)return t=t.clear(),"break"}(r);if("break"===i)break}return t}Object.defineProperty(t,"__esModule",{value:!0}),t.blockRenderMap=void 0,t.getSelectedBlocksMap=r,t.getSelectedBlocksList=o,t.getSelectedBlock=i,t.getBlockBeforeSelectedBlock=l,t.getAllBlocks=c,t.getSelectedBlocksType=a,t.removeSelectedBlocksStyle=f,t.getSelectionText=u,t.addLineBreakRemovingSelection=s,t.insertNewUnstyledBlock=g,t.clearEditorContent=d,t.setBlockData=S,t.getSelectedBlocksMetadata=y;var p=n(0),v=n(6),k=(0, v.Map)({code:{element:"pre"}});t.blockRenderMap=p.DefaultDraftBlockRenderMap.merge(k);},function(e,t,n){function r(e){if(e){var t=e.getType();return "unordered-list-item"===t||"ordered-list-item"===t}return !1}function o(e,t,n){var r=e.getSelection(),o=e.getCurrentContent(),i=o.getBlockMap(),l=(0, c.getSelectedBlocksMap)(e).map(function(e){var r=e.getDepth()+t;return r=Math.max(0,Math.min(r,n)),e.set("depth",r)});return i=i.merge(l),o.merge({blockMap:i,selectionBefore:r,selectionAfter:r})}function i(e,t,n){var r=e.getSelection(),i=void 0;i=r.getIsBackward()?r.getFocusKey():r.getAnchorKey();var c=e.getCurrentContent(),a=c.getBlockForKey(i),f=a.getType();if("unordered-list-item"!==f&&"ordered-list-item"!==f)return e;var u=c.getBlockBefore(i);if(!u)return e;if(u.getType()!==f)return e;var s=a.getDepth();if(1===t&&s===n)return e;var g=Math.min(u.getDepth()+1,n),d=o(e,t,g);return l.EditorState.push(e,d,"adjust-depth")}Object.defineProperty(t,"__esModule",{value:!0}),t.isListBlock=r,t.changeDepth=i;var l=n(0),c=n(1);},function(e,t,n){e.exports=n(4);},function(e,t,n){var r=n(5),o=n(1),i=n(7),l=function(e){return e&&e.__esModule?e:{default:e}}(i),c=n(2);e.exports={getSelectedBlocksMap:o.getSelectedBlocksMap,getSelectedBlocksList:o.getSelectedBlocksList,getSelectedBlock:o.getSelectedBlock,getBlockBeforeSelectedBlock:o.getBlockBeforeSelectedBlock,getAllBlocks:o.getAllBlocks,getSelectedBlocksType:o.getSelectedBlocksType,removeSelectedBlocksStyle:o.removeSelectedBlocksStyle,getSelectionText:o.getSelectionText,addLineBreakRemovingSelection:o.addLineBreakRemovingSelection,insertNewUnstyledBlock:o.insertNewUnstyledBlock,clearEditorContent:o.clearEditorContent,setBlockData:o.setBlockData,getSelectedBlocksMetadata:o.getSelectedBlocksMetadata,blockRenderMap:o.blockRenderMap,getEntityRange:r.getEntityRange,getCustomStyleMap:r.getCustomStyleMap,toggleCustomInlineStyle:r.toggleCustomInlineStyle,getSelectionEntity:r.getSelectionEntity,extractInlineStyle:r.extractInlineStyle,removeAllInlineStyles:r.removeAllInlineStyles,getSelectionInlineStyle:r.getSelectionInlineStyle,getSelectionCustomInlineStyle:r.getSelectionCustomInlineStyle,handleNewLine:l.default,isListBlock:c.isListBlock,changeDepth:c.changeDepth};},function(e,t,n){function r(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function o(e){var t=e.getSelection();if(t.isCollapsed()){var n={},r=e.getCurrentInlineStyle().toList().toJS();if(r)return ["BOLD","ITALIC","UNDERLINE","STRIKETHROUGH","CODE","SUPERSCRIPT","SUBSCRIPT"].forEach(function(e){n[e]=r.indexOf(e)>=0;}),n}var o=t.getStartOffset(),i=t.getEndOffset(),l=(0, p.getSelectedBlocksList)(e);if(l.size>0){var c=function(){for(var e={BOLD:!0,ITALIC:!0,UNDERLINE:!0,STRIKETHROUGH:!0,CODE:!0,SUPERSCRIPT:!0,SUBSCRIPT:!0},t=0;t<l.size;t+=1){var n=0===t?o:0,r=t===l.size-1?i:l.get(t).getText().length;n===r&&0===n?(n=1,r=2):n===r&&(n-=1);for(var c=n;c<r;c+=1)!function(n){var r=l.get(t).getInlineStyleAt(n);["BOLD","ITALIC","UNDERLINE","STRIKETHROUGH","CODE","SUPERSCRIPT","SUBSCRIPT"].forEach(function(t){e[t]=e[t]&&r.get(t)===t;});}(c);}return {v:e}}();if("object"===(void 0===c?"undefined":S(c)))return c.v}return {}}function i(e){var t=void 0,n=e.getSelection(),r=n.getStartOffset(),o=n.getEndOffset();r===o&&0===r?o=1:r===o&&(r-=1);for(var i=(0, p.getSelectedBlock)(e),l=r;l<o;l+=1){var c=i.getEntityAt(l);if(!c){t=void 0;break}if(l===r)t=c;else if(t!==c){t=void 0;break}}return t}function l(e,t){var n=(0, p.getSelectedBlock)(e),r=void 0;return n.findEntityRanges(function(e){return e.get("entity")===t},function(e,t){r={start:e,end:t,text:n.get("text").slice(e,t)};}),r}function c(e,t,n){var r=e.getSelection(),o=Object.keys(v[t]).reduce(function(e,t){return y.Modifier.removeInlineStyle(e,r,t)},e.getCurrentContent()),i=y.EditorState.push(e,o,"changeinline-style"),l=e.getCurrentInlineStyle();if(r.isCollapsed()&&(i=l.reduce(function(e,t){return y.RichUtils.toggleInlineStyle(e,t)},i)),"SUPERSCRIPT"===t||"SUBSCRIPT"==t)l.has(n)||(i=y.RichUtils.toggleInlineStyle(i,n));else{var c="bgcolor"===t?"backgroundColor":t;l.has(c+"-"+n)||(i=y.RichUtils.toggleInlineStyle(i,t.toLowerCase()+"-"+n),k(t,c,n));}return i}function a(e){if(e){e.getCurrentContent().getBlockMap().map(function(e){return e.get("characterList")}).toList().flatten().forEach(function(e){e&&0===e.indexOf("color-")?k("color","color",e.substr(6)):e&&0===e.indexOf("bgcolor-")?k("bgcolor","backgroundColor",e.substr(8)):e&&0===e.indexOf("fontsize-")?k("fontSize","fontSize",+e.substr(9)):e&&0===e.indexOf("fontfamily-")&&k("fontFamily","fontFamily",e.substr(11));});}}function f(e,t,n){var r=e.getInlineStyleAt(n).toList(),o=r.filter(function(e){return e.startsWith(t.toLowerCase())});if(o&&o.size>0)return o.get(0)}function u(e,t){var n=e.getCurrentInlineStyle().toList(),r=n.filter(function(e){return e.startsWith(t.toLowerCase())});if(r&&r.size>0)return r.get(0)}function s(e,t){if(e&&t&&t.length>0){var n=function(){var n=e.getSelection(),r={};if(n.isCollapsed())return t.forEach(function(t){r[t]=u(e,t);}),{v:r};var o=n.getStartOffset(),i=n.getEndOffset(),l=(0, p.getSelectedBlocksList)(e);if(l.size>0){for(var c=0;c<l.size;c+=1)!function(e){var n=0===e?o:0,c=e===l.size-1?i:l.get(e).getText().length;n===c&&0===n?(n=1,c=2):n===c&&(n-=1);for(var a=n;a<c;a+=1)!function(o){o===n?t.forEach(function(t){r[t]=f(l.get(e),t,o);}):t.forEach(function(t){r[t]&&r[t]!==f(l.get(e),t,o)&&(r[t]=void 0);});}(a);}(c);return {v:r}}}();if("object"===(void 0===n?"undefined":S(n)))return n.v}return {}}function g(e){var t=e.getCurrentInlineStyle(),n=e.getCurrentContent();return t.forEach(function(t){n=y.Modifier.removeInlineStyle(n,e.getSelection(),t);}),y.EditorState.push(e,n,"change-inline-style")}Object.defineProperty(t,"__esModule",{value:!0}),t.getCustomStyleMap=void 0;var d=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(e[r]=n[r]);}return e},S="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e};t.getSelectionInlineStyle=o,t.getSelectionEntity=i,t.getEntityRange=l,t.toggleCustomInlineStyle=c,t.extractInlineStyle=a,t.getSelectionCustomInlineStyle=s,t.removeAllInlineStyles=g;var y=n(0),p=n(1),v={color:{},bgcolor:{},fontSize:{},fontFamily:{},CODE:{fontFamily:"monospace",wordWrap:"break-word",background:"#f1f1f1",borderRadius:3,padding:"1px 3px"},SUPERSCRIPT:{fontSize:11,position:"relative",top:-8,display:"inline-flex"},SUBSCRIPT:{fontSize:11,position:"relative",bottom:-8,display:"inline-flex"}},k=function(e,t,n){v[e][e.toLowerCase()+"-"+n]=r({},""+t,n);};t.getCustomStyleMap=function(){return d({},v.color,v.bgcolor,v.fontSize,v.fontFamily,{CODE:v.CODE,SUPERSCRIPT:v.SUPERSCRIPT,SUBSCRIPT:v.SUBSCRIPT})};},function(e,n){e.exports=t;},function(e,t,n){function r(e){var t=e.getSelection();if(t.isCollapsed()){var n=e.getCurrentContent(),r=t.getStartKey(),o=n.getBlockForKey(r);if(!(0, a.isListBlock)(o)&&"unstyled"!==o.getType()&&o.getLength()===t.getStartOffset())return (0, c.insertNewUnstyledBlock)(e);if((0, a.isListBlock)(o)&&0===o.getLength()){var i=o.getDepth();if(0===i)return (0, c.removeSelectedBlocksStyle)(e);if(i>0)return (0, a.changeDepth)(e,-1,i)}}}function o(e){return 13===e.which&&(e.getModifierState("Shift")||e.getModifierState("Alt")||e.getModifierState("Control"))}function i(e,t){if(o(t)){return e.getSelection().isCollapsed()?l.RichUtils.insertSoftNewline(e):(0, c.addLineBreakRemovingSelection)(e)}return r(e)}Object.defineProperty(t,"__esModule",{value:!0}),t.default=i;var l=n(0),c=n(1),a=n(2);}])});
  32513. });
  32514. unwrapExports(draftjsUtils$1);
  32515. var draftjsUtils_1$1 = draftjsUtils$1.draftjsUtils;
  32516. var dist$3 = createCommonjsModule(function (module, exports) {
  32517. (function webpackUniversalModuleDefinition(root, factory) {
  32518. module.exports = factory(React, dist$1, Draft, immutable$3, dist, reactDom, dist$2, draftjsUtils$1);
  32519. })(window, function(__WEBPACK_EXTERNAL_MODULE__0__, __WEBPACK_EXTERNAL_MODULE__3__, __WEBPACK_EXTERNAL_MODULE__6__, __WEBPACK_EXTERNAL_MODULE__13__, __WEBPACK_EXTERNAL_MODULE__14__, __WEBPACK_EXTERNAL_MODULE__16__, __WEBPACK_EXTERNAL_MODULE__17__, __WEBPACK_EXTERNAL_MODULE__23__) {
  32520. return /******/ (function(modules) { // webpackBootstrap
  32521. /******/ // The module cache
  32522. /******/ var installedModules = {};
  32523. /******/
  32524. /******/ // The require function
  32525. /******/ function __webpack_require__(moduleId) {
  32526. /******/
  32527. /******/ // Check if module is in cache
  32528. /******/ if(installedModules[moduleId]) {
  32529. /******/ return installedModules[moduleId].exports;
  32530. /******/ }
  32531. /******/ // Create a new module (and put it into the cache)
  32532. /******/ var module = installedModules[moduleId] = {
  32533. /******/ i: moduleId,
  32534. /******/ l: false,
  32535. /******/ exports: {}
  32536. /******/ };
  32537. /******/
  32538. /******/ // Execute the module function
  32539. /******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);
  32540. /******/
  32541. /******/ // Flag the module as loaded
  32542. /******/ module.l = true;
  32543. /******/
  32544. /******/ // Return the exports of the module
  32545. /******/ return module.exports;
  32546. /******/ }
  32547. /******/
  32548. /******/
  32549. /******/ // expose the modules object (__webpack_modules__)
  32550. /******/ __webpack_require__.m = modules;
  32551. /******/
  32552. /******/ // expose the module cache
  32553. /******/ __webpack_require__.c = installedModules;
  32554. /******/
  32555. /******/ // define getter function for harmony exports
  32556. /******/ __webpack_require__.d = function(exports, name, getter) {
  32557. /******/ if(!__webpack_require__.o(exports, name)) {
  32558. /******/ Object.defineProperty(exports, name, { enumerable: true, get: getter });
  32559. /******/ }
  32560. /******/ };
  32561. /******/
  32562. /******/ // define __esModule on exports
  32563. /******/ __webpack_require__.r = function(exports) {
  32564. /******/ if(typeof Symbol !== 'undefined' && Symbol.toStringTag) {
  32565. /******/ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
  32566. /******/ }
  32567. /******/ Object.defineProperty(exports, '__esModule', { value: true });
  32568. /******/ };
  32569. /******/
  32570. /******/ // create a fake namespace object
  32571. /******/ // mode & 1: value is a module id, require it
  32572. /******/ // mode & 2: merge all properties of value into the ns
  32573. /******/ // mode & 4: return value when already ns object
  32574. /******/ // mode & 8|1: behave like require
  32575. /******/ __webpack_require__.t = function(value, mode) {
  32576. /******/ if(mode & 1) value = __webpack_require__(value);
  32577. /******/ if(mode & 8) return value;
  32578. /******/ if((mode & 4) && typeof value === 'object' && value && value.__esModule) return value;
  32579. /******/ var ns = Object.create(null);
  32580. /******/ __webpack_require__.r(ns);
  32581. /******/ Object.defineProperty(ns, 'default', { enumerable: true, value: value });
  32582. /******/ if(mode & 2 && typeof value != 'string') for(var key in value) __webpack_require__.d(ns, key, function(key) { return value[key]; }.bind(null, key));
  32583. /******/ return ns;
  32584. /******/ };
  32585. /******/
  32586. /******/ // getDefaultExport function for compatibility with non-harmony modules
  32587. /******/ __webpack_require__.n = function(module) {
  32588. /******/ var getter = module && module.__esModule ?
  32589. /******/ function getDefault() { return module['default']; } :
  32590. /******/ function getModuleExports() { return module; };
  32591. /******/ __webpack_require__.d(getter, 'a', getter);
  32592. /******/ return getter;
  32593. /******/ };
  32594. /******/
  32595. /******/ // Object.prototype.hasOwnProperty.call
  32596. /******/ __webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); };
  32597. /******/
  32598. /******/ // __webpack_public_path__
  32599. /******/ __webpack_require__.p = "/";
  32600. /******/
  32601. /******/
  32602. /******/ // Load entry module and return exports
  32603. /******/ return __webpack_require__(__webpack_require__.s = 39);
  32604. /******/ })
  32605. /************************************************************************/
  32606. /******/ ([
  32607. /* 0 */
  32608. /***/ (function(module, exports) {
  32609. module.exports = __WEBPACK_EXTERNAL_MODULE__0__;
  32610. /***/ }),
  32611. /* 1 */
  32612. /***/ (function(module, exports) {
  32613. function _assertThisInitialized(self) {
  32614. if (self === void 0) {
  32615. throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
  32616. }
  32617. return self;
  32618. }
  32619. module.exports = _assertThisInitialized;
  32620. /***/ }),
  32621. /* 2 */
  32622. /***/ (function(module, exports) {
  32623. function _defineProperty(obj, key, value) {
  32624. if (key in obj) {
  32625. Object.defineProperty(obj, key, {
  32626. value: value,
  32627. enumerable: true,
  32628. configurable: true,
  32629. writable: true
  32630. });
  32631. } else {
  32632. obj[key] = value;
  32633. }
  32634. return obj;
  32635. }
  32636. module.exports = _defineProperty;
  32637. /***/ }),
  32638. /* 3 */
  32639. /***/ (function(module, exports) {
  32640. module.exports = __WEBPACK_EXTERNAL_MODULE__3__;
  32641. /***/ }),
  32642. /* 4 */
  32643. /***/ (function(module, exports) {
  32644. function _classCallCheck(instance, Constructor) {
  32645. if (!(instance instanceof Constructor)) {
  32646. throw new TypeError("Cannot call a class as a function");
  32647. }
  32648. }
  32649. module.exports = _classCallCheck;
  32650. /***/ }),
  32651. /* 5 */
  32652. /***/ (function(module, exports, __webpack_require__) {
  32653. var defineProperty = __webpack_require__(2);
  32654. function _objectSpread(target) {
  32655. for (var i = 1; i < arguments.length; i++) {
  32656. var source = arguments[i] != null ? arguments[i] : {};
  32657. var ownKeys = Object.keys(source);
  32658. if (typeof Object.getOwnPropertySymbols === 'function') {
  32659. ownKeys = ownKeys.concat(Object.getOwnPropertySymbols(source).filter(function (sym) {
  32660. return Object.getOwnPropertyDescriptor(source, sym).enumerable;
  32661. }));
  32662. }
  32663. ownKeys.forEach(function (key) {
  32664. defineProperty(target, key, source[key]);
  32665. });
  32666. }
  32667. return target;
  32668. }
  32669. module.exports = _objectSpread;
  32670. /***/ }),
  32671. /* 6 */
  32672. /***/ (function(module, exports) {
  32673. module.exports = __WEBPACK_EXTERNAL_MODULE__6__;
  32674. /***/ }),
  32675. /* 7 */
  32676. /***/ (function(module, exports) {
  32677. function _defineProperties(target, props) {
  32678. for (var i = 0; i < props.length; i++) {
  32679. var descriptor = props[i];
  32680. descriptor.enumerable = descriptor.enumerable || false;
  32681. descriptor.configurable = true;
  32682. if ("value" in descriptor) descriptor.writable = true;
  32683. Object.defineProperty(target, descriptor.key, descriptor);
  32684. }
  32685. }
  32686. function _createClass(Constructor, protoProps, staticProps) {
  32687. if (protoProps) _defineProperties(Constructor.prototype, protoProps);
  32688. if (staticProps) _defineProperties(Constructor, staticProps);
  32689. return Constructor;
  32690. }
  32691. module.exports = _createClass;
  32692. /***/ }),
  32693. /* 8 */
  32694. /***/ (function(module, exports, __webpack_require__) {
  32695. var _typeof = __webpack_require__(15);
  32696. var assertThisInitialized = __webpack_require__(1);
  32697. function _possibleConstructorReturn(self, call) {
  32698. if (call && (_typeof(call) === "object" || typeof call === "function")) {
  32699. return call;
  32700. }
  32701. return assertThisInitialized(self);
  32702. }
  32703. module.exports = _possibleConstructorReturn;
  32704. /***/ }),
  32705. /* 9 */
  32706. /***/ (function(module, exports) {
  32707. function _getPrototypeOf(o) {
  32708. module.exports = _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) {
  32709. return o.__proto__ || Object.getPrototypeOf(o);
  32710. };
  32711. return _getPrototypeOf(o);
  32712. }
  32713. module.exports = _getPrototypeOf;
  32714. /***/ }),
  32715. /* 10 */
  32716. /***/ (function(module, exports, __webpack_require__) {
  32717. var setPrototypeOf = __webpack_require__(26);
  32718. function _inherits(subClass, superClass) {
  32719. if (typeof superClass !== "function" && superClass !== null) {
  32720. throw new TypeError("Super expression must either be null or a function");
  32721. }
  32722. subClass.prototype = Object.create(superClass && superClass.prototype, {
  32723. constructor: {
  32724. value: subClass,
  32725. writable: true,
  32726. configurable: true
  32727. }
  32728. });
  32729. if (superClass) setPrototypeOf(subClass, superClass);
  32730. }
  32731. module.exports = _inherits;
  32732. /***/ }),
  32733. /* 11 */
  32734. /***/ (function(module, exports) {
  32735. function _extends() {
  32736. module.exports = _extends = Object.assign || function (target) {
  32737. for (var i = 1; i < arguments.length; i++) {
  32738. var source = arguments[i];
  32739. for (var key in source) {
  32740. if (Object.prototype.hasOwnProperty.call(source, key)) {
  32741. target[key] = source[key];
  32742. }
  32743. }
  32744. }
  32745. return target;
  32746. };
  32747. return _extends.apply(this, arguments);
  32748. }
  32749. module.exports = _extends;
  32750. /***/ }),
  32751. /* 12 */
  32752. /***/ (function(module, exports, __webpack_require__) {
  32753. var arrayWithoutHoles = __webpack_require__(27);
  32754. var iterableToArray = __webpack_require__(28);
  32755. var nonIterableSpread = __webpack_require__(29);
  32756. function _toConsumableArray(arr) {
  32757. return arrayWithoutHoles(arr) || iterableToArray(arr) || nonIterableSpread();
  32758. }
  32759. module.exports = _toConsumableArray;
  32760. /***/ }),
  32761. /* 13 */
  32762. /***/ (function(module, exports) {
  32763. module.exports = __WEBPACK_EXTERNAL_MODULE__13__;
  32764. /***/ }),
  32765. /* 14 */
  32766. /***/ (function(module, exports) {
  32767. module.exports = __WEBPACK_EXTERNAL_MODULE__14__;
  32768. /***/ }),
  32769. /* 15 */
  32770. /***/ (function(module, exports) {
  32771. function _typeof2(obj) { if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof2 = function _typeof2(obj) { return typeof obj; }; } else { _typeof2 = function _typeof2(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof2(obj); }
  32772. function _typeof(obj) {
  32773. if (typeof Symbol === "function" && _typeof2(Symbol.iterator) === "symbol") {
  32774. module.exports = _typeof = function _typeof(obj) {
  32775. return _typeof2(obj);
  32776. };
  32777. } else {
  32778. module.exports = _typeof = function _typeof(obj) {
  32779. return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : _typeof2(obj);
  32780. };
  32781. }
  32782. return _typeof(obj);
  32783. }
  32784. module.exports = _typeof;
  32785. /***/ }),
  32786. /* 16 */
  32787. /***/ (function(module, exports) {
  32788. module.exports = __WEBPACK_EXTERNAL_MODULE__16__;
  32789. /***/ }),
  32790. /* 17 */
  32791. /***/ (function(module, exports) {
  32792. module.exports = __WEBPACK_EXTERNAL_MODULE__17__;
  32793. /***/ }),
  32794. /* 18 */
  32795. /***/ (function(module, exports, __webpack_require__) {
  32796. var Immutable = __webpack_require__(13);
  32797. var KEY_SEPARATOR = '-';
  32798. function MultiDecorator(decorators) {
  32799. this.decorators = Immutable.List(decorators);
  32800. }
  32801. /**
  32802. Return list of decoration IDs per character
  32803. @param {ContentBlock}
  32804. @return {List<String>}
  32805. */
  32806. MultiDecorator.prototype.getDecorations = function(block) {
  32807. var decorations = Array(block.getText().length).fill(null);
  32808. this.decorators.forEach(function(decorator, i) {
  32809. var _decorations = decorator.getDecorations(block);
  32810. _decorations.forEach(function(key, offset) {
  32811. if (!key) {
  32812. return;
  32813. }
  32814. key = i + KEY_SEPARATOR + key;
  32815. decorations[offset] = key;
  32816. });
  32817. });
  32818. return Immutable.List(decorations);
  32819. };
  32820. /**
  32821. Return component to render a decoration
  32822. @param {String}
  32823. @return {Function}
  32824. */
  32825. MultiDecorator.prototype.getComponentForKey = function(key) {
  32826. var decorator = this.getDecoratorForKey(key);
  32827. return decorator.getComponentForKey(
  32828. this.getInnerKey(key)
  32829. );
  32830. };
  32831. /**
  32832. Return props to render a decoration
  32833. @param {String}
  32834. @return {Object}
  32835. */
  32836. MultiDecorator.prototype.getPropsForKey = function(key) {
  32837. var decorator = this.getDecoratorForKey(key);
  32838. return decorator.getPropsForKey(
  32839. this.getInnerKey(key)
  32840. );
  32841. };
  32842. /**
  32843. Return a decorator for a specific key
  32844. @param {String}
  32845. @return {Decorator}
  32846. */
  32847. MultiDecorator.prototype.getDecoratorForKey = function(key) {
  32848. var parts = key.split(KEY_SEPARATOR);
  32849. var index = Number(parts[0]);
  32850. return this.decorators.get(index);
  32851. };
  32852. /**
  32853. Return inner key for a decorator
  32854. @param {String}
  32855. @return {String}
  32856. */
  32857. MultiDecorator.prototype.getInnerKey = function(key) {
  32858. var parts = key.split(KEY_SEPARATOR);
  32859. return parts.slice(1).join(KEY_SEPARATOR);
  32860. };
  32861. module.exports = MultiDecorator;
  32862. /***/ }),
  32863. /* 19 */
  32864. /***/ (function(module, exports, __webpack_require__) {
  32865. /**
  32866. * Copyright (c) 2013-present, Facebook, Inc.
  32867. * All rights reserved.
  32868. *
  32869. * This source code is licensed under the BSD-style license found in the
  32870. * LICENSE file in the root directory of this source tree. An additional grant
  32871. * of patent rights can be found in the PATENTS file in the same directory.
  32872. *
  32873. * @providesModule CharacterMetadata
  32874. * @format
  32875. *
  32876. */
  32877. function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  32878. function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }
  32879. function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
  32880. var _require = __webpack_require__(13),
  32881. Map = _require.Map,
  32882. OrderedSet = _require.OrderedSet,
  32883. Record = _require.Record;
  32884. // Immutable.map is typed such that the value for every key in the map
  32885. // must be the same type
  32886. var EMPTY_SET = OrderedSet();
  32887. var defaultRecord = {
  32888. style: EMPTY_SET,
  32889. entity: null
  32890. };
  32891. var CharacterMetadataRecord = Record(defaultRecord);
  32892. var CharacterMetadata = function (_CharacterMetadataRec) {
  32893. _inherits(CharacterMetadata, _CharacterMetadataRec);
  32894. function CharacterMetadata() {
  32895. _classCallCheck(this, CharacterMetadata);
  32896. return _possibleConstructorReturn(this, _CharacterMetadataRec.apply(this, arguments));
  32897. }
  32898. CharacterMetadata.prototype.getStyle = function getStyle() {
  32899. return this.get('style');
  32900. };
  32901. CharacterMetadata.prototype.getEntity = function getEntity() {
  32902. return this.get('entity');
  32903. };
  32904. CharacterMetadata.prototype.hasStyle = function hasStyle(style) {
  32905. return this.getStyle().includes(style);
  32906. };
  32907. CharacterMetadata.applyStyle = function applyStyle(record, style) {
  32908. var withStyle = record.set('style', record.getStyle().add(style));
  32909. return CharacterMetadata.create(withStyle);
  32910. };
  32911. CharacterMetadata.removeStyle = function removeStyle(record, style) {
  32912. var withoutStyle = record.set('style', record.getStyle().remove(style));
  32913. return CharacterMetadata.create(withoutStyle);
  32914. };
  32915. CharacterMetadata.applyEntity = function applyEntity(record, entityKey) {
  32916. var withEntity = record.getEntity() === entityKey ? record : record.set('entity', entityKey);
  32917. return CharacterMetadata.create(withEntity);
  32918. };
  32919. /**
  32920. * Use this function instead of the `CharacterMetadata` constructor.
  32921. * Since most content generally uses only a very small number of
  32922. * style/entity permutations, we can reuse these objects as often as
  32923. * possible.
  32924. */
  32925. CharacterMetadata.create = function create(config) {
  32926. if (!config) {
  32927. return EMPTY;
  32928. }
  32929. var defaultConfig = {
  32930. style: EMPTY_SET,
  32931. entity: null
  32932. };
  32933. // Fill in unspecified properties, if necessary.
  32934. var configMap = Map(defaultConfig).merge(config);
  32935. var existing = pool.get(configMap);
  32936. if (existing) {
  32937. return existing;
  32938. }
  32939. var newCharacter = new CharacterMetadata(configMap);
  32940. pool = pool.set(configMap, newCharacter);
  32941. return newCharacter;
  32942. };
  32943. return CharacterMetadata;
  32944. }(CharacterMetadataRecord);
  32945. var EMPTY = new CharacterMetadata();
  32946. var pool = Map([[Map(defaultRecord), EMPTY]]);
  32947. CharacterMetadata.EMPTY = EMPTY;
  32948. module.exports = CharacterMetadata;
  32949. /***/ }),
  32950. /* 20 */
  32951. /***/ (function(module, exports, __webpack_require__) {
  32952. /**
  32953. * Copyright (c) 2013-present, Facebook, Inc.
  32954. * All rights reserved.
  32955. *
  32956. * This source code is licensed under the BSD-style license found in the
  32957. * LICENSE file in the root directory of this source tree. An additional grant
  32958. * of patent rights can be found in the PATENTS file in the same directory.
  32959. *
  32960. * @providesModule findRangesImmutable
  32961. * @format
  32962. *
  32963. */
  32964. /**
  32965. * Search through an array to find contiguous stretches of elements that
  32966. * match a specified filter function.
  32967. *
  32968. * When ranges are found, execute a specified `found` function to supply
  32969. * the values to the caller.
  32970. */
  32971. function findRangesImmutable(haystack, areEqualFn, filterFn, foundFn) {
  32972. if (!haystack.size) {
  32973. return;
  32974. }
  32975. var cursor = 0;
  32976. haystack.reduce(function (value, nextValue, nextIndex) {
  32977. if (!areEqualFn(value, nextValue)) {
  32978. if (filterFn(value)) {
  32979. foundFn(cursor, nextIndex);
  32980. }
  32981. cursor = nextIndex;
  32982. }
  32983. return nextValue;
  32984. });
  32985. filterFn(haystack.last()) && foundFn(cursor, haystack.count());
  32986. }
  32987. module.exports = findRangesImmutable;
  32988. /***/ }),
  32989. /* 21 */
  32990. /***/ (function(module, exports, __webpack_require__) {
  32991. var objectWithoutPropertiesLoose = __webpack_require__(25);
  32992. function _objectWithoutProperties(source, excluded) {
  32993. if (source == null) return {};
  32994. var target = objectWithoutPropertiesLoose(source, excluded);
  32995. var key, i;
  32996. if (Object.getOwnPropertySymbols) {
  32997. var sourceSymbolKeys = Object.getOwnPropertySymbols(source);
  32998. for (i = 0; i < sourceSymbolKeys.length; i++) {
  32999. key = sourceSymbolKeys[i];
  33000. if (excluded.indexOf(key) >= 0) continue;
  33001. if (!Object.prototype.propertyIsEnumerable.call(source, key)) continue;
  33002. target[key] = source[key];
  33003. }
  33004. }
  33005. return target;
  33006. }
  33007. module.exports = _objectWithoutProperties;
  33008. /***/ }),
  33009. /* 22 */
  33010. /***/ (function(module, exports, __webpack_require__) {
  33011. /**
  33012. * Copyright (c) 2013-present, Facebook, Inc.
  33013. * All rights reserved.
  33014. *
  33015. * This source code is licensed under the BSD-style license found in the
  33016. * LICENSE file in the root directory of this source tree. An additional grant
  33017. * of patent rights can be found in the PATENTS file in the same directory.
  33018. *
  33019. * @providesModule getFragmentFromSelection
  33020. * @format
  33021. *
  33022. */
  33023. var getContentStateFragment = __webpack_require__(30);
  33024. function getFragmentFromSelection(editorState) {
  33025. var selectionState = editorState.getSelection();
  33026. if (selectionState.isCollapsed()) {
  33027. return null;
  33028. }
  33029. return getContentStateFragment(editorState.getCurrentContent(), selectionState);
  33030. }
  33031. module.exports = getFragmentFromSelection;
  33032. /***/ }),
  33033. /* 23 */
  33034. /***/ (function(module, exports) {
  33035. module.exports = __WEBPACK_EXTERNAL_MODULE__23__;
  33036. /***/ }),
  33037. /* 24 */
  33038. /***/ (function(module, exports, __webpack_require__) {
  33039. var arrayWithHoles = __webpack_require__(36);
  33040. var iterableToArrayLimit = __webpack_require__(37);
  33041. var nonIterableRest = __webpack_require__(38);
  33042. function _slicedToArray(arr, i) {
  33043. return arrayWithHoles(arr) || iterableToArrayLimit(arr, i) || nonIterableRest();
  33044. }
  33045. module.exports = _slicedToArray;
  33046. /***/ }),
  33047. /* 25 */
  33048. /***/ (function(module, exports) {
  33049. function _objectWithoutPropertiesLoose(source, excluded) {
  33050. if (source == null) return {};
  33051. var target = {};
  33052. var sourceKeys = Object.keys(source);
  33053. var key, i;
  33054. for (i = 0; i < sourceKeys.length; i++) {
  33055. key = sourceKeys[i];
  33056. if (excluded.indexOf(key) >= 0) continue;
  33057. target[key] = source[key];
  33058. }
  33059. return target;
  33060. }
  33061. module.exports = _objectWithoutPropertiesLoose;
  33062. /***/ }),
  33063. /* 26 */
  33064. /***/ (function(module, exports) {
  33065. function _setPrototypeOf(o, p) {
  33066. module.exports = _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) {
  33067. o.__proto__ = p;
  33068. return o;
  33069. };
  33070. return _setPrototypeOf(o, p);
  33071. }
  33072. module.exports = _setPrototypeOf;
  33073. /***/ }),
  33074. /* 27 */
  33075. /***/ (function(module, exports) {
  33076. function _arrayWithoutHoles(arr) {
  33077. if (Array.isArray(arr)) {
  33078. for (var i = 0, arr2 = new Array(arr.length); i < arr.length; i++) {
  33079. arr2[i] = arr[i];
  33080. }
  33081. return arr2;
  33082. }
  33083. }
  33084. module.exports = _arrayWithoutHoles;
  33085. /***/ }),
  33086. /* 28 */
  33087. /***/ (function(module, exports) {
  33088. function _iterableToArray(iter) {
  33089. if (Symbol.iterator in Object(iter) || Object.prototype.toString.call(iter) === "[object Arguments]") return Array.from(iter);
  33090. }
  33091. module.exports = _iterableToArray;
  33092. /***/ }),
  33093. /* 29 */
  33094. /***/ (function(module, exports) {
  33095. function _nonIterableSpread() {
  33096. throw new TypeError("Invalid attempt to spread non-iterable instance");
  33097. }
  33098. module.exports = _nonIterableSpread;
  33099. /***/ }),
  33100. /* 30 */
  33101. /***/ (function(module, exports, __webpack_require__) {
  33102. /**
  33103. * Copyright (c) 2013-present, Facebook, Inc.
  33104. * All rights reserved.
  33105. *
  33106. * This source code is licensed under the BSD-style license found in the
  33107. * LICENSE file in the root directory of this source tree. An additional grant
  33108. * of patent rights can be found in the PATENTS file in the same directory.
  33109. *
  33110. * @providesModule getContentStateFragment
  33111. * @format
  33112. *
  33113. */
  33114. var randomizeBlockMapKeys = __webpack_require__(31);
  33115. var removeEntitiesAtEdges = __webpack_require__(34);
  33116. var getContentStateFragment = function getContentStateFragment(contentState, selectionState) {
  33117. var startKey = selectionState.getStartKey();
  33118. var startOffset = selectionState.getStartOffset();
  33119. var endKey = selectionState.getEndKey();
  33120. var endOffset = selectionState.getEndOffset();
  33121. // Edge entities should be stripped to ensure that we don't preserve
  33122. // invalid partial entities when the fragment is reused. We do, however,
  33123. // preserve entities that are entirely within the selection range.
  33124. var contentWithoutEdgeEntities = removeEntitiesAtEdges(contentState, selectionState);
  33125. var blockMap = contentWithoutEdgeEntities.getBlockMap();
  33126. var blockKeys = blockMap.keySeq();
  33127. var startIndex = blockKeys.indexOf(startKey);
  33128. var endIndex = blockKeys.indexOf(endKey) + 1;
  33129. return randomizeBlockMapKeys(blockMap.slice(startIndex, endIndex).map(function (block, blockKey) {
  33130. var text = block.getText();
  33131. var chars = block.getCharacterList();
  33132. if (startKey === endKey) {
  33133. return block.merge({
  33134. text: text.slice(startOffset, endOffset),
  33135. characterList: chars.slice(startOffset, endOffset)
  33136. });
  33137. }
  33138. if (blockKey === startKey) {
  33139. return block.merge({
  33140. text: text.slice(startOffset),
  33141. characterList: chars.slice(startOffset)
  33142. });
  33143. }
  33144. if (blockKey === endKey) {
  33145. return block.merge({
  33146. text: text.slice(0, endOffset),
  33147. characterList: chars.slice(0, endOffset)
  33148. });
  33149. }
  33150. return block;
  33151. }));
  33152. };
  33153. module.exports = getContentStateFragment;
  33154. /***/ }),
  33155. /* 31 */
  33156. /***/ (function(module, exports, __webpack_require__) {
  33157. /**
  33158. * Copyright (c) 2013-present, Facebook, Inc.
  33159. * All rights reserved.
  33160. *
  33161. * This source code is licensed under the BSD-style license found in the
  33162. * LICENSE file in the root directory of this source tree. An additional grant
  33163. * of patent rights can be found in the PATENTS file in the same directory.
  33164. *
  33165. * @providesModule randomizeBlockMapKeys
  33166. * @format
  33167. *
  33168. */
  33169. var ContentBlockNode = __webpack_require__(32);
  33170. var Immutable = __webpack_require__(13);
  33171. var generateRandomKey = __webpack_require__(33);
  33172. var OrderedMap = Immutable.OrderedMap;
  33173. var randomizeContentBlockNodeKeys = function randomizeContentBlockNodeKeys(blockMap) {
  33174. var newKeysRef = {};
  33175. // we keep track of root blocks in order to update subsequent sibling links
  33176. var lastRootBlock = void 0;
  33177. return OrderedMap(blockMap.withMutations(function (blockMapState) {
  33178. blockMapState.forEach(function (block, index) {
  33179. var oldKey = block.getKey();
  33180. var nextKey = block.getNextSiblingKey();
  33181. var prevKey = block.getPrevSiblingKey();
  33182. var childrenKeys = block.getChildKeys();
  33183. var parentKey = block.getParentKey();
  33184. // new key that we will use to build linking
  33185. var key = generateRandomKey();
  33186. // we will add it here to re-use it later
  33187. newKeysRef[oldKey] = key;
  33188. if (nextKey) {
  33189. var nextBlock = blockMapState.get(nextKey);
  33190. if (nextBlock) {
  33191. blockMapState.setIn([nextKey, 'prevSibling'], key);
  33192. } else {
  33193. // this can happen when generating random keys for fragments
  33194. blockMapState.setIn([oldKey, 'nextSibling'], null);
  33195. }
  33196. }
  33197. if (prevKey) {
  33198. var prevBlock = blockMapState.get(prevKey);
  33199. if (prevBlock) {
  33200. blockMapState.setIn([prevKey, 'nextSibling'], key);
  33201. } else {
  33202. // this can happen when generating random keys for fragments
  33203. blockMapState.setIn([oldKey, 'prevSibling'], null);
  33204. }
  33205. }
  33206. if (parentKey && blockMapState.get(parentKey)) {
  33207. var parentBlock = blockMapState.get(parentKey);
  33208. var parentChildrenList = parentBlock.getChildKeys();
  33209. blockMapState.setIn([parentKey, 'children'], parentChildrenList.set(parentChildrenList.indexOf(block.getKey()), key));
  33210. } else {
  33211. // blocks will then be treated as root block nodes
  33212. blockMapState.setIn([oldKey, 'parent'], null);
  33213. if (lastRootBlock) {
  33214. blockMapState.setIn([lastRootBlock.getKey(), 'nextSibling'], key);
  33215. blockMapState.setIn([oldKey, 'prevSibling'], newKeysRef[lastRootBlock.getKey()]);
  33216. }
  33217. lastRootBlock = blockMapState.get(oldKey);
  33218. }
  33219. childrenKeys.forEach(function (childKey) {
  33220. var childBlock = blockMapState.get(childKey);
  33221. if (childBlock) {
  33222. blockMapState.setIn([childKey, 'parent'], key);
  33223. } else {
  33224. blockMapState.setIn([oldKey, 'children'], block.getChildKeys().filter(function (child) {
  33225. return child !== childKey;
  33226. }));
  33227. }
  33228. });
  33229. });
  33230. }).toArray().map(function (block) {
  33231. return [newKeysRef[block.getKey()], block.set('key', newKeysRef[block.getKey()])];
  33232. }));
  33233. };
  33234. var randomizeContentBlockKeys = function randomizeContentBlockKeys(blockMap) {
  33235. return OrderedMap(blockMap.toArray().map(function (block) {
  33236. var key = generateRandomKey();
  33237. return [key, block.set('key', key)];
  33238. }));
  33239. };
  33240. var randomizeBlockMapKeys = function randomizeBlockMapKeys(blockMap) {
  33241. var isTreeBasedBlockMap = blockMap.first() instanceof ContentBlockNode;
  33242. if (!isTreeBasedBlockMap) {
  33243. return randomizeContentBlockKeys(blockMap);
  33244. }
  33245. return randomizeContentBlockNodeKeys(blockMap);
  33246. };
  33247. module.exports = randomizeBlockMapKeys;
  33248. /***/ }),
  33249. /* 32 */
  33250. /***/ (function(module, exports, __webpack_require__) {
  33251. /**
  33252. * Copyright (c) 2013-present, Facebook, Inc.
  33253. * All rights reserved.
  33254. *
  33255. * This source code is licensed under the BSD-style license found in the
  33256. * LICENSE file in the root directory of this source tree. An additional grant
  33257. * of patent rights can be found in the PATENTS file in the same directory.
  33258. *
  33259. * @providesModule ContentBlockNode
  33260. * @format
  33261. *
  33262. *
  33263. * This file is a fork of ContentBlock adding support for nesting references by
  33264. * providing links to children, parent, prevSibling, and nextSibling.
  33265. *
  33266. * This is unstable and not part of the public API and should not be used by
  33267. * production systems. This file may be update/removed without notice.
  33268. */
  33269. function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  33270. function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }
  33271. function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
  33272. var CharacterMetadata = __webpack_require__(19);
  33273. var Immutable = __webpack_require__(13);
  33274. var findRangesImmutable = __webpack_require__(20);
  33275. var List = Immutable.List,
  33276. Map = Immutable.Map,
  33277. OrderedSet = Immutable.OrderedSet,
  33278. Record = Immutable.Record,
  33279. Repeat = Immutable.Repeat;
  33280. var EMPTY_SET = OrderedSet();
  33281. var defaultRecord = {
  33282. parent: null,
  33283. characterList: List(),
  33284. data: Map(),
  33285. depth: 0,
  33286. key: '',
  33287. text: '',
  33288. type: 'unstyled',
  33289. children: List(),
  33290. prevSibling: null,
  33291. nextSibling: null
  33292. };
  33293. var haveEqualStyle = function haveEqualStyle(charA, charB) {
  33294. return charA.getStyle() === charB.getStyle();
  33295. };
  33296. var haveEqualEntity = function haveEqualEntity(charA, charB) {
  33297. return charA.getEntity() === charB.getEntity();
  33298. };
  33299. var decorateCharacterList = function decorateCharacterList(config) {
  33300. if (!config) {
  33301. return config;
  33302. }
  33303. var characterList = config.characterList,
  33304. text = config.text;
  33305. if (text && !characterList) {
  33306. config.characterList = List(Repeat(CharacterMetadata.EMPTY, text.length));
  33307. }
  33308. return config;
  33309. };
  33310. var ContentBlockNode = function (_Record) {
  33311. _inherits(ContentBlockNode, _Record);
  33312. function ContentBlockNode() {
  33313. var props = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : defaultRecord;
  33314. _classCallCheck(this, ContentBlockNode);
  33315. return _possibleConstructorReturn(this, _Record.call(this, decorateCharacterList(props)));
  33316. }
  33317. ContentBlockNode.prototype.getKey = function getKey() {
  33318. return this.get('key');
  33319. };
  33320. ContentBlockNode.prototype.getType = function getType() {
  33321. return this.get('type');
  33322. };
  33323. ContentBlockNode.prototype.getText = function getText() {
  33324. return this.get('text');
  33325. };
  33326. ContentBlockNode.prototype.getCharacterList = function getCharacterList() {
  33327. return this.get('characterList');
  33328. };
  33329. ContentBlockNode.prototype.getLength = function getLength() {
  33330. return this.getText().length;
  33331. };
  33332. ContentBlockNode.prototype.getDepth = function getDepth() {
  33333. return this.get('depth');
  33334. };
  33335. ContentBlockNode.prototype.getData = function getData() {
  33336. return this.get('data');
  33337. };
  33338. ContentBlockNode.prototype.getInlineStyleAt = function getInlineStyleAt(offset) {
  33339. var character = this.getCharacterList().get(offset);
  33340. return character ? character.getStyle() : EMPTY_SET;
  33341. };
  33342. ContentBlockNode.prototype.getEntityAt = function getEntityAt(offset) {
  33343. var character = this.getCharacterList().get(offset);
  33344. return character ? character.getEntity() : null;
  33345. };
  33346. ContentBlockNode.prototype.getChildKeys = function getChildKeys() {
  33347. return this.get('children');
  33348. };
  33349. ContentBlockNode.prototype.getParentKey = function getParentKey() {
  33350. return this.get('parent');
  33351. };
  33352. ContentBlockNode.prototype.getPrevSiblingKey = function getPrevSiblingKey() {
  33353. return this.get('prevSibling');
  33354. };
  33355. ContentBlockNode.prototype.getNextSiblingKey = function getNextSiblingKey() {
  33356. return this.get('nextSibling');
  33357. };
  33358. ContentBlockNode.prototype.findStyleRanges = function findStyleRanges(filterFn, callback) {
  33359. findRangesImmutable(this.getCharacterList(), haveEqualStyle, filterFn, callback);
  33360. };
  33361. ContentBlockNode.prototype.findEntityRanges = function findEntityRanges(filterFn, callback) {
  33362. findRangesImmutable(this.getCharacterList(), haveEqualEntity, filterFn, callback);
  33363. };
  33364. return ContentBlockNode;
  33365. }(Record(defaultRecord));
  33366. module.exports = ContentBlockNode;
  33367. /***/ }),
  33368. /* 33 */
  33369. /***/ (function(module, exports, __webpack_require__) {
  33370. /**
  33371. * Copyright (c) 2013-present, Facebook, Inc.
  33372. * All rights reserved.
  33373. *
  33374. * This source code is licensed under the BSD-style license found in the
  33375. * LICENSE file in the root directory of this source tree. An additional grant
  33376. * of patent rights can be found in the PATENTS file in the same directory.
  33377. *
  33378. * @providesModule generateRandomKey
  33379. * @format
  33380. *
  33381. */
  33382. var seenKeys = {};
  33383. var MULTIPLIER = Math.pow(2, 24);
  33384. function generateRandomKey() {
  33385. var key = void 0;
  33386. while (key === undefined || seenKeys.hasOwnProperty(key) || !isNaN(+key)) {
  33387. key = Math.floor(Math.random() * MULTIPLIER).toString(32);
  33388. }
  33389. seenKeys[key] = true;
  33390. return key;
  33391. }
  33392. module.exports = generateRandomKey;
  33393. /***/ }),
  33394. /* 34 */
  33395. /***/ (function(module, exports, __webpack_require__) {
  33396. /**
  33397. * Copyright (c) 2013-present, Facebook, Inc.
  33398. * All rights reserved.
  33399. *
  33400. * This source code is licensed under the BSD-style license found in the
  33401. * LICENSE file in the root directory of this source tree. An additional grant
  33402. * of patent rights can be found in the PATENTS file in the same directory.
  33403. *
  33404. * @providesModule removeEntitiesAtEdges
  33405. * @format
  33406. *
  33407. */
  33408. var CharacterMetadata = __webpack_require__(19);
  33409. var findRangesImmutable = __webpack_require__(20);
  33410. var invariant = __webpack_require__(35);
  33411. function removeEntitiesAtEdges(contentState, selectionState) {
  33412. var blockMap = contentState.getBlockMap();
  33413. var entityMap = contentState.getEntityMap();
  33414. var updatedBlocks = {};
  33415. var startKey = selectionState.getStartKey();
  33416. var startOffset = selectionState.getStartOffset();
  33417. var startBlock = blockMap.get(startKey);
  33418. var updatedStart = removeForBlock(entityMap, startBlock, startOffset);
  33419. if (updatedStart !== startBlock) {
  33420. updatedBlocks[startKey] = updatedStart;
  33421. }
  33422. var endKey = selectionState.getEndKey();
  33423. var endOffset = selectionState.getEndOffset();
  33424. var endBlock = blockMap.get(endKey);
  33425. if (startKey === endKey) {
  33426. endBlock = updatedStart;
  33427. }
  33428. var updatedEnd = removeForBlock(entityMap, endBlock, endOffset);
  33429. if (updatedEnd !== endBlock) {
  33430. updatedBlocks[endKey] = updatedEnd;
  33431. }
  33432. if (!Object.keys(updatedBlocks).length) {
  33433. return contentState.set('selectionAfter', selectionState);
  33434. }
  33435. return contentState.merge({
  33436. blockMap: blockMap.merge(updatedBlocks),
  33437. selectionAfter: selectionState
  33438. });
  33439. }
  33440. function getRemovalRange(characters, key, offset) {
  33441. var removalRange;
  33442. findRangesImmutable(characters, function (a, b) {
  33443. return a.getEntity() === b.getEntity();
  33444. }, function (element) {
  33445. return element.getEntity() === key;
  33446. }, function (start, end) {
  33447. if (start <= offset && end >= offset) {
  33448. removalRange = { start: start, end: end };
  33449. }
  33450. });
  33451. !(typeof removalRange === 'object') ? invariant(false) : void 0;
  33452. return removalRange;
  33453. }
  33454. function removeForBlock(entityMap, block, offset) {
  33455. var chars = block.getCharacterList();
  33456. var charBefore = offset > 0 ? chars.get(offset - 1) : undefined;
  33457. var charAfter = offset < chars.count() ? chars.get(offset) : undefined;
  33458. var entityBeforeCursor = charBefore ? charBefore.getEntity() : undefined;
  33459. var entityAfterCursor = charAfter ? charAfter.getEntity() : undefined;
  33460. if (entityAfterCursor && entityAfterCursor === entityBeforeCursor) {
  33461. var entity = entityMap.__get(entityAfterCursor);
  33462. if (entity.getMutability() !== 'MUTABLE') {
  33463. var _getRemovalRange = getRemovalRange(chars, entityAfterCursor, offset),
  33464. start = _getRemovalRange.start,
  33465. end = _getRemovalRange.end;
  33466. var current;
  33467. while (start < end) {
  33468. current = chars.get(start);
  33469. chars = chars.set(start, CharacterMetadata.applyEntity(current, null));
  33470. start++;
  33471. }
  33472. return block.set('characterList', chars);
  33473. }
  33474. }
  33475. return block;
  33476. }
  33477. module.exports = removeEntitiesAtEdges;
  33478. /***/ }),
  33479. /* 35 */
  33480. /***/ (function(module, exports, __webpack_require__) {
  33481. function invariant(condition, format, a, b, c, d, e, f) {
  33482. if (!condition) {
  33483. var error;
  33484. if (format === undefined) {
  33485. error = new Error('Minified exception occurred; use the non-minified dev environment ' + 'for the full error message and additional helpful warnings.');
  33486. } else {
  33487. var args = [a, b, c, d, e, f];
  33488. var argIndex = 0;
  33489. error = new Error(format.replace(/%s/g, function () {
  33490. return args[argIndex++];
  33491. }));
  33492. error.name = 'Invariant Violation';
  33493. }
  33494. error.framesToPop = 1; // we don't care about invariant's own frame
  33495. throw error;
  33496. }
  33497. }
  33498. module.exports = invariant;
  33499. /***/ }),
  33500. /* 36 */
  33501. /***/ (function(module, exports) {
  33502. function _arrayWithHoles(arr) {
  33503. if (Array.isArray(arr)) return arr;
  33504. }
  33505. module.exports = _arrayWithHoles;
  33506. /***/ }),
  33507. /* 37 */
  33508. /***/ (function(module, exports) {
  33509. function _iterableToArrayLimit(arr, i) {
  33510. var _arr = [];
  33511. var _n = true;
  33512. var _d = false;
  33513. var _e = undefined;
  33514. try {
  33515. for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) {
  33516. _arr.push(_s.value);
  33517. if (i && _arr.length === i) break;
  33518. }
  33519. } catch (err) {
  33520. _d = true;
  33521. _e = err;
  33522. } finally {
  33523. try {
  33524. if (!_n && _i["return"] != null) _i["return"]();
  33525. } finally {
  33526. if (_d) throw _e;
  33527. }
  33528. }
  33529. return _arr;
  33530. }
  33531. module.exports = _iterableToArrayLimit;
  33532. /***/ }),
  33533. /* 38 */
  33534. /***/ (function(module, exports) {
  33535. function _nonIterableRest() {
  33536. throw new TypeError("Invalid attempt to destructure non-iterable instance");
  33537. }
  33538. module.exports = _nonIterableRest;
  33539. /***/ }),
  33540. /* 39 */
  33541. /***/ (function(module, __webpack_exports__, __webpack_require__) {
  33542. __webpack_require__.r(__webpack_exports__);
  33543. // EXTERNAL MODULE: ../node_modules/@babel/runtime/helpers/typeof.js
  33544. var helpers_typeof = __webpack_require__(15);
  33545. var typeof_default = /*#__PURE__*/__webpack_require__.n(helpers_typeof);
  33546. // EXTERNAL MODULE: ../node_modules/@babel/runtime/helpers/objectSpread.js
  33547. var objectSpread = __webpack_require__(5);
  33548. var objectSpread_default = /*#__PURE__*/__webpack_require__.n(objectSpread);
  33549. // EXTERNAL MODULE: ../node_modules/@babel/runtime/helpers/objectWithoutProperties.js
  33550. var objectWithoutProperties = __webpack_require__(21);
  33551. var objectWithoutProperties_default = /*#__PURE__*/__webpack_require__.n(objectWithoutProperties);
  33552. // EXTERNAL MODULE: ../node_modules/@babel/runtime/helpers/classCallCheck.js
  33553. var classCallCheck = __webpack_require__(4);
  33554. var classCallCheck_default = /*#__PURE__*/__webpack_require__.n(classCallCheck);
  33555. // EXTERNAL MODULE: ../node_modules/@babel/runtime/helpers/createClass.js
  33556. var createClass = __webpack_require__(7);
  33557. var createClass_default = /*#__PURE__*/__webpack_require__.n(createClass);
  33558. // EXTERNAL MODULE: ../node_modules/@babel/runtime/helpers/possibleConstructorReturn.js
  33559. var possibleConstructorReturn = __webpack_require__(8);
  33560. var possibleConstructorReturn_default = /*#__PURE__*/__webpack_require__.n(possibleConstructorReturn);
  33561. // EXTERNAL MODULE: ../node_modules/@babel/runtime/helpers/getPrototypeOf.js
  33562. var getPrototypeOf = __webpack_require__(9);
  33563. var getPrototypeOf_default = /*#__PURE__*/__webpack_require__.n(getPrototypeOf);
  33564. // EXTERNAL MODULE: ../node_modules/@babel/runtime/helpers/inherits.js
  33565. var inherits = __webpack_require__(10);
  33566. var inherits_default = /*#__PURE__*/__webpack_require__.n(inherits);
  33567. // EXTERNAL MODULE: ../node_modules/@babel/runtime/helpers/assertThisInitialized.js
  33568. var assertThisInitialized = __webpack_require__(1);
  33569. var assertThisInitialized_default = /*#__PURE__*/__webpack_require__.n(assertThisInitialized);
  33570. // EXTERNAL MODULE: ../node_modules/@babel/runtime/helpers/defineProperty.js
  33571. var defineProperty = __webpack_require__(2);
  33572. var defineProperty_default = /*#__PURE__*/__webpack_require__.n(defineProperty);
  33573. // EXTERNAL MODULE: ../node_modules/@babel/runtime/helpers/toConsumableArray.js
  33574. var toConsumableArray = __webpack_require__(12);
  33575. var toConsumableArray_default = /*#__PURE__*/__webpack_require__.n(toConsumableArray);
  33576. // EXTERNAL MODULE: ../node_modules/draft-js/dist/Draft.css
  33577. var Draft = __webpack_require__(40);
  33578. // EXTERNAL MODULE: ./assets/scss/_base.scss
  33579. var _base = __webpack_require__(42);
  33580. // EXTERNAL MODULE: external "react"
  33581. var external_react_ = __webpack_require__(0);
  33582. var external_react_default = /*#__PURE__*/__webpack_require__.n(external_react_);
  33583. // CONCATENATED MODULE: ./languages/en.js
  33584. /* harmony default export */ var en = ({
  33585. base: {
  33586. remove: 'Remove',
  33587. cancel: 'Cancel',
  33588. confirm: 'Confirm',
  33589. inert: 'Insert',
  33590. width: 'Width',
  33591. height: 'Height'
  33592. },
  33593. controls: {
  33594. clear: 'Clear',
  33595. undo: 'Undo',
  33596. redo: 'Redo',
  33597. fontSize: 'Font Size',
  33598. color: 'Color',
  33599. textColor: 'Text',
  33600. tempColors: 'Temp Colors',
  33601. backgroundColor: 'Background',
  33602. bold: 'Bold',
  33603. lineHeight: 'Line Height',
  33604. letterSpacing: 'Letter Spacing',
  33605. textIndent: 'Text Indent',
  33606. increaseIndent: 'Increase Indent',
  33607. decreaseIndent: 'Decrease Indent',
  33608. italic: 'Italic',
  33609. underline: 'Underline',
  33610. strikeThrough: 'Strike Through',
  33611. fontFamily: 'Font Family',
  33612. textAlign: 'Text Alignment',
  33613. alignLeft: 'Left Alignment',
  33614. alignCenter: 'Center Alignment',
  33615. alignRight: 'Right Alignment',
  33616. alignJustify: 'Justify Alignment',
  33617. floatLeft: 'Left Float',
  33618. floatRight: 'Right Float',
  33619. superScript: 'Super Script',
  33620. subScript: 'Sub Script',
  33621. removeStyles: 'Remove Styles',
  33622. headings: 'Headings',
  33623. header: 'Header',
  33624. normal: 'Normal',
  33625. orderedList: 'Ordered List',
  33626. unorderedList: 'Unordered List',
  33627. blockQuote: 'Quote',
  33628. code: 'Code',
  33629. link: 'Link',
  33630. unlink: 'Unlink',
  33631. hr: 'Horizontal Line',
  33632. media: 'Media',
  33633. mediaLibirary: 'Media Library',
  33634. emoji: 'Emoji',
  33635. fullscreen: 'Fullscreen',
  33636. exitFullscreen: 'Exit Fullscreen'
  33637. },
  33638. linkEditor: {
  33639. textInputPlaceHolder: 'Input link text',
  33640. linkInputPlaceHolder: 'Input link URL',
  33641. inputWithEnterPlaceHolder: 'Input link URL and press Enter',
  33642. openInNewWindow: 'Open in new window',
  33643. removeLink: 'Remove Link'
  33644. },
  33645. audioPlayer: {
  33646. title: 'Play Audio'
  33647. },
  33648. videoPlayer: {
  33649. title: 'Play Video',
  33650. embedTitle: 'Embed Media'
  33651. },
  33652. media: {
  33653. image: 'Image',
  33654. video: 'Video',
  33655. audio: 'Audio',
  33656. embed: 'Embed'
  33657. }
  33658. });
  33659. // CONCATENATED MODULE: ./languages/zh.js
  33660. /* harmony default export */ var zh = ({
  33661. base: {
  33662. remove: '删除',
  33663. cancel: '取消',
  33664. confirm: '确定',
  33665. inert: '插入',
  33666. width: '宽度',
  33667. height: '高度'
  33668. },
  33669. controls: {
  33670. clear: '清除内容',
  33671. undo: '撤销',
  33672. redo: '重做',
  33673. fontSize: '字号',
  33674. lineHeight: '行高',
  33675. letterSpacing: '字间距',
  33676. textIndent: '段落缩进',
  33677. increaseIndent: '增加缩进',
  33678. decreaseIndent: '减少缩进',
  33679. border: '边框',
  33680. color: '颜色',
  33681. textColor: '文字颜色',
  33682. backgroundColor: '背景颜色',
  33683. tempColors: '临时颜色',
  33684. bold: '加粗',
  33685. italic: '斜体',
  33686. underline: '下划线',
  33687. strikeThrough: '删除线',
  33688. fontFamily: '字体',
  33689. textAlign: '文本对齐',
  33690. alignLeft: '居左',
  33691. alignCenter: '居中',
  33692. alignRight: '居右',
  33693. alignJustify: '两端',
  33694. floatLeft: '左浮动',
  33695. floatRight: '右浮动',
  33696. superScript: '上标',
  33697. subScript: '下标',
  33698. removeStyles: '清除样式',
  33699. headings: '标题',
  33700. header: '标题',
  33701. normal: '常规',
  33702. orderedList: '有序列表',
  33703. unorderedList: '无序列表',
  33704. blockQuote: '引用',
  33705. code: '代码',
  33706. link: '链接',
  33707. unlink: '清除链接',
  33708. hr: '水平线',
  33709. media: '媒体',
  33710. mediaLibirary: '媒体库',
  33711. emoji: '小表情',
  33712. fullscreen: '全屏',
  33713. exitFullscreen: '退出全屏'
  33714. },
  33715. linkEditor: {
  33716. textInputPlaceHolder: '输入链接文字',
  33717. linkInputPlaceHolder: '输入链接地址',
  33718. inputWithEnterPlaceHolder: '输入链接地址并回车',
  33719. openInNewWindow: '在新窗口打开',
  33720. removeLink: '移除链接'
  33721. },
  33722. audioPlayer: {
  33723. title: '播放音频文件'
  33724. },
  33725. videoPlayer: {
  33726. title: '播放视频文件',
  33727. embedTitle: '嵌入式媒体'
  33728. },
  33729. media: {
  33730. image: '图像',
  33731. video: '视频',
  33732. audio: '音频',
  33733. embed: '嵌入式媒体'
  33734. }
  33735. });
  33736. // CONCATENATED MODULE: ./languages/zh-hant.js
  33737. /* harmony default export */ var zh_hant = ({
  33738. base: {
  33739. remove: '刪除',
  33740. cancel: '取消',
  33741. confirm: '確定',
  33742. inert: '插入',
  33743. width: '宽度',
  33744. height: '高度'
  33745. },
  33746. controls: {
  33747. clear: '清除内容',
  33748. undo: '撤銷',
  33749. redo: '重做',
  33750. fontSize: '字號',
  33751. color: '顏色',
  33752. textColor: '文字顏色',
  33753. backgroundColor: '背景顏色',
  33754. tempColors: '臨時顏色',
  33755. bold: '加粗',
  33756. lineHeight: '行高',
  33757. letterSpacing: '字間距',
  33758. textIndent: '段落縮進',
  33759. increaseIndent: '增加縮進',
  33760. decreaseIndent: '减少縮進',
  33761. border: '邊框',
  33762. italic: '斜體',
  33763. underline: '下劃線',
  33764. strikeThrough: '刪除線',
  33765. fontFamily: '字體',
  33766. textAlign: '文本對齊',
  33767. alignLeft: '居左',
  33768. alignCenter: '居中',
  33769. alignRight: '居右',
  33770. alignJustify: '兩端對齊',
  33771. floatLeft: '左浮動',
  33772. floatRight: '右浮動',
  33773. superScript: '上標',
  33774. subScript: '下標',
  33775. removeStyles: '清除样式',
  33776. headings: '標題',
  33777. header: '標題',
  33778. normal: '常規',
  33779. orderedList: '有序列表',
  33780. unorderedList: '無序列表',
  33781. blockQuote: '引用',
  33782. code: '代碼',
  33783. link: '鏈接',
  33784. unlink: '清除鏈接',
  33785. hr: '水平线',
  33786. media: '媒體',
  33787. mediaLibirary: '媒體库',
  33788. emoji: '小表情',
  33789. fullscreen: '全熒幕',
  33790. exitFullscreen: '退出全熒幕'
  33791. },
  33792. linkEditor: {
  33793. textInputPlaceHolder: '輸入鏈接文字',
  33794. linkInputPlaceHolder: '輸入鏈接地址',
  33795. inputWithEnterPlaceHolder: '輸入鏈接地址並回車',
  33796. openInNewWindow: '在新窗口打開',
  33797. removeLink: '移除鏈接'
  33798. },
  33799. audioPlayer: {
  33800. title: '播放音頻文件'
  33801. },
  33802. videoPlayer: {
  33803. title: '播放視頻文件',
  33804. embedTitle: '嵌入式媒體'
  33805. },
  33806. media: {
  33807. image: '圖像',
  33808. video: '視頻',
  33809. audio: '音頻',
  33810. embed: '嵌入式媒體'
  33811. }
  33812. });
  33813. // CONCATENATED MODULE: ./languages/pl.js
  33814. /* harmony default export */ var pl = ({
  33815. base: {
  33816. remove: 'Usuń',
  33817. cancel: 'Anuluj',
  33818. confirm: 'Potwierdź',
  33819. inert: 'Wstaw',
  33820. width: 'Szerokość',
  33821. height: 'Wysokość'
  33822. },
  33823. controls: {
  33824. clear: 'Wyczyść',
  33825. undo: 'Cofnij',
  33826. redo: 'Przywróć',
  33827. fontSize: 'Wielkość',
  33828. color: 'Kolor',
  33829. textColor: 'Kolor tekstu',
  33830. tempColors: 'Kolory',
  33831. backgroundColor: 'Tło',
  33832. bold: 'Pogrubienie',
  33833. lineHeight: 'Wysokość linii',
  33834. letterSpacing: 'Odstęp znaków',
  33835. textIndent: 'Wcięcie tekstu',
  33836. increaseIndent: 'Zwiększ wcięcie',
  33837. decreaseIndent: 'Zmniejsz wcięcie',
  33838. italic: 'Italiki',
  33839. underline: 'Podkreślenie',
  33840. strikeThrough: 'Przekreślenie',
  33841. fontFamily: 'Czcionka',
  33842. textAlign: 'Wyrównanie tekstu',
  33843. alignLeft: 'Do lewej',
  33844. alignCenter: 'Wycentruj',
  33845. alignRight: 'Do prawej',
  33846. alignJustify: 'Wyjustuj',
  33847. floatLeft: 'Do lewej',
  33848. floatRight: 'Do prawej',
  33849. superScript: 'Superskrypt',
  33850. subScript: 'Subskrypt',
  33851. removeStyles: 'Usuń stylowanie',
  33852. headings: 'Nagłówki',
  33853. header: 'Nagłówek',
  33854. normal: 'Normalny',
  33855. orderedList: 'Lista uporządkowana',
  33856. unorderedList: 'Lista nieuporządkowana',
  33857. blockQuote: 'Cytat',
  33858. code: 'Kod',
  33859. link: 'Link',
  33860. unlink: 'Usuń link',
  33861. hr: 'Linia pozioma',
  33862. media: 'Media',
  33863. mediaLibirary: 'Biblioteka mediów',
  33864. emoji: 'Emoji'
  33865. },
  33866. linkEditor: {
  33867. textInputPlaceHolder: 'Wpisz tekst linku',
  33868. linkInputPlaceHolder: 'Wpisz Adres URL',
  33869. inputWithEnterPlaceHolder: 'Wpisz adres URL i naciśnij Enter',
  33870. openInNewWindow: 'Otwórz w nowym oknie',
  33871. removeLink: 'Usuń link'
  33872. },
  33873. audioPlayer: {
  33874. title: 'Odtwórz audio'
  33875. },
  33876. videoPlayer: {
  33877. title: 'Odtwórz wideo',
  33878. embedTitle: 'Tytuł'
  33879. },
  33880. media: {
  33881. image: 'Obraz',
  33882. video: 'Wideo',
  33883. audio: 'Audio',
  33884. embed: 'Obiekt osadzony'
  33885. }
  33886. });
  33887. // CONCATENATED MODULE: ./languages/kr.js
  33888. /* harmony default export */ var kr = ({
  33889. base: {
  33890. remove: '삭제',
  33891. cancel: '취소',
  33892. confirm: '결정',
  33893. inert: '삽입',
  33894. width: '너비',
  33895. height: '높이'
  33896. },
  33897. controls: {
  33898. clear: '콘텐츠지우기',
  33899. undo: '취소',
  33900. redo: '다시하기',
  33901. fontSize: '글자크기',
  33902. lineHeight: '행높이',
  33903. letterSpacing: '단어간격',
  33904. textIndent: '단락들여쓰기',
  33905. increaseIndent: '들여쓰기늘리기',
  33906. decreaseIndent: '들여쓰기줄이기',
  33907. border: '국경',
  33908. color: '색상',
  33909. textColor: '텍스트색상',
  33910. backgroundColor: '배경색상',
  33911. tempColors: '임시색',
  33912. bold: '굵게',
  33913. italic: '기울임꼴',
  33914. underline: '밑줄',
  33915. strikeThrough: '취소선',
  33916. fontFamily: '글꼴',
  33917. textAlign: '텍스트정렬',
  33918. alignLeft: '왼쪽',
  33919. alignCenter: '중심',
  33920. alignRight: '오른쪽',
  33921. alignJustify: '양쪽끝',
  33922. floatLeft: '떠다니기',
  33923. floatRight: '오른쪽부동',
  33924. superScript: '위첨자',
  33925. subScript: '첨자',
  33926. removeStyles: '스타일지우기',
  33927. headings: '제목',
  33928. header: '제목',
  33929. normal: '재래식',
  33930. orderedList: '순서가지정된목록',
  33931. unorderedList: '정렬되지않은목록',
  33932. blockQuote: '참고문헌',
  33933. code: '코드',
  33934. link: '링크',
  33935. unlink: '링크삭제',
  33936. hr: '수평선',
  33937. media: '미디어',
  33938. mediaLibirary: '미디어라이브러리',
  33939. emoji: '작은표현',
  33940. fullscreen: '전체화면',
  33941. exitFullscreen: '전체화면종료'
  33942. },
  33943. linkEditor: {
  33944. textInputPlaceHolder: '링크텍스트입력',
  33945. linkInputPlaceHolder: '링크주소입력',
  33946. inputWithEnterPlaceHolder: '링크주소입력.',
  33947. openInNewWindow: '새창열기',
  33948. removeLink: '링크삭제'
  33949. },
  33950. audioPlayer: {
  33951. title: '오디오파일재생'
  33952. },
  33953. videoPlayer: {
  33954. title: '비디오파일재생',
  33955. embedTitle: '임베디드미디어'
  33956. },
  33957. media: {
  33958. image: '이미지',
  33959. video: '비디오',
  33960. audio: '오디오',
  33961. embed: '임베디드미디어'
  33962. }
  33963. });
  33964. // CONCATENATED MODULE: ./languages/tr.js
  33965. /* harmony default export */ var tr = ({
  33966. base: {
  33967. remove: 'Kaldır',
  33968. cancel: 'İptal',
  33969. confirm: 'Onayla',
  33970. inert: 'Ekle',
  33971. width: 'Genişlik',
  33972. height: 'Yükseklik'
  33973. },
  33974. controls: {
  33975. clear: 'Temizle',
  33976. undo: 'Geri al',
  33977. redo: 'İleri al',
  33978. fontSize: 'Yazı boyutu',
  33979. color: 'Renk',
  33980. textColor: 'Yazı rengi',
  33981. tempColors: 'Geçici renkler',
  33982. backgroundColor: 'Arkaplan',
  33983. bold: 'Kalın',
  33984. lineHeight: 'Satır yüksekliği',
  33985. letterSpacing: 'Harf aralığı',
  33986. textIndent: 'Çentik aralığı',
  33987. increaseIndent: 'Çentiği genişlet',
  33988. decreaseIndent: 'Çentiği daralt',
  33989. italic: 'Eğik',
  33990. underline: 'Altı çizili',
  33991. strikeThrough: 'Üstü çizili',
  33992. fontFamily: 'Yazı tipi',
  33993. textAlign: 'Metin Hizalama',
  33994. alignLeft: 'Sola hizala',
  33995. alignCenter: 'Ortaya hizala',
  33996. alignRight: 'Sağa hizala',
  33997. alignJustify: 'Her iki tarafa hizala',
  33998. floatLeft: 'Sola yatır',
  33999. floatRight: 'Sağa yatır',
  34000. superScript: 'Ana kod',
  34001. subScript: 'Alt kod',
  34002. removeStyles: 'Stilleri kaldır',
  34003. headings: 'Başlıklar',
  34004. header: 'Başlık',
  34005. normal: 'Normal',
  34006. orderedList: 'Sıralı liste',
  34007. unorderedList: 'Sırasız liste',
  34008. blockQuote: 'Alıntı',
  34009. code: 'Kod',
  34010. link: 'Bağlantı',
  34011. unlink: 'Bağlantıyı kaldır',
  34012. hr: 'Yatay çizgi',
  34013. media: 'Medya',
  34014. mediaLibirary: 'Kütüphane',
  34015. emoji: 'İfade',
  34016. fullscreen: 'Tam ekran',
  34017. exitFullscreen: 'Tam ekrandan çık'
  34018. },
  34019. linkEditor: {
  34020. textInputPlaceHolder: 'Bağlantı metnini girin',
  34021. linkInputPlaceHolder: 'Bağlantı URL\' si girin',
  34022. inputWithEnterPlaceHolder: 'Bağlantı URL\'si girin ve Enter\' a basın',
  34023. openInNewWindow: 'Yeni pencerede aç',
  34024. removeLink: 'Bağlantıyı kaldır'
  34025. },
  34026. audioPlayer: {
  34027. title: 'Ses çal'
  34028. },
  34029. videoPlayer: {
  34030. title: 'Görüntü oynat',
  34031. embedTitle: 'Görüntüyü göm'
  34032. },
  34033. media: {
  34034. image: 'Resim',
  34035. video: 'Görüntü',
  34036. audio: 'Ses',
  34037. embed: 'Gömülü nesne'
  34038. }
  34039. });
  34040. // CONCATENATED MODULE: ./languages/jpn.js
  34041. /* harmony default export */ var jpn = ({
  34042. base: {
  34043. remove: '削除',
  34044. cancel: 'キャンセル',
  34045. confirm: '決定',
  34046. inert: '挿入',
  34047. width: '幅',
  34048. height: '高さ'
  34049. },
  34050. controls: {
  34051. clear: 'クリアコンテンツ',
  34052. undo: 'キャンセル',
  34053. redo: 'キャンセル',
  34054. fontSize: 'フォントサイズ',
  34055. lineHeight: 'フォントサイズ',
  34056. letterSpacing: 'ワード間隔',
  34057. textIndent: '段落のインデント',
  34058. increaseIndent: 'インデントを増やす',
  34059. decreaseIndent: 'インデントを減らす',
  34060. border: '国境',
  34061. color: '色',
  34062. textColor: 'テキストの色',
  34063. backgroundColor: '背景色',
  34064. tempColors: '仮色',
  34065. bold: '太字',
  34066. italic: 'イタリック体',
  34067. underline: '下線',
  34068. strikeThrough: '取り消し線',
  34069. fontFamily: 'フォント',
  34070. textAlign: 'テキストの配置',
  34071. alignLeft: '左',
  34072. alignCenter: '中央揃え',
  34073. alignRight: '右に立つ',
  34074. alignJustify: '両端',
  34075. floatLeft: '左フローティング',
  34076. floatRight: '右フローティング',
  34077. superScript: '上付き',
  34078. subScript: '下付き文字',
  34079. removeStyles: 'クリアスタイル',
  34080. headings: '役職',
  34081. header: '役職',
  34082. normal: '従来の',
  34083. orderedList: '順序付きリスト',
  34084. unorderedList: '番号なしリスト',
  34085. blockQuote: '参照',
  34086. code: 'コード',
  34087. link: 'リンク',
  34088. unlink: 'リンクを解除',
  34089. hr: '横線',
  34090. media: 'メディア',
  34091. mediaLibirary: 'メディアライブラリー',
  34092. emoji: '小さな表現',
  34093. fullscreen: '全画面',
  34094. exitFullscreen: '全画面を退く'
  34095. },
  34096. linkEditor: {
  34097. textInputPlaceHolder: 'リンクテキストを入力',
  34098. linkInputPlaceHolder: 'リンクアドレスを入力',
  34099. inputWithEnterPlaceHolder: 'リンクアドレスを入力して戻ります',
  34100. openInNewWindow: '新しいウィンドウで開く',
  34101. removeLink: '新しいウィンドウで開く'
  34102. },
  34103. audioPlayer: {
  34104. title: 'オーディオファイルを再生する'
  34105. },
  34106. videoPlayer: {
  34107. title: 'ビデオファイルを再生する',
  34108. embedTitle: '埋め込みメディア'
  34109. },
  34110. media: {
  34111. image: '画像',
  34112. video: 'ビデオ',
  34113. audio: '音声',
  34114. embed: '埋め込みメディア'
  34115. }
  34116. });
  34117. // CONCATENATED MODULE: ./languages/ru.js
  34118. /* harmony default export */ var ru = ({
  34119. base: {
  34120. remove: 'Удалить',
  34121. cancel: 'Отмена',
  34122. confirm: 'Подтвердить',
  34123. insert: 'Вставить',
  34124. width: 'Ширина',
  34125. height: 'Высота'
  34126. },
  34127. controls: {
  34128. clear: 'Очистить',
  34129. undo: 'Отменить',
  34130. redo: 'Повторить',
  34131. fontSize: 'Размер шрифта',
  34132. color: 'Цвет',
  34133. textColor: 'Цвет текста',
  34134. tempColors: 'Temp Colors',
  34135. backgroundColor: 'Цвет фона',
  34136. bold: 'Жирный',
  34137. lineHeight: 'Межстрочный интервал',
  34138. letterSpacing: 'Межбуквенный интервал',
  34139. textIndent: 'Отступ',
  34140. increaseIndent: 'Увеличить отступ',
  34141. decreaseIndent: 'Уменьшить отступ',
  34142. italic: 'Курсив',
  34143. underline: 'Подчеркнутый',
  34144. strikeThrough: 'Перечеркнутый',
  34145. fontFamily: 'Шрифт',
  34146. textAlign: 'Расположение текста',
  34147. alignLeft: 'По левому краю',
  34148. alignCenter: 'По центру',
  34149. alignRight: 'По правому краю',
  34150. alignJustify: 'По ширине',
  34151. floatLeft: 'Обтекание слева',
  34152. floatRight: 'Обтекание справа',
  34153. superScript: 'Надстрочный индекс',
  34154. subScript: 'Подстрочный индекс',
  34155. removeStyles: 'Убрать стили',
  34156. headings: 'Заголовки',
  34157. header: 'Заголовок',
  34158. normal: 'Обычный',
  34159. orderedList: 'Упорядоченный список',
  34160. unorderedList: 'Неупорядоченный список',
  34161. blockQuote: 'Цитата',
  34162. code: 'Код',
  34163. link: 'Вставить ссылку',
  34164. unlink: 'Убрать ссылку',
  34165. hr: 'Горизонтальная линия',
  34166. media: 'Медиа',
  34167. mediaLibirary: 'Медиа библиотека',
  34168. emoji: 'Emoji',
  34169. fullscreen: 'Полноэкранный режим',
  34170. exitFullscreen: 'Выйти из полноэкранного режима'
  34171. },
  34172. linkEditor: {
  34173. textInputPlaceHolder: 'Введите текст ссылки',
  34174. linkInputPlaceHolder: 'Вставить ссылку',
  34175. inputWithEnterPlaceHolder: 'Вставить ссылку и нажать Enter',
  34176. openInNewWindow: 'Открыть в новом окне',
  34177. removeLink: 'Убрать ссылку'
  34178. },
  34179. audioPlayer: {
  34180. title: 'Воспроизвести аудиофайл'
  34181. },
  34182. videoPlayer: {
  34183. title: 'Воспроизвести видеофайл',
  34184. embedTitle: 'Embed Media'
  34185. },
  34186. media: {
  34187. image: 'Картинка',
  34188. video: 'Видео',
  34189. audio: 'Аудио',
  34190. embed: 'Встроенное'
  34191. }
  34192. });
  34193. // CONCATENATED MODULE: ./languages/fr.js
  34194. /* harmony default export */ var fr = ({
  34195. base: {
  34196. remove: 'Supprimer',
  34197. cancel: 'Annuler',
  34198. confirm: 'Confirmer',
  34199. inert: 'Insérer',
  34200. width: 'Largeur',
  34201. height: 'Hauteur'
  34202. },
  34203. controls: {
  34204. clear: 'Effacer',
  34205. undo: 'Annuler',
  34206. redo: 'Refaire',
  34207. fontSize: 'Taille de police',
  34208. color: 'Couleur',
  34209. textColor: 'Texte',
  34210. tempColors: 'Couleurs temporaire',
  34211. backgroundColor: 'Couleur d\'arrière plan',
  34212. bold: 'Gras',
  34213. lineHeight: 'Hauteur de ligne',
  34214. letterSpacing: 'Espacement des lettres',
  34215. textIndent: 'Indentation du texte',
  34216. increaseIndent: 'Augmenter l\'indentation',
  34217. decreaseIndent: 'Réduire l\'indentation',
  34218. italic: 'Italique',
  34219. underline: 'Souligner',
  34220. strikeThrough: 'Barrer',
  34221. fontFamily: 'Police d\'écriture',
  34222. textAlign: 'Alignement du texte',
  34223. alignLeft: 'Aligner à gauche',
  34224. alignCenter: 'Aligner au centre',
  34225. alignRight: 'Aligner à droite',
  34226. alignJustify: 'Justifier',
  34227. floatLeft: 'Déplacer à gauche',
  34228. floatRight: 'Déplacer à droite',
  34229. superScript: 'Super-script',
  34230. subScript: 'Sous-script',
  34231. removeStyles: 'Supprimer les styles',
  34232. headings: 'Titres',
  34233. header: 'Entêtes',
  34234. normal: 'Normal',
  34235. orderedList: 'Liste ordonnée',
  34236. unorderedList: 'Liste non-ordonnée',
  34237. blockQuote: 'Citation',
  34238. code: 'Code',
  34239. link: 'Insérer un lien',
  34240. unlink: 'Supprimer le lien',
  34241. hr: 'Ligne horizontale',
  34242. media: 'Média',
  34243. mediaLibirary: 'Bibliothêque',
  34244. emoji: 'Emoji',
  34245. fullscreen: 'Plein écran',
  34246. exitFullscreen: 'Quitter le plein écran'
  34247. },
  34248. linkEditor: {
  34249. textInputPlaceHolder: 'Insérer le texte à afficher',
  34250. linkInputPlaceHolder: 'Insérer le lien URL',
  34251. inputWithEnterPlaceHolder: 'Insérer le lien URL puis appuyer sur Entrée',
  34252. openInNewWindow: 'Ouvrir dans une nouvelle fenêtre',
  34253. removeLink: 'Supprimer le lien'
  34254. },
  34255. audioPlayer: {
  34256. title: 'Lancer le son audio'
  34257. },
  34258. videoPlayer: {
  34259. title: 'Lancer la video',
  34260. embedTitle: 'Intégrer média'
  34261. },
  34262. media: {
  34263. image: 'Image',
  34264. video: 'Vidéo',
  34265. audio: 'Audio',
  34266. embed: 'Intégré'
  34267. }
  34268. });
  34269. // CONCATENATED MODULE: ./languages/pt-br.js
  34270. /* harmony default export */ var pt_br = ({
  34271. base: {
  34272. remove: 'Remover',
  34273. cancel: 'Cancelar',
  34274. confirm: 'Confirmar',
  34275. inert: 'Inserir',
  34276. width: 'Largura',
  34277. height: 'Altura'
  34278. },
  34279. controls: {
  34280. clear: 'Limpar',
  34281. undo: 'Desfazer',
  34282. redo: 'Refazer',
  34283. fontSize: 'Tamanho da Fonte',
  34284. color: 'Cor',
  34285. textColor: 'Texto',
  34286. tempColors: 'Temp Colors',
  34287. backgroundColor: 'Cor de Fundo',
  34288. bold: 'Negrito',
  34289. lineHeight: 'Altura da LinhaLine Height',
  34290. letterSpacing: 'Espaçamento entre Letras',
  34291. textIndent: 'Identação de Texto',
  34292. increaseIndent: 'Aumentar Identação',
  34293. decreaseIndent: 'Diminuir Identção',
  34294. italic: 'Itálico',
  34295. underline: 'Sublinhado',
  34296. strikeThrough: 'Riscado',
  34297. fontFamily: 'Família da Fonte',
  34298. textAlign: 'Alinhamento de Texto',
  34299. alignLeft: 'Alinhamento à Esquerda',
  34300. alignCenter: 'Alinhamento Centralizado',
  34301. alignRight: 'Alinhamento à Direita',
  34302. alignJustify: 'Alinhamento Justificado',
  34303. floatLeft: 'Flutuação à Esquerda',
  34304. floatRight: 'Flutuação à Direita',
  34305. superScript: 'Sobrescrito',
  34306. subScript: 'Subscrito',
  34307. removeStyles: 'Remover Estilos',
  34308. headings: 'Cabeçalhos',
  34309. header: 'Cabeçalho',
  34310. normal: 'Normal',
  34311. orderedList: 'Lista Ordenada',
  34312. unorderedList: 'Lista Não Ordenada',
  34313. blockQuote: 'Citação',
  34314. code: 'Código',
  34315. link: 'Link',
  34316. unlink: 'Remover Link',
  34317. hr: 'Linha Horizontal',
  34318. media: 'Mídia',
  34319. mediaLibirary: 'Biblioteca de Mídia',
  34320. emoji: 'Emoji',
  34321. fullscreen: 'Tela Cheia',
  34322. exitFullscreen: 'Sair de Tela Cheia'
  34323. },
  34324. linkEditor: {
  34325. textInputPlaceHolder: 'Insira o texto do link',
  34326. linkInputPlaceHolder: 'Insira a URL do link',
  34327. inputWithEnterPlaceHolder: 'Insira a URL do link e aperte Enter',
  34328. openInNewWindow: 'Abrir em nova janela',
  34329. removeLink: 'Remover Link'
  34330. },
  34331. audioPlayer: {
  34332. title: 'Tocar Áudio'
  34333. },
  34334. videoPlayer: {
  34335. title: 'Tocar Vídeo',
  34336. embedTitle: 'Mídia Embutida'
  34337. },
  34338. media: {
  34339. image: 'Imagem',
  34340. video: 'Vídeo',
  34341. audio: 'Áudio',
  34342. embed: 'Embutido'
  34343. }
  34344. });
  34345. // CONCATENATED MODULE: ./languages/index.js
  34346. /* harmony default export */ var languages = ({
  34347. 'en': en,
  34348. 'zh': zh,
  34349. 'zh-hant': zh_hant,
  34350. 'pl': pl,
  34351. 'kr': kr,
  34352. 'tr': tr,
  34353. 'jpn': jpn,
  34354. 'ru': ru,
  34355. 'fr': fr,
  34356. 'pt-br': pt_br
  34357. });
  34358. // EXTERNAL MODULE: external "braft-finder"
  34359. var external_braft_finder_ = __webpack_require__(17);
  34360. var external_braft_finder_default = /*#__PURE__*/__webpack_require__.n(external_braft_finder_);
  34361. // EXTERNAL MODULE: external "braft-utils"
  34362. var external_braft_utils_ = __webpack_require__(3);
  34363. // EXTERNAL MODULE: external "draft-js"
  34364. var external_draft_js_ = __webpack_require__(6);
  34365. // EXTERNAL MODULE: external "immutable"
  34366. var external_immutable_ = __webpack_require__(13);
  34367. var external_immutable_default = /*#__PURE__*/__webpack_require__.n(external_immutable_);
  34368. // CONCATENATED MODULE: ./configs/keybindings.js
  34369. // TODO
  34370. // 允许自定义的快捷键设置
  34371. /* harmony default export */ var keybindings = (function (customKeyBindingFn) {
  34372. return function (event) {
  34373. if (event.keyCode === 83 && (external_draft_js_["KeyBindingUtil"].hasCommandModifier(event) || external_draft_js_["KeyBindingUtil"].isCtrlKeyCommand(event))) {
  34374. return 'braft-save';
  34375. }
  34376. if (customKeyBindingFn) {
  34377. return customKeyBindingFn(event) || Object(external_draft_js_["getDefaultKeyBinding"])(event);
  34378. }
  34379. return Object(external_draft_js_["getDefaultKeyBinding"])(event);
  34380. };
  34381. });
  34382. // CONCATENATED MODULE: ./configs/props.js
  34383. /* harmony default export */ var configs_props = ({
  34384. language: 'zh',
  34385. controls: ['undo', 'redo', 'separator', 'font-size', 'line-height', 'letter-spacing', 'separator', 'text-color', 'bold', 'italic', 'underline', 'strike-through', 'separator', 'superscript', 'subscript', 'remove-styles', 'emoji', 'separator', 'text-indent', 'text-align', 'separator', 'headings', 'list-ul', 'list-ol', 'blockquote', 'code', 'separator', 'media', 'link', 'table', 'split', 'hr', 'separator', 'clear', 'separator', 'fullscreen'],
  34386. excludeControls: [],
  34387. extendControls: [],
  34388. extendAtomics: [],
  34389. componentBelowControlBar: null,
  34390. media: {
  34391. pasteImage: true,
  34392. imagePasteLimit: 5,
  34393. image: true,
  34394. video: true,
  34395. audio: true,
  34396. uploadFn: null,
  34397. validateFn: null,
  34398. onBeforeDeselect: null,
  34399. onDeselect: null,
  34400. onBeforeSelect: null,
  34401. onSelect: null,
  34402. onBeforeRemove: null,
  34403. onRemove: null,
  34404. onCancel: null,
  34405. onFileSelect: null,
  34406. onBeforeInsert: null,
  34407. onInsert: null,
  34408. onChange: null,
  34409. accepts: {
  34410. image: 'image/png,image/jpeg,image/gif,image/webp,image/apng,image/svg',
  34411. video: 'video/mp4',
  34412. audio: 'audio/mp3'
  34413. },
  34414. externals: {
  34415. audio: true,
  34416. video: true,
  34417. image: true,
  34418. embed: true
  34419. }
  34420. },
  34421. imageControls: ['float-left', 'float-right', 'align-left', 'align-center', 'align-right', 'link', 'size', 'remove'],
  34422. imageResizable: true,
  34423. colors: ['#000000', '#333333', '#666666', '#999999', '#cccccc', '#ffffff', '#61a951', '#16a085', '#07a9fe', '#003ba5', '#8e44ad', '#f32784', '#c0392b', '#d35400', '#f39c12', '#fdda00'],
  34424. colorPicker: null,
  34425. colorPickerTheme: 'dark',
  34426. colorPickerAutoHide: true,
  34427. codeTabIndents: 2,
  34428. headings: ['header-one', 'header-two', 'header-three', 'header-four', 'header-five', 'header-six', 'unstyled'],
  34429. textAligns: ['left', 'center', 'right', 'justify'],
  34430. textBackgroundColor: true,
  34431. allowInsertLinkText: false,
  34432. defaultLinkTarget: '',
  34433. letterSpacings: [0, 1, 2, 3, 4, 5, 6],
  34434. lineHeights: [1, 1.2, 1.5, 1.75, 2, 2.5, 3, 4],
  34435. fontSizes: [12, 14, 16, 18, 20, 24, 28, 30, 32, 36, 40, 48, 56, 64, 72, 96, 120, 144],
  34436. fontFamilies: [{
  34437. name: 'Araial',
  34438. family: 'Arial, Helvetica, sans-serif'
  34439. }, {
  34440. name: 'Georgia',
  34441. family: 'Georgia, serif'
  34442. }, {
  34443. name: 'Impact',
  34444. family: 'Impact, serif'
  34445. }, {
  34446. name: 'Monospace',
  34447. family: '"Courier New", Courier, monospace'
  34448. }, {
  34449. name: 'Tahoma',
  34450. family: 'tahoma, arial, "Hiragino Sans GB", 宋体, sans-serif'
  34451. }],
  34452. converts: {
  34453. unitExportFn: function unitExportFn(value, type) {
  34454. return type === 'line-height' ? value : "".concat(value, "px");
  34455. }
  34456. },
  34457. emojis: ['🤣', '🙌', '💚', '💛', '👏', '😉', '💯', '💕', '💞', '💘', '💙', '💝', '🖤', '💜', '❤️', '😍', '😻', '💓', '💗', '😋', '😇', '😂', '😹', '😘', '💖', '😁', '😀', '🤞', '😲', '😄', '😊', '👍', '😌', '😃', '😅', '✌️', '🤗', '💋', '😗', '😽', '😚', '🤠', '😙', '😺', '👄', '😸', '😏', '😼', '👌', '😎', '😆', '😛', '🙏', '🤝', '🙂', '🤑', '😝', '😐', '😑', '🤤', '😤', '🙃', '🤡', '😶', '😪', '😴', '😵', '😓', '👊', '😦', '😷', '🤐', '😜', '🤓', '👻', '😥', '🙄', '🤔', '🤒', '🙁', '😔', '😯', '☹️', '☠️', '😰', '😩', '😖', '😕', '😒', '😣', '😢', '😮', '😿', '🤧', '😫', '🤥', '😞', '😬', '👎', '💀', '😳', '😨', '🤕', '🤢', '😱', '😭', '😠', '😈', '😧', '💔', '😟', '🙀', '💩', '👿', '😡', '😾', '🖕'],
  34458. stripPastedStyles: false,
  34459. triggerChangeOnMount: true,
  34460. className: '',
  34461. style: {},
  34462. controlBarClassName: '',
  34463. controlBarStyle: {},
  34464. contentClassName: '',
  34465. contentStyle: {},
  34466. draftProps: {},
  34467. hooks: {},
  34468. onChange: null,
  34469. onFocus: null,
  34470. onBlur: null,
  34471. onTab: null,
  34472. onDelete: null,
  34473. onSave: null,
  34474. fixPlaceholder: false
  34475. });
  34476. // EXTERNAL MODULE: ../node_modules/draft-js/lib/getFragmentFromSelection.js
  34477. var getFragmentFromSelection = __webpack_require__(22);
  34478. var getFragmentFromSelection_default = /*#__PURE__*/__webpack_require__.n(getFragmentFromSelection);
  34479. // EXTERNAL MODULE: external "draftjs-utils"
  34480. var external_draftjs_utils_ = __webpack_require__(23);
  34481. // CONCATENATED MODULE: ./configs/handlers.js
  34482. var handlers_keyCommandHandlers = function keyCommandHandlers(command, editorState, editor) {
  34483. if (editor.editorProps.handleKeyCommand && editor.editorProps.handleKeyCommand(command, editorState, editor) === 'handled') {
  34484. return 'handled';
  34485. }
  34486. if (command === 'braft-save') {
  34487. editor.editorProps.onSave && editor.editorProps.onSave(editorState);
  34488. return 'handled';
  34489. }
  34490. var _editor$editorProps = editor.editorProps,
  34491. controls = _editor$editorProps.controls,
  34492. excludeControls = _editor$editorProps.excludeControls;
  34493. var allowIndent = (controls.indexOf('text-indent') !== 0 || controls.find(function (item) {
  34494. return item.key === 'text-indent';
  34495. })) && excludeControls.indexOf('text-indent') === -1;
  34496. var cursorStart = editorState.getSelection().getStartOffset();
  34497. var cursorEnd = editorState.getSelection().getEndOffset();
  34498. var cursorIsAtFirst = cursorStart === 0 && cursorEnd === 0;
  34499. if (command === 'backspace') {
  34500. if (editor.editorProps.onDelete && editor.editorProps.onDelete(editorState) === false) {
  34501. return 'handled';
  34502. }
  34503. var blockType = external_braft_utils_["ContentUtils"].getSelectionBlockType(editorState);
  34504. if (allowIndent && cursorIsAtFirst && blockType !== 'code-block') {
  34505. editor.setValue(external_braft_utils_["ContentUtils"].decreaseSelectionIndent(editorState));
  34506. }
  34507. }
  34508. if (command === 'tab') {
  34509. var _blockType = external_braft_utils_["ContentUtils"].getSelectionBlockType(editorState);
  34510. if (_blockType === 'code-block') {
  34511. editor.setValue(external_braft_utils_["ContentUtils"].insertText(editorState, ' '.repeat(editor.editorProps.codeTabIndents)));
  34512. return 'handled';
  34513. } else if (_blockType === 'ordered-list-item' || _blockType === 'unordered-list-item') {
  34514. var newEditorState = external_draft_js_["RichUtils"].onTab(event, editorState, 4);
  34515. if (newEditorState !== editorState) {
  34516. editor.setValue(newEditorState);
  34517. }
  34518. return 'handled';
  34519. } else if (_blockType !== 'atomic' && allowIndent && cursorIsAtFirst) {
  34520. editor.setValue(external_braft_utils_["ContentUtils"].increaseSelectionIndent(editorState));
  34521. return 'handled';
  34522. }
  34523. }
  34524. var nextEditorState = external_braft_utils_["ContentUtils"].handleKeyCommand(editorState, command);
  34525. if (nextEditorState) {
  34526. editor.setValue(nextEditorState);
  34527. return 'handled';
  34528. }
  34529. return 'not-handled';
  34530. };
  34531. var handlers_returnHandlers = function returnHandlers(event, editorState, editor) {
  34532. if (editor.editorProps.handleReturn && editor.editorProps.handleReturn(event, editorState, editor) === 'handled') {
  34533. return 'handled';
  34534. }
  34535. var currentBlock = external_braft_utils_["ContentUtils"].getSelectionBlock(editorState);
  34536. var currentBlockType = currentBlock.getType();
  34537. if (currentBlockType === 'unordered-list-item' || currentBlockType === 'ordered-list-item') {
  34538. if (currentBlock.getLength() === 0) {
  34539. editor.setValue(external_braft_utils_["ContentUtils"].toggleSelectionBlockType(editorState, 'unstyled'));
  34540. return 'handled';
  34541. }
  34542. return 'not-handled';
  34543. } else if (currentBlockType === 'code-block') {
  34544. if (event.which === 13 && (event.getModifierState('Shift') || event.getModifierState('Alt') || event.getModifierState('Control'))) {
  34545. editor.setValue(external_braft_utils_["ContentUtils"].toggleSelectionBlockType(editorState, 'unstyled'));
  34546. return 'handled';
  34547. }
  34548. return 'not-handled';
  34549. } else if (currentBlockType === 'blockquote') {
  34550. if (event.which === 13) {
  34551. if (event.getModifierState('Shift') || event.getModifierState('Alt') || event.getModifierState('Control')) {
  34552. event.which = 0;
  34553. } else {
  34554. editor.setValue(external_draft_js_["RichUtils"].insertSoftNewline(editorState));
  34555. return 'handled';
  34556. }
  34557. }
  34558. }
  34559. var nextEditorState = Object(external_draftjs_utils_["handleNewLine"])(editorState, event);
  34560. if (nextEditorState) {
  34561. editor.setValue(nextEditorState);
  34562. return 'handled';
  34563. }
  34564. return 'not-handled';
  34565. };
  34566. var beforeInputHandlers = function beforeInputHandlers(chars, editorState, editor) {
  34567. if (editor.editorProps.handleBeforeInput && editor.editorProps.handleBeforeInput(chars, editorState, editor) === 'handled') {
  34568. return 'handled';
  34569. }
  34570. return 'not-handled';
  34571. };
  34572. var handlers_compositionStartHandler = function compositionStartHandler(_, editor) {
  34573. var editorState = editor.state.editorState;
  34574. var selectedBlocks = external_braft_utils_["ContentUtils"].getSelectedBlocks(editorState);
  34575. if (selectedBlocks && selectedBlocks.length > 1) {
  34576. var nextEditorState = external_draft_js_["EditorState"].push(editorState, external_draft_js_["Modifier"].removeRange(editorState.getCurrentContent(), editorState.getSelection(), 'backward'), 'remove-range');
  34577. editor.setValue(nextEditorState);
  34578. }
  34579. };
  34580. var handlers_dropHandlers = function dropHandlers(selectionState, dataTransfer, editor) {
  34581. if (editor.editorProps.readOnly || editor.editorProps.disabled) {
  34582. return 'handled';
  34583. }
  34584. if (window && window.__BRAFT_DRAGING__IMAGE__) {
  34585. var nextEditorState = external_draft_js_["EditorState"].forceSelection(editor.state.editorState, selectionState);
  34586. nextEditorState = external_braft_utils_["ContentUtils"].insertMedias(nextEditorState, [window.__BRAFT_DRAGING__IMAGE__.mediaData]);
  34587. nextEditorState = external_braft_utils_["ContentUtils"].removeBlock(nextEditorState, window.__BRAFT_DRAGING__IMAGE__.block, nextEditorState.getSelection());
  34588. window.__BRAFT_DRAGING__IMAGE__ = null;
  34589. editor.lockOrUnlockEditor(true);
  34590. editor.setValue(nextEditorState);
  34591. return 'handled';
  34592. } else if (!dataTransfer || !dataTransfer.getText()) {
  34593. return 'handled';
  34594. }
  34595. return 'not-handled';
  34596. };
  34597. var handlers_handleFiles = function handleFiles(files, editor) {
  34598. var _editor$constructor$d = objectSpread_default()({}, editor.constructor.defaultProps.media, editor.editorProps.media),
  34599. pasteImage = _editor$constructor$d.pasteImage,
  34600. validateFn = _editor$constructor$d.validateFn,
  34601. imagePasteLimit = _editor$constructor$d.imagePasteLimit;
  34602. pasteImage && files.slice(0, imagePasteLimit).forEach(function (file) {
  34603. if (file && file.type.indexOf('image') > -1 && editor.braftFinder) {
  34604. var validateResult = validateFn ? validateFn(file) : true;
  34605. if (validateResult instanceof Promise) {
  34606. validateResult.then(function () {
  34607. editor.braftFinder.uploadImage(file, function (image) {
  34608. editor.isLiving && editor.setValue(external_braft_utils_["ContentUtils"].insertMedias(editor.state.editorState, [image]));
  34609. });
  34610. });
  34611. } else if (validateResult) {
  34612. editor.braftFinder.uploadImage(file, function (image) {
  34613. editor.isLiving && editor.setValue(external_braft_utils_["ContentUtils"].insertMedias(editor.state.editorState, [image]));
  34614. });
  34615. }
  34616. }
  34617. });
  34618. if (files[0] && files[0].type.indexOf('image') > -1 && pasteImage) {
  34619. return 'handled';
  34620. }
  34621. return 'not-handled';
  34622. };
  34623. var droppedFilesHandlers = function droppedFilesHandlers(selectionState, files, editor) {
  34624. if (editor.editorProps.handleDroppedFiles && editor.editorProps.handleDroppedFiles(selectionState, files, editor) === 'handled') {
  34625. return 'handled';
  34626. }
  34627. return handlers_handleFiles(files, editor);
  34628. };
  34629. var pastedFilesHandlers = function pastedFilesHandlers(files, editor) {
  34630. if (editor.editorProps.handlePastedFiles && editor.editorProps.handlePastedFiles(files, editor) === 'handled') {
  34631. return 'handled';
  34632. }
  34633. return handlers_handleFiles(files, editor);
  34634. };
  34635. var handlers_copyHandlers = function copyHandlers(event, editor) {
  34636. var blockMap = getFragmentFromSelection_default()(editor.state.editorState);
  34637. if (blockMap && blockMap.toArray) {
  34638. try {
  34639. var tempContentState = external_draft_js_["ContentState"].createFromBlockArray(blockMap.toArray());
  34640. var tempEditorState = external_draft_js_["EditorState"].createWithContent(tempContentState);
  34641. var clipboardData = event.clipboardData || window.clipboardData || event.originalEvent.clipboardData;
  34642. tempEditorState.setConvertOptions(editor.state.editorState.convertOptions);
  34643. clipboardData.setData('text/html', tempEditorState.toHTML());
  34644. clipboardData.setData('text/plain', tempEditorState.toText());
  34645. event.preventDefault();
  34646. } catch (error) {
  34647. console.warn(error);
  34648. }
  34649. }
  34650. };
  34651. var handlers_pastedTextHandlers = function pastedTextHandlers(text, html, editorState, editor) {
  34652. if (editor.editorProps.handlePastedText && editor.editorProps.handlePastedText(text, html, editorState, editor) === 'handled') {
  34653. return 'handled';
  34654. }
  34655. if (!html || editor.editorProps.stripPastedStyles) {
  34656. return false;
  34657. }
  34658. var tempColors = external_braft_utils_["ColorUtils"].detectColorsFromHTMLString(html);
  34659. editor.setState({
  34660. tempColors: toConsumableArray_default()(editor.state.tempColors).concat(toConsumableArray_default()(tempColors)).filter(function (item) {
  34661. return editor.editorProps.colors.indexOf(item) === -1;
  34662. }).filter(function (item, index, array) {
  34663. return array.indexOf(item) === index;
  34664. })
  34665. }, function () {
  34666. editor.setValue(external_braft_utils_["ContentUtils"].insertHTML(editorState, html, 'paste'));
  34667. });
  34668. return 'handled';
  34669. };
  34670. // CONCATENATED MODULE: ./helpers/extension.js
  34671. // TODO
  34672. // - block-style和atomic类型的扩展支持
  34673. var extension_extensionControls = [];
  34674. var extension_extensionDecorators = [];
  34675. var extension_propInterceptors = [];
  34676. var extension_extensionBlockRenderMaps = [];
  34677. var extension_extensionBlockRendererFns = [];
  34678. var extensionInlineStyleMaps = [];
  34679. var extension_extensionInlineStyleFns = [];
  34680. var extensionEntities = [];
  34681. var inlineStyleImporters = [];
  34682. var inlineStyleExporters = [];
  34683. var blockImporters = [];
  34684. var blockExporters = [];
  34685. var filterByEditorId = function filterByEditorId(items, editorId) {
  34686. if (!editorId) {
  34687. return items.filter(function (item) {
  34688. return !item.includeEditors;
  34689. }).map(function (item) {
  34690. return item.data;
  34691. });
  34692. }
  34693. return items.map(function (item) {
  34694. if (!item.includeEditors && !item.excludeEditors) {
  34695. return item.data;
  34696. }
  34697. if (item.includeEditors) {
  34698. return item.includeEditors.indexOf(editorId) !== -1 ? item.data : false;
  34699. }
  34700. if (item.excludeEditors) {
  34701. return item.excludeEditors.indexOf(editorId) !== -1 ? false : item.data;
  34702. }
  34703. return false;
  34704. }).filter(function (item) {
  34705. return item;
  34706. });
  34707. };
  34708. var getPropInterceptors = function getPropInterceptors(editorId) {
  34709. return filterByEditorId(extension_propInterceptors, editorId);
  34710. };
  34711. var getExtensionControls = function getExtensionControls(editorId) {
  34712. return filterByEditorId(extension_extensionControls, editorId);
  34713. };
  34714. var getExtensionDecorators = function getExtensionDecorators(editorId) {
  34715. return filterByEditorId(extension_extensionDecorators, editorId);
  34716. };
  34717. var getExtensionBlockRenderMaps = function getExtensionBlockRenderMaps(editorId) {
  34718. return filterByEditorId(extension_extensionBlockRenderMaps, editorId);
  34719. };
  34720. var getExtensionBlockRendererFns = function getExtensionBlockRendererFns(editorId) {
  34721. return filterByEditorId(extension_extensionBlockRendererFns, editorId);
  34722. };
  34723. var getExtensionInlineStyleMap = function getExtensionInlineStyleMap(editorId) {
  34724. var inlineStyleMap = {};
  34725. filterByEditorId(extensionInlineStyleMaps, editorId).forEach(function (item) {
  34726. inlineStyleMap[item.inlineStyleName] = item.styleMap;
  34727. });
  34728. return inlineStyleMap;
  34729. };
  34730. var getExtensionInlineStyleFns = function getExtensionInlineStyleFns(editorId) {
  34731. return filterByEditorId(extension_extensionInlineStyleFns, editorId);
  34732. };
  34733. var compositeStyleImportFn = function compositeStyleImportFn(styleImportFn, editorId) {
  34734. return function (nodeName, node, style) {
  34735. filterByEditorId(inlineStyleImporters, editorId).forEach(function (styleImporter) {
  34736. if (styleImporter.importer && styleImporter.importer(nodeName, node)) {
  34737. style = style.add(styleImporter.inlineStyleName);
  34738. }
  34739. });
  34740. return styleImportFn ? styleImportFn(nodeName, node, style) : style;
  34741. };
  34742. };
  34743. var compositeStyleExportFn = function compositeStyleExportFn(styleExportFn, editorId) {
  34744. return function (style) {
  34745. style = style.toUpperCase();
  34746. var result = styleExportFn ? styleExportFn(style) : undefined;
  34747. if (result) {
  34748. return result;
  34749. }
  34750. filterByEditorId(inlineStyleExporters, editorId).find(function (item) {
  34751. if (item.inlineStyleName === style) {
  34752. result = item.exporter;
  34753. return true;
  34754. }
  34755. });
  34756. return result;
  34757. };
  34758. };
  34759. var compositeEntityImportFn = function compositeEntityImportFn(entityImportFn, editorId) {
  34760. return function (nodeName, node, createEntity, source) {
  34761. var result = entityImportFn ? entityImportFn(nodeName, node, createEntity, source) : null;
  34762. if (result) {
  34763. return result;
  34764. }
  34765. filterByEditorId(extensionEntities, editorId).find(function (entityItem) {
  34766. var matched = entityItem.importer ? entityItem.importer(nodeName, node, source) : null;
  34767. matched && (result = createEntity(entityItem.entityType, matched.mutability || 'MUTABLE', matched.data || {}));
  34768. return !!matched;
  34769. });
  34770. return result;
  34771. };
  34772. };
  34773. var compositeEntityExportFn = function compositeEntityExportFn(entityExportFn, editorId) {
  34774. return function (entity, originalText) {
  34775. var result = entityExportFn ? entityExportFn(entity, originalText) : undefined;
  34776. if (result) {
  34777. return result;
  34778. }
  34779. var entityType = entity.type.toUpperCase();
  34780. filterByEditorId(extensionEntities, editorId).find(function (entityItem) {
  34781. if (entityItem.entityType === entityType) {
  34782. result = entityItem.exporter ? entityItem.exporter(entity, originalText) : undefined;
  34783. return true;
  34784. }
  34785. });
  34786. return result;
  34787. };
  34788. };
  34789. var compositeBlockImportFn = function compositeBlockImportFn(blockImportFn, editorId) {
  34790. return function (nodeName, node, source) {
  34791. var result = blockImportFn ? blockImportFn(nodeName, node, source) : null;
  34792. if (result) {
  34793. return result;
  34794. }
  34795. filterByEditorId(blockImporters, editorId).find(function (blockImporter) {
  34796. var matched = blockImporter.importer ? blockImporter.importer(nodeName, node, source) : undefined;
  34797. matched && (result = matched);
  34798. return !!matched;
  34799. });
  34800. return result;
  34801. };
  34802. };
  34803. var compositeBlockExportFn = function compositeBlockExportFn(blockExportFn, editorId) {
  34804. return function (contentState, block) {
  34805. var result = blockExportFn ? blockExportFn(contentState, block) : null;
  34806. if (result) {
  34807. return result;
  34808. }
  34809. filterByEditorId(blockExporters, editorId).find(function (blockExporter) {
  34810. var matched = blockExporter.exporter ? blockExporter.exporter(contentState, block) : undefined;
  34811. matched && (result = matched);
  34812. return !!matched;
  34813. });
  34814. return result;
  34815. };
  34816. };
  34817. var extension_useExtension = function useExtension(extension) {
  34818. if (extension instanceof Array) {
  34819. extension.forEach(useExtension);
  34820. return false;
  34821. }
  34822. if (!extension || !extension.type || typeof extension.type !== 'string') {
  34823. return false;
  34824. }
  34825. var includeEditors = extension.includeEditors,
  34826. excludeEditors = extension.excludeEditors;
  34827. if (extension.type === 'control') {
  34828. extension_extensionControls.push({
  34829. includeEditors: includeEditors,
  34830. excludeEditors: excludeEditors,
  34831. data: extension.control
  34832. });
  34833. } else if (extension.type === 'inline-style') {
  34834. var inlineStyleName = extension.name.toUpperCase();
  34835. if (extension.control) {
  34836. extension_extensionControls.push({
  34837. includeEditors: includeEditors,
  34838. excludeEditors: excludeEditors,
  34839. data: objectSpread_default()({
  34840. key: inlineStyleName,
  34841. type: 'inline-style',
  34842. command: inlineStyleName
  34843. }, extension.control)
  34844. });
  34845. }
  34846. if (extension.style) {
  34847. extensionInlineStyleMaps.push({
  34848. includeEditors: includeEditors,
  34849. excludeEditors: excludeEditors,
  34850. data: {
  34851. inlineStyleName: inlineStyleName,
  34852. styleMap: extension.style
  34853. }
  34854. });
  34855. }
  34856. if (extension.styleFn) {
  34857. extension_extensionInlineStyleFns.push({
  34858. includeEditors: includeEditors,
  34859. excludeEditors: excludeEditors,
  34860. data: {
  34861. inlineStyleName: inlineStyleName,
  34862. styleFn: extension.styleFn
  34863. }
  34864. });
  34865. }
  34866. if (extension.importer) {
  34867. inlineStyleImporters.push({
  34868. includeEditors: includeEditors,
  34869. excludeEditors: excludeEditors,
  34870. data: {
  34871. inlineStyleName: inlineStyleName,
  34872. importer: extension.importer
  34873. }
  34874. });
  34875. }
  34876. inlineStyleExporters.push({
  34877. includeEditors: includeEditors,
  34878. excludeEditors: excludeEditors,
  34879. data: {
  34880. inlineStyleName: inlineStyleName,
  34881. exporter: extension.exporter ? extension.exporter(extension) : external_react_default.a.createElement("span", {
  34882. style: extension.style
  34883. })
  34884. }
  34885. });
  34886. } else if (extension.type === 'block-style') ; else if (extension.type === 'entity') {
  34887. var entityType = extension.name.toUpperCase();
  34888. if (extension.control) {
  34889. extension_extensionControls.push({
  34890. includeEditors: includeEditors,
  34891. excludeEditors: excludeEditors,
  34892. data: typeof extension.control === 'function' ? extension.control : objectSpread_default()({
  34893. key: entityType,
  34894. type: 'entity',
  34895. command: entityType,
  34896. data: {
  34897. mutability: extension.mutability || 'MUTABLE',
  34898. data: extension.data || {}
  34899. }
  34900. }, extension.control)
  34901. });
  34902. }
  34903. extensionEntities.push({
  34904. includeEditors: includeEditors,
  34905. excludeEditors: excludeEditors,
  34906. data: {
  34907. entityType: entityType,
  34908. importer: extension.importer,
  34909. exporter: extension.exporter
  34910. }
  34911. });
  34912. extension_extensionDecorators.push({
  34913. includeEditors: includeEditors,
  34914. excludeEditors: excludeEditors,
  34915. data: {
  34916. type: 'entity',
  34917. decorator: {
  34918. key: entityType,
  34919. component: extension.component
  34920. }
  34921. }
  34922. });
  34923. } else if (extension.type === 'block') {
  34924. var blockType = extension.name;
  34925. if (extension.renderMap) {
  34926. extension_extensionBlockRenderMaps.push({
  34927. includeEditors: includeEditors,
  34928. excludeEditors: excludeEditors,
  34929. data: {
  34930. blockType: blockType,
  34931. renderMap: extension.renderMap
  34932. }
  34933. });
  34934. }
  34935. if (extension.rendererFn) {
  34936. extension_extensionBlockRendererFns.push({
  34937. includeEditors: includeEditors,
  34938. excludeEditors: excludeEditors,
  34939. data: {
  34940. blockType: blockType,
  34941. rendererFn: extension.rendererFn
  34942. }
  34943. });
  34944. }
  34945. if (extension.importer) {
  34946. blockImporters.push({
  34947. includeEditors: includeEditors,
  34948. excludeEditors: excludeEditors,
  34949. data: {
  34950. blockType: blockType,
  34951. importer: extension.importer
  34952. }
  34953. });
  34954. }
  34955. if (extension.exporter) {
  34956. blockExporters.push({
  34957. includeEditors: includeEditors,
  34958. excludeEditors: excludeEditors,
  34959. data: {
  34960. blockType: blockType,
  34961. exporter: extension.exporter
  34962. }
  34963. });
  34964. }
  34965. } else if (extension.type === 'atomic') ; else if (extension.type === 'decorator') {
  34966. var decorator = extension.decorator;
  34967. if (decorator && decorator.strategy && decorator.component) {
  34968. extension_extensionDecorators.push({
  34969. includeEditors: includeEditors,
  34970. excludeEditors: excludeEditors,
  34971. data: {
  34972. type: 'strategy',
  34973. decorator: decorator
  34974. }
  34975. });
  34976. } else if (decorator && decorator.getDecorations) {
  34977. extension_extensionDecorators.push({
  34978. includeEditors: includeEditors,
  34979. excludeEditors: excludeEditors,
  34980. data: {
  34981. type: 'class',
  34982. decorator: decorator
  34983. }
  34984. });
  34985. }
  34986. } else if (extension.type === 'prop-interception') {
  34987. extension_propInterceptors.push({
  34988. includeEditors: includeEditors,
  34989. excludeEditors: excludeEditors,
  34990. data: extension.interceptor
  34991. });
  34992. }
  34993. };
  34994. var createExtensibleEditor = function createExtensibleEditor(BraftEditor) {
  34995. BraftEditor.use = extension_useExtension;
  34996. return BraftEditor;
  34997. };
  34998. // CONCATENATED MODULE: ./renderers/block/blockRenderMap.js
  34999. /* harmony default export */ var block_blockRenderMap = (function (props, blockRenderMap) {
  35000. var customBlockRenderMap = Object(external_immutable_["Map"])({
  35001. 'atomic': {
  35002. element: ''
  35003. },
  35004. 'code-block': {
  35005. element: 'code',
  35006. wrapper: external_react_default.a.createElement("pre", {
  35007. className: "braft-code-block"
  35008. })
  35009. }
  35010. });
  35011. try {
  35012. var extensionBlockRenderMaps = getExtensionBlockRenderMaps(props.editorId);
  35013. customBlockRenderMap = extensionBlockRenderMaps.reduce(function (customBlockRenderMap, item) {
  35014. return customBlockRenderMap.merge(typeof item.renderMap === 'function' ? item.renderMap(props) : item.renderMap);
  35015. }, customBlockRenderMap);
  35016. if (blockRenderMap) {
  35017. if (typeof blockRenderMap === 'function') {
  35018. customBlockRenderMap = customBlockRenderMap.merge(blockRenderMap(props));
  35019. } else {
  35020. customBlockRenderMap = customBlockRenderMap.merge(blockRenderMap);
  35021. }
  35022. }
  35023. customBlockRenderMap = external_draft_js_["DefaultDraftBlockRenderMap"].merge(customBlockRenderMap);
  35024. } catch (error) {
  35025. console.warn(error);
  35026. }
  35027. return customBlockRenderMap;
  35028. });
  35029. // EXTERNAL MODULE: ../node_modules/@babel/runtime/helpers/extends.js
  35030. var helpers_extends = __webpack_require__(11);
  35031. var extends_default = /*#__PURE__*/__webpack_require__.n(helpers_extends);
  35032. // EXTERNAL MODULE: ../node_modules/@babel/runtime/helpers/slicedToArray.js
  35033. var slicedToArray = __webpack_require__(24);
  35034. var slicedToArray_default = /*#__PURE__*/__webpack_require__.n(slicedToArray);
  35035. // EXTERNAL MODULE: ./renderers/atomics/Image/style.scss
  35036. var Image_style = __webpack_require__(45);
  35037. // EXTERNAL MODULE: ./components/common/Switch/style.scss
  35038. var Switch_style = __webpack_require__(46);
  35039. // CONCATENATED MODULE: ./components/common/Switch/index.jsx
  35040. /* harmony default export */ var Switch = (function (props) {
  35041. var active = props.active,
  35042. _onClick = props.onClick,
  35043. className = props.className;
  35044. return external_react_default.a.createElement("div", {
  35045. onClick: function onClick() {
  35046. return _onClick();
  35047. },
  35048. className: 'bf-switch ' + className + (active ? ' active' : '')
  35049. });
  35050. });
  35051. // CONCATENATED MODULE: ./configs/controls.js
  35052. /* harmony default export */ var configs_controls = (function (lang, editor) {
  35053. return [{
  35054. key: 'undo',
  35055. title: lang.controls.undo,
  35056. text: external_react_default.a.createElement("i", {
  35057. className: "bfi-undo"
  35058. }),
  35059. type: 'editor-method',
  35060. command: 'undo'
  35061. }, {
  35062. key: 'redo',
  35063. title: lang.controls.redo,
  35064. text: external_react_default.a.createElement("i", {
  35065. className: "bfi-redo"
  35066. }),
  35067. type: 'editor-method',
  35068. command: 'redo'
  35069. }, {
  35070. key: 'remove-styles',
  35071. title: lang.controls.removeStyles,
  35072. text: external_react_default.a.createElement("i", {
  35073. className: "bfi-format_clear"
  35074. }),
  35075. type: 'editor-method',
  35076. command: 'removeSelectionInlineStyles'
  35077. }, {
  35078. key: 'hr',
  35079. title: lang.controls.hr,
  35080. text: external_react_default.a.createElement("i", {
  35081. className: "bfi-hr"
  35082. }),
  35083. type: 'editor-method',
  35084. command: 'insertHorizontalLine'
  35085. }, {
  35086. key: 'bold',
  35087. title: lang.controls.bold,
  35088. text: external_react_default.a.createElement("i", {
  35089. className: "bfi-bold"
  35090. }),
  35091. type: 'inline-style',
  35092. command: 'bold'
  35093. }, {
  35094. key: 'italic',
  35095. title: lang.controls.italic,
  35096. text: external_react_default.a.createElement("i", {
  35097. className: "bfi-italic"
  35098. }),
  35099. type: 'inline-style',
  35100. command: 'italic'
  35101. }, {
  35102. key: 'underline',
  35103. title: lang.controls.underline,
  35104. text: external_react_default.a.createElement("i", {
  35105. className: "bfi-underlined"
  35106. }),
  35107. type: 'inline-style',
  35108. command: 'underline'
  35109. }, {
  35110. key: 'strike-through',
  35111. title: lang.controls.strikeThrough,
  35112. text: external_react_default.a.createElement("i", {
  35113. className: "bfi-strikethrough"
  35114. }),
  35115. type: 'inline-style',
  35116. command: 'strikethrough'
  35117. }, {
  35118. key: 'superscript',
  35119. title: lang.controls.superScript,
  35120. text: external_react_default.a.createElement("i", {
  35121. className: "bfi-superscript"
  35122. }),
  35123. type: 'inline-style',
  35124. command: 'superscript'
  35125. }, {
  35126. key: 'subscript',
  35127. title: lang.controls.subScript,
  35128. text: external_react_default.a.createElement("i", {
  35129. className: "bfi-subscript"
  35130. }),
  35131. type: 'inline-style',
  35132. command: 'subscript'
  35133. }, {
  35134. key: 'headings',
  35135. title: lang.controls.headings,
  35136. type: 'headings'
  35137. }, {
  35138. key: 'blockquote',
  35139. title: lang.controls.blockQuote,
  35140. text: external_react_default.a.createElement("i", {
  35141. className: "bfi-quote"
  35142. }),
  35143. type: 'block-type',
  35144. command: 'blockquote'
  35145. }, {
  35146. key: 'code',
  35147. title: lang.controls.code,
  35148. text: external_react_default.a.createElement("i", {
  35149. className: "bfi-code"
  35150. }),
  35151. type: 'block-type',
  35152. command: 'code-block'
  35153. }, {
  35154. key: 'list-ul',
  35155. title: lang.controls.unorderedList,
  35156. text: external_react_default.a.createElement("i", {
  35157. className: "bfi-list"
  35158. }),
  35159. type: 'block-type',
  35160. command: 'unordered-list-item'
  35161. }, {
  35162. key: 'list-ol',
  35163. title: lang.controls.orderedList,
  35164. text: external_react_default.a.createElement("i", {
  35165. className: "bfi-list-numbered"
  35166. }),
  35167. type: 'block-type',
  35168. command: 'ordered-list-item'
  35169. }, {
  35170. key: 'link',
  35171. title: lang.controls.link,
  35172. type: 'link'
  35173. }, {
  35174. key: 'text-color',
  35175. title: lang.controls.color,
  35176. type: 'text-color'
  35177. }, {
  35178. key: 'line-height',
  35179. title: lang.controls.lineHeight,
  35180. type: 'line-height'
  35181. }, {
  35182. key: 'letter-spacing',
  35183. title: lang.controls.letterSpacing,
  35184. type: 'letter-spacing'
  35185. }, {
  35186. key: 'text-indent',
  35187. title: lang.controls.textIndent,
  35188. type: 'text-indent'
  35189. }, {
  35190. key: 'font-size',
  35191. title: lang.controls.fontSize,
  35192. type: 'font-size'
  35193. }, {
  35194. key: 'font-family',
  35195. title: lang.controls.fontFamily,
  35196. type: 'font-family'
  35197. }, {
  35198. key: 'text-align',
  35199. title: lang.controls.textAlign,
  35200. type: 'text-align'
  35201. }, {
  35202. key: 'media',
  35203. title: lang.controls.media,
  35204. text: external_react_default.a.createElement("i", {
  35205. className: "bfi-media"
  35206. }),
  35207. type: 'media'
  35208. }, {
  35209. key: 'emoji',
  35210. title: lang.controls.emoji,
  35211. text: external_react_default.a.createElement("i", {
  35212. className: "bfi-emoji"
  35213. }),
  35214. type: 'emoji'
  35215. }, {
  35216. key: 'clear',
  35217. title: lang.controls.clear,
  35218. text: external_react_default.a.createElement("i", {
  35219. className: "bfi-clear_all"
  35220. }),
  35221. type: 'editor-method',
  35222. command: 'clearEditorContent'
  35223. }, {
  35224. key: 'fullscreen',
  35225. title: editor.state.isFullscreen ? lang.controls.exitFullscreen : lang.controls.fullscreen,
  35226. text: external_react_default.a.createElement("i", {
  35227. className: editor.state.isFullscreen ? 'bfi-fullscreen-exit' : 'bfi-fullscreen'
  35228. }),
  35229. type: 'editor-method',
  35230. command: 'toggleFullscreen'
  35231. }, {
  35232. key: 'modal',
  35233. type: 'modal'
  35234. }, {
  35235. key: 'button',
  35236. type: 'button'
  35237. }, {
  35238. key: 'dropdown',
  35239. type: 'dropdown'
  35240. }, {
  35241. key: 'component',
  35242. type: 'component'
  35243. }];
  35244. });
  35245. var imageControlItems = {
  35246. 'float-left': {
  35247. text: external_react_default.a.createElement("span", {
  35248. "data-float": "left"
  35249. }, "\uE91E"),
  35250. command: 'setImageFloat|left'
  35251. },
  35252. 'float-right': {
  35253. text: external_react_default.a.createElement("span", {
  35254. "data-float": "right"
  35255. }, "\uE914"),
  35256. command: 'setImageFloat|right'
  35257. },
  35258. 'align-left': {
  35259. text: external_react_default.a.createElement("span", {
  35260. "data-align": "left"
  35261. }, "\uE027"),
  35262. command: 'setImageAlignment|left'
  35263. },
  35264. 'align-center': {
  35265. text: external_react_default.a.createElement("span", {
  35266. "data-align": "center"
  35267. }, "\uE028"),
  35268. command: 'setImageAlignment|center'
  35269. },
  35270. 'align-right': {
  35271. text: external_react_default.a.createElement("span", {
  35272. "data-align": "right"
  35273. }, "\uE029"),
  35274. command: 'setImageAlignment|right'
  35275. },
  35276. 'size': {
  35277. text: external_react_default.a.createElement("span", null, "\uE3C2"),
  35278. command: 'toggleSizeEditor'
  35279. },
  35280. 'link': {
  35281. text: external_react_default.a.createElement("span", null, "\uE91A"),
  35282. command: 'toggleLinkEditor'
  35283. },
  35284. 'remove': {
  35285. text: external_react_default.a.createElement("span", null, "\uE9AC"),
  35286. command: 'removeImage'
  35287. }
  35288. };
  35289. // CONCATENATED MODULE: ./renderers/atomics/Image/index.jsx
  35290. var Image_Image =
  35291. /*#__PURE__*/
  35292. function (_React$Component) {
  35293. inherits_default()(Image, _React$Component);
  35294. function Image() {
  35295. var _getPrototypeOf2;
  35296. var _this;
  35297. classCallCheck_default()(this, Image);
  35298. for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
  35299. args[_key] = arguments[_key];
  35300. }
  35301. _this = possibleConstructorReturn_default()(this, (_getPrototypeOf2 = getPrototypeOf_default()(Image)).call.apply(_getPrototypeOf2, [this].concat(args)));
  35302. defineProperty_default()(assertThisInitialized_default()(assertThisInitialized_default()(_this)), "state", {
  35303. toolbarVisible: false,
  35304. toolbarOffset: 0,
  35305. linkEditorVisible: false,
  35306. sizeEditorVisible: false,
  35307. tempLink: null,
  35308. tempWidth: null,
  35309. tempHeight: null
  35310. });
  35311. defineProperty_default()(assertThisInitialized_default()(assertThisInitialized_default()(_this)), "initialLeft", void 0);
  35312. defineProperty_default()(assertThisInitialized_default()(assertThisInitialized_default()(_this)), "initialTop", void 0);
  35313. defineProperty_default()(assertThisInitialized_default()(assertThisInitialized_default()(_this)), "initialWidth", void 0);
  35314. defineProperty_default()(assertThisInitialized_default()(assertThisInitialized_default()(_this)), "initialHeight", void 0);
  35315. defineProperty_default()(assertThisInitialized_default()(assertThisInitialized_default()(_this)), "reSizeType", void 0);
  35316. defineProperty_default()(assertThisInitialized_default()(assertThisInitialized_default()(_this)), "changeSize", function (e) {
  35317. var type = _this.reSizeType;
  35318. if (!_this.initialLeft) {
  35319. _this.initialLeft = e.screenX;
  35320. _this.initialTop = e.screenY;
  35321. }
  35322. if (type === 'rightbottom') {
  35323. _this.initialHeight += e.screenY - _this.initialTop;
  35324. _this.initialWidth += e.screenX - _this.initialLeft;
  35325. }
  35326. if (type === 'leftbottom') {
  35327. _this.initialHeight += e.screenY - _this.initialTop;
  35328. _this.initialWidth += -e.screenX + _this.initialLeft;
  35329. }
  35330. _this.initialLeft = e.screenX;
  35331. _this.initialTop = e.screenY;
  35332. });
  35333. defineProperty_default()(assertThisInitialized_default()(assertThisInitialized_default()(_this)), "moveImage", function (e) {
  35334. _this.changeSize(e);
  35335. _this.setState({
  35336. tempWidth: Math.abs(_this.initialWidth),
  35337. tempHeight: Math.abs(_this.initialHeight)
  35338. });
  35339. });
  35340. defineProperty_default()(assertThisInitialized_default()(assertThisInitialized_default()(_this)), "upImage", function () {
  35341. _this.confirmImageSize();
  35342. document.removeEventListener('mousemove', _this.moveImage);
  35343. document.removeEventListener('mouseup', _this.upImage);
  35344. });
  35345. defineProperty_default()(assertThisInitialized_default()(assertThisInitialized_default()(_this)), "repareChangeSize", function (type) {
  35346. return function (e) {
  35347. _this.reSizeType = type;
  35348. var imageRect = _this.imageElement.getBoundingClientRect();
  35349. _this.initialLeft = _this.initialTop = 0;
  35350. _this.initialWidth = imageRect.width;
  35351. _this.initialHeight = imageRect.height;
  35352. e.preventDefault();
  35353. document.addEventListener('mousemove', _this.moveImage);
  35354. document.addEventListener('mouseup', _this.upImage);
  35355. };
  35356. });
  35357. defineProperty_default()(assertThisInitialized_default()(assertThisInitialized_default()(_this)), "preventDragEvent", function (event) {
  35358. event.stopPropagation();
  35359. event.preventDefault();
  35360. });
  35361. defineProperty_default()(assertThisInitialized_default()(assertThisInitialized_default()(_this)), "handleDragStart", function () {
  35362. if (_this.props.editor.editorProps.readOnly || _this.props.editor.editorProps.disabled) {
  35363. return false;
  35364. }
  35365. window.__BRAFT_DRAGING__IMAGE__ = {
  35366. block: _this.props.block,
  35367. mediaData: objectSpread_default()({
  35368. type: 'IMAGE'
  35369. }, _this.props.mediaData)
  35370. };
  35371. _this.setState({
  35372. toolbarVisible: false
  35373. }, function () {
  35374. _this.unlockEditor();
  35375. });
  35376. return true;
  35377. });
  35378. defineProperty_default()(assertThisInitialized_default()(assertThisInitialized_default()(_this)), "handleDragEnd", function () {
  35379. window.__BRAFT_DRAGING__IMAGE__ = null;
  35380. return false;
  35381. });
  35382. defineProperty_default()(assertThisInitialized_default()(assertThisInitialized_default()(_this)), "executeCommand", function (command) {
  35383. if (typeof command === 'string') {
  35384. var _command$split = command.split('|'),
  35385. _command$split2 = slicedToArray_default()(_command$split, 2),
  35386. method = _command$split2[0],
  35387. param = _command$split2[1];
  35388. _this[method] && _this[method](param);
  35389. } else if (typeof command === 'function') {
  35390. command(_this.props.block, _this.props.mediaData, _this.props.editor.getValue());
  35391. }
  35392. });
  35393. defineProperty_default()(assertThisInitialized_default()(assertThisInitialized_default()(_this)), "removeImage", function () {
  35394. _this.props.editor.setValue(external_braft_utils_["ContentUtils"].removeBlock(_this.props.editor.getValue(), _this.props.block));
  35395. _this.unlockEditor();
  35396. });
  35397. defineProperty_default()(assertThisInitialized_default()(assertThisInitialized_default()(_this)), "toggleLinkEditor", function () {
  35398. _this.setState({
  35399. linkEditorVisible: !_this.state.linkEditorVisible,
  35400. sizeEditorVisible: false
  35401. });
  35402. });
  35403. defineProperty_default()(assertThisInitialized_default()(assertThisInitialized_default()(_this)), "toggleSizeEditor", function () {
  35404. _this.setState({
  35405. linkEditorVisible: false,
  35406. sizeEditorVisible: !_this.state.sizeEditorVisible
  35407. });
  35408. });
  35409. defineProperty_default()(assertThisInitialized_default()(assertThisInitialized_default()(_this)), "handleLinkInputKeyDown", function (e) {
  35410. if (e.keyCode === 13) {
  35411. _this.confirmImageLink();
  35412. } else {
  35413. return;
  35414. }
  35415. });
  35416. defineProperty_default()(assertThisInitialized_default()(assertThisInitialized_default()(_this)), "setImageLink", function (e) {
  35417. _this.setState({
  35418. tempLink: e.currentTarget.value
  35419. });
  35420. return;
  35421. });
  35422. defineProperty_default()(assertThisInitialized_default()(assertThisInitialized_default()(_this)), "confirmImageLink", function () {
  35423. var link = _this.state.tempLink;
  35424. var hookReturns = _this.props.hooks('set-image-link', link)(link);
  35425. if (hookReturns === false) {
  35426. return false;
  35427. }
  35428. if (typeof hookReturns === 'string') {
  35429. link = hookReturns;
  35430. }
  35431. if (link !== null) {
  35432. _this.props.editor.setValue(external_braft_utils_["ContentUtils"].setMediaData(_this.props.editor.getValue(), _this.props.entityKey, {
  35433. link: link
  35434. }));
  35435. window.setImmediate(_this.props.editor.forceRender);
  35436. }
  35437. });
  35438. defineProperty_default()(assertThisInitialized_default()(assertThisInitialized_default()(_this)), "handleSizeInputKeyDown", function (e) {
  35439. if (e.keyCode === 13) {
  35440. _this.confirmImageSize();
  35441. } else {
  35442. return;
  35443. }
  35444. });
  35445. defineProperty_default()(assertThisInitialized_default()(assertThisInitialized_default()(_this)), "setImageWidth", function (_ref) {
  35446. var currentTarget = _ref.currentTarget;
  35447. var value = currentTarget.value;
  35448. value && !isNaN(value) && (value = value + 'px');
  35449. _this.setState({
  35450. tempWidth: value
  35451. });
  35452. return;
  35453. });
  35454. defineProperty_default()(assertThisInitialized_default()(assertThisInitialized_default()(_this)), "setImageHeight", function (_ref2) {
  35455. var currentTarget = _ref2.currentTarget;
  35456. var value = currentTarget.value;
  35457. value && !isNaN(value) && (value = value + 'px');
  35458. _this.setState({
  35459. tempHeight: value
  35460. });
  35461. return;
  35462. });
  35463. defineProperty_default()(assertThisInitialized_default()(assertThisInitialized_default()(_this)), "confirmImageSize", function () {
  35464. var _this$state = _this.state,
  35465. width = _this$state.tempWidth,
  35466. height = _this$state.tempHeight;
  35467. var newImageSize = {};
  35468. width !== null && (newImageSize.width = width);
  35469. height !== null && (newImageSize.height = height);
  35470. var hookReturns = _this.props.hooks('set-image-size', newImageSize)(newImageSize);
  35471. if (hookReturns === false) {
  35472. return false;
  35473. }
  35474. if (hookReturns && (hookReturns.width || hookReturns.height)) {
  35475. newImageSize = hookReturns;
  35476. }
  35477. _this.props.editor.setValue(external_braft_utils_["ContentUtils"].setMediaData(_this.props.editor.getValue(), _this.props.entityKey, newImageSize));
  35478. window.setImmediate(_this.props.editor.forceRender);
  35479. });
  35480. defineProperty_default()(assertThisInitialized_default()(assertThisInitialized_default()(_this)), "setImageFloat", function (float) {
  35481. var hookReturns = _this.props.hooks('set-image-float', float)(float);
  35482. if (hookReturns === false) {
  35483. return false;
  35484. }
  35485. if (typeof hookReturns === 'string') {
  35486. float = hookReturns;
  35487. }
  35488. _this.props.editor.setValue(external_braft_utils_["ContentUtils"].setMediaPosition(_this.props.editor.getValue(), _this.props.block, {
  35489. float: float
  35490. }));
  35491. _this.unlockEditor();
  35492. });
  35493. defineProperty_default()(assertThisInitialized_default()(assertThisInitialized_default()(_this)), "setImageAlignment", function (alignment) {
  35494. var hookReturns = _this.props.hooks('set-image-alignment', alignment)(alignment);
  35495. if (hookReturns === false) {
  35496. return false;
  35497. }
  35498. if (typeof hookReturns === 'string') {
  35499. alignment = hookReturns;
  35500. }
  35501. _this.props.editor.setValue(external_braft_utils_["ContentUtils"].setMediaPosition(_this.props.editor.getValue(), _this.props.block, {
  35502. alignment: alignment
  35503. }));
  35504. _this.unlockEditor();
  35505. });
  35506. defineProperty_default()(assertThisInitialized_default()(assertThisInitialized_default()(_this)), "showToolbar", function (event) {
  35507. if (_this.props.editor.editorProps.readOnly || _this.props.editor.editorProps.disabled) {
  35508. return false;
  35509. }
  35510. event.preventDefault();
  35511. if (!_this.state.toolbarVisible) {
  35512. _this.setState({
  35513. toolbarVisible: true
  35514. }, function () {
  35515. _this.lockEditor();
  35516. _this.setState({
  35517. toolbarOffset: _this.calcToolbarOffset()
  35518. });
  35519. });
  35520. }
  35521. });
  35522. defineProperty_default()(assertThisInitialized_default()(assertThisInitialized_default()(_this)), "hideToolbar", function (event) {
  35523. event.preventDefault();
  35524. _this.setState({
  35525. toolbarVisible: false
  35526. }, function () {
  35527. _this.unlockEditor(); // this.props.editor.requestFocus()
  35528. });
  35529. });
  35530. return _this;
  35531. }
  35532. createClass_default()(Image, [{
  35533. key: "render",
  35534. value: function render() {
  35535. var _this2 = this;
  35536. var _this$props = this.props,
  35537. mediaData = _this$props.mediaData,
  35538. language = _this$props.language,
  35539. imageControls = _this$props.imageControls,
  35540. imageResizable = _this$props.imageResizable;
  35541. var _this$state2 = this.state,
  35542. toolbarVisible = _this$state2.toolbarVisible,
  35543. toolbarOffset = _this$state2.toolbarOffset,
  35544. linkEditorVisible = _this$state2.linkEditorVisible,
  35545. sizeEditorVisible = _this$state2.sizeEditorVisible,
  35546. tempWidth = _this$state2.tempWidth,
  35547. tempHeight = _this$state2.tempHeight;
  35548. var blockData = this.props.block.getData();
  35549. var float = blockData.get('float');
  35550. var alignment = blockData.get('alignment');
  35551. var url = mediaData.url,
  35552. link = mediaData.link,
  35553. link_target = mediaData.link_target,
  35554. width = mediaData.width,
  35555. height = mediaData.height,
  35556. meta = mediaData.meta;
  35557. var imageStyles = {};
  35558. var clearFix = false;
  35559. if (float) {
  35560. alignment = null;
  35561. } else if (alignment === 'left') {
  35562. imageStyles.float = 'left';
  35563. clearFix = true;
  35564. } else if (alignment === 'right') {
  35565. imageStyles.float = 'right';
  35566. clearFix = true;
  35567. } else if (alignment === 'center') {
  35568. imageStyles.textAlign = 'center';
  35569. } else {
  35570. imageStyles.float = 'left';
  35571. clearFix = true;
  35572. }
  35573. var renderedControlItems = imageControls.map(function (item, index) {
  35574. if (typeof item === 'string' && imageControlItems[item]) {
  35575. return external_react_default.a.createElement("a", {
  35576. className: item === 'link' && link ? 'active' : '',
  35577. key: index,
  35578. onClick: function onClick() {
  35579. return _this2.executeCommand(imageControlItems[item].command);
  35580. }
  35581. }, imageControlItems[item].text);
  35582. } else if (item && (item.render || item.text)) {
  35583. return item.render ? item.render(mediaData, _this2.props.block) : external_react_default.a.createElement("a", {
  35584. key: index,
  35585. onClick: function onClick() {
  35586. return item.onClick && _this2.executeCommand(item.onClick);
  35587. }
  35588. }, item.text);
  35589. } else {
  35590. return null;
  35591. }
  35592. });
  35593. return external_react_default.a.createElement("div", {
  35594. className: "bf-media"
  35595. }, external_react_default.a.createElement("div", {
  35596. style: imageStyles,
  35597. draggable: true,
  35598. onMouseEnter: this.showToolbar,
  35599. onMouseMove: this.showToolbar,
  35600. onMouseLeave: this.hideToolbar,
  35601. onDragStart: this.handleDragStart,
  35602. onDragEnd: this.handleDragEnd,
  35603. ref: function ref(instance) {
  35604. return _this2.mediaEmbederInstance = instance;
  35605. },
  35606. className: "bf-image"
  35607. }, toolbarVisible ? external_react_default.a.createElement("div", {
  35608. style: {
  35609. marginLeft: toolbarOffset
  35610. },
  35611. ref: function ref(instance) {
  35612. return _this2.toolbarElement = instance;
  35613. },
  35614. "data-float": float,
  35615. "data-align": alignment,
  35616. className: "bf-media-toolbar"
  35617. }, linkEditorVisible ? external_react_default.a.createElement("div", {
  35618. className: "bf-image-link-editor"
  35619. }, external_react_default.a.createElement("div", {
  35620. className: "editor-input-group"
  35621. }, external_react_default.a.createElement("input", {
  35622. type: "text",
  35623. placeholder: language.linkEditor.inputWithEnterPlaceHolder,
  35624. onKeyDown: this.handleLinkInputKeyDown,
  35625. onChange: this.setImageLink,
  35626. defaultValue: link
  35627. }), external_react_default.a.createElement("button", {
  35628. type: "button",
  35629. onClick: this.confirmImageLink
  35630. }, language.base.confirm)), external_react_default.a.createElement("div", {
  35631. className: "switch-group"
  35632. }, external_react_default.a.createElement(Switch, {
  35633. active: link_target === '_blank',
  35634. onClick: function onClick() {
  35635. return _this2.setImageLinkTarget(link_target);
  35636. }
  35637. }), external_react_default.a.createElement("label", null, language.linkEditor.openInNewWindow))) : null, sizeEditorVisible ? external_react_default.a.createElement("div", {
  35638. className: "bf-image-size-editor"
  35639. }, external_react_default.a.createElement("div", {
  35640. className: "editor-input-group"
  35641. }, external_react_default.a.createElement("input", {
  35642. type: "text",
  35643. placeholder: language.base.width,
  35644. onKeyDown: this.handleSizeInputKeyDown,
  35645. onChange: this.setImageWidth,
  35646. defaultValue: width
  35647. }), external_react_default.a.createElement("input", {
  35648. type: "text",
  35649. placeholder: language.base.height,
  35650. onKeyDown: this.handleSizeInputKeyDown,
  35651. onChange: this.setImageHeight,
  35652. defaultValue: height
  35653. }), external_react_default.a.createElement("button", {
  35654. type: "button",
  35655. onClick: this.confirmImageSize
  35656. }, language.base.confirm))) : null, renderedControlItems, external_react_default.a.createElement("i", {
  35657. style: {
  35658. marginLeft: toolbarOffset * -1
  35659. },
  35660. className: "bf-media-toolbar-arrow"
  35661. })) : null, external_react_default.a.createElement("div", {
  35662. style: {
  35663. position: 'relative',
  35664. width: "".concat(width, "px"),
  35665. height: "".concat(height, "px"),
  35666. display: 'inline-block'
  35667. }
  35668. }, external_react_default.a.createElement("img", extends_default()({
  35669. ref: function ref(instance) {
  35670. return _this2.imageElement = instance;
  35671. },
  35672. src: url,
  35673. width: width,
  35674. height: height
  35675. }, meta)), toolbarVisible && imageResizable ? external_react_default.a.createElement("div", {
  35676. className: "bf-csize-icon right-bottom",
  35677. onMouseDown: this.repareChangeSize('rightbottom')
  35678. }) : null, toolbarVisible && imageResizable ? external_react_default.a.createElement("div", {
  35679. className: "bf-csize-icon left-bottom",
  35680. onMouseDown: this.repareChangeSize('leftbottom')
  35681. }) : null, external_react_default.a.createElement("div", {
  35682. className: "bf-pre-csize ".concat(this.reSizeType),
  35683. style: {
  35684. width: "".concat(tempWidth, "px"),
  35685. height: "".concat(tempHeight, "px")
  35686. }
  35687. }))), clearFix && external_react_default.a.createElement("div", {
  35688. className: "clearfix",
  35689. style: {
  35690. clear: 'both',
  35691. height: 0,
  35692. lineHeight: 0,
  35693. float: 'none'
  35694. }
  35695. }));
  35696. }
  35697. }, {
  35698. key: "lockEditor",
  35699. value: function lockEditor() {
  35700. this.props.editor.lockOrUnlockEditor(true);
  35701. }
  35702. }, {
  35703. key: "unlockEditor",
  35704. value: function unlockEditor() {
  35705. this.props.editor.lockOrUnlockEditor(false);
  35706. }
  35707. }, {
  35708. key: "calcToolbarOffset",
  35709. value: function calcToolbarOffset() {
  35710. var _this$props2 = this.props,
  35711. getContainerNode = _this$props2.getContainerNode,
  35712. containerNode = _this$props2.containerNode;
  35713. var container = getContainerNode ? getContainerNode() : containerNode;
  35714. if (!container) {
  35715. return 0;
  35716. }
  35717. var viewRect = container.querySelector('.bf-content').getBoundingClientRect();
  35718. var toolbarRect = this.toolbarElement.getBoundingClientRect();
  35719. var imageRect = this.imageElement.getBoundingClientRect();
  35720. var right = viewRect.right - (imageRect.right - imageRect.width / 2 + toolbarRect.width / 2);
  35721. var left = imageRect.left + imageRect.width / 2 - toolbarRect.width / 2 - viewRect.left;
  35722. if (right < 10) {
  35723. return right - 10;
  35724. } else if (left < 10) {
  35725. return left * -1 + 10;
  35726. } else {
  35727. return 0;
  35728. }
  35729. }
  35730. }, {
  35731. key: "setImageLinkTarget",
  35732. value: function setImageLinkTarget(link_target) {
  35733. var hookReturns = this.props.hooks('set-image-link-target', link_target)(link_target);
  35734. if (hookReturns === false) {
  35735. return false;
  35736. }
  35737. if (typeof hookReturns === 'string') {
  35738. link_target = hookReturns;
  35739. }
  35740. link_target = link_target === '_blank' ? '' : '_blank';
  35741. this.props.editor.setValue(external_braft_utils_["ContentUtils"].setMediaData(this.props.editor.getValue(), this.props.entityKey, {
  35742. link_target: link_target
  35743. }));
  35744. window.setImmediate(this.props.editor.forceRender);
  35745. }
  35746. }]);
  35747. return Image;
  35748. }(external_react_default.a.Component);
  35749. // EXTERNAL MODULE: ./renderers/atomics/Video/style.scss
  35750. var Video_style = __webpack_require__(47);
  35751. // EXTERNAL MODULE: ./components/common/Modal/style.scss
  35752. var Modal_style = __webpack_require__(48);
  35753. // EXTERNAL MODULE: external "react-dom"
  35754. var external_react_dom_ = __webpack_require__(16);
  35755. var external_react_dom_default = /*#__PURE__*/__webpack_require__.n(external_react_dom_);
  35756. // CONCATENATED MODULE: ./components/common/Modal/index.jsx
  35757. var Modal_Modal =
  35758. /*#__PURE__*/
  35759. function (_React$Component) {
  35760. inherits_default()(Modal, _React$Component);
  35761. function Modal(props) {
  35762. var _this;
  35763. classCallCheck_default()(this, Modal);
  35764. _this = possibleConstructorReturn_default()(this, getPrototypeOf_default()(Modal).call(this, props));
  35765. defineProperty_default()(assertThisInitialized_default()(assertThisInitialized_default()(_this)), "handleTransitionEnd", function () {
  35766. if (!_this.rootElement || !_this.rootElement.classList) {
  35767. return false;
  35768. }
  35769. if (!_this.rootElement.classList.contains('active')) {
  35770. external_react_dom_default.a.unmountComponentAtNode(_this.rootElement) && _this.rootElement.parentNode.removeChild(_this.rootElement);
  35771. }
  35772. });
  35773. defineProperty_default()(assertThisInitialized_default()(assertThisInitialized_default()(_this)), "handleMouseDown", function (event) {
  35774. var tagName = event.target.tagName.toLowerCase();
  35775. if (tagName === 'input' || tagName === 'textarea') {
  35776. return false;
  35777. }
  35778. event.preventDefault();
  35779. });
  35780. defineProperty_default()(assertThisInitialized_default()(assertThisInitialized_default()(_this)), "handleCancel", function () {
  35781. _this.props.closeOnCancel && _this.close();
  35782. _this.props.onCancel && _this.props.onCancel();
  35783. });
  35784. defineProperty_default()(assertThisInitialized_default()(assertThisInitialized_default()(_this)), "handleConfirm", function () {
  35785. _this.props.closeOnConfirm && _this.close();
  35786. _this.props.onConfirm && _this.props.onConfirm();
  35787. });
  35788. defineProperty_default()(assertThisInitialized_default()(assertThisInitialized_default()(_this)), "handleMaskClick", function () {
  35789. _this.props.closeOnBlur && _this.close();
  35790. _this.props.onBlue && _this.props.onBlue();
  35791. });
  35792. defineProperty_default()(assertThisInitialized_default()(assertThisInitialized_default()(_this)), "close", function () {
  35793. _this.unrenderComponent();
  35794. _this.props.onClose && _this.props.onClose();
  35795. });
  35796. _this.active = false;
  35797. _this.componentId = 'BRAFT-MODAL-' + external_braft_utils_["BaseUtils"].UniqueIndex();
  35798. return _this;
  35799. }
  35800. createClass_default()(Modal, [{
  35801. key: "componentDidMount",
  35802. value: function componentDidMount() {
  35803. if (this.props.visible) {
  35804. this.active = true;
  35805. this.renderComponent(this.props);
  35806. }
  35807. }
  35808. }, {
  35809. key: "componentWillReceiveProps",
  35810. value: function componentWillReceiveProps(next) {
  35811. if (this.props.visible && !next.visible) {
  35812. this.unrenderComponent();
  35813. } else if (this.props.visible || next.visible) {
  35814. this.active = true;
  35815. this.renderComponent(next);
  35816. }
  35817. }
  35818. }, {
  35819. key: "render",
  35820. value: function render() {
  35821. return null;
  35822. }
  35823. }, {
  35824. key: "unrenderComponent",
  35825. value: function unrenderComponent() {
  35826. this.active = false;
  35827. this.activeId && window.clearImmediate(this.activeId);
  35828. if (this.rootElement && this.rootElement.classList) {
  35829. this.rootElement.classList.remove('active');
  35830. }
  35831. }
  35832. }, {
  35833. key: "renderComponent",
  35834. value: function renderComponent(props) {
  35835. var _this2 = this;
  35836. if (!this.active) {
  35837. return false;
  35838. }
  35839. var title = props.title,
  35840. className = props.className,
  35841. width = props.width,
  35842. height = props.height,
  35843. children = props.children,
  35844. component = props.component,
  35845. confirmable = props.confirmable,
  35846. showFooter = props.showFooter,
  35847. showCancel = props.showCancel,
  35848. showConfirm = props.showConfirm,
  35849. showClose = props.showClose,
  35850. cancelText = props.cancelText,
  35851. confirmText = props.confirmText,
  35852. bottomText = props.bottomText,
  35853. language = props.language;
  35854. typeof showCancel === 'undefined' && (showCancel = true);
  35855. typeof showClose === 'undefined' && (showClose = true);
  35856. typeof showConfirm === 'undefined' && (showConfirm = true);
  35857. typeof showFooter === 'undefined' && (showFooter = true);
  35858. var childComponent = external_react_default.a.createElement("div", {
  35859. onMouseDown: this.handleMouseDown,
  35860. className: 'bf-modal ' + (className || '')
  35861. }, external_react_default.a.createElement("div", {
  35862. className: "bf-modal-mask",
  35863. onClick: this.handleMaskClick
  35864. }), external_react_default.a.createElement("div", {
  35865. onTransitionEnd: this.handleTransitionEnd,
  35866. style: {
  35867. width: width,
  35868. height: height
  35869. },
  35870. className: "bf-modal-content"
  35871. }, external_react_default.a.createElement("div", {
  35872. className: "bf-modal-header"
  35873. }, external_react_default.a.createElement("h3", {
  35874. className: "bf-modal-caption"
  35875. }, title), showClose && external_react_default.a.createElement("button", {
  35876. type: "button",
  35877. onClick: this.close,
  35878. className: "bf-modal-close-button"
  35879. }, external_react_default.a.createElement("i", {
  35880. className: "bfi-close"
  35881. }))), external_react_default.a.createElement("div", {
  35882. className: "bf-modal-body"
  35883. }, children || component), showFooter ? external_react_default.a.createElement("div", {
  35884. className: "bf-modal-footer"
  35885. }, external_react_default.a.createElement("div", {
  35886. className: "bf-modal-addon-text"
  35887. }, bottomText), external_react_default.a.createElement("div", {
  35888. className: "bf-modal-buttons"
  35889. }, showCancel && external_react_default.a.createElement("button", {
  35890. type: "button",
  35891. onClick: this.handleCancel,
  35892. className: "bf-modal-cancel"
  35893. }, cancelText || language.base.cancel), showConfirm && external_react_default.a.createElement("button", {
  35894. type: "button",
  35895. onClick: this.handleConfirm,
  35896. className: 'bf-modal-confirm ' + (!confirmable ? 'disabled' : '')
  35897. }, confirmText || language.base.confirm))) : null));
  35898. this.rootElement = document.querySelector('#' + this.componentId);
  35899. if (!this.rootElement) {
  35900. this.rootElement = document.createElement('div');
  35901. this.rootElement.id = this.componentId;
  35902. this.rootElement.className = 'bf-modal-root';
  35903. document.body.appendChild(this.rootElement);
  35904. }
  35905. external_react_dom_default.a.render(childComponent, this.rootElement);
  35906. this.activeId = window.setImmediate(function () {
  35907. _this2.rootElement.classList.add('active');
  35908. });
  35909. }
  35910. }]);
  35911. return Modal;
  35912. }(external_react_default.a.Component);
  35913. defineProperty_default()(Modal_Modal, "defaultProps", {
  35914. showFooter: true,
  35915. closeOnBlur: true
  35916. });
  35917. var Modal_showModal = function showModal(props) {
  35918. var hostNode = document.createElement('div');
  35919. hostNode.style.display = 'none';
  35920. document.body.appendChild(hostNode);
  35921. props = objectSpread_default()({
  35922. visible: true,
  35923. closeOnConfirm: true,
  35924. closeOnCancel: true
  35925. }, props);
  35926. var close = function close() {
  35927. external_react_dom_default.a.unmountComponentAtNode(hostNode) && hostNode.parentNode.removeChild(hostNode);
  35928. };
  35929. var onConfirm = function onConfirm() {
  35930. props.onConfirm && props.onConfirm();
  35931. };
  35932. var onCancel = function onCancel() {
  35933. props.onCancel && props.onCancel();
  35934. };
  35935. var onClose = function onClose() {
  35936. close();
  35937. props.onClose && props.onClose();
  35938. };
  35939. var modalInstance = external_react_dom_default.a.render(external_react_default.a.createElement(Modal_Modal, extends_default()({}, props, {
  35940. onConfirm: onConfirm,
  35941. onCancel: onCancel,
  35942. onClose: onClose
  35943. })), hostNode);
  35944. modalInstance.destroy = close;
  35945. modalInstance.update = modalInstance.renderComponent;
  35946. return modalInstance;
  35947. };
  35948. // EXTERNAL MODULE: ./components/business/PlayerModal/style.scss
  35949. var PlayerModal_style = __webpack_require__(49);
  35950. // CONCATENATED MODULE: ./components/business/PlayerModal/index.jsx
  35951. var PlayerModal_playViaModal = function playViaModal(title, component, language) {
  35952. return Modal_showModal({
  35953. title: title,
  35954. component: component,
  35955. language: language,
  35956. showFooter: false
  35957. });
  35958. };
  35959. var typeIconsMap = {
  35960. 'video': 'bfi-film',
  35961. 'audio': 'bfi-music',
  35962. 'embed': 'bfi-code'
  35963. };
  35964. /* harmony default export */ var PlayerModal = (function (_ref) {
  35965. var title = _ref.title,
  35966. type = _ref.type,
  35967. language = _ref.language,
  35968. name = _ref.name,
  35969. url = _ref.url,
  35970. poster = _ref.poster,
  35971. children = _ref.children,
  35972. onRemove = _ref.onRemove;
  35973. return external_react_default.a.createElement("div", {
  35974. className: "bf-player-holder ".concat(type)
  35975. }, external_react_default.a.createElement("div", {
  35976. className: "icon-badge"
  35977. }, external_react_default.a.createElement("i", {
  35978. className: typeIconsMap[type]
  35979. }), external_react_default.a.createElement("span", {
  35980. className: "text"
  35981. }, language.media[type])), external_react_default.a.createElement("button", {
  35982. onMouseDown: onRemove,
  35983. className: "button-remove"
  35984. }, external_react_default.a.createElement("i", {
  35985. className: "bfi-close"
  35986. })), external_react_default.a.createElement("button", {
  35987. onMouseDown: function onMouseDown() {
  35988. return PlayerModal_playViaModal(name ? "".concat(title, ":").concat(name) : title, children, language);
  35989. },
  35990. className: "button-play"
  35991. }, external_react_default.a.createElement("i", {
  35992. className: "bfi-play_arrow"
  35993. })), name ? external_react_default.a.createElement("h5", {
  35994. className: "bf-name"
  35995. }, name) : null, external_react_default.a.createElement("h6", {
  35996. className: "bf-url"
  35997. }, url), poster ? external_react_default.a.createElement("div", {
  35998. className: "bf-poster",
  35999. style: {
  36000. backgroundImage: "url(".concat(poster, ")")
  36001. }
  36002. }) : null);
  36003. });
  36004. // CONCATENATED MODULE: ./renderers/atomics/Video/index.jsx
  36005. var Video_Video =
  36006. /*#__PURE__*/
  36007. function (_React$Component) {
  36008. inherits_default()(Video, _React$Component);
  36009. function Video() {
  36010. var _getPrototypeOf2;
  36011. var _this;
  36012. classCallCheck_default()(this, Video);
  36013. for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
  36014. args[_key] = arguments[_key];
  36015. }
  36016. _this = possibleConstructorReturn_default()(this, (_getPrototypeOf2 = getPrototypeOf_default()(Video)).call.apply(_getPrototypeOf2, [this].concat(args)));
  36017. defineProperty_default()(assertThisInitialized_default()(assertThisInitialized_default()(_this)), "removeVideo", function () {
  36018. _this.props.editor.setValue(external_braft_utils_["ContentUtils"].removeBlock(_this.props.editorState, _this.props.block));
  36019. });
  36020. return _this;
  36021. }
  36022. createClass_default()(Video, [{
  36023. key: "render",
  36024. value: function render() {
  36025. var _this$props = this.props,
  36026. mediaData = _this$props.mediaData,
  36027. language = _this$props.language;
  36028. var url = mediaData.url,
  36029. name = mediaData.name,
  36030. meta = mediaData.meta;
  36031. return external_react_default.a.createElement("div", {
  36032. className: "bf-video-wrap"
  36033. }, external_react_default.a.createElement(PlayerModal, {
  36034. type: "video",
  36035. onRemove: this.removeVideo,
  36036. poster: meta ? meta.poster || '' : '',
  36037. language: language,
  36038. url: url,
  36039. name: name,
  36040. title: language.videoPlayer.title
  36041. }, external_react_default.a.createElement("div", {
  36042. className: "bf-video-player"
  36043. }, external_react_default.a.createElement("video", {
  36044. controls: true,
  36045. poster: meta ? meta.poster || '' : ''
  36046. }, external_react_default.a.createElement("source", {
  36047. src: url
  36048. })))));
  36049. }
  36050. }]);
  36051. return Video;
  36052. }(external_react_default.a.Component);
  36053. // EXTERNAL MODULE: ./renderers/atomics/Audio/style.scss
  36054. var Audio_style = __webpack_require__(50);
  36055. // CONCATENATED MODULE: ./renderers/atomics/Audio/index.jsx
  36056. var Audio_Audio =
  36057. /*#__PURE__*/
  36058. function (_React$Component) {
  36059. inherits_default()(Audio, _React$Component);
  36060. function Audio() {
  36061. var _getPrototypeOf2;
  36062. var _this;
  36063. classCallCheck_default()(this, Audio);
  36064. for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
  36065. args[_key] = arguments[_key];
  36066. }
  36067. _this = possibleConstructorReturn_default()(this, (_getPrototypeOf2 = getPrototypeOf_default()(Audio)).call.apply(_getPrototypeOf2, [this].concat(args)));
  36068. defineProperty_default()(assertThisInitialized_default()(assertThisInitialized_default()(_this)), "removeAudio", function () {
  36069. _this.props.editor.setValue(external_braft_utils_["ContentUtils"].removeBlock(_this.props.editorState, _this.props.block));
  36070. });
  36071. return _this;
  36072. }
  36073. createClass_default()(Audio, [{
  36074. key: "render",
  36075. value: function render() {
  36076. var _this$props = this.props,
  36077. mediaData = _this$props.mediaData,
  36078. language = _this$props.language;
  36079. var url = mediaData.url,
  36080. name = mediaData.name,
  36081. meta = mediaData.meta;
  36082. return external_react_default.a.createElement("div", {
  36083. className: "bf-audio-wrap"
  36084. }, external_react_default.a.createElement(PlayerModal, {
  36085. type: "audio",
  36086. onRemove: this.removeAudio,
  36087. poster: meta ? meta.poster || '' : '',
  36088. language: language,
  36089. url: url,
  36090. name: name,
  36091. title: language.audioPlayer.title
  36092. }, external_react_default.a.createElement("div", {
  36093. className: "bf-audio-player"
  36094. }, external_react_default.a.createElement("audio", {
  36095. controls: true,
  36096. src: url
  36097. }))));
  36098. }
  36099. }]);
  36100. return Audio;
  36101. }(external_react_default.a.Component);
  36102. // EXTERNAL MODULE: ./renderers/atomics/Embed/style.scss
  36103. var Embed_style = __webpack_require__(51);
  36104. // CONCATENATED MODULE: ./renderers/atomics/Embed/index.jsx
  36105. var Embed_Embed =
  36106. /*#__PURE__*/
  36107. function (_React$Component) {
  36108. inherits_default()(Embed, _React$Component);
  36109. function Embed() {
  36110. var _getPrototypeOf2;
  36111. var _this;
  36112. classCallCheck_default()(this, Embed);
  36113. for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
  36114. args[_key] = arguments[_key];
  36115. }
  36116. _this = possibleConstructorReturn_default()(this, (_getPrototypeOf2 = getPrototypeOf_default()(Embed)).call.apply(_getPrototypeOf2, [this].concat(args)));
  36117. defineProperty_default()(assertThisInitialized_default()(assertThisInitialized_default()(_this)), "removeEmbed", function () {
  36118. _this.props.editor.setValue(external_braft_utils_["ContentUtils"].removeBlock(_this.props.editorState, _this.props.block));
  36119. });
  36120. return _this;
  36121. }
  36122. createClass_default()(Embed, [{
  36123. key: "render",
  36124. value: function render() {
  36125. var _this$props = this.props,
  36126. mediaData = _this$props.mediaData,
  36127. language = _this$props.language;
  36128. var name = mediaData.name,
  36129. url = mediaData.url,
  36130. meta = mediaData.meta;
  36131. return external_react_default.a.createElement("div", {
  36132. className: "bf-embed-wrap"
  36133. }, external_react_default.a.createElement(PlayerModal, {
  36134. type: "embed",
  36135. onRemove: this.removeEmbed,
  36136. poster: meta ? meta.poster || '' : '',
  36137. language: language,
  36138. url: url,
  36139. name: name,
  36140. title: language.videoPlayer.embedTitle
  36141. }, external_react_default.a.createElement("div", {
  36142. className: "bf-embed-player",
  36143. dangerouslySetInnerHTML: {
  36144. __html: url
  36145. }
  36146. })));
  36147. }
  36148. }]);
  36149. return Embed;
  36150. }(external_react_default.a.Component);
  36151. // EXTERNAL MODULE: ./renderers/atomics/HorizontalLine/style.scss
  36152. var HorizontalLine_style = __webpack_require__(52);
  36153. // CONCATENATED MODULE: ./renderers/atomics/HorizontalLine/index.jsx
  36154. var HorizontalLine_HorizontalLine =
  36155. /*#__PURE__*/
  36156. function (_React$Component) {
  36157. inherits_default()(HorizontalLine, _React$Component);
  36158. function HorizontalLine() {
  36159. var _getPrototypeOf2;
  36160. var _this;
  36161. classCallCheck_default()(this, HorizontalLine);
  36162. for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
  36163. args[_key] = arguments[_key];
  36164. }
  36165. _this = possibleConstructorReturn_default()(this, (_getPrototypeOf2 = getPrototypeOf_default()(HorizontalLine)).call.apply(_getPrototypeOf2, [this].concat(args)));
  36166. defineProperty_default()(assertThisInitialized_default()(assertThisInitialized_default()(_this)), "removeHorizontalLine", function () {
  36167. _this.props.editor.setValue(external_braft_utils_["ContentUtils"].removeBlock(_this.props.editorState, _this.props.block));
  36168. });
  36169. return _this;
  36170. }
  36171. createClass_default()(HorizontalLine, [{
  36172. key: "render",
  36173. value: function render() {
  36174. return external_react_default.a.createElement("div", {
  36175. className: "bf-hr"
  36176. }, external_react_default.a.createElement("div", {
  36177. className: "bf-media-toolbar"
  36178. }, external_react_default.a.createElement("a", {
  36179. onClick: this.removeHorizontalLine
  36180. }, "\uE9AC")));
  36181. }
  36182. }]);
  36183. return HorizontalLine;
  36184. }(external_react_default.a.Component);
  36185. // CONCATENATED MODULE: ./renderers/block/blockRendererFn.js
  36186. var blockRendererFn_BlockRenderFnContext = function BlockRenderFnContext() {
  36187. var _this = this;
  36188. classCallCheck_default()(this, BlockRenderFnContext);
  36189. defineProperty_default()(this, "superProps", void 0);
  36190. defineProperty_default()(this, "customBlockRendererFn", void 0);
  36191. defineProperty_default()(this, "getRenderFn", function (superProps, customBlockRendererFn) {
  36192. _this.superProps = superProps;
  36193. _this.customBlockRendererFn = customBlockRendererFn;
  36194. return _this.blockRendererFn;
  36195. });
  36196. defineProperty_default()(this, "renderAtomicBlock", function (props) {
  36197. var superProps = _this.superProps;
  36198. var entityKey = props.block.getEntityAt(0);
  36199. if (!entityKey) {
  36200. return null;
  36201. }
  36202. var entity = props.contentState.getEntity(entityKey);
  36203. var mediaData = entity.getData();
  36204. var mediaType = entity.getType();
  36205. var mediaProps = objectSpread_default()({}, superProps, {
  36206. block: props.block,
  36207. mediaData: mediaData,
  36208. entityKey: entityKey
  36209. });
  36210. if (mediaType === 'IMAGE') {
  36211. return external_react_default.a.createElement(Image_Image, mediaProps);
  36212. } else if (mediaType === 'AUDIO') {
  36213. return external_react_default.a.createElement(Audio_Audio, mediaProps);
  36214. } else if (mediaType === 'VIDEO') {
  36215. return external_react_default.a.createElement(Video_Video, mediaProps);
  36216. } else if (mediaType === 'EMBED') {
  36217. return external_react_default.a.createElement(Embed_Embed, mediaProps);
  36218. } else if (mediaType === 'HR') {
  36219. return external_react_default.a.createElement(HorizontalLine_HorizontalLine, mediaProps);
  36220. }
  36221. if (superProps.extendAtomics) {
  36222. var atomics = superProps.extendAtomics;
  36223. for (var i = 0; i < atomics.length; i++) {
  36224. if (mediaType === atomics[i].type) {
  36225. var Component = atomics[i].component;
  36226. return external_react_default.a.createElement(Component, mediaProps);
  36227. }
  36228. }
  36229. }
  36230. return null;
  36231. });
  36232. defineProperty_default()(this, "blockRendererFn", function (block) {
  36233. var customBlockRendererFn = _this.customBlockRendererFn,
  36234. superProps = _this.superProps;
  36235. var blockType = block.getType();
  36236. var blockRenderer = null;
  36237. if (customBlockRendererFn) {
  36238. blockRenderer = customBlockRendererFn(block, superProps) || null;
  36239. }
  36240. if (blockRenderer) {
  36241. return blockRenderer;
  36242. }
  36243. var extensionBlockRendererFns = getExtensionBlockRendererFns(superProps.editorId);
  36244. extensionBlockRendererFns.find(function (item) {
  36245. if (item.blockType === blockType || item.blockType instanceof RegExp && item.blockType.test(blockType)) {
  36246. blockRenderer = item.rendererFn ? item.rendererFn(superProps) : null;
  36247. return true;
  36248. }
  36249. });
  36250. if (blockRenderer) {
  36251. return blockRenderer;
  36252. }
  36253. if (blockType === 'atomic') {
  36254. blockRenderer = {
  36255. component: _this.renderAtomicBlock,
  36256. editable: false
  36257. };
  36258. }
  36259. return blockRenderer;
  36260. });
  36261. };
  36262. var blockRenderFnContext = new blockRendererFn_BlockRenderFnContext();
  36263. /* harmony default export */ var block_blockRendererFn = (blockRenderFnContext.getRenderFn);
  36264. // CONCATENATED MODULE: ./renderers/block/blockStyleFn.js
  36265. /* harmony default export */ var block_blockStyleFn = (function (customBlockStyleFn) {
  36266. return function (block) {
  36267. var blockAlignment = block.getData() && block.getData().get('textAlign');
  36268. var blockIndent = block.getData() && block.getData().get('textIndent');
  36269. var blockFloat = block.getData() && block.getData().get('float');
  36270. var result = '';
  36271. if (blockAlignment) {
  36272. result = "bfa-".concat(blockAlignment);
  36273. }
  36274. if (blockIndent && blockIndent !== 0) {
  36275. result += " bftd-".concat(blockIndent);
  36276. }
  36277. if (blockFloat) {
  36278. result += " bff-".concat(blockFloat);
  36279. }
  36280. if (customBlockStyleFn) {
  36281. result += customBlockStyleFn(block) || '';
  36282. }
  36283. return result;
  36284. };
  36285. });
  36286. // CONCATENATED MODULE: ./renderers/inline/inlineStyleMap.js
  36287. /* harmony default export */ var inlineStyleMap = (function (props) {
  36288. var customStyleMap = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
  36289. var extensionInlineStyleMap = getExtensionInlineStyleMap(props.editorId);
  36290. return objectSpread_default()({
  36291. 'SUPERSCRIPT': {
  36292. position: 'relative',
  36293. top: '-8px',
  36294. fontSize: '11px'
  36295. },
  36296. 'SUBSCRIPT': {
  36297. position: 'relative',
  36298. bottom: '-8px',
  36299. fontSize: '11px'
  36300. }
  36301. }, extensionInlineStyleMap, customStyleMap);
  36302. });
  36303. // CONCATENATED MODULE: ./renderers/inline/inlineStyleFn.js
  36304. var getStyleValue = function getStyleValue(style) {
  36305. return style.split('-')[1];
  36306. };
  36307. /* harmony default export */ var inlineStyleFn = (function (props, options) {
  36308. return function (styles, block) {
  36309. var output = {};
  36310. var fontFamilies = options.fontFamilies,
  36311. unitExportFn = options.unitExportFn,
  36312. customStyleFn = options.customStyleFn;
  36313. var extensionInlineStyleFns = getExtensionInlineStyleFns(props.editorId);
  36314. extensionInlineStyleFns.forEach(function (item) {
  36315. output = item.styleFn ? item.styleFn(styles, block, output) : output;
  36316. });
  36317. output = customStyleFn ? customStyleFn(styles, block, output) : {};
  36318. styles.forEach(function (style) {
  36319. if (style.indexOf('COLOR-') === 0) {
  36320. output.color = '#' + getStyleValue(style);
  36321. } else if (style.indexOf('BGCOLOR-') === 0) {
  36322. output.backgroundColor = '#' + getStyleValue(style);
  36323. } else if (style.indexOf('FONTSIZE-') === 0) {
  36324. output.fontSize = unitExportFn(getStyleValue(style), 'font-size', 'editor');
  36325. } else if (style.indexOf('LINEHEIGHT-') === 0) {
  36326. output.lineHeight = unitExportFn(getStyleValue(style), 'line-height', 'editor');
  36327. } else if (style.indexOf('LETTERSPACING-') === 0) {
  36328. output.letterSpacing = unitExportFn(getStyleValue(style), 'letter-spacing', 'editor');
  36329. } else if (style.indexOf('TEXTINDENT-') === 0) {
  36330. output.textIndent = unitExportFn(getStyleValue(style), 'text-indent', 'editor');
  36331. } else if (style.indexOf('FONTFAMILY-') === 0) {
  36332. output.fontFamily = (fontFamilies.find(function (item) {
  36333. return item.name.toUpperCase() === getStyleValue(style);
  36334. }) || {}).family || '';
  36335. }
  36336. });
  36337. return output;
  36338. };
  36339. });
  36340. // EXTERNAL MODULE: ../node_modules/draft-js-multidecorators/index.js
  36341. var draft_js_multidecorators = __webpack_require__(18);
  36342. var draft_js_multidecorators_default = /*#__PURE__*/__webpack_require__.n(draft_js_multidecorators);
  36343. // CONCATENATED MODULE: ./renderers/decorators/Link/index.jsx
  36344. /* harmony default export */ var Link = (function (props) {
  36345. var children = props.children,
  36346. entityKey = props.entityKey,
  36347. contentState = props.contentState;
  36348. var _contentState$getEnti = contentState.getEntity(entityKey).getData(),
  36349. href = _contentState$getEnti.href,
  36350. target = _contentState$getEnti.target;
  36351. return external_react_default.a.createElement("span", {
  36352. className: "bf-link-wrap"
  36353. }, external_react_default.a.createElement("a", {
  36354. onClick: function onClick(event) {
  36355. return viewLink(event, href);
  36356. },
  36357. className: "bf-link",
  36358. href: href,
  36359. target: target
  36360. }, children));
  36361. });
  36362. var viewLink = function viewLink(event, link) {
  36363. // 当按下Ctrl/command键时,点击打开链接文字中的url
  36364. if (event.getModifierState('Control') || event.getModifierState('Meta')) {
  36365. var tempLink = document.createElement('a');
  36366. tempLink.href = link;
  36367. tempLink.target = event.currentTarget.target;
  36368. tempLink.click();
  36369. }
  36370. };
  36371. // CONCATENATED MODULE: ./renderers/decorators/index.js
  36372. var KEY_SEPARATOR = '-';
  36373. draft_js_multidecorators_default.a.prototype.getDecorations = function (block, contentState) {
  36374. var decorations = Array(block.getText().length).fill(null);
  36375. this.decorators.forEach(function (decorator, i) {
  36376. decorator.getDecorations(block, contentState).forEach(function (key, offset) {
  36377. if (!key) {
  36378. return;
  36379. }
  36380. key = i + KEY_SEPARATOR + key;
  36381. decorations[offset] = key;
  36382. });
  36383. });
  36384. return external_immutable_default.a.List(decorations);
  36385. };
  36386. var builtinDecorators = [{
  36387. type: 'entity',
  36388. decorator: {
  36389. key: 'LINK',
  36390. component: Link
  36391. }
  36392. }];
  36393. var createStrategy = function createStrategy(type) {
  36394. return function (block, callback, contentState) {
  36395. block.findEntityRanges(function (character) {
  36396. var entityKey = character.getEntity();
  36397. return entityKey !== null && contentState.getEntity(entityKey).getType() === type;
  36398. }, callback);
  36399. };
  36400. };
  36401. /* harmony default export */ var decorators = (function (editorId) {
  36402. var extensionDecorators = getExtensionDecorators(editorId);
  36403. var entityDecorators = builtinDecorators.concat(toConsumableArray_default()(extensionDecorators.filter(function (item) {
  36404. return item.type === 'entity';
  36405. })));
  36406. var strategyDecorators = extensionDecorators.filter(function (item) {
  36407. return item.type === 'strategy';
  36408. });
  36409. var classDecorators = extensionDecorators.filter(function (item) {
  36410. return item.type === 'class';
  36411. });
  36412. return new draft_js_multidecorators_default.a(toConsumableArray_default()(classDecorators.map(function (item) {
  36413. return item.decorator;
  36414. })).concat([// combine decorators created with strategy
  36415. new external_draft_js_["CompositeDecorator"](strategyDecorators.map(function (item) {
  36416. return item.decorator;
  36417. })), // combine decorators for entities
  36418. new external_draft_js_["CompositeDecorator"](entityDecorators.map(function (item) {
  36419. return {
  36420. strategy: createStrategy(item.decorator.key),
  36421. component: item.decorator.component
  36422. };
  36423. }))]));
  36424. });
  36425. // CONCATENATED MODULE: ./renderers/index.js
  36426. var getBlockRenderMap = block_blockRenderMap;
  36427. var getBlockRendererFn = block_blockRendererFn;
  36428. var getBlockStyleFn = block_blockStyleFn;
  36429. var getCustomStyleMap = inlineStyleMap;
  36430. var getCustomStyleFn = inlineStyleFn;
  36431. var getDecorators = decorators;
  36432. // EXTERNAL MODULE: ./components/business/ControlBar/style.scss
  36433. var ControlBar_style = __webpack_require__(53);
  36434. // EXTERNAL MODULE: ./components/business/LinkEditor/style.scss
  36435. var LinkEditor_style = __webpack_require__(54);
  36436. // EXTERNAL MODULE: ./components/common/DropDown/style.scss
  36437. var DropDown_style = __webpack_require__(55);
  36438. // CONCATENATED MODULE: ./helpers/responsive.js
  36439. var resizeEventHandlers = [];
  36440. var responsiveHelperInited = false;
  36441. var debouce = false;
  36442. /* harmony default export */ var responsive = ({
  36443. resolve: function resolve(eventHandler) {
  36444. var id = external_braft_utils_["BaseUtils"].UniqueIndex();
  36445. resizeEventHandlers.push({
  36446. id: id,
  36447. eventHandler: eventHandler
  36448. });
  36449. return id;
  36450. },
  36451. unresolve: function unresolve(id) {
  36452. resizeEventHandlers = resizeEventHandlers.filter(function (item) {
  36453. return item.id !== id;
  36454. });
  36455. }
  36456. });
  36457. if (!responsiveHelperInited && (typeof window === "undefined" ? "undefined" : typeof_default()(window)) === 'object') {
  36458. window.addEventListener('resize', function (event) {
  36459. clearTimeout(debouce);
  36460. debouce = setTimeout(function () {
  36461. resizeEventHandlers.map(function (item) {
  36462. typeof item.eventHandler === 'function' && item.eventHandler(event);
  36463. });
  36464. debouce = false;
  36465. }, 100);
  36466. });
  36467. responsiveHelperInited = true;
  36468. }
  36469. // CONCATENATED MODULE: ./components/common/DropDown/index.jsx
  36470. var DropDown_DropDown =
  36471. /*#__PURE__*/
  36472. function (_React$Component) {
  36473. inherits_default()(DropDown, _React$Component);
  36474. function DropDown() {
  36475. var _getPrototypeOf2;
  36476. var _this;
  36477. classCallCheck_default()(this, DropDown);
  36478. for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
  36479. args[_key] = arguments[_key];
  36480. }
  36481. _this = possibleConstructorReturn_default()(this, (_getPrototypeOf2 = getPrototypeOf_default()(DropDown)).call.apply(_getPrototypeOf2, [this].concat(args)));
  36482. defineProperty_default()(assertThisInitialized_default()(assertThisInitialized_default()(_this)), "responsiveResolveId", null);
  36483. defineProperty_default()(assertThisInitialized_default()(assertThisInitialized_default()(_this)), "dropDownHandlerElement", null);
  36484. defineProperty_default()(assertThisInitialized_default()(assertThisInitialized_default()(_this)), "dropDownContentElement", null);
  36485. defineProperty_default()(assertThisInitialized_default()(assertThisInitialized_default()(_this)), "state", {
  36486. active: false,
  36487. offset: 0
  36488. });
  36489. defineProperty_default()(assertThisInitialized_default()(assertThisInitialized_default()(_this)), "fixDropDownPosition", function () {
  36490. var viewRect = _this.props.getContainerNode().getBoundingClientRect();
  36491. var handlerRect = _this.dropDownHandlerElement.getBoundingClientRect();
  36492. var contentRect = _this.dropDownContentElement.getBoundingClientRect();
  36493. var offset = 0;
  36494. var right = handlerRect.right - handlerRect.width / 2 + contentRect.width / 2;
  36495. var left = handlerRect.left + handlerRect.width / 2 - contentRect.width / 2;
  36496. right = viewRect.right - right;
  36497. left = left - viewRect.left;
  36498. if (right < 10) {
  36499. offset = right - 10;
  36500. } else if (left < 10) {
  36501. offset = left * -1 + 10;
  36502. }
  36503. if (offset !== _this.state.offset) {
  36504. _this.setState({
  36505. offset: offset
  36506. });
  36507. }
  36508. });
  36509. defineProperty_default()(assertThisInitialized_default()(assertThisInitialized_default()(_this)), "registerClickEvent", function (event) {
  36510. var autoHide = _this.props.autoHide;
  36511. var active = _this.state.active;
  36512. if (_this.dropDownContentElement.contains(event.target) || _this.dropDownHandlerElement.contains(event.target)) {
  36513. return false;
  36514. }
  36515. autoHide && active && _this.hide();
  36516. });
  36517. defineProperty_default()(assertThisInitialized_default()(assertThisInitialized_default()(_this)), "toggle", function () {
  36518. _this.setState({
  36519. active: !_this.state.active
  36520. });
  36521. });
  36522. defineProperty_default()(assertThisInitialized_default()(assertThisInitialized_default()(_this)), "show", function () {
  36523. _this.setState({
  36524. active: true
  36525. });
  36526. });
  36527. defineProperty_default()(assertThisInitialized_default()(assertThisInitialized_default()(_this)), "hide", function () {
  36528. _this.setState({
  36529. active: false
  36530. });
  36531. });
  36532. return _this;
  36533. }
  36534. createClass_default()(DropDown, [{
  36535. key: "componentDidMount",
  36536. value: function componentDidMount() {
  36537. if (document) {
  36538. document.body.addEventListener('click', this.registerClickEvent);
  36539. this.responsiveResolveId = responsive.resolve(this.fixDropDownPosition);
  36540. }
  36541. }
  36542. }, {
  36543. key: "componentWillReceiveProps",
  36544. value: function componentWillReceiveProps(next) {
  36545. if (!this.props.disabled && next.disabled) {
  36546. this.hide();
  36547. }
  36548. }
  36549. }, {
  36550. key: "componentDidUpdate",
  36551. value: function componentDidUpdate(prevState) {
  36552. if (!prevState.active && this.state.active) {
  36553. this.fixDropDownPosition();
  36554. }
  36555. }
  36556. }, {
  36557. key: "componentWillUnmount",
  36558. value: function componentWillUnmount() {
  36559. if (document) {
  36560. document.body.removeEventListener('click', this.registerClickEvent);
  36561. responsive.unresolve(this.responsiveResolveId);
  36562. }
  36563. }
  36564. }, {
  36565. key: "render",
  36566. value: function render() {
  36567. var _this2 = this;
  36568. var _this$state = this.state,
  36569. active = _this$state.active,
  36570. offset = _this$state.offset;
  36571. var _this$props = this.props,
  36572. caption = _this$props.caption,
  36573. htmlCaption = _this$props.htmlCaption,
  36574. title = _this$props.title,
  36575. disabled = _this$props.disabled,
  36576. showArrow = _this$props.showArrow,
  36577. arrowActive = _this$props.arrowActive,
  36578. className = _this$props.className,
  36579. children = _this$props.children,
  36580. theme = _this$props.theme;
  36581. disabled && (active = false);
  36582. theme === 'light' && (className = ' light-theme ' + className);
  36583. return external_react_default.a.createElement("div", {
  36584. className: 'bf-dropdown ' + (active ? 'active ' : '') + (disabled ? 'disabled ' : '') + className
  36585. }, htmlCaption ? external_react_default.a.createElement("button", {
  36586. type: "button",
  36587. className: "dropdown-handler",
  36588. "data-title": title,
  36589. onClick: this.toggle,
  36590. dangerouslySetInnerHTML: htmlCaption ? {
  36591. __html: htmlCaption
  36592. } : null,
  36593. ref: function ref(instance) {
  36594. return _this2.dropDownHandlerElement = instance;
  36595. }
  36596. }) : external_react_default.a.createElement("button", {
  36597. type: "button",
  36598. className: "dropdown-handler",
  36599. "data-title": title,
  36600. onClick: this.toggle,
  36601. ref: function ref(instance) {
  36602. return _this2.dropDownHandlerElement = instance;
  36603. }
  36604. }, external_react_default.a.createElement("span", null, caption), showArrow !== false ? external_react_default.a.createElement("i", {
  36605. className: "bfi-drop-down"
  36606. }) : null), external_react_default.a.createElement("div", {
  36607. className: "dropdown-content",
  36608. style: {
  36609. marginLeft: offset
  36610. },
  36611. ref: function ref(instance) {
  36612. return _this2.dropDownContentElement = instance;
  36613. }
  36614. }, external_react_default.a.createElement("i", {
  36615. style: {
  36616. marginLeft: offset * -1
  36617. },
  36618. className: 'dropdown-arrow' + (arrowActive ? ' active' : '')
  36619. }), external_react_default.a.createElement("div", {
  36620. className: "dropdown-content-inner"
  36621. }, children)));
  36622. }
  36623. }]);
  36624. return DropDown;
  36625. }(external_react_default.a.Component);
  36626. // CONCATENATED MODULE: ./components/business/ControlGroup/index.jsx
  36627. /* harmony default export */ var ControlGroup = (function (props) {
  36628. if (external_react_default.a.Fragment) {
  36629. return external_react_default.a.createElement(external_react_default.a.Fragment, null, props.children);
  36630. } else {
  36631. return external_react_default.a.createElement("div", {
  36632. className: "control-item-group"
  36633. }, props.children);
  36634. }
  36635. });
  36636. // CONCATENATED MODULE: ./components/business/LinkEditor/index.jsx
  36637. var LinkEditor_LinkEditor =
  36638. /*#__PURE__*/
  36639. function (_React$Component) {
  36640. inherits_default()(LinkEditor, _React$Component);
  36641. function LinkEditor(props) {
  36642. var _this;
  36643. classCallCheck_default()(this, LinkEditor);
  36644. _this = possibleConstructorReturn_default()(this, getPrototypeOf_default()(LinkEditor).call(this, props));
  36645. defineProperty_default()(assertThisInitialized_default()(assertThisInitialized_default()(_this)), "dropDownInstance", null);
  36646. defineProperty_default()(assertThisInitialized_default()(assertThisInitialized_default()(_this)), "handeKeyDown", function (e) {
  36647. if (e.keyCode === 13) {
  36648. _this.handleConfirm();
  36649. e.preventDefault();
  36650. return false;
  36651. }
  36652. });
  36653. defineProperty_default()(assertThisInitialized_default()(assertThisInitialized_default()(_this)), "handleTnputText", function (e) {
  36654. _this.setState({
  36655. text: e.currentTarget.value
  36656. });
  36657. });
  36658. defineProperty_default()(assertThisInitialized_default()(assertThisInitialized_default()(_this)), "handleInputLink", function (e) {
  36659. _this.setState({
  36660. href: e.currentTarget.value
  36661. });
  36662. });
  36663. defineProperty_default()(assertThisInitialized_default()(assertThisInitialized_default()(_this)), "setTarget", function () {
  36664. _this.setState({
  36665. target: _this.state.target === '_blank' ? '' : '_blank'
  36666. });
  36667. });
  36668. defineProperty_default()(assertThisInitialized_default()(assertThisInitialized_default()(_this)), "handleCancel", function () {
  36669. _this.dropDownInstance.hide();
  36670. });
  36671. defineProperty_default()(assertThisInitialized_default()(assertThisInitialized_default()(_this)), "handleUnlink", function () {
  36672. _this.dropDownInstance.hide();
  36673. _this.props.editor.setValue(external_braft_utils_["ContentUtils"].toggleSelectionLink(_this.props.editorState, false));
  36674. });
  36675. defineProperty_default()(assertThisInitialized_default()(assertThisInitialized_default()(_this)), "handleConfirm", function () {
  36676. var _this$state = _this.state,
  36677. text = _this$state.text,
  36678. href = _this$state.href,
  36679. target = _this$state.target,
  36680. textSelected = _this$state.textSelected;
  36681. var hookReturns = _this.props.hooks('toggle-link', {
  36682. href: href,
  36683. target: target
  36684. })({
  36685. href: href,
  36686. target: target
  36687. });
  36688. _this.dropDownInstance.hide();
  36689. _this.props.editor.requestFocus();
  36690. if (hookReturns === false) {
  36691. return false;
  36692. }
  36693. if (hookReturns) {
  36694. typeof hookReturns.href === 'string' && (href = hookReturns.href);
  36695. typeof hookReturns.target === 'string' && (target = hookReturns.target);
  36696. }
  36697. if (textSelected) {
  36698. if (href) {
  36699. _this.props.editor.setValue(external_braft_utils_["ContentUtils"].toggleSelectionLink(_this.props.editorState, href, target));
  36700. } else {
  36701. _this.props.editor.setValue(external_braft_utils_["ContentUtils"].toggleSelectionLink(_this.props.editorState, false));
  36702. }
  36703. } else {
  36704. _this.props.editor.setValue(external_braft_utils_["ContentUtils"].insertText(_this.props.editorState, text || href, null, {
  36705. type: 'LINK',
  36706. data: {
  36707. href: href,
  36708. target: target
  36709. }
  36710. }));
  36711. }
  36712. });
  36713. _this.state = {
  36714. text: '',
  36715. href: '',
  36716. target: props.defaultLinkTarget || '',
  36717. textSelected: false
  36718. };
  36719. return _this;
  36720. }
  36721. createClass_default()(LinkEditor, [{
  36722. key: "componentWillReceiveProps",
  36723. value: function componentWillReceiveProps(nextProps) {
  36724. var _ContentUtils$getSele = external_braft_utils_["ContentUtils"].getSelectionEntityData(nextProps.editorState, 'LINK'),
  36725. href = _ContentUtils$getSele.href,
  36726. target = _ContentUtils$getSele.target;
  36727. var textSelected = !external_braft_utils_["ContentUtils"].isSelectionCollapsed(this.props.editorState) && external_braft_utils_["ContentUtils"].getSelectionBlockType(this.props.editorState) !== 'atomic';
  36728. var selectedText = '';
  36729. if (textSelected) {
  36730. selectedText = external_braft_utils_["ContentUtils"].getSelectionText(this.props.editorState);
  36731. }
  36732. this.setState({
  36733. textSelected: textSelected,
  36734. text: selectedText,
  36735. href: href || '',
  36736. target: typeof target === 'undefined' ? nextProps.defaultLinkTarget || '' : target || ''
  36737. });
  36738. }
  36739. }, {
  36740. key: "render",
  36741. value: function render() {
  36742. var _this2 = this;
  36743. var allowInsertLinkText = this.props.allowInsertLinkText;
  36744. var _this$state2 = this.state,
  36745. text = _this$state2.text,
  36746. href = _this$state2.href,
  36747. target = _this$state2.target,
  36748. textSelected = _this$state2.textSelected;
  36749. var caption = external_react_default.a.createElement("i", {
  36750. className: "bfi-link"
  36751. });
  36752. return external_react_default.a.createElement(ControlGroup, null, external_react_default.a.createElement(DropDown_DropDown, {
  36753. key: 0,
  36754. caption: caption,
  36755. title: this.props.language.controls.link,
  36756. autoHide: true,
  36757. getContainerNode: this.props.getContainerNode,
  36758. showArrow: false,
  36759. ref: function ref(instance) {
  36760. return _this2.dropDownInstance = instance;
  36761. },
  36762. className: 'control-item dropdown link-editor-dropdown'
  36763. }, external_react_default.a.createElement("div", {
  36764. className: "bf-link-editor"
  36765. }, allowInsertLinkText ? external_react_default.a.createElement("div", {
  36766. className: "input-group"
  36767. }, external_react_default.a.createElement("input", {
  36768. type: "text",
  36769. value: text,
  36770. spellCheck: false,
  36771. disabled: textSelected,
  36772. placeholder: this.props.language.linkEditor.textInputPlaceHolder,
  36773. onKeyDown: this.handeKeyDown,
  36774. onChange: this.handleTnputText
  36775. })) : null, external_react_default.a.createElement("div", {
  36776. className: "input-group"
  36777. }, external_react_default.a.createElement("input", {
  36778. type: "text",
  36779. value: href,
  36780. spellCheck: false,
  36781. placeholder: this.props.language.linkEditor.linkInputPlaceHolder,
  36782. onKeyDown: this.handeKeyDown,
  36783. onChange: this.handleInputLink
  36784. })), external_react_default.a.createElement("div", {
  36785. className: "switch-group"
  36786. }, external_react_default.a.createElement(Switch, {
  36787. active: target === '_blank',
  36788. onClick: this.setTarget
  36789. }), external_react_default.a.createElement("label", null, this.props.language.linkEditor.openInNewWindow)), external_react_default.a.createElement("div", {
  36790. className: "buttons"
  36791. }, external_react_default.a.createElement("a", {
  36792. onClick: this.handleUnlink,
  36793. className: "primary button-remove-link pull-left"
  36794. }, external_react_default.a.createElement("i", {
  36795. className: "bfi-close"
  36796. }), external_react_default.a.createElement("span", null, this.props.language.linkEditor.removeLink)), external_react_default.a.createElement("button", {
  36797. type: "button",
  36798. onClick: this.handleConfirm,
  36799. className: "primary pull-right"
  36800. }, this.props.language.base.confirm), external_react_default.a.createElement("button", {
  36801. type: "button",
  36802. onClick: this.handleCancel,
  36803. className: "default pull-right"
  36804. }, this.props.language.base.cancel)))), external_react_default.a.createElement("button", {
  36805. key: 1,
  36806. type: "button",
  36807. "data-title": this.props.language.controls.unlink,
  36808. className: "control-item button",
  36809. onClick: this.handleUnlink,
  36810. disabled: !textSelected || !href
  36811. }, external_react_default.a.createElement("i", {
  36812. className: "bfi-link-off"
  36813. })));
  36814. }
  36815. }]);
  36816. return LinkEditor;
  36817. }(external_react_default.a.Component);
  36818. // EXTERNAL MODULE: ./components/business/Headings/style.scss
  36819. var Headings_style = __webpack_require__(56);
  36820. // CONCATENATED MODULE: ./configs/maps.js
  36821. var maps_getHeadings = function getHeadings(lang) {
  36822. return [{
  36823. key: 'header-one',
  36824. title: lang.controls.header + ' 1',
  36825. text: external_react_default.a.createElement("h1", null, lang.controls.header, " 1"),
  36826. type: 'block-type',
  36827. command: 'header-one'
  36828. }, {
  36829. key: 'header-two',
  36830. title: lang.controls.header + ' 2',
  36831. text: external_react_default.a.createElement("h2", null, lang.controls.header, " 2"),
  36832. type: 'block-type',
  36833. command: 'header-two'
  36834. }, {
  36835. key: 'header-three',
  36836. title: lang.controls.header + ' 3',
  36837. text: external_react_default.a.createElement("h3", null, lang.controls.header, " 3"),
  36838. type: 'block-type',
  36839. command: 'header-three'
  36840. }, {
  36841. key: 'header-four',
  36842. title: lang.controls.header + ' 4',
  36843. text: external_react_default.a.createElement("h4", null, lang.controls.header, " 4"),
  36844. type: 'block-type',
  36845. command: 'header-four'
  36846. }, {
  36847. key: 'header-five',
  36848. title: lang.controls.header + ' 5',
  36849. text: external_react_default.a.createElement("h5", null, lang.controls.header, " 5"),
  36850. type: 'block-type',
  36851. command: 'header-five'
  36852. }, {
  36853. key: 'header-six',
  36854. title: lang.controls.header + ' 6',
  36855. text: external_react_default.a.createElement("h6", null, lang.controls.header, " 6"),
  36856. type: 'block-type',
  36857. command: 'header-six'
  36858. }, {
  36859. key: 'unstyled',
  36860. title: lang.controls.normal,
  36861. text: lang.controls.normal,
  36862. type: 'block-type',
  36863. command: 'unstyled'
  36864. }];
  36865. };
  36866. // CONCATENATED MODULE: ./components/business/Headings/index.jsx
  36867. /* harmony default export */ var Headings = (function (props) {
  36868. var dropDownInstance = null;
  36869. var headings = maps_getHeadings(props.language).filter(function (item) {
  36870. return props.headings.indexOf(item.key) !== -1;
  36871. });
  36872. var currentHeadingIndex = headings.findIndex(function (item) {
  36873. return item.command === props.current;
  36874. });
  36875. var caption = headings[currentHeadingIndex] ? headings[currentHeadingIndex].title : props.language.controls.normal;
  36876. return external_react_default.a.createElement(DropDown_DropDown, {
  36877. caption: caption,
  36878. autoHide: true,
  36879. getContainerNode: props.getContainerNode,
  36880. title: props.language.controls.headings,
  36881. arrowActive: currentHeadingIndex === 0,
  36882. ref: function ref(instance) {
  36883. return dropDownInstance = instance;
  36884. },
  36885. className: 'control-item dropdown headings-dropdown'
  36886. }, external_react_default.a.createElement("ul", {
  36887. className: "menu"
  36888. }, headings.map(function (item, index) {
  36889. var isActive = props.current === item.command;
  36890. return external_react_default.a.createElement("li", {
  36891. key: index,
  36892. className: 'menu-item' + (isActive ? ' active' : ''),
  36893. onClick: function onClick() {
  36894. props.onChange(item.command, item.type), dropDownInstance.hide();
  36895. }
  36896. }, item.text);
  36897. })));
  36898. });
  36899. // EXTERNAL MODULE: ./components/business/TextColor/style.scss
  36900. var TextColor_style = __webpack_require__(57);
  36901. // EXTERNAL MODULE: ./components/common/ColorPicker/style.scss
  36902. var ColorPicker_style = __webpack_require__(58);
  36903. // CONCATENATED MODULE: ./components/common/ColorPicker/index.jsx
  36904. /* harmony default export */ var common_ColorPicker = (function (props) {
  36905. return external_react_default.a.createElement("div", {
  36906. className: "bf-colors-wrap"
  36907. }, external_react_default.a.createElement("ul", {
  36908. className: "bf-colors"
  36909. }, props.presetColors.map(function (item, index) {
  36910. var className = props.color && item.toLowerCase() === props.color.toLowerCase() ? 'color-item active' : 'color-item';
  36911. return external_react_default.a.createElement("li", {
  36912. key: index,
  36913. title: item,
  36914. className: className,
  36915. style: {
  36916. color: item
  36917. },
  36918. "data-color": item.replace('#', ''),
  36919. onClick: function onClick(e) {
  36920. props.onChange(e.currentTarget.dataset.color, true);
  36921. }
  36922. });
  36923. })));
  36924. });
  36925. // CONCATENATED MODULE: ./components/business/TextColor/index.jsx
  36926. var TextColor_TextColor =
  36927. /*#__PURE__*/
  36928. function (_React$Component) {
  36929. inherits_default()(TextColor, _React$Component);
  36930. function TextColor() {
  36931. var _getPrototypeOf2;
  36932. var _this;
  36933. classCallCheck_default()(this, TextColor);
  36934. for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
  36935. args[_key] = arguments[_key];
  36936. }
  36937. _this = possibleConstructorReturn_default()(this, (_getPrototypeOf2 = getPrototypeOf_default()(TextColor)).call.apply(_getPrototypeOf2, [this].concat(args)));
  36938. defineProperty_default()(assertThisInitialized_default()(assertThisInitialized_default()(_this)), "state", {
  36939. colorType: 'color'
  36940. });
  36941. defineProperty_default()(assertThisInitialized_default()(assertThisInitialized_default()(_this)), "switchColorType", function (_ref) {
  36942. var currentTarget = _ref.currentTarget;
  36943. _this.setState({
  36944. colorType: currentTarget.dataset.type
  36945. });
  36946. });
  36947. defineProperty_default()(assertThisInitialized_default()(assertThisInitialized_default()(_this)), "toggleColor", function (color, closePicker) {
  36948. if (color) {
  36949. var hookReturns = _this.props.hooks("toggle-text-".concat(_this.state.colorType), color)(color);
  36950. if (hookReturns === false) {
  36951. return false;
  36952. }
  36953. if (typeof hookReturns === 'string') {
  36954. color = hookReturns;
  36955. }
  36956. if (_this.state.colorType === 'color') {
  36957. _this.props.editor.setValue(external_braft_utils_["ContentUtils"].toggleSelectionColor(_this.props.editorState, color));
  36958. } else {
  36959. _this.props.editor.setValue(external_braft_utils_["ContentUtils"].toggleSelectionBackgroundColor(_this.props.editorState, color));
  36960. }
  36961. }
  36962. if (closePicker) {
  36963. _this.dropDownInstance.hide();
  36964. _this.props.editor.requestFocus();
  36965. }
  36966. });
  36967. return _this;
  36968. }
  36969. createClass_default()(TextColor, [{
  36970. key: "render",
  36971. value: function render() {
  36972. var _this2 = this;
  36973. var captionStyle = {};
  36974. var currentColor = null;
  36975. var colorType = this.state.colorType;
  36976. var selectionStyles = this.props.editorState.getCurrentInlineStyle().toJS();
  36977. selectionStyles.forEach(function (style) {
  36978. if (style.indexOf('COLOR-') === 0) {
  36979. captionStyle.color = '#' + style.split('-')[1];
  36980. colorType === 'color' && (currentColor = captionStyle.color);
  36981. }
  36982. if (style.indexOf('BGCOLOR-') === 0) {
  36983. captionStyle.backgroundColor = '#' + style.split('-')[1];
  36984. colorType === 'background-color' && (currentColor = captionStyle.backgroundColor);
  36985. }
  36986. });
  36987. var caption = external_react_default.a.createElement("i", {
  36988. style: captionStyle,
  36989. className: "bfi-text-color"
  36990. }, external_react_default.a.createElement("span", {
  36991. className: "path1"
  36992. }), external_react_default.a.createElement("span", {
  36993. className: "path2"
  36994. }));
  36995. var ColorPicker = this.props.colorPicker || common_ColorPicker;
  36996. return external_react_default.a.createElement(DropDown_DropDown, {
  36997. caption: caption,
  36998. title: this.props.language.controls.color,
  36999. showArrow: false,
  37000. autoHide: this.props.autoHide,
  37001. theme: this.props.theme,
  37002. getContainerNode: this.props.getContainerNode,
  37003. ref: function ref(instance) {
  37004. return _this2.dropDownInstance = instance;
  37005. },
  37006. className: 'control-item dropdown text-color-dropdown'
  37007. }, external_react_default.a.createElement("div", {
  37008. className: "bf-text-color-picker-wrap"
  37009. }, external_react_default.a.createElement("div", {
  37010. className: "bf-color-switch-buttons",
  37011. style: this.props.enableBackgroundColor ? {} : {
  37012. display: 'none'
  37013. }
  37014. }, external_react_default.a.createElement("button", {
  37015. type: "button",
  37016. "data-type": "color",
  37017. className: colorType === 'color' ? 'active' : '',
  37018. onClick: this.switchColorType
  37019. }, this.props.language.controls.textColor), external_react_default.a.createElement("button", {
  37020. type: "button",
  37021. "data-type": "background-color",
  37022. className: colorType === 'background-color' ? 'active' : '',
  37023. onClick: this.switchColorType
  37024. }, this.props.language.controls.backgroundColor)), external_react_default.a.createElement(ColorPicker, {
  37025. width: 200,
  37026. color: currentColor,
  37027. disableAlpha: true,
  37028. presetColors: this.props.colors,
  37029. onChange: this.toggleColor
  37030. })));
  37031. }
  37032. }]);
  37033. return TextColor;
  37034. }(external_react_default.a.Component);
  37035. // EXTERNAL MODULE: ./components/business/FontSize/style.scss
  37036. var FontSize_style = __webpack_require__(59);
  37037. // CONCATENATED MODULE: ./components/business/FontSize/index.jsx
  37038. var FontSize_toggleFontSize = function toggleFontSize(event, props) {
  37039. var fontSize = event.currentTarget.dataset.size;
  37040. var hookReturns = props.hooks('toggle-font-size', fontSize)(fontSize);
  37041. if (hookReturns === false) {
  37042. return false;
  37043. }
  37044. if (!isNaN(fontSize)) {
  37045. fontSize = hookReturns;
  37046. }
  37047. props.editor.setValue(external_braft_utils_["ContentUtils"].toggleSelectionFontSize(props.editorState, fontSize));
  37048. props.editor.requestFocus();
  37049. };
  37050. /* harmony default export */ var FontSize = (function (props) {
  37051. var caption = null;
  37052. var currentFontSize = null;
  37053. var dropDownInstance = null;
  37054. props.fontSizes.find(function (item) {
  37055. if (external_braft_utils_["ContentUtils"].selectionHasInlineStyle(props.editorState, 'FONTSIZE-' + item)) {
  37056. caption = item;
  37057. currentFontSize = item;
  37058. return true;
  37059. }
  37060. return false;
  37061. });
  37062. return external_react_default.a.createElement(DropDown_DropDown, {
  37063. autoHide: true,
  37064. caption: caption || props.defaultCaption,
  37065. getContainerNode: props.getContainerNode,
  37066. title: props.language.controls.fontSize,
  37067. ref: function ref(instance) {
  37068. return dropDownInstance = instance;
  37069. },
  37070. className: 'control-item dropdown bf-font-size-dropdown'
  37071. }, external_react_default.a.createElement("ul", {
  37072. className: "bf-font-sizes"
  37073. }, props.fontSizes.map(function (item, index) {
  37074. return external_react_default.a.createElement("li", {
  37075. key: index,
  37076. className: item === currentFontSize ? 'active' : null,
  37077. "data-size": item,
  37078. onClick: function onClick(event) {
  37079. FontSize_toggleFontSize(event, props), dropDownInstance.hide();
  37080. }
  37081. }, item);
  37082. })));
  37083. });
  37084. // EXTERNAL MODULE: ./components/business/LineHeight/style.scss
  37085. var LineHeight_style = __webpack_require__(60);
  37086. // CONCATENATED MODULE: ./components/business/LineHeight/index.jsx
  37087. var LineHeight_toggleLineHeight = function toggleLineHeight(event, props) {
  37088. var lineHeight = event.currentTarget.dataset.size;
  37089. var hookReturns = props.hooks('toggle-line-height', lineHeight)(lineHeight);
  37090. if (hookReturns === false) {
  37091. return false;
  37092. }
  37093. if (!isNaN(hookReturns)) {
  37094. lineHeight = hookReturns;
  37095. }
  37096. props.editor.setValue(external_braft_utils_["ContentUtils"].toggleSelectionLineHeight(props.editorState, lineHeight));
  37097. props.editor.requestFocus();
  37098. };
  37099. /* harmony default export */ var LineHeight = (function (props) {
  37100. var caption = null;
  37101. var currentLineHeight = null;
  37102. var dropDownInstance = null;
  37103. props.lineHeights.find(function (item) {
  37104. if (external_braft_utils_["ContentUtils"].selectionHasInlineStyle(props.editorState, 'LINEHEIGHT-' + item)) {
  37105. caption = item;
  37106. currentLineHeight = item;
  37107. return true;
  37108. }
  37109. return false;
  37110. });
  37111. return external_react_default.a.createElement(DropDown_DropDown, {
  37112. autoHide: true,
  37113. caption: caption || props.defaultCaption,
  37114. getContainerNode: props.getContainerNode,
  37115. title: props.language.controls.lineHeight,
  37116. ref: function ref(instance) {
  37117. return dropDownInstance = instance;
  37118. },
  37119. className: 'control-item dropdown bf-line-height-dropdown'
  37120. }, external_react_default.a.createElement("ul", {
  37121. className: "bf-line-heights"
  37122. }, props.lineHeights.map(function (item, index) {
  37123. return external_react_default.a.createElement("li", {
  37124. key: index,
  37125. className: item === currentLineHeight ? 'active' : null,
  37126. "data-size": item,
  37127. onClick: function onClick(event) {
  37128. LineHeight_toggleLineHeight(event, props), dropDownInstance.hide();
  37129. }
  37130. }, item);
  37131. })));
  37132. });
  37133. // EXTERNAL MODULE: ./components/business/FontFamily/style.scss
  37134. var FontFamily_style = __webpack_require__(61);
  37135. // CONCATENATED MODULE: ./components/business/FontFamily/index.jsx
  37136. var FontFamily_toggleFontFamily = function toggleFontFamily(event, props) {
  37137. var fontFamilyName = event.currentTarget.dataset.name;
  37138. var hookReturns = props.hooks('toggle-font-family', fontFamilyName)(fontFamilyName, props.fontFamilies);
  37139. if (hookReturns === false) {
  37140. return false;
  37141. }
  37142. if (typeof hookReturns === 'string') {
  37143. fontFamilyName = hookReturns;
  37144. }
  37145. props.editor.setValue(external_braft_utils_["ContentUtils"].toggleSelectionFontFamily(props.editorState, fontFamilyName));
  37146. props.editor.requestFocus();
  37147. };
  37148. /* harmony default export */ var FontFamily = (function (props) {
  37149. var caption = null;
  37150. var currentIndex = null;
  37151. var dropDownInstance = null;
  37152. props.fontFamilies.find(function (item, index) {
  37153. if (external_braft_utils_["ContentUtils"].selectionHasInlineStyle(props.editorState, 'FONTFAMILY-' + item.name)) {
  37154. caption = item.name;
  37155. currentIndex = index;
  37156. return true;
  37157. }
  37158. return false;
  37159. });
  37160. return external_react_default.a.createElement(DropDown_DropDown, {
  37161. caption: caption || props.defaultCaption,
  37162. getContainerNode: props.getContainerNode,
  37163. title: props.language.controls.fontFamily,
  37164. autoHide: true,
  37165. arrowActive: currentIndex === 0,
  37166. ref: function ref(instance) {
  37167. return dropDownInstance = instance;
  37168. },
  37169. className: 'control-item dropdown font-family-dropdown'
  37170. }, external_react_default.a.createElement("ul", {
  37171. className: "menu"
  37172. }, props.fontFamilies.map(function (item, index) {
  37173. return external_react_default.a.createElement("li", {
  37174. key: index,
  37175. className: 'menu-item ' + (index === currentIndex ? 'active' : ''),
  37176. "data-name": item.name,
  37177. onClick: function onClick(event) {
  37178. FontFamily_toggleFontFamily(event, props), dropDownInstance.hide();
  37179. }
  37180. }, external_react_default.a.createElement("span", {
  37181. style: {
  37182. fontFamily: item.family
  37183. }
  37184. }, item.name));
  37185. })));
  37186. });
  37187. // CONCATENATED MODULE: ./components/business/TextAlign/index.jsx
  37188. var TextAlign_TextAlign =
  37189. /*#__PURE__*/
  37190. function (_React$Component) {
  37191. inherits_default()(TextAlign, _React$Component);
  37192. function TextAlign() {
  37193. var _getPrototypeOf2;
  37194. var _this;
  37195. classCallCheck_default()(this, TextAlign);
  37196. for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
  37197. args[_key] = arguments[_key];
  37198. }
  37199. _this = possibleConstructorReturn_default()(this, (_getPrototypeOf2 = getPrototypeOf_default()(TextAlign)).call.apply(_getPrototypeOf2, [this].concat(args)));
  37200. defineProperty_default()(assertThisInitialized_default()(assertThisInitialized_default()(_this)), "state", {
  37201. currentAlignment: undefined
  37202. });
  37203. defineProperty_default()(assertThisInitialized_default()(assertThisInitialized_default()(_this)), "setAlignment", function (event) {
  37204. var alignment = event.currentTarget.dataset.alignment;
  37205. var hookReturns = _this.props.hooks('toggle-text-alignment', alignment)(alignment);
  37206. if (_this.props.textAligns.indexOf(hookReturns) > -1) {
  37207. alignment = hookReturns;
  37208. }
  37209. _this.props.editor.setValue(external_braft_utils_["ContentUtils"].toggleSelectionAlignment(_this.props.editorState, alignment));
  37210. _this.props.editor.requestFocus();
  37211. });
  37212. return _this;
  37213. }
  37214. createClass_default()(TextAlign, [{
  37215. key: "componentWillReceiveProps",
  37216. value: function componentWillReceiveProps(next) {
  37217. this.setState({
  37218. currentAlignment: external_braft_utils_["ContentUtils"].getSelectionBlockData(next.editorState, 'textAlign')
  37219. });
  37220. }
  37221. }, {
  37222. key: "render",
  37223. value: function render() {
  37224. var _this2 = this;
  37225. var textAlignmentTitles = [this.props.language.controls.alignLeft, this.props.language.controls.alignCenter, this.props.language.controls.alignRight, this.props.language.controls.alignJustify];
  37226. return external_react_default.a.createElement(ControlGroup, null, this.props.textAligns.map(function (item, index) {
  37227. return external_react_default.a.createElement("button", {
  37228. type: "button",
  37229. key: index,
  37230. "data-title": textAlignmentTitles[index],
  37231. "data-alignment": item,
  37232. className: 'control-item button ' + (item === _this2.state.currentAlignment ? 'active' : null),
  37233. onClick: _this2.setAlignment
  37234. }, external_react_default.a.createElement("i", {
  37235. className: 'bfi-align-' + item
  37236. }));
  37237. }));
  37238. }
  37239. }]);
  37240. return TextAlign;
  37241. }(external_react_default.a.Component);
  37242. // EXTERNAL MODULE: ./components/business/EmojiPicker/style.scss
  37243. var EmojiPicker_style = __webpack_require__(62);
  37244. // CONCATENATED MODULE: ./components/business/EmojiPicker/index.jsx
  37245. var EmojiPicker_insertEmoji = function insertEmoji(event, props) {
  37246. var emoji = event.currentTarget.dataset.emoji;
  37247. var hookReturns = props.hooks('insert-emoji', emoji)(emoji);
  37248. if (hookReturns === false) {
  37249. return false;
  37250. }
  37251. if (typeof hookReturns === 'string') {
  37252. emoji = hookReturns;
  37253. }
  37254. props.editor.setValue(external_braft_utils_["ContentUtils"].insertText(props.editorState, emoji));
  37255. props.editor.requestFocus();
  37256. };
  37257. /* harmony default export */ var EmojiPicker = (function (props) {
  37258. return external_react_default.a.createElement(DropDown_DropDown, {
  37259. caption: props.defaultCaption,
  37260. autoHide: true,
  37261. showArrow: false,
  37262. getContainerNode: props.getContainerNode,
  37263. title: props.language.controls.emoji,
  37264. className: 'control-item dropdown bf-emoji-dropdown'
  37265. }, external_react_default.a.createElement("div", {
  37266. className: "bf-emojis-wrap"
  37267. }, external_react_default.a.createElement("ul", {
  37268. className: "bf-emojis"
  37269. }, props.emojis.map(function (item, index) {
  37270. return external_react_default.a.createElement("li", {
  37271. key: index,
  37272. "data-emoji": item,
  37273. onClick: function onClick(event) {
  37274. return EmojiPicker_insertEmoji(event, props);
  37275. }
  37276. }, item);
  37277. }))));
  37278. });
  37279. // EXTERNAL MODULE: ./components/business/LetterSpacing/style.scss
  37280. var LetterSpacing_style = __webpack_require__(63);
  37281. // CONCATENATED MODULE: ./components/business/LetterSpacing/index.jsx
  37282. var LetterSpacing_toggleLetterSpacing = function toggleLetterSpacing(event, props) {
  37283. var letterSpacing = event.currentTarget.dataset.size;
  37284. var hookReturns = props.hooks('toggle-letter-spacing', letterSpacing)(letterSpacing);
  37285. if (hookReturns === false) {
  37286. return false;
  37287. }
  37288. if (!isNaN(hookReturns)) {
  37289. letterSpacing = hookReturns;
  37290. }
  37291. props.editor.setValue(external_braft_utils_["ContentUtils"].toggleSelectionLetterSpacing(props.editorState, letterSpacing));
  37292. props.editor.requestFocus();
  37293. };
  37294. /* harmony default export */ var LetterSpacing = (function (props) {
  37295. var caption = null;
  37296. var currentLetterSpacing = null;
  37297. var dropDownInstance = null;
  37298. props.letterSpacings.find(function (item) {
  37299. if (external_braft_utils_["ContentUtils"].selectionHasInlineStyle(props.editorState, 'LETTERSPACING-' + item)) {
  37300. caption = item;
  37301. currentLetterSpacing = item;
  37302. return true;
  37303. }
  37304. return false;
  37305. });
  37306. return external_react_default.a.createElement(DropDown_DropDown, {
  37307. autoHide: true,
  37308. caption: caption || props.defaultCaption,
  37309. getContainerNode: props.getContainerNode,
  37310. title: props.language.controls.letterSpacing,
  37311. ref: function ref(instance) {
  37312. return dropDownInstance = instance;
  37313. },
  37314. className: 'control-item dropdown bf-letter-spacing-dropdown'
  37315. }, external_react_default.a.createElement("ul", {
  37316. className: "bf-letter-spacings"
  37317. }, props.letterSpacings.map(function (item, index) {
  37318. return external_react_default.a.createElement("li", {
  37319. key: index,
  37320. className: item === currentLetterSpacing ? 'active' : null,
  37321. "data-size": item,
  37322. onClick: function onClick(event) {
  37323. LetterSpacing_toggleLetterSpacing(event, props), dropDownInstance.hide();
  37324. }
  37325. }, item);
  37326. })));
  37327. });
  37328. // CONCATENATED MODULE: ./components/business/TextIndent/index.jsx
  37329. var TextIndent_TextAlign =
  37330. /*#__PURE__*/
  37331. function (_React$Component) {
  37332. inherits_default()(TextAlign, _React$Component);
  37333. function TextAlign() {
  37334. var _getPrototypeOf2;
  37335. var _this;
  37336. classCallCheck_default()(this, TextAlign);
  37337. for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
  37338. args[_key] = arguments[_key];
  37339. }
  37340. _this = possibleConstructorReturn_default()(this, (_getPrototypeOf2 = getPrototypeOf_default()(TextAlign)).call.apply(_getPrototypeOf2, [this].concat(args)));
  37341. defineProperty_default()(assertThisInitialized_default()(assertThisInitialized_default()(_this)), "state", {
  37342. currentIndent: 0
  37343. });
  37344. defineProperty_default()(assertThisInitialized_default()(assertThisInitialized_default()(_this)), "increaseIndent", function () {
  37345. _this.props.editor.setValue(external_braft_utils_["ContentUtils"].increaseSelectionIndent(_this.props.editorState));
  37346. _this.props.editor.requestFocus();
  37347. });
  37348. defineProperty_default()(assertThisInitialized_default()(assertThisInitialized_default()(_this)), "decreaseIndent", function () {
  37349. _this.props.editor.setValue(external_braft_utils_["ContentUtils"].decreaseSelectionIndent(_this.props.editorState));
  37350. _this.props.editor.requestFocus();
  37351. });
  37352. return _this;
  37353. }
  37354. createClass_default()(TextAlign, [{
  37355. key: "componentWillReceiveProps",
  37356. value: function componentWillReceiveProps(nextProps) {
  37357. this.setState({
  37358. currentIndent: external_braft_utils_["ContentUtils"].getSelectionBlockData(nextProps.editorState, 'textIndent') || 0
  37359. });
  37360. }
  37361. }, {
  37362. key: "render",
  37363. value: function render() {
  37364. var currentIndent = this.state.currentIndent;
  37365. var language = this.props.language;
  37366. return external_react_default.a.createElement(ControlGroup, null, external_react_default.a.createElement("button", {
  37367. key: 0,
  37368. type: "button",
  37369. "data-title": language.controls.increaseIndent,
  37370. disabled: currentIndent >= 6,
  37371. className: "control-item button button-indent-increase".concat(currentIndent > 0 && currentIndent < 6 ? ' active' : ''),
  37372. onClick: this.increaseIndent
  37373. }, external_react_default.a.createElement("i", {
  37374. className: 'bfi-indent-increase'
  37375. })), external_react_default.a.createElement("button", {
  37376. key: 1,
  37377. type: "button",
  37378. "data-title": language.controls.decreaseIndent,
  37379. disabled: currentIndent <= 0,
  37380. className: "control-item button button-indent-decrease",
  37381. onClick: this.decreaseIndent
  37382. }, external_react_default.a.createElement("i", {
  37383. className: 'bfi-indent-decrease'
  37384. })));
  37385. }
  37386. }]);
  37387. return TextAlign;
  37388. }(external_react_default.a.Component);
  37389. // CONCATENATED MODULE: ./components/business/ControlBar/index.jsx
  37390. var commandHookMap = {
  37391. 'inline-style': 'toggle-inline-style',
  37392. 'block-type': 'change-block-type',
  37393. 'editor-method': 'exec-editor-command'
  37394. };
  37395. var exclusiveInlineStyles = {
  37396. 'superscript': 'subscript',
  37397. 'subscript': 'superscript'
  37398. };
  37399. var mergeControls = function mergeControls(commonProps, builtControls, extensionControls, extendControls) {
  37400. extensionControls = extensionControls.map(function (item) {
  37401. return typeof item === 'function' ? item(commonProps) : item;
  37402. });
  37403. extendControls = extendControls.map(function (item) {
  37404. return typeof item === 'function' ? item(commonProps) : item;
  37405. });
  37406. if (extensionControls.length === 0 && extendControls.length === 0) {
  37407. return builtControls;
  37408. }
  37409. return builtControls.map(function (item) {
  37410. return extendControls.find(function (subItem) {
  37411. return subItem.replace === (item.key || item);
  37412. }) || extensionControls.find(function (subItem) {
  37413. return subItem.replace === (item.key || item);
  37414. }) || item;
  37415. }).concat(extensionControls.length ? 'separator' : '').concat(extensionControls.filter(function (item) {
  37416. return !item.replace;
  37417. })).concat(extendControls.filter(function (item) {
  37418. return typeof item === 'string' || !item.replace;
  37419. }));
  37420. };
  37421. var ControlBar_ControlBar =
  37422. /*#__PURE__*/
  37423. function (_React$Component) {
  37424. inherits_default()(ControlBar, _React$Component);
  37425. function ControlBar() {
  37426. var _getPrototypeOf2;
  37427. var _this;
  37428. classCallCheck_default()(this, ControlBar);
  37429. for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
  37430. args[_key] = arguments[_key];
  37431. }
  37432. _this = possibleConstructorReturn_default()(this, (_getPrototypeOf2 = getPrototypeOf_default()(ControlBar)).call.apply(_getPrototypeOf2, [this].concat(args)));
  37433. defineProperty_default()(assertThisInitialized_default()(assertThisInitialized_default()(_this)), "allControls", []);
  37434. defineProperty_default()(assertThisInitialized_default()(assertThisInitialized_default()(_this)), "mediaLibiraryModal", null);
  37435. defineProperty_default()(assertThisInitialized_default()(assertThisInitialized_default()(_this)), "extendedModals", {});
  37436. defineProperty_default()(assertThisInitialized_default()(assertThisInitialized_default()(_this)), "openBraftFinder", function () {
  37437. if (!_this.props.braftFinder || !_this.props.braftFinder.ReactComponent) {
  37438. return false;
  37439. }
  37440. if (_this.props.hooks('open-braft-finder')() === false) {
  37441. return false;
  37442. }
  37443. var mediaProps = _this.props.media;
  37444. var MediaLibrary = _this.props.braftFinder.ReactComponent;
  37445. _this.mediaLibiraryModal = Modal_showModal({
  37446. title: _this.props.language.controls.mediaLibirary,
  37447. language: _this.props.language,
  37448. width: 640,
  37449. showFooter: false,
  37450. component: external_react_default.a.createElement(MediaLibrary, {
  37451. accepts: mediaProps.accepts,
  37452. onCancel: _this.closeBraftFinder,
  37453. onInsert: _this.insertMedias,
  37454. onChange: mediaProps.onChange,
  37455. externals: mediaProps.externals,
  37456. onBeforeSelect: _this.bindBraftFinderHook('select-medias'),
  37457. onBeforeDeselect: _this.bindBraftFinderHook('deselect-medias'),
  37458. onBeforeRemove: _this.bindBraftFinderHook('remove-medias'),
  37459. onBeforeInsert: _this.bindBraftFinderHook('insert-medias'),
  37460. onFileSelect: _this.bindBraftFinderHook('select-files')
  37461. })
  37462. });
  37463. });
  37464. defineProperty_default()(assertThisInitialized_default()(assertThisInitialized_default()(_this)), "bindBraftFinderHook", function (hookName) {
  37465. return function () {
  37466. return _this.props.hooks(hookName, arguments.length <= 0 ? undefined : arguments[0]).apply(void 0, arguments);
  37467. };
  37468. });
  37469. defineProperty_default()(assertThisInitialized_default()(assertThisInitialized_default()(_this)), "insertMedias", function (medias) {
  37470. _this.props.editor.setValue(external_braft_utils_["ContentUtils"].insertMedias(_this.props.editorState, medias));
  37471. _this.props.editor.requestFocus();
  37472. _this.props.media.onInsert && _this.props.media.onInsert(medias);
  37473. _this.closeBraftFinder();
  37474. });
  37475. defineProperty_default()(assertThisInitialized_default()(assertThisInitialized_default()(_this)), "closeBraftFinder", function () {
  37476. _this.props.media.onCancel && _this.props.media.onCancel();
  37477. _this.mediaLibiraryModal && _this.mediaLibiraryModal.close();
  37478. });
  37479. return _this;
  37480. }
  37481. createClass_default()(ControlBar, [{
  37482. key: "componentDidUpdate",
  37483. value: function componentDidUpdate() {
  37484. var _this2 = this;
  37485. var language = this.props.language;
  37486. this.allControls.forEach(function (item) {
  37487. if (item.type === 'modal') {
  37488. if (item.modal && item.modal.id && _this2.extendedModals[item.modal.id]) {
  37489. _this2.extendedModals[item.modal.id].update(objectSpread_default()({}, item.modal, {
  37490. language: language
  37491. }));
  37492. }
  37493. }
  37494. });
  37495. }
  37496. }, {
  37497. key: "getControlItemClassName",
  37498. value: function getControlItemClassName(data) {
  37499. var className = 'control-item button';
  37500. var type = data.type,
  37501. command = data.command;
  37502. if (type === 'inline-style' && external_braft_utils_["ContentUtils"].selectionHasInlineStyle(this.props.editorState, command)) {
  37503. className += ' active';
  37504. } else if (type === 'block-type' && external_braft_utils_["ContentUtils"].getSelectionBlockType(this.props.editorState) === command) {
  37505. className += ' active';
  37506. } else if (type === 'entity' && external_braft_utils_["ContentUtils"].getSelectionEntityType(this.props.editorState) === command) {
  37507. className += ' active';
  37508. }
  37509. return className;
  37510. }
  37511. }, {
  37512. key: "applyControl",
  37513. value: function applyControl(command, type) {
  37514. var data = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
  37515. var hookReturns = this.props.hooks(commandHookMap[type] || type, command)(command);
  37516. var editorState = this.props.editorState;
  37517. if (hookReturns === false) {
  37518. return false;
  37519. }
  37520. if (typeof hookReturns === 'string') {
  37521. command = hookReturns;
  37522. }
  37523. if (type === 'inline-style') {
  37524. var exclusiveInlineStyle = exclusiveInlineStyles[command];
  37525. if (exclusiveInlineStyle && external_braft_utils_["ContentUtils"].selectionHasInlineStyle(editorState, exclusiveInlineStyle)) {
  37526. editorState = external_braft_utils_["ContentUtils"].toggleSelectionInlineStyle(editorState, exclusiveInlineStyle);
  37527. }
  37528. this.props.editor.setValue(external_braft_utils_["ContentUtils"].toggleSelectionInlineStyle(editorState, command));
  37529. } else if (type === 'block-type') {
  37530. this.props.editor.setValue(external_braft_utils_["ContentUtils"].toggleSelectionBlockType(editorState, command));
  37531. } else if (type === 'entity') {
  37532. this.props.editor.setValue(external_braft_utils_["ContentUtils"].toggleSelectionEntity(editorState, {
  37533. type: command,
  37534. mutability: data.mutability || 'MUTABLE',
  37535. data: data.data || {}
  37536. }));
  37537. } else if (type === 'editor-method') {
  37538. this.props.editor[command] && this.props.editor[command]();
  37539. }
  37540. }
  37541. }, {
  37542. key: "render",
  37543. value: function render() {
  37544. var _this3 = this;
  37545. var _this$props = this.props,
  37546. editor = _this$props.editor,
  37547. editorId = _this$props.editorId,
  37548. editorState = _this$props.editorState,
  37549. className = _this$props.className,
  37550. style = _this$props.style,
  37551. controls = _this$props.controls,
  37552. media = _this$props.media,
  37553. extendControls = _this$props.extendControls,
  37554. language = _this$props.language,
  37555. hooks = _this$props.hooks,
  37556. colors = _this$props.colors,
  37557. colorPicker = _this$props.colorPicker,
  37558. colorPickerTheme = _this$props.colorPickerTheme,
  37559. colorPickerAutoHide = _this$props.colorPickerAutoHide,
  37560. headings = _this$props.headings,
  37561. fontSizes = _this$props.fontSizes,
  37562. fontFamilies = _this$props.fontFamilies,
  37563. emojis = _this$props.emojis,
  37564. getContainerNode = _this$props.getContainerNode,
  37565. lineHeights = _this$props.lineHeights,
  37566. letterSpacings = _this$props.letterSpacings,
  37567. textAligns = _this$props.textAligns,
  37568. textBackgroundColor = _this$props.textBackgroundColor,
  37569. allowInsertLinkText = _this$props.allowInsertLinkText,
  37570. defaultLinkTarget = _this$props.defaultLinkTarget;
  37571. var currentBlockType = external_braft_utils_["ContentUtils"].getSelectionBlockType(editorState);
  37572. var commonProps = {
  37573. editor: editor,
  37574. editorId: editorId,
  37575. editorState: editorState,
  37576. language: language,
  37577. getContainerNode: getContainerNode,
  37578. hooks: hooks
  37579. };
  37580. var renderedControls = [];
  37581. var editorControls = configs_controls(language, editor);
  37582. var extensionControls = getExtensionControls(editorId);
  37583. var allControls = mergeControls(commonProps, controls, extensionControls, extendControls);
  37584. this.allControls = allControls;
  37585. return external_react_default.a.createElement("div", {
  37586. className: "bf-controlbar ".concat(className || ''),
  37587. style: style,
  37588. onMouseDown: this.preventDefault
  37589. }, allControls.map(function (item, index) {
  37590. var itemKey = typeof item === 'string' ? item : item.key;
  37591. if (typeof itemKey !== 'string') {
  37592. return null;
  37593. }
  37594. if (renderedControls.indexOf(itemKey) > -1) {
  37595. return null;
  37596. }
  37597. if (itemKey.toLowerCase() === 'separator') {
  37598. return external_react_default.a.createElement("span", {
  37599. key: index,
  37600. className: "separator-line"
  37601. });
  37602. }
  37603. var controlItem = editorControls.find(function (subItem) {
  37604. return subItem.key.toLowerCase() === itemKey.toLowerCase();
  37605. });
  37606. if (typeof item !== 'string') {
  37607. controlItem = objectSpread_default()({}, controlItem, item);
  37608. }
  37609. if (!controlItem) {
  37610. return null;
  37611. }
  37612. renderedControls.push(itemKey);
  37613. if (controlItem.type === 'headings') {
  37614. return external_react_default.a.createElement(Headings, extends_default()({
  37615. key: index,
  37616. headings: headings,
  37617. current: currentBlockType,
  37618. onChange: function onChange(command) {
  37619. return _this3.applyControl(command, 'block-type');
  37620. }
  37621. }, commonProps));
  37622. } else if (controlItem.type === 'text-color') {
  37623. return external_react_default.a.createElement(TextColor_TextColor, extends_default()({
  37624. key: index,
  37625. colors: colors,
  37626. colorPicker: colorPicker,
  37627. theme: colorPickerTheme,
  37628. autoHide: colorPickerAutoHide,
  37629. enableBackgroundColor: textBackgroundColor
  37630. }, commonProps));
  37631. } else if (controlItem.type === 'font-size') {
  37632. return external_react_default.a.createElement(FontSize, extends_default()({
  37633. key: index,
  37634. fontSizes: fontSizes,
  37635. defaultCaption: controlItem.title
  37636. }, commonProps));
  37637. } else if (controlItem.type === 'line-height') {
  37638. return external_react_default.a.createElement(LineHeight, extends_default()({
  37639. key: index,
  37640. lineHeights: lineHeights,
  37641. defaultCaption: controlItem.title
  37642. }, commonProps));
  37643. } else if (controlItem.type === 'letter-spacing') {
  37644. return external_react_default.a.createElement(LetterSpacing, extends_default()({
  37645. key: index,
  37646. letterSpacings: letterSpacings,
  37647. defaultCaption: controlItem.title
  37648. }, commonProps));
  37649. } else if (controlItem.type === 'text-indent') {
  37650. return external_react_default.a.createElement(TextIndent_TextAlign, extends_default()({
  37651. key: index,
  37652. defaultCaption: controlItem.title
  37653. }, commonProps));
  37654. } else if (controlItem.type === 'font-family') {
  37655. return external_react_default.a.createElement(FontFamily, extends_default()({
  37656. key: index,
  37657. fontFamilies: fontFamilies,
  37658. defaultCaption: controlItem.title
  37659. }, commonProps));
  37660. } else if (controlItem.type === 'emoji') {
  37661. return external_react_default.a.createElement(EmojiPicker, extends_default()({
  37662. key: index,
  37663. emojis: emojis,
  37664. defaultCaption: controlItem.text
  37665. }, commonProps));
  37666. } else if (controlItem.type === 'link') {
  37667. return external_react_default.a.createElement(LinkEditor_LinkEditor, extends_default()({
  37668. key: index,
  37669. defaultLinkTarget: defaultLinkTarget,
  37670. allowInsertLinkText: allowInsertLinkText
  37671. }, commonProps));
  37672. } else if (controlItem.type === 'text-align') {
  37673. return external_react_default.a.createElement(TextAlign_TextAlign, extends_default()({
  37674. key: index,
  37675. textAligns: textAligns
  37676. }, commonProps));
  37677. } else if (controlItem.type === 'media') {
  37678. if (!media.image && !media.video && !media.audio) {
  37679. return null;
  37680. }
  37681. return external_react_default.a.createElement("button", {
  37682. type: "button",
  37683. key: index,
  37684. "data-title": controlItem.title,
  37685. disabled: controlItem.disabled,
  37686. className: "control-item media button",
  37687. onClick: _this3.openBraftFinder
  37688. }, controlItem.text);
  37689. } else if (controlItem.type === 'dropdown') {
  37690. return external_react_default.a.createElement(DropDown_DropDown, extends_default()({
  37691. key: index,
  37692. className: "control-item extend-control-item dropdown ".concat(controlItem.className || ''),
  37693. caption: controlItem.text,
  37694. htmlCaption: controlItem.html,
  37695. showArrow: controlItem.showArrow,
  37696. title: controlItem.title,
  37697. arrowActive: controlItem.arrowActive,
  37698. theme: controlItem.theme,
  37699. autoHide: controlItem.autoHide,
  37700. disabled: controlItem.disabled,
  37701. ref: controlItem.ref
  37702. }, commonProps), controlItem.component);
  37703. } else if (controlItem.type === 'modal') {
  37704. return external_react_default.a.createElement("button", {
  37705. type: "button",
  37706. key: index,
  37707. "data-title": controlItem.title,
  37708. disabled: controlItem.disabled,
  37709. className: "control-item extend-control-item button ".concat(controlItem.className || ''),
  37710. dangerouslySetInnerHTML: controlItem.html ? {
  37711. __html: controlItem.html
  37712. } : null,
  37713. onClick: function onClick(event) {
  37714. if (controlItem.modal && controlItem.modal.id) {
  37715. if (_this3.extendedModals[controlItem.modal.id]) {
  37716. _this3.extendedModals[controlItem.modal.id].active = true;
  37717. _this3.extendedModals[controlItem.modal.id].update(objectSpread_default()({}, controlItem.modal, {
  37718. language: language
  37719. }));
  37720. } else {
  37721. _this3.extendedModals[controlItem.modal.id] = Modal_showModal(objectSpread_default()({}, controlItem.modal, {
  37722. language: language
  37723. }));
  37724. controlItem.modal.onCreate && controlItem.modal.onCreate(_this3.extendedModals[controlItem.modal.id]);
  37725. }
  37726. }
  37727. controlItem.onClick && controlItem.onClick(event);
  37728. }
  37729. }, !controlItem.html ? controlItem.text : null);
  37730. } else if (controlItem.type === 'component') {
  37731. return external_react_default.a.createElement("div", {
  37732. key: index,
  37733. className: "component-wrapper ".concat(controlItem.className || '')
  37734. }, controlItem.component);
  37735. } else if (controlItem.type === 'button') {
  37736. return external_react_default.a.createElement("button", {
  37737. type: "button",
  37738. key: index,
  37739. "data-title": controlItem.title,
  37740. disabled: controlItem.disabled,
  37741. className: "control-item button ".concat(controlItem.className || ''),
  37742. dangerouslySetInnerHTML: controlItem.html ? {
  37743. __html: controlItem.html
  37744. } : null,
  37745. onClick: function onClick(event) {
  37746. return controlItem.onClick && controlItem.onClick(event);
  37747. }
  37748. }, !controlItem.html ? controlItem.text : null);
  37749. } else if (controlItem) {
  37750. var disabled = false;
  37751. if (controlItem.command === 'undo') {
  37752. disabled = editorState.getUndoStack().size === 0;
  37753. } else if (controlItem.command === 'redo') {
  37754. disabled = editorState.getRedoStack().size === 0;
  37755. }
  37756. return external_react_default.a.createElement("button", {
  37757. type: "button",
  37758. key: index,
  37759. disabled: disabled,
  37760. "data-title": controlItem.title,
  37761. className: _this3.getControlItemClassName({
  37762. type: controlItem.type,
  37763. command: controlItem.command
  37764. }),
  37765. onClick: function onClick() {
  37766. return _this3.applyControl(controlItem.command, controlItem.type, controlItem.data);
  37767. }
  37768. }, controlItem.text);
  37769. }
  37770. }));
  37771. }
  37772. }, {
  37773. key: "preventDefault",
  37774. value: function preventDefault(event) {
  37775. var tagName = event.target.tagName.toLowerCase();
  37776. if (tagName === 'input' || tagName === 'label') ; else {
  37777. event.preventDefault();
  37778. }
  37779. }
  37780. }]);
  37781. return ControlBar;
  37782. }(external_react_default.a.Component);
  37783. // CONCATENATED MODULE: ./editor/index.jsx
  37784. var buildHooks = function buildHooks(hooks) {
  37785. return function (hookName) {
  37786. var defaultReturns = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
  37787. return hooks[hookName] || function () {
  37788. return defaultReturns;
  37789. };
  37790. };
  37791. };
  37792. var filterColors = function filterColors(colors, colors2) {
  37793. return colors.filter(function (item) {
  37794. return !colors2.find(function (color) {
  37795. return color.toLowerCase() === item.toLowerCase();
  37796. });
  37797. }).filter(function (item, index, array) {
  37798. return array.indexOf(item) === index;
  37799. });
  37800. };
  37801. var editor_isControlEnabled = function isControlEnabled(props, controlName) {
  37802. return toConsumableArray_default()(props.controls).concat(toConsumableArray_default()(props.extendControls)).find(function (item) {
  37803. return item === controlName || item.key === controlName;
  37804. }) && props.excludeControls.indexOf(controlName) === -1;
  37805. };
  37806. var editor_getConvertOptions = function getConvertOptions(props) {
  37807. var editorId = props.editorId || props.id;
  37808. var convertOptions = objectSpread_default()({}, configs_props.converts, props.converts, {
  37809. fontFamilies: props.fontFamilies
  37810. });
  37811. convertOptions.styleImportFn = compositeStyleImportFn(convertOptions.styleImportFn, editorId);
  37812. convertOptions.styleExportFn = compositeStyleExportFn(convertOptions.styleExportFn, editorId);
  37813. convertOptions.entityImportFn = compositeEntityImportFn(convertOptions.entityImportFn, editorId);
  37814. convertOptions.entityExportFn = compositeEntityExportFn(convertOptions.entityExportFn, editorId);
  37815. convertOptions.blockImportFn = compositeBlockImportFn(convertOptions.blockImportFn, editorId);
  37816. convertOptions.blockExportFn = compositeBlockExportFn(convertOptions.blockExportFn, editorId);
  37817. return convertOptions;
  37818. };
  37819. var editor_BraftEditor =
  37820. /*#__PURE__*/
  37821. function (_React$Component) {
  37822. inherits_default()(BraftEditor, _React$Component);
  37823. function BraftEditor(props) {
  37824. var _this;
  37825. classCallCheck_default()(this, BraftEditor);
  37826. _this = possibleConstructorReturn_default()(this, getPrototypeOf_default()(BraftEditor).call(this, props));
  37827. defineProperty_default()(assertThisInitialized_default()(assertThisInitialized_default()(_this)), "onChange", function (editorState, callback) {
  37828. if (!(editorState instanceof external_draft_js_["EditorState"])) {
  37829. editorState = external_draft_js_["EditorState"].set(editorState, {
  37830. decorator: _this.editorDecorators
  37831. });
  37832. }
  37833. if (!editorState.convertOptions) {
  37834. editorState.setConvertOptions(editor_getConvertOptions(_this.editorProps));
  37835. }
  37836. _this.setState({
  37837. editorState: editorState
  37838. }, function () {
  37839. _this.props.onChange && _this.props.onChange(editorState);
  37840. callback && callback(editorState);
  37841. });
  37842. });
  37843. defineProperty_default()(assertThisInitialized_default()(assertThisInitialized_default()(_this)), "getDraftInstance", function () {
  37844. return _this.draftInstance;
  37845. });
  37846. defineProperty_default()(assertThisInitialized_default()(assertThisInitialized_default()(_this)), "getFinderInstance", function () {
  37847. return _this.braftFinder;
  37848. });
  37849. defineProperty_default()(assertThisInitialized_default()(assertThisInitialized_default()(_this)), "getValue", function () {
  37850. return _this.state.editorState;
  37851. });
  37852. defineProperty_default()(assertThisInitialized_default()(assertThisInitialized_default()(_this)), "setValue", function (editorState, callback) {
  37853. return _this.onChange(editorState, callback);
  37854. });
  37855. defineProperty_default()(assertThisInitialized_default()(assertThisInitialized_default()(_this)), "forceRender", function () {
  37856. var selectionState = _this.state.editorState.getSelection();
  37857. _this.setValue(external_draft_js_["EditorState"].set(_this.state.editorState, {
  37858. decorator: _this.editorDecorators
  37859. }), function () {
  37860. _this.setValue(external_draft_js_["EditorState"].forceSelection(_this.state.editorState, selectionState));
  37861. });
  37862. });
  37863. defineProperty_default()(assertThisInitialized_default()(assertThisInitialized_default()(_this)), "onTab", function (event) {
  37864. if (handlers_keyCommandHandlers('tab', _this.state.editorState, assertThisInitialized_default()(assertThisInitialized_default()(_this))) === 'handled') {
  37865. event.preventDefault();
  37866. }
  37867. _this.editorProps.onTab && _this.editorProps.onTab(event);
  37868. });
  37869. defineProperty_default()(assertThisInitialized_default()(assertThisInitialized_default()(_this)), "onFocus", function () {
  37870. _this.isFocused = true;
  37871. _this.editorProps.onFocus && _this.editorProps.onFocus(_this.state.editorState);
  37872. });
  37873. defineProperty_default()(assertThisInitialized_default()(assertThisInitialized_default()(_this)), "onBlur", function () {
  37874. _this.isFocused = false;
  37875. _this.editorProps.onBlur && _this.editorProps.onBlur(_this.state.editorState);
  37876. });
  37877. defineProperty_default()(assertThisInitialized_default()(assertThisInitialized_default()(_this)), "requestFocus", function () {
  37878. setTimeout(function () {
  37879. return _this.draftInstance.focus();
  37880. }, 0);
  37881. });
  37882. defineProperty_default()(assertThisInitialized_default()(assertThisInitialized_default()(_this)), "handleKeyCommand", function (command, editorState) {
  37883. return handlers_keyCommandHandlers(command, editorState, assertThisInitialized_default()(assertThisInitialized_default()(_this)));
  37884. });
  37885. defineProperty_default()(assertThisInitialized_default()(assertThisInitialized_default()(_this)), "handleReturn", function (event, editorState) {
  37886. return handlers_returnHandlers(event, editorState, assertThisInitialized_default()(assertThisInitialized_default()(_this)));
  37887. });
  37888. defineProperty_default()(assertThisInitialized_default()(assertThisInitialized_default()(_this)), "handleBeforeInput", function (chars, editorState) {
  37889. return beforeInputHandlers(chars, editorState, assertThisInitialized_default()(assertThisInitialized_default()(_this)));
  37890. });
  37891. defineProperty_default()(assertThisInitialized_default()(assertThisInitialized_default()(_this)), "handleDrop", function (selectionState, dataTransfer) {
  37892. return handlers_dropHandlers(selectionState, dataTransfer, assertThisInitialized_default()(assertThisInitialized_default()(_this)));
  37893. });
  37894. defineProperty_default()(assertThisInitialized_default()(assertThisInitialized_default()(_this)), "handleDroppedFiles", function (selectionState, files) {
  37895. return droppedFilesHandlers(selectionState, files, assertThisInitialized_default()(assertThisInitialized_default()(_this)));
  37896. });
  37897. defineProperty_default()(assertThisInitialized_default()(assertThisInitialized_default()(_this)), "handlePastedFiles", function (files) {
  37898. return pastedFilesHandlers(files, assertThisInitialized_default()(assertThisInitialized_default()(_this)));
  37899. });
  37900. defineProperty_default()(assertThisInitialized_default()(assertThisInitialized_default()(_this)), "handleCopyContent", function (event) {
  37901. return handlers_copyHandlers(event, assertThisInitialized_default()(assertThisInitialized_default()(_this)));
  37902. });
  37903. defineProperty_default()(assertThisInitialized_default()(assertThisInitialized_default()(_this)), "handlePastedText", function (text, html, editorState) {
  37904. return handlers_pastedTextHandlers(text, html, editorState, assertThisInitialized_default()(assertThisInitialized_default()(_this)));
  37905. });
  37906. defineProperty_default()(assertThisInitialized_default()(assertThisInitialized_default()(_this)), "handleCompositionStart", function (event) {
  37907. return handlers_compositionStartHandler(event, assertThisInitialized_default()(assertThisInitialized_default()(_this)));
  37908. });
  37909. defineProperty_default()(assertThisInitialized_default()(assertThisInitialized_default()(_this)), "undo", function () {
  37910. _this.setValue(external_braft_utils_["ContentUtils"].undo(_this.state.editorState));
  37911. });
  37912. defineProperty_default()(assertThisInitialized_default()(assertThisInitialized_default()(_this)), "redo", function () {
  37913. _this.setValue(external_braft_utils_["ContentUtils"].redo(_this.state.editorState));
  37914. });
  37915. defineProperty_default()(assertThisInitialized_default()(assertThisInitialized_default()(_this)), "removeSelectionInlineStyles", function () {
  37916. _this.setValue(external_braft_utils_["ContentUtils"].removeSelectionInlineStyles(_this.state.editorState));
  37917. });
  37918. defineProperty_default()(assertThisInitialized_default()(assertThisInitialized_default()(_this)), "insertHorizontalLine", function () {
  37919. _this.setValue(external_braft_utils_["ContentUtils"].insertHorizontalLine(_this.state.editorState));
  37920. });
  37921. defineProperty_default()(assertThisInitialized_default()(assertThisInitialized_default()(_this)), "clearEditorContent", function () {
  37922. _this.setValue(external_braft_utils_["ContentUtils"].clear(_this.state.editorState), function (editorState) {
  37923. _this.setValue(external_braft_utils_["ContentUtils"].toggleSelectionIndent(editorState, 0));
  37924. });
  37925. });
  37926. defineProperty_default()(assertThisInitialized_default()(assertThisInitialized_default()(_this)), "toggleFullscreen", function (fullscreen) {
  37927. _this.setState({
  37928. isFullscreen: typeof fullscreen !== 'undefined' ? fullscreen : !_this.state.isFullscreen
  37929. }, function () {
  37930. _this.editorProps.onFullscreen && _this.editorProps.onFullscreen(_this.state.isFullscreen);
  37931. });
  37932. });
  37933. defineProperty_default()(assertThisInitialized_default()(assertThisInitialized_default()(_this)), "setEditorContainerNode", function (containerNode) {
  37934. _this.containerNode = containerNode;
  37935. });
  37936. _this.editorProps = _this.getEditorProps(props);
  37937. _this.editorDecorators = getDecorators(_this.editorProps.editorId || _this.editorProps.id);
  37938. _this.isFocused = false;
  37939. _this.isLiving = false;
  37940. _this.braftFinder = null;
  37941. _this.valueInitialized = !!(_this.props.defaultValue || _this.props.value);
  37942. var defaultEditorState = (_this.props.defaultValue || _this.props.value) instanceof external_draft_js_["EditorState"] ? _this.props.defaultValue || _this.props.value : external_draft_js_["EditorState"].createEmpty(_this.editorDecorators);
  37943. defaultEditorState.setConvertOptions(editor_getConvertOptions(_this.editorProps));
  37944. var tempColors = [];
  37945. if (external_braft_utils_["ContentUtils"].isEditorState(defaultEditorState)) {
  37946. var colors = external_braft_utils_["ColorUtils"].detectColorsFromDraftState(defaultEditorState.toRAW(true));
  37947. defaultEditorState.setConvertOptions(editor_getConvertOptions(_this.editorProps));
  37948. tempColors = filterColors(colors, _this.editorProps.colors);
  37949. }
  37950. _this.state = {
  37951. tempColors: tempColors,
  37952. editorState: defaultEditorState,
  37953. isFullscreen: false,
  37954. draftProps: {}
  37955. };
  37956. _this.containerNode = null;
  37957. return _this;
  37958. }
  37959. createClass_default()(BraftEditor, [{
  37960. key: "getEditorProps",
  37961. value: function getEditorProps(props) {
  37962. var _this2 = this;
  37963. props = props || this.props;
  37964. var _props = props,
  37965. value = _props.value,
  37966. defaultValue = _props.defaultValue,
  37967. onChange = _props.onChange,
  37968. restProps = objectWithoutProperties_default()(_props, ["value", "defaultValue", "onChange"]); // eslint-disable-line no-unused-vars
  37969. var propInterceptors = getPropInterceptors(restProps.editorId || restProps.id);
  37970. if (propInterceptors.length === 0) {
  37971. return restProps;
  37972. }
  37973. var porpsMap = Object(external_immutable_["Map"])(restProps);
  37974. propInterceptors.forEach(function (interceptor) {
  37975. porpsMap = porpsMap.merge(Object(external_immutable_["Map"])(interceptor(porpsMap.toJS(), _this2) || {}));
  37976. });
  37977. return porpsMap.toJS();
  37978. }
  37979. }, {
  37980. key: "componentWillMount",
  37981. value: function componentWillMount() {
  37982. if (editor_isControlEnabled(this.editorProps, 'media')) {
  37983. var _this$editorProps = this.editorProps,
  37984. language = _this$editorProps.language,
  37985. media = _this$editorProps.media;
  37986. var _defaultProps$media$m = objectSpread_default()({}, configs_props.media, media),
  37987. uploadFn = _defaultProps$media$m.uploadFn,
  37988. validateFn = _defaultProps$media$m.validateFn,
  37989. items = _defaultProps$media$m.items;
  37990. this.braftFinder = new external_braft_finder_default.a({
  37991. items: items,
  37992. language: language,
  37993. uploader: uploadFn,
  37994. validator: validateFn
  37995. });
  37996. this.forceUpdate();
  37997. }
  37998. }
  37999. }, {
  38000. key: "componentDidMount",
  38001. value: function componentDidMount() {
  38002. this.isLiving = true;
  38003. }
  38004. }, {
  38005. key: "componentDidUpdate",
  38006. value: function componentDidUpdate(_, prevState) {
  38007. if (prevState.editorState !== this.state.editorState) {
  38008. this.state.editorState.setConvertOptions(editor_getConvertOptions(this.editorProps));
  38009. }
  38010. }
  38011. }, {
  38012. key: "componentWillReceiveProps",
  38013. value: function componentWillReceiveProps(props) {
  38014. var _this3 = this;
  38015. this.editorProps = this.getEditorProps(props);
  38016. var editorState = props.value;
  38017. var _this$editorProps2 = this.editorProps,
  38018. media = _this$editorProps2.media,
  38019. language = _this$editorProps2.language;
  38020. var currentProps = this.getEditorProps();
  38021. if (!editor_isControlEnabled(currentProps, 'media') && editor_isControlEnabled(this.editorProps, 'media') && !this.braftFinder) {
  38022. var _defaultProps$media$m2 = objectSpread_default()({}, configs_props.media, media),
  38023. uploadFn = _defaultProps$media$m2.uploadFn,
  38024. validateFn = _defaultProps$media$m2.validateFn,
  38025. items = _defaultProps$media$m2.items;
  38026. this.braftFinder = new external_braft_finder_default.a({
  38027. items: items,
  38028. language: language,
  38029. uploader: uploadFn,
  38030. validator: validateFn
  38031. });
  38032. this.forceUpdate();
  38033. }
  38034. if (media && media.items && this.braftFinder) {
  38035. this.braftFinder.setItems(media.items);
  38036. }
  38037. var nextEditorState;
  38038. if (!this.valueInitialized && typeof this.props.defaultValue === 'undefined' && external_braft_utils_["ContentUtils"].isEditorState(props.defaultValue)) {
  38039. nextEditorState = props.defaultValue;
  38040. } else if (external_braft_utils_["ContentUtils"].isEditorState(editorState)) {
  38041. nextEditorState = editorState;
  38042. }
  38043. if (nextEditorState) {
  38044. if (nextEditorState && nextEditorState !== this.state.editorState) {
  38045. var tempColors = external_braft_utils_["ColorUtils"].detectColorsFromDraftState(nextEditorState.toRAW(true));
  38046. nextEditorState.setConvertOptions(editor_getConvertOptions(this.editorProps));
  38047. this.setState({
  38048. tempColors: filterColors(toConsumableArray_default()(this.state.tempColors).concat(toConsumableArray_default()(tempColors)), currentProps.colors),
  38049. editorState: nextEditorState
  38050. }, function () {
  38051. _this3.props.onChange && _this3.props.onChange(nextEditorState);
  38052. });
  38053. } else {
  38054. this.setState({
  38055. editorState: nextEditorState
  38056. });
  38057. }
  38058. }
  38059. }
  38060. }, {
  38061. key: "componentWillUnmount",
  38062. value: function componentWillUnmount() {
  38063. this.isLiving = false;
  38064. this.controlBarInstance && this.controlBarInstance.closeBraftFinder();
  38065. }
  38066. }, {
  38067. key: "lockOrUnlockEditor",
  38068. value: function lockOrUnlockEditor(editorLocked) {
  38069. this.setState({
  38070. editorLocked: editorLocked
  38071. });
  38072. }
  38073. }, {
  38074. key: "render",
  38075. value: function render() {
  38076. var _this4 = this;
  38077. var _this$editorProps3 = this.editorProps,
  38078. id = _this$editorProps3.id,
  38079. editorId = _this$editorProps3.editorId,
  38080. controls = _this$editorProps3.controls,
  38081. excludeControls = _this$editorProps3.excludeControls,
  38082. extendControls = _this$editorProps3.extendControls,
  38083. readOnly = _this$editorProps3.readOnly,
  38084. disabled = _this$editorProps3.disabled,
  38085. media = _this$editorProps3.media,
  38086. language = _this$editorProps3.language,
  38087. colors = _this$editorProps3.colors,
  38088. colorPicker = _this$editorProps3.colorPicker,
  38089. colorPickerTheme = _this$editorProps3.colorPickerTheme,
  38090. colorPickerAutoHide = _this$editorProps3.colorPickerAutoHide,
  38091. hooks = _this$editorProps3.hooks,
  38092. fontSizes = _this$editorProps3.fontSizes,
  38093. fontFamilies = _this$editorProps3.fontFamilies,
  38094. emojis = _this$editorProps3.emojis,
  38095. placeholder = _this$editorProps3.placeholder,
  38096. fixPlaceholder = _this$editorProps3.fixPlaceholder,
  38097. headings = _this$editorProps3.headings,
  38098. imageControls = _this$editorProps3.imageControls,
  38099. imageResizable = _this$editorProps3.imageResizable,
  38100. lineHeights = _this$editorProps3.lineHeights,
  38101. letterSpacings = _this$editorProps3.letterSpacings,
  38102. textAligns = _this$editorProps3.textAligns,
  38103. textBackgroundColor = _this$editorProps3.textBackgroundColor,
  38104. allowInsertLinkText = _this$editorProps3.allowInsertLinkText,
  38105. defaultLinkTarget = _this$editorProps3.defaultLinkTarget,
  38106. extendAtomics = _this$editorProps3.extendAtomics,
  38107. className = _this$editorProps3.className,
  38108. style = _this$editorProps3.style,
  38109. controlBarClassName = _this$editorProps3.controlBarClassName,
  38110. controlBarStyle = _this$editorProps3.controlBarStyle,
  38111. contentClassName = _this$editorProps3.contentClassName,
  38112. contentStyle = _this$editorProps3.contentStyle,
  38113. stripPastedStyles = _this$editorProps3.stripPastedStyles,
  38114. componentBelowControlBar = _this$editorProps3.componentBelowControlBar;
  38115. var _this$state = this.state,
  38116. isFullscreen = _this$state.isFullscreen,
  38117. editorState = _this$state.editorState;
  38118. editorId = editorId || id;
  38119. hooks = buildHooks(hooks);
  38120. controls = controls.filter(function (item) {
  38121. return excludeControls.indexOf(item) === -1;
  38122. });
  38123. language = (typeof language === 'function' ? language(languages, 'braft-editor') : languages[language]) || languages[configs_props.language];
  38124. var externalMedias = media && media.externals ? objectSpread_default()({}, configs_props.media.externals, media.externals) : configs_props.media.externals;
  38125. var accepts = media && media.accepts ? objectSpread_default()({}, configs_props.media.accepts, media.accepts) : configs_props.media.accepts;
  38126. media = objectSpread_default()({}, configs_props.media, media, {
  38127. externalMedias: externalMedias,
  38128. accepts: accepts
  38129. });
  38130. if (!media.uploadFn) {
  38131. media.video = false;
  38132. media.audio = false;
  38133. }
  38134. var controlBarProps = {
  38135. editor: this,
  38136. editorState: editorState,
  38137. braftFinder: this.braftFinder,
  38138. ref: function ref(instance) {
  38139. return _this4.controlBarInstance = instance;
  38140. },
  38141. getContainerNode: function getContainerNode() {
  38142. return _this4.containerNode;
  38143. },
  38144. className: controlBarClassName,
  38145. style: controlBarStyle,
  38146. colors: toConsumableArray_default()(colors).concat(toConsumableArray_default()(this.state.tempColors)),
  38147. colorPicker: colorPicker,
  38148. colorPickerTheme: colorPickerTheme,
  38149. colorPickerAutoHide: colorPickerAutoHide,
  38150. hooks: hooks,
  38151. editorId: editorId,
  38152. media: media,
  38153. controls: controls,
  38154. language: language,
  38155. extendControls: extendControls,
  38156. headings: headings,
  38157. fontSizes: fontSizes,
  38158. fontFamilies: fontFamilies,
  38159. emojis: emojis,
  38160. lineHeights: lineHeights,
  38161. letterSpacings: letterSpacings,
  38162. textAligns: textAligns,
  38163. textBackgroundColor: textBackgroundColor,
  38164. allowInsertLinkText: allowInsertLinkText,
  38165. defaultLinkTarget: defaultLinkTarget
  38166. };
  38167. var unitExportFn = editorState.convertOptions.unitExportFn;
  38168. var commonProps = {
  38169. editor: this,
  38170. editorId: editorId,
  38171. hooks: hooks,
  38172. editorState: editorState,
  38173. containerNode: this.containerNode,
  38174. imageControls: imageControls,
  38175. imageResizable: imageResizable,
  38176. language: language,
  38177. extendAtomics: extendAtomics
  38178. };
  38179. var blockRendererFn = getBlockRendererFn(commonProps, this.editorProps.blockRendererFn);
  38180. var blockRenderMap = getBlockRenderMap(commonProps, this.editorProps.blockRenderMap);
  38181. var blockStyleFn = getBlockStyleFn(this.editorProps.blockStyleFn);
  38182. var customStyleMap = getCustomStyleMap(commonProps, this.editorProps.customStyleMap);
  38183. var customStyleFn = getCustomStyleFn(commonProps, {
  38184. fontFamilies: fontFamilies,
  38185. unitExportFn: unitExportFn,
  38186. customStyleFn: this.editorProps.customStyleFn
  38187. });
  38188. var keyBindingFn = keybindings(this.editorProps.keyBindingFn);
  38189. var mixedProps = {};
  38190. if (this.state.editorLocked || this.editorProps.disabled || this.editorProps.readOnly || this.editorProps.draftProps.readOnly) {
  38191. mixedProps.readOnly = true;
  38192. }
  38193. if (placeholder && fixPlaceholder && editorState.isEmpty() && editorState.getCurrentContent().getFirstBlock().getType() !== 'unstyled') {
  38194. placeholder = '';
  38195. }
  38196. var draftProps = objectSpread_default()({
  38197. ref: function ref(instance) {
  38198. _this4.draftInstance = instance;
  38199. },
  38200. editorState: editorState,
  38201. handleKeyCommand: this.handleKeyCommand,
  38202. handleReturn: this.handleReturn,
  38203. handleBeforeInput: this.handleBeforeInput,
  38204. handleDrop: this.handleDrop,
  38205. handleDroppedFiles: this.handleDroppedFiles,
  38206. handlePastedText: this.handlePastedText,
  38207. handlePastedFiles: this.handlePastedFiles,
  38208. onChange: this.onChange,
  38209. onTab: this.onTab,
  38210. onFocus: this.onFocus,
  38211. onBlur: this.onBlur,
  38212. blockRenderMap: blockRenderMap,
  38213. blockRendererFn: blockRendererFn,
  38214. blockStyleFn: blockStyleFn,
  38215. customStyleMap: customStyleMap,
  38216. customStyleFn: customStyleFn,
  38217. keyBindingFn: keyBindingFn,
  38218. placeholder: placeholder,
  38219. stripPastedStyles: stripPastedStyles
  38220. }, this.editorProps.draftProps, mixedProps);
  38221. return external_react_default.a.createElement("div", {
  38222. style: style,
  38223. ref: this.setEditorContainerNode,
  38224. className: "bf-container ".concat(className).concat(disabled ? ' disabled' : '').concat(readOnly ? ' read-only' : '').concat(isFullscreen ? ' fullscreen' : '')
  38225. }, external_react_default.a.createElement(ControlBar_ControlBar, controlBarProps), componentBelowControlBar, external_react_default.a.createElement("div", {
  38226. onCompositionStart: this.handleCompositionStart,
  38227. className: "bf-content ".concat(contentClassName),
  38228. onCopy: this.handleCopyContent,
  38229. style: contentStyle
  38230. }, external_react_default.a.createElement(external_draft_js_["Editor"], draftProps)));
  38231. }
  38232. }]);
  38233. return BraftEditor;
  38234. }(external_react_default.a.Component);
  38235. defineProperty_default()(editor_BraftEditor, "defaultProps", configs_props);
  38236. // EXTERNAL MODULE: external "braft-convert"
  38237. var external_braft_convert_ = __webpack_require__(14);
  38238. // CONCATENATED MODULE: ./index.jsx
  38239. /* concated harmony reexport EditorState */__webpack_require__.d(__webpack_exports__, "EditorState", function() { return external_draft_js_["EditorState"]; });
  38240. /* concated harmony reexport getDecorators */__webpack_require__.d(__webpack_exports__, "getDecorators", function() { return getDecorators; });
  38241. external_draft_js_["EditorState"].prototype.setConvertOptions = function () {
  38242. var options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
  38243. this.convertOptions = options;
  38244. };
  38245. external_draft_js_["EditorState"].prototype.toHTML = function () {
  38246. var options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
  38247. var convertOptions = this.convertOptions || {};
  38248. return Object(external_braft_convert_["convertEditorStateToHTML"])(this, objectSpread_default()({}, convertOptions, options));
  38249. };
  38250. external_draft_js_["EditorState"].prototype.toRAW = function (noStringify) {
  38251. return noStringify ? Object(external_braft_convert_["convertEditorStateToRaw"])(this) : JSON.stringify(Object(external_braft_convert_["convertEditorStateToRaw"])(this));
  38252. };
  38253. external_draft_js_["EditorState"].prototype.toText = function () {
  38254. return this.getCurrentContent().getPlainText();
  38255. };
  38256. external_draft_js_["EditorState"].prototype.isEmpty = function () {
  38257. return !this.getCurrentContent().hasText();
  38258. };
  38259. editor_BraftEditor.createEditorState = external_draft_js_["EditorState"].createFrom = function (content) {
  38260. var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
  38261. options.unitExportFn = options.unitExportFn || editor_BraftEditor.defaultProps.converts.unitExportFn;
  38262. options.styleImportFn = compositeStyleImportFn(options.styleImportFn, options.editorId);
  38263. options.entityImportFn = compositeEntityImportFn(options.entityImportFn, options.editorId);
  38264. options.blockImportFn = compositeBlockImportFn(options.blockImportFn, options.editorId);
  38265. var editorState = null;
  38266. if (content instanceof external_draft_js_["EditorState"]) {
  38267. editorState = content;
  38268. } else if (typeof_default()(content) === 'object' && content && content.blocks && content.entityMap) {
  38269. editorState = Object(external_braft_convert_["convertRawToEditorState"])(content, getDecorators(options.editorId));
  38270. } else if (typeof content === 'string') {
  38271. try {
  38272. if (/^(-)?\d+$/.test(content)) {
  38273. editorState = Object(external_braft_convert_["convertHTMLToEditorState"])(content, getDecorators(options.editorId), options, 'create');
  38274. } else {
  38275. editorState = external_draft_js_["EditorState"].createFrom(JSON.parse(content), options);
  38276. }
  38277. } catch (error) {
  38278. editorState = Object(external_braft_convert_["convertHTMLToEditorState"])(content, getDecorators(options.editorId), options, 'create');
  38279. }
  38280. } else if (typeof content === 'number') {
  38281. editorState = Object(external_braft_convert_["convertHTMLToEditorState"])(content.toLocaleString().replace(/,/g, ''), getDecorators(options.editorId), options, 'create');
  38282. } else {
  38283. editorState = external_draft_js_["EditorState"].createEmpty(getDecorators(options.editorId));
  38284. }
  38285. options.styleExportFn = compositeStyleExportFn(options.styleExportFn, options.editorId);
  38286. options.entityExportFn = compositeEntityExportFn(options.entityExportFn, options.editorId);
  38287. options.blockExportFn = compositeBlockExportFn(options.blockExportFn, options.editorId);
  38288. editorState.setConvertOptions(options);
  38289. return editorState;
  38290. };
  38291. /* harmony default export */ var index_0 = __webpack_exports__["default"] = (createExtensibleEditor(editor_BraftEditor));
  38292. // 2.1版本开发计划
  38293. // [ ]优化选中多行文字是插入链接报错的问题
  38294. // [ ]新增编辑器内图片删除hook
  38295. // 2.2版本开发计划
  38296. // [ ]表格功能
  38297. // [ ]美化UI,包括图标和界面风格
  38298. // 2.3版本开发计划
  38299. // [ ]初级md快捷输入支持
  38300. // [ ]图片裁切等简单的编辑功能
  38301. // [ ]允许自定义快捷键
  38302. /***/ }),
  38303. /* 40 */
  38304. /***/ (function(module, exports) {
  38305. // removed by extract-text-webpack-plugin
  38306. /***/ }),
  38307. /* 41 */,
  38308. /* 42 */
  38309. /***/ (function(module, exports) {
  38310. // removed by extract-text-webpack-plugin
  38311. /***/ }),
  38312. /* 43 */,
  38313. /* 44 */,
  38314. /* 45 */
  38315. /***/ (function(module, exports) {
  38316. // removed by extract-text-webpack-plugin
  38317. /***/ }),
  38318. /* 46 */
  38319. /***/ (function(module, exports) {
  38320. // removed by extract-text-webpack-plugin
  38321. /***/ }),
  38322. /* 47 */
  38323. /***/ (function(module, exports) {
  38324. // removed by extract-text-webpack-plugin
  38325. /***/ }),
  38326. /* 48 */
  38327. /***/ (function(module, exports) {
  38328. // removed by extract-text-webpack-plugin
  38329. /***/ }),
  38330. /* 49 */
  38331. /***/ (function(module, exports) {
  38332. // removed by extract-text-webpack-plugin
  38333. /***/ }),
  38334. /* 50 */
  38335. /***/ (function(module, exports) {
  38336. // removed by extract-text-webpack-plugin
  38337. /***/ }),
  38338. /* 51 */
  38339. /***/ (function(module, exports) {
  38340. // removed by extract-text-webpack-plugin
  38341. /***/ }),
  38342. /* 52 */
  38343. /***/ (function(module, exports) {
  38344. // removed by extract-text-webpack-plugin
  38345. /***/ }),
  38346. /* 53 */
  38347. /***/ (function(module, exports) {
  38348. // removed by extract-text-webpack-plugin
  38349. /***/ }),
  38350. /* 54 */
  38351. /***/ (function(module, exports) {
  38352. // removed by extract-text-webpack-plugin
  38353. /***/ }),
  38354. /* 55 */
  38355. /***/ (function(module, exports) {
  38356. // removed by extract-text-webpack-plugin
  38357. /***/ }),
  38358. /* 56 */
  38359. /***/ (function(module, exports) {
  38360. // removed by extract-text-webpack-plugin
  38361. /***/ }),
  38362. /* 57 */
  38363. /***/ (function(module, exports) {
  38364. // removed by extract-text-webpack-plugin
  38365. /***/ }),
  38366. /* 58 */
  38367. /***/ (function(module, exports) {
  38368. // removed by extract-text-webpack-plugin
  38369. /***/ }),
  38370. /* 59 */
  38371. /***/ (function(module, exports) {
  38372. // removed by extract-text-webpack-plugin
  38373. /***/ }),
  38374. /* 60 */
  38375. /***/ (function(module, exports) {
  38376. // removed by extract-text-webpack-plugin
  38377. /***/ }),
  38378. /* 61 */
  38379. /***/ (function(module, exports) {
  38380. // removed by extract-text-webpack-plugin
  38381. /***/ }),
  38382. /* 62 */
  38383. /***/ (function(module, exports) {
  38384. // removed by extract-text-webpack-plugin
  38385. /***/ }),
  38386. /* 63 */
  38387. /***/ (function(module, exports) {
  38388. // removed by extract-text-webpack-plugin
  38389. /***/ })
  38390. /******/ ]);
  38391. });
  38392. });
  38393. var BraftEditor = unwrapExports(dist$3);
  38394. var css = ".index_bf-controlbar__3CCYm{margin:0;padding:0 5px;box-shadow:inset 0 -1px 0 0 rgba(0,0,0,.2)}.index_bf-controlbar__3CCYm:after{display:block;content:\"\";clear:both}.index_bf-controlbar__3CCYm button{padding:0;outline:none}.index_bf-controlbar__3CCYm button[disabled]{pointer-events:none;opacity:.3}.index_bf-controlbar__3CCYm [data-title]{position:relative}.index_bf-controlbar__3CCYm [data-title]:after,.index_bf-controlbar__3CCYm [data-title]:before{position:absolute;z-index:10;top:100%;left:50%;pointer-events:none;opacity:0;transform:translateX(-50%) translateY(-5px);transition:opacity .3s,transform .3s}.index_bf-controlbar__3CCYm [data-title]:before{margin-top:3px;border:5px solid transparent;border-bottom-color:#21242a;content:\"\"}.index_bf-controlbar__3CCYm [data-title]:after{margin-top:12px;padding:5px;background-color:#21242a;border-radius:2px;box-shadow:0 5px 15px rgba(0,0,0,.2);color:#fff;font-size:12px;line-height:16px;white-space:nowrap;content:attr(data-title)}.index_bf-controlbar__3CCYm [data-title]:hover:after,.index_bf-controlbar__3CCYm [data-title]:hover:before{opacity:1;transform:translateX(-50%) translateY(0)}.index_bf-controlbar__3CCYm input{outline:none}.index_bf-controlbar__3CCYm .index_separator-line__2q8N5{display:block;float:left;height:26px;width:1px;margin:10px;box-shadow:inset -1px 0 0 0 rgba(0,0,0,.1)}.index_bf-controlbar__3CCYm .index_separator-line__2q8N5+.index_control-item__14OBf,.index_bf-controlbar__3CCYm .index_separator-line__2q8N5+.index_control-item-group__1J9a7{margin-left:0}.index_bf-controlbar__3CCYm .index_separator-line__2q8N5+.index_separator-line__2q8N5,.index_bf-controlbar__3CCYm .index_separator-line__2q8N5.index_first-child__o980o,.index_bf-controlbar__3CCYm .index_separator-line__2q8N5.index_last-child__1erOy{display:none}.index_bf-controlbar__3CCYm .index_control-item-group__1J9a7{float:left;height:36px;margin:5px 0 5px 3px}.index_bf-controlbar__3CCYm .index_control-item-group__1J9a7:first-child{margin-left:0}.index_bf-controlbar__3CCYm .index_control-item-group__1J9a7>.index_control-item__14OBf{margin-top:0;margin-bottom:0}.index_bf-controlbar__3CCYm .index_dropdown-handler__MTW22{border-radius:2px}.index_bf-controlbar__3CCYm .index_control-item__14OBf{display:block;float:left;height:36px;margin:5px 0 5px 3px;border-radius:2px;cursor:pointer}.index_bf-controlbar__3CCYm .index_control-item__14OBf.index_component-wrapper__3TwHO{cursor:default}.index_bf-controlbar__3CCYm .index_control-item__14OBf:first-child{margin-left:0}.index_bf-controlbar__3CCYm .index_control-item__14OBf.index_button__3Upba{box-sizing:border-box;min-width:36px;padding:0 8px;background-color:transparent;border:none;color:#6a6f7b;font-size:14px}.index_bf-controlbar__3CCYm .index_control-item__14OBf.index_button__3Upba:hover{background-color:rgba(0,0,0,.05)}.index_bf-controlbar__3CCYm .index_control-item__14OBf.index_button__3Upba.index_active__-pMJD{color:#3498db}.index_bf-controlbar__3CCYm .index_control-item__14OBf.index_button__3Upba i:before{display:block;height:36px;font-size:18px;line-height:36px}.index_bf-controlbar__3CCYm .index_control-item__14OBf.index_button__3Upba .index_bfi-redo__1zMS1:before,.index_bf-controlbar__3CCYm .index_control-item__14OBf.index_button__3Upba .index_bfi-undo__1uH1l:before{font-size:14px}.index_bf-controlbar__3CCYm .index_dropdown__JBUUP .index_control-item__14OBf{width:100%;float:none;margin:0}.index_DraftEditor-editorContainer__2JNtE,.index_DraftEditor-root__1ecF2,.index_public-DraftEditor-content__24kl-{height:inherit;text-align:initial}.index_public-DraftEditor-content__24kl-[contenteditable=true]{-webkit-user-modify:read-write-plaintext-only}.index_DraftEditor-root__1ecF2{position:relative}.index_DraftEditor-editorContainer__2JNtE{background-color:hsla(0,0%,100%,0);border-left:.1px solid transparent;position:relative;z-index:1}.index_public-DraftEditor-block__BK5Tu{position:relative}.index_DraftEditor-alignLeft__1wXXz .index_public-DraftStyleDefault-block__Sv4nb{text-align:left}.index_DraftEditor-alignLeft__1wXXz .index_public-DraftEditorPlaceholder-root__q1VIv{left:0;text-align:left}.index_DraftEditor-alignCenter__1GFcJ .index_public-DraftStyleDefault-block__Sv4nb{text-align:center}.index_DraftEditor-alignCenter__1GFcJ .index_public-DraftEditorPlaceholder-root__q1VIv{margin:0 auto;text-align:center;width:100%}.index_DraftEditor-alignRight__31w6Z .index_public-DraftStyleDefault-block__Sv4nb{text-align:right}.index_DraftEditor-alignRight__31w6Z .index_public-DraftEditorPlaceholder-root__q1VIv{right:0;text-align:right}.index_public-DraftEditorPlaceholder-root__q1VIv{color:#9197a3;position:absolute;z-index:1}.index_public-DraftEditorPlaceholder-hasFocus__3gswB{color:#bdc1c9}.index_DraftEditorPlaceholder-hidden__2vqlD{display:none}.index_public-DraftStyleDefault-block__Sv4nb{position:relative;white-space:pre-wrap}.index_public-DraftStyleDefault-ltr__3nF5D{direction:ltr;text-align:left}.index_public-DraftStyleDefault-rtl__1NKvZ{direction:rtl;text-align:right}.index_public-DraftStyleDefault-listLTR__2_H8S{direction:ltr}.index_public-DraftStyleDefault-listRTL__3aocB{direction:rtl}.index_public-DraftStyleDefault-ol__2Rnls,.index_public-DraftStyleDefault-ul__26fcv{margin:16px 0;padding:0}.index_public-DraftStyleDefault-depth0__3A7Cc.index_public-DraftStyleDefault-listLTR__2_H8S{margin-left:1.5em}.index_public-DraftStyleDefault-depth0__3A7Cc.index_public-DraftStyleDefault-listRTL__3aocB{margin-right:1.5em}.index_public-DraftStyleDefault-depth1__2qvXA.index_public-DraftStyleDefault-listLTR__2_H8S{margin-left:3em}.index_public-DraftStyleDefault-depth1__2qvXA.index_public-DraftStyleDefault-listRTL__3aocB{margin-right:3em}.index_public-DraftStyleDefault-depth2__eQTbg.index_public-DraftStyleDefault-listLTR__2_H8S{margin-left:4.5em}.index_public-DraftStyleDefault-depth2__eQTbg.index_public-DraftStyleDefault-listRTL__3aocB{margin-right:4.5em}.index_public-DraftStyleDefault-depth3__1Lulo.index_public-DraftStyleDefault-listLTR__2_H8S{margin-left:6em}.index_public-DraftStyleDefault-depth3__1Lulo.index_public-DraftStyleDefault-listRTL__3aocB{margin-right:6em}.index_public-DraftStyleDefault-depth4__wdX4S.index_public-DraftStyleDefault-listLTR__2_H8S{margin-left:7.5em}.index_public-DraftStyleDefault-depth4__wdX4S.index_public-DraftStyleDefault-listRTL__3aocB{margin-right:7.5em}.index_public-DraftStyleDefault-unorderedListItem__2as-n{list-style-type:square;position:relative}.index_public-DraftStyleDefault-unorderedListItem__2as-n.index_public-DraftStyleDefault-depth0__3A7Cc{list-style-type:disc}.index_public-DraftStyleDefault-unorderedListItem__2as-n.index_public-DraftStyleDefault-depth1__2qvXA{list-style-type:circle}.index_public-DraftStyleDefault-orderedListItem__7JV9o{list-style-type:none;position:relative}.index_public-DraftStyleDefault-orderedListItem__7JV9o.index_public-DraftStyleDefault-listLTR__2_H8S:before{left:-36px;position:absolute;text-align:right;width:30px}.index_public-DraftStyleDefault-orderedListItem__7JV9o.index_public-DraftStyleDefault-listRTL__3aocB:before{position:absolute;right:-36px;text-align:left;width:30px}.index_public-DraftStyleDefault-orderedListItem__7JV9o:before{content:counter(a) \". \";counter-increment:a}.index_public-DraftStyleDefault-orderedListItem__7JV9o.index_public-DraftStyleDefault-depth1__2qvXA:before{content:counter(b) \". \";counter-increment:b}.index_public-DraftStyleDefault-orderedListItem__7JV9o.index_public-DraftStyleDefault-depth2__eQTbg:before{content:counter(c) \". \";counter-increment:c}.index_public-DraftStyleDefault-orderedListItem__7JV9o.index_public-DraftStyleDefault-depth3__1Lulo:before{content:counter(d) \". \";counter-increment:d}.index_public-DraftStyleDefault-orderedListItem__7JV9o.index_public-DraftStyleDefault-depth4__wdX4S:before{content:counter(e) \". \";counter-increment:e}.index_public-DraftStyleDefault-depth0__3A7Cc.index_public-DraftStyleDefault-reset__8e5iQ{counter-reset:a}.index_public-DraftStyleDefault-depth1__2qvXA.index_public-DraftStyleDefault-reset__8e5iQ{counter-reset:b}.index_public-DraftStyleDefault-depth2__eQTbg.index_public-DraftStyleDefault-reset__8e5iQ{counter-reset:c}.index_public-DraftStyleDefault-depth3__1Lulo.index_public-DraftStyleDefault-reset__8e5iQ{counter-reset:d}.index_public-DraftStyleDefault-depth4__wdX4S.index_public-DraftStyleDefault-reset__8e5iQ{counter-reset:e}.index_bf-switch__5k7Z0{position:relative;width:32px;height:16px;background-color:hsla(0,0%,100%,.15);border-radius:8px;transition:background .3s}.index_bf-switch__5k7Z0.index_active__-pMJD{background-color:#3498db}.index_bf-switch__5k7Z0.index_active__-pMJD:before{left:16px}.index_bf-switch__5k7Z0:before{position:absolute;left:0;display:block;width:16px;height:16px;border-radius:8px;background-color:#eee;content:\"\";transform:scale(1.2);transition:.3s}@font-face{font-family:braft-icons;src:url(data:application/font-woff;base64,d09GRgABAAAAACxUAAsAAAAALAgAAQAAAAAAAAAAAAAAAAAAAAAAAAAAAABPUy8yAAABCAAAAGAAAABgDxIH02NtYXAAAAFoAAAA9AAAAPQXCcwWZ2FzcAAAAlwAAAAIAAAACAAAABBnbHlmAAACZAAAJggAACYI9aImY2hlYWQAAChsAAAANgAAADYTSfwFaGhlYQAAKKQAAAAkAAAAJAfCBAxobXR4AAAoyAAAASwAAAEsIgAgXGxvY2EAACn0AAAAmAAAAJhQxVqgbWF4cAAAKowAAAAgAAAAIABVAH1uYW1lAAAqrAAAAYYAAAGGmUoJ+3Bvc3QAACw0AAAAIAAAACAAAwAAAAMD+QGQAAUAAAKZAswAAACPApkCzAAAAesAMwEJAAAAAAAAAAAAAAAAAAAAARAAAAAAAAAAAAAAAAAAAAAAQAAA6rADwP/AAEADwABAAAAAAQAAAAAAAAAAAAAAIAAAAAAAAwAAAAMAAAAcAAEAAwAAABwAAwABAAAAHAAEANgAAAAyACAABAASAAEAIOAp4DTgN+BC4LjiKOI547jjwuQp6SbpMelG6WjpgOms6mjqbOpu6nXqsP/9//8AAAAAACDgJuA04DfgQuC44ijiOeO448LkKekA6SzpRuln6YDprOpo6mvqbupz6rD//f//AAH/4x/eH9Qf0h/IH1Md5B3UHFYcTRvnFxEXDBb4FtgWwRaWFdsV2RXYFdQVmgADAAEAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABAAH//wAPAAEAAAAAAAAAAAACAAA3OQEAAAAAAQAAAAAAAAAAAAIAADc5AQAAAAABAAAAAAAAAAAAAgAANzkBAAAAAAQAVQCAA6sC1QARACMANQBHAAATITIXFhUUBwYjISInJjU0NzYTITIXFhUUBwYjISInJjU0NzY3ITIXFhUUBwYjISInJjU0NzY3ITIXFhUUBwYjISInJjU0NzaAAwASDA0NDBL9ABIMDQ0MEgMAEgwNDQwS/QASDA0NDBIDABIMDQ0MEv0AEgwNDQwSAwASDA0NDBL9ABIMDQ0MAtUMDRESDQwMDRIRDQz+AAwNERINDAwNEhENDKsNDBIRDQwMDRESDA2rDQwSEgwNDQwSEgwNAAAABABVAIADqwLVABEAIwA1AEcAABMhMhcWFRQHBiMhIicmNTQ3NhMhMhcWFRQHBiMhIicmNTQ3NjchMhcWFRQHBiMhIicmNTQ3NjchMhcWFRQHBiMhIicmNTQ3NoADABIMDQ0MEv0AEgwNDQwSAlUSDA0MDRL9qxIMDQ0MEgMAEgwNDQwS/QASDA0NDBICVRIMDQwNEv2rEgwNDQwC1QwNERINDAwNEhENDP4ADA0REg0MDA0SEQ0Mqw0MEhENDAwNERIMDasNDBISDA0NDBISDA0AAAAEAFUAgAOrAtUAEQAkADYASQAAEyEyFxYVFAcGIyEiJyY1NDc2EyEyFxYVFAcGIyEiJyY1NDc2MychMhcWFRQHBiMhIicmNTQ3NjchMhcWFRQHBiMhIicmNTQ3NjOAAwASDA0NDBL9ABIMDQ0MZwJWEQ0MDA0R/aoRDQwMDRFVAwASDA0NDBL9ABIMDQ0MZwJWEQ0MDA0R/aoRDQwMDREC1QwNERINDAwNEhENDP4ADA0REg0MDA0SEQ0Mqw0MEhENDAwNERIMDasNDBISDA0NDBISDA0AAAAEAFUAgAOrAtUAEQAkADYASQAAEyEyFxYVFAcGIyEiJyY1NDc2EyEyFxYVFAcGIyEiJyY1NDc2MychMhcWFRQHBiMhIicmNTQ3NjchMhcWFRQHBiMhIicmNTQ3NjOAAwASDA0NDBL9ABIMDQ0MvQJVEgwNDQwS/asSDA0MDRKrAwASDA0NDBL9ABIMDQ0MvQJVEgwNDQwS/asSDA0MDRIC1QwNERINDAwNEhENDP4ADA0REg0MDA0SEQ0Mqw0MEhENDAwNERIMDasNDBISDA0NDBISDA0AAAACAQAAgQMAAtUAAwAHAAABMxEjIREzEQJWqqr+qqoC1f2sAlT9rAAAAQFWAIEDKgLVAAIAAAkCAVYB1P4sAtX+1v7WAAEAqgArA1YDgQAuAAABMhceARcWFRQHDgEHBiMiJy4BJyY1MxQXHgEXFjMyNz4BNzY1NCcuAScmIxUnNwIARj8+XRsbGxtdPj5HRj8+XRsbVhQURS8vNTUvL0UUFBQURS8vNdbWAtUbG1w+PkZHPj5dGxsbG10+Pkc2Li9FFBQUFEUvLjY1Ly5GFBSs1tYAAAMAMwCqA80CqwAEAAkADQAAEyEVITUDNSEVITc1IRX/As79MswCzv0yaALKAqtnZ/3/Z2fOZWUABQCAACsDgAMrAAMABwALAA8AEwAAAREhEQERIREDESERAREhEQMhESEDKv8AAQD/AFT/AAEA/wBWAwD9AAHVAQD/AP6sAQD/AAFUAQD/AP6sAQD/AAKq/QAAAAACAFYAKwNWAtUACAARAAABIRUjByc3IycnFwEHJwcjNwEBAAJW+ERaHmZ4dAwCaDbyQoBo/tgC1YCgWEh4CAr9ljbynPYBKAACAIAAKwN0Ax8AAwAWAAAlAScBAR4BDwEXBycBIzUBJzcXNzYyFwEoAVhS/qgCngwBDYZSPDz+gsoBfDw8UoYMJAyBAVhS/qgB6AwjDYZSPDz+hMoBfjw8UoYMDAAAAAAEAIAAKwOAAysACAARABoAIwAAATIWHQEjNSM1EzUzFRQGKwE1JRUzFSMiJj0BETQ2OwEVIxUjAyoiNFaqqlYzI6r+VqqqIjQzI6qqVgMrNCKqqlb9VqqqIzNWqqpWMyOqAaoiNFaqAAYAgAArA4ADKwAHAAsAEwAbAB8AIwAAAREzFTMVIxUXITUhJTMRIzUjNTMBIxEzFSEVIQEhFSERIRUhAoBWqqqq/lYBqv2qVlaqqgEAVFQBVv6q/lYBqv5WAQD/AAIrAQBWVFaqVFb/AFZU/lYBAFZUAlRU/lRUAAIAgABNA4ADTQATAB0AACUhESE1ISIGFREUFjMhMjY1ESMRAxUzARcBFTMRIQMr/aoBK/7VIzIyIwJWIzJV1pr+XDwBpFX+1aICVVYyJP2rIzIyIwEr/tUCq1b+XTwBo5kBKwAEAFUAIgOrA3cABAAhAD0AQgAAJTMRIxETIgcOAQcGFRQXHgEXFjMyNz4BNzY1NCcuAScmIxEiJy4BJyY1NDc+ATc2MzIXHgEXFhUUBw4BBwYDMzUjFQHVVlYrWE5OdCEiIiF0Tk5YWE5OdCEiIiF0Tk5YRz4+XRobGxpdPj5HRz4+XRobGxpdPj5yVlb3AQD/AAKAISJzTk5YWU1OdCEiIiF0Tk1ZWE5OcyIh/QAbG10+PkdGPz5cGxsbG1w+P0ZHPj5dGxsB1lVVAAAEAFUAIgOrA3cABAAhAD0AUgAAJTM1IxUTIgcOAQcGFRQXHgEXFjMyNz4BNzY1NCcuAScmIxEiJy4BJyY1NDc+ATc2MzIXHgEXFhUUBw4BBwYDIgYVMzQ2MzIWFRQGFTM0NjU0JiMB1VZWK1hOTnQhIiIhdE5OWFhOTnQhIiIhdE5OWEc+Pl0aGxsaXT4+R0c+Pl0aGxsaXT4+R0dkVjIjIzKAVoBkR81VVQKqISJzTk5YWU1OdCEiIiF0Tk1ZWE5OcyIh/QAbG10+PkdGPz5cGxsbG1w+P0ZHPj5dGxsCVmRHIzIyI0AtaEg9UEdkAAACAFUAzQOrAs0ABQALAAABJzcnCQElNyc3CQEBkcTEPP8AAQABGsTEPAEA/wABCcTEPP8A/wA8xMQ8/wD/AAAAAwErAM0C9QMiAA8AGQAiAAABPgE1NCYjIREhMjY1NCYnJzMyFhUUBisBNRMjNTMyFhUUBgKaHydjSP72ASxDWzIp74AaJiYagJWVlRslJQIAFkEgSWL9q19DME4TtyUbGiaA/oCAJRsaJgAAAQCAACYDgAN3ADQAAAEiBgclPgE1NCYnJR4BMzI2NTQmIyIGFRQWFwUuASMiBhUUFjMyNjcFDgEVFBYzMjY1NCYjAwAYKxH+0AICAgIBLREtGTVLSzU1SwIC/tMRLRk1S0s1GS0RATACAkk0NElJNAEfEg+xBw8IBw8IrxATSzU2Sko2Bw8HsBATSzU1SxIQsQcOBzNJSTM0SQAAAQErAU0C1QIiAAIAAAEXNwEr1dUCItXVAAAAAAMAVQAiA6sDdwAcACsAOgAAASIHDgEHBhUUFx4BFxYzMjc+ATc2NTQnLgEnJiMBNDc+ATc2MzIWFwEuATUBIiYnAR4BFRQHDgEHBiMCAFhOTXQiIiIidE1OWFhOTXQiIiIidE1OWP6rGxtcPj9GOmot/iIjJQFVOmotAd4jJRsbXD4/RgN3ISJ0Tk1YWE5OdCEiIiF0Tk5YWE1OdCIh/lZGPj5dGxslI/4iLWo6/qomIwHeLWs5Rz4+XRsbAAAAAAMAgADNA4ACzQADAAcACwAANyE1ITUhNSE1FSE1gAMA/QADAP0AAwDNVYBV1lZWAAEBKwF3AtUCTQACAAABNxcBK9XVAXfW1gAAAAADAasAdwJVAyIADAAYACQAAAEyNjU0JiMiBhUUFjMVIgYVFBYzMjY1NCYDIgYVFBYzMjY1NCYCACMyMiMjMjIjIzIyIyMyMiMjMjIjIzIyAnczIyMyMiMjM1UyIyMzMyMjMv8AMiMjMzMjIzIAAAAAAwCrAXcDVQIiAAwAGAAkAAABIgYVFBYzMjY1NCYjISIGFRQWMzI2NTQmISIGFRQWMzI2NTQmAQAjMjIjIzIyIwIAIzIyIyMyMv7dIzIyIyMyMgIiMiMjMzMjIzIyIyMzMyMjMjIjIzMzIyMyAAAAAAIAAP/ABAADgAApAC0AAAERIzU0JiMhIgYdARQWMyEyNj0BMxEhFSMiBhURFBY7ATI2NRE0JisBNQEhNSEEAMAmGv1AGiYmGgLAGiaA/cAgDRMTDYANExMNIAFA/UACwAGAAYBAGiYmGsAaJiYaQP8AgBMN/sANExMNAUANE0ABgEAAAAQA1QCiAysC9wAGAA0AEwAaAAATMxUzNSMVEyMVMzUjFQEzNTM1IxM1IxUzNSPVgFbWgIDWVgEAVoDWVlbWgAEigNVVAVVV1YD+K4BVAQCA1VUAAAEAZAAlA1wDXABEAAABERQHBgcGBwYjIicmJyYnJjU0NzY3Njc2MzIXEQURFAcGBwYHBiMiJyYnJicmNTQ3Njc2NzYzMhcRNDc2NyU2MzIXFhUDXBERGhkaGRYXGRoZGhEREREaGRoZFzMr/oURERoZGhkXFhkaGRoRERERGhkaGRY0KwoJDwGbBggUDg4DLP3WGBQTCgsFBQUFCwoTFBgZExQKCwUFEwEKdv6iGRMTCwsFBQUFCwsTExkZExMLCgYFEwHeDw0MBX8CDg4UAAAEAHUAQgOJA1YALwA8AGIAeAAAAS4BBw4BJy4BJy4BBwYiJyYGBw4BJyYGBxQVHAEVFBUeATM2MzoBMzIzMjY3PAE1BSImNTQ2MzIWFRQGJyUqASM8ATU6ATMUFhUUFxwBFQYHFAYHDgEnLgE3PgE3OgEzPAE1BT4BNzoBMxQWBw4BJy4BNz4BNzoBMwKBARkZChUJCxcEFEMvBw8HHikMDCgdFyILCxgWNDM0ZzQzNBsaAf77L0FBMDBAQDEBtx8/IDRoNgEBAQENCxVFICIlBgc3JAcNCf7OAQICEyQTAwUFSiMmOAIBOiYHEAkCzhcaAQEBAwIJCC0fCAEBBhgbGxYGBBMVKCgpUCgoKQ8VARcaSpRK7T8uMEA/LzBAARchPyAKEgkzMjNmMjMzFCwRIBAOD0IjJjQDN2053QwUCi5dLSUsBgVEJig+BAAAAAAEANUAogMrAvcABQALABEAFwAAASMVMzUjAzM1MzUjASMVMzUjAxUzFTM1AStW1oBWVoDWAgCA1laAgFYBd9VVASuAVf4AVdUBgFWA1QAAAAQAAAAABAADQAAbADMATwBTAAABFBceARcWMzI3PgE3NjU0Jy4BJyYjIgcOAQcGASMuASMhIgYHIyIGFREUFjMhMjY1ETQmASInLgEnJjU0Nz4BNzYzMhceARcWFRQHDgEHBgEjNTMBMBAROCYmKysmJjgREBAROCYmKysmJjgREAKQ4AwkMP8AMCQM4BomJhoDgBomJv4mOzQzTRcWFhdNMzQ7OzQzTRcWFhdNMzQBhYCAAWArJiY4ERAQETgmJisrJiY4ERAQETgmJgE1MFBQMCYa/cAaJiYaAkAaJv2EFhdNMzQ7OzQzTRcWFhdNMzQ7OzQzTRcWAbxAAAEAkQCiA4AC3gAGAAABJwcXAScBAYCzPO8CADz+PAEaszzvAgA8/jwAAAAAAQDiAIADHgLJACYAAAE3NjQnJiIPAScmIgcGFB8BBwYUFx4BMzI2PwEXHgEzMjY3NjQvAQI84g0NDCQM4uIMJAwNDeLiDQ0GEAgIEAbi4gYQCAgQBg0N4gGr4gwjDQwM4uIMDA0jDOLiDSMMBwYGB+HhBwYGBwwjDeIAAAUAVQCVA6sC6wAZACoARABeAHgAAAEhIgYHDgEVFBYXHgEzITI2Nz4BNTQmJy4BJTQmIyEiBh0BFBYzITI2PQEDISIGBw4BFRQWFx4BMyEyNjc+ATU0JicuAQMhIgYHDgEVFBYXHgEzITI2Nz4BNTQmJy4BBSEiBgcOARUUFhceATMhMjY3PgE1NCYnLgEB1f6rCQ8GBgcHBgYPCQFVCQ8GBwYGBwYPAc0ZEv8AEhkZEgEAEhkr/QAJDwYGBwcGBg8JAwAJDwYGBwcGBg8J/QAJDwYGBwcGBg8JAwAJDwYGBwcGBg/+TP6rCQ8GBgcHBgYPCQFVCQ8GBwYGBwYPAZUGBgYQCAkPBgcGBgcGDwkIEAYGBoERGRkRrBEZGRGs/tUHBgYPCQkPBgYHBwYGDwkJDwYGBwIABwYGDwkJDwYGBwcGBg8JCQ8GBgerBgcGDwkIEAYGBgYGBhAICQ8GBwYAAAAABABVAE0DqwNNAA4AEgAeACIAAAEhIgYVETMVITUzETQmIwMhNSE3IiY1NDYzMhYVFAYDIRUhAyv9qjVLqwIAq0s1gP6qAVaAEhkZEhEZGTz+AAIAAndKNv8AqqoBADZK/ivVVhkREhkZEhEZAYCrAAIAgABjA2oDTQAiAC8AAAEjJz4BNTQnLgEnJiMiBw4BBwYVFBceARcWMzI2NxcVFzcnISImNTQ2MzIWFRQGIwKVIQwfJBYWSzMyOjkzMksWFhYWSzIzOTRcJQvWP9X/AE9xcU9QcHBQAXcMJF0zOjIzSxYWFhZLMzI6OTIzSxYWJB8MItQ/1XFPUHBwUE9xAAIAZAAiA5wDdwBNAFkAAAE+ATU0Jic3PgEvAS4BDwEuAS8BLgErASIGDwEOAQcnJgYPAQYWHwEOARUUFhcHDgEfAR4BPwEeAR8BHgE7ATI2PwE+ATcXFjY/ATYmJwUiJjU0NjMyFhUUBgM9AQICAVoGAwRVBA8HahEkFBABDAiqCAwBEBQkEWoHDwRVBAMGWgECAgFaBgMEVQQPB2oRJBQQAQwIqggMARAUJBFqBw8EVQQDBv5pPldXPj5XVwGjChULCxQLRgUPB5QHBQMqDBUIcgcKCgdyCBUMKgMFB5QHDwVGCxUKCxUKRgUQB5MHBQIrDRUIcQgKCghxCBUNKwMGB5MHEAUmWD4+V1c+PlgAAQDVAKIDKwL3AAsAAAEhESMRITUhETMRIQMr/wBW/wABAFYBAAGi/wABAFUBAP8AAAAAAAQAVf/vA6sC7wAeADMAOAA9AAATNwEHJyM1JyM1Jw4BFRQWOwEVIyInLgEnJjU0NjcnBTIXHgEXFhUUBgcnPgE1NCYrATUzITMVIycFFSMnM1U3Ask2q0mMSmogJWdIgIA1Li9FFRQyKlwCVjUuL0UVFEc5PC88Z0iAgP6qgDZRAV0zVYgCuTb9NzerSYxKaxhIKklmURQURS8vNTpnIlwfFRRFLy41R3YhPRRWN0hnUVFR1lVVAAADAFUAmgOrApoAGgA1ADkAAAEjFTMyFhUUBisBFTMyNz4BNzY1NCcuAScmIwE0NjsBNSMiBw4BBwYVFBceARcWOwE1IyImNRchNSECq4CASGdnSICANS4vRRUUFBVFLy41/ftnSICANS4vRRUUFBVFLy41gIBIZ68BVv6qAppRZ0hJZlEUFEUvLzU1Li9FFRT/AEhnURUURS8uNTUvL0UUFFFmSStVAAAFAFUAIgOrA3cAHAA4AEQAUABYAAABIgcOAQcGFRQXHgEXFjMyNz4BNzY1NCcuAScmIxEiJy4BJyY1NDc+ATc2MzIXHgEXFhUUBw4BBwYTMjY1NCYjIgYVFBYhMjY1NCYjIgYVFBYTMjY3IR4BMwIAWU1OdCEiIiF0Tk1ZWE5OdCEiIiF0Tk5YRz4+XRsaGhtdPj5HRz4+XRsaGhtdPj5OGyUlGxomJv7wGiYmGhslJbBLdRr+TBp1SwN3ISJzTk5YWU1OdCEiIiF0Tk1ZWE5OcyIh/QAbG10+PkdHPj5dGhsbGl0+PkdHPj5dGxsBgCYaGyUlGxomJhobJSUbGib+61RBQVQAAAAJAAAAQAQAA0AAAwAHAAsADwATABcAGwAfACIAABMRIREBIzUzNSM1MzUjNTMBIREhEyM1MzUjNTM1IzUzBRElAAQA/MCAgICAgIACQP4AAgDAgICAgICA/cABAANA/QADAP1AgICAgID9gAKA/YCAgICAgID+gMAAAAAAAgDVAE0DKwNNABkAHgAAJTI3PgE3NjURIxEUBiMiJjURIxEUFx4BFxYHFSE1IQIANS8uRhQUa1c+PldrFBRGLi/2Alb9qvcVFEUvLzQBVv6qPVhYPQFW/qo0Ly9FFBVVVVUAAAUAVQCVA6sC6wAaACsARQBfAHoAAAEhMhYXHgEVFAYHDgEjISImJy4BNTQ2Nz4BMyU0NjMhMhYdARQGIyEiJj0BEyEyFhceARUUBgcOASMhIiYnLgE1NDY3PgETITIWFx4BFRQGBw4BIyEiJicuATU0Njc+AQUhMhYXHgEVFAYHDgEjISImJy4BNTQ2Nz4BMwIrAVUJDwYGBwcGBg8J/qsJDwYHBgYHBg8J/ioZEgEAEhkZEv8AEhkrAwAJDwYGBwcGBg8J/QAJDwYGBwcGBg8JAwAJDwYGBwcGBg8J/QAJDwYGBwcGBg8BtAFVCQ8GBgcHBgYPCf6rCQ8GBwYGBwYPCQGVBgYGEAgJDwYHBgYHBg8JCBAGBgaBERkZEawRGRkRrP7VBwYGDwkJDwYGBwcGBg8JCQ8GBgcCAAcGBg8JCQ8GBgcHBgYPCQkPBgYHqwYHBg8JCBAGBgYGBgYQCAkPBgcGAAAAAAMAgACiA4ADIgAEAA0AEQAAJTM1IxUDFTMVMzUzNSEDITUhAauqqtbWqtb9qlUDAP0AooCAAoCAgICA/lVWAAACAIAAogOrAyIACAARAAABFTMRMxEzNSEBMxEzETM1IRUBgNWA1v3V/wCAgID+gAMigP4AAgCA/qv+1QErgIAAAgDVAPcDKwKiAAYADQAAJTM3ESERMwUzNxEhETMBAIBV/wCAAQCAVv8AgPerAQD/AKurAQD/AAAGAFUAdwOAAyIACwASAB0AIgAnACwAADczFSMVMxUjFTM1IxMzNSMVMxUHMwcVMzUjNzUjFRMVITUhESE1IRURITUhFVVWKytWgIArK1YrK01NgExMgNYCVf2rAlX9qwJV/av3FSsVK6sBVasrgIBZJytaJisBAFVV/atVVQEAVVUAAAAGAGsAjQOAAw0ACwAXACMAKAAtADIAABMiBhUUFjMyNjU0JgMiBhUUFjMyNjU0JgMiBhUUFjMyNjU0JhchNSEVESE1IRURFSE1IasbJSUbGiYmGhslJRsaJiYaGyUlGxomJmYCVf2rAlX9qwJV/asCDSYaGyUlGxomAQAmGhslJRsaJv4AJhoaJiYaGiZrVVUBAFVVAVVVVQAAAAABAQAAzQMAAyIACwAAARUzAyMVITUjEzM1AatekncBVV6SdwMigP6rgIABVYAAAAABAAABawQAAesAAwAAEyEVIQAEAPwAAeuAAAAABgBA/8ADwAPAABkAIQA5AEcAVQBjAAABLgEnLgEnLgEjISIGFREUFjMhMjY1ETQmJyceARcjNR4BExQGIyEiJjURNDYzMDM6ATMyMRUUFjsBAyEiJjU0NjMhMhYVFAYnISImNTQ2MyEyFhUUBichIiY1NDYzITIWFRQGA5YRLRkaMxcnKQv+ECEvLyEC4CEvDhyFFyUNmhEphgkH/SAHCQkHTU66TU4TDeCg/kANExMNAcANExMN/kANExMNAcANExMN/kANExMNAcANExMC2xczGhktERwOLyH8oCEvLyECcAspJzYXKRGaDSX86AcJCQcDYAcJ4A0T/gATDQ0TEw0NE4ATDQ0TEw0NE4ATDQ0TEw0NEwAAAAUAAP/ABAADwAAIAAsAEwAWABwAAAERIQcRIREhESUVIwMRMzUhFQcRExUjASERMzUhAoD+QMABgAKA/MBlG8ABQMDAZQHl/gDAAUACwAEAwP3A/wADAKVl/gABwMDAwP8AAWVl/gABwMAAAAUAQP/ABAADwAANABgANAA3AD0AAAEjNTQmKwEiBh0BIxUhJyM1OAExMzgBMRUFNTQmKwEVMxUjBxEhETM1IyIGFREUFjMhFSERBRUjASERMzUhAsCAJhqAGiaAAgDAgIABQBMNQCDAwP8AIEANExMNASACgP5AZQHl/gDAAUADQEAaJiYaQICAQEDAoA0TQIDA/wACQEATDf2ADRPAAsBbZf5AAYDAAAYAgABNA4ADTQADAAcACwAPABMAFwAANyE1IRkBNycBITUhARUhNQEhNSERITUhgAMA/QCrqwFVAav+Vf6rAwD+VQGr/lUBq/5VTVUB1f6rq6r+gFYCAFZW/wBV/wBVAAYAgABNA4ADTQADAAcACwAPABMAFwAAJSE1ISUXEQcRITUhERUhNQEhNSERITUhAdUBq/5V/qurqwMA/QADAP5VAav+VQGr/lX3VoCrAVWq/oBVAqtWVv8AVf8AVQAAAAEAAP/NBAAAdwADAAA3IRUhAAQA/AB3qgAAAAACAOsA9wMVA00ACAAMAAABAzM3IRczAyMDGwEjAdXqYC8BCzBg6lY7ZmbMA039qoCAAlb+gAEO/vIAAAACAAD/wAQAA8AADgASAAABBxcDIxcBFTMBFzUlFzcFJzcXAiBgYODgsP7wJwFpsAEAYGD9wEDgQAPAYGD/ALD+lycBELDg4GBgQEDgQAAAAAEAQP/AA4oDwAARAAAFNjc2JicmBxUJARU2Fx4BBwYC+isTEzhVVqj+gAGAyXFyRignQE1bW5ozMgT+AYABgPgFTk7siokAAAEAdv/AA8ADwAASAAABNQkBNSYHDgEXFhcmJyY2NzYXAkABgP6AqFZVOBMTK2knKEZycckCyPj+gP6A/gQyM5pbW01yiYrsTk4FAAAHAAD/wAQAA0YACwAXACMALwA7AEcAUwAAJTQ2MzIWFRQGIyImATQ2MzIWFRQGIyImJTQ2MzIWFRQGIyImATQ2MzIWFRQGIyImATQ2MzIWFRQGIyImJTQ2MzIWFRQGIyImATQ2MzIWFRQGIyImAaA4KCg4OCgoOP5gOCgoODgoKDgDQDgoKDg4KCg4/To4KCg4OCgoOAJMOCgoODgoKDj9tDgoKDg4KCg4Akw4KCg4OCgoOCAoODgoKDg4AcgoODgoKDg4KCg4OCgoODgBTig4OCgoODj93Cg4OCgoODgoKDg4KCg4OAJ0KDg4KCg4OAAFAHwAAAOEA1UAIgAtADgARgBUAAABIzU0JisBIgYdASMiBhUUFjsBERQWMyEyNjURMzI2NTQmIyU0NjsBMhYdASM1ARQGIyEiJjURIREBIgYdARQWMzI2PQE0JjMiBh0BFBYzMjY9ATQmA12bRDCcMESbEBcXECdEMAGEMEQnEBcXEP4vFhCcEBboAV0XEP58EBcB0v7JEBYWEBAXF4wQFxcQEBYWAronMEREMCcXEBAW/gcwREQwAfkWEBAXJxAXFxAnJ/2TEBYWEAH5/gcBhBcQ6BAXFxDoEBcXEOgQFxcQ6BAXAAAABwAA/8AEAAPAAAMABwALAA8AEwAbACMAABMzFSM3MxUjJTMVIzczFSMlMxUjAxMhEzMTIRMBAyEDIwMhAwCAgMDAwAEAgIDAwMABAICAEBD9ABAgEAKAEP1AEAMAECAQ/YAQAcBAQEBAQEBAQEACQP5AAcD+gAGA/AABgP6AAUD+wAAABABQAIAEAAPAAAgADQAQAEAAAD8BIRczAyMDMxMzFyM3ARsBAyMiJjU0NjsBMjY1NCYrASIGFRQWFx4BOwEyFhUUBisBIgYVFBY7ATI2NTQmJy4BwjoBCDpywODAcppIOrw6AWSgoKBADRMTDYANExMNgCg4DQwNJRVADRMTDYANExMNgCg4DQwNJYDAwAKA/YACAMDA/gABAP8AAsATDQ0TEw0NEzgoEiENDxETDQ0TEw0NEzgoEiENDxEAAAAABABQ/8AEAAMAAAgADQAQAEAAAD8BIRczAyMDMxMzFyM3JQsBEyMiJjU0NjsBMjY1NCYrASIGFRQWFx4BOwEyFhUUBisBIgYVFBY7ATI2NTQmJy4BwjoBCDpywODAcppIOrw6AqSgoKBADRMTDYANExMNgCg4DQwNJRVADRMTDYANExMNgCg4DQwNJYDAwAKA/YACAMDAgP8AAQD9gBMNDRMTDQ0TOCgSIQ0PERMNDRMTDQ0TOCgSIQ0PEQAHAAD/wAQAA8AABwAPABMAFwAbAB8AIgAAAREhESMRIREFESERMxEhESUzFSMnMxUjJTMVIzczFSMlFwcBAAMAQP2AAsD9AEACgP5AgIDAgIABgICAwICA/IDAwAJAAYD+gAFA/sDA/kABwP6AAYCAQEBAQEBAQODAwAAAAQCA/8ADgAPAABcAAAEhFSMRIxEjESMRIicuAScmNTQ3PgE3NgGAAgCAgICANS8uRhQUFBRGLi8DwID8gAOA/IACABQURi4vNTUvLkYUFAACAAD/wAQAA8AAFwAaAAABIgcOAQcGFRQXHgEXFjMRMxEzETMRMzUJAgIANS8uRhQUFBRGLi81gICAgPwAAQD/AAPAFBRGLi81NS8uRhQU/gADgPyAA4CA/UABAAEAAAACAAD/wAQAA8AAFwAaAAABIgcOAQcGFRQXHgEXFjMRMxEzETMRMzUFCQEBADUvLkYUFBQURi4vNYCAgIABAP8AAQADwBQURi4vNTUvLkYUFP4AA4D8gAOAgMD/AP8AAAABAAD/zgQAA7MAYwAAASIHDgEHBhUUFx4BFxYXFjY1PAEnBiYxLgExJjYxHgExFjY3PgE3JicuAScmNTQ2Ny4BNzAWFz4BMzIWFz4BMRYGBx4BFRQHDgEHBgceARUUBhUUFjc2Nz4BNzY1NCcuAScmIwIAal1eiygoGhpdQUBMExABakISJyMnJigiXRYEEgsrKipCFBUcGQQMFUNKHkEhIUEeSkMVDAQZHBUUQyopKw4VARATTEFAXRoaKCiLXl1qA7MoKItdXmpUTU2ALy8ZBBIKCTYgF1QsHxgHAzI7BwoYIgoFDA04Ly9JKkUbCUk1AzEICQkIMQM1SQkbRSpKLy44DA0FCzAjNEwNChIEGS8wf01NVGpeXYsoKAAAAAABAAAAAQAAt9HlfV8PPPUACwQAAAAAANgVW8QAAAAA2BVbxAAA/8AEAAPAAAAACAACAAAAAAAAAAEAAAPA/8AAAAQAAAAAAAQAAAEAAAAAAAAAAAAAAAAAAABLBAAAAAAAAAAAAAAAAgAAAAQAAFUEAABVBAAAVQQAAFUEAAEABAABVgQAAKoEAAAzBAAAgAQAAFYEAACABAAAgAQAAIAEAACABAAAVQQAAFUEAABVBAABKwQAAIAEAAErBAAAVQQAAIAEAAErBAABqwQAAKsEAAAABAAA1QQAAGQEAAB1BAAA1QQAAAAEAACRBAAA4gQAAFUEAABVBAAAgAQAAGQEAADVBAAAVQQAAFUEAABVBAAAAAQAANUEAABVBAAAgAQAAIAEAADVBAAAVQQAAGsEAAEABAAAAAQAAEAEAAAABAAAQAQAAIAEAACABAAAAAQAAOsEAAAABAAAQAQAAHYEAAAABAAAfAQAAAAEAABQBAAAUAQAAAAEAACABAAAAAQAAAAEAAAAAAAAAAAKABQAHgCIAPIBXgHKAd4B7AI0AlACfgKiAtIDBgNCA3QD2gRSBHIEqAT2BQQFZAV8BYoFwgX6BjwGZgbOB3YHnggcCDIIcAkiCVoJogoqCkQKoAr0C3gLtgvoDJwMvAzcDPgNOg2IDaANrg46DnAOxA70DyQPMg9QD3gPnA/CEDoQrhDwEVARrhHsEhQSRBJ0EwQAAQAAAEsAewAJAAAAAAACAAAAAAAAAAAAAAAAAAAAAAAAAA4ArgABAAAAAAABAAcAAAABAAAAAAACAAcAYAABAAAAAAADAAcANgABAAAAAAAEAAcAdQABAAAAAAAFAAsAFQABAAAAAAAGAAcASwABAAAAAAAKABoAigADAAEECQABAA4ABwADAAEECQACAA4AZwADAAEECQADAA4APQADAAEECQAEAA4AfAADAAEECQAFABYAIAADAAEECQAGAA4AUgADAAEECQAKADQApGljb21vb24AaQBjAG8AbQBvAG8AblZlcnNpb24gMS4wAFYAZQByAHMAaQBvAG4AIAAxAC4AMGljb21vb24AaQBjAG8AbQBvAG8Abmljb21vb24AaQBjAG8AbQBvAG8AblJlZ3VsYXIAUgBlAGcAdQBsAGEAcmljb21vb24AaQBjAG8AbQBvAG8AbkZvbnQgZ2VuZXJhdGVkIGJ5IEljb01vb24uAEYAbwBuAHQAIABnAGUAbgBlAHIAYQB0AGUAZAAgAGIAeQAgAEkAYwBvAE0AbwBvAG4ALgAAAAMAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=);font-weight:400;font-style:normal}.index_bf-container__pDnZN [class*=\" bfi-\"],.index_bf-container__pDnZN [class^=bfi-],.index_bf-modal-root__1vZsk [class*=\" bfi-\"],.index_bf-modal-root__1vZsk [class^=bfi-]{font-family:braft-icons!important;speak:none;font-style:normal;font-weight:400;font-variant:normal;text-transform:none;-webkit-font-smoothing:antialiased;-moz-osx-font-smoothing:grayscale}.index_bf-container__pDnZN .index_bfi-table__2n-Nu:before,.index_bf-modal-root__1vZsk .index_bfi-table__2n-Nu:before{content:\"\\E228\"}.index_bf-container__pDnZN .index_bfi-clear_all__1DWPd:before,.index_bf-modal-root__1vZsk .index_bfi-clear_all__1DWPd:before{content:\"\\E0B8\"}.index_bf-container__pDnZN .index_bfi-format_clear__18bKu:before,.index_bf-modal-root__1vZsk .index_bfi-format_clear__18bKu:before{content:\"\\E239\"}.index_bf-container__pDnZN .index_bfi-hr__3Dyol:before,.index_bf-modal-root__1vZsk .index_bfi-hr__3Dyol:before{content:\"\\E925\"}.index_bf-container__pDnZN .index_bfi-colorize__3kvdJ:before,.index_bf-modal-root__1vZsk .index_bfi-colorize__3kvdJ:before{content:\"\\E3B8\"}.index_bf-container__pDnZN .index_bfi-crop_free___WShj:before,.index_bf-modal-root__1vZsk .index_bfi-crop_free___WShj:before{content:\"\\E3C2\"}.index_bf-container__pDnZN .index_bfi-pause__1yVdD:before,.index_bf-modal-root__1vZsk .index_bfi-pause__1yVdD:before{content:\"\\E034\"}.index_bf-container__pDnZN .index_bfi-play_arrow__TAu2k:before,.index_bf-modal-root__1vZsk .index_bfi-play_arrow__TAu2k:before{content:\"\\E037\"}.index_bf-container__pDnZN .index_bfi-bin__1RNIO:before,.index_bf-modal-root__1vZsk .index_bfi-bin__1RNIO:before{content:\"\\E9AC\"}.index_bf-container__pDnZN .index_bfi-replay__a2eQS:before,.index_bf-modal-root__1vZsk .index_bfi-replay__a2eQS:before{content:\"\\E042\"}.index_bf-container__pDnZN .index_bfi-tune__3djXd:before,.index_bf-modal-root__1vZsk .index_bfi-tune__3djXd:before{content:\"\\E429\"}.index_bf-container__pDnZN .index_bfi-close__3nM0K:before,.index_bf-modal-root__1vZsk .index_bfi-close__3nM0K:before{content:\"\\E913\"}.index_bf-container__pDnZN .index_bfi-align-center__32OAW:before,.index_bf-modal-root__1vZsk .index_bfi-align-center__32OAW:before{content:\"\\E028\"}.index_bf-container__pDnZN .index_bfi-align-justify__28esT:before,.index_bf-modal-root__1vZsk .index_bfi-align-justify__28esT:before{content:\"\\E026\"}.index_bf-container__pDnZN .index_bfi-align-left__1xURH:before,.index_bf-modal-root__1vZsk .index_bfi-align-left__1xURH:before{content:\"\\E027\"}.index_bf-container__pDnZN .index_bfi-align-right__dTKZi:before,.index_bf-modal-root__1vZsk .index_bfi-align-right__dTKZi:before{content:\"\\E029\"}.index_bf-container__pDnZN .index_bfi-image-right__dC3pp:before,.index_bf-modal-root__1vZsk .index_bfi-image-right__dC3pp:before{content:\"\\E914\"}.index_bf-container__pDnZN .index_bfi-image-left__1RS1z:before,.index_bf-modal-root__1vZsk .index_bfi-image-left__1RS1z:before{content:\"\\E91E\"}.index_bf-container__pDnZN .index_bfi-music__1icOF:before,.index_bf-modal-root__1vZsk .index_bfi-music__1icOF:before{content:\"\\E90E\"}.index_bf-container__pDnZN .index_bfi-camera__1iPe1:before,.index_bf-modal-root__1vZsk .index_bfi-camera__1iPe1:before{content:\"\\E911\"}.index_bf-container__pDnZN .index_bfi-copy__2zFg6:before,.index_bf-modal-root__1vZsk .index_bfi-copy__2zFg6:before{content:\"\\E92C\"}.index_bf-container__pDnZN .index_bfi-file-text__3mXsh:before,.index_bf-modal-root__1vZsk .index_bfi-file-text__3mXsh:before{content:\"\\E926\"}.index_bf-container__pDnZN .index_bfi-film__2iCvn:before,.index_bf-modal-root__1vZsk .index_bfi-film__2iCvn:before{content:\"\\E91C\"}.index_bf-container__pDnZN .index_bfi-github__brZ94:before,.index_bf-modal-root__1vZsk .index_bfi-github__brZ94:before{content:\"\\EAB0\"}.index_bf-container__pDnZN .index_bfi-ltr__27xC4:before,.index_bf-modal-root__1vZsk .index_bfi-ltr__27xC4:before{content:\"\\EA74\"}.index_bf-container__pDnZN .index_bfi-page-break__4-FKT:before,.index_bf-modal-root__1vZsk .index_bfi-page-break__4-FKT:before{content:\"\\EA68\"}.index_bf-container__pDnZN .index_bfi-pagebreak__1BIxj:before,.index_bf-modal-root__1vZsk .index_bfi-pagebreak__1BIxj:before{content:\"\\EA6E\"}.index_bf-container__pDnZN .index_bfi-paint-format__3Eyz1:before,.index_bf-modal-root__1vZsk .index_bfi-paint-format__3Eyz1:before{content:\"\\E90C\"}.index_bf-container__pDnZN .index_bfi-paste__2D7ES:before,.index_bf-modal-root__1vZsk .index_bfi-paste__2D7ES:before{content:\"\\E92D\"}.index_bf-container__pDnZN .index_bfi-pilcrow__1hD8x:before,.index_bf-modal-root__1vZsk .index_bfi-pilcrow__1hD8x:before{content:\"\\EA73\"}.index_bf-container__pDnZN .index_bfi-pushpin__ddOjX:before,.index_bf-modal-root__1vZsk .index_bfi-pushpin__ddOjX:before{content:\"\\E946\"}.index_bf-container__pDnZN .index_bfi-redo__1zMS1:before,.index_bf-modal-root__1vZsk .index_bfi-redo__1zMS1:before{content:\"\\E968\"}.index_bf-container__pDnZN .index_bfi-rtl__WVUh3:before,.index_bf-modal-root__1vZsk .index_bfi-rtl__WVUh3:before{content:\"\\EA75\"}.index_bf-container__pDnZN .index_bfi-spinner__zgwYo:before,.index_bf-modal-root__1vZsk .index_bfi-spinner__zgwYo:before{content:\"\\E980\"}.index_bf-container__pDnZN .index_bfi-subscript__2lvcn:before,.index_bf-modal-root__1vZsk .index_bfi-subscript__2lvcn:before{content:\"\\EA6C\"}.index_bf-container__pDnZN .index_bfi-superscript__39qvB:before,.index_bf-modal-root__1vZsk .index_bfi-superscript__39qvB:before{content:\"\\EA6B\"}.index_bf-container__pDnZN .index_bfi-undo__1uH1l:before,.index_bf-modal-root__1vZsk .index_bfi-undo__1uH1l:before{content:\"\\E967\"}.index_bf-container__pDnZN .index_bfi-media__1X3ie:before,.index_bf-modal-root__1vZsk .index_bfi-media__1X3ie:before{content:\"\\E90F\"}.index_bf-container__pDnZN .index_bfi-add__Senjb:before,.index_bf-modal-root__1vZsk .index_bfi-add__Senjb:before{content:\"\\E918\"}.index_bf-container__pDnZN .index_bfi-bold__3XBUf:before,.index_bf-modal-root__1vZsk .index_bfi-bold__3XBUf:before{content:\"\\E904\"}.index_bf-container__pDnZN .index_bfi-code__2_u8T:before,.index_bf-modal-root__1vZsk .index_bfi-code__2_u8T:before{content:\"\\E903\"}.index_bf-container__pDnZN .index_bfi-done__2SBW5:before,.index_bf-modal-root__1vZsk .index_bfi-done__2SBW5:before{content:\"\\E912\"}.index_bf-container__pDnZN .index_bfi-drop-down__hwaaA:before,.index_bf-modal-root__1vZsk .index_bfi-drop-down__hwaaA:before{content:\"\\E906\"}.index_bf-container__pDnZN .index_bfi-drop-up__30tNg:before,.index_bf-modal-root__1vZsk .index_bfi-drop-up__30tNg:before{content:\"\\E909\"}.index_bf-container__pDnZN .index_bfi-emoji__1kiSF:before,.index_bf-modal-root__1vZsk .index_bfi-emoji__1kiSF:before{content:\"\\E91B\"}.index_bf-container__pDnZN .index_bfi-font-size__3Ze0F:before,.index_bf-modal-root__1vZsk .index_bfi-font-size__3Ze0F:before{content:\"\\E920\"}.index_bf-container__pDnZN .index_bfi-fullscreen__rXrOP:before,.index_bf-modal-root__1vZsk .index_bfi-fullscreen__rXrOP:before{content:\"\\E910\"}.index_bf-container__pDnZN .index_bfi-fullscreen-exit__3Mqrf:before,.index_bf-modal-root__1vZsk .index_bfi-fullscreen-exit__3Mqrf:before{content:\"\\E90D\"}.index_bf-container__pDnZN .index_bfi-help__fDlhJ:before,.index_bf-modal-root__1vZsk .index_bfi-help__fDlhJ:before{content:\"\\E902\"}.index_bf-container__pDnZN .index_bfi-indent-decrease__CiP-9:before,.index_bf-modal-root__1vZsk .index_bfi-indent-decrease__CiP-9:before{content:\"\\E92F\"}.index_bf-container__pDnZN .index_bfi-indent-increase__ri4Fd:before,.index_bf-modal-root__1vZsk .index_bfi-indent-increase__ri4Fd:before{content:\"\\E92E\"}.index_bf-container__pDnZN .index_bfi-info__1Yirj:before,.index_bf-modal-root__1vZsk .index_bfi-info__1Yirj:before{content:\"\\E901\"}.index_bf-container__pDnZN .index_bfi-italic__pSD0Q:before,.index_bf-modal-root__1vZsk .index_bfi-italic__pSD0Q:before{content:\"\\E924\"}.index_bf-container__pDnZN .index_bfi-link__1G6mh:before,.index_bf-modal-root__1vZsk .index_bfi-link__1G6mh:before{content:\"\\E91A\"}.index_bf-container__pDnZN .index_bfi-link-off__3BJ9G:before,.index_bf-modal-root__1vZsk .index_bfi-link-off__3BJ9G:before{content:\"\\E919\"}.index_bf-container__pDnZN .index_bfi-list__34DiG:before,.index_bf-modal-root__1vZsk .index_bfi-list__34DiG:before{content:\"\\E923\"}.index_bf-container__pDnZN .index_bfi-list-numbered__1smmd:before,.index_bf-modal-root__1vZsk .index_bfi-list-numbered__1smmd:before{content:\"\\E922\"}.index_bf-container__pDnZN .index_bfi-menu__1NUnm:before,.index_bf-modal-root__1vZsk .index_bfi-menu__1NUnm:before{content:\"\\E908\"}.index_bf-container__pDnZN .index_bfi-more-horiz__44PbX:before,.index_bf-modal-root__1vZsk .index_bfi-more-horiz__44PbX:before{content:\"\\E90B\"}.index_bf-container__pDnZN .index_bfi-more-vert__hz05g:before,.index_bf-modal-root__1vZsk .index_bfi-more-vert__hz05g:before{content:\"\\E90A\"}.index_bf-container__pDnZN .index_bfi-not-disturb__2T4dR:before,.index_bf-modal-root__1vZsk .index_bfi-not-disturb__2T4dR:before{content:\"\\E907\"}.index_bf-container__pDnZN .index_bfi-print__16wCn:before,.index_bf-modal-root__1vZsk .index_bfi-print__16wCn:before{content:\"\\E915\"}.index_bf-container__pDnZN .index_bfi-quote__3DFSY:before,.index_bf-modal-root__1vZsk .index_bfi-quote__3DFSY:before{content:\"\\E921\"}.index_bf-container__pDnZN .index_bfi-search__2ZXmI:before,.index_bf-modal-root__1vZsk .index_bfi-search__2ZXmI:before{content:\"\\E916\"}.index_bf-container__pDnZN .index_bfi-settingsx__B0nTj:before,.index_bf-modal-root__1vZsk .index_bfi-settingsx__B0nTj:before{content:\"\\E917\"}.index_bf-container__pDnZN .index_bfi-share__1YW3x:before,.index_bf-modal-root__1vZsk .index_bfi-share__1YW3x:before{content:\"\\E905\"}.index_bf-container__pDnZN .index_bfi-share-square__1WnYO:before,.index_bf-modal-root__1vZsk .index_bfi-share-square__1WnYO:before{content:\"\\E900\"}.index_bf-container__pDnZN .index_bfi-strikethrough__2PgId:before,.index_bf-modal-root__1vZsk .index_bfi-strikethrough__2PgId:before{content:\"\\E91F\"}.index_bf-container__pDnZN .index_bfi-text-color__1O4Kp .index_path1__1A5aH:before,.index_bf-modal-root__1vZsk .index_bfi-text-color__1O4Kp .index_path1__1A5aH:before{font-family:braft-icons!important;content:\"\\E930\";opacity:.36}.index_bf-container__pDnZN .index_bfi-text-color__1O4Kp .index_path2__2v3Cp:before,.index_bf-modal-root__1vZsk .index_bfi-text-color__1O4Kp .index_path2__2v3Cp:before{font-family:braft-icons!important;content:\"\\E931\";margin-left:-1em}.index_bf-container__pDnZN .index_bfi-underlined__3WKo2:before,.index_bf-modal-root__1vZsk .index_bfi-underlined__3WKo2:before{content:\"\\E91D\"}.index_bf-content__216XJ{height:500px;padding-bottom:10px;overflow:auto;font-size:16px}.index_bf-content__216XJ img{-webkit-user-select:none;user-select:none}.index_bf-content__216XJ *{line-height:normal}.index_bf-container__pDnZN{position:relative;height:100%;padding:0}.index_bf-container__pDnZN.index_disabled__QRqWr{pointer-events:none;opacity:.7;filter:grayscale(70%)}.index_bf-container__pDnZN.index_read-only__1ud0X .index_bf-controlbar__3CCYm{pointer-events:none}.index_bf-container__pDnZN.index_read-only__1ud0X .index_bf-image__1aolB img:hover{outline:none}.index_bf-container__pDnZN.index_read-only__1ud0X .index_bf-hr__1U3wo{pointer-events:none}.index_bf-container__pDnZN.index_fullscreen__2ZKS5{position:fixed;display:flex;flex-direction:column;z-index:99999;top:0;right:0;bottom:0;left:0;background-color:#fff;height:100%!important}.index_bf-container__pDnZN.index_fullscreen__2ZKS5 .index_bf-content__216XJ{flex-grow:1;height:auto}.index_bf-container__pDnZN .index_input-group__3B65V{display:block}.index_bf-container__pDnZN .index_input-group__3B65V input{box-sizing:border-box;width:100%;height:36px;padding:0 15px;font-size:14px}.index_bf-container__pDnZN .index_pull-left__3uitd{float:left}.index_bf-container__pDnZN .index_pull-right__3l3V5{float:right}.index_bf-container__pDnZN button{line-height:normal}.index_bf-container__pDnZN button.index_default__dCgOD,.index_bf-container__pDnZN button.index_ghost__22h6J,.index_bf-container__pDnZN button.index_primary__2l-C6{height:32px;padding:0 20px;color:#fff;font-size:12px}.index_bf-container__pDnZN button.index_default__dCgOD{background-color:hsla(0,0%,100%,.15);border:none}.index_bf-container__pDnZN button.index_default__dCgOD:hover{background-color:hsla(0,0%,100%,.1)}.index_bf-container__pDnZN button.index_ghost__22h6J{background-color:transparent;border:none;box-shadow:inset 0 0 0 .5px hsla(0,0%,100%,.5)}.index_bf-container__pDnZN button.index_ghost__22h6J:hover{box-shadow:inset 0 0 0 .5px hsla(0,0%,100%,.7)}.index_bf-container__pDnZN button.index_primary__2l-C6{background-color:#3498db;border:none;color:#fff}.index_bf-container__pDnZN button.index_primary__2l-C6:hover{background-color:#2084c7}.index_bf-container__pDnZN .index_public-DraftEditorPlaceholder-root__q1VIv{top:15px;left:15px;font-size:16px;pointer-events:none}.index_bf-container__pDnZN .index_DraftEditor-editorContainer__2JNtE{box-sizing:border-box;border:none}.index_bf-container__pDnZN .index_DraftEditor-root__1ecF2,.index_bf-container__pDnZN .index_public-DraftEditor-content__24kl-{height:100%}.index_bf-container__pDnZN .index_public-DraftEditor-content__24kl-{box-sizing:border-box;padding:15px;word-wrap:break-word;word-break:break-all}.index_bf-container__pDnZN .index_public-DraftEditor-content__24kl->div{padding-bottom:20px}.index_bf-container__pDnZN .index_public-DraftEditor-content__24kl- .index_braft-link__3aKL8{color:#4078c0}.index_bf-container__pDnZN .index_public-DraftEditor-content__24kl- blockquote{margin:0 0 10px;padding:15px 20px;background-color:#f1f2f3;border-left:5px solid #ccc;color:#666;font-style:italic}.index_bf-container__pDnZN .index_public-DraftEditor-content__24kl- pre{max-width:100%;max-height:100%;margin:10px 0;padding:15px;overflow:auto;background-color:#f1f2f3;border-radius:3px;color:#666;font-family:monospace;font-size:14px;font-weight:400;line-height:16px;word-wrap:break-word;white-space:pre-wrap}.index_bf-container__pDnZN .index_public-DraftEditor-content__24kl- pre pre{margin:0;padding:0}.index_bf-container__pDnZN .index_bfa-left__3-1T_,.index_bf-container__pDnZN .index_bfa-left__3-1T_ .index_public-DraftStyleDefault-ltr__3nF5D{text-align:left}.index_bf-container__pDnZN .index_bfa-right__VstO0,.index_bf-container__pDnZN .index_bfa-right__VstO0 .index_public-DraftStyleDefault-ltr__3nF5D{text-align:right}.index_bf-container__pDnZN .index_bfa-center__1Gy81,.index_bf-container__pDnZN .index_bfa-center__1Gy81 .index_public-DraftStyleDefault-ltr__3nF5D{text-align:center}.index_bf-container__pDnZN .index_bfa-justify__TPlSj,.index_bf-container__pDnZN .index_bfa-justify__TPlSj .index_public-DraftStyleDefault-ltr__3nF5D{text-align:justify}.index_bf-container__pDnZN .index_bfa-center__1Gy81>div,.index_bf-container__pDnZN .index_bfa-justify__TPlSj>div,.index_bf-container__pDnZN .index_bfa-left__3-1T_>div,.index_bf-container__pDnZN .index_bfa-right__VstO0>div{display:inline-block}.index_bf-container__pDnZN .index_bff-left__3vDOo:hover,.index_bf-container__pDnZN .index_bff-right__3X5rQ:hover{z-index:2}.index_bf-container__pDnZN .index_bff-left__3vDOo{position:relative;z-index:1;float:left;margin:0 10px 0 0}.index_bf-container__pDnZN .index_bff-right__3X5rQ{position:relative;z-index:1;float:right;margin:0 0 0 10px}.index_bf-container__pDnZN .index_bftd-1__15-5d{text-indent:2em;display:initial}.index_bf-container__pDnZN .index_bftd-2__1JQXC{text-indent:4em;display:initial}.index_bf-container__pDnZN .index_bftd-3__3gI7R{text-indent:6em;display:initial}.index_bf-container__pDnZN .index_bftd-4__2mnyV{text-indent:8em;display:initial}.index_bf-container__pDnZN .index_bftd-5__2dFUN{text-indent:10em;display:initial}.index_bf-container__pDnZN .index_bftd-6__DN8IU{text-indent:12em;display:initial}.index_bf-container__pDnZN .index_bf-image__1aolB,.index_bf-container__pDnZN .index_bf-media__1enRX{position:relative}.index_bf-container__pDnZN .index_bf-image__1aolB img{display:block;max-width:100%;font-size:0;resize:both;outline-offset:1px}.index_bf-container__pDnZN .index_bf-image__1aolB img:hover{outline:1px solid #3498db}.index_bf-container__pDnZN .index_bf-media-toolbar__2V9Pp{position:absolute;z-index:3;bottom:15px;left:50%;width:auto;background-color:#21242a;border-radius:2px;font-weight:400;text-align:center;white-space:nowrap;transform:translateX(-50%);box-shadow:0 5px 15px rgba(0,0,0,.2);-webkit-user-select:none;user-select:none}.index_bf-container__pDnZN .index_bf-media-toolbar__2V9Pp .index_bf-media-toolbar-arrow__wQs6N,.index_bf-container__pDnZN .index_bf-media-toolbar__2V9Pp:before{position:absolute;bottom:-10px;left:50%;display:block;border:5px solid transparent;border-top-color:#21242a;content:\"\";transform:translateX(-5px)}.index_bf-container__pDnZN .index_bf-media-toolbar__2V9Pp a{display:inline-block;min-width:40px;height:40px;color:hsla(0,0%,100%,.5);font-family:braft-icons!important;font-size:18px;font-weight:400;line-height:40px;text-align:center;text-decoration:none;text-transform:uppercase;cursor:pointer}.index_bf-container__pDnZN .index_bf-media-toolbar__2V9Pp a:hover{color:#fff}.index_bf-container__pDnZN .index_bf-media-toolbar__2V9Pp a:first-child{border-radius:2px 0 0 2px}.index_bf-container__pDnZN .index_bf-media-toolbar__2V9Pp a:last-child{border-radius:0 2px 2px 0}.index_bf-container__pDnZN .index_bf-media-toolbar__2V9Pp a.index_active__-pMJD{color:#3498db}.index_bf-video-player__ShN8m video{display:block;width:640px;max-width:80vw;height:auto;margin:0 10px 10px;object-fit:contain}.index_bf-audio-player__1Lhv8 audio{width:480px;max-width:80vw;margin:0 10px 10px}.index_bf-player-holder__1jMDw{position:relative;height:240px;overflow:hidden;background-color:#21242a;border-radius:3px}.index_bf-player-holder__1jMDw .index_icon-badge__3vdSq{position:absolute;z-index:2;top:0;left:0;height:30px;padding:0 15px;border-radius:0 0 3px 0;color:#fff;background-color:hsla(0,0%,100%,.1)}.index_bf-player-holder__1jMDw .index_icon-badge__3vdSq i,.index_bf-player-holder__1jMDw .index_icon-badge__3vdSq span{display:block;float:left;line-height:30px}.index_bf-player-holder__1jMDw .index_icon-badge__3vdSq span{margin-left:5px;font-size:12px}.index_bf-player-holder__1jMDw .index_button-remove__3gFzp{position:absolute;z-index:2;top:5px;right:5px;width:40px;height:40px;background-color:transparent;border:none;border-radius:50%;outline:none;color:#fff;font-size:24px;text-align:center;cursor:pointer}.index_bf-player-holder__1jMDw .index_button-remove__3gFzp:hover{color:#e74c3c}.index_bf-player-holder__1jMDw .index_button-play__1DEoA{position:relative;z-index:2;display:block;width:80px;height:80px;margin:40px auto 20px;background-color:rgba(0,0,0,.7);border:none;border-radius:50%;outline:none;color:#fff;font-size:48px;line-height:80px;text-align:center;backdrop-filter:blur(10px);-webkit-backdrop-filter:blur(10px);cursor:pointer}.index_bf-player-holder__1jMDw .index_button-play__1DEoA:hover{background-color:#3498db}.index_bf-player-holder__1jMDw .index_bf-name__45BKL{position:relative;z-index:2;margin:0;color:#fff;font-size:14px;font-weight:500;text-align:center}.index_bf-player-holder__1jMDw .index_bf-url__8vnVl{position:relative;z-index:2;width:70%;margin:10px auto;color:hsla(0,0%,100%,.5);font-size:12px;font-weight:400;text-align:center}.index_bf-player-holder__1jMDw .index_bf-poster__2mGu4{position:absolute;top:0;left:0;width:100%;height:100%;background-repeat:no-repeat;background-position:50% 50%;background-size:cover;opacity:.3}.index_bf-modal__1v7vJ{position:fixed;z-index:99999;top:0;left:0;width:100%;height:100%}.index_bf-modal__1v7vJ button{outline:none}.index_bf-modal-mask__17u3f{position:absolute;z-index:1;top:0;left:0;width:100%;height:100%;background-color:rgba(0,0,0,.1);opacity:0;transition:opacity .2s}.index_bf-modal-content__1NJ2r{position:absolute;z-index:2;top:45%;left:50%;max-width:95%;background-color:#fff;border-radius:2px;box-shadow:0 15px 30px rgba(0,0,0,.1);opacity:0;transform:translate(-50%,-40%);transition:transform .2s,opacity .2s}.index_bf-modal-header__1_5Y9{height:50px}.index_bf-modal-caption__3Iajr{float:left;margin:0;padding:0 15px;color:#999;font-size:14px;font-weight:400;line-height:50px}.index_bf-modal-close-button__1-IHh{float:right;width:50px;height:50px;background-color:transparent;border:none;color:#ccc;font-size:18px;cursor:pointer}.index_bf-modal-close-button__1-IHh:hover{color:#e74c3c}.index_bf-modal-body__1WIdL{overflow:auto}.index_bf-modal-footer__L6ZDV{min-height:15px;padding:0 15px;overflow:hidden}.index_bf-modal-addon-text__1Ovsi{float:left;color:#999;font-size:12px;line-height:60px}.index_bf-modal-buttons__1oq66{float:right}.index_bf-modal-cancel__2rR_W,.index_bf-modal-confirm__1wWIW{height:36px;margin:12px 0 12px 15px;padding:0 30px;border:none;border-radius:2px;font-size:12px;font-weight:700;cursor:pointer}.index_bf-modal-cancel__2rR_W{background-color:#e8e9ea;color:#999}.index_bf-modal-cancel__2rR_W:hover{background-color:#d8d9da}.index_bf-modal-confirm__1wWIW{background-color:#3498db;color:#fff}.index_bf-modal-confirm__1wWIW:hover{background-color:#2084c7}.index_bf-modal-confirm__1wWIW.index_disabled__QRqWr{opacity:.3;pointer-events:none;filter:grayscale(.4)}.index_bf-modal-root__1vZsk.index_active__-pMJD .index_bf-modal-mask__17u3f{opacity:1}.index_bf-modal-root__1vZsk.index_active__-pMJD .index_bf-modal-content__1NJ2r{opacity:1;transform:translate(-50%,-50%)}.index_bf-content__216XJ .index_bf-hr__1U3wo{position:relative;box-sizing:content-box;height:15px;padding-top:15px;text-align:center}.index_bf-content__216XJ .index_bf-hr__1U3wo:before{display:block;height:1px;background-color:rgba(0,0,0,.1);content:\"\"}.index_bf-content__216XJ .index_bf-hr__1U3wo:hover:before{background-color:rgba(0,0,0,.3)}.index_bf-content__216XJ .index_bf-hr__1U3wo:hover .index_bf-media-toolbar__2V9Pp{display:block}.index_bf-content__216XJ .index_bf-hr__1U3wo .index_bf-media-toolbar__2V9Pp{display:none}.index_bf-image-link-editor__1bXBJ,.index_bf-image-size-editor__1FDp7{padding-bottom:1px;overflow:hidden;border-radius:2px 2px 0 0;box-shadow:inset 0 -1px 0 0 hsla(0,0%,100%,.1)}.index_bf-image-link-editor__1bXBJ .index_editor-input-group__3JCRG,.index_bf-image-size-editor__1FDp7 .index_editor-input-group__3JCRG{width:300px;margin:8px 10px;overflow:hidden}.index_bf-image-link-editor__1bXBJ input,.index_bf-image-size-editor__1FDp7 input{display:block;float:left;box-sizing:content-box;height:32px;margin:0 5px 0 0;padding:0 10px;background-color:hsla(0,0%,100%,.1);border:none;border-radius:2px;outline:none;box-shadow:inset 0 0 0 1px hsla(0,0%,100%,.1);color:#fff;font-weight:700}.index_bf-image-link-editor__1bXBJ input:hover,.index_bf-image-size-editor__1FDp7 input:hover{box-shadow:inset 0 0 0 1px rgba(52,152,219,.5)}.index_bf-image-link-editor__1bXBJ input:focus,.index_bf-image-size-editor__1FDp7 input:focus{box-shadow:inset 0 0 0 1px #3498db}.index_bf-image-link-editor__1bXBJ button,.index_bf-image-size-editor__1FDp7 button{float:left;width:90px;height:32px;margin:0;padding:0 20px;background-color:#3498db;border:none;color:#fff;font-size:12px;border-radius:2px;cursor:pointer}.index_bf-image-link-editor__1bXBJ button:hover,.index_bf-image-size-editor__1FDp7 button:hover{background-color:#2084c7}.index_bf-image-size-editor__1FDp7 input{width:80px}.index_bf-image-link-editor__1bXBJ input{width:185px}.index_bf-image-link-editor__1bXBJ .index_switch-group__3EJZe{height:16px;margin:10px}.index_bf-image-link-editor__1bXBJ .index_switch-group__3EJZe .index_bf-switch__5k7Z0{float:left}.index_bf-image-link-editor__1bXBJ .index_switch-group__3EJZe label{float:left;margin-left:15px;color:#999;font-size:12px;line-height:16px}.index_bf-content__216XJ .index_bf-image__1aolB{position:relative}.index_bf-content__216XJ .index_bf-image__1aolB .index_bf-csize-icon__hs23I{position:absolute;z-index:2;width:10px;height:10px;background-color:rgba(52,152,219,.3)}.index_bf-content__216XJ .index_bf-image__1aolB .index_bf-csize-icon__hs23I.index_right-bottom__1m3h4{right:0;bottom:0;cursor:se-resize}.index_bf-content__216XJ .index_bf-image__1aolB .index_bf-csize-icon__hs23I.index_left-bottom__3H_hO{left:0;bottom:0;cursor:sw-resize}.index_bf-content__216XJ .index_bf-image__1aolB .index_bf-pre-csize__26hDk{position:absolute;z-index:1;background:transparent}.index_bf-content__216XJ .index_bf-image__1aolB .index_bf-pre-csize__26hDk.index_rightbottom__12aca{left:0;top:0;border:1px dashed #00bfff}.index_bf-content__216XJ .index_bf-image__1aolB .index_bf-pre-csize__26hDk.index_leftbottom__1mn5L{right:0;top:0;border:1px dashed #00bfff}.index_bf-content__216XJ .index_bf-image__1aolB .index_bf-media-toolbar__2V9Pp:before{visibility:hidden}.index_bf-content__216XJ .index_bf-image__1aolB .index_bf-media-toolbar__2V9Pp[data-align=center] [data-align=center],.index_bf-content__216XJ .index_bf-image__1aolB .index_bf-media-toolbar__2V9Pp[data-align=left] [data-align=left],.index_bf-content__216XJ .index_bf-image__1aolB .index_bf-media-toolbar__2V9Pp[data-align=right] [data-align=right],.index_bf-content__216XJ .index_bf-image__1aolB .index_bf-media-toolbar__2V9Pp[data-float=left] [data-float=left],.index_bf-content__216XJ .index_bf-image__1aolB .index_bf-media-toolbar__2V9Pp[data-float=right] [data-float=right]{color:#3498db}.index_headings-dropdown__3zS22{min-width:110px}.index_headings-dropdown__3zS22 .index_menu__369Um{width:200px;overflow:hidden}.index_headings-dropdown__3zS22 .index_menu__369Um .index_menu-item__3Ybal{padding:15px 20px;text-align:left;line-height:normal}.index_headings-dropdown__3zS22 .index_menu__369Um .index_menu-item__3Ybal h1,.index_headings-dropdown__3zS22 .index_menu__369Um .index_menu-item__3Ybal h2,.index_headings-dropdown__3zS22 .index_menu__369Um .index_menu-item__3Ybal h3,.index_headings-dropdown__3zS22 .index_menu__369Um .index_menu-item__3Ybal h4,.index_headings-dropdown__3zS22 .index_menu__369Um .index_menu-item__3Ybal h5,.index_headings-dropdown__3zS22 .index_menu__369Um .index_menu-item__3Ybal h6{margin:0;padding:0;color:inherit}.index_headings-dropdown__3zS22 .index_menu__369Um .index_menu-item__3Ybal h1{font-size:28px}.index_headings-dropdown__3zS22 .index_menu__369Um .index_menu-item__3Ybal h2{font-size:24px}.index_headings-dropdown__3zS22 .index_menu__369Um .index_menu-item__3Ybal h3{font-size:20px}.index_headings-dropdown__3zS22 .index_menu__369Um .index_menu-item__3Ybal h4{font-size:16px}.index_headings-dropdown__3zS22 .index_menu__369Um .index_menu-item__3Ybal h5{font-size:14px}.index_headings-dropdown__3zS22 .index_menu__369Um .index_menu-item__3Ybal h6{font-size:12px}.index_bf-link-editor__fEYeX{width:360px;padding-top:25px}.index_bf-link-editor__fEYeX .index_input-group__3B65V{margin:0 15px 8px}.index_bf-link-editor__fEYeX .index_input-group__3B65V input{background-color:hsla(0,0%,100%,.07);border:none;border-radius:2px;box-shadow:inset 0 0 0 1px hsla(0,0%,100%,.1);color:#fff;font-weight:700}.index_bf-link-editor__fEYeX .index_input-group__3B65V input:hover{box-shadow:inset 0 0 0 1px rgba(52,152,219,.5)}.index_bf-link-editor__fEYeX .index_input-group__3B65V input:focus{box-shadow:inset 0 0 0 1px #3498db}.index_bf-link-editor__fEYeX .index_input-group__3B65V input:disabled{color:hsla(0,0%,100%,.7);box-shadow:none}.index_bf-link-editor__fEYeX .index_switch-group__3EJZe{height:16px;margin:15px}.index_bf-link-editor__fEYeX .index_switch-group__3EJZe .index_bf-switch__5k7Z0{float:left}.index_bf-link-editor__fEYeX .index_switch-group__3EJZe label{float:left;margin-left:15px;color:#999;font-size:12px;line-height:16px}.index_bf-link-editor__fEYeX .index_buttons__14sII{box-sizing:content-box;height:32px;margin-top:20px;padding:15px;overflow:hidden;box-shadow:inset 0 1px 0 0 hsla(0,0%,100%,.1)}.index_bf-link-editor__fEYeX .index_buttons__14sII .index_button-remove-link__2g1bP{color:#999;font-size:12px;line-height:32px;cursor:pointer}.index_bf-link-editor__fEYeX .index_buttons__14sII .index_button-remove-link__2g1bP:hover{color:#e74c3c}.index_bf-link-editor__fEYeX .index_buttons__14sII .index_button-remove-link__2g1bP i{margin-right:5px;font-size:16px}.index_bf-link-editor__fEYeX .index_buttons__14sII .index_button-remove-link__2g1bP i,.index_bf-link-editor__fEYeX .index_buttons__14sII .index_button-remove-link__2g1bP span{display:block;float:left;line-height:32px}.index_bf-link-editor__fEYeX .index_buttons__14sII button{margin-left:10px;border-radius:2px;font-weight:700;cursor:pointer}.index_bf-dropdown__oN6FC{position:relative;width:auto;height:36px;margin:0}.index_bf-dropdown__oN6FC.index_disabled__QRqWr{pointer-events:none;opacity:.3}.index_bf-dropdown__oN6FC.index_light-theme__3jxMV .index_dropdown-content__2MgGm{border:1px solid #ccc}.index_bf-dropdown__oN6FC.index_light-theme__3jxMV .index_dropdown-content__2MgGm .index_dropdown-arrow__1VDfJ{background-color:#fff;border:1px solid #ccc}.index_bf-dropdown__oN6FC.index_light-theme__3jxMV .index_dropdown-content__2MgGm .index_dropdown-content-inner__1Norc{background-color:#fff}.index_bf-dropdown__oN6FC .index_dropdown-content__2MgGm{box-sizing:content-box;position:absolute;z-index:10;top:100%;left:50%;visibility:hidden;float:left;width:auto;min-width:100%;margin-top:9px;border-radius:2px;box-shadow:0 5px 15px rgba(0,0,0,.2);opacity:0;cursor:default;transform:translate(-50%,20px);transition:.2s}.index_bf-dropdown__oN6FC .index_dropdown-content__2MgGm ::-webkit-scrollbar-track{background-color:transparent}.index_bf-dropdown__oN6FC .index_dropdown-content__2MgGm ::-webkit-scrollbar{width:4px;background-color:transparent;border-radius:2px}.index_bf-dropdown__oN6FC .index_dropdown-content__2MgGm ::-webkit-scrollbar-thumb{background-color:hsla(0,0%,100%,.3);border-radius:2px}.index_bf-dropdown__oN6FC .index_dropdown-content__2MgGm .index_dropdown-arrow__1VDfJ{position:absolute;z-index:1;top:-3px;left:50%;width:10px;height:10px;background-color:#21242a;transform:translateX(-50%) rotate(45deg);transition:margin .2s}.index_bf-dropdown__oN6FC .index_dropdown-content__2MgGm .index_dropdown-arrow__1VDfJ.index_active__-pMJD{background-color:#3498db}.index_bf-dropdown__oN6FC .index_dropdown-content__2MgGm .index_menu__369Um{list-style:none;margin:0;padding:0;overflow:hidden;border-radius:2px}.index_bf-dropdown__oN6FC .index_dropdown-content__2MgGm .index_menu-item__3Ybal{display:block;list-style:none;margin:0;font-size:16px;cursor:pointer}.index_bf-dropdown__oN6FC .index_dropdown-content__2MgGm .index_menu-item__3Ybal:hover{background-color:rgba(0,0,0,.1)}.index_bf-dropdown__oN6FC .index_dropdown-content__2MgGm .index_menu-item__3Ybal.index_active__-pMJD{background-color:#3498db;color:#fff}.index_bf-dropdown__oN6FC .index_dropdown-content__2MgGm .index_menu-item__3Ybal:not(.index_active__-pMJD){color:hsla(0,0%,100%,.6);box-shadow:inset 0 -1px 0 0 hsla(0,0%,100%,.1)}.index_bf-dropdown__oN6FC .index_dropdown-content-inner__1Norc{position:relative;z-index:2;overflow:auto;background-color:#21242a;border-radius:2px}.index_bf-dropdown__oN6FC .index_dropdown-handler__MTW22{position:relative;display:block;width:100%;height:36px;background-color:transparent;border:none;color:#6a6f7b;cursor:pointer}.index_bf-dropdown__oN6FC .index_dropdown-handler__MTW22:hover{background-color:rgba(0,0,0,.05)}.index_bf-dropdown__oN6FC .index_dropdown-handler__MTW22 *{display:inline;padding:0;font-size:inherit;font-weight:400}.index_bf-dropdown__oN6FC .index_dropdown-handler__MTW22>span{float:left;padding:0 10px;font-size:14px;line-height:36px;pointer-events:none}.index_bf-dropdown__oN6FC .index_dropdown-handler__MTW22>span i{display:block;height:36px;font-size:16px;line-height:36px;text-align:center}.index_bf-dropdown__oN6FC .index_dropdown-handler__MTW22 .index_bfi-drop-down__hwaaA{float:right;width:30px;height:36px;font-size:16px;line-height:36px;text-align:center;pointer-events:none}.index_bf-dropdown__oN6FC.index_active__-pMJD .index_dropdown-handler__MTW22{background-color:rgba(0,0,0,.05)}.index_bf-dropdown__oN6FC.index_active__-pMJD .index_dropdown-content__2MgGm{visibility:visible;opacity:1;transform:translate(-50%)}.index_text-color-dropdown__MG26p.index_light-theme__3jxMV .index_bf-color-switch-buttons__PLYUW button{border-bottom:1px solid #ccc;color:#616569}.index_text-color-dropdown__MG26p.index_light-theme__3jxMV .index_bf-color-switch-buttons__PLYUW button.index_active__-pMJD{border-bottom-color:#3498db;color:#3498db}.index_text-color-dropdown__MG26p button.index_dropdown-handler__MTW22 span{width:36px;padding:0;overflow:hidden;border-radius:2px}.index_text-color-dropdown__MG26p .index_bf-text-color-picker-wrap__3BVM3{overflow:hidden}.index_text-color-dropdown__MG26p .index_bf-color-switch-buttons__PLYUW{height:36px}.index_text-color-dropdown__MG26p .index_bf-color-switch-buttons__PLYUW button{float:left;width:50%;height:36px;background-color:transparent;border:none;border-bottom:1px solid hsla(0,0%,100%,.1);color:hsla(0,0%,100%,.5);font-size:12px;font-weight:400;text-transform:uppercase;cursor:pointer}.index_text-color-dropdown__MG26p .index_bf-color-switch-buttons__PLYUW button.index_active__-pMJD{border-bottom-color:#3498db;color:#3498db}.index_bf-colors__3herU{box-sizing:content-box;list-style:none;width:240px;margin:0;padding:15px;overflow:hidden}.index_bf-colors__3herU li{box-sizing:content-box;display:block;float:left;width:24px;height:24px;margin:5px;padding:0;background-color:currentColor;border:3px solid transparent;border-radius:50%;cursor:pointer;transition:transform .2s}.index_bf-colors__3herU li:hover{transform:scale(1.3)}.index_bf-colors__3herU li.index_active__-pMJD{box-shadow:0 0 0 2px #3498db}.index_bf-font-size-dropdown__2e1Ks{min-width:95px}.index_bf-font-sizes__7rSPu{box-sizing:content-box;width:210px;list-style:none;margin:0;padding:5px;overflow:hidden}.index_bf-font-sizes__7rSPu li{display:block;float:left;width:60px;height:30px;background-color:hsla(0,0%,100%,.1);border-radius:2px;margin:5px;color:#fff;font-size:12px;line-height:30px;text-align:center;text-transform:uppercase;cursor:pointer}.index_bf-font-sizes__7rSPu li:hover{background-color:hsla(0,0%,100%,.2)}.index_bf-font-sizes__7rSPu li.index_active__-pMJD{background-color:#3498db}.index_font-family-dropdown__3I8Gd{min-width:120px}.index_font-family-dropdown__3I8Gd .index_dropdown-content__2MgGm{width:180px}.index_font-family-dropdown__3I8Gd .index_menu-item__3Ybal{padding:12px 15px}.index_bf-line-height-dropdown__1-8zQ{min-width:95px}.index_bf-line-heights__1Db9U{box-sizing:content-box;width:210px;list-style:none;margin:0;padding:5px;overflow:hidden}.index_bf-line-heights__1Db9U li{display:block;float:left;width:60px;height:30px;background-color:hsla(0,0%,100%,.1);border-radius:2px;margin:5px;color:#fff;font-size:12px;line-height:30px;text-align:center;text-transform:uppercase;cursor:pointer}.index_bf-line-heights__1Db9U li:hover{background-color:hsla(0,0%,100%,.2)}.index_bf-line-heights__1Db9U li.index_active__-pMJD{background-color:#3498db}.index_bf-letter-spacing-dropdown__POLhV{min-width:95px}.index_bf-letter-spacings__2k6yk{box-sizing:content-box;width:210px;list-style:none;margin:0;padding:5px;overflow:hidden}.index_bf-letter-spacings__2k6yk li{display:block;float:left;width:60px;height:30px;background-color:hsla(0,0%,100%,.1);border-radius:2px;margin:5px;color:#fff;font-size:12px;line-height:30px;text-align:center;text-transform:uppercase;cursor:pointer}.index_bf-letter-spacings__2k6yk li:hover{background-color:hsla(0,0%,100%,.2)}.index_bf-letter-spacings__2k6yk li.index_active__-pMJD{background-color:#3498db}.index_bf-emojis-wrap__208kW{position:relative;width:210px;height:220px;overflow:hidden}.index_bf-emojis-wrap__208kW:after,.index_bf-emojis-wrap__208kW:before{position:absolute;z-index:1;right:0;left:0;height:30px;border-radius:2px;content:\"\";pointer-events:none}.index_bf-emojis-wrap__208kW:before{top:0;background-image:linear-gradient(0deg,rgba(33,36,42,0),#21242a)}.index_bf-emojis-wrap__208kW:after{bottom:0;background-image:linear-gradient(rgba(33,36,42,0),#21242a)}.index_bf-emojis__VNlnW{box-sizing:content-box;width:200px;height:195px;list-style:none;margin:0;padding:15px 15px 20px;overflow:auto}.index_bf-emojis__VNlnW li{display:block;float:left;width:30px;height:30px;margin:0;padding:0;color:#fff;border-radius:2px;font-family:Apple Color Emoji,Segoe UI,Segoe UI Emoji,Segoe UI Symbol;font-size:18px;line-height:32px;text-align:center;cursor:pointer;-webkit-user-select:none;user-select:none;transition:transform .2s}.index_bf-emojis__VNlnW li:hover{transform:scale(1.5)}";
  38395. styleInject(css);
  38396. var css$1 = ".emoticon_braft-emoticon-picker__3fALT{box-sizing:border-box;width:210px;height:210px;overflow:hidden}.emoticon_braft-emoticon-picker__3fALT:after,.emoticon_braft-emoticon-picker__3fALT:before{position:absolute;z-index:1;right:0;left:0;height:30px;border-radius:2px;content:\"\";pointer-events:none}.emoticon_braft-emoticon-picker__3fALT:before{top:0;background-image:linear-gradient(0deg,rgba(33,36,42,0),#21242a)}.emoticon_braft-emoticon-picker__3fALT:after{bottom:0;background-image:linear-gradient(rgba(33,36,42,0),#21242a)}.emoticon_braft-emoticon-picker__3fALT .emoticon_braft-emoticons-list__1Wu0r{box-sizing:content-box;width:200px;height:190px;margin:0;padding:15px 15px 20px;overflow:auto}.emoticon_braft-emoticon-picker__3fALT .emoticon_braft-emoticons-list__1Wu0r img{display:block;box-sizing:content-box;float:left;width:20px;height:20px;margin:3px;padding:5px;border-radius:3px}.emoticon_braft-emoticon-picker__3fALT .emoticon_braft-emoticons-list__1Wu0r img:hover{background-color:#3498db}.emoticon_braft-emoticon-in-editor__1xLtg{position:relative;padding:0 2px;letter-spacing:12px}.emoticon_braft-emoticon-in-editor__1xLtg img{position:absolute;top:0;left:2px;width:16px;height:16px}";
  38397. styleInject(css$1);
  38398. var emoticon = createCommonjsModule(function (module, exports) {
  38399. (function webpackUniversalModuleDefinition(root, factory) {
  38400. module.exports = factory(React, dist$1);
  38401. })(window, function(__WEBPACK_EXTERNAL_MODULE__1__, __WEBPACK_EXTERNAL_MODULE__6__) {
  38402. return /******/ (function(modules) { // webpackBootstrap
  38403. /******/ // The module cache
  38404. /******/ var installedModules = {};
  38405. /******/
  38406. /******/ // The require function
  38407. /******/ function __webpack_require__(moduleId) {
  38408. /******/
  38409. /******/ // Check if module is in cache
  38410. /******/ if(installedModules[moduleId]) {
  38411. /******/ return installedModules[moduleId].exports;
  38412. /******/ }
  38413. /******/ // Create a new module (and put it into the cache)
  38414. /******/ var module = installedModules[moduleId] = {
  38415. /******/ i: moduleId,
  38416. /******/ l: false,
  38417. /******/ exports: {}
  38418. /******/ };
  38419. /******/
  38420. /******/ // Execute the module function
  38421. /******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);
  38422. /******/
  38423. /******/ // Flag the module as loaded
  38424. /******/ module.l = true;
  38425. /******/
  38426. /******/ // Return the exports of the module
  38427. /******/ return module.exports;
  38428. /******/ }
  38429. /******/
  38430. /******/
  38431. /******/ // expose the modules object (__webpack_modules__)
  38432. /******/ __webpack_require__.m = modules;
  38433. /******/
  38434. /******/ // expose the module cache
  38435. /******/ __webpack_require__.c = installedModules;
  38436. /******/
  38437. /******/ // define getter function for harmony exports
  38438. /******/ __webpack_require__.d = function(exports, name, getter) {
  38439. /******/ if(!__webpack_require__.o(exports, name)) {
  38440. /******/ Object.defineProperty(exports, name, { enumerable: true, get: getter });
  38441. /******/ }
  38442. /******/ };
  38443. /******/
  38444. /******/ // define __esModule on exports
  38445. /******/ __webpack_require__.r = function(exports) {
  38446. /******/ if(typeof Symbol !== 'undefined' && Symbol.toStringTag) {
  38447. /******/ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
  38448. /******/ }
  38449. /******/ Object.defineProperty(exports, '__esModule', { value: true });
  38450. /******/ };
  38451. /******/
  38452. /******/ // create a fake namespace object
  38453. /******/ // mode & 1: value is a module id, require it
  38454. /******/ // mode & 2: merge all properties of value into the ns
  38455. /******/ // mode & 4: return value when already ns object
  38456. /******/ // mode & 8|1: behave like require
  38457. /******/ __webpack_require__.t = function(value, mode) {
  38458. /******/ if(mode & 1) value = __webpack_require__(value);
  38459. /******/ if(mode & 8) return value;
  38460. /******/ if((mode & 4) && typeof value === 'object' && value && value.__esModule) return value;
  38461. /******/ var ns = Object.create(null);
  38462. /******/ __webpack_require__.r(ns);
  38463. /******/ Object.defineProperty(ns, 'default', { enumerable: true, value: value });
  38464. /******/ if(mode & 2 && typeof value != 'string') for(var key in value) __webpack_require__.d(ns, key, function(key) { return value[key]; }.bind(null, key));
  38465. /******/ return ns;
  38466. /******/ };
  38467. /******/
  38468. /******/ // getDefaultExport function for compatibility with non-harmony modules
  38469. /******/ __webpack_require__.n = function(module) {
  38470. /******/ var getter = module && module.__esModule ?
  38471. /******/ function getDefault() { return module['default']; } :
  38472. /******/ function getModuleExports() { return module; };
  38473. /******/ __webpack_require__.d(getter, 'a', getter);
  38474. /******/ return getter;
  38475. /******/ };
  38476. /******/
  38477. /******/ // Object.prototype.hasOwnProperty.call
  38478. /******/ __webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); };
  38479. /******/
  38480. /******/ // __webpack_public_path__
  38481. /******/ __webpack_require__.p = "/";
  38482. /******/
  38483. /******/
  38484. /******/ // Load entry module and return exports
  38485. /******/ return __webpack_require__(__webpack_require__.s = 33);
  38486. /******/ })
  38487. /************************************************************************/
  38488. /******/ ({
  38489. /***/ 1:
  38490. /***/ (function(module, exports) {
  38491. module.exports = __WEBPACK_EXTERNAL_MODULE__1__;
  38492. /***/ }),
  38493. /***/ 2:
  38494. /***/ (function(module, exports) {
  38495. function _defineProperty(obj, key, value) {
  38496. if (key in obj) {
  38497. Object.defineProperty(obj, key, {
  38498. value: value,
  38499. enumerable: true,
  38500. configurable: true,
  38501. writable: true
  38502. });
  38503. } else {
  38504. obj[key] = value;
  38505. }
  38506. return obj;
  38507. }
  38508. module.exports = _defineProperty;
  38509. /***/ }),
  38510. /***/ 33:
  38511. /***/ (function(module, __webpack_exports__, __webpack_require__) {
  38512. __webpack_require__.r(__webpack_exports__);
  38513. /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "defaultEmoticons", function() { return defaultEmoticons; });
  38514. /* harmony import */ var _babel_runtime_helpers_objectSpread__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(5);
  38515. /* harmony import */ var _babel_runtime_helpers_objectSpread__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_objectSpread__WEBPACK_IMPORTED_MODULE_0__);
  38516. /* harmony import */ var react__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(1);
  38517. /* harmony import */ var react__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_1__);
  38518. /* harmony import */ var braft_utils__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(6);
  38519. /* harmony import */ var _styles_scss__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(48);
  38520. // https://www.iconfinder.com/iconsets/emoji-18
  38521. var defaultEmoticons = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25].map(function (item) {
  38522. return "".concat(item, ".png");
  38523. });
  38524. var insertEmoticon = function insertEmoticon(editor, editorState, src) {
  38525. editor.setValue(braft_utils__WEBPACK_IMPORTED_MODULE_2__["ContentUtils"].insertText(editorState, ' ', null, {
  38526. type: 'EMOTICON',
  38527. mutability: 'IMMUTABLE',
  38528. data: {
  38529. src: src
  38530. }
  38531. }));
  38532. };
  38533. var controlRef = null;
  38534. var bindControlRef = function bindControlRef(ref) {
  38535. return controlRef = ref;
  38536. };
  38537. /* harmony default export */ __webpack_exports__["default"] = (function (options) {
  38538. options = _babel_runtime_helpers_objectSpread__WEBPACK_IMPORTED_MODULE_0___default()({
  38539. emoticons: [],
  38540. closeOnSelect: false,
  38541. closeOnBlur: false
  38542. }, options);
  38543. var _options = options,
  38544. emoticons = _options.emoticons,
  38545. closeOnSelect = _options.closeOnSelect,
  38546. closeOnBlur = _options.closeOnBlur,
  38547. includeEditors = _options.includeEditors,
  38548. excludeEditors = _options.excludeEditors;
  38549. return {
  38550. type: 'entity',
  38551. includeEditors: includeEditors,
  38552. excludeEditors: excludeEditors,
  38553. name: 'EMOTICON',
  38554. control: function control(props) {
  38555. return {
  38556. key: 'EMOTICON',
  38557. replace: 'emoji',
  38558. type: 'dropdown',
  38559. text: react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("i", {
  38560. className: "bfi-emoji"
  38561. }),
  38562. showArrow: false,
  38563. ref: bindControlRef,
  38564. autoHide: closeOnBlur,
  38565. component: react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("div", {
  38566. className: "braft-emoticon-picker"
  38567. }, react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("div", {
  38568. className: "braft-emoticons-list"
  38569. }, emoticons.map(function (item, index) {
  38570. return react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("img", {
  38571. onClick: function onClick() {
  38572. insertEmoticon(props.editor, props.editorState, item);
  38573. closeOnSelect && controlRef && controlRef.hide();
  38574. },
  38575. key: index,
  38576. src: item
  38577. });
  38578. })))
  38579. };
  38580. },
  38581. mutability: 'IMMUTABLE',
  38582. component: function component(props) {
  38583. var entity = props.contentState.getEntity(props.entityKey);
  38584. var _entity$getData = entity.getData(),
  38585. src = _entity$getData.src;
  38586. return react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("span", {
  38587. className: "braft-emoticon-in-editor"
  38588. }, react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("img", {
  38589. src: src
  38590. }), props.children);
  38591. },
  38592. importer: function importer(nodeName, node) {
  38593. if (nodeName.toLowerCase() === 'span' && node.classList && node.classList.contains('braft-emoticon-wrap')) {
  38594. var imgNode = node.querySelector('img');
  38595. var src = imgNode.getAttribute('src'); // 移除img节点以避免生成atomic block
  38596. node.removeChild(imgNode);
  38597. return {
  38598. mutability: 'IMMUTABLE',
  38599. data: {
  38600. src: src
  38601. }
  38602. };
  38603. }
  38604. },
  38605. exporter: function exporter(entityObject, initialText) {
  38606. var src = entityObject.data.src;
  38607. return react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("span", {
  38608. className: "braft-emoticon-wrap"
  38609. }, react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("img", {
  38610. src: src
  38611. }), initialText);
  38612. }
  38613. };
  38614. });
  38615. /***/ }),
  38616. /***/ 48:
  38617. /***/ (function(module, exports) {
  38618. // removed by extract-text-webpack-plugin
  38619. /***/ }),
  38620. /***/ 5:
  38621. /***/ (function(module, exports, __webpack_require__) {
  38622. var defineProperty = __webpack_require__(2);
  38623. function _objectSpread(target) {
  38624. for (var i = 1; i < arguments.length; i++) {
  38625. var source = arguments[i] != null ? arguments[i] : {};
  38626. var ownKeys = Object.keys(source);
  38627. if (typeof Object.getOwnPropertySymbols === 'function') {
  38628. ownKeys = ownKeys.concat(Object.getOwnPropertySymbols(source).filter(function (sym) {
  38629. return Object.getOwnPropertyDescriptor(source, sym).enumerable;
  38630. }));
  38631. }
  38632. ownKeys.forEach(function (key) {
  38633. defineProperty(target, key, source[key]);
  38634. });
  38635. }
  38636. return target;
  38637. }
  38638. module.exports = _objectSpread;
  38639. /***/ }),
  38640. /***/ 6:
  38641. /***/ (function(module, exports) {
  38642. module.exports = __WEBPACK_EXTERNAL_MODULE__6__;
  38643. /***/ })
  38644. /******/ });
  38645. });
  38646. });
  38647. var Emoticon = unwrapExports(emoticon);
  38648. var emoticon_1 = emoticon.defaultEmoticons;
  38649. var maxLength = createCommonjsModule(function (module, exports) {
  38650. (function webpackUniversalModuleDefinition(root, factory) {
  38651. module.exports = factory();
  38652. })(window, function() {
  38653. return /******/ (function(modules) { // webpackBootstrap
  38654. /******/ // The module cache
  38655. /******/ var installedModules = {};
  38656. /******/
  38657. /******/ // The require function
  38658. /******/ function __webpack_require__(moduleId) {
  38659. /******/
  38660. /******/ // Check if module is in cache
  38661. /******/ if(installedModules[moduleId]) {
  38662. /******/ return installedModules[moduleId].exports;
  38663. /******/ }
  38664. /******/ // Create a new module (and put it into the cache)
  38665. /******/ var module = installedModules[moduleId] = {
  38666. /******/ i: moduleId,
  38667. /******/ l: false,
  38668. /******/ exports: {}
  38669. /******/ };
  38670. /******/
  38671. /******/ // Execute the module function
  38672. /******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);
  38673. /******/
  38674. /******/ // Flag the module as loaded
  38675. /******/ module.l = true;
  38676. /******/
  38677. /******/ // Return the exports of the module
  38678. /******/ return module.exports;
  38679. /******/ }
  38680. /******/
  38681. /******/
  38682. /******/ // expose the modules object (__webpack_modules__)
  38683. /******/ __webpack_require__.m = modules;
  38684. /******/
  38685. /******/ // expose the module cache
  38686. /******/ __webpack_require__.c = installedModules;
  38687. /******/
  38688. /******/ // define getter function for harmony exports
  38689. /******/ __webpack_require__.d = function(exports, name, getter) {
  38690. /******/ if(!__webpack_require__.o(exports, name)) {
  38691. /******/ Object.defineProperty(exports, name, { enumerable: true, get: getter });
  38692. /******/ }
  38693. /******/ };
  38694. /******/
  38695. /******/ // define __esModule on exports
  38696. /******/ __webpack_require__.r = function(exports) {
  38697. /******/ if(typeof Symbol !== 'undefined' && Symbol.toStringTag) {
  38698. /******/ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
  38699. /******/ }
  38700. /******/ Object.defineProperty(exports, '__esModule', { value: true });
  38701. /******/ };
  38702. /******/
  38703. /******/ // create a fake namespace object
  38704. /******/ // mode & 1: value is a module id, require it
  38705. /******/ // mode & 2: merge all properties of value into the ns
  38706. /******/ // mode & 4: return value when already ns object
  38707. /******/ // mode & 8|1: behave like require
  38708. /******/ __webpack_require__.t = function(value, mode) {
  38709. /******/ if(mode & 1) value = __webpack_require__(value);
  38710. /******/ if(mode & 8) return value;
  38711. /******/ if((mode & 4) && typeof value === 'object' && value && value.__esModule) return value;
  38712. /******/ var ns = Object.create(null);
  38713. /******/ __webpack_require__.r(ns);
  38714. /******/ Object.defineProperty(ns, 'default', { enumerable: true, value: value });
  38715. /******/ if(mode & 2 && typeof value != 'string') for(var key in value) __webpack_require__.d(ns, key, function(key) { return value[key]; }.bind(null, key));
  38716. /******/ return ns;
  38717. /******/ };
  38718. /******/
  38719. /******/ // getDefaultExport function for compatibility with non-harmony modules
  38720. /******/ __webpack_require__.n = function(module) {
  38721. /******/ var getter = module && module.__esModule ?
  38722. /******/ function getDefault() { return module['default']; } :
  38723. /******/ function getModuleExports() { return module; };
  38724. /******/ __webpack_require__.d(getter, 'a', getter);
  38725. /******/ return getter;
  38726. /******/ };
  38727. /******/
  38728. /******/ // Object.prototype.hasOwnProperty.call
  38729. /******/ __webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); };
  38730. /******/
  38731. /******/ // __webpack_public_path__
  38732. /******/ __webpack_require__.p = "/";
  38733. /******/
  38734. /******/
  38735. /******/ // Load entry module and return exports
  38736. /******/ return __webpack_require__(__webpack_require__.s = 34);
  38737. /******/ })
  38738. /************************************************************************/
  38739. /******/ ({
  38740. /***/ 2:
  38741. /***/ (function(module, exports) {
  38742. function _defineProperty(obj, key, value) {
  38743. if (key in obj) {
  38744. Object.defineProperty(obj, key, {
  38745. value: value,
  38746. enumerable: true,
  38747. configurable: true,
  38748. writable: true
  38749. });
  38750. } else {
  38751. obj[key] = value;
  38752. }
  38753. return obj;
  38754. }
  38755. module.exports = _defineProperty;
  38756. /***/ }),
  38757. /***/ 34:
  38758. /***/ (function(module, __webpack_exports__, __webpack_require__) {
  38759. __webpack_require__.r(__webpack_exports__);
  38760. /* harmony import */ var _babel_runtime_helpers_objectSpread__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(5);
  38761. /* harmony import */ var _babel_runtime_helpers_objectSpread__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_objectSpread__WEBPACK_IMPORTED_MODULE_0__);
  38762. var getSelectedTextLength = function getSelectedTextLength(editorState) {
  38763. var currentSelection = editorState.getSelection();
  38764. var isCollapsed = currentSelection.isCollapsed();
  38765. var length = 0;
  38766. if (!isCollapsed) {
  38767. var currentContent = editorState.getCurrentContent();
  38768. var startKey = currentSelection.getStartKey();
  38769. var endKey = currentSelection.getEndKey();
  38770. var startBlock = currentContent.getBlockForKey(startKey);
  38771. var isStartAndEndBlockAreTheSame = startKey === endKey;
  38772. var startBlockTextLength = startBlock.getLength();
  38773. var startSelectedTextLength = startBlockTextLength - currentSelection.getStartOffset();
  38774. var endSelectedTextLength = currentSelection.getEndOffset();
  38775. var keyAfterEnd = currentContent.getKeyAfter(endKey);
  38776. if (isStartAndEndBlockAreTheSame) {
  38777. length += currentSelection.getEndOffset() - currentSelection.getStartOffset();
  38778. } else {
  38779. var currentKey = startKey;
  38780. while (currentKey && currentKey !== keyAfterEnd) {
  38781. if (currentKey === startKey) {
  38782. length += startSelectedTextLength + 1;
  38783. } else if (currentKey === endKey) {
  38784. length += endSelectedTextLength;
  38785. } else {
  38786. length += currentContent.getBlockForKey(currentKey).getLength() + 1;
  38787. }
  38788. currentKey = currentContent.getKeyAfter(currentKey);
  38789. }
  38790. }
  38791. }
  38792. return length;
  38793. };
  38794. /* harmony default export */ __webpack_exports__["default"] = (function (options) {
  38795. options = _babel_runtime_helpers_objectSpread__WEBPACK_IMPORTED_MODULE_0___default()({
  38796. defaultValue: Infinity
  38797. }, options);
  38798. var _options = options,
  38799. includeEditors = _options.includeEditors,
  38800. excludeEditors = _options.excludeEditors,
  38801. defaultValue = _options.defaultValue;
  38802. return {
  38803. type: 'prop-interception',
  38804. includeEditors: includeEditors,
  38805. excludeEditors: excludeEditors,
  38806. interceptor: function interceptor(editorProps) {
  38807. var maxLength = editorProps.maxLength || defaultValue;
  38808. editorProps.handleBeforeInput = function (_, editorState) {
  38809. if (maxLength === Infinity) {
  38810. return 'not-handled';
  38811. }
  38812. var currentContentLength = editorState.toText().length;
  38813. var selectedTextLength = getSelectedTextLength(editorState);
  38814. if (currentContentLength - selectedTextLength > maxLength - 1) {
  38815. editorProps.onReachMaxLength && editorProps.onReachMaxLength(maxLength);
  38816. return 'handled';
  38817. }
  38818. };
  38819. editorProps.handlePastedText = function (pastedText, _, editorState) {
  38820. if (maxLength === Infinity) {
  38821. return 'not-handled';
  38822. }
  38823. var currentContentLength = editorState.toText().length;
  38824. var selectedTextLength = getSelectedTextLength(editorState);
  38825. if (currentContentLength + pastedText.length - selectedTextLength > maxLength) {
  38826. editorProps.onReachMaxLength && editorProps.onReachMaxLength(maxLength);
  38827. return 'handled';
  38828. }
  38829. };
  38830. return editorProps;
  38831. }
  38832. };
  38833. });
  38834. /***/ }),
  38835. /***/ 5:
  38836. /***/ (function(module, exports, __webpack_require__) {
  38837. var defineProperty = __webpack_require__(2);
  38838. function _objectSpread(target) {
  38839. for (var i = 1; i < arguments.length; i++) {
  38840. var source = arguments[i] != null ? arguments[i] : {};
  38841. var ownKeys = Object.keys(source);
  38842. if (typeof Object.getOwnPropertySymbols === 'function') {
  38843. ownKeys = ownKeys.concat(Object.getOwnPropertySymbols(source).filter(function (sym) {
  38844. return Object.getOwnPropertyDescriptor(source, sym).enumerable;
  38845. }));
  38846. }
  38847. ownKeys.forEach(function (key) {
  38848. defineProperty(target, key, source[key]);
  38849. });
  38850. }
  38851. return target;
  38852. }
  38853. module.exports = _objectSpread;
  38854. /***/ })
  38855. /******/ });
  38856. });
  38857. });
  38858. var MaxLength = unwrapExports(maxLength);
  38859. var lengthOptions = {
  38860. defaultValue: 100 // 指定默认限制数,如不指定则为Infinity(无限)
  38861. // includeEditors: ['editor-id-1'], // 指定该模块对哪些BraftEditor生效,不传此属性则对所有BraftEditor有效
  38862. // excludeEditors: ['editor-id-2'], // 指定该模块对哪些BraftEditor无效
  38863. };
  38864. BraftEditor.use(MaxLength(lengthOptions)); // 转换默认表情包列表,让webpack可以正确加载到默认表情包中的图片,请确保已对png格式的文件配置了loader
  38865. // 如果你使用的webpack版本不支持动态require,或者使用的其他打包工具,请勿使用此写法
  38866. var emoticons = emoticon_1.map(function (item) {
  38867. return require("braft-extensions/dist/assets/".concat(item));
  38868. }); // 也可以使用自己的表情包资源,不受打包工具限制
  38869. // const emoticons = ['http://path/to/emoticon-1.png', 'http://path/to/emoticon-2.png', 'http://path/to/emoticon-3.png', 'http://path/to/emoticon-4.png', ...]
  38870. var emotionOptions = {
  38871. // includeEditors: ['editor-id-1'], // 指定该模块对哪些BraftEditor生效,不传此属性则对所有BraftEditor有效
  38872. // excludeEditors: ['editor-id-2'], // 指定该模块对哪些BraftEditor无效
  38873. emoticons: emoticons,
  38874. // 指定可用表情图片列表,默认为空
  38875. closeOnBlur: true,
  38876. // 指定是否在点击表情选择器之外的地方时关闭表情选择器,默认false
  38877. closeOnSelect: false // 指定是否在选择表情后关闭表情选择器,默认false
  38878. };
  38879. BraftEditor.use(Emoticon(emotionOptions));
  38880. var BarftEditorPage = function BarftEditorPage() {
  38881. var controls = ["bold", "italic", "underline", "separator", "link", "emoji", "separator", "media"];
  38882. var _useState = useState(BraftEditor.createEditorState("<p>Hello <b>World!</b></p>")),
  38883. _useState2 = _slicedToArray(_useState, 2),
  38884. editorState = _useState2[0],
  38885. setEditorState = _useState2[1];
  38886. return React.createElement("div", {
  38887. className: "editor-wrapper"
  38888. }, React.createElement(BraftEditor, {
  38889. value: editorState,
  38890. onChange: setEditorState,
  38891. controls: controls,
  38892. contentStyle: {
  38893. height: 210,
  38894. boxShadow: "inset 0 1px 3px rgba(0,0,0,.1)"
  38895. }
  38896. }));
  38897. };
  38898. var css$2 = ".RichTextEditor_wrapper__3X3Yv .RichTextEditor_btnListWrapper__vUaki {\n display: flex;\n}\n.RichTextEditor_wrapper__3X3Yv .RichTextEditor_editorWrapper__3UFgF {\n border: 1px solid #ccc;\n}\n";
  38899. var styles = {"wrapper":"RichTextEditor_wrapper__3X3Yv","btnListWrapper":"RichTextEditor_btnListWrapper__vUaki","editorWrapper":"RichTextEditor_editorWrapper__3UFgF"};
  38900. styleInject(css$2);
  38901. // 自定义组件,用于超链接
  38902. var Link = function Link(props) {
  38903. // 这里通过contentState来获取entity�,之后通过getData获取entity中包含的数据
  38904. var _props$contentState$g = props.contentState.getEntity(props.entityKey).getData(),
  38905. url = _props$contentState$g.url;
  38906. return React.createElement("a", {
  38907. href: url
  38908. }, props.children);
  38909. }; // decorator,用于超链接
  38910. var decorator = new Draft_4([{
  38911. strategy: function strategy(contentBlock, callback, contentState) {
  38912. // 这个方法接收2个函数作为参数,如果第一个参数的函数执行时�返回true,就会执行第二个参数函数,同时会�将匹配的�字符的起始位置和结束位置传递给第二个参数。
  38913. contentBlock.findEntityRanges(function (character) {
  38914. var entityKey = character.getEntity();
  38915. return entityKey !== null && contentState.getEntity(entityKey).getType() === 'LINK';
  38916. }, function () {
  38917. callback.apply(void 0, arguments);
  38918. });
  38919. },
  38920. component: Link
  38921. }, {
  38922. strategy: function strategy(contentBlock, callback, contentState) {
  38923. contentBlock.findEntityRanges(function (character) {
  38924. var entityKey = character.getEntity();
  38925. return entityKey !== null && contentState.getEntity(entityKey).getType() === 'EMOJI';
  38926. }, function () {
  38927. callback.apply(void 0, arguments);
  38928. });
  38929. },
  38930. // component: (props: any) => (<span style={{ color: 'red' }}>[Emoji]</span>)
  38931. component: function component(props) {
  38932. return React.createElement("i", {
  38933. style: {
  38934. display: 'inline-block',
  38935. height: '18px',
  38936. width: '18px',
  38937. backgroundImage: "url(https://i.pinimg.com/originals/03/7e/79/037e79b2fb52127537be79110891ae3f.png)",
  38938. backgroundSize: '100% 100%',
  38939. color: 'transparent'
  38940. }
  38941. }, "e");
  38942. }
  38943. }]);
  38944. var RichTextEditor =
  38945. /*#__PURE__*/
  38946. function (_React$Component) {
  38947. _inherits$c(RichTextEditor, _React$Component);
  38948. function RichTextEditor(props) {
  38949. var _this;
  38950. _classCallCheck$h(this, RichTextEditor);
  38951. _this = _possibleConstructorReturn$c(this, _getPrototypeOf(RichTextEditor).call(this, props));
  38952. _defineProperty$1(_assertThisInitialized(_this), "onChange", void 0);
  38953. _this.state = {
  38954. editorState: Draft_3.createEmpty(decorator)
  38955. };
  38956. _this.onChange = function (editorState) {
  38957. return _this.setState({
  38958. editorState: editorState
  38959. });
  38960. };
  38961. _this.handleKeyCommand = _this.handleKeyCommand.bind(_assertThisInitialized(_this));
  38962. _this.defaultBlockStyleFn = _this.defaultBlockStyleFn.bind(_assertThisInitialized(_this));
  38963. return _this;
  38964. }
  38965. _createClass(RichTextEditor, [{
  38966. key: "handleKeyCommand",
  38967. value: function handleKeyCommand(command, editorState) {
  38968. var newState = Draft_15.handleKeyCommand(editorState, command);
  38969. console.log('command: ', command);
  38970. console.log('newState: ', newState);
  38971. if (newState) {
  38972. this.onChange(newState);
  38973. return "handled";
  38974. }
  38975. switch (command) {
  38976. case 'backspace':
  38977. var contentState = editorState.getCurrentContent();
  38978. var selectionState = editorState.getSelection();
  38979. var _ref = [selectionState.getStartOffset(), selectionState.getEndOffset()],
  38980. startOffset = _ref[0],
  38981. endOffset = _ref[1];
  38982. if (startOffset === endOffset) {
  38983. // 未选中状态
  38984. console.log(selectionState.getAnchorKey());
  38985. } // 选中状态
  38986. break;
  38987. }
  38988. return "not-handled";
  38989. }
  38990. }, {
  38991. key: "_onBoldClick",
  38992. value: function _onBoldClick() {
  38993. this.onChange(Draft_15.toggleInlineStyle(this.state.editorState, 'BOLD'));
  38994. }
  38995. }, {
  38996. key: "_onLinkClick",
  38997. value: function _onLinkClick() {
  38998. var editorState = this.state.editorState;
  38999. var contentState = editorState.getCurrentContent();
  39000. var selectionState = editorState.getSelection();
  39001. var contentStateWithEntity = contentState.createEntity('LINK', 'MUTABLE', {
  39002. url: 'http://www.zombo.com'
  39003. });
  39004. var entityKey = contentStateWithEntity.getLastCreatedEntityKey();
  39005. var contentStateWithLink = Draft_14.applyEntity(contentStateWithEntity, selectionState, entityKey);
  39006. var newEditorState = Draft_3.push(editorState, contentStateWithLink, 'apply-entity');
  39007. this.onChange(newEditorState);
  39008. }
  39009. }, {
  39010. key: "_onEmojiClick",
  39011. value: function _onEmojiClick(e, emojiCode) {
  39012. var editorState = this.state.editorState;
  39013. var contentState = editorState.getCurrentContent();
  39014. var selectionState = editorState.getSelection();
  39015. var EMOJIEntity = contentState.createEntity('EMOJI', 'IMMUTABLE', {
  39016. emojiCode: emojiCode
  39017. });
  39018. var entityKey = EMOJIEntity.getLastCreatedEntityKey();
  39019. var ncsWithEntity = Draft_14.insertText(contentState, selectionState, 'e', undefined, entityKey);
  39020. var newEditorState = Draft_3.push(editorState, ncsWithEntity, 'insert-characters'); // const newEditorState = AtomicBlockUtils.insertAtomicBlock(
  39021. // editorState,
  39022. // entityKey,
  39023. // ' '
  39024. // );
  39025. this.onChange(newEditorState);
  39026. }
  39027. }, {
  39028. key: "_onCheckRange",
  39029. value: function _onCheckRange() {
  39030. console.log(this.state.editorState.getCurrentContent());
  39031. console.log(Draft_20(this.state.editorState.getCurrentContent()));
  39032. }
  39033. }, {
  39034. key: "defaultBlockStyleFn",
  39035. value: function defaultBlockStyleFn(contentBlock) {
  39036. var type = contentBlock.getType();
  39037. return "";
  39038. }
  39039. }, {
  39040. key: "defaultBlockRenderFn",
  39041. value: function defaultBlockRenderFn(contentBlock) {
  39042. var type = contentBlock.getType();
  39043. return contentBlock;
  39044. }
  39045. }, {
  39046. key: "render",
  39047. value: function render() {
  39048. var _this2 = this;
  39049. var editorState = this.state.editorState;
  39050. return React.createElement("div", {
  39051. className: styles.wrapper
  39052. }, React.createElement("div", {
  39053. className: styles.btnListWrapper
  39054. }, React.createElement("button", {
  39055. onClick: this._onBoldClick.bind(this)
  39056. }, "Bold"), React.createElement("button", {
  39057. onClick: this._onCheckRange.bind(this)
  39058. }, "Check"), React.createElement("button", {
  39059. onClick: this._onLinkClick.bind(this)
  39060. }, "Link"), React.createElement("button", {
  39061. onClick: function onClick(e) {
  39062. return _this2._onEmojiClick(e, '0011');
  39063. }
  39064. }, "Emoji")), React.createElement("div", {
  39065. className: styles.editorWrapper
  39066. }, React.createElement(Draft_1, {
  39067. editorState: editorState,
  39068. blockStyleFn: this.defaultBlockStyleFn,
  39069. blockRendererFn: this.defaultBlockRenderFn,
  39070. handleKeyCommand: this.handleKeyCommand,
  39071. onChange: this.onChange
  39072. })));
  39073. }
  39074. }]);
  39075. return RichTextEditor;
  39076. }(React.Component);
  39077. /*!
  39078. * isobject <https://github.com/jonschlinkert/isobject>
  39079. *
  39080. * Copyright (c) 2014-2017, Jon Schlinkert.
  39081. * Released under the MIT License.
  39082. */
  39083. function isObject(val) {
  39084. return val != null && typeof val === 'object' && Array.isArray(val) === false;
  39085. }
  39086. /*!
  39087. * is-plain-object <https://github.com/jonschlinkert/is-plain-object>
  39088. *
  39089. * Copyright (c) 2014-2017, Jon Schlinkert.
  39090. * Released under the MIT License.
  39091. */
  39092. function isObjectObject(o) {
  39093. return isObject(o) === true
  39094. && Object.prototype.toString.call(o) === '[object Object]';
  39095. }
  39096. function isPlainObject(o) {
  39097. var ctor,prot;
  39098. if (isObjectObject(o) === false) return false;
  39099. // If has modified constructor
  39100. ctor = o.constructor;
  39101. if (typeof ctor !== 'function') return false;
  39102. // If has modified prototype
  39103. prot = ctor.prototype;
  39104. if (isObjectObject(prot) === false) return false;
  39105. // If constructor does not have an Object-specific method
  39106. if (prot.hasOwnProperty('isPrototypeOf') === false) {
  39107. return false;
  39108. }
  39109. // Most likely a plain Object
  39110. return true;
  39111. }
  39112. var index_cjs = isPlainObject;
  39113. var immer_1 = createCommonjsModule(function (module, exports) {
  39114. Object.defineProperty(exports, '__esModule', { value: true });
  39115. // Should be no imports here!
  39116. var _a; // SOme things that should be evaluated before all else...
  39117. var hasSymbol = typeof Symbol !== "undefined";
  39118. var hasMap = typeof Map !== "undefined";
  39119. var hasSet = typeof Set !== "undefined";
  39120. /**
  39121. * The sentinel value returned by producers to replace the draft with undefined.
  39122. */
  39123. var NOTHING = hasSymbol ? Symbol("immer-nothing") : (_a = {}, _a["immer-nothing"] = true, _a);
  39124. /**
  39125. * To let Immer treat your class instances as plain immutable objects
  39126. * (albeit with a custom prototype), you must define either an instance property
  39127. * or a static property on each of your custom classes.
  39128. *
  39129. * Otherwise, your class instance will never be drafted, which means it won't be
  39130. * safe to mutate in a produce callback.
  39131. */
  39132. var DRAFTABLE = hasSymbol ? Symbol("immer-draftable") : "__$immer_draftable";
  39133. var DRAFT_STATE = hasSymbol ? Symbol("immer-state") : "__$immer_state";
  39134. var iteratorSymbol = hasSymbol ? Symbol.iterator : "@@iterator";
  39135. /* istanbul ignore next */
  39136. var extendStatics = function (d, b) {
  39137. extendStatics = Object.setPrototypeOf || {
  39138. __proto__: []
  39139. } instanceof Array && function (d, b) {
  39140. d.__proto__ = b;
  39141. } || function (d, b) {
  39142. for (var p in b) { if (b.hasOwnProperty(p)) { d[p] = b[p]; } }
  39143. };
  39144. return extendStatics(d, b);
  39145. }; // Ugly hack to resolve #502 and inherit built in Map / Set
  39146. function __extends(d, b) {
  39147. extendStatics(d, b);
  39148. function __() {
  39149. this.constructor = d;
  39150. }
  39151. d.prototype = ( // @ts-ignore
  39152. __.prototype = b.prototype, new __());
  39153. }
  39154. var Archtype;
  39155. (function (Archtype) {
  39156. Archtype[Archtype["Object"] = 0] = "Object";
  39157. Archtype[Archtype["Array"] = 1] = "Array";
  39158. Archtype[Archtype["Map"] = 2] = "Map";
  39159. Archtype[Archtype["Set"] = 3] = "Set";
  39160. })(Archtype || (Archtype = {}));
  39161. var ProxyType;
  39162. (function (ProxyType) {
  39163. ProxyType[ProxyType["ProxyObject"] = 0] = "ProxyObject";
  39164. ProxyType[ProxyType["ProxyArray"] = 1] = "ProxyArray";
  39165. ProxyType[ProxyType["ES5Object"] = 2] = "ES5Object";
  39166. ProxyType[ProxyType["ES5Array"] = 3] = "ES5Array";
  39167. ProxyType[ProxyType["Map"] = 4] = "Map";
  39168. ProxyType[ProxyType["Set"] = 5] = "Set";
  39169. })(ProxyType || (ProxyType = {}));
  39170. /** Returns true if the given value is an Immer draft */
  39171. function isDraft(value) {
  39172. return !!value && !!value[DRAFT_STATE];
  39173. }
  39174. /** Returns true if the given value can be drafted by Immer */
  39175. function isDraftable(value) {
  39176. if (!value) { return false; }
  39177. return isPlainObject(value) || Array.isArray(value) || !!value[DRAFTABLE] || !!value.constructor[DRAFTABLE] || isMap(value) || isSet(value);
  39178. }
  39179. function isPlainObject(value) {
  39180. if (!value || typeof value !== "object") { return false; }
  39181. var proto = Object.getPrototypeOf(value);
  39182. return !proto || proto === Object.prototype;
  39183. }
  39184. function original(value) {
  39185. if (value && value[DRAFT_STATE]) {
  39186. return value[DRAFT_STATE].base;
  39187. } // otherwise return undefined
  39188. }
  39189. var ownKeys = typeof Reflect !== "undefined" && Reflect.ownKeys ? Reflect.ownKeys : typeof Object.getOwnPropertySymbols !== "undefined" ? function (obj) {
  39190. return Object.getOwnPropertyNames(obj).concat(Object.getOwnPropertySymbols(obj));
  39191. } :
  39192. /* istanbul ignore next */
  39193. Object.getOwnPropertyNames;
  39194. function each(obj, iter) {
  39195. if (getArchtype(obj) === Archtype.Object) {
  39196. ownKeys(obj).forEach(function (key) {
  39197. return iter(key, obj[key], obj);
  39198. });
  39199. } else {
  39200. obj.forEach(function (entry, index) {
  39201. return iter(index, entry, obj);
  39202. });
  39203. }
  39204. }
  39205. function isEnumerable(base, prop) {
  39206. var desc = Object.getOwnPropertyDescriptor(base, prop);
  39207. return desc && desc.enumerable ? true : false;
  39208. }
  39209. function getArchtype(thing) {
  39210. /* istanbul ignore next */
  39211. if (!thing) { die(); }
  39212. if (thing[DRAFT_STATE]) {
  39213. switch (thing[DRAFT_STATE].type) {
  39214. case ProxyType.ES5Object:
  39215. case ProxyType.ProxyObject:
  39216. return Archtype.Object;
  39217. case ProxyType.ES5Array:
  39218. case ProxyType.ProxyArray:
  39219. return Archtype.Array;
  39220. case ProxyType.Map:
  39221. return Archtype.Map;
  39222. case ProxyType.Set:
  39223. return Archtype.Set;
  39224. }
  39225. }
  39226. return Array.isArray(thing) ? Archtype.Array : isMap(thing) ? Archtype.Map : isSet(thing) ? Archtype.Set : Archtype.Object;
  39227. }
  39228. function has(thing, prop) {
  39229. return getArchtype(thing) === Archtype.Map ? thing.has(prop) : Object.prototype.hasOwnProperty.call(thing, prop);
  39230. }
  39231. function get(thing, prop) {
  39232. // @ts-ignore
  39233. return getArchtype(thing) === Archtype.Map ? thing.get(prop) : thing[prop];
  39234. }
  39235. function set(thing, propOrOldValue, value) {
  39236. switch (getArchtype(thing)) {
  39237. case Archtype.Map:
  39238. thing.set(propOrOldValue, value);
  39239. break;
  39240. case Archtype.Set:
  39241. thing.delete(propOrOldValue);
  39242. thing.add(value);
  39243. break;
  39244. default:
  39245. thing[propOrOldValue] = value;
  39246. }
  39247. }
  39248. function is(x, y) {
  39249. // From: https://github.com/facebook/fbjs/blob/c69904a511b900266935168223063dd8772dfc40/packages/fbjs/src/core/shallowEqual.js
  39250. if (x === y) {
  39251. return x !== 0 || 1 / x === 1 / y;
  39252. } else {
  39253. return x !== x && y !== y;
  39254. }
  39255. }
  39256. function isMap(target) {
  39257. return hasMap && target instanceof Map;
  39258. }
  39259. function isSet(target) {
  39260. return hasSet && target instanceof Set;
  39261. }
  39262. function latest(state) {
  39263. return state.copy || state.base;
  39264. }
  39265. function shallowCopy(base, invokeGetters) {
  39266. if (invokeGetters === void 0) {
  39267. invokeGetters = false;
  39268. }
  39269. if (Array.isArray(base)) { return base.slice(); }
  39270. var clone = Object.create(Object.getPrototypeOf(base));
  39271. ownKeys(base).forEach(function (key) {
  39272. if (key === DRAFT_STATE) {
  39273. return; // Never copy over draft state.
  39274. }
  39275. var desc = Object.getOwnPropertyDescriptor(base, key);
  39276. var value = desc.value;
  39277. if (desc.get) {
  39278. if (!invokeGetters) {
  39279. throw new Error("Immer drafts cannot have computed properties");
  39280. }
  39281. value = desc.get.call(base);
  39282. }
  39283. if (desc.enumerable) {
  39284. clone[key] = value;
  39285. } else {
  39286. Object.defineProperty(clone, key, {
  39287. value: value,
  39288. writable: true,
  39289. configurable: true
  39290. });
  39291. }
  39292. });
  39293. return clone;
  39294. }
  39295. function freeze(obj, deep) {
  39296. if (!isDraftable(obj) || isDraft(obj) || Object.isFrozen(obj)) { return; }
  39297. var type = getArchtype(obj);
  39298. if (type === Archtype.Set) {
  39299. obj.add = obj.clear = obj.delete = dontMutateFrozenCollections;
  39300. } else if (type === Archtype.Map) {
  39301. obj.set = obj.clear = obj.delete = dontMutateFrozenCollections;
  39302. }
  39303. Object.freeze(obj);
  39304. if (deep) { each(obj, function (_, value) {
  39305. return freeze(value, true);
  39306. }); }
  39307. }
  39308. function dontMutateFrozenCollections() {
  39309. throw new Error("This object has been frozen and should not be mutated");
  39310. }
  39311. function createHiddenProperty(target, prop, value) {
  39312. Object.defineProperty(target, prop, {
  39313. value: value,
  39314. enumerable: false,
  39315. writable: true
  39316. });
  39317. }
  39318. /* istanbul ignore next */
  39319. function die() {
  39320. throw new Error("Illegal state, please file a bug");
  39321. }
  39322. /** Each scope represents a `produce` call. */
  39323. var ImmerScope =
  39324. /** @class */
  39325. function () {
  39326. function ImmerScope(parent, immer) {
  39327. this.drafts = [];
  39328. this.parent = parent;
  39329. this.immer = immer; // Whenever the modified draft contains a draft from another scope, we
  39330. // need to prevent auto-freezing so the unowned draft can be finalized.
  39331. this.canAutoFreeze = true;
  39332. }
  39333. ImmerScope.prototype.usePatches = function (patchListener) {
  39334. if (patchListener) {
  39335. this.patches = [];
  39336. this.inversePatches = [];
  39337. this.patchListener = patchListener;
  39338. }
  39339. };
  39340. ImmerScope.prototype.revoke = function () {
  39341. this.leave();
  39342. this.drafts.forEach(revoke); // @ts-ignore
  39343. this.drafts = null;
  39344. };
  39345. ImmerScope.prototype.leave = function () {
  39346. if (this === ImmerScope.current) {
  39347. ImmerScope.current = this.parent;
  39348. }
  39349. };
  39350. ImmerScope.enter = function (immer) {
  39351. var scope = new ImmerScope(ImmerScope.current, immer);
  39352. ImmerScope.current = scope;
  39353. return scope;
  39354. };
  39355. return ImmerScope;
  39356. }();
  39357. function revoke(draft) {
  39358. var state = draft[DRAFT_STATE];
  39359. if (state.type === ProxyType.ProxyObject || state.type === ProxyType.ProxyArray) { state.revoke(); }else { state.revoked = true; }
  39360. }
  39361. function processResult(immer, result, scope) {
  39362. var baseDraft = scope.drafts[0];
  39363. var isReplaced = result !== undefined && result !== baseDraft;
  39364. immer.willFinalize(scope, result, isReplaced);
  39365. if (isReplaced) {
  39366. if (baseDraft[DRAFT_STATE].modified) {
  39367. scope.revoke();
  39368. 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
  39369. }
  39370. if (isDraftable(result)) {
  39371. // Finalize the result in case it contains (or is) a subset of the draft.
  39372. result = finalize(immer, result, scope);
  39373. maybeFreeze(immer, result);
  39374. }
  39375. if (scope.patches) {
  39376. scope.patches.push({
  39377. op: "replace",
  39378. path: [],
  39379. value: result
  39380. });
  39381. scope.inversePatches.push({
  39382. op: "replace",
  39383. path: [],
  39384. value: baseDraft[DRAFT_STATE].base
  39385. });
  39386. }
  39387. } else {
  39388. // Finalize the base draft.
  39389. result = finalize(immer, baseDraft, scope, []);
  39390. }
  39391. scope.revoke();
  39392. if (scope.patches) {
  39393. scope.patchListener(scope.patches, scope.inversePatches);
  39394. }
  39395. return result !== NOTHING ? result : undefined;
  39396. }
  39397. function finalize(immer, draft, scope, path) {
  39398. var state = draft[DRAFT_STATE];
  39399. if (!state) {
  39400. if (Object.isFrozen(draft)) { return draft; }
  39401. return finalizeTree(immer, draft, scope);
  39402. } // Never finalize drafts owned by another scope.
  39403. if (state.scope !== scope) {
  39404. return draft;
  39405. }
  39406. if (!state.modified) {
  39407. maybeFreeze(immer, state.base, true);
  39408. return state.base;
  39409. }
  39410. if (!state.finalized) {
  39411. state.finalized = true;
  39412. finalizeTree(immer, state.draft, scope, path); // We cannot really delete anything inside of a Set. We can only replace the whole Set.
  39413. if (immer.onDelete && state.type !== ProxyType.Set) {
  39414. // The `assigned` object is unreliable with ES5 drafts.
  39415. if (immer.useProxies) {
  39416. var assigned = state.assigned;
  39417. each(assigned, function (prop, exists) {
  39418. if (!exists) { immer.onDelete(state, prop); }
  39419. });
  39420. } else {
  39421. var base = state.base,
  39422. copy_1 = state.copy;
  39423. each(base, function (prop) {
  39424. if (!has(copy_1, prop)) { immer.onDelete(state, prop); }
  39425. });
  39426. }
  39427. }
  39428. if (immer.onCopy) {
  39429. immer.onCopy(state);
  39430. } // At this point, all descendants of `state.copy` have been finalized,
  39431. // so we can be sure that `scope.canAutoFreeze` is accurate.
  39432. if (immer.autoFreeze && scope.canAutoFreeze) {
  39433. freeze(state.copy, false);
  39434. }
  39435. if (path && scope.patches) {
  39436. generatePatches(state, path, scope.patches, scope.inversePatches);
  39437. }
  39438. }
  39439. return state.copy;
  39440. }
  39441. function finalizeTree(immer, root, scope, rootPath) {
  39442. var state = root[DRAFT_STATE];
  39443. if (state) {
  39444. if (state.type === ProxyType.ES5Object || state.type === ProxyType.ES5Array) {
  39445. // Create the final copy, with added keys and without deleted keys.
  39446. state.copy = shallowCopy(state.draft, true);
  39447. }
  39448. root = state.copy;
  39449. }
  39450. each(root, function (key, value) {
  39451. return finalizeProperty(immer, scope, root, state, root, key, value, rootPath);
  39452. });
  39453. return root;
  39454. }
  39455. function finalizeProperty(immer, scope, root, rootState, parentValue, prop, childValue, rootPath) {
  39456. if (childValue === parentValue) {
  39457. throw Error("Immer forbids circular references");
  39458. } // In the `finalizeTree` method, only the `root` object may be a draft.
  39459. var isDraftProp = !!rootState && parentValue === root;
  39460. var isSetMember = isSet(parentValue);
  39461. if (isDraft(childValue)) {
  39462. var path = rootPath && isDraftProp && !isSetMember && // Set objects are atomic since they have no keys.
  39463. !has(rootState.assigned, prop) // Skip deep patches for assigned keys.
  39464. ? rootPath.concat(prop) : undefined; // Drafts owned by `scope` are finalized here.
  39465. childValue = finalize(immer, childValue, scope, path);
  39466. set(parentValue, prop, childValue); // Drafts from another scope must prevent auto-freezing.
  39467. if (isDraft(childValue)) {
  39468. scope.canAutoFreeze = false;
  39469. }
  39470. } // Unchanged draft properties are ignored.
  39471. else if (isDraftProp && is(childValue, get(rootState.base, prop))) {
  39472. return;
  39473. } // Search new objects for unfinalized drafts. Frozen objects should never contain drafts.
  39474. // TODO: the recursion over here looks weird, shouldn't non-draft stuff have it's own recursion?
  39475. // especially the passing on of root and rootState doesn't make sense...
  39476. else if (isDraftable(childValue) && !Object.isFrozen(childValue)) {
  39477. each(childValue, function (key, grandChild) {
  39478. return finalizeProperty(immer, scope, root, rootState, childValue, key, grandChild, rootPath);
  39479. });
  39480. maybeFreeze(immer, childValue);
  39481. }
  39482. if (isDraftProp && immer.onAssign && !isSetMember) {
  39483. immer.onAssign(rootState, prop, childValue);
  39484. }
  39485. }
  39486. function maybeFreeze(immer, value, deep) {
  39487. if (deep === void 0) {
  39488. deep = false;
  39489. }
  39490. if (immer.autoFreeze && !isDraft(value)) {
  39491. freeze(value, deep);
  39492. }
  39493. }
  39494. /**
  39495. * Returns a new draft of the `base` object.
  39496. *
  39497. * The second argument is the parent draft-state (used internally).
  39498. */
  39499. function createProxy(base, parent) {
  39500. var isArray = Array.isArray(base);
  39501. var state = {
  39502. type: isArray ? ProxyType.ProxyArray : ProxyType.ProxyObject,
  39503. // Track which produce call this is associated with.
  39504. scope: parent ? parent.scope : ImmerScope.current,
  39505. // True for both shallow and deep changes.
  39506. modified: false,
  39507. // Used during finalization.
  39508. finalized: false,
  39509. // Track which properties have been assigned (true) or deleted (false).
  39510. assigned: {},
  39511. // The parent draft state.
  39512. parent: parent,
  39513. // The base state.
  39514. base: base,
  39515. // The base proxy.
  39516. draft: null,
  39517. // Any property proxies.
  39518. drafts: {},
  39519. // The base copy with any updated values.
  39520. copy: null,
  39521. // Called by the `produce` function.
  39522. revoke: null,
  39523. isManual: false
  39524. }; // the traps must target something, a bit like the 'real' base.
  39525. // but also, we need to be able to determine from the target what the relevant state is
  39526. // (to avoid creating traps per instance to capture the state in closure,
  39527. // and to avoid creating weird hidden properties as well)
  39528. // So the trick is to use 'state' as the actual 'target'! (and make sure we intercept everything)
  39529. // Note that in the case of an array, we put the state in an array to have better Reflect defaults ootb
  39530. var target = state;
  39531. var traps = objectTraps;
  39532. if (isArray) {
  39533. target = [state];
  39534. traps = arrayTraps;
  39535. } // TODO: optimization: might be faster, cheaper if we created a non-revocable proxy
  39536. // and administrate revoking ourselves
  39537. var _a = Proxy.revocable(target, traps),
  39538. revoke = _a.revoke,
  39539. proxy = _a.proxy;
  39540. state.draft = proxy;
  39541. state.revoke = revoke;
  39542. return proxy;
  39543. }
  39544. /**
  39545. * Object drafts
  39546. */
  39547. var objectTraps = {
  39548. get: function (state, prop) {
  39549. if (prop === DRAFT_STATE) { return state; }
  39550. var drafts = state.drafts; // Check for existing draft in unmodified state.
  39551. if (!state.modified && has(drafts, prop)) {
  39552. return drafts[prop];
  39553. }
  39554. var value = latest(state)[prop];
  39555. if (state.finalized || !isDraftable(value)) {
  39556. return value;
  39557. } // Check for existing draft in modified state.
  39558. if (state.modified) {
  39559. // Assigned values are never drafted. This catches any drafts we created, too.
  39560. if (value !== peek(state.base, prop)) { return value; } // Store drafts on the copy (when one exists).
  39561. // @ts-ignore
  39562. drafts = state.copy;
  39563. }
  39564. return drafts[prop] = state.scope.immer.createProxy(value, state);
  39565. },
  39566. has: function (state, prop) {
  39567. return prop in latest(state);
  39568. },
  39569. ownKeys: function (state) {
  39570. return Reflect.ownKeys(latest(state));
  39571. },
  39572. set: function (state, prop
  39573. /* strictly not, but helps TS */
  39574. , value) {
  39575. if (!state.modified) {
  39576. var baseValue = peek(state.base, prop); // Optimize based on value's truthiness. Truthy values are guaranteed to
  39577. // never be undefined, so we can avoid the `in` operator. Lastly, truthy
  39578. // values may be drafts, but falsy values are never drafts.
  39579. var isUnchanged = value ? is(baseValue, value) || value === state.drafts[prop] : is(baseValue, value) && prop in state.base;
  39580. if (isUnchanged) { return true; }
  39581. prepareCopy(state);
  39582. markChanged(state);
  39583. }
  39584. state.assigned[prop] = true; // @ts-ignore
  39585. state.copy[prop] = value;
  39586. return true;
  39587. },
  39588. deleteProperty: function (state, prop) {
  39589. // The `undefined` check is a fast path for pre-existing keys.
  39590. if (peek(state.base, prop) !== undefined || prop in state.base) {
  39591. state.assigned[prop] = false;
  39592. prepareCopy(state);
  39593. markChanged(state);
  39594. } else if (state.assigned[prop]) {
  39595. // if an originally not assigned property was deleted
  39596. delete state.assigned[prop];
  39597. } // @ts-ignore
  39598. if (state.copy) { delete state.copy[prop]; }
  39599. return true;
  39600. },
  39601. // Note: We never coerce `desc.value` into an Immer draft, because we can't make
  39602. // the same guarantee in ES5 mode.
  39603. getOwnPropertyDescriptor: function (state, prop) {
  39604. var owner = latest(state);
  39605. var desc = Reflect.getOwnPropertyDescriptor(owner, prop);
  39606. if (desc) {
  39607. desc.writable = true;
  39608. desc.configurable = state.type !== ProxyType.ProxyArray || prop !== "length";
  39609. }
  39610. return desc;
  39611. },
  39612. defineProperty: function () {
  39613. throw new Error("Object.defineProperty() cannot be used on an Immer draft"); // prettier-ignore
  39614. },
  39615. getPrototypeOf: function (state) {
  39616. return Object.getPrototypeOf(state.base);
  39617. },
  39618. setPrototypeOf: function () {
  39619. throw new Error("Object.setPrototypeOf() cannot be used on an Immer draft"); // prettier-ignore
  39620. }
  39621. };
  39622. /**
  39623. * Array drafts
  39624. */
  39625. var arrayTraps = {};
  39626. each(objectTraps, function (key, fn) {
  39627. // @ts-ignore
  39628. arrayTraps[key] = function () {
  39629. arguments[0] = arguments[0][0];
  39630. return fn.apply(this, arguments);
  39631. };
  39632. });
  39633. arrayTraps.deleteProperty = function (state, prop) {
  39634. if (isNaN(parseInt(prop))) {
  39635. throw new Error("Immer only supports deleting array indices"); // prettier-ignore
  39636. }
  39637. return objectTraps.deleteProperty.call(this, state[0], prop);
  39638. };
  39639. arrayTraps.set = function (state, prop, value) {
  39640. if (prop !== "length" && isNaN(parseInt(prop))) {
  39641. throw new Error("Immer only supports setting array indices and the 'length' property"); // prettier-ignore
  39642. }
  39643. return objectTraps.set.call(this, state[0], prop, value, state[0]);
  39644. };
  39645. /**
  39646. * Map drafts
  39647. */
  39648. // Access a property without creating an Immer draft.
  39649. function peek(draft, prop) {
  39650. var state = draft[DRAFT_STATE];
  39651. var desc = Reflect.getOwnPropertyDescriptor(state ? latest(state) : draft, prop);
  39652. return desc && desc.value;
  39653. }
  39654. function markChanged(state) {
  39655. if (!state.modified) {
  39656. state.modified = true;
  39657. if (state.type === ProxyType.ProxyObject || state.type === ProxyType.ProxyArray) {
  39658. var copy_1 = state.copy = shallowCopy(state.base);
  39659. each(state.drafts, function (key, value) {
  39660. // @ts-ignore
  39661. copy_1[key] = value;
  39662. });
  39663. state.drafts = undefined;
  39664. }
  39665. if (state.parent) {
  39666. markChanged(state.parent);
  39667. }
  39668. }
  39669. }
  39670. function prepareCopy(state) {
  39671. if (!state.copy) {
  39672. state.copy = shallowCopy(state.base);
  39673. }
  39674. }
  39675. function willFinalizeES5(scope, result, isReplaced) {
  39676. scope.drafts.forEach(function (draft) {
  39677. draft[DRAFT_STATE].finalizing = true;
  39678. });
  39679. if (!isReplaced) {
  39680. if (scope.patches) {
  39681. markChangesRecursively(scope.drafts[0]);
  39682. } // This is faster when we don't care about which attributes changed.
  39683. markChangesSweep(scope.drafts);
  39684. } // When a child draft is returned, look for changes.
  39685. else if (isDraft(result) && result[DRAFT_STATE].scope === scope) {
  39686. markChangesSweep(scope.drafts);
  39687. }
  39688. }
  39689. function createES5Proxy(base, parent) {
  39690. var isArray = Array.isArray(base);
  39691. var draft = clonePotentialDraft(base);
  39692. each(draft, function (prop) {
  39693. proxyProperty(draft, prop, isArray || isEnumerable(base, prop));
  39694. });
  39695. var state = {
  39696. type: isArray ? ProxyType.ES5Array : ProxyType.ES5Object,
  39697. scope: parent ? parent.scope : ImmerScope.current,
  39698. modified: false,
  39699. finalizing: false,
  39700. finalized: false,
  39701. assigned: {},
  39702. parent: parent,
  39703. base: base,
  39704. draft: draft,
  39705. copy: null,
  39706. revoked: false,
  39707. isManual: false
  39708. };
  39709. createHiddenProperty(draft, DRAFT_STATE, state);
  39710. return draft;
  39711. } // Access a property without creating an Immer draft.
  39712. function peek$1(draft, prop) {
  39713. var state = draft[DRAFT_STATE];
  39714. if (state && !state.finalizing) {
  39715. state.finalizing = true;
  39716. var value = draft[prop];
  39717. state.finalizing = false;
  39718. return value;
  39719. }
  39720. return draft[prop];
  39721. }
  39722. function get$1(state, prop) {
  39723. assertUnrevoked(state);
  39724. var value = peek$1(latest(state), prop);
  39725. if (state.finalizing) { return value; } // Create a draft if the value is unmodified.
  39726. if (value === peek$1(state.base, prop) && isDraftable(value)) {
  39727. prepareCopy$1(state); // @ts-ignore
  39728. return state.copy[prop] = state.scope.immer.createProxy(value, state);
  39729. }
  39730. return value;
  39731. }
  39732. function set$1(state, prop, value) {
  39733. assertUnrevoked(state);
  39734. state.assigned[prop] = true;
  39735. if (!state.modified) {
  39736. if (is(value, peek$1(latest(state), prop))) { return; }
  39737. markChangedES5(state);
  39738. prepareCopy$1(state);
  39739. } // @ts-ignore
  39740. state.copy[prop] = value;
  39741. }
  39742. function markChangedES5(state) {
  39743. if (!state.modified) {
  39744. state.modified = true;
  39745. if (state.parent) { markChangedES5(state.parent); }
  39746. }
  39747. }
  39748. function prepareCopy$1(state) {
  39749. if (!state.copy) { state.copy = clonePotentialDraft(state.base); }
  39750. }
  39751. function clonePotentialDraft(base) {
  39752. var state = base && base[DRAFT_STATE];
  39753. if (state) {
  39754. state.finalizing = true;
  39755. var draft = shallowCopy(state.draft, true);
  39756. state.finalizing = false;
  39757. return draft;
  39758. }
  39759. return shallowCopy(base);
  39760. } // property descriptors are recycled to make sure we don't create a get and set closure per property,
  39761. // but share them all instead
  39762. var descriptors = {};
  39763. function proxyProperty(draft, prop, enumerable) {
  39764. var desc = descriptors[prop];
  39765. if (desc) {
  39766. desc.enumerable = enumerable;
  39767. } else {
  39768. descriptors[prop] = desc = {
  39769. configurable: true,
  39770. enumerable: enumerable,
  39771. get: function () {
  39772. return get$1(this[DRAFT_STATE], prop);
  39773. },
  39774. set: function (value) {
  39775. set$1(this[DRAFT_STATE], prop, value);
  39776. }
  39777. };
  39778. }
  39779. Object.defineProperty(draft, prop, desc);
  39780. }
  39781. function assertUnrevoked(state) {
  39782. 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))); }
  39783. } // This looks expensive, but only proxies are visited, and only objects without known changes are scanned.
  39784. function markChangesSweep(drafts) {
  39785. // The natural order of drafts in the `scope` array is based on when they
  39786. // were accessed. By processing drafts in reverse natural order, we have a
  39787. // better chance of processing leaf nodes first. When a leaf node is known to
  39788. // have changed, we can avoid any traversal of its ancestor nodes.
  39789. for (var i = drafts.length - 1; i >= 0; i--) {
  39790. var state = drafts[i][DRAFT_STATE];
  39791. if (!state.modified) {
  39792. switch (state.type) {
  39793. case ProxyType.ES5Array:
  39794. if (hasArrayChanges(state)) { markChangedES5(state); }
  39795. break;
  39796. case ProxyType.ES5Object:
  39797. if (hasObjectChanges(state)) { markChangedES5(state); }
  39798. break;
  39799. }
  39800. }
  39801. }
  39802. }
  39803. function markChangesRecursively(object) {
  39804. if (!object || typeof object !== "object") { return; }
  39805. var state = object[DRAFT_STATE];
  39806. if (!state) { return; }
  39807. var base = state.base,
  39808. draft = state.draft,
  39809. assigned = state.assigned,
  39810. type = state.type;
  39811. if (type === ProxyType.ES5Object) {
  39812. // Look for added keys.
  39813. // TODO: looks quite duplicate to hasObjectChanges,
  39814. // probably there is a faster way to detect changes, as sweep + recurse seems to do some
  39815. // unnecessary work.
  39816. // also: probably we can store the information we detect here, to speed up tree finalization!
  39817. each(draft, function (key) {
  39818. if (key === DRAFT_STATE) { return; } // The `undefined` check is a fast path for pre-existing keys.
  39819. if (base[key] === undefined && !has(base, key)) {
  39820. assigned[key] = true;
  39821. markChangedES5(state);
  39822. } else if (!assigned[key]) {
  39823. // Only untouched properties trigger recursion.
  39824. markChangesRecursively(draft[key]);
  39825. }
  39826. }); // Look for removed keys.
  39827. each(base, function (key) {
  39828. // The `undefined` check is a fast path for pre-existing keys.
  39829. if (draft[key] === undefined && !has(draft, key)) {
  39830. assigned[key] = false;
  39831. markChangedES5(state);
  39832. }
  39833. });
  39834. } else if (type === ProxyType.ES5Array && hasArrayChanges(state)) {
  39835. markChangedES5(state);
  39836. assigned.length = true;
  39837. if (draft.length < base.length) {
  39838. for (var i = draft.length; i < base.length; i++) { assigned[i] = false; }
  39839. } else {
  39840. for (var i = base.length; i < draft.length; i++) { assigned[i] = true; }
  39841. }
  39842. for (var i = 0; i < draft.length; i++) {
  39843. // Only untouched indices trigger recursion.
  39844. if (assigned[i] === undefined) { markChangesRecursively(draft[i]); }
  39845. }
  39846. }
  39847. }
  39848. function hasObjectChanges(state) {
  39849. var base = state.base,
  39850. draft = state.draft; // Search for added keys and changed keys. Start at the back, because
  39851. // non-numeric keys are ordered by time of definition on the object.
  39852. var keys = Object.keys(draft);
  39853. for (var i = keys.length - 1; i >= 0; i--) {
  39854. var key = keys[i];
  39855. var baseValue = base[key]; // The `undefined` check is a fast path for pre-existing keys.
  39856. if (baseValue === undefined && !has(base, key)) {
  39857. return true;
  39858. } // Once a base key is deleted, future changes go undetected, because its
  39859. // descriptor is erased. This branch detects any missed changes.
  39860. else {
  39861. var value = draft[key];
  39862. var state_1 = value && value[DRAFT_STATE];
  39863. if (state_1 ? state_1.base !== baseValue : !is(value, baseValue)) {
  39864. return true;
  39865. }
  39866. }
  39867. } // At this point, no keys were added or changed.
  39868. // Compare key count to determine if keys were deleted.
  39869. return keys.length !== Object.keys(base).length;
  39870. }
  39871. function hasArrayChanges(state) {
  39872. var draft = state.draft;
  39873. if (draft.length !== state.base.length) { return true; } // See #116
  39874. // If we first shorten the length, our array interceptors will be removed.
  39875. // If after that new items are added, result in the same original length,
  39876. // those last items will have no intercepting property.
  39877. // So if there is no own descriptor on the last position, we know that items were removed and added
  39878. // N.B.: splice, unshift, etc only shift values around, but not prop descriptors, so we only have to check
  39879. // the last one
  39880. var descriptor = Object.getOwnPropertyDescriptor(draft, draft.length - 1); // descriptor can be null, but only for newly created sparse arrays, eg. new Array(10)
  39881. 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
  39882. return false;
  39883. }
  39884. var DraftMap = function (_super) {
  39885. if (!_super) {
  39886. /* istanbul ignore next */
  39887. throw new Error("Map is not polyfilled");
  39888. }
  39889. __extends(DraftMap, _super); // Create class manually, cause #502
  39890. function DraftMap(target, parent) {
  39891. this[DRAFT_STATE] = {
  39892. type: ProxyType.Map,
  39893. parent: parent,
  39894. scope: parent ? parent.scope : ImmerScope.current,
  39895. modified: false,
  39896. finalized: false,
  39897. copy: undefined,
  39898. assigned: undefined,
  39899. base: target,
  39900. draft: this,
  39901. isManual: false,
  39902. revoked: false
  39903. };
  39904. return this;
  39905. }
  39906. var p = DraftMap.prototype; // TODO: smaller build size if we create a util for Object.defineProperty
  39907. Object.defineProperty(p, "size", {
  39908. get: function () {
  39909. return latest(this[DRAFT_STATE]).size;
  39910. },
  39911. enumerable: true,
  39912. configurable: true
  39913. });
  39914. p.has = function (key) {
  39915. return latest(this[DRAFT_STATE]).has(key);
  39916. };
  39917. p.set = function (key, value) {
  39918. var state = this[DRAFT_STATE];
  39919. assertUnrevoked(state);
  39920. if (latest(state).get(key) !== value) {
  39921. prepareCopy$2(state);
  39922. state.scope.immer.markChanged(state);
  39923. state.assigned.set(key, true);
  39924. state.copy.set(key, value);
  39925. state.assigned.set(key, true);
  39926. }
  39927. return this;
  39928. };
  39929. p.delete = function (key) {
  39930. if (!this.has(key)) {
  39931. return false;
  39932. }
  39933. var state = this[DRAFT_STATE];
  39934. assertUnrevoked(state);
  39935. prepareCopy$2(state);
  39936. state.scope.immer.markChanged(state);
  39937. state.assigned.set(key, false);
  39938. state.copy.delete(key);
  39939. return true;
  39940. };
  39941. p.clear = function () {
  39942. var state = this[DRAFT_STATE];
  39943. assertUnrevoked(state);
  39944. prepareCopy$2(state);
  39945. state.scope.immer.markChanged(state);
  39946. state.assigned = new Map();
  39947. return state.copy.clear();
  39948. };
  39949. p.forEach = function (cb, thisArg) {
  39950. var _this = this;
  39951. var state = this[DRAFT_STATE];
  39952. latest(state).forEach(function (_value, key, _map) {
  39953. cb.call(thisArg, _this.get(key), key, _this);
  39954. });
  39955. };
  39956. p.get = function (key) {
  39957. var state = this[DRAFT_STATE];
  39958. assertUnrevoked(state);
  39959. var value = latest(state).get(key);
  39960. if (state.finalized || !isDraftable(value)) {
  39961. return value;
  39962. }
  39963. if (value !== state.base.get(key)) {
  39964. return value; // either already drafted or reassigned
  39965. } // despite what it looks, this creates a draft only once, see above condition
  39966. var draft = state.scope.immer.createProxy(value, state);
  39967. prepareCopy$2(state);
  39968. state.copy.set(key, draft);
  39969. return draft;
  39970. };
  39971. p.keys = function () {
  39972. return latest(this[DRAFT_STATE]).keys();
  39973. };
  39974. p.values = function () {
  39975. var _a;
  39976. var _this = this;
  39977. var iterator = this.keys();
  39978. return _a = {}, _a[iteratorSymbol] = function () {
  39979. return _this.values();
  39980. }, _a.next = function () {
  39981. var r = iterator.next();
  39982. /* istanbul ignore next */
  39983. if (r.done) { return r; }
  39984. var value = _this.get(r.value);
  39985. return {
  39986. done: false,
  39987. value: value
  39988. };
  39989. }, _a;
  39990. };
  39991. p.entries = function () {
  39992. var _a;
  39993. var _this = this;
  39994. var iterator = this.keys();
  39995. return _a = {}, _a[iteratorSymbol] = function () {
  39996. return _this.entries();
  39997. }, _a.next = function () {
  39998. var r = iterator.next();
  39999. /* istanbul ignore next */
  40000. if (r.done) { return r; }
  40001. var value = _this.get(r.value);
  40002. return {
  40003. done: false,
  40004. value: [r.value, value]
  40005. };
  40006. }, _a;
  40007. };
  40008. p[iteratorSymbol] = function () {
  40009. return this.entries();
  40010. };
  40011. return DraftMap;
  40012. }(Map);
  40013. function proxyMap(target, parent) {
  40014. // @ts-ignore
  40015. return new DraftMap(target, parent);
  40016. }
  40017. function prepareCopy$2(state) {
  40018. if (!state.copy) {
  40019. state.assigned = new Map();
  40020. state.copy = new Map(state.base);
  40021. }
  40022. }
  40023. var DraftSet = function (_super) {
  40024. if (!_super) {
  40025. /* istanbul ignore next */
  40026. throw new Error("Set is not polyfilled");
  40027. }
  40028. __extends(DraftSet, _super); // Create class manually, cause #502
  40029. function DraftSet(target, parent) {
  40030. this[DRAFT_STATE] = {
  40031. type: ProxyType.Set,
  40032. parent: parent,
  40033. scope: parent ? parent.scope : ImmerScope.current,
  40034. modified: false,
  40035. finalized: false,
  40036. copy: undefined,
  40037. base: target,
  40038. draft: this,
  40039. drafts: new Map(),
  40040. revoked: false,
  40041. isManual: false
  40042. };
  40043. return this;
  40044. }
  40045. var p = DraftSet.prototype;
  40046. Object.defineProperty(p, "size", {
  40047. get: function () {
  40048. return latest(this[DRAFT_STATE]).size;
  40049. },
  40050. enumerable: true,
  40051. configurable: true
  40052. });
  40053. p.has = function (value) {
  40054. var state = this[DRAFT_STATE];
  40055. assertUnrevoked(state); // bit of trickery here, to be able to recognize both the value, and the draft of its value
  40056. if (!state.copy) {
  40057. return state.base.has(value);
  40058. }
  40059. if (state.copy.has(value)) { return true; }
  40060. if (state.drafts.has(value) && state.copy.has(state.drafts.get(value))) { return true; }
  40061. return false;
  40062. };
  40063. p.add = function (value) {
  40064. var state = this[DRAFT_STATE];
  40065. assertUnrevoked(state);
  40066. if (state.copy) {
  40067. state.copy.add(value);
  40068. } else if (!state.base.has(value)) {
  40069. prepareCopy$3(state);
  40070. state.scope.immer.markChanged(state);
  40071. state.copy.add(value);
  40072. }
  40073. return this;
  40074. };
  40075. p.delete = function (value) {
  40076. if (!this.has(value)) {
  40077. return false;
  40078. }
  40079. var state = this[DRAFT_STATE];
  40080. assertUnrevoked(state);
  40081. prepareCopy$3(state);
  40082. state.scope.immer.markChanged(state);
  40083. return state.copy.delete(value) || (state.drafts.has(value) ? state.copy.delete(state.drafts.get(value)) :
  40084. /* istanbul ignore next */
  40085. false);
  40086. };
  40087. p.clear = function () {
  40088. var state = this[DRAFT_STATE];
  40089. assertUnrevoked(state);
  40090. prepareCopy$3(state);
  40091. state.scope.immer.markChanged(state);
  40092. return state.copy.clear();
  40093. };
  40094. p.values = function () {
  40095. var state = this[DRAFT_STATE];
  40096. assertUnrevoked(state);
  40097. prepareCopy$3(state);
  40098. return state.copy.values();
  40099. };
  40100. p.entries = function entries() {
  40101. var state = this[DRAFT_STATE];
  40102. assertUnrevoked(state);
  40103. prepareCopy$3(state);
  40104. return state.copy.entries();
  40105. };
  40106. p.keys = function () {
  40107. return this.values();
  40108. };
  40109. p[iteratorSymbol] = function () {
  40110. return this.values();
  40111. };
  40112. p.forEach = function forEach(cb, thisArg) {
  40113. var iterator = this.values();
  40114. var result = iterator.next();
  40115. while (!result.done) {
  40116. cb.call(thisArg, result.value, result.value, this);
  40117. result = iterator.next();
  40118. }
  40119. };
  40120. return DraftSet;
  40121. }(Set);
  40122. function proxySet(target, parent) {
  40123. // @ts-ignore
  40124. return new DraftSet(target, parent);
  40125. }
  40126. function prepareCopy$3(state) {
  40127. if (!state.copy) {
  40128. // create drafts for all entries to preserve insertion order
  40129. state.copy = new Set();
  40130. state.base.forEach(function (value) {
  40131. if (isDraftable(value)) {
  40132. var draft = state.scope.immer.createProxy(value, state);
  40133. state.drafts.set(value, draft);
  40134. state.copy.add(draft);
  40135. } else {
  40136. state.copy.add(value);
  40137. }
  40138. });
  40139. }
  40140. }
  40141. function generatePatches(state, basePath, patches, inversePatches) {
  40142. switch (state.type) {
  40143. case ProxyType.ProxyObject:
  40144. case ProxyType.ES5Object:
  40145. case ProxyType.Map:
  40146. return generatePatchesFromAssigned(state, basePath, patches, inversePatches);
  40147. case ProxyType.ES5Array:
  40148. case ProxyType.ProxyArray:
  40149. return generateArrayPatches(state, basePath, patches, inversePatches);
  40150. case ProxyType.Set:
  40151. return generateSetPatches(state, basePath, patches, inversePatches);
  40152. }
  40153. }
  40154. function generateArrayPatches(state, basePath, patches, inversePatches) {
  40155. var _a, _b;
  40156. var base = state.base,
  40157. assigned = state.assigned,
  40158. copy = state.copy;
  40159. /* istanbul ignore next */
  40160. if (!copy) { die(); } // Reduce complexity by ensuring `base` is never longer.
  40161. if (copy.length < base.length) {
  40162. _a = [copy, base], base = _a[0], copy = _a[1];
  40163. _b = [inversePatches, patches], patches = _b[0], inversePatches = _b[1];
  40164. }
  40165. var delta = copy.length - base.length; // Find the first replaced index.
  40166. var start = 0;
  40167. while (base[start] === copy[start] && start < base.length) {
  40168. ++start;
  40169. } // Find the last replaced index. Search from the end to optimize splice patches.
  40170. var end = base.length;
  40171. while (end > start && base[end - 1] === copy[end + delta - 1]) {
  40172. --end;
  40173. } // Process replaced indices.
  40174. for (var i = start; i < end; ++i) {
  40175. if (assigned[i] && copy[i] !== base[i]) {
  40176. var path = basePath.concat([i]);
  40177. patches.push({
  40178. op: "replace",
  40179. path: path,
  40180. value: copy[i]
  40181. });
  40182. inversePatches.push({
  40183. op: "replace",
  40184. path: path,
  40185. value: base[i]
  40186. });
  40187. }
  40188. }
  40189. var replaceCount = patches.length; // Process added indices.
  40190. for (var i = end + delta - 1; i >= end; --i) {
  40191. var path = basePath.concat([i]);
  40192. patches[replaceCount + i - end] = {
  40193. op: "add",
  40194. path: path,
  40195. value: copy[i]
  40196. };
  40197. inversePatches.push({
  40198. op: "remove",
  40199. path: path
  40200. });
  40201. }
  40202. } // This is used for both Map objects and normal objects.
  40203. function generatePatchesFromAssigned(state, basePath, patches, inversePatches) {
  40204. var base = state.base,
  40205. copy = state.copy;
  40206. each(state.assigned, function (key, assignedValue) {
  40207. var origValue = get(base, key);
  40208. var value = get(copy, key);
  40209. var op = !assignedValue ? "remove" : has(base, key) ? "replace" : "add";
  40210. if (origValue === value && op === "replace") { return; }
  40211. var path = basePath.concat(key);
  40212. patches.push(op === "remove" ? {
  40213. op: op,
  40214. path: path
  40215. } : {
  40216. op: op,
  40217. path: path,
  40218. value: value
  40219. });
  40220. inversePatches.push(op === "add" ? {
  40221. op: "remove",
  40222. path: path
  40223. } : op === "remove" ? {
  40224. op: "add",
  40225. path: path,
  40226. value: origValue
  40227. } : {
  40228. op: "replace",
  40229. path: path,
  40230. value: origValue
  40231. });
  40232. });
  40233. }
  40234. function generateSetPatches(state, basePath, patches, inversePatches) {
  40235. var base = state.base,
  40236. copy = state.copy;
  40237. var i = 0;
  40238. base.forEach(function (value) {
  40239. if (!copy.has(value)) {
  40240. var path = basePath.concat([i]);
  40241. patches.push({
  40242. op: "remove",
  40243. path: path,
  40244. value: value
  40245. });
  40246. inversePatches.unshift({
  40247. op: "add",
  40248. path: path,
  40249. value: value
  40250. });
  40251. }
  40252. i++;
  40253. });
  40254. i = 0;
  40255. copy.forEach(function (value) {
  40256. if (!base.has(value)) {
  40257. var path = basePath.concat([i]);
  40258. patches.push({
  40259. op: "add",
  40260. path: path,
  40261. value: value
  40262. });
  40263. inversePatches.unshift({
  40264. op: "remove",
  40265. path: path,
  40266. value: value
  40267. });
  40268. }
  40269. i++;
  40270. });
  40271. }
  40272. function applyPatches(draft, patches) {
  40273. patches.forEach(function (patch) {
  40274. var path = patch.path,
  40275. op = patch.op;
  40276. /* istanbul ignore next */
  40277. if (!path.length) { die(); }
  40278. var base = draft;
  40279. for (var i = 0; i < path.length - 1; i++) {
  40280. base = get(base, path[i]);
  40281. if (!base || typeof base !== "object") { throw new Error("Cannot apply patch, path doesn't resolve: " + path.join("/")); } // prettier-ignore
  40282. }
  40283. var type = getArchtype(base);
  40284. var value = deepClonePatchValue(patch.value); // used to clone patch to ensure original patch is not modified, see #411
  40285. var key = path[path.length - 1];
  40286. switch (op) {
  40287. case "replace":
  40288. switch (type) {
  40289. case Archtype.Map:
  40290. return base.set(key, value);
  40291. /* istanbul ignore next */
  40292. case Archtype.Set:
  40293. throw new Error('Sets cannot have "replace" patches.');
  40294. default:
  40295. // if value is an object, then it's assigned by reference
  40296. // in the following add or remove ops, the value field inside the patch will also be modifyed
  40297. // so we use value from the cloned patch
  40298. // @ts-ignore
  40299. return base[key] = value;
  40300. }
  40301. case "add":
  40302. switch (type) {
  40303. case Archtype.Array:
  40304. return base.splice(key, 0, value);
  40305. case Archtype.Map:
  40306. return base.set(key, value);
  40307. case Archtype.Set:
  40308. return base.add(value);
  40309. default:
  40310. return base[key] = value;
  40311. }
  40312. case "remove":
  40313. switch (type) {
  40314. case Archtype.Array:
  40315. return base.splice(key, 1);
  40316. case Archtype.Map:
  40317. return base.delete(key);
  40318. case Archtype.Set:
  40319. return base.delete(patch.value);
  40320. default:
  40321. return delete base[key];
  40322. }
  40323. default:
  40324. throw new Error("Unsupported patch operation: " + op);
  40325. }
  40326. });
  40327. return draft;
  40328. }
  40329. function deepClonePatchValue(obj) {
  40330. if (!obj || typeof obj !== "object") { return obj; }
  40331. if (Array.isArray(obj)) { return obj.map(deepClonePatchValue); }
  40332. if (isMap(obj)) { return new Map(Array.from(obj.entries()).map(function (_a) {
  40333. var k = _a[0],
  40334. v = _a[1];
  40335. return [k, deepClonePatchValue(v)];
  40336. })); } // Not needed: if (isSet(obj)) return new Set(Array.from(obj.values()).map(deepClone))
  40337. var cloned = Object.create(Object.getPrototypeOf(obj));
  40338. for (var key in obj) { cloned[key] = deepClonePatchValue(obj[key]); }
  40339. return cloned;
  40340. }
  40341. /*! *****************************************************************************
  40342. Copyright (c) Microsoft Corporation. All rights reserved.
  40343. Licensed under the Apache License, Version 2.0 (the "License"); you may not use
  40344. this file except in compliance with the License. You may obtain a copy of the
  40345. License at http://www.apache.org/licenses/LICENSE-2.0
  40346. THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  40347. KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
  40348. WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
  40349. MERCHANTABLITY OR NON-INFRINGEMENT.
  40350. See the Apache Version 2.0 License for specific language governing permissions
  40351. and limitations under the License.
  40352. ***************************************************************************** */
  40353. function __spreadArrays() {
  40354. for (var s = 0, i = 0, il = arguments.length; i < il; i++) s += arguments[i].length;
  40355. for (var r = Array(s), k = 0, i = 0; i < il; i++)
  40356. for (var a = arguments[i], j = 0, jl = a.length; j < jl; j++, k++)
  40357. r[k] = a[j];
  40358. return r;
  40359. }
  40360. /* istanbul ignore next */
  40361. function verifyMinified() {}
  40362. var configDefaults = {
  40363. useProxies: typeof Proxy !== "undefined" && typeof Proxy.revocable !== "undefined" && typeof Reflect !== "undefined",
  40364. autoFreeze: typeof process !== "undefined" ? process.env.NODE_ENV !== "production" :
  40365. /* istanbul ignore next */
  40366. verifyMinified.name === "verifyMinified",
  40367. onAssign: null,
  40368. onDelete: null,
  40369. onCopy: null
  40370. };
  40371. var Immer =
  40372. /** @class */
  40373. function () {
  40374. function Immer(config) {
  40375. var _this = this;
  40376. this.useProxies = false;
  40377. this.autoFreeze = false;
  40378. each(configDefaults, function (key, value) {
  40379. var _a, _b; // @ts-ignore
  40380. _this[key] = (_b = (_a = config) === null || _a === void 0 ? void 0 : _a[key], _b !== null && _b !== void 0 ? _b : value);
  40381. });
  40382. this.setUseProxies(this.useProxies);
  40383. this.produce = this.produce.bind(this);
  40384. this.produceWithPatches = this.produceWithPatches.bind(this);
  40385. }
  40386. /**
  40387. * The `produce` function takes a value and a "recipe function" (whose
  40388. * return value often depends on the base state). The recipe function is
  40389. * free to mutate its first argument however it wants. All mutations are
  40390. * only ever applied to a __copy__ of the base state.
  40391. *
  40392. * Pass only a function to create a "curried producer" which relieves you
  40393. * from passing the recipe function every time.
  40394. *
  40395. * Only plain objects and arrays are made mutable. All other objects are
  40396. * considered uncopyable.
  40397. *
  40398. * Note: This function is __bound__ to its `Immer` instance.
  40399. *
  40400. * @param {any} base - the initial state
  40401. * @param {Function} producer - function that receives a proxy of the base state as first argument and which can be freely modified
  40402. * @param {Function} patchListener - optional function that will be called with all the patches produced here
  40403. * @returns {any} a new state, or the initial state if nothing was modified
  40404. */
  40405. Immer.prototype.produce = function (base, recipe, patchListener) {
  40406. var _this = this; // curried invocation
  40407. if (typeof base === "function" && typeof recipe !== "function") {
  40408. var defaultBase_1 = recipe;
  40409. recipe = base;
  40410. var self_1 = this;
  40411. return function curriedProduce(base) {
  40412. var arguments$1 = arguments;
  40413. var _this = this;
  40414. if (base === void 0) {
  40415. base = defaultBase_1;
  40416. }
  40417. var args = [];
  40418. for (var _i = 1; _i < arguments.length; _i++) {
  40419. args[_i - 1] = arguments$1[_i];
  40420. }
  40421. return self_1.produce(base, function (draft) {
  40422. return recipe.call.apply(recipe, __spreadArrays([_this, draft], args));
  40423. }); // prettier-ignore
  40424. };
  40425. } // prettier-ignore
  40426. {
  40427. if (typeof recipe !== "function") {
  40428. throw new Error("The first or second argument to `produce` must be a function");
  40429. }
  40430. if (patchListener !== undefined && typeof patchListener !== "function") {
  40431. throw new Error("The third argument to `produce` must be a function or undefined");
  40432. }
  40433. }
  40434. var result; // Only plain objects, arrays, and "immerable classes" are drafted.
  40435. if (isDraftable(base)) {
  40436. var scope_1 = ImmerScope.enter(this);
  40437. var proxy = this.createProxy(base, undefined);
  40438. var hasError = true;
  40439. try {
  40440. result = recipe(proxy);
  40441. hasError = false;
  40442. } finally {
  40443. // finally instead of catch + rethrow better preserves original stack
  40444. if (hasError) { scope_1.revoke(); }else { scope_1.leave(); }
  40445. }
  40446. if (typeof Promise !== "undefined" && result instanceof Promise) {
  40447. return result.then(function (result) {
  40448. scope_1.usePatches(patchListener);
  40449. return processResult(_this, result, scope_1);
  40450. }, function (error) {
  40451. scope_1.revoke();
  40452. throw error;
  40453. });
  40454. }
  40455. scope_1.usePatches(patchListener);
  40456. return processResult(this, result, scope_1);
  40457. } else {
  40458. result = recipe(base);
  40459. if (result === NOTHING) { return undefined; }
  40460. if (result === undefined) { result = base; }
  40461. maybeFreeze(this, result, true);
  40462. return result;
  40463. }
  40464. };
  40465. Immer.prototype.produceWithPatches = function (arg1, arg2, arg3) {
  40466. var _this = this;
  40467. if (typeof arg1 === "function") {
  40468. return function (state) {
  40469. var arguments$1 = arguments;
  40470. var args = [];
  40471. for (var _i = 1; _i < arguments.length; _i++) {
  40472. args[_i - 1] = arguments$1[_i];
  40473. }
  40474. return _this.produceWithPatches(state, function (draft) {
  40475. return arg1.apply(void 0, __spreadArrays([draft], args));
  40476. });
  40477. };
  40478. } // non-curried form
  40479. /* istanbul ignore next */
  40480. if (arg3) { die(); }
  40481. var patches, inversePatches;
  40482. var nextState = this.produce(arg1, arg2, function (p, ip) {
  40483. patches = p;
  40484. inversePatches = ip;
  40485. });
  40486. return [nextState, patches, inversePatches];
  40487. };
  40488. Immer.prototype.createDraft = function (base) {
  40489. if (!isDraftable(base)) {
  40490. throw new Error("First argument to `createDraft` must be a plain object, an array, or an immerable object"); // prettier-ignore
  40491. }
  40492. var scope = ImmerScope.enter(this);
  40493. var proxy = this.createProxy(base, undefined);
  40494. proxy[DRAFT_STATE].isManual = true;
  40495. scope.leave();
  40496. return proxy;
  40497. };
  40498. Immer.prototype.finishDraft = function (draft, patchListener) {
  40499. var state = draft && draft[DRAFT_STATE];
  40500. if (!state || !state.isManual) {
  40501. throw new Error("First argument to `finishDraft` must be a draft returned by `createDraft`"); // prettier-ignore
  40502. }
  40503. if (state.finalized) {
  40504. throw new Error("The given draft is already finalized"); // prettier-ignore
  40505. }
  40506. var scope = state.scope;
  40507. scope.usePatches(patchListener);
  40508. return processResult(this, undefined, scope);
  40509. };
  40510. /**
  40511. * Pass true to automatically freeze all copies created by Immer.
  40512. *
  40513. * By default, auto-freezing is disabled in production.
  40514. */
  40515. Immer.prototype.setAutoFreeze = function (value) {
  40516. this.autoFreeze = value;
  40517. };
  40518. /**
  40519. * Pass true to use the ES2015 `Proxy` class when creating drafts, which is
  40520. * always faster than using ES5 proxies.
  40521. *
  40522. * By default, feature detection is used, so calling this is rarely necessary.
  40523. */
  40524. Immer.prototype.setUseProxies = function (value) {
  40525. this.useProxies = value;
  40526. };
  40527. Immer.prototype.applyPatches = function (base, patches) {
  40528. // If a patch replaces the entire state, take that replacement as base
  40529. // before applying patches
  40530. var i;
  40531. for (i = patches.length - 1; i >= 0; i--) {
  40532. var patch = patches[i];
  40533. if (patch.path.length === 0 && patch.op === "replace") {
  40534. base = patch.value;
  40535. break;
  40536. }
  40537. }
  40538. if (isDraft(base)) {
  40539. // N.B: never hits if some patch a replacement, patches are never drafts
  40540. return applyPatches(base, patches);
  40541. } // Otherwise, produce a copy of the base state.
  40542. return this.produce(base, function (draft) {
  40543. return applyPatches(draft, patches.slice(i + 1));
  40544. });
  40545. };
  40546. Immer.prototype.createProxy = function (value, parent) {
  40547. // precondition: createProxy should be guarded by isDraftable, so we know we can safely draft
  40548. var draft = isMap(value) ? proxyMap(value, parent) : isSet(value) ? proxySet(value, parent) : this.useProxies ? createProxy(value, parent) : createES5Proxy(value, parent);
  40549. var scope = parent ? parent.scope : ImmerScope.current;
  40550. scope.drafts.push(draft);
  40551. return draft;
  40552. };
  40553. Immer.prototype.willFinalize = function (scope, thing, isReplaced) {
  40554. if (!this.useProxies) { willFinalizeES5(scope, thing, isReplaced); }
  40555. };
  40556. Immer.prototype.markChanged = function (state) {
  40557. if (this.useProxies) {
  40558. markChanged(state);
  40559. } else {
  40560. markChangedES5(state);
  40561. }
  40562. };
  40563. return Immer;
  40564. }();
  40565. var immer = new Immer();
  40566. /**
  40567. * The `produce` function takes a value and a "recipe function" (whose
  40568. * return value often depends on the base state). The recipe function is
  40569. * free to mutate its first argument however it wants. All mutations are
  40570. * only ever applied to a __copy__ of the base state.
  40571. *
  40572. * Pass only a function to create a "curried producer" which relieves you
  40573. * from passing the recipe function every time.
  40574. *
  40575. * Only plain objects and arrays are made mutable. All other objects are
  40576. * considered uncopyable.
  40577. *
  40578. * Note: This function is __bound__ to its `Immer` instance.
  40579. *
  40580. * @param {any} base - the initial state
  40581. * @param {Function} producer - function that receives a proxy of the base state as first argument and which can be freely modified
  40582. * @param {Function} patchListener - optional function that will be called with all the patches produced here
  40583. * @returns {any} a new state, or the initial state if nothing was modified
  40584. */
  40585. var produce = immer.produce;
  40586. /**
  40587. * Like `produce`, but `produceWithPatches` always returns a tuple
  40588. * [nextState, patches, inversePatches] (instead of just the next state)
  40589. */
  40590. var produceWithPatches = immer.produceWithPatches.bind(immer);
  40591. /**
  40592. * Pass true to automatically freeze all copies created by Immer.
  40593. *
  40594. * By default, auto-freezing is disabled in production.
  40595. */
  40596. var setAutoFreeze = immer.setAutoFreeze.bind(immer);
  40597. /**
  40598. * Pass true to use the ES2015 `Proxy` class when creating drafts, which is
  40599. * always faster than using ES5 proxies.
  40600. *
  40601. * By default, feature detection is used, so calling this is rarely necessary.
  40602. */
  40603. var setUseProxies = immer.setUseProxies.bind(immer);
  40604. /**
  40605. * Apply an array of Immer patches to the first argument.
  40606. *
  40607. * This function is a producer, which means copy-on-write is in effect.
  40608. */
  40609. var applyPatches$1 = immer.applyPatches.bind(immer);
  40610. /**
  40611. * Create an Immer draft from the given base state, which may be a draft itself.
  40612. * The draft can be modified until you finalize it with the `finishDraft` function.
  40613. */
  40614. var createDraft = immer.createDraft.bind(immer);
  40615. /**
  40616. * Finalize an Immer draft from a `createDraft` call, returning the base state
  40617. * (if no changes were made) or a modified copy. The draft must *not* be
  40618. * mutated afterwards.
  40619. *
  40620. * Pass a function as the 2nd argument to generate Immer patches based on the
  40621. * changes that were made.
  40622. */
  40623. var finishDraft = immer.finishDraft.bind(immer);
  40624. /**
  40625. * This function is actually a no-op, but can be used to cast an immutable type
  40626. * to an draft type and make TypeScript happy
  40627. *
  40628. * @param value
  40629. */
  40630. function castDraft(value) {
  40631. return value;
  40632. }
  40633. /**
  40634. * This function is actually a no-op, but can be used to cast a mutable type
  40635. * to an immutable type and make TypeScript happy
  40636. * @param value
  40637. */
  40638. function castImmutable(value) {
  40639. return value;
  40640. }
  40641. exports.Immer = Immer;
  40642. exports.applyPatches = applyPatches$1;
  40643. exports.castDraft = castDraft;
  40644. exports.castImmutable = castImmutable;
  40645. exports.createDraft = createDraft;
  40646. exports.default = produce;
  40647. exports.finishDraft = finishDraft;
  40648. exports.immerable = DRAFTABLE;
  40649. exports.isDraft = isDraft;
  40650. exports.isDraftable = isDraftable;
  40651. exports.nothing = NOTHING;
  40652. exports.original = original;
  40653. exports.produce = produce;
  40654. exports.produceWithPatches = produceWithPatches;
  40655. exports.setAutoFreeze = setAutoFreeze;
  40656. exports.setUseProxies = setUseProxies;
  40657. });
  40658. unwrapExports(immer_1);
  40659. var immer_2 = immer_1.Immer;
  40660. var immer_3 = immer_1.applyPatches;
  40661. var immer_4 = immer_1.castDraft;
  40662. var immer_5 = immer_1.castImmutable;
  40663. var immer_6 = immer_1.createDraft;
  40664. var immer_7 = immer_1.finishDraft;
  40665. var immer_8 = immer_1.immerable;
  40666. var immer_9 = immer_1.isDraft;
  40667. var immer_10 = immer_1.isDraftable;
  40668. var immer_11 = immer_1.nothing;
  40669. var immer_12 = immer_1.original;
  40670. var immer_13 = immer_1.produce;
  40671. var immer_14 = immer_1.produceWithPatches;
  40672. var immer_15 = immer_1.setAutoFreeze;
  40673. var immer_16 = immer_1.setUseProxies;
  40674. var esrever = createCommonjsModule(function (module, exports) {
  40675. (function(root) {
  40676. // Detect free variables `exports`
  40677. var freeExports = exports;
  40678. // Detect free variable `module`
  40679. var freeModule = module &&
  40680. module.exports == freeExports && module;
  40681. // Detect free variable `global`, from Node.js or Browserified code,
  40682. // and use it as `root`
  40683. var freeGlobal = typeof commonjsGlobal == 'object' && commonjsGlobal;
  40684. if (freeGlobal.global === freeGlobal || freeGlobal.window === freeGlobal) {
  40685. root = freeGlobal;
  40686. }
  40687. /*--------------------------------------------------------------------------*/
  40688. 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;
  40689. var regexSurrogatePair = /([\uD800-\uDBFF])([\uDC00-\uDFFF])/g;
  40690. var reverse = function(string) {
  40691. // Step 1: deal with combining marks and astral symbols (surrogate pairs)
  40692. string = string
  40693. // Swap symbols with their combining marks so the combining marks go first
  40694. .replace(regexSymbolWithCombiningMarks, function($0, $1, $2) {
  40695. // Reverse the combining marks so they will end up in the same order
  40696. // later on (after another round of reversing)
  40697. return reverse($2) + $1;
  40698. })
  40699. // Swap high and low surrogates so the low surrogates go first
  40700. .replace(regexSurrogatePair, '$2$1');
  40701. // Step 2: reverse the code units in the string
  40702. var result = '';
  40703. var index = string.length;
  40704. while (index--) {
  40705. result += string.charAt(index);
  40706. }
  40707. return result;
  40708. };
  40709. /*--------------------------------------------------------------------------*/
  40710. var esrever = {
  40711. 'version': '0.2.0',
  40712. 'reverse': reverse
  40713. };
  40714. // Some AMD build optimizers, like r.js, check for specific condition patterns
  40715. // like the following:
  40716. if (freeExports && !freeExports.nodeType) {
  40717. if (freeModule) { // in Node.js, io.js, or RingoJS v0.8.0+
  40718. freeModule.exports = esrever;
  40719. } else { // in Narwhal or RingoJS v0.7.0-
  40720. for (var key in esrever) {
  40721. esrever.hasOwnProperty(key) && (freeExports[key] = esrever[key]);
  40722. }
  40723. }
  40724. } else { // in Rhino or a web browser
  40725. root.esrever = esrever;
  40726. }
  40727. }(commonjsGlobal));
  40728. });
  40729. var dist$4 = createCommonjsModule(function (module, exports) {
  40730. Object.defineProperty(exports, '__esModule', { value: true });
  40731. function _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; }
  40732. var isPlainObject = _interopDefault(index_cjs);
  40733. function _defineProperty(obj, key, value) {
  40734. if (key in obj) {
  40735. Object.defineProperty(obj, key, {
  40736. value: value,
  40737. enumerable: true,
  40738. configurable: true,
  40739. writable: true
  40740. });
  40741. } else {
  40742. obj[key] = value;
  40743. }
  40744. return obj;
  40745. }
  40746. var DIRTY_PATHS = new WeakMap();
  40747. var FLUSHING = new WeakMap();
  40748. var NORMALIZING = new WeakMap();
  40749. var PATH_REFS = new WeakMap();
  40750. var POINT_REFS = new WeakMap();
  40751. var RANGE_REFS = new WeakMap();
  40752. 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; }
  40753. 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; }
  40754. /**
  40755. * Create a new Slate `Editor` object.
  40756. */
  40757. var createEditor = () => {
  40758. var editor = {
  40759. children: [],
  40760. operations: [],
  40761. selection: null,
  40762. marks: null,
  40763. isInline: () => false,
  40764. isVoid: () => false,
  40765. onChange: () => {},
  40766. apply: op => {
  40767. for (var ref of Editor.pathRefs(editor)) {
  40768. PathRef.transform(ref, op);
  40769. }
  40770. for (var _ref of Editor.pointRefs(editor)) {
  40771. PointRef.transform(_ref, op);
  40772. }
  40773. for (var _ref2 of Editor.rangeRefs(editor)) {
  40774. RangeRef.transform(_ref2, op);
  40775. }
  40776. var set = new Set();
  40777. var dirtyPaths = [];
  40778. var add = path => {
  40779. if (path) {
  40780. var key = path.join(',');
  40781. if (!set.has(key)) {
  40782. set.add(key);
  40783. dirtyPaths.push(path);
  40784. }
  40785. }
  40786. };
  40787. var oldDirtyPaths = DIRTY_PATHS.get(editor) || [];
  40788. var newDirtyPaths = getDirtyPaths(op);
  40789. for (var path of oldDirtyPaths) {
  40790. var newPath = Path.transform(path, op);
  40791. add(newPath);
  40792. }
  40793. for (var _path of newDirtyPaths) {
  40794. add(_path);
  40795. }
  40796. DIRTY_PATHS.set(editor, dirtyPaths);
  40797. Editor.transform(editor, op);
  40798. editor.operations.push(op);
  40799. Editor.normalize(editor); // Clear any formats applied to the cursor if the selection changes.
  40800. if (op.type === 'set_selection') {
  40801. editor.marks = null;
  40802. }
  40803. if (!FLUSHING.get(editor)) {
  40804. FLUSHING.set(editor, true);
  40805. Promise.resolve().then(() => {
  40806. FLUSHING.set(editor, false);
  40807. editor.onChange();
  40808. editor.operations = [];
  40809. });
  40810. }
  40811. },
  40812. addMark: (key, value) => {
  40813. var {
  40814. selection
  40815. } = editor;
  40816. if (selection) {
  40817. if (Range.isExpanded(selection)) {
  40818. Transforms.setNodes(editor, {
  40819. [key]: value
  40820. }, {
  40821. match: Text.isText,
  40822. split: true
  40823. });
  40824. } else {
  40825. var marks = _objectSpread({}, Editor.marks(editor) || {}, {
  40826. [key]: value
  40827. });
  40828. editor.marks = marks;
  40829. editor.onChange();
  40830. }
  40831. }
  40832. },
  40833. deleteBackward: unit => {
  40834. var {
  40835. selection
  40836. } = editor;
  40837. if (selection && Range.isCollapsed(selection)) {
  40838. Transforms.delete(editor, {
  40839. unit,
  40840. reverse: true
  40841. });
  40842. }
  40843. },
  40844. deleteForward: unit => {
  40845. var {
  40846. selection
  40847. } = editor;
  40848. if (selection && Range.isCollapsed(selection)) {
  40849. Transforms.delete(editor, {
  40850. unit
  40851. });
  40852. }
  40853. },
  40854. deleteFragment: () => {
  40855. var {
  40856. selection
  40857. } = editor;
  40858. if (selection && Range.isExpanded(selection)) {
  40859. Transforms.delete(editor);
  40860. }
  40861. },
  40862. insertBreak: () => {
  40863. Transforms.splitNodes(editor, {
  40864. always: true
  40865. });
  40866. },
  40867. insertFragment: fragment => {
  40868. Transforms.insertFragment(editor, fragment);
  40869. },
  40870. insertNode: node => {
  40871. Transforms.insertNodes(editor, node);
  40872. },
  40873. insertText: text => {
  40874. var {
  40875. selection,
  40876. marks
  40877. } = editor;
  40878. if (selection) {
  40879. // If the cursor is at the end of an inline, move it outside of
  40880. // the inline before inserting
  40881. if (Range.isCollapsed(selection)) {
  40882. var inline = Editor.above(editor, {
  40883. match: n => Editor.isInline(editor, n),
  40884. mode: 'highest'
  40885. });
  40886. if (inline) {
  40887. var [, inlinePath] = inline;
  40888. if (Editor.isEnd(editor, selection.anchor, inlinePath)) {
  40889. var point = Editor.after(editor, inlinePath);
  40890. Transforms.setSelection(editor, {
  40891. anchor: point,
  40892. focus: point
  40893. });
  40894. }
  40895. }
  40896. }
  40897. if (marks) {
  40898. var node = _objectSpread({
  40899. text
  40900. }, marks);
  40901. Transforms.insertNodes(editor, node);
  40902. } else {
  40903. Transforms.insertText(editor, text);
  40904. }
  40905. editor.marks = null;
  40906. }
  40907. },
  40908. normalizeNode: entry => {
  40909. var [node, path] = entry; // There are no core normalizations for text nodes.
  40910. if (Text.isText(node)) {
  40911. return;
  40912. } // Ensure that block and inline nodes have at least one text child.
  40913. if (Element.isElement(node) && node.children.length === 0) {
  40914. var child = {
  40915. text: ''
  40916. };
  40917. Transforms.insertNodes(editor, child, {
  40918. at: path.concat(0),
  40919. voids: true
  40920. });
  40921. return;
  40922. } // Determine whether the node should have block or inline children.
  40923. 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
  40924. // index that accounts for any added/removed nodes.
  40925. var n = 0;
  40926. for (var i = 0; i < node.children.length; i++, n++) {
  40927. var _child = node.children[i];
  40928. var prev = node.children[i - 1];
  40929. var isLast = i === node.children.length - 1;
  40930. var isInlineOrText = Text.isText(_child) || Element.isElement(_child) && editor.isInline(_child); // Only allow block nodes in the top-level children and parent blocks
  40931. // that only contain block nodes. Similarly, only allow inline nodes in
  40932. // other inline nodes, or parent blocks that only contain inlines and
  40933. // text.
  40934. if (isInlineOrText !== shouldHaveInlines) {
  40935. Transforms.removeNodes(editor, {
  40936. at: path.concat(n),
  40937. voids: true
  40938. });
  40939. n--;
  40940. } else if (Element.isElement(_child)) {
  40941. // Ensure that inline nodes are surrounded by text nodes.
  40942. if (editor.isInline(_child)) {
  40943. if (prev == null || !Text.isText(prev)) {
  40944. var newChild = {
  40945. text: ''
  40946. };
  40947. Transforms.insertNodes(editor, newChild, {
  40948. at: path.concat(n),
  40949. voids: true
  40950. });
  40951. n++;
  40952. } else if (isLast) {
  40953. var _newChild = {
  40954. text: ''
  40955. };
  40956. Transforms.insertNodes(editor, _newChild, {
  40957. at: path.concat(n + 1),
  40958. voids: true
  40959. });
  40960. n++;
  40961. }
  40962. }
  40963. } else {
  40964. // Merge adjacent text nodes that are empty or match.
  40965. if (prev != null && Text.isText(prev)) {
  40966. if (Text.equals(_child, prev, {
  40967. loose: true
  40968. })) {
  40969. Transforms.mergeNodes(editor, {
  40970. at: path.concat(n),
  40971. voids: true
  40972. });
  40973. n--;
  40974. } else if (prev.text === '') {
  40975. Transforms.removeNodes(editor, {
  40976. at: path.concat(n - 1),
  40977. voids: true
  40978. });
  40979. n--;
  40980. } else if (isLast && _child.text === '') {
  40981. Transforms.removeNodes(editor, {
  40982. at: path.concat(n),
  40983. voids: true
  40984. });
  40985. n--;
  40986. }
  40987. }
  40988. }
  40989. }
  40990. },
  40991. removeMark: key => {
  40992. var {
  40993. selection
  40994. } = editor;
  40995. if (selection) {
  40996. if (Range.isExpanded(selection)) {
  40997. Transforms.unsetNodes(editor, key, {
  40998. match: Text.isText,
  40999. split: true
  41000. });
  41001. } else {
  41002. var marks = _objectSpread({}, Editor.marks(editor) || {});
  41003. delete marks[key];
  41004. editor.marks = marks;
  41005. editor.onChange();
  41006. }
  41007. }
  41008. }
  41009. };
  41010. return editor;
  41011. };
  41012. /**
  41013. * Get the "dirty" paths generated from an operation.
  41014. */
  41015. var getDirtyPaths = op => {
  41016. switch (op.type) {
  41017. case 'insert_text':
  41018. case 'remove_text':
  41019. case 'set_node':
  41020. {
  41021. var {
  41022. path
  41023. } = op;
  41024. return Path.levels(path);
  41025. }
  41026. case 'insert_node':
  41027. {
  41028. var {
  41029. node,
  41030. path: _path2
  41031. } = op;
  41032. var levels = Path.levels(_path2);
  41033. var descendants = Text.isText(node) ? [] : Array.from(Node.nodes(node), (_ref3) => {
  41034. var [, p] = _ref3;
  41035. return _path2.concat(p);
  41036. });
  41037. return [...levels, ...descendants];
  41038. }
  41039. case 'merge_node':
  41040. {
  41041. var {
  41042. path: _path3
  41043. } = op;
  41044. var ancestors = Path.ancestors(_path3);
  41045. var previousPath = Path.previous(_path3);
  41046. return [...ancestors, previousPath];
  41047. }
  41048. case 'move_node':
  41049. {
  41050. var {
  41051. path: _path4,
  41052. newPath
  41053. } = op;
  41054. if (Path.equals(_path4, newPath)) {
  41055. return [];
  41056. }
  41057. var oldAncestors = [];
  41058. var newAncestors = [];
  41059. for (var ancestor of Path.ancestors(_path4)) {
  41060. var p = Path.transform(ancestor, op);
  41061. oldAncestors.push(p);
  41062. }
  41063. for (var _ancestor of Path.ancestors(newPath)) {
  41064. var _p = Path.transform(_ancestor, op);
  41065. newAncestors.push(_p);
  41066. }
  41067. return [...oldAncestors, ...newAncestors];
  41068. }
  41069. case 'remove_node':
  41070. {
  41071. var {
  41072. path: _path5
  41073. } = op;
  41074. var _ancestors = Path.ancestors(_path5);
  41075. return [..._ancestors];
  41076. }
  41077. case 'split_node':
  41078. {
  41079. var {
  41080. path: _path6
  41081. } = op;
  41082. var _levels = Path.levels(_path6);
  41083. var nextPath = Path.next(_path6);
  41084. return [..._levels, nextPath];
  41085. }
  41086. default:
  41087. {
  41088. return [];
  41089. }
  41090. }
  41091. };
  41092. function _objectWithoutPropertiesLoose(source, excluded) {
  41093. if (source == null) return {};
  41094. var target = {};
  41095. var sourceKeys = Object.keys(source);
  41096. var key, i;
  41097. for (i = 0; i < sourceKeys.length; i++) {
  41098. key = sourceKeys[i];
  41099. if (excluded.indexOf(key) >= 0) continue;
  41100. target[key] = source[key];
  41101. }
  41102. return target;
  41103. }
  41104. function _objectWithoutProperties(source, excluded) {
  41105. if (source == null) return {};
  41106. var target = _objectWithoutPropertiesLoose(source, excluded);
  41107. var key, i;
  41108. if (Object.getOwnPropertySymbols) {
  41109. var sourceSymbolKeys = Object.getOwnPropertySymbols(source);
  41110. for (i = 0; i < sourceSymbolKeys.length; i++) {
  41111. key = sourceSymbolKeys[i];
  41112. if (excluded.indexOf(key) >= 0) continue;
  41113. if (!Object.prototype.propertyIsEnumerable.call(source, key)) continue;
  41114. target[key] = source[key];
  41115. }
  41116. }
  41117. return target;
  41118. }
  41119. /**
  41120. * Constants for string distance checking.
  41121. */
  41122. var SPACE = /\s/;
  41123. 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]/;
  41124. var CHAMELEON = /['\u2018\u2019]/;
  41125. var SURROGATE_START = 0xd800;
  41126. var SURROGATE_END = 0xdfff;
  41127. var ZERO_WIDTH_JOINER = 0x200d;
  41128. /**
  41129. * Get the distance to the end of the first character in a string of text.
  41130. */
  41131. var getCharacterDistance = text => {
  41132. var offset = 0; // prev types:
  41133. // SURR: surrogate pair
  41134. // MOD: modifier (technically also surrogate pair)
  41135. // ZWJ: zero width joiner
  41136. // VAR: variation selector
  41137. // BMP: sequenceable character from basic multilingual plane
  41138. var prev = null;
  41139. var charCode = text.charCodeAt(0);
  41140. while (charCode) {
  41141. if (isSurrogate(charCode)) {
  41142. var modifier = isModifier(charCode, text, offset); // Early returns are the heart of this function, where we decide if previous and current
  41143. // codepoints should form a single character (in terms of how many of them should selection
  41144. // jump over).
  41145. if (prev === 'SURR' || prev === 'BMP') {
  41146. break;
  41147. }
  41148. offset += 2;
  41149. prev = modifier ? 'MOD' : 'SURR';
  41150. charCode = text.charCodeAt(offset); // Absolutely fine to `continue` without any checks because if `charCode` is NaN (which
  41151. // is the case when out of `text` range), next `while` loop won"t execute and we"re done.
  41152. continue;
  41153. }
  41154. if (charCode === ZERO_WIDTH_JOINER) {
  41155. offset += 1;
  41156. prev = 'ZWJ';
  41157. charCode = text.charCodeAt(offset);
  41158. continue;
  41159. }
  41160. if (isBMPEmoji(charCode)) {
  41161. if (prev && prev !== 'ZWJ' && prev !== 'VAR') {
  41162. break;
  41163. }
  41164. offset += 1;
  41165. prev = 'BMP';
  41166. charCode = text.charCodeAt(offset);
  41167. continue;
  41168. }
  41169. if (isVariationSelector(charCode)) {
  41170. if (prev && prev !== 'ZWJ') {
  41171. break;
  41172. }
  41173. offset += 1;
  41174. prev = 'VAR';
  41175. charCode = text.charCodeAt(offset);
  41176. continue;
  41177. } // Modifier 'groups up' with what ever character is before that (even whitespace), need to
  41178. // look ahead.
  41179. if (prev === 'MOD') {
  41180. offset += 1;
  41181. break;
  41182. } // If while loop ever gets here, we're done (e.g latin chars).
  41183. break;
  41184. }
  41185. return offset || 1;
  41186. };
  41187. /**
  41188. * Get the distance to the end of the first word in a string of text.
  41189. */
  41190. var getWordDistance = text => {
  41191. var length = 0;
  41192. var i = 0;
  41193. var started = false;
  41194. var char;
  41195. while (char = text.charAt(i)) {
  41196. var l = getCharacterDistance(char);
  41197. char = text.slice(i, i + l);
  41198. var rest = text.slice(i + l);
  41199. if (isWordCharacter(char, rest)) {
  41200. started = true;
  41201. length += l;
  41202. } else if (!started) {
  41203. length += l;
  41204. } else {
  41205. break;
  41206. }
  41207. i += l;
  41208. }
  41209. return length;
  41210. };
  41211. /**
  41212. * Check if a character is a word character. The `remaining` argument is used
  41213. * because sometimes you must read subsequent characters to truly determine it.
  41214. */
  41215. var isWordCharacter = (char, remaining) => {
  41216. if (SPACE.test(char)) {
  41217. return false;
  41218. } // Chameleons count as word characters as long as they're in a word, so
  41219. // recurse to see if the next one is a word character or not.
  41220. if (CHAMELEON.test(char)) {
  41221. var next = remaining.charAt(0);
  41222. var length = getCharacterDistance(next);
  41223. next = remaining.slice(0, length);
  41224. var rest = remaining.slice(length);
  41225. if (isWordCharacter(next, rest)) {
  41226. return true;
  41227. }
  41228. }
  41229. if (PUNCTUATION.test(char)) {
  41230. return false;
  41231. }
  41232. return true;
  41233. };
  41234. /**
  41235. * Determines if `code` is a surrogate
  41236. */
  41237. var isSurrogate = code => SURROGATE_START <= code && code <= SURROGATE_END;
  41238. /**
  41239. * Does `code` form Modifier with next one.
  41240. *
  41241. * https://emojipedia.org/modifiers/
  41242. */
  41243. var isModifier = (code, text, offset) => {
  41244. if (code === 0xd83c) {
  41245. var next = text.charCodeAt(offset + 1);
  41246. return next <= 0xdfff && next >= 0xdffb;
  41247. }
  41248. return false;
  41249. };
  41250. /**
  41251. * Is `code` a Variation Selector.
  41252. *
  41253. * https://codepoints.net/variation_selectors
  41254. */
  41255. var isVariationSelector = code => {
  41256. return code <= 0xfe0f && code >= 0xfe00;
  41257. };
  41258. /**
  41259. * Is `code` one of the BMP codes used in emoji sequences.
  41260. *
  41261. * https://emojipedia.org/emoji-zwj-sequences/
  41262. */
  41263. var isBMPEmoji = code => {
  41264. // This requires tiny bit of maintanance, better ideas?
  41265. // Fortunately it only happens if new Unicode Standard
  41266. // is released. Fails gracefully if upkeep lags behind,
  41267. // same way Slate previously behaved with all emojis.
  41268. return code === 0x2764 || // heart (❤)
  41269. code === 0x2642 || // male (♂)
  41270. code === 0x2640 || // female (♀)
  41271. code === 0x2620 || // scull (☠)
  41272. code === 0x2695 || // medical (⚕)
  41273. code === 0x2708 || // plane (✈️)
  41274. code === 0x25ef // large circle (◯)
  41275. ;
  41276. };
  41277. 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; }
  41278. 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; }
  41279. var Editor = {
  41280. /**
  41281. * Get the ancestor above a location in the document.
  41282. */
  41283. above(editor) {
  41284. var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
  41285. var {
  41286. voids = false,
  41287. mode = 'lowest',
  41288. at = editor.selection,
  41289. match
  41290. } = options;
  41291. if (!at) {
  41292. return;
  41293. }
  41294. var path = Editor.path(editor, at);
  41295. var reverse = mode === 'lowest';
  41296. for (var [n, p] of Editor.levels(editor, {
  41297. at: path,
  41298. voids,
  41299. match,
  41300. reverse
  41301. })) {
  41302. if (!Text.isText(n) && !Path.equals(path, p)) {
  41303. return [n, p];
  41304. }
  41305. }
  41306. },
  41307. /**
  41308. * Add a custom property to the leaf text nodes in the current selection.
  41309. *
  41310. * If the selection is currently collapsed, the marks will be added to the
  41311. * `editor.marks` property instead, and applied when text is inserted next.
  41312. */
  41313. addMark(editor, key, value) {
  41314. editor.addMark(key, value);
  41315. },
  41316. /**
  41317. * Get the point after a location.
  41318. */
  41319. after(editor, at) {
  41320. var options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
  41321. var anchor = Editor.point(editor, at, {
  41322. edge: 'end'
  41323. });
  41324. var focus = Editor.end(editor, []);
  41325. var range = {
  41326. anchor,
  41327. focus
  41328. };
  41329. var {
  41330. distance = 1
  41331. } = options;
  41332. var d = 0;
  41333. var target;
  41334. for (var p of Editor.positions(editor, _objectSpread$1({}, options, {
  41335. at: range
  41336. }))) {
  41337. if (d > distance) {
  41338. break;
  41339. }
  41340. if (d !== 0) {
  41341. target = p;
  41342. }
  41343. d++;
  41344. }
  41345. return target;
  41346. },
  41347. /**
  41348. * Get the point before a location.
  41349. */
  41350. before(editor, at) {
  41351. var options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
  41352. var anchor = Editor.start(editor, []);
  41353. var focus = Editor.point(editor, at, {
  41354. edge: 'start'
  41355. });
  41356. var range = {
  41357. anchor,
  41358. focus
  41359. };
  41360. var {
  41361. distance = 1
  41362. } = options;
  41363. var d = 0;
  41364. var target;
  41365. for (var p of Editor.positions(editor, _objectSpread$1({}, options, {
  41366. at: range,
  41367. reverse: true
  41368. }))) {
  41369. if (d > distance) {
  41370. break;
  41371. }
  41372. if (d !== 0) {
  41373. target = p;
  41374. }
  41375. d++;
  41376. }
  41377. return target;
  41378. },
  41379. /**
  41380. * Delete content in the editor backward from the current selection.
  41381. */
  41382. deleteBackward(editor) {
  41383. var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
  41384. var {
  41385. unit = 'character'
  41386. } = options;
  41387. editor.deleteBackward(unit);
  41388. },
  41389. /**
  41390. * Delete content in the editor forward from the current selection.
  41391. */
  41392. deleteForward(editor) {
  41393. var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
  41394. var {
  41395. unit = 'character'
  41396. } = options;
  41397. editor.deleteForward(unit);
  41398. },
  41399. /**
  41400. * Delete the content in the current selection.
  41401. */
  41402. deleteFragment(editor) {
  41403. editor.deleteFragment();
  41404. },
  41405. /**
  41406. * Get the start and end points of a location.
  41407. */
  41408. edges(editor, at) {
  41409. return [Editor.start(editor, at), Editor.end(editor, at)];
  41410. },
  41411. /**
  41412. * Get the end point of a location.
  41413. */
  41414. end(editor, at) {
  41415. return Editor.point(editor, at, {
  41416. edge: 'end'
  41417. });
  41418. },
  41419. /**
  41420. * Get the first node at a location.
  41421. */
  41422. first(editor, at) {
  41423. var path = Editor.path(editor, at, {
  41424. edge: 'start'
  41425. });
  41426. return Editor.node(editor, path);
  41427. },
  41428. /**
  41429. * Get the fragment at a location.
  41430. */
  41431. fragment(editor, at) {
  41432. var range = Editor.range(editor, at);
  41433. var fragment = Node.fragment(editor, range);
  41434. return fragment;
  41435. },
  41436. /**
  41437. * Check if a node has block children.
  41438. */
  41439. hasBlocks(editor, element) {
  41440. return element.children.some(n => Editor.isBlock(editor, n));
  41441. },
  41442. /**
  41443. * Check if a node has inline and text children.
  41444. */
  41445. hasInlines(editor, element) {
  41446. return element.children.some(n => Text.isText(n) || Editor.isInline(editor, n));
  41447. },
  41448. /**
  41449. * Check if a node has text children.
  41450. */
  41451. hasTexts(editor, element) {
  41452. return element.children.every(n => Text.isText(n));
  41453. },
  41454. /**
  41455. * Insert a block break at the current selection.
  41456. *
  41457. * If the selection is currently expanded, it will be deleted first.
  41458. */
  41459. insertBreak(editor) {
  41460. editor.insertBreak();
  41461. },
  41462. /**
  41463. * Insert a fragment at the current selection.
  41464. *
  41465. * If the selection is currently expanded, it will be deleted first.
  41466. */
  41467. insertFragment(editor, fragment) {
  41468. editor.insertFragment(fragment);
  41469. },
  41470. /**
  41471. * Insert a node at the current selection.
  41472. *
  41473. * If the selection is currently expanded, it will be deleted first.
  41474. */
  41475. insertNode(editor, node) {
  41476. editor.insertNode(node);
  41477. },
  41478. /**
  41479. * Insert text at the current selection.
  41480. *
  41481. * If the selection is currently expanded, it will be deleted first.
  41482. */
  41483. insertText(editor, text) {
  41484. editor.insertText(text);
  41485. },
  41486. /**
  41487. * Check if a value is a block `Element` object.
  41488. */
  41489. isBlock(editor, value) {
  41490. return Element.isElement(value) && !editor.isInline(value);
  41491. },
  41492. /**
  41493. * Check if a value is an `Editor` object.
  41494. */
  41495. isEditor(value) {
  41496. 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);
  41497. },
  41498. /**
  41499. * Check if a point is the end point of a location.
  41500. */
  41501. isEnd(editor, point, at) {
  41502. var end = Editor.end(editor, at);
  41503. return Point.equals(point, end);
  41504. },
  41505. /**
  41506. * Check if a point is an edge of a location.
  41507. */
  41508. isEdge(editor, point, at) {
  41509. return Editor.isStart(editor, point, at) || Editor.isEnd(editor, point, at);
  41510. },
  41511. /**
  41512. * Check if an element is empty, accounting for void nodes.
  41513. */
  41514. isEmpty(editor, element) {
  41515. var {
  41516. children
  41517. } = element;
  41518. var [first] = children;
  41519. return children.length === 0 || children.length === 1 && Text.isText(first) && first.text === '' && !editor.isVoid(element);
  41520. },
  41521. /**
  41522. * Check if a value is an inline `Element` object.
  41523. */
  41524. isInline(editor, value) {
  41525. return Element.isElement(value) && editor.isInline(value);
  41526. },
  41527. /**
  41528. * Check if the editor is currently normalizing after each operation.
  41529. */
  41530. isNormalizing(editor) {
  41531. var isNormalizing = NORMALIZING.get(editor);
  41532. return isNormalizing === undefined ? true : isNormalizing;
  41533. },
  41534. /**
  41535. * Check if a point is the start point of a location.
  41536. */
  41537. isStart(editor, point, at) {
  41538. // PERF: If the offset isn't `0` we know it's not the start.
  41539. if (point.offset !== 0) {
  41540. return false;
  41541. }
  41542. var start = Editor.start(editor, at);
  41543. return Point.equals(point, start);
  41544. },
  41545. /**
  41546. * Check if a value is a void `Element` object.
  41547. */
  41548. isVoid(editor, value) {
  41549. return Element.isElement(value) && editor.isVoid(value);
  41550. },
  41551. /**
  41552. * Get the last node at a location.
  41553. */
  41554. last(editor, at) {
  41555. var path = Editor.path(editor, at, {
  41556. edge: 'end'
  41557. });
  41558. return Editor.node(editor, path);
  41559. },
  41560. /**
  41561. * Get the leaf text node at a location.
  41562. */
  41563. leaf(editor, at) {
  41564. var options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
  41565. var path = Editor.path(editor, at, options);
  41566. var node = Node.leaf(editor, path);
  41567. return [node, path];
  41568. },
  41569. /**
  41570. * Iterate through all of the levels at a location.
  41571. */
  41572. *levels(editor) {
  41573. var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
  41574. var {
  41575. at = editor.selection,
  41576. reverse = false,
  41577. voids = false
  41578. } = options;
  41579. var {
  41580. match
  41581. } = options;
  41582. if (match == null) {
  41583. match = () => true;
  41584. }
  41585. if (!at) {
  41586. return;
  41587. }
  41588. var levels = [];
  41589. var path = Editor.path(editor, at);
  41590. for (var [n, p] of Node.levels(editor, path)) {
  41591. if (!match(n)) {
  41592. continue;
  41593. }
  41594. levels.push([n, p]);
  41595. if (!voids && Editor.isVoid(editor, n)) {
  41596. break;
  41597. }
  41598. }
  41599. if (reverse) {
  41600. levels.reverse();
  41601. }
  41602. yield* levels;
  41603. },
  41604. /**
  41605. * Get the marks that would be added to text at the current selection.
  41606. */
  41607. marks(editor) {
  41608. var {
  41609. marks,
  41610. selection
  41611. } = editor;
  41612. if (!selection) {
  41613. return null;
  41614. }
  41615. if (marks) {
  41616. return marks;
  41617. }
  41618. if (Range.isExpanded(selection)) {
  41619. var [match] = Editor.nodes(editor, {
  41620. match: Text.isText
  41621. });
  41622. if (match) {
  41623. var [_node] = match;
  41624. var _rest = _objectWithoutProperties(_node, ["text"]);
  41625. return _rest;
  41626. } else {
  41627. return {};
  41628. }
  41629. }
  41630. var {
  41631. anchor
  41632. } = selection;
  41633. var {
  41634. path
  41635. } = anchor;
  41636. var [node] = Editor.leaf(editor, path);
  41637. if (anchor.offset === 0) {
  41638. var prev = Editor.previous(editor, {
  41639. at: path,
  41640. match: Text.isText
  41641. });
  41642. var block = Editor.above(editor, {
  41643. match: n => Editor.isBlock(editor, n)
  41644. });
  41645. if (prev && block) {
  41646. var [prevNode, prevPath] = prev;
  41647. var [, blockPath] = block;
  41648. if (Path.isAncestor(blockPath, prevPath)) {
  41649. node = prevNode;
  41650. }
  41651. }
  41652. }
  41653. var rest = _objectWithoutProperties(node, ["text"]);
  41654. return rest;
  41655. },
  41656. /**
  41657. * Get the matching node in the branch of the document after a location.
  41658. */
  41659. next(editor) {
  41660. var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
  41661. var {
  41662. mode = 'lowest',
  41663. voids = false
  41664. } = options;
  41665. var {
  41666. match,
  41667. at = editor.selection
  41668. } = options;
  41669. if (!at) {
  41670. return;
  41671. }
  41672. var [, from] = Editor.last(editor, at);
  41673. var [, to] = Editor.last(editor, []);
  41674. var span = [from, to];
  41675. if (Path.isPath(at) && at.length === 0) {
  41676. throw new Error("Cannot get the next node from the root node!");
  41677. }
  41678. if (match == null) {
  41679. if (Path.isPath(at)) {
  41680. var [parent] = Editor.parent(editor, at);
  41681. match = n => parent.children.includes(n);
  41682. } else {
  41683. match = () => true;
  41684. }
  41685. }
  41686. var [, next] = Editor.nodes(editor, {
  41687. at: span,
  41688. match,
  41689. mode,
  41690. voids
  41691. });
  41692. return next;
  41693. },
  41694. /**
  41695. * Get the node at a location.
  41696. */
  41697. node(editor, at) {
  41698. var options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
  41699. var path = Editor.path(editor, at, options);
  41700. var node = Node.get(editor, path);
  41701. return [node, path];
  41702. },
  41703. /**
  41704. * Iterate through all of the nodes in the Editor.
  41705. */
  41706. *nodes(editor) {
  41707. var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
  41708. var {
  41709. at = editor.selection,
  41710. mode = 'all',
  41711. universal = false,
  41712. reverse = false,
  41713. voids = false
  41714. } = options;
  41715. var {
  41716. match
  41717. } = options;
  41718. if (!match) {
  41719. match = () => true;
  41720. }
  41721. if (!at) {
  41722. return;
  41723. }
  41724. var from;
  41725. var to;
  41726. if (Span.isSpan(at)) {
  41727. from = at[0];
  41728. to = at[1];
  41729. } else {
  41730. var first = Editor.path(editor, at, {
  41731. edge: 'start'
  41732. });
  41733. var last = Editor.path(editor, at, {
  41734. edge: 'end'
  41735. });
  41736. from = reverse ? last : first;
  41737. to = reverse ? first : last;
  41738. }
  41739. var iterable = Node.nodes(editor, {
  41740. reverse,
  41741. from,
  41742. to,
  41743. pass: (_ref) => {
  41744. var [n] = _ref;
  41745. return voids ? false : Editor.isVoid(editor, n);
  41746. }
  41747. });
  41748. var matches = [];
  41749. var hit;
  41750. for (var [node, path] of iterable) {
  41751. var isLower = hit && Path.compare(path, hit[1]) === 0; // In highest mode any node lower than the last hit is not a match.
  41752. if (mode === 'highest' && isLower) {
  41753. continue;
  41754. }
  41755. if (!match(node)) {
  41756. // If we've arrived at a leaf text node that is not lower than the last
  41757. // hit, then we've found a branch that doesn't include a match, which
  41758. // means the match is not universal.
  41759. if (universal && !isLower && Text.isText(node)) {
  41760. return;
  41761. } else {
  41762. continue;
  41763. }
  41764. } // If there's a match and it's lower than the last, update the hit.
  41765. if (mode === 'lowest' && isLower) {
  41766. hit = [node, path];
  41767. continue;
  41768. } // In lowest mode we emit the last hit, once it's guaranteed lowest.
  41769. var emit = mode === 'lowest' ? hit : [node, path];
  41770. if (emit) {
  41771. if (universal) {
  41772. matches.push(emit);
  41773. } else {
  41774. yield emit;
  41775. }
  41776. }
  41777. hit = [node, path];
  41778. } // Since lowest is always emitting one behind, catch up at the end.
  41779. if (mode === 'lowest' && hit) {
  41780. if (universal) {
  41781. matches.push(hit);
  41782. } else {
  41783. yield hit;
  41784. }
  41785. } // Universal defers to ensure that the match occurs in every branch, so we
  41786. // yield all of the matches after iterating.
  41787. if (universal) {
  41788. yield* matches;
  41789. }
  41790. },
  41791. /**
  41792. * Normalize any dirty objects in the editor.
  41793. */
  41794. normalize(editor) {
  41795. var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
  41796. var {
  41797. force = false
  41798. } = options;
  41799. var getDirtyPaths = editor => {
  41800. return DIRTY_PATHS.get(editor) || [];
  41801. };
  41802. if (!Editor.isNormalizing(editor)) {
  41803. return;
  41804. }
  41805. if (force) {
  41806. var allPaths = Array.from(Node.nodes(editor), (_ref2) => {
  41807. var [, p] = _ref2;
  41808. return p;
  41809. });
  41810. DIRTY_PATHS.set(editor, allPaths);
  41811. }
  41812. if (getDirtyPaths(editor).length === 0) {
  41813. return;
  41814. }
  41815. Editor.withoutNormalizing(editor, () => {
  41816. var max = getDirtyPaths(editor).length * 42; // HACK: better way?
  41817. var m = 0;
  41818. while (getDirtyPaths(editor).length !== 0) {
  41819. if (m > max) {
  41820. 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 "));
  41821. }
  41822. var path = getDirtyPaths(editor).pop();
  41823. var entry = Editor.node(editor, path);
  41824. editor.normalizeNode(entry);
  41825. m++;
  41826. }
  41827. });
  41828. },
  41829. /**
  41830. * Get the parent node of a location.
  41831. */
  41832. parent(editor, at) {
  41833. var options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
  41834. var path = Editor.path(editor, at, options);
  41835. var parentPath = Path.parent(path);
  41836. var entry = Editor.node(editor, parentPath);
  41837. return entry;
  41838. },
  41839. /**
  41840. * Get the path of a location.
  41841. */
  41842. path(editor, at) {
  41843. var options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
  41844. var {
  41845. depth,
  41846. edge
  41847. } = options;
  41848. if (Path.isPath(at)) {
  41849. if (edge === 'start') {
  41850. var [, firstPath] = Node.first(editor, at);
  41851. at = firstPath;
  41852. } else if (edge === 'end') {
  41853. var [, lastPath] = Node.last(editor, at);
  41854. at = lastPath;
  41855. }
  41856. }
  41857. if (Range.isRange(at)) {
  41858. if (edge === 'start') {
  41859. at = Range.start(at);
  41860. } else if (edge === 'end') {
  41861. at = Range.end(at);
  41862. } else {
  41863. at = Path.common(at.anchor.path, at.focus.path);
  41864. }
  41865. }
  41866. if (Point.isPoint(at)) {
  41867. at = at.path;
  41868. }
  41869. if (depth != null) {
  41870. at = at.slice(0, depth);
  41871. }
  41872. return at;
  41873. },
  41874. /**
  41875. * Create a mutable ref for a `Path` object, which will stay in sync as new
  41876. * operations are applied to the editor.
  41877. */
  41878. pathRef(editor, path) {
  41879. var options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
  41880. var {
  41881. affinity = 'forward'
  41882. } = options;
  41883. var ref = {
  41884. current: path,
  41885. affinity,
  41886. unref() {
  41887. var {
  41888. current
  41889. } = ref;
  41890. var pathRefs = Editor.pathRefs(editor);
  41891. pathRefs.delete(ref);
  41892. ref.current = null;
  41893. return current;
  41894. }
  41895. };
  41896. var refs = Editor.pathRefs(editor);
  41897. refs.add(ref);
  41898. return ref;
  41899. },
  41900. /**
  41901. * Get the set of currently tracked path refs of the editor.
  41902. */
  41903. pathRefs(editor) {
  41904. var refs = PATH_REFS.get(editor);
  41905. if (!refs) {
  41906. refs = new Set();
  41907. PATH_REFS.set(editor, refs);
  41908. }
  41909. return refs;
  41910. },
  41911. /**
  41912. * Get the start or end point of a location.
  41913. */
  41914. point(editor, at) {
  41915. var options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
  41916. var {
  41917. edge = 'start'
  41918. } = options;
  41919. if (Path.isPath(at)) {
  41920. var path;
  41921. if (edge === 'end') {
  41922. var [, lastPath] = Node.last(editor, at);
  41923. path = lastPath;
  41924. } else {
  41925. var [, firstPath] = Node.first(editor, at);
  41926. path = firstPath;
  41927. }
  41928. var node = Node.get(editor, path);
  41929. if (!Text.isText(node)) {
  41930. throw new Error("Cannot get the ".concat(edge, " point in the node at path [").concat(at, "] because it has no ").concat(edge, " text node."));
  41931. }
  41932. return {
  41933. path,
  41934. offset: edge === 'end' ? node.text.length : 0
  41935. };
  41936. }
  41937. if (Range.isRange(at)) {
  41938. var [start, end] = Range.edges(at);
  41939. return edge === 'start' ? start : end;
  41940. }
  41941. return at;
  41942. },
  41943. /**
  41944. * Create a mutable ref for a `Point` object, which will stay in sync as new
  41945. * operations are applied to the editor.
  41946. */
  41947. pointRef(editor, point) {
  41948. var options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
  41949. var {
  41950. affinity = 'forward'
  41951. } = options;
  41952. var ref = {
  41953. current: point,
  41954. affinity,
  41955. unref() {
  41956. var {
  41957. current
  41958. } = ref;
  41959. var pointRefs = Editor.pointRefs(editor);
  41960. pointRefs.delete(ref);
  41961. ref.current = null;
  41962. return current;
  41963. }
  41964. };
  41965. var refs = Editor.pointRefs(editor);
  41966. refs.add(ref);
  41967. return ref;
  41968. },
  41969. /**
  41970. * Get the set of currently tracked point refs of the editor.
  41971. */
  41972. pointRefs(editor) {
  41973. var refs = POINT_REFS.get(editor);
  41974. if (!refs) {
  41975. refs = new Set();
  41976. POINT_REFS.set(editor, refs);
  41977. }
  41978. return refs;
  41979. },
  41980. /**
  41981. * Iterate through all of the positions in the document where a `Point` can be
  41982. * placed.
  41983. *
  41984. * By default it will move forward by individual offsets at a time, but you
  41985. * can pass the `unit: 'character'` option to moved forward one character, word,
  41986. * or line at at time.
  41987. *
  41988. * Note: void nodes are treated as a single point, and iteration will not
  41989. * happen inside their content.
  41990. */
  41991. *positions(editor) {
  41992. var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
  41993. var {
  41994. at = editor.selection,
  41995. unit = 'offset',
  41996. reverse = false
  41997. } = options;
  41998. if (!at) {
  41999. return;
  42000. }
  42001. var range = Editor.range(editor, at);
  42002. var [start, end] = Range.edges(range);
  42003. var first = reverse ? end : start;
  42004. var string = '';
  42005. var available = 0;
  42006. var offset = 0;
  42007. var distance = null;
  42008. var isNewBlock = false;
  42009. var advance = () => {
  42010. if (distance == null) {
  42011. if (unit === 'character') {
  42012. distance = getCharacterDistance(string);
  42013. } else if (unit === 'word') {
  42014. distance = getWordDistance(string);
  42015. } else if (unit === 'line' || unit === 'block') {
  42016. distance = string.length;
  42017. } else {
  42018. distance = 1;
  42019. }
  42020. string = string.slice(distance);
  42021. } // Add or substract the offset.
  42022. offset = reverse ? offset - distance : offset + distance; // Subtract the distance traveled from the available text.
  42023. available = available - distance; // If the available had room to spare, reset the distance so that it will
  42024. // advance again next time. Otherwise, set it to the overflow amount.
  42025. distance = available >= 0 ? null : 0 - available;
  42026. };
  42027. for (var [node, path] of Editor.nodes(editor, {
  42028. at,
  42029. reverse
  42030. })) {
  42031. if (Element.isElement(node)) {
  42032. // Void nodes are a special case, since we don't want to iterate over
  42033. // their content. We instead always just yield their first point.
  42034. if (editor.isVoid(node)) {
  42035. yield Editor.start(editor, path);
  42036. continue;
  42037. }
  42038. if (editor.isInline(node)) {
  42039. continue;
  42040. }
  42041. if (Editor.hasInlines(editor, node)) {
  42042. var e = Path.isAncestor(path, end.path) ? end : Editor.end(editor, path);
  42043. var s = Path.isAncestor(path, start.path) ? start : Editor.start(editor, path);
  42044. var text = Editor.string(editor, {
  42045. anchor: s,
  42046. focus: e
  42047. });
  42048. string = reverse ? esrever.reverse(text) : text;
  42049. isNewBlock = true;
  42050. }
  42051. }
  42052. if (Text.isText(node)) {
  42053. var isFirst = Path.equals(path, first.path);
  42054. available = node.text.length;
  42055. offset = reverse ? available : 0;
  42056. if (isFirst) {
  42057. available = reverse ? first.offset : available - first.offset;
  42058. offset = first.offset;
  42059. }
  42060. if (isFirst || isNewBlock || unit === 'offset') {
  42061. yield {
  42062. path,
  42063. offset
  42064. };
  42065. }
  42066. while (true) {
  42067. // If there's no more string, continue to the next block.
  42068. if (string === '') {
  42069. break;
  42070. } else {
  42071. advance();
  42072. } // If the available space hasn't overflow, we have another point to
  42073. // yield in the current text node.
  42074. if (available >= 0) {
  42075. yield {
  42076. path,
  42077. offset
  42078. };
  42079. } else {
  42080. break;
  42081. }
  42082. }
  42083. isNewBlock = false;
  42084. }
  42085. }
  42086. },
  42087. /**
  42088. * Get the matching node in the branch of the document before a location.
  42089. */
  42090. previous(editor) {
  42091. var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
  42092. var {
  42093. mode = 'lowest',
  42094. voids = false
  42095. } = options;
  42096. var {
  42097. match,
  42098. at = editor.selection
  42099. } = options;
  42100. if (!at) {
  42101. return;
  42102. }
  42103. var [, from] = Editor.first(editor, at);
  42104. var [, to] = Editor.first(editor, []);
  42105. var span = [from, to];
  42106. if (Path.isPath(at) && at.length === 0) {
  42107. throw new Error("Cannot get the previous node from the root node!");
  42108. }
  42109. if (match == null) {
  42110. if (Path.isPath(at)) {
  42111. var [parent] = Editor.parent(editor, at);
  42112. match = n => parent.children.includes(n);
  42113. } else {
  42114. match = () => true;
  42115. }
  42116. }
  42117. var [, previous] = Editor.nodes(editor, {
  42118. reverse: true,
  42119. at: span,
  42120. match,
  42121. mode,
  42122. voids
  42123. });
  42124. return previous;
  42125. },
  42126. /**
  42127. * Get a range of a location.
  42128. */
  42129. range(editor, at, to) {
  42130. if (Range.isRange(at) && !to) {
  42131. return at;
  42132. }
  42133. var start = Editor.start(editor, at);
  42134. var end = Editor.end(editor, to || at);
  42135. return {
  42136. anchor: start,
  42137. focus: end
  42138. };
  42139. },
  42140. /**
  42141. * Create a mutable ref for a `Range` object, which will stay in sync as new
  42142. * operations are applied to the editor.
  42143. */
  42144. rangeRef(editor, range) {
  42145. var options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
  42146. var {
  42147. affinity = 'forward'
  42148. } = options;
  42149. var ref = {
  42150. current: range,
  42151. affinity,
  42152. unref() {
  42153. var {
  42154. current
  42155. } = ref;
  42156. var rangeRefs = Editor.rangeRefs(editor);
  42157. rangeRefs.delete(ref);
  42158. ref.current = null;
  42159. return current;
  42160. }
  42161. };
  42162. var refs = Editor.rangeRefs(editor);
  42163. refs.add(ref);
  42164. return ref;
  42165. },
  42166. /**
  42167. * Get the set of currently tracked range refs of the editor.
  42168. */
  42169. rangeRefs(editor) {
  42170. var refs = RANGE_REFS.get(editor);
  42171. if (!refs) {
  42172. refs = new Set();
  42173. RANGE_REFS.set(editor, refs);
  42174. }
  42175. return refs;
  42176. },
  42177. /**
  42178. * Remove a custom property from all of the leaf text nodes in the current
  42179. * selection.
  42180. *
  42181. * If the selection is currently collapsed, the removal will be stored on
  42182. * `editor.marks` and applied to the text inserted next.
  42183. */
  42184. removeMark(editor, key) {
  42185. editor.removeMark(key);
  42186. },
  42187. /**
  42188. * Get the start point of a location.
  42189. */
  42190. start(editor, at) {
  42191. return Editor.point(editor, at, {
  42192. edge: 'start'
  42193. });
  42194. },
  42195. /**
  42196. * Get the text string content of a location.
  42197. *
  42198. * Note: the text of void nodes is presumed to be an empty string, regardless
  42199. * of what their actual content is.
  42200. */
  42201. string(editor, at) {
  42202. var range = Editor.range(editor, at);
  42203. var [start, end] = Range.edges(range);
  42204. var text = '';
  42205. for (var [node, path] of Editor.nodes(editor, {
  42206. at: range,
  42207. match: Text.isText
  42208. })) {
  42209. var t = node.text;
  42210. if (Path.equals(path, end.path)) {
  42211. t = t.slice(0, end.offset);
  42212. }
  42213. if (Path.equals(path, start.path)) {
  42214. t = t.slice(start.offset);
  42215. }
  42216. text += t;
  42217. }
  42218. return text;
  42219. },
  42220. /**
  42221. * Transform the editor by an operation.
  42222. */
  42223. transform(editor, op) {
  42224. editor.children = immer_1.createDraft(editor.children);
  42225. var selection = editor.selection && immer_1.createDraft(editor.selection);
  42226. switch (op.type) {
  42227. case 'insert_node':
  42228. {
  42229. var {
  42230. path,
  42231. node
  42232. } = op;
  42233. var parent = Node.parent(editor, path);
  42234. var index = path[path.length - 1];
  42235. parent.children.splice(index, 0, node);
  42236. if (selection) {
  42237. for (var [point, key] of Range.points(selection)) {
  42238. selection[key] = Point.transform(point, op);
  42239. }
  42240. }
  42241. break;
  42242. }
  42243. case 'insert_text':
  42244. {
  42245. var {
  42246. path: _path,
  42247. offset,
  42248. text
  42249. } = op;
  42250. var _node2 = Node.leaf(editor, _path);
  42251. var before = _node2.text.slice(0, offset);
  42252. var after = _node2.text.slice(offset);
  42253. _node2.text = before + text + after;
  42254. if (selection) {
  42255. for (var [_point, _key] of Range.points(selection)) {
  42256. selection[_key] = Point.transform(_point, op);
  42257. }
  42258. }
  42259. break;
  42260. }
  42261. case 'merge_node':
  42262. {
  42263. var {
  42264. path: _path2
  42265. } = op;
  42266. var _node3 = Node.get(editor, _path2);
  42267. var prevPath = Path.previous(_path2);
  42268. var prev = Node.get(editor, prevPath);
  42269. var _parent = Node.parent(editor, _path2);
  42270. var _index = _path2[_path2.length - 1];
  42271. if (Text.isText(_node3) && Text.isText(prev)) {
  42272. prev.text += _node3.text;
  42273. } else if (!Text.isText(_node3) && !Text.isText(prev)) {
  42274. prev.children.push(..._node3.children);
  42275. } else {
  42276. throw new Error("Cannot apply a \"merge_node\" operation at path [".concat(_path2, "] to nodes of different interaces: ").concat(_node3, " ").concat(prev));
  42277. }
  42278. _parent.children.splice(_index, 1);
  42279. if (selection) {
  42280. for (var [_point2, _key2] of Range.points(selection)) {
  42281. selection[_key2] = Point.transform(_point2, op);
  42282. }
  42283. }
  42284. break;
  42285. }
  42286. case 'move_node':
  42287. {
  42288. var {
  42289. path: _path3,
  42290. newPath
  42291. } = op;
  42292. if (Path.isAncestor(_path3, newPath)) {
  42293. throw new Error("Cannot move a path [".concat(_path3, "] to new path [").concat(newPath, "] because the destination is inside itself."));
  42294. }
  42295. var _node4 = Node.get(editor, _path3);
  42296. var _parent2 = Node.parent(editor, _path3);
  42297. var _index2 = _path3[_path3.length - 1]; // This is tricky, but since the `path` and `newPath` both refer to
  42298. // the same snapshot in time, there's a mismatch. After either
  42299. // removing the original position, the second step's path can be out
  42300. // of date. So instead of using the `op.newPath` directly, we
  42301. // transform `op.path` to ascertain what the `newPath` would be after
  42302. // the operation was applied.
  42303. _parent2.children.splice(_index2, 1);
  42304. var truePath = Path.transform(_path3, op);
  42305. var newParent = Node.get(editor, Path.parent(truePath));
  42306. var newIndex = truePath[truePath.length - 1];
  42307. newParent.children.splice(newIndex, 0, _node4);
  42308. if (selection) {
  42309. for (var [_point3, _key3] of Range.points(selection)) {
  42310. selection[_key3] = Point.transform(_point3, op);
  42311. }
  42312. }
  42313. break;
  42314. }
  42315. case 'remove_node':
  42316. {
  42317. var {
  42318. path: _path4
  42319. } = op;
  42320. var _index3 = _path4[_path4.length - 1];
  42321. var _parent3 = Node.parent(editor, _path4);
  42322. _parent3.children.splice(_index3, 1); // Transform all of the points in the value, but if the point was in the
  42323. // node that was removed we need to update the range or remove it.
  42324. if (selection) {
  42325. for (var [_point4, _key4] of Range.points(selection)) {
  42326. var result = Point.transform(_point4, op);
  42327. if (selection != null && result != null) {
  42328. selection[_key4] = result;
  42329. } else {
  42330. var _prev = void 0;
  42331. var next = void 0;
  42332. for (var [n, p] of Node.texts(editor)) {
  42333. if (Path.compare(p, _path4) === -1) {
  42334. _prev = [n, p];
  42335. } else {
  42336. next = [n, p];
  42337. break;
  42338. }
  42339. }
  42340. if (_prev) {
  42341. _point4.path = _prev[1];
  42342. _point4.offset = _prev[0].text.length;
  42343. } else if (next) {
  42344. _point4.path = next[1];
  42345. _point4.offset = 0;
  42346. } else {
  42347. selection = null;
  42348. }
  42349. }
  42350. }
  42351. }
  42352. break;
  42353. }
  42354. case 'remove_text':
  42355. {
  42356. var {
  42357. path: _path5,
  42358. offset: _offset,
  42359. text: _text2
  42360. } = op;
  42361. var _node5 = Node.leaf(editor, _path5);
  42362. var _before = _node5.text.slice(0, _offset);
  42363. var _after = _node5.text.slice(_offset + _text2.length);
  42364. _node5.text = _before + _after;
  42365. if (selection) {
  42366. for (var [_point5, _key5] of Range.points(selection)) {
  42367. selection[_key5] = Point.transform(_point5, op);
  42368. }
  42369. }
  42370. break;
  42371. }
  42372. case 'set_node':
  42373. {
  42374. var {
  42375. path: _path6,
  42376. newProperties
  42377. } = op;
  42378. if (_path6.length === 0) {
  42379. throw new Error("Cannot set properties on the root node!");
  42380. }
  42381. var _node6 = Node.get(editor, _path6);
  42382. for (var _key6 in newProperties) {
  42383. if (_key6 === 'children' || _key6 === 'text') {
  42384. throw new Error("Cannot set the \"".concat(_key6, "\" property of nodes!"));
  42385. }
  42386. var value = newProperties[_key6];
  42387. if (value == null) {
  42388. delete _node6[_key6];
  42389. } else {
  42390. _node6[_key6] = value;
  42391. }
  42392. }
  42393. break;
  42394. }
  42395. case 'set_selection':
  42396. {
  42397. var {
  42398. newProperties: _newProperties
  42399. } = op;
  42400. if (_newProperties == null) {
  42401. selection = _newProperties;
  42402. } else if (selection == null) {
  42403. if (!Range.isRange(_newProperties)) {
  42404. throw new Error("Cannot apply an incomplete \"set_selection\" operation properties ".concat(JSON.stringify(_newProperties), " when there is no current selection."));
  42405. }
  42406. selection = _newProperties;
  42407. } else {
  42408. Object.assign(selection, _newProperties);
  42409. }
  42410. break;
  42411. }
  42412. case 'split_node':
  42413. {
  42414. var {
  42415. path: _path7,
  42416. position,
  42417. properties
  42418. } = op;
  42419. if (_path7.length === 0) {
  42420. throw new Error("Cannot apply a \"split_node\" operation at path [".concat(_path7, "] because the root node cannot be split."));
  42421. }
  42422. var _node7 = Node.get(editor, _path7);
  42423. var _parent4 = Node.parent(editor, _path7);
  42424. var _index4 = _path7[_path7.length - 1];
  42425. var newNode;
  42426. if (Text.isText(_node7)) {
  42427. var _before2 = _node7.text.slice(0, position);
  42428. var _after2 = _node7.text.slice(position);
  42429. _node7.text = _before2;
  42430. newNode = _objectSpread$1({}, _node7, {}, properties, {
  42431. text: _after2
  42432. });
  42433. } else {
  42434. var _before3 = _node7.children.slice(0, position);
  42435. var _after3 = _node7.children.slice(position);
  42436. _node7.children = _before3;
  42437. newNode = _objectSpread$1({}, _node7, {}, properties, {
  42438. children: _after3
  42439. });
  42440. }
  42441. _parent4.children.splice(_index4 + 1, 0, newNode);
  42442. if (selection) {
  42443. for (var [_point6, _key7] of Range.points(selection)) {
  42444. selection[_key7] = Point.transform(_point6, op);
  42445. }
  42446. }
  42447. break;
  42448. }
  42449. }
  42450. editor.children = immer_1.finishDraft(editor.children);
  42451. if (selection) {
  42452. editor.selection = immer_1.isDraft(selection) ? immer_1.finishDraft(selection) : selection;
  42453. } else {
  42454. editor.selection = null;
  42455. }
  42456. },
  42457. /**
  42458. * Convert a range into a non-hanging one.
  42459. */
  42460. unhangRange(editor, range) {
  42461. var options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
  42462. var {
  42463. voids = false
  42464. } = options;
  42465. var [start, end] = Range.edges(range); // PERF: exit early if we can guarantee that the range isn't hanging.
  42466. if (start.offset !== 0 || end.offset !== 0 || Range.isCollapsed(range)) {
  42467. return range;
  42468. }
  42469. var endBlock = Editor.above(editor, {
  42470. at: end,
  42471. match: n => Editor.isBlock(editor, n)
  42472. });
  42473. var blockPath = endBlock ? endBlock[1] : [];
  42474. var first = Editor.start(editor, []);
  42475. var before = {
  42476. anchor: first,
  42477. focus: end
  42478. };
  42479. var skip = true;
  42480. for (var [node, path] of Editor.nodes(editor, {
  42481. at: before,
  42482. match: Text.isText,
  42483. reverse: true,
  42484. voids
  42485. })) {
  42486. if (skip) {
  42487. skip = false;
  42488. continue;
  42489. }
  42490. if (node.text !== '' || Path.isBefore(path, blockPath)) {
  42491. end = {
  42492. path,
  42493. offset: node.text.length
  42494. };
  42495. break;
  42496. }
  42497. }
  42498. return {
  42499. anchor: start,
  42500. focus: end
  42501. };
  42502. },
  42503. /**
  42504. * Match a void node in the current branch of the editor.
  42505. */
  42506. void(editor) {
  42507. var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
  42508. return Editor.above(editor, _objectSpread$1({}, options, {
  42509. match: n => Editor.isVoid(editor, n)
  42510. }));
  42511. },
  42512. /**
  42513. * Call a function, deferring normalization until after it completes.
  42514. */
  42515. withoutNormalizing(editor, fn) {
  42516. var value = Editor.isNormalizing(editor);
  42517. NORMALIZING.set(editor, false);
  42518. fn();
  42519. NORMALIZING.set(editor, value);
  42520. Editor.normalize(editor);
  42521. }
  42522. };
  42523. var Element = {
  42524. /**
  42525. * Check if a value implements the `Element` interface.
  42526. */
  42527. isElement(value) {
  42528. return isPlainObject(value) && Node.isNodeList(value.children) && !Editor.isEditor(value);
  42529. },
  42530. /**
  42531. * Check if a value is an array of `Element` objects.
  42532. */
  42533. isElementList(value) {
  42534. return Array.isArray(value) && (value.length === 0 || Element.isElement(value[0]));
  42535. },
  42536. /**
  42537. * Check if an element matches set of properties.
  42538. *
  42539. * Note: this checks custom properties, and it does not ensure that any
  42540. * children are equivalent.
  42541. */
  42542. matches(element, props) {
  42543. for (var key in props) {
  42544. if (key === 'children') {
  42545. continue;
  42546. }
  42547. if (element[key] !== props[key]) {
  42548. return false;
  42549. }
  42550. }
  42551. return true;
  42552. }
  42553. };
  42554. var Location = {
  42555. /**
  42556. * Check if a value implements the `Location` interface.
  42557. */
  42558. isLocation(value) {
  42559. return Path.isPath(value) || Point.isPoint(value) || Range.isRange(value);
  42560. }
  42561. };
  42562. var Span = {
  42563. /**
  42564. * Check if a value implements the `Span` interface.
  42565. */
  42566. isSpan(value) {
  42567. return Array.isArray(value) && value.length === 2 && value.every(Path.isPath);
  42568. }
  42569. };
  42570. var Node = {
  42571. /**
  42572. * Get the node at a specific path, asserting that it's an ancestor node.
  42573. */
  42574. ancestor(root, path) {
  42575. var node = Node.get(root, path);
  42576. if (Text.isText(node)) {
  42577. throw new Error("Cannot get the ancestor node at path [".concat(path, "] because it refers to a text node instead: ").concat(node));
  42578. }
  42579. return node;
  42580. },
  42581. /**
  42582. * Return an iterable of all the ancestor nodes above a specific path.
  42583. *
  42584. * By default the order is bottom-up, from lowest to highest ancestor in
  42585. * the tree, but you can pass the `reverse: true` option to go top-down.
  42586. */
  42587. *ancestors(root, path) {
  42588. var options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
  42589. for (var p of Path.ancestors(path, options)) {
  42590. var n = Node.ancestor(root, p);
  42591. var entry = [n, p];
  42592. yield entry;
  42593. }
  42594. },
  42595. /**
  42596. * Get the child of a node at a specific index.
  42597. */
  42598. child(root, index) {
  42599. if (Text.isText(root)) {
  42600. throw new Error("Cannot get the child of a text node: ".concat(JSON.stringify(root)));
  42601. }
  42602. var c = root.children[index];
  42603. if (c == null) {
  42604. throw new Error("Cannot get child at index `".concat(index, "` in node: ").concat(JSON.stringify(root)));
  42605. }
  42606. return c;
  42607. },
  42608. /**
  42609. * Iterate over the children of a node at a specific path.
  42610. */
  42611. *children(root, path) {
  42612. var options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
  42613. var {
  42614. reverse = false
  42615. } = options;
  42616. var ancestor = Node.ancestor(root, path);
  42617. var {
  42618. children
  42619. } = ancestor;
  42620. var index = reverse ? children.length - 1 : 0;
  42621. while (reverse ? index >= 0 : index < children.length) {
  42622. var child = Node.child(ancestor, index);
  42623. var childPath = path.concat(index);
  42624. yield [child, childPath];
  42625. index = reverse ? index - 1 : index + 1;
  42626. }
  42627. },
  42628. /**
  42629. * Get an entry for the common ancesetor node of two paths.
  42630. */
  42631. common(root, path, another) {
  42632. var p = Path.common(path, another);
  42633. var n = Node.get(root, p);
  42634. return [n, p];
  42635. },
  42636. /**
  42637. * Get the node at a specific path, asserting that it's a descendant node.
  42638. */
  42639. descendant(root, path) {
  42640. var node = Node.get(root, path);
  42641. if (Editor.isEditor(node)) {
  42642. throw new Error("Cannot get the descendant node at path [".concat(path, "] because it refers to the root editor node instead: ").concat(node));
  42643. }
  42644. return node;
  42645. },
  42646. /**
  42647. * Return an iterable of all the descendant node entries inside a root node.
  42648. */
  42649. *descendants(root) {
  42650. var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
  42651. for (var [node, path] of Node.nodes(root, options)) {
  42652. if (path.length !== 0) {
  42653. // NOTE: we have to coerce here because checking the path's length does
  42654. // guarantee that `node` is not a `Editor`, but TypeScript doesn't know.
  42655. yield [node, path];
  42656. }
  42657. }
  42658. },
  42659. /**
  42660. * Return an iterable of all the element nodes inside a root node. Each iteration
  42661. * will return an `ElementEntry` tuple consisting of `[Element, Path]`. If the
  42662. * root node is an element it will be included in the iteration as well.
  42663. */
  42664. *elements(root) {
  42665. var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
  42666. for (var [node, path] of Node.nodes(root, options)) {
  42667. if (Element.isElement(node)) {
  42668. yield [node, path];
  42669. }
  42670. }
  42671. },
  42672. /**
  42673. * Get the first node entry in a root node from a path.
  42674. */
  42675. first(root, path) {
  42676. var p = path.slice();
  42677. var n = Node.get(root, p);
  42678. while (n) {
  42679. if (Text.isText(n) || n.children.length === 0) {
  42680. break;
  42681. } else {
  42682. n = n.children[0];
  42683. p.push(0);
  42684. }
  42685. }
  42686. return [n, p];
  42687. },
  42688. /**
  42689. * Get the sliced fragment represented by a range inside a root node.
  42690. */
  42691. fragment(root, range) {
  42692. if (Text.isText(root)) {
  42693. throw new Error("Cannot get a fragment starting from a root text node: ".concat(JSON.stringify(root)));
  42694. }
  42695. var newRoot = immer_1.produce(root, r => {
  42696. var [start, end] = Range.edges(range);
  42697. var iterable = Node.nodes(r, {
  42698. reverse: true,
  42699. pass: (_ref) => {
  42700. var [, path] = _ref;
  42701. return !Range.includes(range, path);
  42702. }
  42703. });
  42704. for (var [, path] of iterable) {
  42705. if (!Range.includes(range, path)) {
  42706. var parent = Node.parent(r, path);
  42707. var index = path[path.length - 1];
  42708. parent.children.splice(index, 1);
  42709. }
  42710. if (Path.equals(path, end.path)) {
  42711. var leaf = Node.leaf(r, path);
  42712. leaf.text = leaf.text.slice(0, end.offset);
  42713. }
  42714. if (Path.equals(path, start.path)) {
  42715. var _leaf = Node.leaf(r, path);
  42716. _leaf.text = _leaf.text.slice(start.offset);
  42717. }
  42718. }
  42719. delete r.selection;
  42720. });
  42721. return newRoot.children;
  42722. },
  42723. /**
  42724. * Get the descendant node referred to by a specific path. If the path is an
  42725. * empty array, it refers to the root node itself.
  42726. */
  42727. get(root, path) {
  42728. var node = root;
  42729. for (var i = 0; i < path.length; i++) {
  42730. var p = path[i];
  42731. if (Text.isText(node) || !node.children[p]) {
  42732. throw new Error("Cannot find a descendant at path [".concat(path, "] in node: ").concat(JSON.stringify(root)));
  42733. }
  42734. node = node.children[p];
  42735. }
  42736. return node;
  42737. },
  42738. /**
  42739. * Check if a descendant node exists at a specific path.
  42740. */
  42741. has(root, path) {
  42742. var node = root;
  42743. for (var i = 0; i < path.length; i++) {
  42744. var p = path[i];
  42745. if (Text.isText(node) || !node.children[p]) {
  42746. return false;
  42747. }
  42748. node = node.children[p];
  42749. }
  42750. return true;
  42751. },
  42752. /**
  42753. * Check if a value implements the `Node` interface.
  42754. */
  42755. isNode(value) {
  42756. return Text.isText(value) || Element.isElement(value) || Editor.isEditor(value);
  42757. },
  42758. /**
  42759. * Check if a value is a list of `Node` objects.
  42760. */
  42761. isNodeList(value) {
  42762. return Array.isArray(value) && (value.length === 0 || Node.isNode(value[0]));
  42763. },
  42764. /**
  42765. * Get the lash node entry in a root node from a path.
  42766. */
  42767. last(root, path) {
  42768. var p = path.slice();
  42769. var n = Node.get(root, p);
  42770. while (n) {
  42771. if (Text.isText(n) || n.children.length === 0) {
  42772. break;
  42773. } else {
  42774. var i = n.children.length - 1;
  42775. n = n.children[i];
  42776. p.push(i);
  42777. }
  42778. }
  42779. return [n, p];
  42780. },
  42781. /**
  42782. * Get the node at a specific path, ensuring it's a leaf text node.
  42783. */
  42784. leaf(root, path) {
  42785. var node = Node.get(root, path);
  42786. if (!Text.isText(node)) {
  42787. throw new Error("Cannot get the leaf node at path [".concat(path, "] because it refers to a non-leaf node: ").concat(node));
  42788. }
  42789. return node;
  42790. },
  42791. /**
  42792. * Return an iterable of the in a branch of the tree, from a specific path.
  42793. *
  42794. * By default the order is top-down, from lowest to highest node in the tree,
  42795. * but you can pass the `reverse: true` option to go bottom-up.
  42796. */
  42797. *levels(root, path) {
  42798. var options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
  42799. for (var p of Path.levels(path, options)) {
  42800. var n = Node.get(root, p);
  42801. yield [n, p];
  42802. }
  42803. },
  42804. /**
  42805. * Check if a node matches a set of props.
  42806. */
  42807. matches(node, props) {
  42808. return Element.isElement(node) && Element.matches(node, props) || Text.isText(node) && Text.matches(node, props);
  42809. },
  42810. /**
  42811. * Return an iterable of all the node entries of a root node. Each entry is
  42812. * returned as a `[Node, Path]` tuple, with the path referring to the node's
  42813. * position inside the root node.
  42814. */
  42815. *nodes(root) {
  42816. var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
  42817. var {
  42818. pass,
  42819. reverse = false
  42820. } = options;
  42821. var {
  42822. from = [],
  42823. to
  42824. } = options;
  42825. var visited = new Set();
  42826. var p = [];
  42827. var n = root;
  42828. while (true) {
  42829. if (to && (reverse ? Path.isBefore(p, to) : Path.isAfter(p, to))) {
  42830. break;
  42831. }
  42832. if (!visited.has(n)) {
  42833. yield [n, p];
  42834. } // If we're allowed to go downward and we haven't decsended yet, do.
  42835. if (!visited.has(n) && !Text.isText(n) && n.children.length !== 0 && (pass == null || pass([n, p]) === false)) {
  42836. visited.add(n);
  42837. var nextIndex = reverse ? n.children.length - 1 : 0;
  42838. if (Path.isAncestor(p, from)) {
  42839. nextIndex = from[p.length];
  42840. }
  42841. p = p.concat(nextIndex);
  42842. n = Node.get(root, p);
  42843. continue;
  42844. } // If we're at the root and we can't go down, we're done.
  42845. if (p.length === 0) {
  42846. break;
  42847. } // If we're going forward...
  42848. if (!reverse) {
  42849. var newPath = Path.next(p);
  42850. if (Node.has(root, newPath)) {
  42851. p = newPath;
  42852. n = Node.get(root, p);
  42853. continue;
  42854. }
  42855. } // If we're going backward...
  42856. if (reverse && p[p.length - 1] !== 0) {
  42857. var _newPath = Path.previous(p);
  42858. p = _newPath;
  42859. n = Node.get(root, p);
  42860. continue;
  42861. } // Otherwise we're going upward...
  42862. p = Path.parent(p);
  42863. n = Node.get(root, p);
  42864. visited.add(n);
  42865. }
  42866. },
  42867. /**
  42868. * Get the parent of a node at a specific path.
  42869. */
  42870. parent(root, path) {
  42871. var parentPath = Path.parent(path);
  42872. var p = Node.get(root, parentPath);
  42873. if (Text.isText(p)) {
  42874. throw new Error("Cannot get the parent of path [".concat(path, "] because it does not exist in the root."));
  42875. }
  42876. return p;
  42877. },
  42878. /**
  42879. * Get the concatenated text string of a node's content.
  42880. *
  42881. * Note that this will not include spaces or line breaks between block nodes.
  42882. * It is not a user-facing string, but a string for performing offset-related
  42883. * computations for a node.
  42884. */
  42885. string(node) {
  42886. if (Text.isText(node)) {
  42887. return node.text;
  42888. } else {
  42889. return node.children.map(Node.string).join('');
  42890. }
  42891. },
  42892. /**
  42893. * Return an iterable of all leaf text nodes in a root node.
  42894. */
  42895. *texts(root) {
  42896. var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
  42897. for (var [node, path] of Node.nodes(root, options)) {
  42898. if (Text.isText(node)) {
  42899. yield [node, path];
  42900. }
  42901. }
  42902. }
  42903. };
  42904. 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; }
  42905. 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; }
  42906. var Operation = {
  42907. /**
  42908. * Check of a value is a `NodeOperation` object.
  42909. */
  42910. isNodeOperation(value) {
  42911. return Operation.isOperation(value) && value.type.endsWith('_node');
  42912. },
  42913. /**
  42914. * Check of a value is an `Operation` object.
  42915. */
  42916. isOperation(value) {
  42917. if (!isPlainObject(value)) {
  42918. return false;
  42919. }
  42920. switch (value.type) {
  42921. case 'insert_node':
  42922. return Path.isPath(value.path) && Node.isNode(value.node);
  42923. case 'insert_text':
  42924. return typeof value.offset === 'number' && typeof value.text === 'string' && Path.isPath(value.path);
  42925. case 'merge_node':
  42926. return typeof value.position === 'number' && (typeof value.target === 'number' || value.target === null) && Path.isPath(value.path) && isPlainObject(value.properties);
  42927. case 'move_node':
  42928. return Path.isPath(value.path) && Path.isPath(value.newPath);
  42929. case 'remove_node':
  42930. return Path.isPath(value.path) && Node.isNode(value.node);
  42931. case 'remove_text':
  42932. return typeof value.offset === 'number' && typeof value.text === 'string' && Path.isPath(value.path);
  42933. case 'set_node':
  42934. return Path.isPath(value.path) && isPlainObject(value.properties) && isPlainObject(value.newProperties);
  42935. case 'set_selection':
  42936. return value.properties === null && Range.isRange(value.newProperties) || value.newProperties === null && Range.isRange(value.properties) || isPlainObject(value.properties) && isPlainObject(value.newProperties);
  42937. case 'split_node':
  42938. return Path.isPath(value.path) && typeof value.position === 'number' && (typeof value.target === 'number' || value.target === null) && isPlainObject(value.properties);
  42939. default:
  42940. return false;
  42941. }
  42942. },
  42943. /**
  42944. * Check if a value is a list of `Operation` objects.
  42945. */
  42946. isOperationList(value) {
  42947. return Array.isArray(value) && (value.length === 0 || Operation.isOperation(value[0]));
  42948. },
  42949. /**
  42950. * Check of a value is a `SelectionOperation` object.
  42951. */
  42952. isSelectionOperation(value) {
  42953. return Operation.isOperation(value) && value.type.endsWith('_selection');
  42954. },
  42955. /**
  42956. * Check of a value is a `TextOperation` object.
  42957. */
  42958. isTextOperation(value) {
  42959. return Operation.isOperation(value) && value.type.endsWith('_text');
  42960. },
  42961. /**
  42962. * Invert an operation, returning a new operation that will exactly undo the
  42963. * original when applied.
  42964. */
  42965. inverse(op) {
  42966. switch (op.type) {
  42967. case 'insert_node':
  42968. {
  42969. return _objectSpread$2({}, op, {
  42970. type: 'remove_node'
  42971. });
  42972. }
  42973. case 'insert_text':
  42974. {
  42975. return _objectSpread$2({}, op, {
  42976. type: 'remove_text'
  42977. });
  42978. }
  42979. case 'merge_node':
  42980. {
  42981. return _objectSpread$2({}, op, {
  42982. type: 'split_node',
  42983. path: Path.previous(op.path)
  42984. });
  42985. }
  42986. case 'move_node':
  42987. {
  42988. var {
  42989. newPath,
  42990. path
  42991. } = op; // PERF: in this case the move operation is a no-op anyways.
  42992. if (Path.equals(newPath, path)) {
  42993. return op;
  42994. } // We need to get the original path here, but sometimes the `newPath`
  42995. // is a younger sibling of (or ends before) the original, and this
  42996. // accounts for it.
  42997. var inversePath = Path.transform(path, op);
  42998. var inverseNewPath = Path.transform(Path.next(path), op);
  42999. return _objectSpread$2({}, op, {
  43000. path: inversePath,
  43001. newPath: inverseNewPath
  43002. });
  43003. }
  43004. case 'remove_node':
  43005. {
  43006. return _objectSpread$2({}, op, {
  43007. type: 'insert_node'
  43008. });
  43009. }
  43010. case 'remove_text':
  43011. {
  43012. return _objectSpread$2({}, op, {
  43013. type: 'insert_text'
  43014. });
  43015. }
  43016. case 'set_node':
  43017. {
  43018. var {
  43019. properties,
  43020. newProperties
  43021. } = op;
  43022. return _objectSpread$2({}, op, {
  43023. properties: newProperties,
  43024. newProperties: properties
  43025. });
  43026. }
  43027. case 'set_selection':
  43028. {
  43029. var {
  43030. properties: _properties,
  43031. newProperties: _newProperties
  43032. } = op;
  43033. if (_properties == null) {
  43034. return _objectSpread$2({}, op, {
  43035. properties: _newProperties,
  43036. newProperties: null
  43037. });
  43038. } else if (_newProperties == null) {
  43039. return _objectSpread$2({}, op, {
  43040. properties: null,
  43041. newProperties: _properties
  43042. });
  43043. } else {
  43044. return _objectSpread$2({}, op, {
  43045. properties: _newProperties,
  43046. newProperties: _properties
  43047. });
  43048. }
  43049. }
  43050. case 'split_node':
  43051. {
  43052. return _objectSpread$2({}, op, {
  43053. type: 'merge_node',
  43054. path: Path.next(op.path)
  43055. });
  43056. }
  43057. }
  43058. }
  43059. };
  43060. var Path = {
  43061. /**
  43062. * Get a list of ancestor paths for a given path.
  43063. *
  43064. * The paths are sorted from deepest to shallowest ancestor. However, if the
  43065. * `reverse: true` option is passed, they are reversed.
  43066. */
  43067. ancestors(path) {
  43068. var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
  43069. var {
  43070. reverse = false
  43071. } = options;
  43072. var paths = Path.levels(path, options);
  43073. if (reverse) {
  43074. paths = paths.slice(1);
  43075. } else {
  43076. paths = paths.slice(0, -1);
  43077. }
  43078. return paths;
  43079. },
  43080. /**
  43081. * Get the common ancestor path of two paths.
  43082. */
  43083. common(path, another) {
  43084. var common = [];
  43085. for (var i = 0; i < path.length && i < another.length; i++) {
  43086. var av = path[i];
  43087. var bv = another[i];
  43088. if (av !== bv) {
  43089. break;
  43090. }
  43091. common.push(av);
  43092. }
  43093. return common;
  43094. },
  43095. /**
  43096. * Compare a path to another, returning an integer indicating whether the path
  43097. * was before, at, or after the other.
  43098. *
  43099. * Note: Two paths of unequal length can still receive a `0` result if one is
  43100. * directly above or below the other. If you want exact matching, use
  43101. * [[Path.equals]] instead.
  43102. */
  43103. compare(path, another) {
  43104. var min = Math.min(path.length, another.length);
  43105. for (var i = 0; i < min; i++) {
  43106. if (path[i] < another[i]) return -1;
  43107. if (path[i] > another[i]) return 1;
  43108. }
  43109. return 0;
  43110. },
  43111. /**
  43112. * Check if a path ends after one of the indexes in another.
  43113. */
  43114. endsAfter(path, another) {
  43115. var i = path.length - 1;
  43116. var as = path.slice(0, i);
  43117. var bs = another.slice(0, i);
  43118. var av = path[i];
  43119. var bv = another[i];
  43120. return Path.equals(as, bs) && av > bv;
  43121. },
  43122. /**
  43123. * Check if a path ends at one of the indexes in another.
  43124. */
  43125. endsAt(path, another) {
  43126. var i = path.length;
  43127. var as = path.slice(0, i);
  43128. var bs = another.slice(0, i);
  43129. return Path.equals(as, bs);
  43130. },
  43131. /**
  43132. * Check if a path ends before one of the indexes in another.
  43133. */
  43134. endsBefore(path, another) {
  43135. var i = path.length - 1;
  43136. var as = path.slice(0, i);
  43137. var bs = another.slice(0, i);
  43138. var av = path[i];
  43139. var bv = another[i];
  43140. return Path.equals(as, bs) && av < bv;
  43141. },
  43142. /**
  43143. * Check if a path is exactly equal to another.
  43144. */
  43145. equals(path, another) {
  43146. return path.length === another.length && path.every((n, i) => n === another[i]);
  43147. },
  43148. /**
  43149. * Check if a path is after another.
  43150. */
  43151. isAfter(path, another) {
  43152. return Path.compare(path, another) === 1;
  43153. },
  43154. /**
  43155. * Check if a path is an ancestor of another.
  43156. */
  43157. isAncestor(path, another) {
  43158. return path.length < another.length && Path.compare(path, another) === 0;
  43159. },
  43160. /**
  43161. * Check if a path is before another.
  43162. */
  43163. isBefore(path, another) {
  43164. return Path.compare(path, another) === -1;
  43165. },
  43166. /**
  43167. * Check if a path is a child of another.
  43168. */
  43169. isChild(path, another) {
  43170. return path.length === another.length + 1 && Path.compare(path, another) === 0;
  43171. },
  43172. /**
  43173. * Check if a path is equal to or an ancestor of another.
  43174. */
  43175. isCommon(path, another) {
  43176. return path.length <= another.length && Path.compare(path, another) === 0;
  43177. },
  43178. /**
  43179. * Check if a path is a descendant of another.
  43180. */
  43181. isDescendant(path, another) {
  43182. return path.length > another.length && Path.compare(path, another) === 0;
  43183. },
  43184. /**
  43185. * Check if a path is the parent of another.
  43186. */
  43187. isParent(path, another) {
  43188. return path.length + 1 === another.length && Path.compare(path, another) === 0;
  43189. },
  43190. /**
  43191. * Check is a value implements the `Path` interface.
  43192. */
  43193. isPath(value) {
  43194. return Array.isArray(value) && (value.length === 0 || typeof value[0] === 'number');
  43195. },
  43196. /**
  43197. * Check if a path is a sibling of another.
  43198. */
  43199. isSibling(path, another) {
  43200. if (path.length !== another.length) {
  43201. return false;
  43202. }
  43203. var as = path.slice(0, -1);
  43204. var bs = another.slice(0, -1);
  43205. var al = path[path.length - 1];
  43206. var bl = another[another.length - 1];
  43207. return al !== bl && Path.equals(as, bs);
  43208. },
  43209. /**
  43210. * Get a list of paths at every level down to a path. Note: this is the same
  43211. * as `Path.ancestors`, but including the path itself.
  43212. *
  43213. * The paths are sorted from shallowest to deepest. However, if the `reverse:
  43214. * true` option is passed, they are reversed.
  43215. */
  43216. levels(path) {
  43217. var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
  43218. var {
  43219. reverse = false
  43220. } = options;
  43221. var list = [];
  43222. for (var i = 0; i <= path.length; i++) {
  43223. list.push(path.slice(0, i));
  43224. }
  43225. if (reverse) {
  43226. list.reverse();
  43227. }
  43228. return list;
  43229. },
  43230. /**
  43231. * Given a path, get the path to the next sibling node.
  43232. */
  43233. next(path) {
  43234. if (path.length === 0) {
  43235. throw new Error("Cannot get the next path of a root path [".concat(path, "], because it has no next index."));
  43236. }
  43237. var last = path[path.length - 1];
  43238. return path.slice(0, -1).concat(last + 1);
  43239. },
  43240. /**
  43241. * Given a path, return a new path referring to the parent node above it.
  43242. */
  43243. parent(path) {
  43244. if (path.length === 0) {
  43245. throw new Error("Cannot get the parent path of the root path [".concat(path, "]."));
  43246. }
  43247. return path.slice(0, -1);
  43248. },
  43249. /**
  43250. * Given a path, get the path to the previous sibling node.
  43251. */
  43252. previous(path) {
  43253. if (path.length === 0) {
  43254. throw new Error("Cannot get the previous path of a root path [".concat(path, "], because it has no previous index."));
  43255. }
  43256. var last = path[path.length - 1];
  43257. if (last <= 0) {
  43258. throw new Error("Cannot get the previous path of a first child path [".concat(path, "] because it would result in a negative index."));
  43259. }
  43260. return path.slice(0, -1).concat(last - 1);
  43261. },
  43262. /**
  43263. * Get a path relative to an ancestor.
  43264. */
  43265. relative(path, ancestor) {
  43266. if (!Path.isAncestor(ancestor, path) && !Path.equals(path, ancestor)) {
  43267. 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."));
  43268. }
  43269. return path.slice(ancestor.length);
  43270. },
  43271. /**
  43272. * Transform a path by an operation.
  43273. */
  43274. transform(path, operation) {
  43275. var options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
  43276. return immer_1.produce(path, p => {
  43277. var {
  43278. affinity = 'forward'
  43279. } = options; // PERF: Exit early if the operation is guaranteed not to have an effect.
  43280. if (path.length === 0) {
  43281. return;
  43282. }
  43283. switch (operation.type) {
  43284. case 'insert_node':
  43285. {
  43286. var {
  43287. path: op
  43288. } = operation;
  43289. if (Path.equals(op, p) || Path.endsBefore(op, p) || Path.isAncestor(op, p)) {
  43290. p[op.length - 1] += 1;
  43291. }
  43292. break;
  43293. }
  43294. case 'remove_node':
  43295. {
  43296. var {
  43297. path: _op
  43298. } = operation;
  43299. if (Path.equals(_op, p) || Path.isAncestor(_op, p)) {
  43300. return null;
  43301. } else if (Path.endsBefore(_op, p)) {
  43302. p[_op.length - 1] -= 1;
  43303. }
  43304. break;
  43305. }
  43306. case 'merge_node':
  43307. {
  43308. var {
  43309. path: _op2,
  43310. position
  43311. } = operation;
  43312. if (Path.equals(_op2, p) || Path.endsBefore(_op2, p)) {
  43313. p[_op2.length - 1] -= 1;
  43314. } else if (Path.isAncestor(_op2, p)) {
  43315. p[_op2.length - 1] -= 1;
  43316. p[_op2.length] += position;
  43317. }
  43318. break;
  43319. }
  43320. case 'split_node':
  43321. {
  43322. var {
  43323. path: _op3,
  43324. position: _position
  43325. } = operation;
  43326. if (Path.equals(_op3, p)) {
  43327. if (affinity === 'forward') {
  43328. p[p.length - 1] += 1;
  43329. } else if (affinity === 'backward') ; else {
  43330. return null;
  43331. }
  43332. } else if (Path.endsBefore(_op3, p)) {
  43333. p[_op3.length - 1] += 1;
  43334. } else if (Path.isAncestor(_op3, p) && path[_op3.length] >= _position) {
  43335. p[_op3.length - 1] += 1;
  43336. p[_op3.length] -= _position;
  43337. }
  43338. break;
  43339. }
  43340. case 'move_node':
  43341. {
  43342. var {
  43343. path: _op4,
  43344. newPath: onp
  43345. } = operation; // If the old and new path are the same, it's a no-op.
  43346. if (Path.equals(_op4, onp)) {
  43347. return;
  43348. }
  43349. if (Path.isAncestor(_op4, p) || Path.equals(_op4, p)) {
  43350. var copy = onp.slice();
  43351. if (Path.endsBefore(_op4, onp) && _op4.length < onp.length) {
  43352. var i = Math.min(onp.length, _op4.length) - 1;
  43353. copy[i] -= 1;
  43354. }
  43355. return copy.concat(p.slice(_op4.length));
  43356. } else if (Path.endsBefore(onp, p) || Path.equals(onp, p) || Path.isAncestor(onp, p)) {
  43357. if (Path.endsBefore(_op4, p)) {
  43358. p[_op4.length - 1] -= 1;
  43359. }
  43360. p[onp.length - 1] += 1;
  43361. } else if (Path.endsBefore(_op4, p)) {
  43362. if (Path.equals(onp, p)) {
  43363. p[onp.length - 1] += 1;
  43364. }
  43365. p[_op4.length - 1] -= 1;
  43366. }
  43367. break;
  43368. }
  43369. }
  43370. });
  43371. }
  43372. };
  43373. var PathRef = {
  43374. /**
  43375. * Transform the path ref's current value by an operation.
  43376. */
  43377. transform(ref, op) {
  43378. var {
  43379. current,
  43380. affinity
  43381. } = ref;
  43382. if (current == null) {
  43383. return;
  43384. }
  43385. var path = Path.transform(current, op, {
  43386. affinity
  43387. });
  43388. ref.current = path;
  43389. if (path == null) {
  43390. ref.unref();
  43391. }
  43392. }
  43393. };
  43394. 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; }
  43395. 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; }
  43396. var Point = {
  43397. /**
  43398. * Compare a point to another, returning an integer indicating whether the
  43399. * point was before, at, or after the other.
  43400. */
  43401. compare(point, another) {
  43402. var result = Path.compare(point.path, another.path);
  43403. if (result === 0) {
  43404. if (point.offset < another.offset) return -1;
  43405. if (point.offset > another.offset) return 1;
  43406. return 0;
  43407. }
  43408. return result;
  43409. },
  43410. /**
  43411. * Check if a point is after another.
  43412. */
  43413. isAfter(point, another) {
  43414. return Point.compare(point, another) === 1;
  43415. },
  43416. /**
  43417. * Check if a point is before another.
  43418. */
  43419. isBefore(point, another) {
  43420. return Point.compare(point, another) === -1;
  43421. },
  43422. /**
  43423. * Check if a point is exactly equal to another.
  43424. */
  43425. equals(point, another) {
  43426. // PERF: ensure the offsets are equal first since they are cheaper to check.
  43427. return point.offset === another.offset && Path.equals(point.path, another.path);
  43428. },
  43429. /**
  43430. * Check if a value implements the `Point` interface.
  43431. */
  43432. isPoint(value) {
  43433. return isPlainObject(value) && typeof value.offset === 'number' && Path.isPath(value.path);
  43434. },
  43435. /**
  43436. * Transform a point by an operation.
  43437. */
  43438. transform(point, op) {
  43439. var options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
  43440. return immer_1.produce(point, p => {
  43441. var {
  43442. affinity = 'forward'
  43443. } = options;
  43444. var {
  43445. path,
  43446. offset
  43447. } = p;
  43448. switch (op.type) {
  43449. case 'insert_node':
  43450. case 'move_node':
  43451. {
  43452. p.path = Path.transform(path, op, options);
  43453. break;
  43454. }
  43455. case 'insert_text':
  43456. {
  43457. if (Path.equals(op.path, path) && op.offset <= offset) {
  43458. p.offset += op.text.length;
  43459. }
  43460. break;
  43461. }
  43462. case 'merge_node':
  43463. {
  43464. if (Path.equals(op.path, path)) {
  43465. p.offset += op.position;
  43466. }
  43467. p.path = Path.transform(path, op, options);
  43468. break;
  43469. }
  43470. case 'remove_text':
  43471. {
  43472. if (Path.equals(op.path, path) && op.offset <= offset) {
  43473. p.offset -= Math.min(offset - op.offset, op.text.length);
  43474. }
  43475. break;
  43476. }
  43477. case 'remove_node':
  43478. {
  43479. if (Path.equals(op.path, path) || Path.isAncestor(op.path, path)) {
  43480. return null;
  43481. }
  43482. p.path = Path.transform(path, op, options);
  43483. break;
  43484. }
  43485. case 'split_node':
  43486. {
  43487. if (Path.equals(op.path, path)) {
  43488. if (op.position === offset && affinity == null) {
  43489. return null;
  43490. } else if (op.position < offset || op.position === offset && affinity === 'forward') {
  43491. p.offset -= op.position;
  43492. p.path = Path.transform(path, op, _objectSpread$3({}, options, {
  43493. affinity: 'forward'
  43494. }));
  43495. }
  43496. } else {
  43497. p.path = Path.transform(path, op, options);
  43498. }
  43499. break;
  43500. }
  43501. }
  43502. });
  43503. }
  43504. };
  43505. var PointRef = {
  43506. /**
  43507. * Transform the point ref's current value by an operation.
  43508. */
  43509. transform(ref, op) {
  43510. var {
  43511. current,
  43512. affinity
  43513. } = ref;
  43514. if (current == null) {
  43515. return;
  43516. }
  43517. var point = Point.transform(current, op, {
  43518. affinity
  43519. });
  43520. ref.current = point;
  43521. if (point == null) {
  43522. ref.unref();
  43523. }
  43524. }
  43525. };
  43526. 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; }
  43527. 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; }
  43528. var Range = {
  43529. /**
  43530. * Get the start and end points of a range, in the order in which they appear
  43531. * in the document.
  43532. */
  43533. edges(range) {
  43534. var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
  43535. var {
  43536. reverse = false
  43537. } = options;
  43538. var {
  43539. anchor,
  43540. focus
  43541. } = range;
  43542. return Range.isBackward(range) === reverse ? [anchor, focus] : [focus, anchor];
  43543. },
  43544. /**
  43545. * Get the end point of a range.
  43546. */
  43547. end(range) {
  43548. var [, end] = Range.edges(range);
  43549. return end;
  43550. },
  43551. /**
  43552. * Check if a range is exactly equal to another.
  43553. */
  43554. equals(range, another) {
  43555. return Point.equals(range.anchor, another.anchor) && Point.equals(range.focus, another.focus);
  43556. },
  43557. /**
  43558. * Check if a range includes a path, a point or part of another range.
  43559. */
  43560. includes(range, target) {
  43561. if (Range.isRange(target)) {
  43562. if (Range.includes(range, target.anchor) || Range.includes(range, target.focus)) {
  43563. return true;
  43564. }
  43565. var [rs, re] = Range.edges(range);
  43566. var [ts, te] = Range.edges(target);
  43567. return Point.isBefore(rs, ts) && Point.isAfter(re, te);
  43568. }
  43569. var [start, end] = Range.edges(range);
  43570. var isAfterStart = false;
  43571. var isBeforeEnd = false;
  43572. if (Point.isPoint(target)) {
  43573. isAfterStart = Point.compare(target, start) >= 0;
  43574. isBeforeEnd = Point.compare(target, end) <= 0;
  43575. } else {
  43576. isAfterStart = Path.compare(target, start.path) >= 0;
  43577. isBeforeEnd = Path.compare(target, end.path) <= 0;
  43578. }
  43579. return isAfterStart && isBeforeEnd;
  43580. },
  43581. /**
  43582. * Get the intersection of a range with another.
  43583. */
  43584. intersection(range, another) {
  43585. var rest = _objectWithoutProperties(range, ["anchor", "focus"]);
  43586. var [s1, e1] = Range.edges(range);
  43587. var [s2, e2] = Range.edges(another);
  43588. var start = Point.isBefore(s1, s2) ? s2 : s1;
  43589. var end = Point.isBefore(e1, e2) ? e1 : e2;
  43590. if (Point.isBefore(end, start)) {
  43591. return null;
  43592. } else {
  43593. return _objectSpread$4({
  43594. anchor: start,
  43595. focus: end
  43596. }, rest);
  43597. }
  43598. },
  43599. /**
  43600. * Check if a range is backward, meaning that its anchor point appears in the
  43601. * document _after_ its focus point.
  43602. */
  43603. isBackward(range) {
  43604. var {
  43605. anchor,
  43606. focus
  43607. } = range;
  43608. return Point.isAfter(anchor, focus);
  43609. },
  43610. /**
  43611. * Check if a range is collapsed, meaning that both its anchor and focus
  43612. * points refer to the exact same position in the document.
  43613. */
  43614. isCollapsed(range) {
  43615. var {
  43616. anchor,
  43617. focus
  43618. } = range;
  43619. return Point.equals(anchor, focus);
  43620. },
  43621. /**
  43622. * Check if a range is expanded.
  43623. *
  43624. * This is the opposite of [[Range.isCollapsed]] and is provided for legibility.
  43625. */
  43626. isExpanded(range) {
  43627. return !Range.isCollapsed(range);
  43628. },
  43629. /**
  43630. * Check if a range is forward.
  43631. *
  43632. * This is the opposite of [[Range.isBackward]] and is provided for legibility.
  43633. */
  43634. isForward(range) {
  43635. return !Range.isBackward(range);
  43636. },
  43637. /**
  43638. * Check if a value implements the [[Range]] interface.
  43639. */
  43640. isRange(value) {
  43641. return isPlainObject(value) && Point.isPoint(value.anchor) && Point.isPoint(value.focus);
  43642. },
  43643. /**
  43644. * Iterate through all of the point entries in a range.
  43645. */
  43646. *points(range) {
  43647. yield [range.anchor, 'anchor'];
  43648. yield [range.focus, 'focus'];
  43649. },
  43650. /**
  43651. * Get the start point of a range.
  43652. */
  43653. start(range) {
  43654. var [start] = Range.edges(range);
  43655. return start;
  43656. },
  43657. /**
  43658. * Transform a range by an operation.
  43659. */
  43660. transform(range, op, options) {
  43661. var {
  43662. affinity = 'inward'
  43663. } = options;
  43664. var affinityAnchor;
  43665. var affinityFocus;
  43666. if (affinity === 'inward') {
  43667. if (Range.isForward(range)) {
  43668. affinityAnchor = 'forward';
  43669. affinityFocus = 'backward';
  43670. } else {
  43671. affinityAnchor = 'backward';
  43672. affinityFocus = 'forward';
  43673. }
  43674. } else if (affinity === 'outward') {
  43675. if (Range.isForward(range)) {
  43676. affinityAnchor = 'backward';
  43677. affinityFocus = 'forward';
  43678. } else {
  43679. affinityAnchor = 'forward';
  43680. affinityFocus = 'backward';
  43681. }
  43682. } else {
  43683. affinityAnchor = affinity;
  43684. affinityFocus = affinity;
  43685. }
  43686. return immer_1.produce(range, r => {
  43687. var anchor = Point.transform(r.anchor, op, {
  43688. affinity: affinityAnchor
  43689. });
  43690. var focus = Point.transform(r.focus, op, {
  43691. affinity: affinityFocus
  43692. });
  43693. if (!anchor || !focus) {
  43694. return null;
  43695. }
  43696. r.anchor = anchor;
  43697. r.focus = focus;
  43698. });
  43699. }
  43700. };
  43701. var RangeRef = {
  43702. /**
  43703. * Transform the range ref's current value by an operation.
  43704. */
  43705. transform(ref, op) {
  43706. var {
  43707. current,
  43708. affinity
  43709. } = ref;
  43710. if (current == null) {
  43711. return;
  43712. }
  43713. var path = Range.transform(current, op, {
  43714. affinity
  43715. });
  43716. ref.current = path;
  43717. if (path == null) {
  43718. ref.unref();
  43719. }
  43720. }
  43721. };
  43722. 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; }
  43723. 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; }
  43724. var Text = {
  43725. /**
  43726. * Check if two text nodes are equal.
  43727. */
  43728. equals(text, another) {
  43729. var options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
  43730. var {
  43731. loose = false
  43732. } = options;
  43733. for (var key in text) {
  43734. if (loose && key === 'text') {
  43735. continue;
  43736. }
  43737. if (text[key] !== another[key]) {
  43738. return false;
  43739. }
  43740. }
  43741. for (var _key in another) {
  43742. if (loose && _key === 'text') {
  43743. continue;
  43744. }
  43745. if (text[_key] !== another[_key]) {
  43746. return false;
  43747. }
  43748. }
  43749. return true;
  43750. },
  43751. /**
  43752. * Check if a value implements the `Text` interface.
  43753. */
  43754. isText(value) {
  43755. return isPlainObject(value) && typeof value.text === 'string';
  43756. },
  43757. /**
  43758. * Check if a value is a list of `Text` objects.
  43759. */
  43760. isTextList(value) {
  43761. return Array.isArray(value) && (value.length === 0 || Text.isText(value[0]));
  43762. },
  43763. /**
  43764. * Check if an text matches set of properties.
  43765. *
  43766. * Note: this is for matching custom properties, and it does not ensure that
  43767. * the `text` property are two nodes equal.
  43768. */
  43769. matches(text, props) {
  43770. for (var key in props) {
  43771. if (key === 'text') {
  43772. continue;
  43773. }
  43774. if (text[key] !== props[key]) {
  43775. return false;
  43776. }
  43777. }
  43778. return true;
  43779. },
  43780. /**
  43781. * Get the leaves for a text node given decorations.
  43782. */
  43783. decorations(node, decorations) {
  43784. var leaves = [_objectSpread$5({}, node)];
  43785. for (var dec of decorations) {
  43786. var rest = _objectWithoutProperties(dec, ["anchor", "focus"]);
  43787. var [start, end] = Range.edges(dec);
  43788. var next = [];
  43789. var o = 0;
  43790. for (var leaf of leaves) {
  43791. var {
  43792. length
  43793. } = leaf.text;
  43794. var offset = o;
  43795. o += length; // If the range encompases the entire leaf, add the range.
  43796. if (start.offset <= offset && end.offset >= offset + length) {
  43797. Object.assign(leaf, rest);
  43798. next.push(leaf);
  43799. continue;
  43800. } // If the range starts after the leaf, or ends before it, continue.
  43801. if (start.offset > offset + length || end.offset < offset || end.offset === offset && offset !== 0) {
  43802. next.push(leaf);
  43803. continue;
  43804. } // Otherwise we need to split the leaf, at the start, end, or both,
  43805. // and add the range to the middle intersecting section. Do the end
  43806. // split first since we don't need to update the offset that way.
  43807. var middle = leaf;
  43808. var before = void 0;
  43809. var after = void 0;
  43810. if (end.offset < offset + length) {
  43811. var off = end.offset - offset;
  43812. after = _objectSpread$5({}, middle, {
  43813. text: middle.text.slice(off)
  43814. });
  43815. middle = _objectSpread$5({}, middle, {
  43816. text: middle.text.slice(0, off)
  43817. });
  43818. }
  43819. if (start.offset > offset) {
  43820. var _off = start.offset - offset;
  43821. before = _objectSpread$5({}, middle, {
  43822. text: middle.text.slice(0, _off)
  43823. });
  43824. middle = _objectSpread$5({}, middle, {
  43825. text: middle.text.slice(_off)
  43826. });
  43827. }
  43828. Object.assign(middle, rest);
  43829. if (before) {
  43830. next.push(before);
  43831. }
  43832. next.push(middle);
  43833. if (after) {
  43834. next.push(after);
  43835. }
  43836. }
  43837. leaves = next;
  43838. }
  43839. return leaves;
  43840. }
  43841. };
  43842. 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; }
  43843. 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; }
  43844. var GeneralTransforms = {
  43845. /**
  43846. * Transform the editor by an operation.
  43847. */
  43848. transform(editor, op) {
  43849. editor.children = immer_1.createDraft(editor.children);
  43850. var selection = editor.selection && immer_1.createDraft(editor.selection);
  43851. switch (op.type) {
  43852. case 'insert_node':
  43853. {
  43854. var {
  43855. path,
  43856. node
  43857. } = op;
  43858. var parent = Node.parent(editor, path);
  43859. var index = path[path.length - 1];
  43860. parent.children.splice(index, 0, node);
  43861. if (selection) {
  43862. for (var [point, key] of Range.points(selection)) {
  43863. selection[key] = Point.transform(point, op);
  43864. }
  43865. }
  43866. break;
  43867. }
  43868. case 'insert_text':
  43869. {
  43870. var {
  43871. path: _path,
  43872. offset,
  43873. text
  43874. } = op;
  43875. var _node = Node.leaf(editor, _path);
  43876. var before = _node.text.slice(0, offset);
  43877. var after = _node.text.slice(offset);
  43878. _node.text = before + text + after;
  43879. if (selection) {
  43880. for (var [_point, _key] of Range.points(selection)) {
  43881. selection[_key] = Point.transform(_point, op);
  43882. }
  43883. }
  43884. break;
  43885. }
  43886. case 'merge_node':
  43887. {
  43888. var {
  43889. path: _path2
  43890. } = op;
  43891. var _node2 = Node.get(editor, _path2);
  43892. var prevPath = Path.previous(_path2);
  43893. var prev = Node.get(editor, prevPath);
  43894. var _parent = Node.parent(editor, _path2);
  43895. var _index = _path2[_path2.length - 1];
  43896. if (Text.isText(_node2) && Text.isText(prev)) {
  43897. prev.text += _node2.text;
  43898. } else if (!Text.isText(_node2) && !Text.isText(prev)) {
  43899. prev.children.push(..._node2.children);
  43900. } else {
  43901. throw new Error("Cannot apply a \"merge_node\" operation at path [".concat(_path2, "] to nodes of different interaces: ").concat(_node2, " ").concat(prev));
  43902. }
  43903. _parent.children.splice(_index, 1);
  43904. if (selection) {
  43905. for (var [_point2, _key2] of Range.points(selection)) {
  43906. selection[_key2] = Point.transform(_point2, op);
  43907. }
  43908. }
  43909. break;
  43910. }
  43911. case 'move_node':
  43912. {
  43913. var {
  43914. path: _path3,
  43915. newPath
  43916. } = op;
  43917. if (Path.isAncestor(_path3, newPath)) {
  43918. throw new Error("Cannot move a path [".concat(_path3, "] to new path [").concat(newPath, "] because the destination is inside itself."));
  43919. }
  43920. var _node3 = Node.get(editor, _path3);
  43921. var _parent2 = Node.parent(editor, _path3);
  43922. var _index2 = _path3[_path3.length - 1]; // This is tricky, but since the `path` and `newPath` both refer to
  43923. // the same snapshot in time, there's a mismatch. After either
  43924. // removing the original position, the second step's path can be out
  43925. // of date. So instead of using the `op.newPath` directly, we
  43926. // transform `op.path` to ascertain what the `newPath` would be after
  43927. // the operation was applied.
  43928. _parent2.children.splice(_index2, 1);
  43929. var truePath = Path.transform(_path3, op);
  43930. var newParent = Node.get(editor, Path.parent(truePath));
  43931. var newIndex = truePath[truePath.length - 1];
  43932. newParent.children.splice(newIndex, 0, _node3);
  43933. if (selection) {
  43934. for (var [_point3, _key3] of Range.points(selection)) {
  43935. selection[_key3] = Point.transform(_point3, op);
  43936. }
  43937. }
  43938. break;
  43939. }
  43940. case 'remove_node':
  43941. {
  43942. var {
  43943. path: _path4
  43944. } = op;
  43945. var _index3 = _path4[_path4.length - 1];
  43946. var _parent3 = Node.parent(editor, _path4);
  43947. _parent3.children.splice(_index3, 1); // Transform all of the points in the value, but if the point was in the
  43948. // node that was removed we need to update the range or remove it.
  43949. if (selection) {
  43950. for (var [_point4, _key4] of Range.points(selection)) {
  43951. var result = Point.transform(_point4, op);
  43952. if (selection != null && result != null) {
  43953. selection[_key4] = result;
  43954. } else {
  43955. var _prev = void 0;
  43956. var next = void 0;
  43957. for (var [n, p] of Node.texts(editor)) {
  43958. if (Path.compare(p, _path4) === -1) {
  43959. _prev = [n, p];
  43960. } else {
  43961. next = [n, p];
  43962. break;
  43963. }
  43964. }
  43965. if (_prev) {
  43966. _point4.path = _prev[1];
  43967. _point4.offset = _prev[0].text.length;
  43968. } else if (next) {
  43969. _point4.path = next[1];
  43970. _point4.offset = 0;
  43971. } else {
  43972. selection = null;
  43973. }
  43974. }
  43975. }
  43976. }
  43977. break;
  43978. }
  43979. case 'remove_text':
  43980. {
  43981. var {
  43982. path: _path5,
  43983. offset: _offset,
  43984. text: _text
  43985. } = op;
  43986. var _node4 = Node.leaf(editor, _path5);
  43987. var _before = _node4.text.slice(0, _offset);
  43988. var _after = _node4.text.slice(_offset + _text.length);
  43989. _node4.text = _before + _after;
  43990. if (selection) {
  43991. for (var [_point5, _key5] of Range.points(selection)) {
  43992. selection[_key5] = Point.transform(_point5, op);
  43993. }
  43994. }
  43995. break;
  43996. }
  43997. case 'set_node':
  43998. {
  43999. var {
  44000. path: _path6,
  44001. newProperties
  44002. } = op;
  44003. if (_path6.length === 0) {
  44004. throw new Error("Cannot set properties on the root node!");
  44005. }
  44006. var _node5 = Node.get(editor, _path6);
  44007. for (var _key6 in newProperties) {
  44008. if (_key6 === 'children' || _key6 === 'text') {
  44009. throw new Error("Cannot set the \"".concat(_key6, "\" property of nodes!"));
  44010. }
  44011. var value = newProperties[_key6];
  44012. if (value == null) {
  44013. delete _node5[_key6];
  44014. } else {
  44015. _node5[_key6] = value;
  44016. }
  44017. }
  44018. break;
  44019. }
  44020. case 'set_selection':
  44021. {
  44022. var {
  44023. newProperties: _newProperties
  44024. } = op;
  44025. if (_newProperties == null) {
  44026. selection = _newProperties;
  44027. } else if (selection == null) {
  44028. if (!Range.isRange(_newProperties)) {
  44029. throw new Error("Cannot apply an incomplete \"set_selection\" operation properties ".concat(JSON.stringify(_newProperties), " when there is no current selection."));
  44030. }
  44031. selection = _newProperties;
  44032. } else {
  44033. Object.assign(selection, _newProperties);
  44034. }
  44035. break;
  44036. }
  44037. case 'split_node':
  44038. {
  44039. var {
  44040. path: _path7,
  44041. position,
  44042. properties
  44043. } = op;
  44044. if (_path7.length === 0) {
  44045. throw new Error("Cannot apply a \"split_node\" operation at path [".concat(_path7, "] because the root node cannot be split."));
  44046. }
  44047. var _node6 = Node.get(editor, _path7);
  44048. var _parent4 = Node.parent(editor, _path7);
  44049. var _index4 = _path7[_path7.length - 1];
  44050. var newNode;
  44051. if (Text.isText(_node6)) {
  44052. var _before2 = _node6.text.slice(0, position);
  44053. var _after2 = _node6.text.slice(position);
  44054. _node6.text = _before2;
  44055. newNode = _objectSpread$6({}, _node6, {}, properties, {
  44056. text: _after2
  44057. });
  44058. } else {
  44059. var _before3 = _node6.children.slice(0, position);
  44060. var _after3 = _node6.children.slice(position);
  44061. _node6.children = _before3;
  44062. newNode = _objectSpread$6({}, _node6, {}, properties, {
  44063. children: _after3
  44064. });
  44065. }
  44066. _parent4.children.splice(_index4 + 1, 0, newNode);
  44067. if (selection) {
  44068. for (var [_point6, _key7] of Range.points(selection)) {
  44069. selection[_key7] = Point.transform(_point6, op);
  44070. }
  44071. }
  44072. break;
  44073. }
  44074. }
  44075. editor.children = immer_1.finishDraft(editor.children);
  44076. if (selection) {
  44077. editor.selection = immer_1.isDraft(selection) ? immer_1.finishDraft(selection) : selection;
  44078. } else {
  44079. editor.selection = null;
  44080. }
  44081. }
  44082. };
  44083. 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; }
  44084. 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; }
  44085. var NodeTransforms = {
  44086. /**
  44087. * Insert nodes at a specific location in the Editor.
  44088. */
  44089. insertNodes(editor, nodes) {
  44090. var options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
  44091. Editor.withoutNormalizing(editor, () => {
  44092. var {
  44093. hanging = false,
  44094. voids = false,
  44095. mode = 'lowest'
  44096. } = options;
  44097. var {
  44098. at,
  44099. match,
  44100. select
  44101. } = options;
  44102. if (Node.isNode(nodes)) {
  44103. nodes = [nodes];
  44104. }
  44105. if (nodes.length === 0) {
  44106. return;
  44107. }
  44108. var [node] = nodes; // By default, use the selection as the target location. But if there is
  44109. // no selection, insert at the end of the document since that is such a
  44110. // common use case when inserting from a non-selected state.
  44111. if (!at) {
  44112. if (editor.selection) {
  44113. at = editor.selection;
  44114. } else if (editor.children.length > 0) {
  44115. at = Editor.end(editor, []);
  44116. } else {
  44117. at = [0];
  44118. }
  44119. select = true;
  44120. }
  44121. if (select == null) {
  44122. select = false;
  44123. }
  44124. if (Range.isRange(at)) {
  44125. if (!hanging) {
  44126. at = Editor.unhangRange(editor, at);
  44127. }
  44128. if (Range.isCollapsed(at)) {
  44129. at = at.anchor;
  44130. } else {
  44131. var [, end] = Range.edges(at);
  44132. var pointRef = Editor.pointRef(editor, end);
  44133. Transforms.delete(editor, {
  44134. at
  44135. });
  44136. at = pointRef.unref();
  44137. }
  44138. }
  44139. if (Point.isPoint(at)) {
  44140. if (match == null) {
  44141. if (Text.isText(node)) {
  44142. match = n => Text.isText(n);
  44143. } else if (editor.isInline(node)) {
  44144. match = n => Text.isText(n) || Editor.isInline(editor, n);
  44145. } else {
  44146. match = n => Editor.isBlock(editor, n);
  44147. }
  44148. }
  44149. var [entry] = Editor.nodes(editor, {
  44150. at: at.path,
  44151. match,
  44152. mode,
  44153. voids
  44154. });
  44155. if (entry) {
  44156. var [, _matchPath] = entry;
  44157. var pathRef = Editor.pathRef(editor, _matchPath);
  44158. var isAtEnd = Editor.isEnd(editor, at, _matchPath);
  44159. Transforms.splitNodes(editor, {
  44160. at,
  44161. match,
  44162. mode,
  44163. voids
  44164. });
  44165. var path = pathRef.unref();
  44166. at = isAtEnd ? Path.next(path) : path;
  44167. } else {
  44168. return;
  44169. }
  44170. }
  44171. var parentPath = Path.parent(at);
  44172. var index = at[at.length - 1];
  44173. if (!voids && Editor.void(editor, {
  44174. at: parentPath
  44175. })) {
  44176. return;
  44177. }
  44178. for (var _node of nodes) {
  44179. var _path = parentPath.concat(index);
  44180. index++;
  44181. editor.apply({
  44182. type: 'insert_node',
  44183. path: _path,
  44184. node: _node
  44185. });
  44186. }
  44187. if (select) {
  44188. var point = Editor.end(editor, at);
  44189. if (point) {
  44190. Transforms.select(editor, point);
  44191. }
  44192. }
  44193. });
  44194. },
  44195. /**
  44196. * Lift nodes at a specific location upwards in the document tree, splitting
  44197. * their parent in two if necessary.
  44198. */
  44199. liftNodes(editor) {
  44200. var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
  44201. Editor.withoutNormalizing(editor, () => {
  44202. var {
  44203. at = editor.selection,
  44204. mode = 'lowest',
  44205. voids = false
  44206. } = options;
  44207. var {
  44208. match
  44209. } = options;
  44210. if (match == null) {
  44211. match = Path.isPath(at) ? matchPath(editor, at) : n => Editor.isBlock(editor, n);
  44212. }
  44213. if (!at) {
  44214. return;
  44215. }
  44216. var matches = Editor.nodes(editor, {
  44217. at,
  44218. match,
  44219. mode,
  44220. voids
  44221. });
  44222. var pathRefs = Array.from(matches, (_ref) => {
  44223. var [, p] = _ref;
  44224. return Editor.pathRef(editor, p);
  44225. });
  44226. for (var pathRef of pathRefs) {
  44227. var path = pathRef.unref();
  44228. if (path.length < 2) {
  44229. throw new Error("Cannot lift node at a path [".concat(path, "] because it has a depth of less than `2`."));
  44230. }
  44231. var [parent, parentPath] = Editor.node(editor, Path.parent(path));
  44232. var index = path[path.length - 1];
  44233. var {
  44234. length
  44235. } = parent.children;
  44236. if (length === 1) {
  44237. var toPath = Path.next(parentPath);
  44238. Transforms.moveNodes(editor, {
  44239. at: path,
  44240. to: toPath,
  44241. voids
  44242. });
  44243. Transforms.removeNodes(editor, {
  44244. at: parentPath,
  44245. voids
  44246. });
  44247. } else if (index === 0) {
  44248. Transforms.moveNodes(editor, {
  44249. at: path,
  44250. to: parentPath,
  44251. voids
  44252. });
  44253. } else if (index === length - 1) {
  44254. var _toPath = Path.next(parentPath);
  44255. Transforms.moveNodes(editor, {
  44256. at: path,
  44257. to: _toPath,
  44258. voids
  44259. });
  44260. } else {
  44261. var splitPath = Path.next(path);
  44262. var _toPath2 = Path.next(parentPath);
  44263. Transforms.splitNodes(editor, {
  44264. at: splitPath,
  44265. voids
  44266. });
  44267. Transforms.moveNodes(editor, {
  44268. at: path,
  44269. to: _toPath2,
  44270. voids
  44271. });
  44272. }
  44273. }
  44274. });
  44275. },
  44276. /**
  44277. * Merge a node at a location with the previous node of the same depth,
  44278. * removing any empty containing nodes after the merge if necessary.
  44279. */
  44280. mergeNodes(editor) {
  44281. var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
  44282. Editor.withoutNormalizing(editor, () => {
  44283. var {
  44284. match,
  44285. at = editor.selection
  44286. } = options;
  44287. var {
  44288. hanging = false,
  44289. voids = false,
  44290. mode = 'lowest'
  44291. } = options;
  44292. if (!at) {
  44293. return;
  44294. }
  44295. if (match == null) {
  44296. if (Path.isPath(at)) {
  44297. var [parent] = Editor.parent(editor, at);
  44298. match = n => parent.children.includes(n);
  44299. } else {
  44300. match = n => Editor.isBlock(editor, n);
  44301. }
  44302. }
  44303. if (!hanging && Range.isRange(at)) {
  44304. at = Editor.unhangRange(editor, at);
  44305. }
  44306. if (Range.isRange(at)) {
  44307. if (Range.isCollapsed(at)) {
  44308. at = at.anchor;
  44309. } else {
  44310. var [, end] = Range.edges(at);
  44311. var pointRef = Editor.pointRef(editor, end);
  44312. Transforms.delete(editor, {
  44313. at
  44314. });
  44315. at = pointRef.unref();
  44316. if (options.at == null) {
  44317. Transforms.select(editor, at);
  44318. }
  44319. }
  44320. }
  44321. var [current] = Editor.nodes(editor, {
  44322. at,
  44323. match,
  44324. voids,
  44325. mode
  44326. });
  44327. var prev = Editor.previous(editor, {
  44328. at,
  44329. match,
  44330. voids,
  44331. mode
  44332. });
  44333. if (!current || !prev) {
  44334. return;
  44335. }
  44336. var [node, path] = current;
  44337. var [prevNode, prevPath] = prev;
  44338. if (path.length === 0 || prevPath.length === 0) {
  44339. return;
  44340. }
  44341. var newPath = Path.next(prevPath);
  44342. var commonPath = Path.common(path, prevPath);
  44343. var isPreviousSibling = Path.isSibling(path, prevPath);
  44344. var levels = Array.from(Editor.levels(editor, {
  44345. at: path
  44346. }), (_ref2) => {
  44347. var [n] = _ref2;
  44348. return n;
  44349. }).slice(commonPath.length).slice(0, -1); // Determine if the merge will leave an ancestor of the path empty as a
  44350. // result, in which case we'll want to remove it after merging.
  44351. var emptyAncestor = Editor.above(editor, {
  44352. at: path,
  44353. mode: 'highest',
  44354. match: n => levels.includes(n) && Element.isElement(n) && n.children.length === 1
  44355. });
  44356. var emptyRef = emptyAncestor && Editor.pathRef(editor, emptyAncestor[1]);
  44357. var properties;
  44358. var position; // Ensure that the nodes are equivalent, and figure out what the position
  44359. // and extra properties of the merge will be.
  44360. if (Text.isText(node) && Text.isText(prevNode)) {
  44361. var rest = _objectWithoutProperties(node, ["text"]);
  44362. position = prevNode.text.length;
  44363. properties = rest;
  44364. } else if (Element.isElement(node) && Element.isElement(prevNode)) {
  44365. var rest = _objectWithoutProperties(node, ["children"]);
  44366. position = prevNode.children.length;
  44367. properties = rest;
  44368. } else {
  44369. 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)));
  44370. } // If the node isn't already the next sibling of the previous node, move
  44371. // it so that it is before merging.
  44372. if (!isPreviousSibling) {
  44373. Transforms.moveNodes(editor, {
  44374. at: path,
  44375. to: newPath,
  44376. voids
  44377. });
  44378. } // If there was going to be an empty ancestor of the node that was merged,
  44379. // we remove it from the tree.
  44380. if (emptyRef) {
  44381. Transforms.removeNodes(editor, {
  44382. at: emptyRef.current,
  44383. voids
  44384. });
  44385. } // If the target node that we're merging with is empty, remove it instead
  44386. // of merging the two. This is a common rich text editor behavior to
  44387. // prevent losing formatting when deleting entire nodes when you have a
  44388. // hanging selection.
  44389. if (Element.isElement(prevNode) && Editor.isEmpty(editor, prevNode) || Text.isText(prevNode) && prevNode.text === '') {
  44390. Transforms.removeNodes(editor, {
  44391. at: prevPath,
  44392. voids
  44393. });
  44394. } else {
  44395. editor.apply({
  44396. type: 'merge_node',
  44397. path: newPath,
  44398. position,
  44399. target: null,
  44400. properties
  44401. });
  44402. }
  44403. if (emptyRef) {
  44404. emptyRef.unref();
  44405. }
  44406. });
  44407. },
  44408. /**
  44409. * Move the nodes at a location to a new location.
  44410. */
  44411. moveNodes(editor, options) {
  44412. Editor.withoutNormalizing(editor, () => {
  44413. var {
  44414. to,
  44415. at = editor.selection,
  44416. mode = 'lowest',
  44417. voids = false
  44418. } = options;
  44419. var {
  44420. match
  44421. } = options;
  44422. if (!at) {
  44423. return;
  44424. }
  44425. if (match == null) {
  44426. match = Path.isPath(at) ? matchPath(editor, at) : n => Editor.isBlock(editor, n);
  44427. }
  44428. var toRef = Editor.pathRef(editor, to);
  44429. var targets = Editor.nodes(editor, {
  44430. at,
  44431. match,
  44432. mode,
  44433. voids
  44434. });
  44435. var pathRefs = Array.from(targets, (_ref3) => {
  44436. var [, p] = _ref3;
  44437. return Editor.pathRef(editor, p);
  44438. });
  44439. for (var pathRef of pathRefs) {
  44440. var path = pathRef.unref();
  44441. var newPath = toRef.current;
  44442. if (path.length !== 0) {
  44443. editor.apply({
  44444. type: 'move_node',
  44445. path,
  44446. newPath
  44447. });
  44448. }
  44449. }
  44450. toRef.unref();
  44451. });
  44452. },
  44453. /**
  44454. * Remove the nodes at a specific location in the document.
  44455. */
  44456. removeNodes(editor) {
  44457. var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
  44458. Editor.withoutNormalizing(editor, () => {
  44459. var {
  44460. hanging = false,
  44461. voids = false,
  44462. mode = 'lowest'
  44463. } = options;
  44464. var {
  44465. at = editor.selection,
  44466. match
  44467. } = options;
  44468. if (!at) {
  44469. return;
  44470. }
  44471. if (match == null) {
  44472. match = Path.isPath(at) ? matchPath(editor, at) : n => Editor.isBlock(editor, n);
  44473. }
  44474. if (!hanging && Range.isRange(at)) {
  44475. at = Editor.unhangRange(editor, at);
  44476. }
  44477. var depths = Editor.nodes(editor, {
  44478. at,
  44479. match,
  44480. mode,
  44481. voids
  44482. });
  44483. var pathRefs = Array.from(depths, (_ref4) => {
  44484. var [, p] = _ref4;
  44485. return Editor.pathRef(editor, p);
  44486. });
  44487. for (var pathRef of pathRefs) {
  44488. var path = pathRef.unref();
  44489. if (path) {
  44490. var [node] = Editor.node(editor, path);
  44491. editor.apply({
  44492. type: 'remove_node',
  44493. path,
  44494. node
  44495. });
  44496. }
  44497. }
  44498. });
  44499. },
  44500. /**
  44501. * Set new properties on the nodes at a location.
  44502. */
  44503. setNodes(editor, props) {
  44504. var options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
  44505. Editor.withoutNormalizing(editor, () => {
  44506. var {
  44507. match,
  44508. at = editor.selection
  44509. } = options;
  44510. var {
  44511. hanging = false,
  44512. mode = 'lowest',
  44513. split = false,
  44514. voids = false
  44515. } = options;
  44516. if (!at) {
  44517. return;
  44518. }
  44519. if (match == null) {
  44520. match = Path.isPath(at) ? matchPath(editor, at) : n => Editor.isBlock(editor, n);
  44521. }
  44522. if (!hanging && Range.isRange(at)) {
  44523. at = Editor.unhangRange(editor, at);
  44524. }
  44525. if (split && Range.isRange(at)) {
  44526. var rangeRef = Editor.rangeRef(editor, at, {
  44527. affinity: 'inward'
  44528. });
  44529. var [start, end] = Range.edges(at);
  44530. var splitMode = mode === 'lowest' ? 'lowest' : 'highest';
  44531. Transforms.splitNodes(editor, {
  44532. at: end,
  44533. match,
  44534. mode: splitMode,
  44535. voids
  44536. });
  44537. Transforms.splitNodes(editor, {
  44538. at: start,
  44539. match,
  44540. mode: splitMode,
  44541. voids
  44542. });
  44543. at = rangeRef.unref();
  44544. if (options.at == null) {
  44545. Transforms.select(editor, at);
  44546. }
  44547. }
  44548. for (var [node, path] of Editor.nodes(editor, {
  44549. at,
  44550. match,
  44551. mode,
  44552. voids
  44553. })) {
  44554. var properties = {};
  44555. var newProperties = {}; // You can't set properties on the editor node.
  44556. if (path.length === 0) {
  44557. continue;
  44558. }
  44559. for (var k in props) {
  44560. if (k === 'children' || k === 'text') {
  44561. continue;
  44562. }
  44563. if (props[k] !== node[k]) {
  44564. properties[k] = node[k];
  44565. newProperties[k] = props[k];
  44566. }
  44567. }
  44568. if (Object.keys(newProperties).length !== 0) {
  44569. editor.apply({
  44570. type: 'set_node',
  44571. path,
  44572. properties,
  44573. newProperties
  44574. });
  44575. }
  44576. }
  44577. });
  44578. },
  44579. /**
  44580. * Split the nodes at a specific location.
  44581. */
  44582. splitNodes(editor) {
  44583. var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
  44584. Editor.withoutNormalizing(editor, () => {
  44585. var {
  44586. mode = 'lowest',
  44587. voids = false
  44588. } = options;
  44589. var {
  44590. match,
  44591. at = editor.selection,
  44592. height = 0,
  44593. always = false
  44594. } = options;
  44595. if (match == null) {
  44596. match = n => Editor.isBlock(editor, n);
  44597. }
  44598. if (Range.isRange(at)) {
  44599. at = deleteRange(editor, at);
  44600. } // If the target is a path, the default height-skipping and position
  44601. // counters need to account for us potentially splitting at a non-leaf.
  44602. if (Path.isPath(at)) {
  44603. var path = at;
  44604. var point = Editor.point(editor, path);
  44605. var [parent] = Editor.parent(editor, path);
  44606. match = n => n === parent;
  44607. height = point.path.length - path.length + 1;
  44608. at = point;
  44609. always = true;
  44610. }
  44611. if (!at) {
  44612. return;
  44613. }
  44614. var beforeRef = Editor.pointRef(editor, at, {
  44615. affinity: 'backward'
  44616. });
  44617. var [highest] = Editor.nodes(editor, {
  44618. at,
  44619. match,
  44620. mode,
  44621. voids
  44622. });
  44623. if (!highest) {
  44624. return;
  44625. }
  44626. var voidMatch = Editor.void(editor, {
  44627. at,
  44628. mode: 'highest'
  44629. });
  44630. var nudge = 0;
  44631. if (!voids && voidMatch) {
  44632. var [voidNode, voidPath] = voidMatch;
  44633. if (Element.isElement(voidNode) && editor.isInline(voidNode)) {
  44634. var after = Editor.after(editor, voidPath);
  44635. if (!after) {
  44636. var text = {
  44637. text: ''
  44638. };
  44639. var afterPath = Path.next(voidPath);
  44640. Transforms.insertNodes(editor, text, {
  44641. at: afterPath,
  44642. voids
  44643. });
  44644. after = Editor.point(editor, afterPath);
  44645. }
  44646. at = after;
  44647. always = true;
  44648. }
  44649. var siblingHeight = at.path.length - voidPath.length;
  44650. height = siblingHeight + 1;
  44651. always = true;
  44652. }
  44653. var afterRef = Editor.pointRef(editor, at);
  44654. var depth = at.path.length - height;
  44655. var [, highestPath] = highest;
  44656. var lowestPath = at.path.slice(0, depth);
  44657. var position = height === 0 ? at.offset : at.path[depth] + nudge;
  44658. var target = null;
  44659. for (var [node, _path2] of Editor.levels(editor, {
  44660. at: lowestPath,
  44661. reverse: true,
  44662. voids
  44663. })) {
  44664. var split = false;
  44665. if (_path2.length < highestPath.length || _path2.length === 0 || !voids && Editor.isVoid(editor, node)) {
  44666. break;
  44667. }
  44668. var _point = beforeRef.current;
  44669. var isEnd = Editor.isEnd(editor, _point, _path2);
  44670. if (always || !beforeRef || !Editor.isEdge(editor, _point, _path2)) {
  44671. split = true;
  44672. var properties = _objectWithoutProperties(node, ["text", "children"]);
  44673. editor.apply({
  44674. type: 'split_node',
  44675. path: _path2,
  44676. position,
  44677. target,
  44678. properties
  44679. });
  44680. }
  44681. target = position;
  44682. position = _path2[_path2.length - 1] + (split || isEnd ? 1 : 0);
  44683. }
  44684. if (options.at == null) {
  44685. var _point2 = afterRef.current || Editor.end(editor, []);
  44686. Transforms.select(editor, _point2);
  44687. }
  44688. beforeRef.unref();
  44689. afterRef.unref();
  44690. });
  44691. },
  44692. /**
  44693. * Unset properties on the nodes at a location.
  44694. */
  44695. unsetNodes(editor, props) {
  44696. var options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
  44697. if (!Array.isArray(props)) {
  44698. props = [props];
  44699. }
  44700. var obj = {};
  44701. for (var key of props) {
  44702. obj[key] = null;
  44703. }
  44704. Transforms.setNodes(editor, obj, options);
  44705. },
  44706. /**
  44707. * Unwrap the nodes at a location from a parent node, splitting the parent if
  44708. * necessary to ensure that only the content in the range is unwrapped.
  44709. */
  44710. unwrapNodes(editor, options) {
  44711. Editor.withoutNormalizing(editor, () => {
  44712. var {
  44713. mode = 'lowest',
  44714. split = false,
  44715. voids = false
  44716. } = options;
  44717. var {
  44718. at = editor.selection,
  44719. match
  44720. } = options;
  44721. if (!at) {
  44722. return;
  44723. }
  44724. if (match == null) {
  44725. match = Path.isPath(at) ? matchPath(editor, at) : n => Editor.isBlock(editor, n);
  44726. }
  44727. if (Path.isPath(at)) {
  44728. at = Editor.range(editor, at);
  44729. }
  44730. var rangeRef = Range.isRange(at) ? Editor.rangeRef(editor, at) : null;
  44731. var matches = Editor.nodes(editor, {
  44732. at,
  44733. match,
  44734. mode,
  44735. voids
  44736. });
  44737. var pathRefs = Array.from(matches, (_ref5) => {
  44738. var [, p] = _ref5;
  44739. return Editor.pathRef(editor, p);
  44740. });
  44741. var _loop = function _loop(pathRef) {
  44742. var path = pathRef.unref();
  44743. var [node] = Editor.node(editor, path);
  44744. var range = Editor.range(editor, path);
  44745. if (split && rangeRef) {
  44746. range = Range.intersection(rangeRef.current, range);
  44747. }
  44748. Transforms.liftNodes(editor, {
  44749. at: range,
  44750. match: n => node.children.includes(n),
  44751. voids
  44752. });
  44753. };
  44754. for (var pathRef of pathRefs) {
  44755. _loop(pathRef);
  44756. }
  44757. if (rangeRef) {
  44758. rangeRef.unref();
  44759. }
  44760. });
  44761. },
  44762. /**
  44763. * Wrap the nodes at a location in a new container node, splitting the edges
  44764. * of the range first to ensure that only the content in the range is wrapped.
  44765. */
  44766. wrapNodes(editor, element) {
  44767. var options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
  44768. Editor.withoutNormalizing(editor, () => {
  44769. var {
  44770. mode = 'lowest',
  44771. split = false,
  44772. voids = false
  44773. } = options;
  44774. var {
  44775. match,
  44776. at = editor.selection
  44777. } = options;
  44778. if (!at) {
  44779. return;
  44780. }
  44781. if (match == null) {
  44782. if (Path.isPath(at)) {
  44783. match = matchPath(editor, at);
  44784. } else if (editor.isInline(element)) {
  44785. match = n => Editor.isInline(editor, n) || Text.isText(n);
  44786. } else {
  44787. match = n => Editor.isBlock(editor, n);
  44788. }
  44789. }
  44790. if (split && Range.isRange(at)) {
  44791. var [start, end] = Range.edges(at);
  44792. var rangeRef = Editor.rangeRef(editor, at, {
  44793. affinity: 'inward'
  44794. });
  44795. Transforms.splitNodes(editor, {
  44796. at: end,
  44797. match,
  44798. voids
  44799. });
  44800. Transforms.splitNodes(editor, {
  44801. at: start,
  44802. match,
  44803. voids
  44804. });
  44805. at = rangeRef.unref();
  44806. if (options.at == null) {
  44807. Transforms.select(editor, at);
  44808. }
  44809. }
  44810. var roots = Array.from(Editor.nodes(editor, {
  44811. at,
  44812. match: editor.isInline(element) ? n => Editor.isBlock(editor, n) : n => Editor.isEditor(n),
  44813. mode: 'highest',
  44814. voids
  44815. }));
  44816. for (var [, rootPath] of roots) {
  44817. var a = Range.isRange(at) ? Range.intersection(at, Editor.range(editor, rootPath)) : at;
  44818. if (!a) {
  44819. continue;
  44820. }
  44821. var matches = Array.from(Editor.nodes(editor, {
  44822. at: a,
  44823. match,
  44824. mode,
  44825. voids
  44826. }));
  44827. if (matches.length > 0) {
  44828. (function () {
  44829. var [first] = matches;
  44830. var last = matches[matches.length - 1];
  44831. var [, firstPath] = first;
  44832. var [, lastPath] = last;
  44833. var commonPath = Path.equals(firstPath, lastPath) ? Path.parent(firstPath) : Path.common(firstPath, lastPath);
  44834. var range = Editor.range(editor, firstPath, lastPath);
  44835. var [commonNode] = Editor.node(editor, commonPath);
  44836. var depth = commonPath.length + 1;
  44837. var wrapperPath = Path.next(lastPath.slice(0, depth));
  44838. var wrapper = _objectSpread$7({}, element, {
  44839. children: []
  44840. });
  44841. Transforms.insertNodes(editor, wrapper, {
  44842. at: wrapperPath,
  44843. voids
  44844. });
  44845. Transforms.moveNodes(editor, {
  44846. at: range,
  44847. match: n => commonNode.children.includes(n),
  44848. to: wrapperPath.concat(0),
  44849. voids
  44850. });
  44851. })();
  44852. }
  44853. }
  44854. });
  44855. }
  44856. };
  44857. /**
  44858. * Convert a range into a point by deleting it's content.
  44859. */
  44860. var deleteRange = (editor, range) => {
  44861. if (Range.isCollapsed(range)) {
  44862. return range.anchor;
  44863. } else {
  44864. var [, end] = Range.edges(range);
  44865. var pointRef = Editor.pointRef(editor, end);
  44866. Transforms.delete(editor, {
  44867. at: range
  44868. });
  44869. return pointRef.unref();
  44870. }
  44871. };
  44872. var matchPath = (editor, path) => {
  44873. var [node] = Editor.node(editor, path);
  44874. return n => n === node;
  44875. };
  44876. var SelectionTransforms = {
  44877. /**
  44878. * Collapse the selection.
  44879. */
  44880. collapse(editor) {
  44881. var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
  44882. var {
  44883. edge = 'anchor'
  44884. } = options;
  44885. var {
  44886. selection
  44887. } = editor;
  44888. if (!selection) {
  44889. return;
  44890. } else if (edge === 'anchor') {
  44891. Transforms.select(editor, selection.anchor);
  44892. } else if (edge === 'focus') {
  44893. Transforms.select(editor, selection.focus);
  44894. } else if (edge === 'start') {
  44895. var [start] = Range.edges(selection);
  44896. Transforms.select(editor, start);
  44897. } else if (edge === 'end') {
  44898. var [, end] = Range.edges(selection);
  44899. Transforms.select(editor, end);
  44900. }
  44901. },
  44902. /**
  44903. * Unset the selection.
  44904. */
  44905. deselect(editor) {
  44906. var {
  44907. selection
  44908. } = editor;
  44909. if (selection) {
  44910. editor.apply({
  44911. type: 'set_selection',
  44912. properties: selection,
  44913. newProperties: null
  44914. });
  44915. }
  44916. },
  44917. /**
  44918. * Move the selection's point forward or backward.
  44919. */
  44920. move(editor) {
  44921. var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
  44922. var {
  44923. selection
  44924. } = editor;
  44925. var {
  44926. distance = 1,
  44927. unit = 'character',
  44928. reverse = false
  44929. } = options;
  44930. var {
  44931. edge = null
  44932. } = options;
  44933. if (!selection) {
  44934. return;
  44935. }
  44936. if (edge === 'start') {
  44937. edge = Range.isBackward(selection) ? 'focus' : 'anchor';
  44938. }
  44939. if (edge === 'end') {
  44940. edge = Range.isBackward(selection) ? 'anchor' : 'focus';
  44941. }
  44942. var {
  44943. anchor,
  44944. focus
  44945. } = selection;
  44946. var opts = {
  44947. distance,
  44948. unit
  44949. };
  44950. var props = {};
  44951. if (edge == null || edge === 'anchor') {
  44952. var point = reverse ? Editor.before(editor, anchor, opts) : Editor.after(editor, anchor, opts);
  44953. if (point) {
  44954. props.anchor = point;
  44955. }
  44956. }
  44957. if (edge == null || edge === 'focus') {
  44958. var _point = reverse ? Editor.before(editor, focus, opts) : Editor.after(editor, focus, opts);
  44959. if (_point) {
  44960. props.focus = _point;
  44961. }
  44962. }
  44963. Transforms.setSelection(editor, props);
  44964. },
  44965. /**
  44966. * Set the selection to a new value.
  44967. */
  44968. select(editor, target) {
  44969. var {
  44970. selection
  44971. } = editor;
  44972. target = Editor.range(editor, target);
  44973. if (selection) {
  44974. Transforms.setSelection(editor, target);
  44975. return;
  44976. }
  44977. if (!Range.isRange(target)) {
  44978. 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)));
  44979. }
  44980. editor.apply({
  44981. type: 'set_selection',
  44982. properties: selection,
  44983. newProperties: target
  44984. });
  44985. },
  44986. /**
  44987. * Set new properties on one of the selection's points.
  44988. */
  44989. setPoint(editor, props, options) {
  44990. var {
  44991. selection
  44992. } = editor;
  44993. var {
  44994. edge = 'both'
  44995. } = options;
  44996. if (!selection) {
  44997. return;
  44998. }
  44999. if (edge === 'start') {
  45000. edge = Range.isBackward(selection) ? 'focus' : 'anchor';
  45001. }
  45002. if (edge === 'end') {
  45003. edge = Range.isBackward(selection) ? 'anchor' : 'focus';
  45004. }
  45005. var {
  45006. anchor,
  45007. focus
  45008. } = selection;
  45009. var point = edge === 'anchor' ? anchor : focus;
  45010. var newPoint = Object.assign(point, props);
  45011. if (edge === 'anchor') {
  45012. Transforms.setSelection(editor, {
  45013. anchor: newPoint
  45014. });
  45015. } else {
  45016. Transforms.setSelection(editor, {
  45017. focus: newPoint
  45018. });
  45019. }
  45020. },
  45021. /**
  45022. * Set new properties on the selection.
  45023. */
  45024. setSelection(editor, props) {
  45025. var {
  45026. selection
  45027. } = editor;
  45028. var oldProps = {};
  45029. var newProps = {};
  45030. if (!selection) {
  45031. return;
  45032. }
  45033. for (var k in props) {
  45034. 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]) {
  45035. oldProps[k] = selection[k];
  45036. newProps[k] = props[k];
  45037. }
  45038. }
  45039. if (Object.keys(oldProps).length > 0) {
  45040. editor.apply({
  45041. type: 'set_selection',
  45042. properties: oldProps,
  45043. newProperties: newProps
  45044. });
  45045. }
  45046. }
  45047. };
  45048. var TextTransforms = {
  45049. /**
  45050. * Delete content in the editor.
  45051. */
  45052. delete(editor) {
  45053. var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
  45054. Editor.withoutNormalizing(editor, () => {
  45055. var {
  45056. reverse = false,
  45057. unit = 'character',
  45058. distance = 1,
  45059. voids = false
  45060. } = options;
  45061. var {
  45062. at = editor.selection,
  45063. hanging = false
  45064. } = options;
  45065. if (!at) {
  45066. return;
  45067. }
  45068. if (Range.isRange(at) && Range.isCollapsed(at)) {
  45069. at = at.anchor;
  45070. }
  45071. if (Point.isPoint(at)) {
  45072. var furthestVoid = Editor.void(editor, {
  45073. at,
  45074. mode: 'highest'
  45075. });
  45076. if (!voids && furthestVoid) {
  45077. var [, voidPath] = furthestVoid;
  45078. at = voidPath;
  45079. } else {
  45080. var opts = {
  45081. unit,
  45082. distance
  45083. };
  45084. var target = reverse ? Editor.before(editor, at, opts) || Editor.start(editor, []) : Editor.after(editor, at, opts) || Editor.end(editor, []);
  45085. at = {
  45086. anchor: at,
  45087. focus: target
  45088. };
  45089. hanging = true;
  45090. }
  45091. }
  45092. if (Path.isPath(at)) {
  45093. Transforms.removeNodes(editor, {
  45094. at,
  45095. voids
  45096. });
  45097. return;
  45098. }
  45099. if (Range.isCollapsed(at)) {
  45100. return;
  45101. }
  45102. if (!hanging) {
  45103. at = Editor.unhangRange(editor, at, {
  45104. voids
  45105. });
  45106. }
  45107. var [start, end] = Range.edges(at);
  45108. var startBlock = Editor.above(editor, {
  45109. match: n => Editor.isBlock(editor, n),
  45110. at: start,
  45111. voids
  45112. });
  45113. var endBlock = Editor.above(editor, {
  45114. match: n => Editor.isBlock(editor, n),
  45115. at: end,
  45116. voids
  45117. });
  45118. var isAcrossBlocks = startBlock && endBlock && !Path.equals(startBlock[1], endBlock[1]);
  45119. var isSingleText = Path.equals(start.path, end.path);
  45120. var startVoid = voids ? null : Editor.void(editor, {
  45121. at: start,
  45122. mode: 'highest'
  45123. });
  45124. var endVoid = voids ? null : Editor.void(editor, {
  45125. at: end,
  45126. mode: 'highest'
  45127. }); // If the start or end points are inside an inline void, nudge them out.
  45128. if (startVoid) {
  45129. var before = Editor.before(editor, start);
  45130. if (before && startBlock && Path.isAncestor(startBlock[1], before.path)) {
  45131. start = before;
  45132. }
  45133. }
  45134. if (endVoid) {
  45135. var after = Editor.after(editor, end);
  45136. if (after && endBlock && Path.isAncestor(endBlock[1], after.path)) {
  45137. end = after;
  45138. }
  45139. } // Get the highest nodes that are completely inside the range, as well as
  45140. // the start and end nodes.
  45141. var matches = [];
  45142. var lastPath;
  45143. for (var entry of Editor.nodes(editor, {
  45144. at,
  45145. voids
  45146. })) {
  45147. var [node, path] = entry;
  45148. if (lastPath && Path.compare(path, lastPath) === 0) {
  45149. continue;
  45150. }
  45151. if (!voids && Editor.isVoid(editor, node) || !Path.isCommon(path, start.path) && !Path.isCommon(path, end.path)) {
  45152. matches.push(entry);
  45153. lastPath = path;
  45154. }
  45155. }
  45156. var pathRefs = Array.from(matches, (_ref) => {
  45157. var [, p] = _ref;
  45158. return Editor.pathRef(editor, p);
  45159. });
  45160. var startRef = Editor.pointRef(editor, start);
  45161. var endRef = Editor.pointRef(editor, end);
  45162. if (!isSingleText && !startVoid) {
  45163. var _point = startRef.current;
  45164. var [_node] = Editor.leaf(editor, _point);
  45165. var {
  45166. path: _path
  45167. } = _point;
  45168. var {
  45169. offset
  45170. } = start;
  45171. var text = _node.text.slice(offset);
  45172. editor.apply({
  45173. type: 'remove_text',
  45174. path: _path,
  45175. offset,
  45176. text
  45177. });
  45178. }
  45179. for (var pathRef of pathRefs) {
  45180. var _path2 = pathRef.unref();
  45181. Transforms.removeNodes(editor, {
  45182. at: _path2,
  45183. voids
  45184. });
  45185. }
  45186. if (!endVoid) {
  45187. var _point2 = endRef.current;
  45188. var [_node2] = Editor.leaf(editor, _point2);
  45189. var {
  45190. path: _path3
  45191. } = _point2;
  45192. var _offset = isSingleText ? start.offset : 0;
  45193. var _text = _node2.text.slice(_offset, end.offset);
  45194. editor.apply({
  45195. type: 'remove_text',
  45196. path: _path3,
  45197. offset: _offset,
  45198. text: _text
  45199. });
  45200. }
  45201. if (!isSingleText && isAcrossBlocks && endRef.current && startRef.current) {
  45202. Transforms.mergeNodes(editor, {
  45203. at: endRef.current,
  45204. hanging: true,
  45205. voids
  45206. });
  45207. }
  45208. var point = endRef.unref() || startRef.unref();
  45209. if (options.at == null && point) {
  45210. Transforms.select(editor, point);
  45211. }
  45212. });
  45213. },
  45214. /**
  45215. * Insert a fragment at a specific location in the editor.
  45216. */
  45217. insertFragment(editor, fragment) {
  45218. var options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
  45219. Editor.withoutNormalizing(editor, () => {
  45220. var {
  45221. hanging = false,
  45222. voids = false
  45223. } = options;
  45224. var {
  45225. at = editor.selection
  45226. } = options;
  45227. if (!fragment.length) {
  45228. return;
  45229. }
  45230. if (!at) {
  45231. return;
  45232. } else if (Range.isRange(at)) {
  45233. if (!hanging) {
  45234. at = Editor.unhangRange(editor, at);
  45235. }
  45236. if (Range.isCollapsed(at)) {
  45237. at = at.anchor;
  45238. } else {
  45239. var [, end] = Range.edges(at);
  45240. if (!voids && Editor.void(editor, {
  45241. at: end
  45242. })) {
  45243. return;
  45244. }
  45245. var pointRef = Editor.pointRef(editor, end);
  45246. Transforms.delete(editor, {
  45247. at
  45248. });
  45249. at = pointRef.unref();
  45250. }
  45251. } else if (Path.isPath(at)) {
  45252. at = Editor.start(editor, at);
  45253. }
  45254. if (!voids && Editor.void(editor, {
  45255. at
  45256. })) {
  45257. return;
  45258. } // If the insert point is at the edge of an inline node, move it outside
  45259. // instead since it will need to be split otherwise.
  45260. var inlineElementMatch = Editor.above(editor, {
  45261. at,
  45262. match: n => Editor.isInline(editor, n),
  45263. mode: 'highest',
  45264. voids
  45265. });
  45266. if (inlineElementMatch) {
  45267. var [, _inlinePath] = inlineElementMatch;
  45268. if (Editor.isEnd(editor, at, _inlinePath)) {
  45269. var after = Editor.after(editor, _inlinePath);
  45270. at = after;
  45271. } else if (Editor.isStart(editor, at, _inlinePath)) {
  45272. var before = Editor.before(editor, _inlinePath);
  45273. at = before;
  45274. }
  45275. }
  45276. var blockMatch = Editor.above(editor, {
  45277. match: n => Editor.isBlock(editor, n),
  45278. at,
  45279. voids
  45280. });
  45281. var [, blockPath] = blockMatch;
  45282. var isBlockStart = Editor.isStart(editor, at, blockPath);
  45283. var isBlockEnd = Editor.isEnd(editor, at, blockPath);
  45284. var mergeStart = !isBlockStart || isBlockStart && isBlockEnd;
  45285. var mergeEnd = !isBlockEnd;
  45286. var [, firstPath] = Node.first({
  45287. children: fragment
  45288. }, []);
  45289. var [, lastPath] = Node.last({
  45290. children: fragment
  45291. }, []);
  45292. var matches = [];
  45293. var matcher = (_ref2) => {
  45294. var [n, p] = _ref2;
  45295. if (mergeStart && Path.isAncestor(p, firstPath) && Element.isElement(n) && !editor.isVoid(n) && !editor.isInline(n)) {
  45296. return false;
  45297. }
  45298. if (mergeEnd && Path.isAncestor(p, lastPath) && Element.isElement(n) && !editor.isVoid(n) && !editor.isInline(n)) {
  45299. return false;
  45300. }
  45301. return true;
  45302. };
  45303. for (var entry of Node.nodes({
  45304. children: fragment
  45305. }, {
  45306. pass: matcher
  45307. })) {
  45308. if (entry[1].length > 0 && matcher(entry)) {
  45309. matches.push(entry);
  45310. }
  45311. }
  45312. var starts = [];
  45313. var middles = [];
  45314. var ends = [];
  45315. var starting = true;
  45316. var hasBlocks = false;
  45317. for (var [node] of matches) {
  45318. if (Element.isElement(node) && !editor.isInline(node)) {
  45319. starting = false;
  45320. hasBlocks = true;
  45321. middles.push(node);
  45322. } else if (starting) {
  45323. starts.push(node);
  45324. } else {
  45325. ends.push(node);
  45326. }
  45327. }
  45328. var [inlineMatch] = Editor.nodes(editor, {
  45329. at,
  45330. match: n => Text.isText(n) || Editor.isInline(editor, n),
  45331. mode: 'highest',
  45332. voids
  45333. });
  45334. var [, inlinePath] = inlineMatch;
  45335. var isInlineStart = Editor.isStart(editor, at, inlinePath);
  45336. var isInlineEnd = Editor.isEnd(editor, at, inlinePath);
  45337. var middleRef = Editor.pathRef(editor, isBlockEnd ? Path.next(blockPath) : blockPath);
  45338. var endRef = Editor.pathRef(editor, isInlineEnd ? Path.next(inlinePath) : inlinePath);
  45339. Transforms.splitNodes(editor, {
  45340. at,
  45341. match: n => hasBlocks ? Editor.isBlock(editor, n) : Text.isText(n) || Editor.isInline(editor, n),
  45342. mode: hasBlocks ? 'lowest' : 'highest',
  45343. voids
  45344. });
  45345. var startRef = Editor.pathRef(editor, !isInlineStart || isInlineStart && isInlineEnd ? Path.next(inlinePath) : inlinePath);
  45346. Transforms.insertNodes(editor, starts, {
  45347. at: startRef.current,
  45348. match: n => Text.isText(n) || Editor.isInline(editor, n),
  45349. mode: 'highest',
  45350. voids
  45351. });
  45352. Transforms.insertNodes(editor, middles, {
  45353. at: middleRef.current,
  45354. match: n => Editor.isBlock(editor, n),
  45355. mode: 'lowest',
  45356. voids
  45357. });
  45358. Transforms.insertNodes(editor, ends, {
  45359. at: endRef.current,
  45360. match: n => Text.isText(n) || Editor.isInline(editor, n),
  45361. mode: 'highest',
  45362. voids
  45363. });
  45364. if (!options.at) {
  45365. var path;
  45366. if (ends.length > 0) {
  45367. path = Path.previous(endRef.current);
  45368. } else if (middles.length > 0) {
  45369. path = Path.previous(middleRef.current);
  45370. } else {
  45371. path = Path.previous(startRef.current);
  45372. }
  45373. var _end = Editor.end(editor, path);
  45374. Transforms.select(editor, _end);
  45375. }
  45376. startRef.unref();
  45377. middleRef.unref();
  45378. endRef.unref();
  45379. });
  45380. },
  45381. /**
  45382. * Insert a string of text in the Editor.
  45383. */
  45384. insertText(editor, text) {
  45385. var options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
  45386. Editor.withoutNormalizing(editor, () => {
  45387. var {
  45388. voids = false
  45389. } = options;
  45390. var {
  45391. at = editor.selection
  45392. } = options;
  45393. if (!at) {
  45394. return;
  45395. }
  45396. if (Path.isPath(at)) {
  45397. at = Editor.range(editor, at);
  45398. }
  45399. if (Range.isRange(at)) {
  45400. if (Range.isCollapsed(at)) {
  45401. at = at.anchor;
  45402. } else {
  45403. var end = Range.end(at);
  45404. if (!voids && Editor.void(editor, {
  45405. at: end
  45406. })) {
  45407. return;
  45408. }
  45409. var pointRef = Editor.pointRef(editor, end);
  45410. Transforms.delete(editor, {
  45411. at,
  45412. voids
  45413. });
  45414. at = pointRef.unref();
  45415. Transforms.setSelection(editor, {
  45416. anchor: at,
  45417. focus: at
  45418. });
  45419. }
  45420. }
  45421. if (!voids && Editor.void(editor, {
  45422. at
  45423. })) {
  45424. return;
  45425. }
  45426. var {
  45427. path,
  45428. offset
  45429. } = at;
  45430. editor.apply({
  45431. type: 'insert_text',
  45432. path,
  45433. offset,
  45434. text
  45435. });
  45436. });
  45437. }
  45438. };
  45439. 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; }
  45440. 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; }
  45441. var Transforms = _objectSpread$8({}, GeneralTransforms, {}, NodeTransforms, {}, SelectionTransforms, {}, TextTransforms);
  45442. exports.Editor = Editor;
  45443. exports.Element = Element;
  45444. exports.Location = Location;
  45445. exports.Node = Node;
  45446. exports.Operation = Operation;
  45447. exports.Path = Path;
  45448. exports.PathRef = PathRef;
  45449. exports.Point = Point;
  45450. exports.PointRef = PointRef;
  45451. exports.Range = Range;
  45452. exports.RangeRef = RangeRef;
  45453. exports.Span = Span;
  45454. exports.Text = Text;
  45455. exports.Transforms = Transforms;
  45456. exports.createEditor = createEditor;
  45457. });
  45458. unwrapExports(dist$4);
  45459. var dist_1$2 = dist$4.Editor;
  45460. var dist_2$2 = dist$4.Element;
  45461. var dist_3$2 = dist$4.Location;
  45462. var dist_4$1 = dist$4.Node;
  45463. var dist_5$1 = dist$4.Operation;
  45464. var dist_6$1 = dist$4.Path;
  45465. var dist_7 = dist$4.PathRef;
  45466. var dist_8 = dist$4.Point;
  45467. var dist_9 = dist$4.PointRef;
  45468. var dist_10 = dist$4.Range;
  45469. var dist_11 = dist$4.RangeRef;
  45470. var dist_12 = dist$4.Span;
  45471. var dist_13 = dist$4.Text;
  45472. var dist_14 = dist$4.Transforms;
  45473. var dist_15 = dist$4.createEditor;
  45474. /**
  45475. * Returns a function, that, as long as it continues to be invoked, will not
  45476. * be triggered. The function will be called after it stops being called for
  45477. * N milliseconds. If `immediate` is passed, trigger the function on the
  45478. * leading edge, instead of the trailing. The function also has a property 'clear'
  45479. * that is a function which will clear the timer to prevent previously scheduled executions.
  45480. *
  45481. * @source underscore.js
  45482. * @see http://unscriptable.com/2009/03/20/debouncing-javascript-methods/
  45483. * @param {Function} function to wrap
  45484. * @param {Number} timeout in ms (`100`)
  45485. * @param {Boolean} whether to execute at the beginning (`false`)
  45486. * @api public
  45487. */
  45488. function debounce(func, wait, immediate){
  45489. var timeout, args, context, timestamp, result;
  45490. if (null == wait) wait = 100;
  45491. function later() {
  45492. var last = Date.now() - timestamp;
  45493. if (last < wait && last >= 0) {
  45494. timeout = setTimeout(later, wait - last);
  45495. } else {
  45496. timeout = null;
  45497. if (!immediate) {
  45498. result = func.apply(context, args);
  45499. context = args = null;
  45500. }
  45501. }
  45502. }
  45503. var debounced = function(){
  45504. context = this;
  45505. args = arguments;
  45506. timestamp = Date.now();
  45507. var callNow = immediate && !timeout;
  45508. if (!timeout) timeout = setTimeout(later, wait);
  45509. if (callNow) {
  45510. result = func.apply(context, args);
  45511. context = args = null;
  45512. }
  45513. return result;
  45514. };
  45515. debounced.clear = function() {
  45516. if (timeout) {
  45517. clearTimeout(timeout);
  45518. timeout = null;
  45519. }
  45520. };
  45521. debounced.flush = function() {
  45522. if (timeout) {
  45523. result = func.apply(context, args);
  45524. context = args = null;
  45525. clearTimeout(timeout);
  45526. timeout = null;
  45527. }
  45528. };
  45529. return debounced;
  45530. }
  45531. // Adds compatibility for ES modules
  45532. debounce.debounce = debounce;
  45533. var debounce_1 = debounce;
  45534. var computeScrollIntoView = createCommonjsModule(function (module, exports) {
  45535. exports.__esModule = true;
  45536. exports["default"] = void 0;
  45537. function isElement(el) {
  45538. return el != null && typeof el === 'object' && el.nodeType === 1;
  45539. }
  45540. function canOverflow(overflow, skipOverflowHiddenElements) {
  45541. if (skipOverflowHiddenElements && overflow === 'hidden') {
  45542. return false;
  45543. }
  45544. return overflow !== 'visible' && overflow !== 'clip';
  45545. }
  45546. function getFrameElement(el) {
  45547. if (!el.ownerDocument || !el.ownerDocument.defaultView) {
  45548. return null;
  45549. }
  45550. return el.ownerDocument.defaultView.frameElement;
  45551. }
  45552. function isHiddenByFrame(el) {
  45553. var frame = getFrameElement(el);
  45554. if (!frame) {
  45555. return false;
  45556. }
  45557. return frame.clientHeight < el.scrollHeight || frame.clientWidth < el.scrollWidth;
  45558. }
  45559. function isScrollable(el, skipOverflowHiddenElements) {
  45560. if (el.clientHeight < el.scrollHeight || el.clientWidth < el.scrollWidth) {
  45561. var style = getComputedStyle(el, null);
  45562. return canOverflow(style.overflowY, skipOverflowHiddenElements) || canOverflow(style.overflowX, skipOverflowHiddenElements) || isHiddenByFrame(el);
  45563. }
  45564. return false;
  45565. }
  45566. function alignNearest(scrollingEdgeStart, scrollingEdgeEnd, scrollingSize, scrollingBorderStart, scrollingBorderEnd, elementEdgeStart, elementEdgeEnd, elementSize) {
  45567. if (elementEdgeStart < scrollingEdgeStart && elementEdgeEnd > scrollingEdgeEnd || elementEdgeStart > scrollingEdgeStart && elementEdgeEnd < scrollingEdgeEnd) {
  45568. return 0;
  45569. }
  45570. if (elementEdgeStart <= scrollingEdgeStart && elementSize <= scrollingSize || elementEdgeEnd >= scrollingEdgeEnd && elementSize >= scrollingSize) {
  45571. return elementEdgeStart - scrollingEdgeStart - scrollingBorderStart;
  45572. }
  45573. if (elementEdgeEnd > scrollingEdgeEnd && elementSize < scrollingSize || elementEdgeStart < scrollingEdgeStart && elementSize > scrollingSize) {
  45574. return elementEdgeEnd - scrollingEdgeEnd + scrollingBorderEnd;
  45575. }
  45576. return 0;
  45577. }
  45578. var _default = function _default(target, options) {
  45579. var scrollMode = options.scrollMode,
  45580. block = options.block,
  45581. inline = options.inline,
  45582. boundary = options.boundary,
  45583. skipOverflowHiddenElements = options.skipOverflowHiddenElements;
  45584. var checkBoundary = typeof boundary === 'function' ? boundary : function (node) {
  45585. return node !== boundary;
  45586. };
  45587. if (!isElement(target)) {
  45588. throw new TypeError('Invalid target');
  45589. }
  45590. var scrollingElement = document.scrollingElement || document.documentElement;
  45591. var frames = [];
  45592. var cursor = target;
  45593. while (isElement(cursor) && checkBoundary(cursor)) {
  45594. cursor = cursor.parentNode;
  45595. if (cursor === scrollingElement) {
  45596. frames.push(cursor);
  45597. break;
  45598. }
  45599. if (cursor === document.body && isScrollable(cursor) && !isScrollable(document.documentElement)) {
  45600. continue;
  45601. }
  45602. if (isScrollable(cursor, skipOverflowHiddenElements)) {
  45603. frames.push(cursor);
  45604. }
  45605. }
  45606. var viewportWidth = window.visualViewport ? visualViewport.width : innerWidth;
  45607. var viewportHeight = window.visualViewport ? visualViewport.height : innerHeight;
  45608. var viewportX = window.scrollX || pageXOffset;
  45609. var viewportY = window.scrollY || pageYOffset;
  45610. var _target$getBoundingCl = target.getBoundingClientRect(),
  45611. targetHeight = _target$getBoundingCl.height,
  45612. targetWidth = _target$getBoundingCl.width,
  45613. targetTop = _target$getBoundingCl.top,
  45614. targetRight = _target$getBoundingCl.right,
  45615. targetBottom = _target$getBoundingCl.bottom,
  45616. targetLeft = _target$getBoundingCl.left;
  45617. var targetBlock = block === 'start' || block === 'nearest' ? targetTop : block === 'end' ? targetBottom : targetTop + targetHeight / 2;
  45618. var targetInline = inline === 'center' ? targetLeft + targetWidth / 2 : inline === 'end' ? targetRight : targetLeft;
  45619. var computations = [];
  45620. for (var index = 0; index < frames.length; index++) {
  45621. var frame = frames[index];
  45622. var _frame$getBoundingCli = frame.getBoundingClientRect(),
  45623. height = _frame$getBoundingCli.height,
  45624. width = _frame$getBoundingCli.width,
  45625. top = _frame$getBoundingCli.top,
  45626. right = _frame$getBoundingCli.right,
  45627. bottom = _frame$getBoundingCli.bottom,
  45628. left = _frame$getBoundingCli.left;
  45629. if (scrollMode === 'if-needed' && targetTop >= 0 && targetLeft >= 0 && targetBottom <= viewportHeight && targetRight <= viewportWidth && targetTop >= top && targetBottom <= bottom && targetLeft >= left && targetRight <= right) {
  45630. return computations;
  45631. }
  45632. var frameStyle = getComputedStyle(frame);
  45633. var borderLeft = parseInt(frameStyle.borderLeftWidth, 10);
  45634. var borderTop = parseInt(frameStyle.borderTopWidth, 10);
  45635. var borderRight = parseInt(frameStyle.borderRightWidth, 10);
  45636. var borderBottom = parseInt(frameStyle.borderBottomWidth, 10);
  45637. var blockScroll = 0;
  45638. var inlineScroll = 0;
  45639. var scrollbarWidth = 'offsetWidth' in frame ? frame.offsetWidth - frame.clientWidth - borderLeft - borderRight : 0;
  45640. var scrollbarHeight = 'offsetHeight' in frame ? frame.offsetHeight - frame.clientHeight - borderTop - borderBottom : 0;
  45641. if (scrollingElement === frame) {
  45642. if (block === 'start') {
  45643. blockScroll = targetBlock;
  45644. } else if (block === 'end') {
  45645. blockScroll = targetBlock - viewportHeight;
  45646. } else if (block === 'nearest') {
  45647. blockScroll = alignNearest(viewportY, viewportY + viewportHeight, viewportHeight, borderTop, borderBottom, viewportY + targetBlock, viewportY + targetBlock + targetHeight, targetHeight);
  45648. } else {
  45649. blockScroll = targetBlock - viewportHeight / 2;
  45650. }
  45651. if (inline === 'start') {
  45652. inlineScroll = targetInline;
  45653. } else if (inline === 'center') {
  45654. inlineScroll = targetInline - viewportWidth / 2;
  45655. } else if (inline === 'end') {
  45656. inlineScroll = targetInline - viewportWidth;
  45657. } else {
  45658. inlineScroll = alignNearest(viewportX, viewportX + viewportWidth, viewportWidth, borderLeft, borderRight, viewportX + targetInline, viewportX + targetInline + targetWidth, targetWidth);
  45659. }
  45660. blockScroll = Math.max(0, blockScroll + viewportY);
  45661. inlineScroll = Math.max(0, inlineScroll + viewportX);
  45662. } else {
  45663. if (block === 'start') {
  45664. blockScroll = targetBlock - top - borderTop;
  45665. } else if (block === 'end') {
  45666. blockScroll = targetBlock - bottom + borderBottom + scrollbarHeight;
  45667. } else if (block === 'nearest') {
  45668. blockScroll = alignNearest(top, bottom, height, borderTop, borderBottom + scrollbarHeight, targetBlock, targetBlock + targetHeight, targetHeight);
  45669. } else {
  45670. blockScroll = targetBlock - (top + height / 2) + scrollbarHeight / 2;
  45671. }
  45672. if (inline === 'start') {
  45673. inlineScroll = targetInline - left - borderLeft;
  45674. } else if (inline === 'center') {
  45675. inlineScroll = targetInline - (left + width / 2) + scrollbarWidth / 2;
  45676. } else if (inline === 'end') {
  45677. inlineScroll = targetInline - right + borderRight + scrollbarWidth;
  45678. } else {
  45679. inlineScroll = alignNearest(left, right, width, borderLeft, borderRight + scrollbarWidth, targetInline, targetInline + targetWidth, targetWidth);
  45680. }
  45681. var scrollLeft = frame.scrollLeft,
  45682. scrollTop = frame.scrollTop;
  45683. blockScroll = Math.max(0, Math.min(scrollTop + blockScroll, frame.scrollHeight - height + scrollbarHeight));
  45684. inlineScroll = Math.max(0, Math.min(scrollLeft + inlineScroll, frame.scrollWidth - width + scrollbarWidth));
  45685. targetBlock += scrollTop - blockScroll;
  45686. targetInline += scrollLeft - inlineScroll;
  45687. }
  45688. computations.push({
  45689. el: frame,
  45690. top: blockScroll,
  45691. left: inlineScroll
  45692. });
  45693. }
  45694. return computations;
  45695. };
  45696. exports["default"] = _default;
  45697. module.exports = exports.default;
  45698. });
  45699. unwrapExports(computeScrollIntoView);
  45700. var scrollIntoViewIfNeeded = createCommonjsModule(function (module, exports) {
  45701. exports.__esModule = true;
  45702. exports["default"] = void 0;
  45703. var _computeScrollIntoView = _interopRequireDefault(computeScrollIntoView);
  45704. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
  45705. function isOptionsObject(options) {
  45706. return options === Object(options) && Object.keys(options).length !== 0;
  45707. }
  45708. function defaultBehavior(actions, behavior) {
  45709. if (behavior === void 0) {
  45710. behavior = 'auto';
  45711. }
  45712. var canSmoothScroll = 'scrollBehavior' in document.body.style;
  45713. actions.forEach(function (_ref) {
  45714. var el = _ref.el,
  45715. top = _ref.top,
  45716. left = _ref.left;
  45717. if (el.scroll && canSmoothScroll) {
  45718. el.scroll({
  45719. top: top,
  45720. left: left,
  45721. behavior: behavior
  45722. });
  45723. } else {
  45724. el.scrollTop = top;
  45725. el.scrollLeft = left;
  45726. }
  45727. });
  45728. }
  45729. function getOptions(options) {
  45730. if (options === false) {
  45731. return {
  45732. block: 'end',
  45733. inline: 'nearest'
  45734. };
  45735. }
  45736. if (isOptionsObject(options)) {
  45737. return options;
  45738. }
  45739. return {
  45740. block: 'start',
  45741. inline: 'nearest'
  45742. };
  45743. }
  45744. function scrollIntoView(target, options) {
  45745. var targetIsDetached = !target.ownerDocument.documentElement.contains(target);
  45746. if (isOptionsObject(options) && typeof options.behavior === 'function') {
  45747. return options.behavior(targetIsDetached ? [] : (0, _computeScrollIntoView["default"])(target, options));
  45748. }
  45749. if (targetIsDetached) {
  45750. return;
  45751. }
  45752. var computeOptions = getOptions(options);
  45753. return defaultBehavior((0, _computeScrollIntoView["default"])(target, computeOptions), computeOptions.behavior);
  45754. }
  45755. var _default = scrollIntoView;
  45756. exports["default"] = _default;
  45757. module.exports = exports.default;
  45758. });
  45759. unwrapExports(scrollIntoViewIfNeeded);
  45760. var direction_1 = direction;
  45761. var RTL$1 = '\u0591-\u07FF\uFB1D-\uFDFD\uFE70-\uFEFC';
  45762. var LTR$1 =
  45763. 'A-Za-z\u00C0-\u00D6\u00D8-\u00F6' +
  45764. '\u00F8-\u02B8\u0300-\u0590\u0800-\u1FFF\u200E\u2C00-\uFB1C' +
  45765. '\uFE00-\uFE6F\uFEFD-\uFFFF';
  45766. var rtl = new RegExp('^[^' + LTR$1 + ']*[' + RTL$1 + ']');
  45767. var ltr = new RegExp('^[^' + RTL$1 + ']*[' + LTR$1 + ']');
  45768. function direction(value) {
  45769. value = String(value || '');
  45770. if (rtl.test(value)) {
  45771. return 'rtl'
  45772. }
  45773. if (ltr.test(value)) {
  45774. return 'ltr'
  45775. }
  45776. return 'neutral'
  45777. }
  45778. var lib$1 = createCommonjsModule(function (module, exports) {
  45779. Object.defineProperty(exports, "__esModule", {
  45780. value: true
  45781. });
  45782. /**
  45783. * Constants.
  45784. */
  45785. var IS_MAC = typeof window != 'undefined' && /Mac|iPod|iPhone|iPad/.test(window.navigator.platform);
  45786. var MODIFIERS = {
  45787. alt: 'altKey',
  45788. control: 'ctrlKey',
  45789. meta: 'metaKey',
  45790. shift: 'shiftKey'
  45791. };
  45792. var ALIASES = {
  45793. add: '+',
  45794. break: 'pause',
  45795. cmd: 'meta',
  45796. command: 'meta',
  45797. ctl: 'control',
  45798. ctrl: 'control',
  45799. del: 'delete',
  45800. down: 'arrowdown',
  45801. esc: 'escape',
  45802. ins: 'insert',
  45803. left: 'arrowleft',
  45804. mod: IS_MAC ? 'meta' : 'control',
  45805. opt: 'alt',
  45806. option: 'alt',
  45807. return: 'enter',
  45808. right: 'arrowright',
  45809. space: ' ',
  45810. spacebar: ' ',
  45811. up: 'arrowup',
  45812. win: 'meta',
  45813. windows: 'meta'
  45814. };
  45815. var CODES = {
  45816. backspace: 8,
  45817. tab: 9,
  45818. enter: 13,
  45819. shift: 16,
  45820. control: 17,
  45821. alt: 18,
  45822. pause: 19,
  45823. capslock: 20,
  45824. escape: 27,
  45825. ' ': 32,
  45826. pageup: 33,
  45827. pagedown: 34,
  45828. end: 35,
  45829. home: 36,
  45830. arrowleft: 37,
  45831. arrowup: 38,
  45832. arrowright: 39,
  45833. arrowdown: 40,
  45834. insert: 45,
  45835. delete: 46,
  45836. meta: 91,
  45837. numlock: 144,
  45838. scrolllock: 145,
  45839. ';': 186,
  45840. '=': 187,
  45841. ',': 188,
  45842. '-': 189,
  45843. '.': 190,
  45844. '/': 191,
  45845. '`': 192,
  45846. '[': 219,
  45847. '\\': 220,
  45848. ']': 221,
  45849. '\'': 222
  45850. };
  45851. for (var f = 1; f < 20; f++) {
  45852. CODES['f' + f] = 111 + f;
  45853. }
  45854. /**
  45855. * Is hotkey?
  45856. */
  45857. function isHotkey(hotkey, options, event) {
  45858. if (options && !('byKey' in options)) {
  45859. event = options;
  45860. options = null;
  45861. }
  45862. if (!Array.isArray(hotkey)) {
  45863. hotkey = [hotkey];
  45864. }
  45865. var array = hotkey.map(function (string) {
  45866. return parseHotkey(string, options);
  45867. });
  45868. var check = function check(e) {
  45869. return array.some(function (object) {
  45870. return compareHotkey(object, e);
  45871. });
  45872. };
  45873. var ret = event == null ? check : check(event);
  45874. return ret;
  45875. }
  45876. function isCodeHotkey(hotkey, event) {
  45877. return isHotkey(hotkey, event);
  45878. }
  45879. function isKeyHotkey(hotkey, event) {
  45880. return isHotkey(hotkey, { byKey: true }, event);
  45881. }
  45882. /**
  45883. * Parse.
  45884. */
  45885. function parseHotkey(hotkey, options) {
  45886. var byKey = options && options.byKey;
  45887. var ret = {};
  45888. // Special case to handle the `+` key since we use it as a separator.
  45889. hotkey = hotkey.replace('++', '+add');
  45890. var values = hotkey.split('+');
  45891. var length = values.length;
  45892. // Ensure that all the modifiers are set to false unless the hotkey has them.
  45893. for (var k in MODIFIERS) {
  45894. ret[MODIFIERS[k]] = false;
  45895. }
  45896. var _iteratorNormalCompletion = true;
  45897. var _didIteratorError = false;
  45898. var _iteratorError = undefined;
  45899. try {
  45900. for (var _iterator = values[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) {
  45901. var value = _step.value;
  45902. var optional = value.endsWith('?') && value.length > 1;
  45903. if (optional) {
  45904. value = value.slice(0, -1);
  45905. }
  45906. var name = toKeyName(value);
  45907. var modifier = MODIFIERS[name];
  45908. if (length === 1 || !modifier) {
  45909. if (byKey) {
  45910. ret.key = name;
  45911. } else {
  45912. ret.which = toKeyCode(value);
  45913. }
  45914. }
  45915. if (modifier) {
  45916. ret[modifier] = optional ? null : true;
  45917. }
  45918. }
  45919. } catch (err) {
  45920. _didIteratorError = true;
  45921. _iteratorError = err;
  45922. } finally {
  45923. try {
  45924. if (!_iteratorNormalCompletion && _iterator.return) {
  45925. _iterator.return();
  45926. }
  45927. } finally {
  45928. if (_didIteratorError) {
  45929. throw _iteratorError;
  45930. }
  45931. }
  45932. }
  45933. return ret;
  45934. }
  45935. /**
  45936. * Compare.
  45937. */
  45938. function compareHotkey(object, event) {
  45939. for (var key in object) {
  45940. var expected = object[key];
  45941. var actual = void 0;
  45942. if (expected == null) {
  45943. continue;
  45944. }
  45945. if (key === 'key' && event.key != null) {
  45946. actual = event.key.toLowerCase();
  45947. } else if (key === 'which') {
  45948. actual = expected === 91 && event.which === 93 ? 91 : event.which;
  45949. } else {
  45950. actual = event[key];
  45951. }
  45952. if (actual == null && expected === false) {
  45953. continue;
  45954. }
  45955. if (actual !== expected) {
  45956. return false;
  45957. }
  45958. }
  45959. return true;
  45960. }
  45961. /**
  45962. * Utils.
  45963. */
  45964. function toKeyCode(name) {
  45965. name = toKeyName(name);
  45966. var code = CODES[name] || name.toUpperCase().charCodeAt(0);
  45967. return code;
  45968. }
  45969. function toKeyName(name) {
  45970. name = name.toLowerCase();
  45971. name = ALIASES[name] || name;
  45972. return name;
  45973. }
  45974. /**
  45975. * Export.
  45976. */
  45977. exports.default = isHotkey;
  45978. exports.isHotkey = isHotkey;
  45979. exports.isCodeHotkey = isCodeHotkey;
  45980. exports.isKeyHotkey = isKeyHotkey;
  45981. exports.parseHotkey = parseHotkey;
  45982. exports.compareHotkey = compareHotkey;
  45983. exports.toKeyCode = toKeyCode;
  45984. exports.toKeyName = toKeyName;
  45985. });
  45986. unwrapExports(lib$1);
  45987. var lib_1 = lib$1.isHotkey;
  45988. var lib_2 = lib$1.isCodeHotkey;
  45989. var lib_3 = lib$1.isKeyHotkey;
  45990. var lib_4 = lib$1.parseHotkey;
  45991. var lib_5 = lib$1.compareHotkey;
  45992. var lib_6 = lib$1.toKeyCode;
  45993. var lib_7 = lib$1.toKeyName;
  45994. var dist$5 = createCommonjsModule(function (module, exports) {
  45995. Object.defineProperty(exports, '__esModule', { value: true });
  45996. function _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; }
  45997. var React__default = _interopDefault(React);
  45998. var debounce = _interopDefault(debounce_1);
  45999. var scrollIntoView = _interopDefault(scrollIntoViewIfNeeded);
  46000. var getDirection = _interopDefault(direction_1);
  46001. var ReactDOM = _interopDefault(reactDom);
  46002. /**
  46003. * Leaf content strings.
  46004. */
  46005. const String = (props) => {
  46006. const { isLast, leaf, parent, text } = props;
  46007. const editor = useEditor();
  46008. const path = ReactEditor.findPath(editor, text);
  46009. const parentPath = dist$4.Path.parent(path);
  46010. // COMPAT: Render text inside void nodes with a zero-width space.
  46011. // So the node can contain selection but the text is not visible.
  46012. if (editor.isVoid(parent)) {
  46013. return React__default.createElement(ZeroWidthString, { length: dist$4.Node.string(parent).length });
  46014. }
  46015. // COMPAT: If this is the last text node in an empty block, render a zero-
  46016. // width space that will convert into a line break when copying and pasting
  46017. // to support expected plain text.
  46018. if (leaf.text === '' &&
  46019. parent.children[parent.children.length - 1] === text &&
  46020. !editor.isInline(parent) &&
  46021. dist$4.Editor.string(editor, parentPath) === '') {
  46022. return React__default.createElement(ZeroWidthString, { isLineBreak: true });
  46023. }
  46024. // COMPAT: If the text is empty, it's because it's on the edge of an inline
  46025. // node, so we render a zero-width space so that the selection can be
  46026. // inserted next to it still.
  46027. if (leaf.text === '') {
  46028. return React__default.createElement(ZeroWidthString, null);
  46029. }
  46030. // COMPAT: Browsers will collapse trailing new lines at the end of blocks,
  46031. // so we need to add an extra trailing new lines to prevent that.
  46032. if (isLast && leaf.text.slice(-1) === '\n') {
  46033. return React__default.createElement(TextString, { isTrailing: true, text: leaf.text });
  46034. }
  46035. return React__default.createElement(TextString, { text: leaf.text });
  46036. };
  46037. /**
  46038. * Leaf strings with text in them.
  46039. */
  46040. const TextString = (props) => {
  46041. const { text, isTrailing = false } = props;
  46042. return (React__default.createElement("span", { "data-slate-string": true },
  46043. text,
  46044. isTrailing ? '\n' : null));
  46045. };
  46046. /**
  46047. * Leaf strings without text, render as zero-width strings.
  46048. */
  46049. const ZeroWidthString = (props) => {
  46050. const { length = 0, isLineBreak = false } = props;
  46051. return (React__default.createElement("span", { "data-slate-zero-width": isLineBreak ? 'n' : 'z', "data-slate-length": length },
  46052. '\uFEFF',
  46053. isLineBreak ? React__default.createElement("br", null) : null));
  46054. };
  46055. /**
  46056. * Two weak maps that allow us rebuild a path given a node. They are populated
  46057. * at render time such that after a render occurs we can always backtrack.
  46058. */
  46059. var NODE_TO_INDEX = new WeakMap();
  46060. var NODE_TO_PARENT = new WeakMap();
  46061. /**
  46062. * Weak maps that allow us to go between Slate nodes and DOM nodes. These
  46063. * are used to resolve DOM event-related logic into Slate actions.
  46064. */
  46065. var EDITOR_TO_ELEMENT = new WeakMap();
  46066. var ELEMENT_TO_NODE = new WeakMap();
  46067. var KEY_TO_ELEMENT = new WeakMap();
  46068. var NODE_TO_ELEMENT = new WeakMap();
  46069. var NODE_TO_KEY = new WeakMap();
  46070. /**
  46071. * Weak maps for storing editor-related state.
  46072. */
  46073. var IS_READ_ONLY = new WeakMap();
  46074. var IS_FOCUSED = new WeakMap();
  46075. /**
  46076. * Weak map for associating the context `onChange` context with the plugin.
  46077. */
  46078. var EDITOR_TO_ON_CHANGE = new WeakMap();
  46079. /**
  46080. * Symbols.
  46081. */
  46082. var PLACEHOLDER_SYMBOL = Symbol('placeholder');
  46083. /**
  46084. * Individual leaves in a text node with unique formatting.
  46085. */
  46086. const Leaf = (props) => {
  46087. const { leaf, isLast, text, parent, renderLeaf = (props) => React__default.createElement(DefaultLeaf, Object.assign({}, props)), } = props;
  46088. let children = (React__default.createElement(String, { isLast: isLast, leaf: leaf, parent: parent, text: text }));
  46089. if (leaf[PLACEHOLDER_SYMBOL]) {
  46090. children = (React__default.createElement(React__default.Fragment, null,
  46091. React__default.createElement("span", { contentEditable: false, style: {
  46092. pointerEvents: 'none',
  46093. display: 'inline-block',
  46094. verticalAlign: 'text-top',
  46095. width: '0',
  46096. maxWidth: '100%',
  46097. whiteSpace: 'nowrap',
  46098. opacity: '0.333',
  46099. } }, leaf.placeholder),
  46100. children));
  46101. }
  46102. // COMPAT: Having the `data-` attributes on these leaf elements ensures that
  46103. // in certain misbehaving browsers they aren't weirdly cloned/destroyed by
  46104. // contenteditable behaviors. (2019/05/08)
  46105. const attributes = {
  46106. 'data-slate-leaf': true,
  46107. };
  46108. return renderLeaf({ attributes, children, leaf, text });
  46109. };
  46110. const MemoizedLeaf = React__default.memo(Leaf, (prev, next) => {
  46111. return (next.parent === prev.parent &&
  46112. next.isLast === prev.isLast &&
  46113. next.renderLeaf === prev.renderLeaf &&
  46114. next.text === prev.text &&
  46115. dist$4.Text.matches(next.leaf, prev.leaf));
  46116. });
  46117. /**
  46118. * The default custom leaf renderer.
  46119. */
  46120. const DefaultLeaf = (props) => {
  46121. const { attributes, children } = props;
  46122. return React__default.createElement("span", Object.assign({}, attributes), children);
  46123. };
  46124. /**
  46125. * Prevent warning on SSR by falling back to useEffect when window is not defined
  46126. */
  46127. var useIsomorphicLayoutEffect = typeof window !== 'undefined' ? React.useLayoutEffect : React.useEffect;
  46128. /**
  46129. * Text.
  46130. */
  46131. const Text = (props) => {
  46132. const { decorations, isLast, parent, renderLeaf, text } = props;
  46133. const editor = useEditor();
  46134. const ref = React.useRef(null);
  46135. const leaves = dist$4.Text.decorations(text, decorations);
  46136. const key = ReactEditor.findKey(editor, text);
  46137. const children = [];
  46138. for (let i = 0; i < leaves.length; i++) {
  46139. const leaf = leaves[i];
  46140. children.push(React__default.createElement(MemoizedLeaf, { isLast: isLast && i === leaves.length - 1, key: `${key.id}-${i}`, leaf: leaf, text: text, parent: parent, renderLeaf: renderLeaf }));
  46141. }
  46142. // Update element-related weak maps with the DOM element ref.
  46143. useIsomorphicLayoutEffect(() => {
  46144. if (ref.current) {
  46145. KEY_TO_ELEMENT.set(key, ref.current);
  46146. NODE_TO_ELEMENT.set(text, ref.current);
  46147. ELEMENT_TO_NODE.set(ref.current, text);
  46148. }
  46149. else {
  46150. KEY_TO_ELEMENT.delete(key);
  46151. NODE_TO_ELEMENT.delete(text);
  46152. }
  46153. });
  46154. return (React__default.createElement("span", { "data-slate-node": "text", ref: ref }, children));
  46155. };
  46156. const MemoizedText = React__default.memo(Text, (prev, next) => {
  46157. return (next.parent === prev.parent &&
  46158. next.isLast === prev.isLast &&
  46159. next.renderLeaf === prev.renderLeaf &&
  46160. next.text === prev.text);
  46161. });
  46162. /**
  46163. * A React context for sharing the `selected` state of an element.
  46164. */
  46165. var SelectedContext = React.createContext(false);
  46166. /**
  46167. * Get the current `selected` state of an element.
  46168. */
  46169. var useSelected = () => {
  46170. return React.useContext(SelectedContext);
  46171. };
  46172. /**
  46173. * Element.
  46174. */
  46175. const Element = (props) => {
  46176. const { decorate, decorations, element, renderElement = (p) => React__default.createElement(DefaultElement, Object.assign({}, p)), renderLeaf, selection, } = props;
  46177. const ref = React.useRef(null);
  46178. const editor = useEditor();
  46179. const readOnly = useReadOnly();
  46180. const isInline = editor.isInline(element);
  46181. const key = ReactEditor.findKey(editor, element);
  46182. let children = (React__default.createElement(Children, { decorate: decorate, decorations: decorations, node: element, renderElement: renderElement, renderLeaf: renderLeaf, selection: selection }));
  46183. // Attributes that the developer must mix into the element in their
  46184. // custom node renderer component.
  46185. const attributes = {
  46186. 'data-slate-node': 'element',
  46187. ref,
  46188. };
  46189. if (isInline) {
  46190. attributes['data-slate-inline'] = true;
  46191. }
  46192. // If it's a block node with inline children, add the proper `dir` attribute
  46193. // for text direction.
  46194. if (!isInline && dist$4.Editor.hasInlines(editor, element)) {
  46195. const text = dist$4.Node.string(element);
  46196. const dir = getDirection(text);
  46197. if (dir === 'rtl') {
  46198. attributes.dir = dir;
  46199. }
  46200. }
  46201. // If it's a void node, wrap the children in extra void-specific elements.
  46202. if (dist$4.Editor.isVoid(editor, element)) {
  46203. attributes['data-slate-void'] = true;
  46204. if (!readOnly && isInline) {
  46205. attributes.contentEditable = false;
  46206. }
  46207. const Tag = isInline ? 'span' : 'div';
  46208. const [[text]] = dist$4.Node.texts(element);
  46209. children = readOnly ? null : (React__default.createElement(Tag, { "data-slate-spacer": true, style: {
  46210. height: '0',
  46211. color: 'transparent',
  46212. outline: 'none',
  46213. position: 'absolute',
  46214. } },
  46215. React__default.createElement(MemoizedText, { decorations: [], isLast: false, parent: element, text: text })));
  46216. NODE_TO_INDEX.set(text, 0);
  46217. NODE_TO_PARENT.set(text, element);
  46218. }
  46219. // Update element-related weak maps with the DOM element ref.
  46220. useIsomorphicLayoutEffect(() => {
  46221. if (ref.current) {
  46222. KEY_TO_ELEMENT.set(key, ref.current);
  46223. NODE_TO_ELEMENT.set(element, ref.current);
  46224. ELEMENT_TO_NODE.set(ref.current, element);
  46225. }
  46226. else {
  46227. KEY_TO_ELEMENT.delete(key);
  46228. NODE_TO_ELEMENT.delete(element);
  46229. }
  46230. });
  46231. return (React__default.createElement(SelectedContext.Provider, { value: !!selection }, renderElement({ attributes, children, element })));
  46232. };
  46233. const MemoizedElement = React__default.memo(Element, (prev, next) => {
  46234. return (prev.decorate === next.decorate &&
  46235. prev.element === next.element &&
  46236. prev.renderElement === next.renderElement &&
  46237. prev.renderLeaf === next.renderLeaf &&
  46238. isRangeListEqual(prev.decorations, next.decorations) &&
  46239. (prev.selection === next.selection ||
  46240. (!!prev.selection &&
  46241. !!next.selection &&
  46242. dist$4.Range.equals(prev.selection, next.selection))));
  46243. });
  46244. /**
  46245. * The default element renderer.
  46246. */
  46247. const DefaultElement = (props) => {
  46248. const { attributes, children, element } = props;
  46249. const editor = useEditor();
  46250. const Tag = editor.isInline(element) ? 'span' : 'div';
  46251. return (React__default.createElement(Tag, Object.assign({}, attributes, { style: { position: 'relative' } }), children));
  46252. };
  46253. /**
  46254. * Check if a list of ranges is equal to another.
  46255. *
  46256. * PERF: this requires the two lists to also have the ranges inside them in the
  46257. * same order, but this is an okay constraint for us since decorations are
  46258. * kept in order, and the odd case where they aren't is okay to re-render for.
  46259. */
  46260. const isRangeListEqual = (list, another) => {
  46261. if (list.length !== another.length) {
  46262. return false;
  46263. }
  46264. for (let i = 0; i < list.length; i++) {
  46265. const range = list[i];
  46266. const other = another[i];
  46267. if (!dist$4.Range.equals(range, other)) {
  46268. return false;
  46269. }
  46270. }
  46271. return true;
  46272. };
  46273. /**
  46274. * A React context for sharing the editor object.
  46275. */
  46276. const EditorContext = React.createContext(null);
  46277. /**
  46278. * Get the current editor object from the React context.
  46279. */
  46280. const useEditor = () => {
  46281. const editor = React.useContext(EditorContext);
  46282. if (!editor) {
  46283. throw new Error(`The \`useEditor\` hook must be used inside the <Slate> component's context.`);
  46284. }
  46285. return editor;
  46286. };
  46287. /**
  46288. * Children.
  46289. */
  46290. const Children = (props) => {
  46291. const { decorate, decorations, node, renderElement, renderLeaf, selection, } = props;
  46292. const editor = useEditor();
  46293. const path = ReactEditor.findPath(editor, node);
  46294. const children = [];
  46295. const isLeafBlock = dist$4.Element.isElement(node) &&
  46296. !editor.isInline(node) &&
  46297. dist$4.Editor.hasInlines(editor, node);
  46298. for (let i = 0; i < node.children.length; i++) {
  46299. const p = path.concat(i);
  46300. const n = node.children[i];
  46301. const key = ReactEditor.findKey(editor, n);
  46302. const range = dist$4.Editor.range(editor, p);
  46303. const sel = selection && dist$4.Range.intersection(range, selection);
  46304. const ds = decorate([n, p]);
  46305. for (const dec of decorations) {
  46306. const d = dist$4.Range.intersection(dec, range);
  46307. if (d) {
  46308. ds.push(d);
  46309. }
  46310. }
  46311. if (dist$4.Element.isElement(n)) {
  46312. children.push(React__default.createElement(MemoizedElement, { decorate: decorate, decorations: ds, element: n, key: key.id, renderElement: renderElement, renderLeaf: renderLeaf, selection: sel }));
  46313. }
  46314. else {
  46315. children.push(React__default.createElement(MemoizedText, { decorations: ds, key: key.id, isLast: isLeafBlock && i === node.children.length - 1, parent: node, renderLeaf: renderLeaf, text: n }));
  46316. }
  46317. NODE_TO_INDEX.set(n, i);
  46318. NODE_TO_PARENT.set(n, node);
  46319. }
  46320. return React__default.createElement(React__default.Fragment, null, children);
  46321. };
  46322. var IS_IOS = typeof navigator !== 'undefined' && typeof window !== 'undefined' && /iPad|iPhone|iPod/.test(navigator.userAgent) && !window.MSStream;
  46323. var IS_APPLE = typeof navigator !== 'undefined' && /Mac OS X/.test(navigator.userAgent);
  46324. var IS_FIREFOX = typeof navigator !== 'undefined' && /^(?!.*Seamonkey)(?=.*Firefox).*/i.test(navigator.userAgent);
  46325. var IS_SAFARI = typeof navigator !== 'undefined' && /Version\/[\d\.]+.*Safari/.test(navigator.userAgent);
  46326. /**
  46327. * Hotkey mappings for each platform.
  46328. */
  46329. var HOTKEYS = {
  46330. bold: 'mod+b',
  46331. compose: ['down', 'left', 'right', 'up', 'backspace', 'enter'],
  46332. moveBackward: 'left',
  46333. moveForward: 'right',
  46334. moveWordBackward: 'ctrl+left',
  46335. moveWordForward: 'ctrl+right',
  46336. deleteBackward: 'shift?+backspace',
  46337. deleteForward: 'shift?+delete',
  46338. extendBackward: 'shift+left',
  46339. extendForward: 'shift+right',
  46340. italic: 'mod+i',
  46341. splitBlock: 'shift?+enter',
  46342. undo: 'mod+z'
  46343. };
  46344. var APPLE_HOTKEYS = {
  46345. moveLineBackward: 'opt+up',
  46346. moveLineForward: 'opt+down',
  46347. moveWordBackward: 'opt+left',
  46348. moveWordForward: 'opt+right',
  46349. deleteBackward: ['ctrl+backspace', 'ctrl+h'],
  46350. deleteForward: ['ctrl+delete', 'ctrl+d'],
  46351. deleteLineBackward: 'cmd+shift?+backspace',
  46352. deleteLineForward: ['cmd+shift?+delete', 'ctrl+k'],
  46353. deleteWordBackward: 'opt+shift?+backspace',
  46354. deleteWordForward: 'opt+shift?+delete',
  46355. extendLineBackward: 'opt+shift+up',
  46356. extendLineForward: 'opt+shift+down',
  46357. redo: 'cmd+shift+z',
  46358. transposeCharacter: 'ctrl+t'
  46359. };
  46360. var WINDOWS_HOTKEYS = {
  46361. deleteWordBackward: 'ctrl+shift?+backspace',
  46362. deleteWordForward: 'ctrl+shift?+delete',
  46363. redo: ['ctrl+y', 'ctrl+shift+z']
  46364. };
  46365. /**
  46366. * Create a platform-aware hotkey checker.
  46367. */
  46368. var create = key => {
  46369. var generic = HOTKEYS[key];
  46370. var apple = APPLE_HOTKEYS[key];
  46371. var windows = WINDOWS_HOTKEYS[key];
  46372. var isGeneric = generic && lib$1.isKeyHotkey(generic);
  46373. var isApple = apple && lib$1.isKeyHotkey(apple);
  46374. var isWindows = windows && lib$1.isKeyHotkey(windows);
  46375. return event => {
  46376. if (isGeneric && isGeneric(event)) return true;
  46377. if (IS_APPLE && isApple && isApple(event)) return true;
  46378. if (!IS_APPLE && isWindows && isWindows(event)) return true;
  46379. return false;
  46380. };
  46381. };
  46382. /**
  46383. * Hotkeys.
  46384. */
  46385. var Hotkeys = {
  46386. isBold: create('bold'),
  46387. isCompose: create('compose'),
  46388. isMoveBackward: create('moveBackward'),
  46389. isMoveForward: create('moveForward'),
  46390. isDeleteBackward: create('deleteBackward'),
  46391. isDeleteForward: create('deleteForward'),
  46392. isDeleteLineBackward: create('deleteLineBackward'),
  46393. isDeleteLineForward: create('deleteLineForward'),
  46394. isDeleteWordBackward: create('deleteWordBackward'),
  46395. isDeleteWordForward: create('deleteWordForward'),
  46396. isExtendBackward: create('extendBackward'),
  46397. isExtendForward: create('extendForward'),
  46398. isExtendLineBackward: create('extendLineBackward'),
  46399. isExtendLineForward: create('extendLineForward'),
  46400. isItalic: create('italic'),
  46401. isMoveLineBackward: create('moveLineBackward'),
  46402. isMoveLineForward: create('moveLineForward'),
  46403. isMoveWordBackward: create('moveWordBackward'),
  46404. isMoveWordForward: create('moveWordForward'),
  46405. isRedo: create('redo'),
  46406. isSplitBlock: create('splitBlock'),
  46407. isTransposeCharacter: create('transposeCharacter'),
  46408. isUndo: create('undo')
  46409. };
  46410. /**
  46411. * A React context for sharing the `readOnly` state of the editor.
  46412. */
  46413. var ReadOnlyContext = React.createContext(false);
  46414. /**
  46415. * Get the current `readOnly` state of the editor.
  46416. */
  46417. var useReadOnly = () => {
  46418. return React.useContext(ReadOnlyContext);
  46419. };
  46420. /**
  46421. * A React context for sharing the editor object, in a way that re-renders the
  46422. * context whenever changes occur.
  46423. */
  46424. const SlateContext = React.createContext(null);
  46425. /**
  46426. * Get the current editor object from the React context.
  46427. */
  46428. const useSlate = () => {
  46429. const context = React.useContext(SlateContext);
  46430. if (!context) {
  46431. throw new Error(`The \`useSlate\` hook must be used inside the <SlateProvider> component's context.`);
  46432. }
  46433. const [editor] = context;
  46434. return editor;
  46435. };
  46436. /**
  46437. * Types.
  46438. */
  46439. /**
  46440. * Check if a DOM node is a comment node.
  46441. */
  46442. var isDOMComment = value => {
  46443. return isDOMNode(value) && value.nodeType === 8;
  46444. };
  46445. /**
  46446. * Check if a DOM node is an element node.
  46447. */
  46448. var isDOMElement = value => {
  46449. return isDOMNode(value) && value.nodeType === 1;
  46450. };
  46451. /**
  46452. * Check if a value is a DOM node.
  46453. */
  46454. var isDOMNode = value => {
  46455. return value instanceof Node;
  46456. };
  46457. /**
  46458. * Check if a DOM node is an element node.
  46459. */
  46460. var isDOMText = value => {
  46461. return isDOMNode(value) && value.nodeType === 3;
  46462. };
  46463. /**
  46464. * Normalize a DOM point so that it always refers to a text node.
  46465. */
  46466. var normalizeDOMPoint = domPoint => {
  46467. var [node, offset] = domPoint; // If it's an element node, its offset refers to the index of its children
  46468. // including comment nodes, so try to find the right text child node.
  46469. if (isDOMElement(node) && node.childNodes.length) {
  46470. var isLast = offset === node.childNodes.length;
  46471. var direction = isLast ? 'backward' : 'forward';
  46472. var index = isLast ? offset - 1 : offset;
  46473. node = getEditableChild(node, index, direction); // If the node has children, traverse until we have a leaf node. Leaf nodes
  46474. // can be either text nodes, or other void DOM nodes.
  46475. while (isDOMElement(node) && node.childNodes.length) {
  46476. var i = isLast ? node.childNodes.length - 1 : 0;
  46477. node = getEditableChild(node, i, direction);
  46478. } // Determine the new offset inside the text node.
  46479. offset = isLast && node.textContent != null ? node.textContent.length : 0;
  46480. } // Return the node and offset.
  46481. return [node, offset];
  46482. };
  46483. /**
  46484. * Get the nearest editable child at `index` in a `parent`, preferring
  46485. * `direction`.
  46486. */
  46487. var getEditableChild = (parent, index, direction) => {
  46488. var {
  46489. childNodes
  46490. } = parent;
  46491. var child = childNodes[index];
  46492. var i = index;
  46493. var triedForward = false;
  46494. var triedBackward = false; // While the child is a comment node, or an element node with no children,
  46495. // keep iterating to find a sibling non-void, non-comment node.
  46496. while (isDOMComment(child) || isDOMElement(child) && child.childNodes.length === 0 || isDOMElement(child) && child.getAttribute('contenteditable') === 'false') {
  46497. if (triedForward && triedBackward) {
  46498. break;
  46499. }
  46500. if (i >= childNodes.length) {
  46501. triedForward = true;
  46502. i = index - 1;
  46503. direction = 'backward';
  46504. continue;
  46505. }
  46506. if (i < 0) {
  46507. triedBackward = true;
  46508. i = index + 1;
  46509. direction = 'forward';
  46510. continue;
  46511. }
  46512. child = childNodes[i];
  46513. i += direction === 'forward' ? 1 : -1;
  46514. }
  46515. return child;
  46516. };
  46517. /**
  46518. * Editable.
  46519. */
  46520. const Editable = (props) => {
  46521. const { autoFocus, decorate = defaultDecorate, onDOMBeforeInput: propsOnDOMBeforeInput, placeholder, readOnly = false, renderElement, renderLeaf, style = {}, as: Component = 'div', ...attributes } = props;
  46522. const editor = useSlate();
  46523. const ref = React.useRef(null);
  46524. // Update internal state on each render.
  46525. IS_READ_ONLY.set(editor, readOnly);
  46526. // Keep track of some state for the event handler logic.
  46527. const state = React.useMemo(() => ({
  46528. isComposing: false,
  46529. isUpdatingSelection: false,
  46530. latestElement: null,
  46531. }), []);
  46532. // Update element-related weak maps with the DOM element ref.
  46533. useIsomorphicLayoutEffect(() => {
  46534. if (ref.current) {
  46535. EDITOR_TO_ELEMENT.set(editor, ref.current);
  46536. NODE_TO_ELEMENT.set(editor, ref.current);
  46537. ELEMENT_TO_NODE.set(ref.current, editor);
  46538. }
  46539. else {
  46540. NODE_TO_ELEMENT.delete(editor);
  46541. }
  46542. });
  46543. // Attach a native DOM event handler for `selectionchange`, because React's
  46544. // built-in `onSelect` handler doesn't fire for all selection changes. It's a
  46545. // leaky polyfill that only fires on keypresses or clicks. Instead, we want to
  46546. // fire for any change to the selection inside the editor. (2019/11/04)
  46547. // https://github.com/facebook/react/issues/5785
  46548. useIsomorphicLayoutEffect(() => {
  46549. window.document.addEventListener('selectionchange', onDOMSelectionChange);
  46550. return () => {
  46551. window.document.removeEventListener('selectionchange', onDOMSelectionChange);
  46552. };
  46553. }, []);
  46554. // Attach a native DOM event handler for `beforeinput` events, because React's
  46555. // built-in `onBeforeInput` is actually a leaky polyfill that doesn't expose
  46556. // real `beforeinput` events sadly... (2019/11/04)
  46557. // https://github.com/facebook/react/issues/11211
  46558. useIsomorphicLayoutEffect(() => {
  46559. if (ref.current) {
  46560. // @ts-ignore The `beforeinput` event isn't recognized.
  46561. ref.current.addEventListener('beforeinput', onDOMBeforeInput);
  46562. }
  46563. return () => {
  46564. if (ref.current) {
  46565. // @ts-ignore The `beforeinput` event isn't recognized.
  46566. ref.current.removeEventListener('beforeinput', onDOMBeforeInput);
  46567. }
  46568. };
  46569. }, []);
  46570. // Whenever the editor updates, make sure the DOM selection state is in sync.
  46571. useIsomorphicLayoutEffect(() => {
  46572. const { selection } = editor;
  46573. const domSelection = window.getSelection();
  46574. if (state.isComposing || !domSelection || !ReactEditor.isFocused(editor)) {
  46575. return;
  46576. }
  46577. const hasDomSelection = domSelection.type !== 'None';
  46578. // If the DOM selection is properly unset, we're done.
  46579. if (!selection && !hasDomSelection) {
  46580. return;
  46581. }
  46582. const newDomRange = selection && ReactEditor.toDOMRange(editor, selection);
  46583. // If the DOM selection is already correct, we're done.
  46584. if (hasDomSelection &&
  46585. newDomRange &&
  46586. isRangeEqual(domSelection.getRangeAt(0), newDomRange)) {
  46587. return;
  46588. }
  46589. // Otherwise the DOM selection is out of sync, so update it.
  46590. const el = ReactEditor.toDOMNode(editor, editor);
  46591. state.isUpdatingSelection = true;
  46592. domSelection.removeAllRanges();
  46593. if (newDomRange) {
  46594. domSelection.addRange(newDomRange);
  46595. const leafEl = newDomRange.startContainer.parentElement;
  46596. scrollIntoView(leafEl, { scrollMode: 'if-needed' });
  46597. }
  46598. setTimeout(() => {
  46599. // COMPAT: In Firefox, it's not enough to create a range, you also need
  46600. // to focus the contenteditable element too. (2016/11/16)
  46601. if (newDomRange && IS_FIREFOX) {
  46602. el.focus();
  46603. }
  46604. state.isUpdatingSelection = false;
  46605. });
  46606. });
  46607. // The autoFocus TextareaHTMLAttribute doesn't do anything on a div, so it
  46608. // needs to be manually focused.
  46609. React.useEffect(() => {
  46610. if (ref.current && autoFocus) {
  46611. ref.current.focus();
  46612. }
  46613. }, [autoFocus]);
  46614. // Listen on the native `beforeinput` event to get real "Level 2" events. This
  46615. // is required because React's `beforeinput` is fake and never really attaches
  46616. // to the real event sadly. (2019/11/01)
  46617. // https://github.com/facebook/react/issues/11211
  46618. const onDOMBeforeInput = React.useCallback((event) => {
  46619. if (!readOnly &&
  46620. hasEditableTarget(editor, event.target) &&
  46621. !isDOMEventHandled(event, propsOnDOMBeforeInput)) {
  46622. const { selection } = editor;
  46623. const { inputType: type } = event;
  46624. const data = event.dataTransfer || event.data || undefined;
  46625. // These two types occur while a user is composing text and can't be
  46626. // cancelled. Let them through and wait for the composition to end.
  46627. if (type === 'insertCompositionText' ||
  46628. type === 'deleteCompositionText') {
  46629. return;
  46630. }
  46631. event.preventDefault();
  46632. // COMPAT: For the deleting forward/backward input types we don't want
  46633. // to change the selection because it is the range that will be deleted,
  46634. // and those commands determine that for themselves.
  46635. if (!type.startsWith('delete') || type.startsWith('deleteBy')) {
  46636. const [targetRange] = event.getTargetRanges();
  46637. if (targetRange) {
  46638. const range = ReactEditor.toSlateRange(editor, targetRange);
  46639. if (!selection || !dist$4.Range.equals(selection, range)) {
  46640. dist$4.Transforms.select(editor, range);
  46641. }
  46642. }
  46643. }
  46644. // COMPAT: If the selection is expanded, even if the command seems like
  46645. // a delete forward/backward command it should delete the selection.
  46646. if (selection &&
  46647. dist$4.Range.isExpanded(selection) &&
  46648. type.startsWith('delete')) {
  46649. dist$4.Editor.deleteFragment(editor);
  46650. return;
  46651. }
  46652. switch (type) {
  46653. case 'deleteByComposition':
  46654. case 'deleteByCut':
  46655. case 'deleteByDrag': {
  46656. dist$4.Editor.deleteFragment(editor);
  46657. break;
  46658. }
  46659. case 'deleteContent':
  46660. case 'deleteContentForward': {
  46661. dist$4.Editor.deleteForward(editor);
  46662. break;
  46663. }
  46664. case 'deleteContentBackward': {
  46665. dist$4.Editor.deleteBackward(editor);
  46666. break;
  46667. }
  46668. case 'deleteEntireSoftLine': {
  46669. dist$4.Editor.deleteBackward(editor, { unit: 'line' });
  46670. dist$4.Editor.deleteForward(editor, { unit: 'line' });
  46671. break;
  46672. }
  46673. case 'deleteHardLineBackward': {
  46674. dist$4.Editor.deleteBackward(editor, { unit: 'block' });
  46675. break;
  46676. }
  46677. case 'deleteSoftLineBackward': {
  46678. dist$4.Editor.deleteBackward(editor, { unit: 'line' });
  46679. break;
  46680. }
  46681. case 'deleteHardLineForward': {
  46682. dist$4.Editor.deleteForward(editor, { unit: 'block' });
  46683. break;
  46684. }
  46685. case 'deleteSoftLineForward': {
  46686. dist$4.Editor.deleteForward(editor, { unit: 'line' });
  46687. break;
  46688. }
  46689. case 'deleteWordBackward': {
  46690. dist$4.Editor.deleteBackward(editor, { unit: 'word' });
  46691. break;
  46692. }
  46693. case 'deleteWordForward': {
  46694. dist$4.Editor.deleteForward(editor, { unit: 'word' });
  46695. break;
  46696. }
  46697. case 'insertLineBreak':
  46698. case 'insertParagraph': {
  46699. dist$4.Editor.insertBreak(editor);
  46700. break;
  46701. }
  46702. case 'insertFromComposition':
  46703. case 'insertFromDrop':
  46704. case 'insertFromPaste':
  46705. case 'insertFromYank':
  46706. case 'insertReplacementText':
  46707. case 'insertText': {
  46708. if (data instanceof DataTransfer) {
  46709. ReactEditor.insertData(editor, data);
  46710. }
  46711. else if (typeof data === 'string') {
  46712. dist$4.Editor.insertText(editor, data);
  46713. }
  46714. break;
  46715. }
  46716. }
  46717. }
  46718. }, []);
  46719. // Listen on the native `selectionchange` event to be able to update any time
  46720. // the selection changes. This is required because React's `onSelect` is leaky
  46721. // and non-standard so it doesn't fire until after a selection has been
  46722. // released. This causes issues in situations where another change happens
  46723. // while a selection is being dragged.
  46724. const onDOMSelectionChange = React.useCallback(debounce(() => {
  46725. if (!readOnly && !state.isComposing && !state.isUpdatingSelection) {
  46726. const { activeElement } = window.document;
  46727. const el = ReactEditor.toDOMNode(editor, editor);
  46728. const domSelection = window.getSelection();
  46729. const domRange = domSelection &&
  46730. domSelection.rangeCount > 0 &&
  46731. domSelection.getRangeAt(0);
  46732. if (activeElement === el) {
  46733. state.latestElement = activeElement;
  46734. IS_FOCUSED.set(editor, true);
  46735. }
  46736. else {
  46737. IS_FOCUSED.delete(editor);
  46738. }
  46739. if (domRange &&
  46740. hasEditableTarget(editor, domRange.startContainer) &&
  46741. hasEditableTarget(editor, domRange.endContainer)) {
  46742. const range = ReactEditor.toSlateRange(editor, domRange);
  46743. dist$4.Transforms.select(editor, range);
  46744. }
  46745. else {
  46746. dist$4.Transforms.deselect(editor);
  46747. }
  46748. }
  46749. }, 100), []);
  46750. const decorations = decorate([editor, []]);
  46751. if (placeholder &&
  46752. editor.children.length === 1 &&
  46753. Array.from(dist$4.Node.texts(editor)).length === 1 &&
  46754. dist$4.Node.string(editor) === '') {
  46755. const start = dist$4.Editor.start(editor, []);
  46756. decorations.push({
  46757. [PLACEHOLDER_SYMBOL]: true,
  46758. placeholder,
  46759. anchor: start,
  46760. focus: start,
  46761. });
  46762. }
  46763. return (React__default.createElement(ReadOnlyContext.Provider, { value: readOnly },
  46764. React__default.createElement(Component
  46765. // COMPAT: The Grammarly Chrome extension works by changing the DOM
  46766. // out from under `contenteditable` elements, which leads to weird
  46767. // behaviors so we have to disable it like editor. (2017/04/24)
  46768. , Object.assign({ "data-gramm": false, role: readOnly ? undefined : 'textbox' }, attributes, {
  46769. // COMPAT: Firefox doesn't support the `beforeinput` event, so we'd
  46770. // have to use hacks to make these replacement-based features work.
  46771. 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: {
  46772. // Prevent the default outline styles.
  46773. outline: 'none',
  46774. // Preserve adjacent whitespace and new lines.
  46775. whiteSpace: 'pre-wrap',
  46776. // Allow words to break if they are too long.
  46777. wordWrap: 'break-word',
  46778. // Allow for passed-in styles to override anything.
  46779. ...style,
  46780. }, onBeforeInput: React.useCallback((event) => {
  46781. // COMPAT: Firefox doesn't support the `beforeinput` event, so we
  46782. // fall back to React's leaky polyfill instead just for it. It
  46783. // only works for the `insertText` input type.
  46784. if (IS_FIREFOX && !readOnly) {
  46785. event.preventDefault();
  46786. const text = event.data;
  46787. dist$4.Editor.insertText(editor, text);
  46788. }
  46789. }, [readOnly]), onBlur: React.useCallback((event) => {
  46790. if (readOnly ||
  46791. state.isUpdatingSelection ||
  46792. !hasEditableTarget(editor, event.target) ||
  46793. isEventHandled(event, attributes.onBlur)) {
  46794. return;
  46795. }
  46796. // COMPAT: If the current `activeElement` is still the previous
  46797. // one, this is due to the window being blurred when the tab
  46798. // itself becomes unfocused, so we want to abort early to allow to
  46799. // editor to stay focused when the tab becomes focused again.
  46800. if (state.latestElement === window.document.activeElement) {
  46801. return;
  46802. }
  46803. const { relatedTarget } = event;
  46804. const el = ReactEditor.toDOMNode(editor, editor);
  46805. // COMPAT: The event should be ignored if the focus is returning
  46806. // to the editor from an embedded editable element (eg. an <input>
  46807. // element inside a void node).
  46808. if (relatedTarget === el) {
  46809. return;
  46810. }
  46811. // COMPAT: The event should be ignored if the focus is moving from
  46812. // the editor to inside a void node's spacer element.
  46813. if (isDOMElement(relatedTarget) &&
  46814. relatedTarget.hasAttribute('data-slate-spacer')) {
  46815. return;
  46816. }
  46817. // COMPAT: The event should be ignored if the focus is moving to a
  46818. // non- editable section of an element that isn't a void node (eg.
  46819. // a list item of the check list example).
  46820. if (relatedTarget != null &&
  46821. isDOMNode(relatedTarget) &&
  46822. ReactEditor.hasDOMNode(editor, relatedTarget)) {
  46823. const node = ReactEditor.toSlateNode(editor, relatedTarget);
  46824. if (dist$4.Element.isElement(node) && !editor.isVoid(node)) {
  46825. return;
  46826. }
  46827. }
  46828. IS_FOCUSED.delete(editor);
  46829. }, [readOnly, attributes.onBlur]), onClick: React.useCallback((event) => {
  46830. if (!readOnly &&
  46831. hasTarget(editor, event.target) &&
  46832. !isEventHandled(event, attributes.onClick) &&
  46833. isDOMNode(event.target)) {
  46834. const node = ReactEditor.toSlateNode(editor, event.target);
  46835. const path = ReactEditor.findPath(editor, node);
  46836. const start = dist$4.Editor.start(editor, path);
  46837. if (dist$4.Editor.void(editor, { at: start })) {
  46838. const range = dist$4.Editor.range(editor, start);
  46839. dist$4.Transforms.select(editor, range);
  46840. }
  46841. }
  46842. }, [readOnly, attributes.onClick]), onCompositionEnd: React.useCallback((event) => {
  46843. if (hasEditableTarget(editor, event.target) &&
  46844. !isEventHandled(event, attributes.onCompositionEnd)) {
  46845. state.isComposing = false;
  46846. // COMPAT: In Chrome, `beforeinput` events for compositions
  46847. // aren't correct and never fire the "insertFromComposition"
  46848. // type that we need. So instead, insert whenever a composition
  46849. // ends since it will already have been committed to the DOM.
  46850. if (!IS_SAFARI && !IS_FIREFOX && event.data) {
  46851. dist$4.Editor.insertText(editor, event.data);
  46852. }
  46853. }
  46854. }, [attributes.onCompositionEnd]), onCompositionStart: React.useCallback((event) => {
  46855. if (hasEditableTarget(editor, event.target) &&
  46856. !isEventHandled(event, attributes.onCompositionStart)) {
  46857. state.isComposing = true;
  46858. }
  46859. }, [attributes.onCompositionStart]), onCopy: React.useCallback((event) => {
  46860. if (hasEditableTarget(editor, event.target) &&
  46861. !isEventHandled(event, attributes.onCopy)) {
  46862. event.preventDefault();
  46863. setFragmentData(event.clipboardData, editor);
  46864. }
  46865. }, [attributes.onCopy]), onCut: React.useCallback((event) => {
  46866. if (!readOnly &&
  46867. hasEditableTarget(editor, event.target) &&
  46868. !isEventHandled(event, attributes.onCut)) {
  46869. event.preventDefault();
  46870. setFragmentData(event.clipboardData, editor);
  46871. const { selection } = editor;
  46872. if (selection && dist$4.Range.isExpanded(selection)) {
  46873. dist$4.Editor.deleteFragment(editor);
  46874. }
  46875. }
  46876. }, [readOnly, attributes.onCut]), onDragOver: React.useCallback((event) => {
  46877. if (hasTarget(editor, event.target) &&
  46878. !isEventHandled(event, attributes.onDragOver)) {
  46879. // Only when the target is void, call `preventDefault` to signal
  46880. // that drops are allowed. Editable content is droppable by
  46881. // default, and calling `preventDefault` hides the cursor.
  46882. const node = ReactEditor.toSlateNode(editor, event.target);
  46883. if (dist$4.Editor.isVoid(editor, node)) {
  46884. event.preventDefault();
  46885. }
  46886. }
  46887. }, [attributes.onDragOver]), onDragStart: React.useCallback((event) => {
  46888. if (hasTarget(editor, event.target) &&
  46889. !isEventHandled(event, attributes.onDragStart)) {
  46890. const node = ReactEditor.toSlateNode(editor, event.target);
  46891. const path = ReactEditor.findPath(editor, node);
  46892. const voidMatch = dist$4.Editor.void(editor, { at: path });
  46893. // If starting a drag on a void node, make sure it is selected
  46894. // so that it shows up in the selection's fragment.
  46895. if (voidMatch) {
  46896. const range = dist$4.Editor.range(editor, path);
  46897. dist$4.Transforms.select(editor, range);
  46898. }
  46899. setFragmentData(event.dataTransfer, editor);
  46900. }
  46901. }, [attributes.onDragStart]), onDrop: React.useCallback((event) => {
  46902. if (hasTarget(editor, event.target) &&
  46903. !readOnly &&
  46904. !isEventHandled(event, attributes.onDrop)) {
  46905. // COMPAT: Firefox doesn't fire `beforeinput` events at all, and
  46906. // Chromium browsers don't properly fire them for files being
  46907. // dropped into a `contenteditable`. (2019/11/26)
  46908. // https://bugs.chromium.org/p/chromium/issues/detail?id=1028668
  46909. if (IS_FIREFOX ||
  46910. (!IS_SAFARI && event.dataTransfer.files.length > 0)) {
  46911. event.preventDefault();
  46912. const range = ReactEditor.findEventRange(editor, event);
  46913. const data = event.dataTransfer;
  46914. dist$4.Transforms.select(editor, range);
  46915. ReactEditor.insertData(editor, data);
  46916. }
  46917. }
  46918. }, [readOnly, attributes.onDrop]), onFocus: React.useCallback((event) => {
  46919. if (!readOnly &&
  46920. !state.isUpdatingSelection &&
  46921. hasEditableTarget(editor, event.target) &&
  46922. !isEventHandled(event, attributes.onFocus)) {
  46923. const el = ReactEditor.toDOMNode(editor, editor);
  46924. state.latestElement = window.document.activeElement;
  46925. // COMPAT: If the editor has nested editable elements, the focus
  46926. // can go to them. In Firefox, this must be prevented because it
  46927. // results in issues with keyboard navigation. (2017/03/30)
  46928. if (IS_FIREFOX && event.target !== el) {
  46929. el.focus();
  46930. return;
  46931. }
  46932. IS_FOCUSED.set(editor, true);
  46933. }
  46934. }, [readOnly, attributes.onFocus]), onKeyDown: React.useCallback((event) => {
  46935. if (!readOnly &&
  46936. hasEditableTarget(editor, event.target) &&
  46937. !isEventHandled(event, attributes.onKeyDown)) {
  46938. const { nativeEvent } = event;
  46939. const { selection } = editor;
  46940. // COMPAT: Since we prevent the default behavior on
  46941. // `beforeinput` events, the browser doesn't think there's ever
  46942. // any history stack to undo or redo, so we have to manage these
  46943. // hotkeys ourselves. (2019/11/06)
  46944. if (Hotkeys.isRedo(nativeEvent)) {
  46945. event.preventDefault();
  46946. if (editor.redo) {
  46947. editor.redo();
  46948. }
  46949. return;
  46950. }
  46951. if (Hotkeys.isUndo(nativeEvent)) {
  46952. event.preventDefault();
  46953. if (editor.undo) {
  46954. editor.undo();
  46955. }
  46956. return;
  46957. }
  46958. // COMPAT: Certain browsers don't handle the selection updates
  46959. // properly. In Chrome, the selection isn't properly extended.
  46960. // And in Firefox, the selection isn't properly collapsed.
  46961. // (2017/10/17)
  46962. if (Hotkeys.isMoveLineBackward(nativeEvent)) {
  46963. event.preventDefault();
  46964. dist$4.Transforms.move(editor, { unit: 'line', reverse: true });
  46965. return;
  46966. }
  46967. if (Hotkeys.isMoveLineForward(nativeEvent)) {
  46968. event.preventDefault();
  46969. dist$4.Transforms.move(editor, { unit: 'line' });
  46970. return;
  46971. }
  46972. if (Hotkeys.isExtendLineBackward(nativeEvent)) {
  46973. event.preventDefault();
  46974. dist$4.Transforms.move(editor, {
  46975. unit: 'line',
  46976. edge: 'focus',
  46977. reverse: true,
  46978. });
  46979. return;
  46980. }
  46981. if (Hotkeys.isExtendLineForward(nativeEvent)) {
  46982. event.preventDefault();
  46983. dist$4.Transforms.move(editor, { unit: 'line', edge: 'focus' });
  46984. return;
  46985. }
  46986. // COMPAT: If a void node is selected, or a zero-width text node
  46987. // adjacent to an inline is selected, we need to handle these
  46988. // hotkeys manually because browsers won't be able to skip over
  46989. // the void node with the zero-width space not being an empty
  46990. // string.
  46991. if (Hotkeys.isMoveBackward(nativeEvent)) {
  46992. event.preventDefault();
  46993. if (selection && dist$4.Range.isCollapsed(selection)) {
  46994. dist$4.Transforms.move(editor, { reverse: true });
  46995. }
  46996. else {
  46997. dist$4.Transforms.collapse(editor, { edge: 'start' });
  46998. }
  46999. return;
  47000. }
  47001. if (Hotkeys.isMoveForward(nativeEvent)) {
  47002. event.preventDefault();
  47003. if (selection && dist$4.Range.isCollapsed(selection)) {
  47004. dist$4.Transforms.move(editor);
  47005. }
  47006. else {
  47007. dist$4.Transforms.collapse(editor, { edge: 'end' });
  47008. }
  47009. return;
  47010. }
  47011. if (Hotkeys.isMoveWordBackward(nativeEvent)) {
  47012. event.preventDefault();
  47013. dist$4.Transforms.move(editor, { unit: 'word', reverse: true });
  47014. return;
  47015. }
  47016. if (Hotkeys.isMoveWordForward(nativeEvent)) {
  47017. event.preventDefault();
  47018. dist$4.Transforms.move(editor, { unit: 'word' });
  47019. return;
  47020. }
  47021. // COMPAT: Firefox doesn't support the `beforeinput` event, so we
  47022. // fall back to guessing at the input intention for hotkeys.
  47023. // COMPAT: In iOS, some of these hotkeys are handled in the
  47024. if (IS_FIREFOX) {
  47025. // We don't have a core behavior for these, but they change the
  47026. // DOM if we don't prevent them, so we have to.
  47027. if (Hotkeys.isBold(nativeEvent) ||
  47028. Hotkeys.isItalic(nativeEvent) ||
  47029. Hotkeys.isTransposeCharacter(nativeEvent)) {
  47030. event.preventDefault();
  47031. return;
  47032. }
  47033. if (Hotkeys.isSplitBlock(nativeEvent)) {
  47034. event.preventDefault();
  47035. dist$4.Editor.insertBreak(editor);
  47036. return;
  47037. }
  47038. if (Hotkeys.isDeleteBackward(nativeEvent)) {
  47039. event.preventDefault();
  47040. if (selection && dist$4.Range.isExpanded(selection)) {
  47041. dist$4.Editor.deleteFragment(editor);
  47042. }
  47043. else {
  47044. dist$4.Editor.deleteBackward(editor);
  47045. }
  47046. return;
  47047. }
  47048. if (Hotkeys.isDeleteForward(nativeEvent)) {
  47049. event.preventDefault();
  47050. if (selection && dist$4.Range.isExpanded(selection)) {
  47051. dist$4.Editor.deleteFragment(editor);
  47052. }
  47053. else {
  47054. dist$4.Editor.deleteForward(editor);
  47055. }
  47056. return;
  47057. }
  47058. if (Hotkeys.isDeleteLineBackward(nativeEvent)) {
  47059. event.preventDefault();
  47060. if (selection && dist$4.Range.isExpanded(selection)) {
  47061. dist$4.Editor.deleteFragment(editor);
  47062. }
  47063. else {
  47064. dist$4.Editor.deleteBackward(editor, { unit: 'line' });
  47065. }
  47066. return;
  47067. }
  47068. if (Hotkeys.isDeleteLineForward(nativeEvent)) {
  47069. event.preventDefault();
  47070. if (selection && dist$4.Range.isExpanded(selection)) {
  47071. dist$4.Editor.deleteFragment(editor);
  47072. }
  47073. else {
  47074. dist$4.Editor.deleteForward(editor, { unit: 'line' });
  47075. }
  47076. return;
  47077. }
  47078. if (Hotkeys.isDeleteWordBackward(nativeEvent)) {
  47079. event.preventDefault();
  47080. if (selection && dist$4.Range.isExpanded(selection)) {
  47081. dist$4.Editor.deleteFragment(editor);
  47082. }
  47083. else {
  47084. dist$4.Editor.deleteBackward(editor, { unit: 'word' });
  47085. }
  47086. return;
  47087. }
  47088. if (Hotkeys.isDeleteWordForward(nativeEvent)) {
  47089. event.preventDefault();
  47090. if (selection && dist$4.Range.isExpanded(selection)) {
  47091. dist$4.Editor.deleteFragment(editor);
  47092. }
  47093. else {
  47094. dist$4.Editor.deleteForward(editor, { unit: 'word' });
  47095. }
  47096. return;
  47097. }
  47098. }
  47099. }
  47100. }, [readOnly, attributes.onKeyDown]), onPaste: React.useCallback((event) => {
  47101. // COMPAT: Firefox doesn't support the `beforeinput` event, so we
  47102. // fall back to React's `onPaste` here instead.
  47103. if (IS_FIREFOX &&
  47104. !readOnly &&
  47105. hasEditableTarget(editor, event.target) &&
  47106. !isEventHandled(event, attributes.onPaste)) {
  47107. event.preventDefault();
  47108. ReactEditor.insertData(editor, event.clipboardData);
  47109. }
  47110. }, [readOnly, attributes.onPaste]) }),
  47111. React__default.createElement(Children, { decorate: decorate, decorations: decorations, node: editor, renderElement: renderElement, renderLeaf: renderLeaf, selection: editor.selection }))));
  47112. };
  47113. /**
  47114. * A default memoized decorate function.
  47115. */
  47116. const defaultDecorate = () => [];
  47117. /**
  47118. * Check if two DOM range objects are equal.
  47119. */
  47120. const isRangeEqual = (a, b) => {
  47121. return ((a.startContainer === b.startContainer &&
  47122. a.startOffset === b.startOffset &&
  47123. a.endContainer === b.endContainer &&
  47124. a.endOffset === b.endOffset) ||
  47125. (a.startContainer === b.endContainer &&
  47126. a.startOffset === b.endOffset &&
  47127. a.endContainer === b.startContainer &&
  47128. a.endOffset === b.startOffset));
  47129. };
  47130. /**
  47131. * Check if the target is in the editor.
  47132. */
  47133. const hasTarget = (editor, target) => {
  47134. return isDOMNode(target) && ReactEditor.hasDOMNode(editor, target);
  47135. };
  47136. /**
  47137. * Check if the target is editable and in the editor.
  47138. */
  47139. const hasEditableTarget = (editor, target) => {
  47140. return (isDOMNode(target) &&
  47141. ReactEditor.hasDOMNode(editor, target, { editable: true }));
  47142. };
  47143. /**
  47144. * Check if an event is overrided by a handler.
  47145. */
  47146. const isEventHandled = (event, handler) => {
  47147. if (!handler) {
  47148. return false;
  47149. }
  47150. handler(event);
  47151. return event.isDefaultPrevented() || event.isPropagationStopped();
  47152. };
  47153. /**
  47154. * Check if a DOM event is overrided by a handler.
  47155. */
  47156. const isDOMEventHandled = (event, handler) => {
  47157. if (!handler) {
  47158. return false;
  47159. }
  47160. handler(event);
  47161. return event.defaultPrevented;
  47162. };
  47163. /**
  47164. * Set the currently selected fragment to the clipboard.
  47165. */
  47166. const setFragmentData = (dataTransfer, editor) => {
  47167. const { selection } = editor;
  47168. if (!selection) {
  47169. return;
  47170. }
  47171. const [start, end] = dist$4.Range.edges(selection);
  47172. const startVoid = dist$4.Editor.void(editor, { at: start.path });
  47173. const endVoid = dist$4.Editor.void(editor, { at: end.path });
  47174. if (dist$4.Range.isCollapsed(selection) && !startVoid) {
  47175. return;
  47176. }
  47177. // Create a fake selection so that we can add a Base64-encoded copy of the
  47178. // fragment to the HTML, to decode on future pastes.
  47179. const domRange = ReactEditor.toDOMRange(editor, selection);
  47180. let contents = domRange.cloneContents();
  47181. let attach = contents.childNodes[0];
  47182. // Make sure attach is non-empty, since empty nodes will not get copied.
  47183. contents.childNodes.forEach(node => {
  47184. if (node.textContent && node.textContent.trim() !== '') {
  47185. attach = node;
  47186. }
  47187. });
  47188. // COMPAT: If the end node is a void node, we need to move the end of the
  47189. // range from the void node's spacer span, to the end of the void node's
  47190. // content, since the spacer is before void's content in the DOM.
  47191. if (endVoid) {
  47192. const [voidNode] = endVoid;
  47193. const r = domRange.cloneRange();
  47194. const domNode = ReactEditor.toDOMNode(editor, voidNode);
  47195. r.setEndAfter(domNode);
  47196. contents = r.cloneContents();
  47197. }
  47198. // COMPAT: If the start node is a void node, we need to attach the encoded
  47199. // fragment to the void node's content node instead of the spacer, because
  47200. // attaching it to empty `<div>/<span>` nodes will end up having it erased by
  47201. // most browsers. (2018/04/27)
  47202. if (startVoid) {
  47203. attach = contents.querySelector('[data-slate-spacer]');
  47204. }
  47205. // Remove any zero-width space spans from the cloned DOM so that they don't
  47206. // show up elsewhere when pasted.
  47207. Array.from(contents.querySelectorAll('[data-slate-zero-width]')).forEach(zw => {
  47208. const isNewline = zw.getAttribute('data-slate-zero-width') === 'n';
  47209. zw.textContent = isNewline ? '\n' : '';
  47210. });
  47211. // Set a `data-slate-fragment` attribute on a non-empty node, so it shows up
  47212. // in the HTML, and can be used for intra-Slate pasting. If it's a text
  47213. // node, wrap it in a `<span>` so we have something to set an attribute on.
  47214. if (isDOMText(attach)) {
  47215. const span = document.createElement('span');
  47216. // COMPAT: In Chrome and Safari, if we don't add the `white-space` style
  47217. // then leading and trailing spaces will be ignored. (2017/09/21)
  47218. span.style.whiteSpace = 'pre';
  47219. span.appendChild(attach);
  47220. contents.appendChild(span);
  47221. attach = span;
  47222. }
  47223. const fragment = dist$4.Node.fragment(editor, selection);
  47224. const string = JSON.stringify(fragment);
  47225. const encoded = window.btoa(encodeURIComponent(string));
  47226. attach.setAttribute('data-slate-fragment', encoded);
  47227. dataTransfer.setData('application/x-slate-fragment', encoded);
  47228. // Add the content to a <div> so that we can get its inner HTML.
  47229. const div = document.createElement('div');
  47230. div.appendChild(contents);
  47231. dataTransfer.setData('text/html', div.innerHTML);
  47232. dataTransfer.setData('text/plain', getPlainText(div));
  47233. };
  47234. /**
  47235. * Get a plaintext representation of the content of a node, accounting for block
  47236. * elements which get a newline appended.
  47237. */
  47238. const getPlainText = (domNode) => {
  47239. let text = '';
  47240. if (isDOMText(domNode) && domNode.nodeValue) {
  47241. return domNode.nodeValue;
  47242. }
  47243. if (isDOMElement(domNode)) {
  47244. for (const childNode of Array.from(domNode.childNodes)) {
  47245. text += getPlainText(childNode);
  47246. }
  47247. const display = getComputedStyle(domNode).getPropertyValue('display');
  47248. if (display === 'block' || display === 'list' || domNode.tagName === 'BR') {
  47249. text += '\n';
  47250. }
  47251. }
  47252. return text;
  47253. };
  47254. /**
  47255. * An auto-incrementing identifier for keys.
  47256. */
  47257. var n = 0;
  47258. /**
  47259. * A class that keeps track of a key string. We use a full class here because we
  47260. * want to be able to use them as keys in `WeakMap` objects.
  47261. */
  47262. class Key {
  47263. constructor() {
  47264. this.id = "".concat(n++);
  47265. }
  47266. }
  47267. var ReactEditor = {
  47268. /**
  47269. * Find a key for a Slate node.
  47270. */
  47271. findKey(editor, node) {
  47272. var key = NODE_TO_KEY.get(node);
  47273. if (!key) {
  47274. key = new Key();
  47275. NODE_TO_KEY.set(node, key);
  47276. }
  47277. return key;
  47278. },
  47279. /**
  47280. * Find the path of Slate node.
  47281. */
  47282. findPath(editor, node) {
  47283. var path = [];
  47284. var child = node;
  47285. while (true) {
  47286. var parent = NODE_TO_PARENT.get(child);
  47287. if (parent == null) {
  47288. if (dist$4.Editor.isEditor(child)) {
  47289. return path;
  47290. } else {
  47291. break;
  47292. }
  47293. }
  47294. var i = NODE_TO_INDEX.get(child);
  47295. if (i == null) {
  47296. break;
  47297. }
  47298. path.unshift(i);
  47299. child = parent;
  47300. }
  47301. throw new Error("Unable to find the path for Slate node: ".concat(JSON.stringify(node)));
  47302. },
  47303. /**
  47304. * Check if the editor is focused.
  47305. */
  47306. isFocused(editor) {
  47307. return !!IS_FOCUSED.get(editor);
  47308. },
  47309. /**
  47310. * Check if the editor is in read-only mode.
  47311. */
  47312. isReadOnly(editor) {
  47313. return !!IS_READ_ONLY.get(editor);
  47314. },
  47315. /**
  47316. * Blur the editor.
  47317. */
  47318. blur(editor) {
  47319. var el = ReactEditor.toDOMNode(editor, editor);
  47320. IS_FOCUSED.set(editor, false);
  47321. if (window.document.activeElement === el) {
  47322. el.blur();
  47323. }
  47324. },
  47325. /**
  47326. * Focus the editor.
  47327. */
  47328. focus(editor) {
  47329. var el = ReactEditor.toDOMNode(editor, editor);
  47330. IS_FOCUSED.set(editor, true);
  47331. if (window.document.activeElement !== el) {
  47332. el.focus({
  47333. preventScroll: true
  47334. });
  47335. }
  47336. },
  47337. /**
  47338. * Deselect the editor.
  47339. */
  47340. deselect(editor) {
  47341. var {
  47342. selection
  47343. } = editor;
  47344. var domSelection = window.getSelection();
  47345. if (domSelection && domSelection.rangeCount > 0) {
  47346. domSelection.removeAllRanges();
  47347. }
  47348. if (selection) {
  47349. dist$4.Transforms.deselect(editor);
  47350. }
  47351. },
  47352. /**
  47353. * Check if a DOM node is within the editor.
  47354. */
  47355. hasDOMNode(editor, target) {
  47356. var options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
  47357. var {
  47358. editable = false
  47359. } = options;
  47360. var el = ReactEditor.toDOMNode(editor, editor);
  47361. var element; // COMPAT: In Firefox, reading `target.nodeType` will throw an error if
  47362. // target is originating from an internal "restricted" element (e.g. a
  47363. // stepper arrow on a number input). (2018/05/04)
  47364. // https://github.com/ianstormtaylor/slate/issues/1819
  47365. try {
  47366. element = isDOMElement(target) ? target : target.parentElement;
  47367. } catch (err) {
  47368. if (!err.message.includes('Permission denied to access property "nodeType"')) {
  47369. throw err;
  47370. }
  47371. }
  47372. if (!element) {
  47373. return false;
  47374. }
  47375. return element.closest("[data-slate-editor]") === el && (!editable || el.isContentEditable);
  47376. },
  47377. /**
  47378. * Insert data from a `DataTransfer` into the editor.
  47379. */
  47380. insertData(editor, data) {
  47381. editor.insertData(data);
  47382. },
  47383. /**
  47384. * Find the native DOM element from a Slate node.
  47385. */
  47386. toDOMNode(editor, node) {
  47387. var domNode = dist$4.Editor.isEditor(node) ? EDITOR_TO_ELEMENT.get(editor) : KEY_TO_ELEMENT.get(ReactEditor.findKey(editor, node));
  47388. if (!domNode) {
  47389. throw new Error("Cannot resolve a DOM node from Slate node: ".concat(JSON.stringify(node)));
  47390. }
  47391. return domNode;
  47392. },
  47393. /**
  47394. * Find a native DOM selection point from a Slate point.
  47395. */
  47396. toDOMPoint(editor, point) {
  47397. var [node] = dist$4.Editor.node(editor, point.path);
  47398. var el = ReactEditor.toDOMNode(editor, node);
  47399. var domPoint; // If we're inside a void node, force the offset to 0, otherwise the zero
  47400. // width spacing character will result in an incorrect offset of 1
  47401. if (dist$4.Editor.void(editor, {
  47402. at: point
  47403. })) {
  47404. point = {
  47405. path: point.path,
  47406. offset: 0
  47407. };
  47408. } // For each leaf, we need to isolate its content, which means filtering
  47409. // to its direct text and zero-width spans. (We have to filter out any
  47410. // other siblings that may have been rendered alongside them.)
  47411. var selector = "[data-slate-string], [data-slate-zero-width]";
  47412. var texts = Array.from(el.querySelectorAll(selector));
  47413. var start = 0;
  47414. for (var text of texts) {
  47415. var domNode = text.childNodes[0];
  47416. if (domNode == null || domNode.textContent == null) {
  47417. continue;
  47418. }
  47419. var {
  47420. length
  47421. } = domNode.textContent;
  47422. var attr = text.getAttribute('data-slate-length');
  47423. var trueLength = attr == null ? length : parseInt(attr, 10);
  47424. var end = start + trueLength;
  47425. if (point.offset <= end) {
  47426. var offset = Math.min(length, Math.max(0, point.offset - start));
  47427. domPoint = [domNode, offset];
  47428. break;
  47429. }
  47430. start = end;
  47431. }
  47432. if (!domPoint) {
  47433. throw new Error("Cannot resolve a DOM point from Slate point: ".concat(JSON.stringify(point)));
  47434. }
  47435. return domPoint;
  47436. },
  47437. /**
  47438. * Find a native DOM range from a Slate `range`.
  47439. */
  47440. toDOMRange(editor, range) {
  47441. var {
  47442. anchor,
  47443. focus
  47444. } = range;
  47445. var domAnchor = ReactEditor.toDOMPoint(editor, anchor);
  47446. var domFocus = dist$4.Range.isCollapsed(range) ? domAnchor : ReactEditor.toDOMPoint(editor, focus);
  47447. var domRange = window.document.createRange();
  47448. var start = dist$4.Range.isBackward(range) ? domFocus : domAnchor;
  47449. var end = dist$4.Range.isBackward(range) ? domAnchor : domFocus;
  47450. domRange.setStart(start[0], start[1]);
  47451. domRange.setEnd(end[0], end[1]);
  47452. return domRange;
  47453. },
  47454. /**
  47455. * Find a Slate node from a native DOM `element`.
  47456. */
  47457. toSlateNode(editor, domNode) {
  47458. var domEl = isDOMElement(domNode) ? domNode : domNode.parentElement;
  47459. if (domEl && !domEl.hasAttribute('data-slate-node')) {
  47460. domEl = domEl.closest("[data-slate-node]");
  47461. }
  47462. var node = domEl ? ELEMENT_TO_NODE.get(domEl) : null;
  47463. if (!node) {
  47464. throw new Error("Cannot resolve a Slate node from DOM node: ".concat(domEl));
  47465. }
  47466. return node;
  47467. },
  47468. /**
  47469. * Get the target range from a DOM `event`.
  47470. */
  47471. findEventRange(editor, event) {
  47472. if ('nativeEvent' in event) {
  47473. event = event.nativeEvent;
  47474. }
  47475. var {
  47476. clientX: x,
  47477. clientY: y,
  47478. target
  47479. } = event;
  47480. if (x == null || y == null) {
  47481. throw new Error("Cannot resolve a Slate range from a DOM event: ".concat(event));
  47482. }
  47483. var node = ReactEditor.toSlateNode(editor, event.target);
  47484. var path = ReactEditor.findPath(editor, node); // If the drop target is inside a void node, move it into either the
  47485. // next or previous node, depending on which side the `x` and `y`
  47486. // coordinates are closest to.
  47487. if (dist$4.Editor.isVoid(editor, node)) {
  47488. var rect = target.getBoundingClientRect();
  47489. var isPrev = editor.isInline(node) ? x - rect.left < rect.left + rect.width - x : y - rect.top < rect.top + rect.height - y;
  47490. var edge = dist$4.Editor.point(editor, path, {
  47491. edge: isPrev ? 'start' : 'end'
  47492. });
  47493. var point = isPrev ? dist$4.Editor.before(editor, edge) : dist$4.Editor.after(editor, edge);
  47494. if (point) {
  47495. var _range = dist$4.Editor.range(editor, point);
  47496. return _range;
  47497. }
  47498. } // Else resolve a range from the caret position where the drop occured.
  47499. var domRange;
  47500. var {
  47501. document
  47502. } = window; // COMPAT: In Firefox, `caretRangeFromPoint` doesn't exist. (2016/07/25)
  47503. if (document.caretRangeFromPoint) {
  47504. domRange = document.caretRangeFromPoint(x, y);
  47505. } else {
  47506. var position = document.caretPositionFromPoint(x, y);
  47507. if (position) {
  47508. domRange = document.createRange();
  47509. domRange.setStart(position.offsetNode, position.offset);
  47510. domRange.setEnd(position.offsetNode, position.offset);
  47511. }
  47512. }
  47513. if (!domRange) {
  47514. throw new Error("Cannot resolve a Slate range from a DOM event: ".concat(event));
  47515. } // Resolve a Slate range from the DOM range.
  47516. var range = ReactEditor.toSlateRange(editor, domRange);
  47517. return range;
  47518. },
  47519. /**
  47520. * Find a Slate point from a DOM selection's `domNode` and `domOffset`.
  47521. */
  47522. toSlatePoint(editor, domPoint) {
  47523. var [nearestNode, nearestOffset] = normalizeDOMPoint(domPoint);
  47524. var parentNode = nearestNode.parentNode;
  47525. var textNode = null;
  47526. var offset = 0;
  47527. if (parentNode) {
  47528. var voidNode = parentNode.closest('[data-slate-void="true"]');
  47529. var leafNode = parentNode.closest('[data-slate-leaf]');
  47530. var domNode = null; // Calculate how far into the text node the `nearestNode` is, so that we
  47531. // can determine what the offset relative to the text node is.
  47532. if (leafNode) {
  47533. textNode = leafNode.closest('[data-slate-node="text"]');
  47534. var range = window.document.createRange();
  47535. range.setStart(textNode, 0);
  47536. range.setEnd(nearestNode, nearestOffset);
  47537. var contents = range.cloneContents();
  47538. var removals = [...contents.querySelectorAll('[data-slate-zero-width]'), ...contents.querySelectorAll('[contenteditable=false]')];
  47539. removals.forEach(el => {
  47540. el.parentNode.removeChild(el);
  47541. }); // COMPAT: Edge has a bug where Range.prototype.toString() will
  47542. // convert \n into \r\n. The bug causes a loop when slate-react
  47543. // attempts to reposition its cursor to match the native position. Use
  47544. // textContent.length instead.
  47545. // https://developer.microsoft.com/en-us/microsoft-edge/platform/issues/10291116/
  47546. offset = contents.textContent.length;
  47547. domNode = textNode;
  47548. } else if (voidNode) {
  47549. // For void nodes, the element with the offset key will be a cousin, not an
  47550. // ancestor, so find it by going down from the nearest void parent.
  47551. leafNode = voidNode.querySelector('[data-slate-leaf]');
  47552. textNode = leafNode.closest('[data-slate-node="text"]');
  47553. domNode = leafNode;
  47554. offset = domNode.textContent.length;
  47555. } // COMPAT: If the parent node is a Slate zero-width space, editor is
  47556. // because the text node should have no characters. However, during IME
  47557. // composition the ASCII characters will be prepended to the zero-width
  47558. // space, so subtract 1 from the offset to account for the zero-width
  47559. // space character.
  47560. if (domNode && offset === domNode.textContent.length && parentNode.hasAttribute('data-slate-zero-width')) {
  47561. offset--;
  47562. }
  47563. }
  47564. if (!textNode) {
  47565. throw new Error("Cannot resolve a Slate point from DOM point: ".concat(domPoint));
  47566. } // COMPAT: If someone is clicking from one Slate editor into another,
  47567. // the select event fires twice, once for the old editor's `element`
  47568. // first, and then afterwards for the correct `element`. (2017/03/03)
  47569. var slateNode = ReactEditor.toSlateNode(editor, textNode);
  47570. var path = ReactEditor.findPath(editor, slateNode);
  47571. return {
  47572. path,
  47573. offset
  47574. };
  47575. },
  47576. /**
  47577. * Find a Slate range from a DOM range or selection.
  47578. */
  47579. toSlateRange(editor, domRange) {
  47580. var el = domRange instanceof Selection ? domRange.anchorNode : domRange.startContainer;
  47581. var anchorNode;
  47582. var anchorOffset;
  47583. var focusNode;
  47584. var focusOffset;
  47585. var isCollapsed;
  47586. if (el) {
  47587. if (domRange instanceof Selection) {
  47588. anchorNode = domRange.anchorNode;
  47589. anchorOffset = domRange.anchorOffset;
  47590. focusNode = domRange.focusNode;
  47591. focusOffset = domRange.focusOffset;
  47592. isCollapsed = domRange.isCollapsed;
  47593. } else {
  47594. anchorNode = domRange.startContainer;
  47595. anchorOffset = domRange.startOffset;
  47596. focusNode = domRange.endContainer;
  47597. focusOffset = domRange.endOffset;
  47598. isCollapsed = domRange.collapsed;
  47599. }
  47600. }
  47601. if (anchorNode == null || focusNode == null || anchorOffset == null || focusOffset == null) {
  47602. throw new Error("Cannot resolve a Slate range from DOM range: ".concat(domRange));
  47603. }
  47604. var anchor = ReactEditor.toSlatePoint(editor, [anchorNode, anchorOffset]);
  47605. var focus = isCollapsed ? anchor : ReactEditor.toSlatePoint(editor, [focusNode, focusOffset]);
  47606. return {
  47607. anchor,
  47608. focus
  47609. };
  47610. }
  47611. };
  47612. /**
  47613. * A React context for sharing the `focused` state of the editor.
  47614. */
  47615. var FocusedContext = React.createContext(false);
  47616. /**
  47617. * Get the current `focused` state of the editor.
  47618. */
  47619. var useFocused = () => {
  47620. return React.useContext(FocusedContext);
  47621. };
  47622. /**
  47623. * A wrapper around the provider to handle `onChange` events, because the editor
  47624. * is a mutable singleton so it won't ever register as "changed" otherwise.
  47625. */
  47626. const Slate = (props) => {
  47627. const { editor, children, onChange, value, ...rest } = props;
  47628. const [key, setKey] = React.useState(0);
  47629. const context = React.useMemo(() => {
  47630. editor.children = value;
  47631. Object.assign(editor, rest);
  47632. return [editor];
  47633. }, [key, value, ...Object.values(rest)]);
  47634. const onContextChange = React.useCallback(() => {
  47635. onChange(editor.children);
  47636. setKey(key + 1);
  47637. }, [key, onChange]);
  47638. EDITOR_TO_ON_CHANGE.set(editor, onContextChange);
  47639. return (React__default.createElement(SlateContext.Provider, { value: context },
  47640. React__default.createElement(EditorContext.Provider, { value: editor },
  47641. React__default.createElement(FocusedContext.Provider, { value: ReactEditor.isFocused(editor) }, children))));
  47642. };
  47643. /**
  47644. * `withReact` adds React and DOM specific behaviors to the editor.
  47645. */
  47646. var withReact = editor => {
  47647. var e = editor;
  47648. var {
  47649. apply,
  47650. onChange
  47651. } = e;
  47652. e.apply = op => {
  47653. var matches = [];
  47654. switch (op.type) {
  47655. case 'insert_text':
  47656. case 'remove_text':
  47657. case 'set_node':
  47658. {
  47659. for (var [node, path] of dist$4.Editor.levels(e, {
  47660. at: op.path
  47661. })) {
  47662. var key = ReactEditor.findKey(e, node);
  47663. matches.push([path, key]);
  47664. }
  47665. break;
  47666. }
  47667. case 'insert_node':
  47668. case 'remove_node':
  47669. case 'merge_node':
  47670. case 'split_node':
  47671. {
  47672. for (var [_node, _path] of dist$4.Editor.levels(e, {
  47673. at: dist$4.Path.parent(op.path)
  47674. })) {
  47675. var _key = ReactEditor.findKey(e, _node);
  47676. matches.push([_path, _key]);
  47677. }
  47678. break;
  47679. }
  47680. }
  47681. apply(op);
  47682. for (var [_path2, _key2] of matches) {
  47683. var [_node2] = dist$4.Editor.node(e, _path2);
  47684. NODE_TO_KEY.set(_node2, _key2);
  47685. }
  47686. };
  47687. e.insertData = data => {
  47688. var fragment = data.getData('application/x-slate-fragment');
  47689. if (fragment) {
  47690. var decoded = decodeURIComponent(window.atob(fragment));
  47691. var parsed = JSON.parse(decoded);
  47692. dist$4.Transforms.insertFragment(e, parsed);
  47693. return;
  47694. }
  47695. var text = data.getData('text/plain');
  47696. if (text) {
  47697. var lines = text.split('\n');
  47698. var split = false;
  47699. for (var line of lines) {
  47700. if (split) {
  47701. dist$4.Transforms.splitNodes(e);
  47702. }
  47703. dist$4.Transforms.insertText(e, line);
  47704. split = true;
  47705. }
  47706. }
  47707. };
  47708. e.onChange = () => {
  47709. // COMPAT: React doesn't batch `setState` hook calls, which means that the
  47710. // children and selection can get out of sync for one render pass. So we
  47711. // have to use this unstable API to ensure it batches them. (2019/12/03)
  47712. // https://github.com/facebook/react/issues/14259#issuecomment-439702367
  47713. ReactDOM.unstable_batchedUpdates(() => {
  47714. var onContextChange = EDITOR_TO_ON_CHANGE.get(e);
  47715. if (onContextChange) {
  47716. onContextChange();
  47717. }
  47718. onChange();
  47719. });
  47720. };
  47721. return e;
  47722. };
  47723. exports.DefaultElement = DefaultElement;
  47724. exports.DefaultLeaf = DefaultLeaf;
  47725. exports.Editable = Editable;
  47726. exports.ReactEditor = ReactEditor;
  47727. exports.Slate = Slate;
  47728. exports.useEditor = useEditor;
  47729. exports.useFocused = useFocused;
  47730. exports.useReadOnly = useReadOnly;
  47731. exports.useSelected = useSelected;
  47732. exports.useSlate = useSlate;
  47733. exports.withReact = withReact;
  47734. });
  47735. unwrapExports(dist$5);
  47736. var dist_1$3 = dist$5.DefaultElement;
  47737. var dist_2$3 = dist$5.DefaultLeaf;
  47738. var dist_3$3 = dist$5.Editable;
  47739. var dist_4$2 = dist$5.ReactEditor;
  47740. var dist_5$2 = dist$5.Slate;
  47741. var dist_6$2 = dist$5.useEditor;
  47742. var dist_7$1 = dist$5.useFocused;
  47743. var dist_8$1 = dist$5.useReadOnly;
  47744. var dist_9$1 = dist$5.useSelected;
  47745. var dist_10$1 = dist$5.useSlate;
  47746. var dist_11$1 = dist$5.withReact;
  47747. var RichTextEditorForSlate = function RichTextEditorForSlate() {
  47748. var editor = useMemo(function () {
  47749. return dist_11$1(dist_15());
  47750. }, []);
  47751. var _useState = useState([{
  47752. type: 'paragraph',
  47753. children: [{
  47754. text: 'A line of text in a paragraph.'
  47755. }]
  47756. }]),
  47757. _useState2 = _slicedToArray(_useState, 2),
  47758. value = _useState2[0],
  47759. setValue = _useState2[1];
  47760. return (// Add the editable component inside the context.
  47761. React.createElement(dist_5$2, {
  47762. editor: editor,
  47763. value: value,
  47764. onChange: function onChange(value) {
  47765. console.log('value: ', value);
  47766. setValue(value);
  47767. }
  47768. }, React.createElement(dist_3$3, null))
  47769. );
  47770. }; // class RichTextEditorForSlate extends React.Component<RichTextEditorForSlateProps, RichTextEditorForSlateState> {
  47771. export { BarftEditorPage as BraftEditor, RichTextEditor, RichTextEditorForSlate };
  47772. //# sourceMappingURL=index.js.map