App.tsx 288 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431
  1. import React, { useContext } from "react";
  2. import { flushSync } from "react-dom";
  3. import { RoughCanvas } from "roughjs/bin/canvas";
  4. import rough from "roughjs/bin/rough";
  5. import clsx from "clsx";
  6. import { nanoid } from "nanoid";
  7. import {
  8. actionAddToLibrary,
  9. actionBringForward,
  10. actionBringToFront,
  11. actionCopy,
  12. actionCopyAsPng,
  13. actionCopyAsSvg,
  14. copyText,
  15. actionCopyStyles,
  16. actionCut,
  17. actionDeleteSelected,
  18. actionDuplicateSelection,
  19. actionFinalize,
  20. actionFlipHorizontal,
  21. actionFlipVertical,
  22. actionGroup,
  23. actionPasteStyles,
  24. actionSelectAll,
  25. actionSendBackward,
  26. actionSendToBack,
  27. actionToggleGridMode,
  28. actionToggleStats,
  29. actionToggleZenMode,
  30. actionUnbindText,
  31. actionBindText,
  32. actionUngroup,
  33. actionLink,
  34. actionToggleElementLock,
  35. actionToggleLinearEditor,
  36. actionToggleObjectsSnapMode,
  37. } from "../actions";
  38. import { createRedoAction, createUndoAction } from "../actions/actionHistory";
  39. import { ActionManager } from "../actions/manager";
  40. import { actions } from "../actions/register";
  41. import { Action, ActionResult } from "../actions/types";
  42. import { trackEvent } from "../analytics";
  43. import {
  44. getDefaultAppState,
  45. isEraserActive,
  46. isHandToolActive,
  47. } from "../appState";
  48. import {
  49. PastedMixedContent,
  50. copyTextToSystemClipboard,
  51. parseClipboard,
  52. } from "../clipboard";
  53. import {
  54. APP_NAME,
  55. CURSOR_TYPE,
  56. DEFAULT_MAX_IMAGE_WIDTH_OR_HEIGHT,
  57. DEFAULT_VERTICAL_ALIGN,
  58. DRAGGING_THRESHOLD,
  59. ELEMENT_SHIFT_TRANSLATE_AMOUNT,
  60. ELEMENT_TRANSLATE_AMOUNT,
  61. ENV,
  62. EVENT,
  63. FRAME_STYLE,
  64. EXPORT_IMAGE_TYPES,
  65. GRID_SIZE,
  66. IMAGE_MIME_TYPES,
  67. IMAGE_RENDER_TIMEOUT,
  68. isBrave,
  69. LINE_CONFIRM_THRESHOLD,
  70. MAX_ALLOWED_FILE_BYTES,
  71. MIME_TYPES,
  72. MQ_MAX_HEIGHT_LANDSCAPE,
  73. MQ_MAX_WIDTH_LANDSCAPE,
  74. MQ_MAX_WIDTH_PORTRAIT,
  75. MQ_RIGHT_SIDEBAR_MIN_WIDTH,
  76. POINTER_BUTTON,
  77. ROUNDNESS,
  78. SCROLL_TIMEOUT,
  79. TAP_TWICE_TIMEOUT,
  80. TEXT_TO_CENTER_SNAP_THRESHOLD,
  81. THEME,
  82. THEME_FILTER,
  83. TOUCH_CTX_MENU_TIMEOUT,
  84. VERTICAL_ALIGN,
  85. YOUTUBE_STATES,
  86. ZOOM_STEP,
  87. POINTER_EVENTS,
  88. TOOL_TYPE,
  89. EDITOR_LS_KEYS,
  90. isIOS,
  91. } from "../constants";
  92. import { ExportedElements, exportCanvas, loadFromBlob } from "../data";
  93. import Library, { distributeLibraryItemsOnSquareGrid } from "../data/library";
  94. import { restore, restoreElements } from "../data/restore";
  95. import {
  96. dragNewElement,
  97. dragSelectedElements,
  98. duplicateElement,
  99. getCommonBounds,
  100. getCursorForResizingElement,
  101. getDragOffsetXY,
  102. getElementWithTransformHandleType,
  103. getNormalizedDimensions,
  104. getResizeArrowDirection,
  105. getResizeOffsetXY,
  106. getLockedLinearCursorAlignSize,
  107. getTransformHandleTypeFromCoords,
  108. hitTest,
  109. isHittingElementBoundingBoxWithoutHittingElement,
  110. isInvisiblySmallElement,
  111. isNonDeletedElement,
  112. isTextElement,
  113. newElement,
  114. newLinearElement,
  115. newTextElement,
  116. newImageElement,
  117. textWysiwyg,
  118. transformElements,
  119. updateTextElement,
  120. redrawTextBoundingBox,
  121. } from "../element";
  122. import {
  123. bindOrUnbindLinearElement,
  124. bindOrUnbindSelectedElements,
  125. fixBindingsAfterDeletion,
  126. fixBindingsAfterDuplication,
  127. getEligibleElementsForBinding,
  128. getHoveredElementForBinding,
  129. isBindingEnabled,
  130. isLinearElementSimpleAndAlreadyBound,
  131. maybeBindLinearElement,
  132. shouldEnableBindingForPointerEvent,
  133. unbindLinearElements,
  134. updateBoundElements,
  135. } from "../element/binding";
  136. import { LinearElementEditor } from "../element/linearElementEditor";
  137. import { mutateElement, newElementWith } from "../element/mutateElement";
  138. import {
  139. deepCopyElement,
  140. duplicateElements,
  141. newFrameElement,
  142. newFreeDrawElement,
  143. newEmbeddableElement,
  144. newMagicFrameElement,
  145. newIframeElement,
  146. } from "../element/newElement";
  147. import {
  148. hasBoundTextElement,
  149. isArrowElement,
  150. isBindingElement,
  151. isBindingElementType,
  152. isBoundToContainer,
  153. isFrameLikeElement,
  154. isImageElement,
  155. isEmbeddableElement,
  156. isInitializedImageElement,
  157. isLinearElement,
  158. isLinearElementType,
  159. isUsingAdaptiveRadius,
  160. isFrameElement,
  161. isIframeElement,
  162. isIframeLikeElement,
  163. isMagicFrameElement,
  164. } from "../element/typeChecks";
  165. import {
  166. ExcalidrawBindableElement,
  167. ExcalidrawElement,
  168. ExcalidrawFreeDrawElement,
  169. ExcalidrawGenericElement,
  170. ExcalidrawLinearElement,
  171. ExcalidrawTextElement,
  172. NonDeleted,
  173. InitializedExcalidrawImageElement,
  174. ExcalidrawImageElement,
  175. FileId,
  176. NonDeletedExcalidrawElement,
  177. ExcalidrawTextContainer,
  178. ExcalidrawFrameLikeElement,
  179. ExcalidrawMagicFrameElement,
  180. ExcalidrawIframeLikeElement,
  181. IframeData,
  182. ExcalidrawIframeElement,
  183. ExcalidrawEmbeddableElement,
  184. } from "../element/types";
  185. import { getCenter, getDistance } from "../gesture";
  186. import {
  187. editGroupForSelectedElement,
  188. getElementsInGroup,
  189. getSelectedGroupIdForElement,
  190. getSelectedGroupIds,
  191. isElementInGroup,
  192. isSelectedViaGroup,
  193. selectGroupsForSelectedElements,
  194. } from "../groups";
  195. import History from "../history";
  196. import { defaultLang, getLanguage, languages, setLanguage, t } from "../i18n";
  197. import {
  198. CODES,
  199. shouldResizeFromCenter,
  200. shouldMaintainAspectRatio,
  201. shouldRotateWithDiscreteAngle,
  202. isArrowKey,
  203. KEYS,
  204. } from "../keys";
  205. import { isElementInViewport } from "../element/sizeHelpers";
  206. import {
  207. distance2d,
  208. getCornerRadius,
  209. getGridPoint,
  210. isPathALoop,
  211. } from "../math";
  212. import {
  213. calculateScrollCenter,
  214. getElementsAtPosition,
  215. getElementsWithinSelection,
  216. getNormalizedZoom,
  217. getSelectedElements,
  218. hasBackground,
  219. isOverScrollBars,
  220. isSomeElementSelected,
  221. } from "../scene";
  222. import Scene from "../scene/Scene";
  223. import { RenderInteractiveSceneCallback, ScrollBars } from "../scene/types";
  224. import { getStateForZoom } from "../scene/zoom";
  225. import { findShapeByKey } from "../shapes";
  226. import {
  227. AppClassProperties,
  228. AppProps,
  229. AppState,
  230. BinaryFileData,
  231. DataURL,
  232. ExcalidrawImperativeAPI,
  233. BinaryFiles,
  234. Gesture,
  235. GestureEvent,
  236. LibraryItems,
  237. PointerDownState,
  238. SceneData,
  239. Device,
  240. FrameNameBoundsCache,
  241. SidebarName,
  242. SidebarTabName,
  243. KeyboardModifiersObject,
  244. CollaboratorPointer,
  245. ToolType,
  246. OnUserFollowedPayload,
  247. UnsubscribeCallback,
  248. ElementsPendingErasure,
  249. } from "../types";
  250. import {
  251. debounce,
  252. distance,
  253. getFontString,
  254. getNearestScrollableContainer,
  255. isInputLike,
  256. isToolIcon,
  257. isWritableElement,
  258. sceneCoordsToViewportCoords,
  259. tupleToCoors,
  260. viewportCoordsToSceneCoords,
  261. wrapEvent,
  262. updateObject,
  263. updateActiveTool,
  264. getShortcutKey,
  265. isTransparent,
  266. easeToValuesRAF,
  267. muteFSAbortError,
  268. isTestEnv,
  269. easeOut,
  270. updateStable,
  271. addEventListener,
  272. normalizeEOL,
  273. } from "../utils";
  274. import {
  275. createSrcDoc,
  276. embeddableURLValidator,
  277. maybeParseEmbedSrc,
  278. getEmbedLink,
  279. } from "../element/embeddable";
  280. import {
  281. ContextMenu,
  282. ContextMenuItems,
  283. CONTEXT_MENU_SEPARATOR,
  284. } from "./ContextMenu";
  285. import LayerUI from "./LayerUI";
  286. import { Toast } from "./Toast";
  287. import { actionToggleViewMode } from "../actions/actionToggleViewMode";
  288. import {
  289. dataURLToFile,
  290. generateIdFromFile,
  291. getDataURL,
  292. getFileFromEvent,
  293. ImageURLToFile,
  294. isImageFileHandle,
  295. isSupportedImageFile,
  296. loadSceneOrLibraryFromBlob,
  297. normalizeFile,
  298. parseLibraryJSON,
  299. resizeImageFile,
  300. SVGStringToFile,
  301. } from "../data/blob";
  302. import {
  303. getInitializedImageElements,
  304. loadHTMLImageElement,
  305. normalizeSVG,
  306. updateImageCache as _updateImageCache,
  307. } from "../element/image";
  308. import throttle from "lodash.throttle";
  309. import { fileOpen, FileSystemHandle } from "../data/filesystem";
  310. import {
  311. bindTextToShapeAfterDuplication,
  312. getApproxMinLineHeight,
  313. getApproxMinLineWidth,
  314. getBoundTextElement,
  315. getContainerCenter,
  316. getContainerElement,
  317. getDefaultLineHeight,
  318. getLineHeightInPx,
  319. getTextBindableContainerAtPosition,
  320. isMeasureTextSupported,
  321. isValidTextContainer,
  322. } from "../element/textElement";
  323. import { isHittingElementNotConsideringBoundingBox } from "../element/collision";
  324. import {
  325. showHyperlinkTooltip,
  326. hideHyperlinkToolip,
  327. Hyperlink,
  328. isPointHittingLink,
  329. isPointHittingLinkIcon,
  330. } from "../element/Hyperlink";
  331. import { isLocalLink, normalizeLink, toValidURL } from "../data/url";
  332. import { shouldShowBoundingBox } from "../element/transformHandles";
  333. import { actionUnlockAllElements } from "../actions/actionElementLock";
  334. import { Fonts } from "../scene/Fonts";
  335. import {
  336. getFrameChildren,
  337. isCursorInFrame,
  338. bindElementsToFramesAfterDuplication,
  339. addElementsToFrame,
  340. replaceAllElementsInFrame,
  341. removeElementsFromFrame,
  342. getElementsInResizingFrame,
  343. getElementsInNewFrame,
  344. getContainingFrame,
  345. elementOverlapsWithFrame,
  346. updateFrameMembershipOfSelectedElements,
  347. isElementInFrame,
  348. getFrameLikeTitle,
  349. } from "../frame";
  350. import {
  351. excludeElementsInFramesFromSelection,
  352. makeNextSelectedElementIds,
  353. } from "../scene/selection";
  354. import { actionPaste } from "../actions/actionClipboard";
  355. import {
  356. actionRemoveAllElementsFromFrame,
  357. actionSelectAllElementsInFrame,
  358. } from "../actions/actionFrame";
  359. import { actionToggleHandTool, zoomToFit } from "../actions/actionCanvas";
  360. import { jotaiStore } from "../jotai";
  361. import { activeConfirmDialogAtom } from "./ActiveConfirmDialog";
  362. import { ImageSceneDataError } from "../errors";
  363. import {
  364. getSnapLinesAtPointer,
  365. snapDraggedElements,
  366. isActiveToolNonLinearSnappable,
  367. snapNewElement,
  368. snapResizingElements,
  369. isSnappingEnabled,
  370. getVisibleGaps,
  371. getReferenceSnapPoints,
  372. SnapCache,
  373. } from "../snapping";
  374. import { actionWrapTextInContainer } from "../actions/actionBoundText";
  375. import BraveMeasureTextError from "./BraveMeasureTextError";
  376. import { activeEyeDropperAtom } from "./EyeDropper";
  377. import {
  378. ExcalidrawElementSkeleton,
  379. convertToExcalidrawElements,
  380. } from "../data/transform";
  381. import { ValueOf } from "../utility-types";
  382. import { isSidebarDockedAtom } from "./Sidebar/Sidebar";
  383. import { StaticCanvas, InteractiveCanvas } from "./canvases";
  384. import { Renderer } from "../scene/Renderer";
  385. import { ShapeCache } from "../scene/ShapeCache";
  386. import { SVGLayer } from "./SVGLayer";
  387. import {
  388. setEraserCursor,
  389. setCursor,
  390. resetCursor,
  391. setCursorForShape,
  392. } from "../cursor";
  393. import { Emitter } from "../emitter";
  394. import { ElementCanvasButtons } from "../element/ElementCanvasButtons";
  395. import { MagicCacheData, diagramToHTML } from "../data/magic";
  396. import { elementsOverlappingBBox, exportToBlob } from "../../utils/export";
  397. import { COLOR_PALETTE } from "../colors";
  398. import { ElementCanvasButton } from "./MagicButton";
  399. import { MagicIcon, copyIcon, fullscreenIcon } from "./icons";
  400. import { EditorLocalStorage } from "../data/EditorLocalStorage";
  401. import FollowMode from "./FollowMode/FollowMode";
  402. import { AnimationFrameHandler } from "../animation-frame-handler";
  403. import { AnimatedTrail } from "../animated-trail";
  404. import { LaserTrails } from "../laser-trails";
  405. import { withBatchedUpdates, withBatchedUpdatesThrottled } from "../reactUtils";
  406. import { getRenderOpacity } from "../renderer/renderElement";
  407. const AppContext = React.createContext<AppClassProperties>(null!);
  408. const AppPropsContext = React.createContext<AppProps>(null!);
  409. const deviceContextInitialValue = {
  410. viewport: {
  411. isMobile: false,
  412. isLandscape: false,
  413. },
  414. editor: {
  415. isMobile: false,
  416. canFitSidebar: false,
  417. },
  418. isTouchScreen: false,
  419. };
  420. const DeviceContext = React.createContext<Device>(deviceContextInitialValue);
  421. DeviceContext.displayName = "DeviceContext";
  422. export const ExcalidrawContainerContext = React.createContext<{
  423. container: HTMLDivElement | null;
  424. id: string | null;
  425. }>({ container: null, id: null });
  426. ExcalidrawContainerContext.displayName = "ExcalidrawContainerContext";
  427. const ExcalidrawElementsContext = React.createContext<
  428. readonly NonDeletedExcalidrawElement[]
  429. >([]);
  430. ExcalidrawElementsContext.displayName = "ExcalidrawElementsContext";
  431. const ExcalidrawAppStateContext = React.createContext<AppState>({
  432. ...getDefaultAppState(),
  433. width: 0,
  434. height: 0,
  435. offsetLeft: 0,
  436. offsetTop: 0,
  437. });
  438. ExcalidrawAppStateContext.displayName = "ExcalidrawAppStateContext";
  439. const ExcalidrawSetAppStateContext = React.createContext<
  440. React.Component<any, AppState>["setState"]
  441. >(() => {
  442. console.warn("Uninitialized ExcalidrawSetAppStateContext context!");
  443. });
  444. ExcalidrawSetAppStateContext.displayName = "ExcalidrawSetAppStateContext";
  445. const ExcalidrawActionManagerContext = React.createContext<ActionManager>(
  446. null!,
  447. );
  448. ExcalidrawActionManagerContext.displayName = "ExcalidrawActionManagerContext";
  449. export const useApp = () => useContext(AppContext);
  450. export const useAppProps = () => useContext(AppPropsContext);
  451. export const useDevice = () => useContext<Device>(DeviceContext);
  452. export const useExcalidrawContainer = () =>
  453. useContext(ExcalidrawContainerContext);
  454. export const useExcalidrawElements = () =>
  455. useContext(ExcalidrawElementsContext);
  456. export const useExcalidrawAppState = () =>
  457. useContext(ExcalidrawAppStateContext);
  458. export const useExcalidrawSetAppState = () =>
  459. useContext(ExcalidrawSetAppStateContext);
  460. export const useExcalidrawActionManager = () =>
  461. useContext(ExcalidrawActionManagerContext);
  462. const supportsResizeObserver =
  463. typeof window !== "undefined" && "ResizeObserver" in window;
  464. let didTapTwice: boolean = false;
  465. let tappedTwiceTimer = 0;
  466. let isHoldingSpace: boolean = false;
  467. let isPanning: boolean = false;
  468. let isDraggingScrollBar: boolean = false;
  469. let currentScrollBars: ScrollBars = { horizontal: null, vertical: null };
  470. let touchTimeout = 0;
  471. let invalidateContextMenu = false;
  472. /**
  473. * Map of youtube embed video states
  474. */
  475. const YOUTUBE_VIDEO_STATES = new Map<
  476. ExcalidrawElement["id"],
  477. ValueOf<typeof YOUTUBE_STATES>
  478. >();
  479. let IS_PLAIN_PASTE = false;
  480. let IS_PLAIN_PASTE_TIMER = 0;
  481. let PLAIN_PASTE_TOAST_SHOWN = false;
  482. let lastPointerUp: (() => void) | null = null;
  483. const gesture: Gesture = {
  484. pointers: new Map(),
  485. lastCenter: null,
  486. initialDistance: null,
  487. initialScale: null,
  488. };
  489. class App extends React.Component<AppProps, AppState> {
  490. canvas: AppClassProperties["canvas"];
  491. interactiveCanvas: AppClassProperties["interactiveCanvas"] = null;
  492. rc: RoughCanvas;
  493. unmounted: boolean = false;
  494. actionManager: ActionManager;
  495. device: Device = deviceContextInitialValue;
  496. private excalidrawContainerRef = React.createRef<HTMLDivElement>();
  497. public scene: Scene;
  498. public renderer: Renderer;
  499. private fonts: Fonts;
  500. private resizeObserver: ResizeObserver | undefined;
  501. private nearestScrollableContainer: HTMLElement | Document | undefined;
  502. public library: AppClassProperties["library"];
  503. public libraryItemsFromStorage: LibraryItems | undefined;
  504. public id: string;
  505. private history: History;
  506. private excalidrawContainerValue: {
  507. container: HTMLDivElement | null;
  508. id: string;
  509. };
  510. public files: BinaryFiles = {};
  511. public imageCache: AppClassProperties["imageCache"] = new Map();
  512. private iFrameRefs = new Map<ExcalidrawElement["id"], HTMLIFrameElement>();
  513. private initializedEmbeds = new Set<ExcalidrawIframeLikeElement["id"]>();
  514. private elementsPendingErasure: ElementsPendingErasure = new Set();
  515. hitLinkElement?: NonDeletedExcalidrawElement;
  516. lastPointerDownEvent: React.PointerEvent<HTMLElement> | null = null;
  517. lastPointerUpEvent: React.PointerEvent<HTMLElement> | PointerEvent | null =
  518. null;
  519. lastPointerMoveEvent: PointerEvent | null = null;
  520. lastViewportPosition = { x: 0, y: 0 };
  521. animationFrameHandler = new AnimationFrameHandler();
  522. laserTrails = new LaserTrails(this.animationFrameHandler, this);
  523. eraserTrail = new AnimatedTrail(this.animationFrameHandler, this, {
  524. streamline: 0.2,
  525. size: 5,
  526. keepHead: true,
  527. sizeMapping: (c) => {
  528. const DECAY_TIME = 200;
  529. const DECAY_LENGTH = 10;
  530. const t = Math.max(0, 1 - (performance.now() - c.pressure) / DECAY_TIME);
  531. const l =
  532. (DECAY_LENGTH -
  533. Math.min(DECAY_LENGTH, c.totalLength - c.currentIndex)) /
  534. DECAY_LENGTH;
  535. return Math.min(easeOut(l), easeOut(t));
  536. },
  537. fill: () =>
  538. this.state.theme === THEME.LIGHT
  539. ? "rgba(0, 0, 0, 0.2)"
  540. : "rgba(255, 255, 255, 0.2)",
  541. });
  542. onChangeEmitter = new Emitter<
  543. [
  544. elements: readonly ExcalidrawElement[],
  545. appState: AppState,
  546. files: BinaryFiles,
  547. ]
  548. >();
  549. onPointerDownEmitter = new Emitter<
  550. [
  551. activeTool: AppState["activeTool"],
  552. pointerDownState: PointerDownState,
  553. event: React.PointerEvent<HTMLElement>,
  554. ]
  555. >();
  556. onPointerUpEmitter = new Emitter<
  557. [
  558. activeTool: AppState["activeTool"],
  559. pointerDownState: PointerDownState,
  560. event: PointerEvent,
  561. ]
  562. >();
  563. onUserFollowEmitter = new Emitter<[payload: OnUserFollowedPayload]>();
  564. onScrollChangeEmitter = new Emitter<
  565. [scrollX: number, scrollY: number, zoom: AppState["zoom"]]
  566. >();
  567. missingPointerEventCleanupEmitter = new Emitter<
  568. [event: PointerEvent | null]
  569. >();
  570. onRemoveEventListenersEmitter = new Emitter<[]>();
  571. constructor(props: AppProps) {
  572. super(props);
  573. const defaultAppState = getDefaultAppState();
  574. const {
  575. excalidrawAPI,
  576. viewModeEnabled = false,
  577. zenModeEnabled = false,
  578. gridModeEnabled = false,
  579. objectsSnapModeEnabled = false,
  580. theme = defaultAppState.theme,
  581. name = defaultAppState.name,
  582. } = props;
  583. this.state = {
  584. ...defaultAppState,
  585. theme,
  586. isLoading: true,
  587. ...this.getCanvasOffsets(),
  588. viewModeEnabled,
  589. zenModeEnabled,
  590. objectsSnapModeEnabled,
  591. gridSize: gridModeEnabled ? GRID_SIZE : null,
  592. name,
  593. width: window.innerWidth,
  594. height: window.innerHeight,
  595. };
  596. this.id = nanoid();
  597. this.library = new Library(this);
  598. this.actionManager = new ActionManager(
  599. this.syncActionResult,
  600. () => this.state,
  601. () => this.scene.getElementsIncludingDeleted(),
  602. this,
  603. );
  604. this.scene = new Scene();
  605. this.canvas = document.createElement("canvas");
  606. this.rc = rough.canvas(this.canvas);
  607. this.renderer = new Renderer(this.scene);
  608. if (excalidrawAPI) {
  609. const api: ExcalidrawImperativeAPI = {
  610. updateScene: this.updateScene,
  611. updateLibrary: this.library.updateLibrary,
  612. addFiles: this.addFiles,
  613. resetScene: this.resetScene,
  614. getSceneElementsIncludingDeleted: this.getSceneElementsIncludingDeleted,
  615. history: {
  616. clear: this.resetHistory,
  617. },
  618. scrollToContent: this.scrollToContent,
  619. getSceneElements: this.getSceneElements,
  620. getAppState: () => this.state,
  621. getFiles: () => this.files,
  622. registerAction: (action: Action) => {
  623. this.actionManager.registerAction(action);
  624. },
  625. refresh: this.refresh,
  626. setToast: this.setToast,
  627. id: this.id,
  628. setActiveTool: this.setActiveTool,
  629. setCursor: this.setCursor,
  630. resetCursor: this.resetCursor,
  631. updateFrameRendering: this.updateFrameRendering,
  632. toggleSidebar: this.toggleSidebar,
  633. onChange: (cb) => this.onChangeEmitter.on(cb),
  634. onPointerDown: (cb) => this.onPointerDownEmitter.on(cb),
  635. onPointerUp: (cb) => this.onPointerUpEmitter.on(cb),
  636. onScrollChange: (cb) => this.onScrollChangeEmitter.on(cb),
  637. onUserFollow: (cb) => this.onUserFollowEmitter.on(cb),
  638. } as const;
  639. if (typeof excalidrawAPI === "function") {
  640. excalidrawAPI(api);
  641. } else {
  642. console.error("excalidrawAPI should be a function!");
  643. }
  644. }
  645. this.excalidrawContainerValue = {
  646. container: this.excalidrawContainerRef.current,
  647. id: this.id,
  648. };
  649. this.fonts = new Fonts({
  650. scene: this.scene,
  651. onSceneUpdated: this.onSceneUpdated,
  652. });
  653. this.history = new History();
  654. this.actionManager.registerAll(actions);
  655. this.actionManager.registerAction(createUndoAction(this.history));
  656. this.actionManager.registerAction(createRedoAction(this.history));
  657. }
  658. private onWindowMessage(event: MessageEvent) {
  659. if (
  660. event.origin !== "https://player.vimeo.com" &&
  661. event.origin !== "https://www.youtube.com"
  662. ) {
  663. return;
  664. }
  665. let data = null;
  666. try {
  667. data = JSON.parse(event.data);
  668. } catch (e) {}
  669. if (!data) {
  670. return;
  671. }
  672. switch (event.origin) {
  673. case "https://player.vimeo.com":
  674. //Allowing for multiple instances of Excalidraw running in the window
  675. if (data.method === "paused") {
  676. let source: Window | null = null;
  677. const iframes = document.body.querySelectorAll(
  678. "iframe.excalidraw__embeddable",
  679. );
  680. if (!iframes) {
  681. break;
  682. }
  683. for (const iframe of iframes as NodeListOf<HTMLIFrameElement>) {
  684. if (iframe.contentWindow === event.source) {
  685. source = iframe.contentWindow;
  686. }
  687. }
  688. source?.postMessage(
  689. JSON.stringify({
  690. method: data.value ? "play" : "pause",
  691. value: true,
  692. }),
  693. "*",
  694. );
  695. }
  696. break;
  697. case "https://www.youtube.com":
  698. if (
  699. data.event === "infoDelivery" &&
  700. data.info &&
  701. data.id &&
  702. typeof data.info.playerState === "number"
  703. ) {
  704. const id = data.id;
  705. const playerState = data.info.playerState as number;
  706. if (
  707. (Object.values(YOUTUBE_STATES) as number[]).includes(playerState)
  708. ) {
  709. YOUTUBE_VIDEO_STATES.set(
  710. id,
  711. playerState as ValueOf<typeof YOUTUBE_STATES>,
  712. );
  713. }
  714. }
  715. break;
  716. }
  717. }
  718. private cacheEmbeddableRef(
  719. element: ExcalidrawIframeLikeElement,
  720. ref: HTMLIFrameElement | null,
  721. ) {
  722. if (ref) {
  723. this.iFrameRefs.set(element.id, ref);
  724. }
  725. }
  726. private getHTMLIFrameElement(
  727. element: ExcalidrawIframeLikeElement,
  728. ): HTMLIFrameElement | undefined {
  729. return this.iFrameRefs.get(element.id);
  730. }
  731. private handleEmbeddableCenterClick(element: ExcalidrawIframeLikeElement) {
  732. if (
  733. this.state.activeEmbeddable?.element === element &&
  734. this.state.activeEmbeddable?.state === "active"
  735. ) {
  736. return;
  737. }
  738. // The delay serves two purposes
  739. // 1. To prevent first click propagating to iframe on mobile,
  740. // else the click will immediately start and stop the video
  741. // 2. If the user double clicks the frame center to activate it
  742. // without the delay youtube will immediately open the video
  743. // in fullscreen mode
  744. setTimeout(() => {
  745. this.setState({
  746. activeEmbeddable: { element, state: "active" },
  747. selectedElementIds: { [element.id]: true },
  748. draggingElement: null,
  749. selectionElement: null,
  750. });
  751. }, 100);
  752. if (isIframeElement(element)) {
  753. return;
  754. }
  755. const iframe = this.getHTMLIFrameElement(element);
  756. if (!iframe?.contentWindow) {
  757. return;
  758. }
  759. if (iframe.src.includes("youtube")) {
  760. const state = YOUTUBE_VIDEO_STATES.get(element.id);
  761. if (!state) {
  762. YOUTUBE_VIDEO_STATES.set(element.id, YOUTUBE_STATES.UNSTARTED);
  763. iframe.contentWindow.postMessage(
  764. JSON.stringify({
  765. event: "listening",
  766. id: element.id,
  767. }),
  768. "*",
  769. );
  770. }
  771. switch (state) {
  772. case YOUTUBE_STATES.PLAYING:
  773. case YOUTUBE_STATES.BUFFERING:
  774. iframe.contentWindow?.postMessage(
  775. JSON.stringify({
  776. event: "command",
  777. func: "pauseVideo",
  778. args: "",
  779. }),
  780. "*",
  781. );
  782. break;
  783. default:
  784. iframe.contentWindow?.postMessage(
  785. JSON.stringify({
  786. event: "command",
  787. func: "playVideo",
  788. args: "",
  789. }),
  790. "*",
  791. );
  792. }
  793. }
  794. if (iframe.src.includes("player.vimeo.com")) {
  795. iframe.contentWindow.postMessage(
  796. JSON.stringify({
  797. method: "paused", //video play/pause in onWindowMessage handler
  798. }),
  799. "*",
  800. );
  801. }
  802. }
  803. private isIframeLikeElementCenter(
  804. el: ExcalidrawIframeLikeElement | null,
  805. event: React.PointerEvent<HTMLElement> | PointerEvent,
  806. sceneX: number,
  807. sceneY: number,
  808. ) {
  809. return (
  810. el &&
  811. !event.altKey &&
  812. !event.shiftKey &&
  813. !event.metaKey &&
  814. !event.ctrlKey &&
  815. (this.state.activeEmbeddable?.element !== el ||
  816. this.state.activeEmbeddable?.state === "hover" ||
  817. !this.state.activeEmbeddable) &&
  818. sceneX >= el.x + el.width / 3 &&
  819. sceneX <= el.x + (2 * el.width) / 3 &&
  820. sceneY >= el.y + el.height / 3 &&
  821. sceneY <= el.y + (2 * el.height) / 3
  822. );
  823. }
  824. private updateEmbeddables = () => {
  825. const iframeLikes = new Set<ExcalidrawIframeLikeElement["id"]>();
  826. let updated = false;
  827. this.scene.getNonDeletedElements().filter((element) => {
  828. if (isEmbeddableElement(element)) {
  829. iframeLikes.add(element.id);
  830. if (element.validated == null) {
  831. updated = true;
  832. const validated = embeddableURLValidator(
  833. element.link,
  834. this.props.validateEmbeddable,
  835. );
  836. mutateElement(element, { validated }, false);
  837. ShapeCache.delete(element);
  838. }
  839. } else if (isIframeElement(element)) {
  840. iframeLikes.add(element.id);
  841. }
  842. return false;
  843. });
  844. if (updated) {
  845. this.scene.informMutation();
  846. }
  847. // GC
  848. this.iFrameRefs.forEach((ref, id) => {
  849. if (!iframeLikes.has(id)) {
  850. this.iFrameRefs.delete(id);
  851. }
  852. });
  853. };
  854. private renderEmbeddables() {
  855. const scale = this.state.zoom.value;
  856. const normalizedWidth = this.state.width;
  857. const normalizedHeight = this.state.height;
  858. const embeddableElements = this.scene
  859. .getNonDeletedElements()
  860. .filter(
  861. (el): el is NonDeleted<ExcalidrawIframeLikeElement> =>
  862. (isEmbeddableElement(el) && !!el.validated) || isIframeElement(el),
  863. );
  864. return (
  865. <>
  866. {embeddableElements.map((el) => {
  867. const { x, y } = sceneCoordsToViewportCoords(
  868. { sceneX: el.x, sceneY: el.y },
  869. this.state,
  870. );
  871. const isVisible = isElementInViewport(
  872. el,
  873. normalizedWidth,
  874. normalizedHeight,
  875. this.state,
  876. );
  877. const hasBeenInitialized = this.initializedEmbeds.has(el.id);
  878. if (isVisible && !hasBeenInitialized) {
  879. this.initializedEmbeds.add(el.id);
  880. }
  881. const shouldRender = isVisible || hasBeenInitialized;
  882. if (!shouldRender) {
  883. return null;
  884. }
  885. let src: IframeData | null;
  886. if (isIframeElement(el)) {
  887. src = null;
  888. const data: MagicCacheData = (el.customData?.generationData ??
  889. this.magicGenerations.get(el.id)) || {
  890. status: "error",
  891. message: "No generation data",
  892. code: "ERR_NO_GENERATION_DATA",
  893. };
  894. if (data.status === "done") {
  895. const html = data.html;
  896. src = {
  897. intrinsicSize: { w: el.width, h: el.height },
  898. type: "document",
  899. srcdoc: () => {
  900. return html;
  901. },
  902. } as const;
  903. } else if (data.status === "pending") {
  904. src = {
  905. intrinsicSize: { w: el.width, h: el.height },
  906. type: "document",
  907. srcdoc: () => {
  908. return createSrcDoc(`
  909. <style>
  910. html, body {
  911. width: 100%;
  912. height: 100%;
  913. color: ${
  914. this.state.theme === "dark" ? "white" : "black"
  915. };
  916. }
  917. body {
  918. display: flex;
  919. align-items: center;
  920. justify-content: center;
  921. flex-direction: column;
  922. gap: 1rem;
  923. }
  924. .Spinner {
  925. display: flex;
  926. align-items: center;
  927. justify-content: center;
  928. margin-left: auto;
  929. margin-right: auto;
  930. }
  931. .Spinner svg {
  932. animation: rotate 1.6s linear infinite;
  933. transform-origin: center center;
  934. width: 40px;
  935. height: 40px;
  936. }
  937. .Spinner circle {
  938. stroke: currentColor;
  939. animation: dash 1.6s linear 0s infinite;
  940. stroke-linecap: round;
  941. }
  942. @keyframes rotate {
  943. 100% {
  944. transform: rotate(360deg);
  945. }
  946. }
  947. @keyframes dash {
  948. 0% {
  949. stroke-dasharray: 1, 300;
  950. stroke-dashoffset: 0;
  951. }
  952. 50% {
  953. stroke-dasharray: 150, 300;
  954. stroke-dashoffset: -200;
  955. }
  956. 100% {
  957. stroke-dasharray: 1, 300;
  958. stroke-dashoffset: -280;
  959. }
  960. }
  961. </style>
  962. <div class="Spinner">
  963. <svg
  964. viewBox="0 0 100 100"
  965. >
  966. <circle
  967. cx="50"
  968. cy="50"
  969. r="46"
  970. stroke-width="8"
  971. fill="none"
  972. stroke-miter-limit="10"
  973. />
  974. </svg>
  975. </div>
  976. <div>Generating...</div>
  977. `);
  978. },
  979. } as const;
  980. } else {
  981. let message: string;
  982. if (data.code === "ERR_GENERATION_INTERRUPTED") {
  983. message = "Generation was interrupted...";
  984. } else {
  985. message = data.message || "Generation failed";
  986. }
  987. src = {
  988. intrinsicSize: { w: el.width, h: el.height },
  989. type: "document",
  990. srcdoc: () => {
  991. return createSrcDoc(`
  992. <style>
  993. html, body {
  994. height: 100%;
  995. }
  996. body {
  997. display: flex;
  998. flex-direction: column;
  999. align-items: center;
  1000. justify-content: center;
  1001. color: ${COLOR_PALETTE.red[3]};
  1002. }
  1003. h1, h3 {
  1004. margin-top: 0;
  1005. margin-bottom: 0.5rem;
  1006. }
  1007. </style>
  1008. <h1>Error!</h1>
  1009. <h3>${message}</h3>
  1010. `);
  1011. },
  1012. } as const;
  1013. }
  1014. } else {
  1015. src = getEmbedLink(toValidURL(el.link || ""));
  1016. }
  1017. const isActive =
  1018. this.state.activeEmbeddable?.element === el &&
  1019. this.state.activeEmbeddable?.state === "active";
  1020. const isHovered =
  1021. this.state.activeEmbeddable?.element === el &&
  1022. this.state.activeEmbeddable?.state === "hover";
  1023. return (
  1024. <div
  1025. key={el.id}
  1026. className={clsx("excalidraw__embeddable-container", {
  1027. "is-hovered": isHovered,
  1028. })}
  1029. style={{
  1030. transform: isVisible
  1031. ? `translate(${x - this.state.offsetLeft}px, ${
  1032. y - this.state.offsetTop
  1033. }px) scale(${scale})`
  1034. : "none",
  1035. display: isVisible ? "block" : "none",
  1036. opacity: getRenderOpacity(
  1037. el,
  1038. getContainingFrame(el),
  1039. this.elementsPendingErasure,
  1040. ),
  1041. ["--embeddable-radius" as string]: `${getCornerRadius(
  1042. Math.min(el.width, el.height),
  1043. el,
  1044. )}px`,
  1045. }}
  1046. >
  1047. <div
  1048. //this is a hack that addresses isse with embedded excalidraw.com embeddable
  1049. //https://github.com/excalidraw/excalidraw/pull/6691#issuecomment-1607383938
  1050. /*ref={(ref) => {
  1051. if (!this.excalidrawContainerRef.current) {
  1052. return;
  1053. }
  1054. const container = this.excalidrawContainerRef.current;
  1055. const sh = container.scrollHeight;
  1056. const ch = container.clientHeight;
  1057. if (sh !== ch) {
  1058. container.style.height = `${sh}px`;
  1059. setTimeout(() => {
  1060. container.style.height = `100%`;
  1061. });
  1062. }
  1063. }}*/
  1064. className="excalidraw__embeddable-container__inner"
  1065. style={{
  1066. width: isVisible ? `${el.width}px` : 0,
  1067. height: isVisible ? `${el.height}px` : 0,
  1068. transform: isVisible ? `rotate(${el.angle}rad)` : "none",
  1069. pointerEvents: isActive
  1070. ? POINTER_EVENTS.enabled
  1071. : POINTER_EVENTS.disabled,
  1072. }}
  1073. >
  1074. {isHovered && (
  1075. <div className="excalidraw__embeddable-hint">
  1076. {t("buttons.embeddableInteractionButton")}
  1077. </div>
  1078. )}
  1079. <div
  1080. className="excalidraw__embeddable__outer"
  1081. style={{
  1082. padding: `${el.strokeWidth}px`,
  1083. }}
  1084. >
  1085. {(isEmbeddableElement(el)
  1086. ? this.props.renderEmbeddable?.(el, this.state)
  1087. : null) ?? (
  1088. <iframe
  1089. ref={(ref) => this.cacheEmbeddableRef(el, ref)}
  1090. className="excalidraw__embeddable"
  1091. srcDoc={
  1092. src?.type === "document"
  1093. ? src.srcdoc(this.state.theme)
  1094. : undefined
  1095. }
  1096. src={
  1097. src?.type !== "document" ? src?.link ?? "" : undefined
  1098. }
  1099. // https://stackoverflow.com/q/18470015
  1100. scrolling="no"
  1101. referrerPolicy="no-referrer-when-downgrade"
  1102. title="Excalidraw Embedded Content"
  1103. allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture"
  1104. allowFullScreen={true}
  1105. sandbox="allow-same-origin allow-scripts allow-forms allow-popups allow-popups-to-escape-sandbox allow-presentation allow-downloads"
  1106. />
  1107. )}
  1108. </div>
  1109. </div>
  1110. </div>
  1111. );
  1112. })}
  1113. </>
  1114. );
  1115. }
  1116. private getFrameNameDOMId = (frameElement: ExcalidrawElement) => {
  1117. return `${this.id}-frame-name-${frameElement.id}`;
  1118. };
  1119. frameNameBoundsCache: FrameNameBoundsCache = {
  1120. get: (frameElement) => {
  1121. let bounds = this.frameNameBoundsCache._cache.get(frameElement.id);
  1122. if (
  1123. !bounds ||
  1124. bounds.zoom !== this.state.zoom.value ||
  1125. bounds.versionNonce !== frameElement.versionNonce
  1126. ) {
  1127. const frameNameDiv = document.getElementById(
  1128. this.getFrameNameDOMId(frameElement),
  1129. );
  1130. if (frameNameDiv) {
  1131. const box = frameNameDiv.getBoundingClientRect();
  1132. const boxSceneTopLeft = viewportCoordsToSceneCoords(
  1133. { clientX: box.x, clientY: box.y },
  1134. this.state,
  1135. );
  1136. const boxSceneBottomRight = viewportCoordsToSceneCoords(
  1137. { clientX: box.right, clientY: box.bottom },
  1138. this.state,
  1139. );
  1140. bounds = {
  1141. x: boxSceneTopLeft.x,
  1142. y: boxSceneTopLeft.y,
  1143. width: boxSceneBottomRight.x - boxSceneTopLeft.x,
  1144. height: boxSceneBottomRight.y - boxSceneTopLeft.y,
  1145. angle: 0,
  1146. zoom: this.state.zoom.value,
  1147. versionNonce: frameElement.versionNonce,
  1148. };
  1149. this.frameNameBoundsCache._cache.set(frameElement.id, bounds);
  1150. return bounds;
  1151. }
  1152. return null;
  1153. }
  1154. return bounds;
  1155. },
  1156. /**
  1157. * @private
  1158. */
  1159. _cache: new Map(),
  1160. };
  1161. private renderFrameNames = () => {
  1162. if (!this.state.frameRendering.enabled || !this.state.frameRendering.name) {
  1163. return null;
  1164. }
  1165. const isDarkTheme = this.state.theme === "dark";
  1166. let frameIndex = 0;
  1167. let magicFrameIndex = 0;
  1168. return this.scene.getNonDeletedFramesLikes().map((f) => {
  1169. if (isFrameElement(f)) {
  1170. frameIndex++;
  1171. } else {
  1172. magicFrameIndex++;
  1173. }
  1174. if (
  1175. !isElementInViewport(
  1176. f,
  1177. this.canvas.width / window.devicePixelRatio,
  1178. this.canvas.height / window.devicePixelRatio,
  1179. {
  1180. offsetLeft: this.state.offsetLeft,
  1181. offsetTop: this.state.offsetTop,
  1182. scrollX: this.state.scrollX,
  1183. scrollY: this.state.scrollY,
  1184. zoom: this.state.zoom,
  1185. },
  1186. )
  1187. ) {
  1188. // if frame not visible, don't render its name
  1189. return null;
  1190. }
  1191. const { x: x1, y: y1 } = sceneCoordsToViewportCoords(
  1192. { sceneX: f.x, sceneY: f.y },
  1193. this.state,
  1194. );
  1195. const FRAME_NAME_EDIT_PADDING = 6;
  1196. const reset = () => {
  1197. if (f.name?.trim() === "") {
  1198. mutateElement(f, { name: null });
  1199. }
  1200. this.setState({ editingFrame: null });
  1201. };
  1202. let frameNameJSX;
  1203. const frameName = getFrameLikeTitle(
  1204. f,
  1205. isFrameElement(f) ? frameIndex : magicFrameIndex,
  1206. );
  1207. if (f.id === this.state.editingFrame) {
  1208. const frameNameInEdit = frameName;
  1209. frameNameJSX = (
  1210. <input
  1211. autoFocus
  1212. value={frameNameInEdit}
  1213. onChange={(e) => {
  1214. mutateElement(f, {
  1215. name: e.target.value,
  1216. });
  1217. }}
  1218. onBlur={() => reset()}
  1219. onKeyDown={(event) => {
  1220. // for some inexplicable reason, `onBlur` triggered on ESC
  1221. // does not reset `state.editingFrame` despite being called,
  1222. // and we need to reset it here as well
  1223. if (event.key === KEYS.ESCAPE || event.key === KEYS.ENTER) {
  1224. reset();
  1225. }
  1226. }}
  1227. style={{
  1228. background: this.state.viewBackgroundColor,
  1229. filter: isDarkTheme ? THEME_FILTER : "none",
  1230. zIndex: 2,
  1231. border: "none",
  1232. display: "block",
  1233. padding: `${FRAME_NAME_EDIT_PADDING}px`,
  1234. borderRadius: 4,
  1235. boxShadow: "inset 0 0 0 1px var(--color-primary)",
  1236. fontFamily: "Assistant",
  1237. fontSize: "14px",
  1238. transform: `translate(-${FRAME_NAME_EDIT_PADDING}px, ${FRAME_NAME_EDIT_PADDING}px)`,
  1239. color: "var(--color-gray-80)",
  1240. overflow: "hidden",
  1241. maxWidth: `${
  1242. document.body.clientWidth - x1 - FRAME_NAME_EDIT_PADDING
  1243. }px`,
  1244. }}
  1245. size={frameNameInEdit.length + 1 || 1}
  1246. dir="auto"
  1247. autoComplete="off"
  1248. autoCapitalize="off"
  1249. autoCorrect="off"
  1250. />
  1251. );
  1252. } else {
  1253. frameNameJSX = frameName;
  1254. }
  1255. return (
  1256. <div
  1257. id={this.getFrameNameDOMId(f)}
  1258. key={f.id}
  1259. style={{
  1260. position: "absolute",
  1261. // Positioning from bottom so that we don't to either
  1262. // calculate text height or adjust using transform (which)
  1263. // messes up input position when editing the frame name.
  1264. // This makes the positioning deterministic and we can calculate
  1265. // the same position when rendering to canvas / svg.
  1266. bottom: `${
  1267. this.state.height +
  1268. FRAME_STYLE.nameOffsetY -
  1269. y1 +
  1270. this.state.offsetTop
  1271. }px`,
  1272. left: `${x1 - this.state.offsetLeft}px`,
  1273. zIndex: 2,
  1274. fontSize: FRAME_STYLE.nameFontSize,
  1275. color: isDarkTheme
  1276. ? FRAME_STYLE.nameColorDarkTheme
  1277. : FRAME_STYLE.nameColorLightTheme,
  1278. lineHeight: FRAME_STYLE.nameLineHeight,
  1279. width: "max-content",
  1280. maxWidth: `${f.width}px`,
  1281. overflow: f.id === this.state.editingFrame ? "visible" : "hidden",
  1282. whiteSpace: "nowrap",
  1283. textOverflow: "ellipsis",
  1284. cursor: CURSOR_TYPE.MOVE,
  1285. pointerEvents: this.state.viewModeEnabled
  1286. ? POINTER_EVENTS.disabled
  1287. : POINTER_EVENTS.enabled,
  1288. }}
  1289. onPointerDown={(event) => this.handleCanvasPointerDown(event)}
  1290. onWheel={(event) => this.handleWheel(event)}
  1291. onContextMenu={this.handleCanvasContextMenu}
  1292. onDoubleClick={() => {
  1293. this.setState({
  1294. editingFrame: f.id,
  1295. });
  1296. }}
  1297. >
  1298. {frameNameJSX}
  1299. </div>
  1300. );
  1301. });
  1302. };
  1303. public render() {
  1304. const selectedElements = this.scene.getSelectedElements(this.state);
  1305. const { renderTopRightUI, renderCustomStats } = this.props;
  1306. const versionNonce = this.scene.getVersionNonce();
  1307. const { canvasElements, visibleElements } =
  1308. this.renderer.getRenderableElements({
  1309. versionNonce,
  1310. zoom: this.state.zoom,
  1311. offsetLeft: this.state.offsetLeft,
  1312. offsetTop: this.state.offsetTop,
  1313. scrollX: this.state.scrollX,
  1314. scrollY: this.state.scrollY,
  1315. height: this.state.height,
  1316. width: this.state.width,
  1317. editingElement: this.state.editingElement,
  1318. pendingImageElementId: this.state.pendingImageElementId,
  1319. });
  1320. const shouldBlockPointerEvents =
  1321. !(
  1322. this.state.editingElement && isLinearElement(this.state.editingElement)
  1323. ) &&
  1324. (this.state.selectionElement ||
  1325. this.state.draggingElement ||
  1326. this.state.resizingElement ||
  1327. (this.state.activeTool.type === "laser" &&
  1328. // technically we can just test on this once we make it more safe
  1329. this.state.cursorButton === "down") ||
  1330. (this.state.editingElement &&
  1331. !isTextElement(this.state.editingElement)));
  1332. const firstSelectedElement = selectedElements[0];
  1333. return (
  1334. <div
  1335. className={clsx("excalidraw excalidraw-container", {
  1336. "excalidraw--view-mode": this.state.viewModeEnabled,
  1337. "excalidraw--mobile": this.device.editor.isMobile,
  1338. })}
  1339. style={{
  1340. ["--ui-pointerEvents" as any]: shouldBlockPointerEvents
  1341. ? POINTER_EVENTS.disabled
  1342. : POINTER_EVENTS.enabled,
  1343. }}
  1344. ref={this.excalidrawContainerRef}
  1345. onDrop={this.handleAppOnDrop}
  1346. tabIndex={0}
  1347. onKeyDown={
  1348. this.props.handleKeyboardGlobally ? undefined : this.onKeyDown
  1349. }
  1350. >
  1351. <AppContext.Provider value={this}>
  1352. <AppPropsContext.Provider value={this.props}>
  1353. <ExcalidrawContainerContext.Provider
  1354. value={this.excalidrawContainerValue}
  1355. >
  1356. <DeviceContext.Provider value={this.device}>
  1357. <ExcalidrawSetAppStateContext.Provider value={this.setAppState}>
  1358. <ExcalidrawAppStateContext.Provider value={this.state}>
  1359. <ExcalidrawElementsContext.Provider
  1360. value={this.scene.getNonDeletedElements()}
  1361. >
  1362. <ExcalidrawActionManagerContext.Provider
  1363. value={this.actionManager}
  1364. >
  1365. <LayerUI
  1366. canvas={this.canvas}
  1367. appState={this.state}
  1368. files={this.files}
  1369. setAppState={this.setAppState}
  1370. actionManager={this.actionManager}
  1371. elements={this.scene.getNonDeletedElements()}
  1372. onLockToggle={this.toggleLock}
  1373. onPenModeToggle={this.togglePenMode}
  1374. onHandToolToggle={this.onHandToolToggle}
  1375. langCode={getLanguage().code}
  1376. renderTopRightUI={renderTopRightUI}
  1377. renderCustomStats={renderCustomStats}
  1378. showExitZenModeBtn={
  1379. typeof this.props?.zenModeEnabled === "undefined" &&
  1380. this.state.zenModeEnabled
  1381. }
  1382. UIOptions={this.props.UIOptions}
  1383. onExportImage={this.onExportImage}
  1384. renderWelcomeScreen={
  1385. !this.state.isLoading &&
  1386. this.state.showWelcomeScreen &&
  1387. this.state.activeTool.type === "selection" &&
  1388. !this.state.zenModeEnabled &&
  1389. !this.scene.getElementsIncludingDeleted().length
  1390. }
  1391. app={this}
  1392. isCollaborating={this.props.isCollaborating}
  1393. openAIKey={this.OPENAI_KEY}
  1394. isOpenAIKeyPersisted={this.OPENAI_KEY_IS_PERSISTED}
  1395. onOpenAIAPIKeyChange={this.onOpenAIKeyChange}
  1396. onMagicSettingsConfirm={this.onMagicSettingsConfirm}
  1397. >
  1398. {this.props.children}
  1399. </LayerUI>
  1400. <div className="excalidraw-textEditorContainer" />
  1401. <div className="excalidraw-contextMenuContainer" />
  1402. <div className="excalidraw-eye-dropper-container" />
  1403. <SVGLayer
  1404. trails={[this.laserTrails, this.eraserTrail]}
  1405. />
  1406. {selectedElements.length === 1 &&
  1407. this.state.showHyperlinkPopup && (
  1408. <Hyperlink
  1409. key={firstSelectedElement.id}
  1410. element={firstSelectedElement}
  1411. setAppState={this.setAppState}
  1412. onLinkOpen={this.props.onLinkOpen}
  1413. setToast={this.setToast}
  1414. />
  1415. )}
  1416. {this.props.aiEnabled !== false &&
  1417. selectedElements.length === 1 &&
  1418. isMagicFrameElement(firstSelectedElement) && (
  1419. <ElementCanvasButtons
  1420. element={firstSelectedElement}
  1421. >
  1422. <ElementCanvasButton
  1423. title={t("labels.convertToCode")}
  1424. icon={MagicIcon}
  1425. checked={false}
  1426. onChange={() =>
  1427. this.onMagicFrameGenerate(
  1428. firstSelectedElement,
  1429. "button",
  1430. )
  1431. }
  1432. />
  1433. </ElementCanvasButtons>
  1434. )}
  1435. {selectedElements.length === 1 &&
  1436. isIframeElement(firstSelectedElement) &&
  1437. firstSelectedElement.customData?.generationData
  1438. ?.status === "done" && (
  1439. <ElementCanvasButtons
  1440. element={firstSelectedElement}
  1441. >
  1442. <ElementCanvasButton
  1443. title={t("labels.copySource")}
  1444. icon={copyIcon}
  1445. checked={false}
  1446. onChange={() =>
  1447. this.onIframeSrcCopy(firstSelectedElement)
  1448. }
  1449. />
  1450. <ElementCanvasButton
  1451. title="Enter fullscreen"
  1452. icon={fullscreenIcon}
  1453. checked={false}
  1454. onChange={() => {
  1455. const iframe =
  1456. this.getHTMLIFrameElement(
  1457. firstSelectedElement,
  1458. );
  1459. if (iframe) {
  1460. try {
  1461. iframe.requestFullscreen();
  1462. this.setState({
  1463. activeEmbeddable: {
  1464. element: firstSelectedElement,
  1465. state: "active",
  1466. },
  1467. selectedElementIds: {
  1468. [firstSelectedElement.id]: true,
  1469. },
  1470. draggingElement: null,
  1471. selectionElement: null,
  1472. });
  1473. } catch (err: any) {
  1474. console.warn(err);
  1475. this.setState({
  1476. errorMessage:
  1477. "Couldn't enter fullscreen",
  1478. });
  1479. }
  1480. }
  1481. }}
  1482. />
  1483. </ElementCanvasButtons>
  1484. )}
  1485. {this.state.toast !== null && (
  1486. <Toast
  1487. message={this.state.toast.message}
  1488. onClose={() => this.setToast(null)}
  1489. duration={this.state.toast.duration}
  1490. closable={this.state.toast.closable}
  1491. />
  1492. )}
  1493. {this.state.contextMenu && (
  1494. <ContextMenu
  1495. items={this.state.contextMenu.items}
  1496. top={this.state.contextMenu.top}
  1497. left={this.state.contextMenu.left}
  1498. actionManager={this.actionManager}
  1499. onClose={(callback) => {
  1500. this.setState({ contextMenu: null }, () => {
  1501. this.focusContainer();
  1502. callback?.();
  1503. });
  1504. }}
  1505. />
  1506. )}
  1507. <StaticCanvas
  1508. canvas={this.canvas}
  1509. rc={this.rc}
  1510. elements={canvasElements}
  1511. visibleElements={visibleElements}
  1512. versionNonce={versionNonce}
  1513. selectionNonce={
  1514. this.state.selectionElement?.versionNonce
  1515. }
  1516. scale={window.devicePixelRatio}
  1517. appState={this.state}
  1518. renderConfig={{
  1519. imageCache: this.imageCache,
  1520. isExporting: false,
  1521. renderGrid: true,
  1522. canvasBackgroundColor:
  1523. this.state.viewBackgroundColor,
  1524. elementsPendingErasure: this.elementsPendingErasure,
  1525. }}
  1526. />
  1527. <InteractiveCanvas
  1528. containerRef={this.excalidrawContainerRef}
  1529. canvas={this.interactiveCanvas}
  1530. elements={canvasElements}
  1531. visibleElements={visibleElements}
  1532. selectedElements={selectedElements}
  1533. versionNonce={versionNonce}
  1534. selectionNonce={
  1535. this.state.selectionElement?.versionNonce
  1536. }
  1537. scale={window.devicePixelRatio}
  1538. appState={this.state}
  1539. renderInteractiveSceneCallback={
  1540. this.renderInteractiveSceneCallback
  1541. }
  1542. handleCanvasRef={this.handleInteractiveCanvasRef}
  1543. onContextMenu={this.handleCanvasContextMenu}
  1544. onPointerMove={this.handleCanvasPointerMove}
  1545. onPointerUp={this.handleCanvasPointerUp}
  1546. onPointerCancel={this.removePointer}
  1547. onTouchMove={this.handleTouchMove}
  1548. onPointerDown={this.handleCanvasPointerDown}
  1549. onDoubleClick={this.handleCanvasDoubleClick}
  1550. />
  1551. {this.state.userToFollow && (
  1552. <FollowMode
  1553. width={this.state.width}
  1554. height={this.state.height}
  1555. userToFollow={this.state.userToFollow}
  1556. onDisconnect={this.maybeUnfollowRemoteUser}
  1557. />
  1558. )}
  1559. {this.renderFrameNames()}
  1560. </ExcalidrawActionManagerContext.Provider>
  1561. {this.renderEmbeddables()}
  1562. </ExcalidrawElementsContext.Provider>
  1563. </ExcalidrawAppStateContext.Provider>
  1564. </ExcalidrawSetAppStateContext.Provider>
  1565. </DeviceContext.Provider>
  1566. </ExcalidrawContainerContext.Provider>
  1567. </AppPropsContext.Provider>
  1568. </AppContext.Provider>
  1569. </div>
  1570. );
  1571. }
  1572. public focusContainer: AppClassProperties["focusContainer"] = () => {
  1573. this.excalidrawContainerRef.current?.focus();
  1574. };
  1575. public getSceneElementsIncludingDeleted = () => {
  1576. return this.scene.getElementsIncludingDeleted();
  1577. };
  1578. public getSceneElements = () => {
  1579. return this.scene.getNonDeletedElements();
  1580. };
  1581. public onInsertElements = (elements: readonly ExcalidrawElement[]) => {
  1582. this.addElementsFromPasteOrLibrary({
  1583. elements,
  1584. position: "center",
  1585. files: null,
  1586. });
  1587. };
  1588. public onExportImage = async (
  1589. type: keyof typeof EXPORT_IMAGE_TYPES,
  1590. elements: ExportedElements,
  1591. opts: { exportingFrame: ExcalidrawFrameLikeElement | null },
  1592. ) => {
  1593. trackEvent("export", type, "ui");
  1594. const fileHandle = await exportCanvas(
  1595. type,
  1596. elements,
  1597. this.state,
  1598. this.files,
  1599. {
  1600. exportBackground: this.state.exportBackground,
  1601. name: this.state.name,
  1602. viewBackgroundColor: this.state.viewBackgroundColor,
  1603. exportingFrame: opts.exportingFrame,
  1604. },
  1605. )
  1606. .catch(muteFSAbortError)
  1607. .catch((error) => {
  1608. console.error(error);
  1609. this.setState({ errorMessage: error.message });
  1610. });
  1611. if (
  1612. this.state.exportEmbedScene &&
  1613. fileHandle &&
  1614. isImageFileHandle(fileHandle)
  1615. ) {
  1616. this.setState({ fileHandle });
  1617. }
  1618. };
  1619. private magicGenerations = new Map<
  1620. ExcalidrawIframeElement["id"],
  1621. MagicCacheData
  1622. >();
  1623. private updateMagicGeneration = ({
  1624. frameElement,
  1625. data,
  1626. }: {
  1627. frameElement: ExcalidrawIframeElement;
  1628. data: MagicCacheData;
  1629. }) => {
  1630. if (data.status === "pending") {
  1631. // We don't wanna persist pending state to storage. It should be in-app
  1632. // state only.
  1633. // Thus reset so that we prefer local cache (if there was some
  1634. // generationData set previously)
  1635. mutateElement(
  1636. frameElement,
  1637. { customData: { generationData: undefined } },
  1638. false,
  1639. );
  1640. } else {
  1641. mutateElement(
  1642. frameElement,
  1643. { customData: { generationData: data } },
  1644. false,
  1645. );
  1646. }
  1647. this.magicGenerations.set(frameElement.id, data);
  1648. this.onSceneUpdated();
  1649. };
  1650. private getTextFromElements(elements: readonly ExcalidrawElement[]) {
  1651. const text = elements
  1652. .reduce((acc: string[], element) => {
  1653. if (isTextElement(element)) {
  1654. acc.push(element.text);
  1655. }
  1656. return acc;
  1657. }, [])
  1658. .join("\n\n");
  1659. return text;
  1660. }
  1661. private async onMagicFrameGenerate(
  1662. magicFrame: ExcalidrawMagicFrameElement,
  1663. source: "button" | "upstream",
  1664. ) {
  1665. if (!this.OPENAI_KEY) {
  1666. this.setState({
  1667. openDialog: {
  1668. name: "settings",
  1669. tab: "diagram-to-code",
  1670. source: "generation",
  1671. },
  1672. });
  1673. trackEvent("ai", "generate (missing key)", "d2c");
  1674. return;
  1675. }
  1676. const magicFrameChildren = elementsOverlappingBBox({
  1677. elements: this.scene.getNonDeletedElements(),
  1678. bounds: magicFrame,
  1679. type: "overlap",
  1680. }).filter((el) => !isMagicFrameElement(el));
  1681. if (!magicFrameChildren.length) {
  1682. if (source === "button") {
  1683. this.setState({ errorMessage: "Cannot generate from an empty frame" });
  1684. trackEvent("ai", "generate (no-children)", "d2c");
  1685. } else {
  1686. this.setActiveTool({ type: "magicframe" });
  1687. }
  1688. return;
  1689. }
  1690. const frameElement = this.insertIframeElement({
  1691. sceneX: magicFrame.x + magicFrame.width + 30,
  1692. sceneY: magicFrame.y,
  1693. width: magicFrame.width,
  1694. height: magicFrame.height,
  1695. });
  1696. if (!frameElement) {
  1697. return;
  1698. }
  1699. this.updateMagicGeneration({
  1700. frameElement,
  1701. data: { status: "pending" },
  1702. });
  1703. this.setState({
  1704. selectedElementIds: { [frameElement.id]: true },
  1705. });
  1706. const blob = await exportToBlob({
  1707. elements: this.scene.getNonDeletedElements(),
  1708. appState: {
  1709. ...this.state,
  1710. exportBackground: true,
  1711. viewBackgroundColor: this.state.viewBackgroundColor,
  1712. },
  1713. exportingFrame: magicFrame,
  1714. files: this.files,
  1715. });
  1716. const dataURL = await getDataURL(blob);
  1717. const textFromFrameChildren = this.getTextFromElements(magicFrameChildren);
  1718. trackEvent("ai", "generate (start)", "d2c");
  1719. const result = await diagramToHTML({
  1720. image: dataURL,
  1721. apiKey: this.OPENAI_KEY,
  1722. text: textFromFrameChildren,
  1723. theme: this.state.theme,
  1724. });
  1725. if (!result.ok) {
  1726. trackEvent("ai", "generate (failed)", "d2c");
  1727. console.error(result.error);
  1728. this.updateMagicGeneration({
  1729. frameElement,
  1730. data: {
  1731. status: "error",
  1732. code: "ERR_OAI",
  1733. message: result.error?.message || "Unknown error during generation",
  1734. },
  1735. });
  1736. return;
  1737. }
  1738. trackEvent("ai", "generate (success)", "d2c");
  1739. if (result.choices[0].message.content == null) {
  1740. this.updateMagicGeneration({
  1741. frameElement,
  1742. data: {
  1743. status: "error",
  1744. code: "ERR_OAI",
  1745. message: "Nothing genereated :(",
  1746. },
  1747. });
  1748. return;
  1749. }
  1750. const message = result.choices[0].message.content;
  1751. const html = message.slice(
  1752. message.indexOf("<!DOCTYPE html>"),
  1753. message.indexOf("</html>") + "</html>".length,
  1754. );
  1755. this.updateMagicGeneration({
  1756. frameElement,
  1757. data: { status: "done", html },
  1758. });
  1759. }
  1760. private onIframeSrcCopy(element: ExcalidrawIframeElement) {
  1761. if (element.customData?.generationData?.status === "done") {
  1762. copyTextToSystemClipboard(element.customData.generationData.html);
  1763. this.setToast({
  1764. message: "copied to clipboard",
  1765. closable: false,
  1766. duration: 1500,
  1767. });
  1768. }
  1769. }
  1770. private OPENAI_KEY: string | null = EditorLocalStorage.get(
  1771. EDITOR_LS_KEYS.OAI_API_KEY,
  1772. );
  1773. private OPENAI_KEY_IS_PERSISTED: boolean =
  1774. EditorLocalStorage.has(EDITOR_LS_KEYS.OAI_API_KEY) || false;
  1775. private onOpenAIKeyChange = (
  1776. openAIKey: string | null,
  1777. shouldPersist: boolean,
  1778. ) => {
  1779. this.OPENAI_KEY = openAIKey || null;
  1780. if (shouldPersist) {
  1781. const didPersist = EditorLocalStorage.set(
  1782. EDITOR_LS_KEYS.OAI_API_KEY,
  1783. openAIKey,
  1784. );
  1785. this.OPENAI_KEY_IS_PERSISTED = didPersist;
  1786. } else {
  1787. this.OPENAI_KEY_IS_PERSISTED = false;
  1788. }
  1789. };
  1790. private onMagicSettingsConfirm = (
  1791. apiKey: string,
  1792. shouldPersist: boolean,
  1793. source: "tool" | "generation" | "settings",
  1794. ) => {
  1795. this.OPENAI_KEY = apiKey || null;
  1796. this.onOpenAIKeyChange(this.OPENAI_KEY, shouldPersist);
  1797. if (source === "settings") {
  1798. return;
  1799. }
  1800. const selectedElements = this.scene.getSelectedElements({
  1801. selectedElementIds: this.state.selectedElementIds,
  1802. });
  1803. if (apiKey) {
  1804. if (selectedElements.length) {
  1805. this.onMagicframeToolSelect();
  1806. } else {
  1807. this.setActiveTool({ type: "magicframe" });
  1808. }
  1809. } else if (!isMagicFrameElement(selectedElements[0])) {
  1810. // even if user didn't end up setting api key, let's pick the tool
  1811. // so they can draw up a frame and move forward
  1812. this.setActiveTool({ type: "magicframe" });
  1813. }
  1814. };
  1815. public onMagicframeToolSelect = () => {
  1816. if (!this.OPENAI_KEY) {
  1817. this.setState({
  1818. openDialog: {
  1819. name: "settings",
  1820. tab: "diagram-to-code",
  1821. source: "tool",
  1822. },
  1823. });
  1824. trackEvent("ai", "tool-select (missing key)", "d2c");
  1825. return;
  1826. }
  1827. const selectedElements = this.scene.getSelectedElements({
  1828. selectedElementIds: this.state.selectedElementIds,
  1829. });
  1830. if (selectedElements.length === 0) {
  1831. this.setActiveTool({ type: TOOL_TYPE.magicframe });
  1832. trackEvent("ai", "tool-select (empty-selection)", "d2c");
  1833. } else {
  1834. const selectedMagicFrame: ExcalidrawMagicFrameElement | false =
  1835. selectedElements.length === 1 &&
  1836. isMagicFrameElement(selectedElements[0]) &&
  1837. selectedElements[0];
  1838. // case: user selected elements containing frame-like(s) or are frame
  1839. // members, we don't want to wrap into another magicframe
  1840. // (unless the only selected element is a magic frame which we reuse)
  1841. if (
  1842. !selectedMagicFrame &&
  1843. selectedElements.some((el) => isFrameLikeElement(el) || el.frameId)
  1844. ) {
  1845. this.setActiveTool({ type: TOOL_TYPE.magicframe });
  1846. return;
  1847. }
  1848. trackEvent("ai", "tool-select (existing selection)", "d2c");
  1849. let frame: ExcalidrawMagicFrameElement;
  1850. if (selectedMagicFrame) {
  1851. // a single magicframe already selected -> use it
  1852. frame = selectedMagicFrame;
  1853. } else {
  1854. // selected elements aren't wrapped in magic frame yet -> wrap now
  1855. const [minX, minY, maxX, maxY] = getCommonBounds(selectedElements);
  1856. const padding = 50;
  1857. frame = newMagicFrameElement({
  1858. ...FRAME_STYLE,
  1859. x: minX - padding,
  1860. y: minY - padding,
  1861. width: maxX - minX + padding * 2,
  1862. height: maxY - minY + padding * 2,
  1863. opacity: 100,
  1864. locked: false,
  1865. });
  1866. this.scene.addNewElement(frame);
  1867. for (const child of selectedElements) {
  1868. mutateElement(child, { frameId: frame.id });
  1869. }
  1870. this.setState({
  1871. selectedElementIds: { [frame.id]: true },
  1872. });
  1873. }
  1874. this.onMagicFrameGenerate(frame, "upstream");
  1875. }
  1876. };
  1877. private openEyeDropper = ({ type }: { type: "stroke" | "background" }) => {
  1878. jotaiStore.set(activeEyeDropperAtom, {
  1879. swapPreviewOnAlt: true,
  1880. colorPickerType:
  1881. type === "stroke" ? "elementStroke" : "elementBackground",
  1882. onSelect: (color, event) => {
  1883. const shouldUpdateStrokeColor =
  1884. (type === "background" && event.altKey) ||
  1885. (type === "stroke" && !event.altKey);
  1886. const selectedElements = this.scene.getSelectedElements(this.state);
  1887. if (
  1888. !selectedElements.length ||
  1889. this.state.activeTool.type !== "selection"
  1890. ) {
  1891. if (shouldUpdateStrokeColor) {
  1892. this.syncActionResult({
  1893. appState: { ...this.state, currentItemStrokeColor: color },
  1894. commitToHistory: true,
  1895. });
  1896. } else {
  1897. this.syncActionResult({
  1898. appState: { ...this.state, currentItemBackgroundColor: color },
  1899. commitToHistory: true,
  1900. });
  1901. }
  1902. } else {
  1903. this.updateScene({
  1904. elements: this.scene.getElementsIncludingDeleted().map((el) => {
  1905. if (this.state.selectedElementIds[el.id]) {
  1906. return newElementWith(el, {
  1907. [shouldUpdateStrokeColor ? "strokeColor" : "backgroundColor"]:
  1908. color,
  1909. });
  1910. }
  1911. return el;
  1912. }),
  1913. });
  1914. }
  1915. },
  1916. keepOpenOnAlt: false,
  1917. });
  1918. };
  1919. private syncActionResult = withBatchedUpdates(
  1920. (actionResult: ActionResult) => {
  1921. if (this.unmounted || actionResult === false) {
  1922. return;
  1923. }
  1924. let editingElement: AppState["editingElement"] | null = null;
  1925. if (actionResult.elements) {
  1926. actionResult.elements.forEach((element) => {
  1927. if (
  1928. this.state.editingElement?.id === element.id &&
  1929. this.state.editingElement !== element &&
  1930. isNonDeletedElement(element)
  1931. ) {
  1932. editingElement = element;
  1933. }
  1934. });
  1935. this.scene.replaceAllElements(actionResult.elements);
  1936. if (actionResult.commitToHistory) {
  1937. this.history.resumeRecording();
  1938. }
  1939. }
  1940. if (actionResult.files) {
  1941. this.files = actionResult.replaceFiles
  1942. ? actionResult.files
  1943. : { ...this.files, ...actionResult.files };
  1944. this.addNewImagesToImageCache();
  1945. }
  1946. if (actionResult.appState || editingElement || this.state.contextMenu) {
  1947. if (actionResult.commitToHistory) {
  1948. this.history.resumeRecording();
  1949. }
  1950. let viewModeEnabled = actionResult?.appState?.viewModeEnabled || false;
  1951. let zenModeEnabled = actionResult?.appState?.zenModeEnabled || false;
  1952. let gridSize = actionResult?.appState?.gridSize || null;
  1953. const theme =
  1954. actionResult?.appState?.theme || this.props.theme || THEME.LIGHT;
  1955. let name = actionResult?.appState?.name ?? this.state.name;
  1956. const errorMessage =
  1957. actionResult?.appState?.errorMessage ?? this.state.errorMessage;
  1958. if (typeof this.props.viewModeEnabled !== "undefined") {
  1959. viewModeEnabled = this.props.viewModeEnabled;
  1960. }
  1961. if (typeof this.props.zenModeEnabled !== "undefined") {
  1962. zenModeEnabled = this.props.zenModeEnabled;
  1963. }
  1964. if (typeof this.props.gridModeEnabled !== "undefined") {
  1965. gridSize = this.props.gridModeEnabled ? GRID_SIZE : null;
  1966. }
  1967. if (typeof this.props.name !== "undefined") {
  1968. name = this.props.name;
  1969. }
  1970. editingElement =
  1971. editingElement || actionResult.appState?.editingElement || null;
  1972. if (editingElement?.isDeleted) {
  1973. editingElement = null;
  1974. }
  1975. this.setState(
  1976. (state) => {
  1977. // using Object.assign instead of spread to fool TS 4.2.2+ into
  1978. // regarding the resulting type as not containing undefined
  1979. // (which the following expression will never contain)
  1980. return Object.assign(actionResult.appState || {}, {
  1981. // NOTE this will prevent opening context menu using an action
  1982. // or programmatically from the host, so it will need to be
  1983. // rewritten later
  1984. contextMenu: null,
  1985. editingElement,
  1986. viewModeEnabled,
  1987. zenModeEnabled,
  1988. gridSize,
  1989. theme,
  1990. name,
  1991. errorMessage,
  1992. });
  1993. },
  1994. () => {
  1995. if (actionResult.syncHistory) {
  1996. this.history.setCurrentState(
  1997. this.state,
  1998. this.scene.getElementsIncludingDeleted(),
  1999. );
  2000. }
  2001. },
  2002. );
  2003. }
  2004. },
  2005. );
  2006. // Lifecycle
  2007. private onBlur = withBatchedUpdates(() => {
  2008. isHoldingSpace = false;
  2009. this.setState({ isBindingEnabled: true });
  2010. });
  2011. private onUnload = () => {
  2012. this.onBlur();
  2013. };
  2014. private disableEvent: EventListener = (event) => {
  2015. event.preventDefault();
  2016. };
  2017. private resetHistory = () => {
  2018. this.history.clear();
  2019. };
  2020. /**
  2021. * Resets scene & history.
  2022. * ! Do not use to clear scene user action !
  2023. */
  2024. private resetScene = withBatchedUpdates(
  2025. (opts?: { resetLoadingState: boolean }) => {
  2026. this.scene.replaceAllElements([]);
  2027. this.setState((state) => ({
  2028. ...getDefaultAppState(),
  2029. isLoading: opts?.resetLoadingState ? false : state.isLoading,
  2030. theme: this.state.theme,
  2031. }));
  2032. this.resetHistory();
  2033. },
  2034. );
  2035. private initializeScene = async () => {
  2036. if ("launchQueue" in window && "LaunchParams" in window) {
  2037. (window as any).launchQueue.setConsumer(
  2038. async (launchParams: { files: any[] }) => {
  2039. if (!launchParams.files.length) {
  2040. return;
  2041. }
  2042. const fileHandle = launchParams.files[0];
  2043. const blob: Blob = await fileHandle.getFile();
  2044. this.loadFileToCanvas(
  2045. new File([blob], blob.name || "", { type: blob.type }),
  2046. fileHandle,
  2047. );
  2048. },
  2049. );
  2050. }
  2051. if (this.props.theme) {
  2052. this.setState({ theme: this.props.theme });
  2053. }
  2054. if (!this.state.isLoading) {
  2055. this.setState({ isLoading: true });
  2056. }
  2057. let initialData = null;
  2058. try {
  2059. initialData = (await this.props.initialData) || null;
  2060. if (initialData?.libraryItems) {
  2061. this.library
  2062. .updateLibrary({
  2063. libraryItems: initialData.libraryItems,
  2064. merge: true,
  2065. })
  2066. .catch((error) => {
  2067. console.error(error);
  2068. });
  2069. }
  2070. } catch (error: any) {
  2071. console.error(error);
  2072. initialData = {
  2073. appState: {
  2074. errorMessage:
  2075. error.message ||
  2076. "Encountered an error during importing or restoring scene data",
  2077. },
  2078. };
  2079. }
  2080. const scene = restore(initialData, null, null, { repairBindings: true });
  2081. scene.appState = {
  2082. ...scene.appState,
  2083. theme: this.props.theme || scene.appState.theme,
  2084. // we're falling back to current (pre-init) state when deciding
  2085. // whether to open the library, to handle a case where we
  2086. // update the state outside of initialData (e.g. when loading the app
  2087. // with a library install link, which should auto-open the library)
  2088. openSidebar: scene.appState?.openSidebar || this.state.openSidebar,
  2089. activeTool:
  2090. scene.appState.activeTool.type === "image"
  2091. ? { ...scene.appState.activeTool, type: "selection" }
  2092. : scene.appState.activeTool,
  2093. isLoading: false,
  2094. toast: this.state.toast,
  2095. };
  2096. if (initialData?.scrollToContent) {
  2097. scene.appState = {
  2098. ...scene.appState,
  2099. ...calculateScrollCenter(scene.elements, {
  2100. ...scene.appState,
  2101. width: this.state.width,
  2102. height: this.state.height,
  2103. offsetTop: this.state.offsetTop,
  2104. offsetLeft: this.state.offsetLeft,
  2105. }),
  2106. };
  2107. }
  2108. // FontFaceSet loadingdone event we listen on may not always fire
  2109. // (looking at you Safari), so on init we manually load fonts for current
  2110. // text elements on canvas, and rerender them once done. This also
  2111. // seems faster even in browsers that do fire the loadingdone event.
  2112. this.fonts.loadFontsForElements(scene.elements);
  2113. this.resetHistory();
  2114. this.syncActionResult({
  2115. ...scene,
  2116. commitToHistory: true,
  2117. });
  2118. };
  2119. private isMobileBreakpoint = (width: number, height: number) => {
  2120. return (
  2121. width < MQ_MAX_WIDTH_PORTRAIT ||
  2122. (height < MQ_MAX_HEIGHT_LANDSCAPE && width < MQ_MAX_WIDTH_LANDSCAPE)
  2123. );
  2124. };
  2125. private refreshViewportBreakpoints = () => {
  2126. const container = this.excalidrawContainerRef.current;
  2127. if (!container) {
  2128. return;
  2129. }
  2130. const { clientWidth: viewportWidth, clientHeight: viewportHeight } =
  2131. document.body;
  2132. const prevViewportState = this.device.viewport;
  2133. const nextViewportState = updateObject(prevViewportState, {
  2134. isLandscape: viewportWidth > viewportHeight,
  2135. isMobile: this.isMobileBreakpoint(viewportWidth, viewportHeight),
  2136. });
  2137. if (prevViewportState !== nextViewportState) {
  2138. this.device = { ...this.device, viewport: nextViewportState };
  2139. return true;
  2140. }
  2141. return false;
  2142. };
  2143. private refreshEditorBreakpoints = () => {
  2144. const container = this.excalidrawContainerRef.current;
  2145. if (!container) {
  2146. return;
  2147. }
  2148. const { width: editorWidth, height: editorHeight } =
  2149. container.getBoundingClientRect();
  2150. const sidebarBreakpoint =
  2151. this.props.UIOptions.dockedSidebarBreakpoint != null
  2152. ? this.props.UIOptions.dockedSidebarBreakpoint
  2153. : MQ_RIGHT_SIDEBAR_MIN_WIDTH;
  2154. const prevEditorState = this.device.editor;
  2155. const nextEditorState = updateObject(prevEditorState, {
  2156. isMobile: this.isMobileBreakpoint(editorWidth, editorHeight),
  2157. canFitSidebar: editorWidth > sidebarBreakpoint,
  2158. });
  2159. if (prevEditorState !== nextEditorState) {
  2160. this.device = { ...this.device, editor: nextEditorState };
  2161. return true;
  2162. }
  2163. return false;
  2164. };
  2165. public async componentDidMount() {
  2166. this.unmounted = false;
  2167. this.excalidrawContainerValue.container =
  2168. this.excalidrawContainerRef.current;
  2169. if (import.meta.env.MODE === ENV.TEST || import.meta.env.DEV) {
  2170. const setState = this.setState.bind(this);
  2171. Object.defineProperties(window.h, {
  2172. state: {
  2173. configurable: true,
  2174. get: () => {
  2175. return this.state;
  2176. },
  2177. },
  2178. setState: {
  2179. configurable: true,
  2180. value: (...args: Parameters<typeof setState>) => {
  2181. return this.setState(...args);
  2182. },
  2183. },
  2184. app: {
  2185. configurable: true,
  2186. value: this,
  2187. },
  2188. history: {
  2189. configurable: true,
  2190. value: this.history,
  2191. },
  2192. });
  2193. }
  2194. this.scene.addCallback(this.onSceneUpdated);
  2195. this.addEventListeners();
  2196. if (this.props.autoFocus && this.excalidrawContainerRef.current) {
  2197. this.focusContainer();
  2198. }
  2199. if (
  2200. // bounding rects don't work in tests so updating
  2201. // the state on init would result in making the test enviro run
  2202. // in mobile breakpoint (0 width/height), making everything fail
  2203. !isTestEnv()
  2204. ) {
  2205. this.refreshViewportBreakpoints();
  2206. this.refreshEditorBreakpoints();
  2207. }
  2208. if (supportsResizeObserver && this.excalidrawContainerRef.current) {
  2209. this.resizeObserver = new ResizeObserver(() => {
  2210. this.refreshEditorBreakpoints();
  2211. this.updateDOMRect();
  2212. });
  2213. this.resizeObserver?.observe(this.excalidrawContainerRef.current);
  2214. }
  2215. const searchParams = new URLSearchParams(window.location.search.slice(1));
  2216. if (searchParams.has("web-share-target")) {
  2217. // Obtain a file that was shared via the Web Share Target API.
  2218. this.restoreFileFromShare();
  2219. } else {
  2220. this.updateDOMRect(this.initializeScene);
  2221. }
  2222. // note that this check seems to always pass in localhost
  2223. if (isBrave() && !isMeasureTextSupported()) {
  2224. this.setState({
  2225. errorMessage: <BraveMeasureTextError />,
  2226. });
  2227. }
  2228. }
  2229. public componentWillUnmount() {
  2230. this.renderer.destroy();
  2231. this.scene = new Scene();
  2232. this.renderer = new Renderer(this.scene);
  2233. this.files = {};
  2234. this.imageCache.clear();
  2235. this.resizeObserver?.disconnect();
  2236. this.unmounted = true;
  2237. this.removeEventListeners();
  2238. this.scene.destroy();
  2239. this.library.destroy();
  2240. this.laserTrails.stop();
  2241. this.eraserTrail.stop();
  2242. this.onChangeEmitter.clear();
  2243. ShapeCache.destroy();
  2244. SnapCache.destroy();
  2245. clearTimeout(touchTimeout);
  2246. isSomeElementSelected.clearCache();
  2247. selectGroupsForSelectedElements.clearCache();
  2248. touchTimeout = 0;
  2249. }
  2250. private onResize = withBatchedUpdates(() => {
  2251. this.scene
  2252. .getElementsIncludingDeleted()
  2253. .forEach((element) => ShapeCache.delete(element));
  2254. this.refreshViewportBreakpoints();
  2255. this.updateDOMRect();
  2256. if (!supportsResizeObserver) {
  2257. this.refreshEditorBreakpoints();
  2258. }
  2259. this.setState({});
  2260. });
  2261. /** generally invoked only if fullscreen was invoked programmatically */
  2262. private onFullscreenChange = () => {
  2263. if (
  2264. // points to the iframe element we fullscreened
  2265. !document.fullscreenElement &&
  2266. this.state.activeEmbeddable?.state === "active"
  2267. ) {
  2268. this.setState({
  2269. activeEmbeddable: null,
  2270. });
  2271. }
  2272. };
  2273. private removeEventListeners() {
  2274. this.onRemoveEventListenersEmitter.trigger();
  2275. }
  2276. private addEventListeners() {
  2277. // remove first as we can add event listeners multiple times
  2278. this.removeEventListeners();
  2279. // -------------------------------------------------------------------------
  2280. // view+edit mode listeners
  2281. // -------------------------------------------------------------------------
  2282. if (this.props.handleKeyboardGlobally) {
  2283. this.onRemoveEventListenersEmitter.once(
  2284. addEventListener(document, EVENT.KEYDOWN, this.onKeyDown, false),
  2285. );
  2286. }
  2287. this.onRemoveEventListenersEmitter.once(
  2288. addEventListener(
  2289. this.excalidrawContainerRef.current,
  2290. EVENT.WHEEL,
  2291. this.onWheel,
  2292. { passive: false },
  2293. ),
  2294. addEventListener(window, EVENT.MESSAGE, this.onWindowMessage, false),
  2295. addEventListener(document, EVENT.POINTER_UP, this.removePointer), // #3553
  2296. addEventListener(document, EVENT.COPY, this.onCopy),
  2297. addEventListener(document, EVENT.KEYUP, this.onKeyUp, { passive: true }),
  2298. addEventListener(
  2299. document,
  2300. EVENT.MOUSE_MOVE,
  2301. this.updateCurrentCursorPosition,
  2302. ),
  2303. // rerender text elements on font load to fix #637 && #1553
  2304. addEventListener(document.fonts, "loadingdone", (event) => {
  2305. const loadedFontFaces = (event as FontFaceSetLoadEvent).fontfaces;
  2306. this.fonts.onFontsLoaded(loadedFontFaces);
  2307. }),
  2308. // Safari-only desktop pinch zoom
  2309. addEventListener(
  2310. document,
  2311. EVENT.GESTURE_START,
  2312. this.onGestureStart as any,
  2313. false,
  2314. ),
  2315. addEventListener(
  2316. document,
  2317. EVENT.GESTURE_CHANGE,
  2318. this.onGestureChange as any,
  2319. false,
  2320. ),
  2321. addEventListener(
  2322. document,
  2323. EVENT.GESTURE_END,
  2324. this.onGestureEnd as any,
  2325. false,
  2326. ),
  2327. addEventListener(window, EVENT.FOCUS, () => {
  2328. this.maybeCleanupAfterMissingPointerUp(null);
  2329. }),
  2330. );
  2331. if (this.state.viewModeEnabled) {
  2332. return;
  2333. }
  2334. // -------------------------------------------------------------------------
  2335. // edit-mode listeners only
  2336. // -------------------------------------------------------------------------
  2337. this.onRemoveEventListenersEmitter.once(
  2338. addEventListener(
  2339. document,
  2340. EVENT.FULLSCREENCHANGE,
  2341. this.onFullscreenChange,
  2342. ),
  2343. addEventListener(document, EVENT.PASTE, this.pasteFromClipboard),
  2344. addEventListener(document, EVENT.CUT, this.onCut),
  2345. addEventListener(window, EVENT.RESIZE, this.onResize, false),
  2346. addEventListener(window, EVENT.UNLOAD, this.onUnload, false),
  2347. addEventListener(window, EVENT.BLUR, this.onBlur, false),
  2348. addEventListener(
  2349. this.excalidrawContainerRef.current,
  2350. EVENT.DRAG_OVER,
  2351. this.disableEvent,
  2352. false,
  2353. ),
  2354. addEventListener(
  2355. this.excalidrawContainerRef.current,
  2356. EVENT.DROP,
  2357. this.disableEvent,
  2358. false,
  2359. ),
  2360. );
  2361. if (this.props.detectScroll) {
  2362. this.onRemoveEventListenersEmitter.once(
  2363. addEventListener(
  2364. getNearestScrollableContainer(this.excalidrawContainerRef.current!),
  2365. EVENT.SCROLL,
  2366. this.onScroll,
  2367. ),
  2368. );
  2369. }
  2370. }
  2371. componentDidUpdate(prevProps: AppProps, prevState: AppState) {
  2372. this.updateEmbeddables();
  2373. if (
  2374. !this.state.showWelcomeScreen &&
  2375. !this.scene.getElementsIncludingDeleted().length
  2376. ) {
  2377. this.setState({ showWelcomeScreen: true });
  2378. }
  2379. if (
  2380. prevProps.UIOptions.dockedSidebarBreakpoint !==
  2381. this.props.UIOptions.dockedSidebarBreakpoint
  2382. ) {
  2383. this.refreshEditorBreakpoints();
  2384. }
  2385. const hasFollowedPersonLeft =
  2386. prevState.userToFollow &&
  2387. !this.state.collaborators.has(prevState.userToFollow.socketId);
  2388. if (hasFollowedPersonLeft) {
  2389. this.maybeUnfollowRemoteUser();
  2390. }
  2391. if (
  2392. prevState.zoom.value !== this.state.zoom.value ||
  2393. prevState.scrollX !== this.state.scrollX ||
  2394. prevState.scrollY !== this.state.scrollY
  2395. ) {
  2396. this.props?.onScrollChange?.(
  2397. this.state.scrollX,
  2398. this.state.scrollY,
  2399. this.state.zoom,
  2400. );
  2401. this.onScrollChangeEmitter.trigger(
  2402. this.state.scrollX,
  2403. this.state.scrollY,
  2404. this.state.zoom,
  2405. );
  2406. }
  2407. if (prevState.userToFollow !== this.state.userToFollow) {
  2408. if (prevState.userToFollow) {
  2409. this.onUserFollowEmitter.trigger({
  2410. userToFollow: prevState.userToFollow,
  2411. action: "UNFOLLOW",
  2412. });
  2413. }
  2414. if (this.state.userToFollow) {
  2415. this.onUserFollowEmitter.trigger({
  2416. userToFollow: this.state.userToFollow,
  2417. action: "FOLLOW",
  2418. });
  2419. }
  2420. }
  2421. if (
  2422. Object.keys(this.state.selectedElementIds).length &&
  2423. isEraserActive(this.state)
  2424. ) {
  2425. this.setState({
  2426. activeTool: updateActiveTool(this.state, { type: "selection" }),
  2427. });
  2428. }
  2429. if (
  2430. this.state.activeTool.type === "eraser" &&
  2431. prevState.theme !== this.state.theme
  2432. ) {
  2433. setEraserCursor(this.interactiveCanvas, this.state.theme);
  2434. }
  2435. // Hide hyperlink popup if shown when element type is not selection
  2436. if (
  2437. prevState.activeTool.type === "selection" &&
  2438. this.state.activeTool.type !== "selection" &&
  2439. this.state.showHyperlinkPopup
  2440. ) {
  2441. this.setState({ showHyperlinkPopup: false });
  2442. }
  2443. if (prevProps.langCode !== this.props.langCode) {
  2444. this.updateLanguage();
  2445. }
  2446. if (isEraserActive(prevState) && !isEraserActive(this.state)) {
  2447. this.eraserTrail.endPath();
  2448. }
  2449. if (prevProps.viewModeEnabled !== this.props.viewModeEnabled) {
  2450. this.setState({ viewModeEnabled: !!this.props.viewModeEnabled });
  2451. }
  2452. if (prevState.viewModeEnabled !== this.state.viewModeEnabled) {
  2453. this.addEventListeners();
  2454. this.deselectElements();
  2455. }
  2456. if (prevProps.zenModeEnabled !== this.props.zenModeEnabled) {
  2457. this.setState({ zenModeEnabled: !!this.props.zenModeEnabled });
  2458. }
  2459. if (prevProps.theme !== this.props.theme && this.props.theme) {
  2460. this.setState({ theme: this.props.theme });
  2461. }
  2462. if (prevProps.gridModeEnabled !== this.props.gridModeEnabled) {
  2463. this.setState({
  2464. gridSize: this.props.gridModeEnabled ? GRID_SIZE : null,
  2465. });
  2466. }
  2467. if (this.props.name && prevProps.name !== this.props.name) {
  2468. this.setState({
  2469. name: this.props.name,
  2470. });
  2471. }
  2472. this.excalidrawContainerRef.current?.classList.toggle(
  2473. "theme--dark",
  2474. this.state.theme === "dark",
  2475. );
  2476. if (
  2477. this.state.editingLinearElement &&
  2478. !this.state.selectedElementIds[this.state.editingLinearElement.elementId]
  2479. ) {
  2480. // defer so that the commitToHistory flag isn't reset via current update
  2481. setTimeout(() => {
  2482. // execute only if the condition still holds when the deferred callback
  2483. // executes (it can be scheduled multiple times depending on how
  2484. // many times the component renders)
  2485. this.state.editingLinearElement &&
  2486. this.actionManager.executeAction(actionFinalize);
  2487. });
  2488. }
  2489. // failsafe in case the state is being updated in incorrect order resulting
  2490. // in the editingElement being now a deleted element
  2491. if (this.state.editingElement?.isDeleted) {
  2492. this.setState({ editingElement: null });
  2493. }
  2494. if (
  2495. this.state.selectedLinearElement &&
  2496. !this.state.selectedElementIds[this.state.selectedLinearElement.elementId]
  2497. ) {
  2498. // To make sure `selectedLinearElement` is in sync with `selectedElementIds`, however this shouldn't be needed once
  2499. // we have a single API to update `selectedElementIds`
  2500. this.setState({ selectedLinearElement: null });
  2501. }
  2502. const { multiElement } = prevState;
  2503. if (
  2504. prevState.activeTool !== this.state.activeTool &&
  2505. multiElement != null &&
  2506. isBindingEnabled(this.state) &&
  2507. isBindingElement(multiElement, false)
  2508. ) {
  2509. maybeBindLinearElement(
  2510. multiElement,
  2511. this.state,
  2512. this.scene,
  2513. tupleToCoors(
  2514. LinearElementEditor.getPointAtIndexGlobalCoordinates(
  2515. multiElement,
  2516. -1,
  2517. ),
  2518. ),
  2519. );
  2520. }
  2521. this.history.record(this.state, this.scene.getElementsIncludingDeleted());
  2522. // Do not notify consumers if we're still loading the scene. Among other
  2523. // potential issues, this fixes a case where the tab isn't focused during
  2524. // init, which would trigger onChange with empty elements, which would then
  2525. // override whatever is in localStorage currently.
  2526. if (!this.state.isLoading) {
  2527. this.props.onChange?.(
  2528. this.scene.getElementsIncludingDeleted(),
  2529. this.state,
  2530. this.files,
  2531. );
  2532. this.onChangeEmitter.trigger(
  2533. this.scene.getElementsIncludingDeleted(),
  2534. this.state,
  2535. this.files,
  2536. );
  2537. }
  2538. }
  2539. private renderInteractiveSceneCallback = ({
  2540. atLeastOneVisibleElement,
  2541. scrollBars,
  2542. elements,
  2543. }: RenderInteractiveSceneCallback) => {
  2544. if (scrollBars) {
  2545. currentScrollBars = scrollBars;
  2546. }
  2547. const scrolledOutside =
  2548. // hide when editing text
  2549. isTextElement(this.state.editingElement)
  2550. ? false
  2551. : !atLeastOneVisibleElement && elements.length > 0;
  2552. if (this.state.scrolledOutside !== scrolledOutside) {
  2553. this.setState({ scrolledOutside });
  2554. }
  2555. this.scheduleImageRefresh();
  2556. };
  2557. private onScroll = debounce(() => {
  2558. const { offsetTop, offsetLeft } = this.getCanvasOffsets();
  2559. this.setState((state) => {
  2560. if (state.offsetLeft === offsetLeft && state.offsetTop === offsetTop) {
  2561. return null;
  2562. }
  2563. return { offsetTop, offsetLeft };
  2564. });
  2565. }, SCROLL_TIMEOUT);
  2566. // Copy/paste
  2567. private onCut = withBatchedUpdates((event: ClipboardEvent) => {
  2568. const isExcalidrawActive = this.excalidrawContainerRef.current?.contains(
  2569. document.activeElement,
  2570. );
  2571. if (!isExcalidrawActive || isWritableElement(event.target)) {
  2572. return;
  2573. }
  2574. this.actionManager.executeAction(actionCut, "keyboard", event);
  2575. event.preventDefault();
  2576. event.stopPropagation();
  2577. });
  2578. private onCopy = withBatchedUpdates((event: ClipboardEvent) => {
  2579. const isExcalidrawActive = this.excalidrawContainerRef.current?.contains(
  2580. document.activeElement,
  2581. );
  2582. if (!isExcalidrawActive || isWritableElement(event.target)) {
  2583. return;
  2584. }
  2585. this.actionManager.executeAction(actionCopy, "keyboard", event);
  2586. event.preventDefault();
  2587. event.stopPropagation();
  2588. });
  2589. private static resetTapTwice() {
  2590. didTapTwice = false;
  2591. }
  2592. private onTouchStart = (event: TouchEvent) => {
  2593. // fix for Apple Pencil Scribble (do not prevent for other devices)
  2594. if (isIOS) {
  2595. event.preventDefault();
  2596. }
  2597. if (!didTapTwice) {
  2598. didTapTwice = true;
  2599. clearTimeout(tappedTwiceTimer);
  2600. tappedTwiceTimer = window.setTimeout(
  2601. App.resetTapTwice,
  2602. TAP_TWICE_TIMEOUT,
  2603. );
  2604. return;
  2605. }
  2606. // insert text only if we tapped twice with a single finger
  2607. // event.touches.length === 1 will also prevent inserting text when user's zooming
  2608. if (didTapTwice && event.touches.length === 1) {
  2609. const touch = event.touches[0];
  2610. // @ts-ignore
  2611. this.handleCanvasDoubleClick({
  2612. clientX: touch.clientX,
  2613. clientY: touch.clientY,
  2614. });
  2615. didTapTwice = false;
  2616. clearTimeout(tappedTwiceTimer);
  2617. }
  2618. if (event.touches.length === 2) {
  2619. this.setState({
  2620. selectedElementIds: makeNextSelectedElementIds({}, this.state),
  2621. activeEmbeddable: null,
  2622. });
  2623. }
  2624. };
  2625. private onTouchEnd = (event: TouchEvent) => {
  2626. this.resetContextMenuTimer();
  2627. if (event.touches.length > 0) {
  2628. this.setState({
  2629. previousSelectedElementIds: {},
  2630. selectedElementIds: makeNextSelectedElementIds(
  2631. this.state.previousSelectedElementIds,
  2632. this.state,
  2633. ),
  2634. });
  2635. } else {
  2636. gesture.pointers.clear();
  2637. }
  2638. };
  2639. public pasteFromClipboard = withBatchedUpdates(
  2640. async (event: ClipboardEvent) => {
  2641. const isPlainPaste = !!IS_PLAIN_PASTE;
  2642. // #686
  2643. const target = document.activeElement;
  2644. const isExcalidrawActive =
  2645. this.excalidrawContainerRef.current?.contains(target);
  2646. if (event && !isExcalidrawActive) {
  2647. return;
  2648. }
  2649. const elementUnderCursor = document.elementFromPoint(
  2650. this.lastViewportPosition.x,
  2651. this.lastViewportPosition.y,
  2652. );
  2653. if (
  2654. event &&
  2655. (!(elementUnderCursor instanceof HTMLCanvasElement) ||
  2656. isWritableElement(target))
  2657. ) {
  2658. return;
  2659. }
  2660. const { x: sceneX, y: sceneY } = viewportCoordsToSceneCoords(
  2661. {
  2662. clientX: this.lastViewportPosition.x,
  2663. clientY: this.lastViewportPosition.y,
  2664. },
  2665. this.state,
  2666. );
  2667. // must be called in the same frame (thus before any awaits) as the paste
  2668. // event else some browsers (FF...) will clear the clipboardData
  2669. // (something something security)
  2670. let file = event?.clipboardData?.files[0];
  2671. const data = await parseClipboard(event, isPlainPaste);
  2672. if (!file && !isPlainPaste) {
  2673. if (data.mixedContent) {
  2674. return this.addElementsFromMixedContentPaste(data.mixedContent, {
  2675. isPlainPaste,
  2676. sceneX,
  2677. sceneY,
  2678. });
  2679. } else if (data.text) {
  2680. const string = data.text.trim();
  2681. if (string.startsWith("<svg") && string.endsWith("</svg>")) {
  2682. // ignore SVG validation/normalization which will be done during image
  2683. // initialization
  2684. file = SVGStringToFile(string);
  2685. }
  2686. }
  2687. }
  2688. // prefer spreadsheet data over image file (MS Office/Libre Office)
  2689. if (isSupportedImageFile(file) && !data.spreadsheet) {
  2690. if (!this.isToolSupported("image")) {
  2691. this.setState({ errorMessage: t("errors.imageToolNotSupported") });
  2692. return;
  2693. }
  2694. const imageElement = this.createImageElement({ sceneX, sceneY });
  2695. this.insertImageElement(imageElement, file);
  2696. this.initializeImageDimensions(imageElement);
  2697. this.setState({
  2698. selectedElementIds: makeNextSelectedElementIds(
  2699. {
  2700. [imageElement.id]: true,
  2701. },
  2702. this.state,
  2703. ),
  2704. });
  2705. return;
  2706. }
  2707. if (this.props.onPaste) {
  2708. try {
  2709. if ((await this.props.onPaste(data, event)) === false) {
  2710. return;
  2711. }
  2712. } catch (error: any) {
  2713. console.error(error);
  2714. }
  2715. }
  2716. if (data.errorMessage) {
  2717. this.setState({ errorMessage: data.errorMessage });
  2718. } else if (data.spreadsheet && !isPlainPaste) {
  2719. this.setState({
  2720. pasteDialog: {
  2721. data: data.spreadsheet,
  2722. shown: true,
  2723. },
  2724. });
  2725. } else if (data.elements) {
  2726. const elements = (
  2727. data.programmaticAPI
  2728. ? convertToExcalidrawElements(
  2729. data.elements as ExcalidrawElementSkeleton[],
  2730. )
  2731. : data.elements
  2732. ) as readonly ExcalidrawElement[];
  2733. // TODO remove formatting from elements if isPlainPaste
  2734. this.addElementsFromPasteOrLibrary({
  2735. elements,
  2736. files: data.files || null,
  2737. position: "cursor",
  2738. retainSeed: isPlainPaste,
  2739. });
  2740. } else if (data.text) {
  2741. const nonEmptyLines = normalizeEOL(data.text)
  2742. .split(/\n+/)
  2743. .map((s) => s.trim())
  2744. .filter(Boolean);
  2745. const embbeddableUrls = nonEmptyLines
  2746. .map((str) => maybeParseEmbedSrc(str))
  2747. .filter((string) => {
  2748. return (
  2749. embeddableURLValidator(string, this.props.validateEmbeddable) &&
  2750. (/^(http|https):\/\/[^\s/$.?#].[^\s]*$/.test(string) ||
  2751. getEmbedLink(string)?.type === "video")
  2752. );
  2753. });
  2754. if (
  2755. !IS_PLAIN_PASTE &&
  2756. embbeddableUrls.length > 0 &&
  2757. // if there were non-embeddable text (lines) mixed in with embeddable
  2758. // urls, ignore and paste as text
  2759. embbeddableUrls.length === nonEmptyLines.length
  2760. ) {
  2761. const embeddables: NonDeleted<ExcalidrawEmbeddableElement>[] = [];
  2762. for (const url of embbeddableUrls) {
  2763. const prevEmbeddable: ExcalidrawEmbeddableElement | undefined =
  2764. embeddables[embeddables.length - 1];
  2765. const embeddable = this.insertEmbeddableElement({
  2766. sceneX: prevEmbeddable
  2767. ? prevEmbeddable.x + prevEmbeddable.width + 20
  2768. : sceneX,
  2769. sceneY,
  2770. link: normalizeLink(url),
  2771. });
  2772. if (embeddable) {
  2773. embeddables.push(embeddable);
  2774. }
  2775. }
  2776. if (embeddables.length) {
  2777. this.setState({
  2778. selectedElementIds: Object.fromEntries(
  2779. embeddables.map((embeddable) => [embeddable.id, true]),
  2780. ),
  2781. });
  2782. }
  2783. return;
  2784. }
  2785. this.addTextFromPaste(data.text, isPlainPaste);
  2786. }
  2787. this.setActiveTool({ type: "selection" });
  2788. event?.preventDefault();
  2789. },
  2790. );
  2791. addElementsFromPasteOrLibrary = (opts: {
  2792. elements: readonly ExcalidrawElement[];
  2793. files: BinaryFiles | null;
  2794. position: { clientX: number; clientY: number } | "cursor" | "center";
  2795. retainSeed?: boolean;
  2796. fitToContent?: boolean;
  2797. }) => {
  2798. const elements = restoreElements(opts.elements, null, undefined);
  2799. const [minX, minY, maxX, maxY] = getCommonBounds(elements);
  2800. const elementsCenterX = distance(minX, maxX) / 2;
  2801. const elementsCenterY = distance(minY, maxY) / 2;
  2802. const clientX =
  2803. typeof opts.position === "object"
  2804. ? opts.position.clientX
  2805. : opts.position === "cursor"
  2806. ? this.lastViewportPosition.x
  2807. : this.state.width / 2 + this.state.offsetLeft;
  2808. const clientY =
  2809. typeof opts.position === "object"
  2810. ? opts.position.clientY
  2811. : opts.position === "cursor"
  2812. ? this.lastViewportPosition.y
  2813. : this.state.height / 2 + this.state.offsetTop;
  2814. const { x, y } = viewportCoordsToSceneCoords(
  2815. { clientX, clientY },
  2816. this.state,
  2817. );
  2818. const dx = x - elementsCenterX;
  2819. const dy = y - elementsCenterY;
  2820. const [gridX, gridY] = getGridPoint(dx, dy, this.state.gridSize);
  2821. const newElements = duplicateElements(
  2822. elements.map((element) => {
  2823. return newElementWith(element, {
  2824. x: element.x + gridX - minX,
  2825. y: element.y + gridY - minY,
  2826. });
  2827. }),
  2828. {
  2829. randomizeSeed: !opts.retainSeed,
  2830. },
  2831. );
  2832. const nextElements = [
  2833. ...this.scene.getElementsIncludingDeleted(),
  2834. ...newElements,
  2835. ];
  2836. this.scene.replaceAllElements(nextElements);
  2837. newElements.forEach((newElement) => {
  2838. if (isTextElement(newElement) && isBoundToContainer(newElement)) {
  2839. const container = getContainerElement(newElement);
  2840. redrawTextBoundingBox(newElement, container);
  2841. }
  2842. });
  2843. if (opts.files) {
  2844. this.files = { ...this.files, ...opts.files };
  2845. }
  2846. this.history.resumeRecording();
  2847. const nextElementsToSelect =
  2848. excludeElementsInFramesFromSelection(newElements);
  2849. this.setState(
  2850. {
  2851. ...this.state,
  2852. // keep sidebar (presumably the library) open if it's docked and
  2853. // can fit.
  2854. //
  2855. // Note, we should close the sidebar only if we're dropping items
  2856. // from library, not when pasting from clipboard. Alas.
  2857. openSidebar:
  2858. this.state.openSidebar &&
  2859. this.device.editor.canFitSidebar &&
  2860. jotaiStore.get(isSidebarDockedAtom)
  2861. ? this.state.openSidebar
  2862. : null,
  2863. ...selectGroupsForSelectedElements(
  2864. {
  2865. editingGroupId: null,
  2866. selectedElementIds: nextElementsToSelect.reduce(
  2867. (acc: Record<ExcalidrawElement["id"], true>, element) => {
  2868. if (!isBoundToContainer(element)) {
  2869. acc[element.id] = true;
  2870. }
  2871. return acc;
  2872. },
  2873. {},
  2874. ),
  2875. },
  2876. this.scene.getNonDeletedElements(),
  2877. this.state,
  2878. this,
  2879. ),
  2880. },
  2881. () => {
  2882. if (opts.files) {
  2883. this.addNewImagesToImageCache();
  2884. }
  2885. },
  2886. );
  2887. this.setActiveTool({ type: "selection" });
  2888. if (opts.fitToContent) {
  2889. this.scrollToContent(newElements, {
  2890. fitToContent: true,
  2891. });
  2892. }
  2893. };
  2894. // TODO rewrite this to paste both text & images at the same time if
  2895. // pasted data contains both
  2896. private async addElementsFromMixedContentPaste(
  2897. mixedContent: PastedMixedContent,
  2898. {
  2899. isPlainPaste,
  2900. sceneX,
  2901. sceneY,
  2902. }: { isPlainPaste: boolean; sceneX: number; sceneY: number },
  2903. ) {
  2904. if (
  2905. !isPlainPaste &&
  2906. mixedContent.some((node) => node.type === "imageUrl") &&
  2907. this.isToolSupported("image")
  2908. ) {
  2909. const imageURLs = mixedContent
  2910. .filter((node) => node.type === "imageUrl")
  2911. .map((node) => node.value);
  2912. const responses = await Promise.all(
  2913. imageURLs.map(async (url) => {
  2914. try {
  2915. return { file: await ImageURLToFile(url) };
  2916. } catch (error: any) {
  2917. return { errorMessage: error.message as string };
  2918. }
  2919. }),
  2920. );
  2921. let y = sceneY;
  2922. let firstImageYOffsetDone = false;
  2923. const nextSelectedIds: Record<ExcalidrawElement["id"], true> = {};
  2924. for (const response of responses) {
  2925. if (response.file) {
  2926. const imageElement = this.createImageElement({
  2927. sceneX,
  2928. sceneY: y,
  2929. });
  2930. const initializedImageElement = await this.insertImageElement(
  2931. imageElement,
  2932. response.file,
  2933. );
  2934. if (initializedImageElement) {
  2935. // vertically center first image in the batch
  2936. if (!firstImageYOffsetDone) {
  2937. firstImageYOffsetDone = true;
  2938. y -= initializedImageElement.height / 2;
  2939. }
  2940. // hack to reset the `y` coord because we vertically center during
  2941. // insertImageElement
  2942. mutateElement(initializedImageElement, { y }, false);
  2943. y = imageElement.y + imageElement.height + 25;
  2944. nextSelectedIds[imageElement.id] = true;
  2945. }
  2946. }
  2947. }
  2948. this.setState({
  2949. selectedElementIds: makeNextSelectedElementIds(
  2950. nextSelectedIds,
  2951. this.state,
  2952. ),
  2953. });
  2954. const error = responses.find((response) => !!response.errorMessage);
  2955. if (error && error.errorMessage) {
  2956. this.setState({ errorMessage: error.errorMessage });
  2957. }
  2958. } else {
  2959. const textNodes = mixedContent.filter((node) => node.type === "text");
  2960. if (textNodes.length) {
  2961. this.addTextFromPaste(
  2962. textNodes.map((node) => node.value).join("\n\n"),
  2963. isPlainPaste,
  2964. );
  2965. }
  2966. }
  2967. }
  2968. private addTextFromPaste(text: string, isPlainPaste = false) {
  2969. const { x, y } = viewportCoordsToSceneCoords(
  2970. {
  2971. clientX: this.lastViewportPosition.x,
  2972. clientY: this.lastViewportPosition.y,
  2973. },
  2974. this.state,
  2975. );
  2976. const textElementProps = {
  2977. x,
  2978. y,
  2979. strokeColor: this.state.currentItemStrokeColor,
  2980. backgroundColor: this.state.currentItemBackgroundColor,
  2981. fillStyle: this.state.currentItemFillStyle,
  2982. strokeWidth: this.state.currentItemStrokeWidth,
  2983. strokeStyle: this.state.currentItemStrokeStyle,
  2984. roundness: null,
  2985. roughness: this.state.currentItemRoughness,
  2986. opacity: this.state.currentItemOpacity,
  2987. text,
  2988. fontSize: this.state.currentItemFontSize,
  2989. fontFamily: this.state.currentItemFontFamily,
  2990. textAlign: this.state.currentItemTextAlign,
  2991. verticalAlign: DEFAULT_VERTICAL_ALIGN,
  2992. locked: false,
  2993. };
  2994. const LINE_GAP = 10;
  2995. let currentY = y;
  2996. const lines = isPlainPaste ? [text] : text.split("\n");
  2997. const textElements = lines.reduce(
  2998. (acc: ExcalidrawTextElement[], line, idx) => {
  2999. const text = line.trim();
  3000. const lineHeight = getDefaultLineHeight(textElementProps.fontFamily);
  3001. if (text.length) {
  3002. const topLayerFrame = this.getTopLayerFrameAtSceneCoords({
  3003. x,
  3004. y: currentY,
  3005. });
  3006. const element = newTextElement({
  3007. ...textElementProps,
  3008. x,
  3009. y: currentY,
  3010. text,
  3011. lineHeight,
  3012. frameId: topLayerFrame ? topLayerFrame.id : null,
  3013. });
  3014. acc.push(element);
  3015. currentY += element.height + LINE_GAP;
  3016. } else {
  3017. const prevLine = lines[idx - 1]?.trim();
  3018. // add paragraph only if previous line was not empty, IOW don't add
  3019. // more than one empty line
  3020. if (prevLine) {
  3021. currentY +=
  3022. getLineHeightInPx(textElementProps.fontSize, lineHeight) +
  3023. LINE_GAP;
  3024. }
  3025. }
  3026. return acc;
  3027. },
  3028. [],
  3029. );
  3030. if (textElements.length === 0) {
  3031. return;
  3032. }
  3033. const frameId = textElements[0].frameId;
  3034. if (frameId) {
  3035. this.scene.insertElementsAtIndex(
  3036. textElements,
  3037. this.scene.getElementIndex(frameId),
  3038. );
  3039. } else {
  3040. this.scene.replaceAllElements([
  3041. ...this.scene.getElementsIncludingDeleted(),
  3042. ...textElements,
  3043. ]);
  3044. }
  3045. this.setState({
  3046. selectedElementIds: makeNextSelectedElementIds(
  3047. Object.fromEntries(textElements.map((el) => [el.id, true])),
  3048. this.state,
  3049. ),
  3050. });
  3051. if (
  3052. !isPlainPaste &&
  3053. textElements.length > 1 &&
  3054. PLAIN_PASTE_TOAST_SHOWN === false &&
  3055. !this.device.editor.isMobile
  3056. ) {
  3057. this.setToast({
  3058. message: t("toast.pasteAsSingleElement", {
  3059. shortcut: getShortcutKey("CtrlOrCmd+Shift+V"),
  3060. }),
  3061. duration: 5000,
  3062. });
  3063. PLAIN_PASTE_TOAST_SHOWN = true;
  3064. }
  3065. this.history.resumeRecording();
  3066. }
  3067. setAppState: React.Component<any, AppState>["setState"] = (
  3068. state,
  3069. callback,
  3070. ) => {
  3071. this.setState(state, callback);
  3072. };
  3073. removePointer = (event: React.PointerEvent<HTMLElement> | PointerEvent) => {
  3074. if (touchTimeout) {
  3075. this.resetContextMenuTimer();
  3076. }
  3077. gesture.pointers.delete(event.pointerId);
  3078. };
  3079. toggleLock = (source: "keyboard" | "ui" = "ui") => {
  3080. if (!this.state.activeTool.locked) {
  3081. trackEvent(
  3082. "toolbar",
  3083. "toggleLock",
  3084. `${source} (${this.device.editor.isMobile ? "mobile" : "desktop"})`,
  3085. );
  3086. }
  3087. this.setState((prevState) => {
  3088. return {
  3089. activeTool: {
  3090. ...prevState.activeTool,
  3091. ...updateActiveTool(
  3092. this.state,
  3093. prevState.activeTool.locked
  3094. ? { type: "selection" }
  3095. : prevState.activeTool,
  3096. ),
  3097. locked: !prevState.activeTool.locked,
  3098. },
  3099. };
  3100. });
  3101. };
  3102. updateFrameRendering = (
  3103. opts:
  3104. | Partial<AppState["frameRendering"]>
  3105. | ((
  3106. prevState: AppState["frameRendering"],
  3107. ) => Partial<AppState["frameRendering"]>),
  3108. ) => {
  3109. this.setState((prevState) => {
  3110. const next =
  3111. typeof opts === "function" ? opts(prevState.frameRendering) : opts;
  3112. return {
  3113. frameRendering: {
  3114. enabled: next?.enabled ?? prevState.frameRendering.enabled,
  3115. clip: next?.clip ?? prevState.frameRendering.clip,
  3116. name: next?.name ?? prevState.frameRendering.name,
  3117. outline: next?.outline ?? prevState.frameRendering.outline,
  3118. },
  3119. };
  3120. });
  3121. };
  3122. togglePenMode = (force: boolean | null) => {
  3123. this.setState((prevState) => {
  3124. return {
  3125. penMode: force ?? !prevState.penMode,
  3126. penDetected: true,
  3127. };
  3128. });
  3129. };
  3130. onHandToolToggle = () => {
  3131. this.actionManager.executeAction(actionToggleHandTool);
  3132. };
  3133. /**
  3134. * Zooms on canvas viewport center
  3135. */
  3136. zoomCanvas = (
  3137. /** decimal fraction between 0.1 (10% zoom) and 30 (3000% zoom) */
  3138. value: number,
  3139. ) => {
  3140. this.setState({
  3141. ...getStateForZoom(
  3142. {
  3143. viewportX: this.state.width / 2 + this.state.offsetLeft,
  3144. viewportY: this.state.height / 2 + this.state.offsetTop,
  3145. nextZoom: getNormalizedZoom(value),
  3146. },
  3147. this.state,
  3148. ),
  3149. });
  3150. };
  3151. private cancelInProgressAnimation: (() => void) | null = null;
  3152. scrollToContent = (
  3153. target:
  3154. | ExcalidrawElement
  3155. | readonly ExcalidrawElement[] = this.scene.getNonDeletedElements(),
  3156. opts?:
  3157. | {
  3158. fitToContent?: boolean;
  3159. fitToViewport?: never;
  3160. viewportZoomFactor?: never;
  3161. animate?: boolean;
  3162. duration?: number;
  3163. }
  3164. | {
  3165. fitToContent?: never;
  3166. fitToViewport?: boolean;
  3167. /** when fitToViewport=true, how much screen should the content cover,
  3168. * between 0.1 (10%) and 1 (100%)
  3169. */
  3170. viewportZoomFactor?: number;
  3171. animate?: boolean;
  3172. duration?: number;
  3173. },
  3174. ) => {
  3175. this.cancelInProgressAnimation?.();
  3176. // convert provided target into ExcalidrawElement[] if necessary
  3177. const targetElements = Array.isArray(target) ? target : [target];
  3178. let zoom = this.state.zoom;
  3179. let scrollX = this.state.scrollX;
  3180. let scrollY = this.state.scrollY;
  3181. if (opts?.fitToContent || opts?.fitToViewport) {
  3182. const { appState } = zoomToFit({
  3183. targetElements,
  3184. appState: this.state,
  3185. fitToViewport: !!opts?.fitToViewport,
  3186. viewportZoomFactor: opts?.viewportZoomFactor,
  3187. });
  3188. zoom = appState.zoom;
  3189. scrollX = appState.scrollX;
  3190. scrollY = appState.scrollY;
  3191. } else {
  3192. // compute only the viewport location, without any zoom adjustment
  3193. const scroll = calculateScrollCenter(targetElements, this.state);
  3194. scrollX = scroll.scrollX;
  3195. scrollY = scroll.scrollY;
  3196. }
  3197. // when animating, we use RequestAnimationFrame to prevent the animation
  3198. // from slowing down other processes
  3199. if (opts?.animate) {
  3200. const origScrollX = this.state.scrollX;
  3201. const origScrollY = this.state.scrollY;
  3202. const origZoom = this.state.zoom.value;
  3203. const cancel = easeToValuesRAF({
  3204. fromValues: {
  3205. scrollX: origScrollX,
  3206. scrollY: origScrollY,
  3207. zoom: origZoom,
  3208. },
  3209. toValues: { scrollX, scrollY, zoom: zoom.value },
  3210. interpolateValue: (from, to, progress, key) => {
  3211. // for zoom, use different easing
  3212. if (key === "zoom") {
  3213. return from * Math.pow(to / from, easeOut(progress));
  3214. }
  3215. // handle using default
  3216. return undefined;
  3217. },
  3218. onStep: ({ scrollX, scrollY, zoom }) => {
  3219. this.setState({
  3220. scrollX,
  3221. scrollY,
  3222. zoom: { value: zoom },
  3223. });
  3224. },
  3225. onStart: () => {
  3226. this.setState({ shouldCacheIgnoreZoom: true });
  3227. },
  3228. onEnd: () => {
  3229. this.setState({ shouldCacheIgnoreZoom: false });
  3230. },
  3231. onCancel: () => {
  3232. this.setState({ shouldCacheIgnoreZoom: false });
  3233. },
  3234. duration: opts?.duration ?? 500,
  3235. });
  3236. this.cancelInProgressAnimation = () => {
  3237. cancel();
  3238. this.cancelInProgressAnimation = null;
  3239. };
  3240. } else {
  3241. this.setState({ scrollX, scrollY, zoom });
  3242. }
  3243. };
  3244. private maybeUnfollowRemoteUser = () => {
  3245. if (this.state.userToFollow) {
  3246. this.setState({ userToFollow: null });
  3247. }
  3248. };
  3249. /** use when changing scrollX/scrollY/zoom based on user interaction */
  3250. private translateCanvas: React.Component<any, AppState>["setState"] = (
  3251. state,
  3252. ) => {
  3253. this.cancelInProgressAnimation?.();
  3254. this.maybeUnfollowRemoteUser();
  3255. this.setState(state);
  3256. };
  3257. setToast = (
  3258. toast: {
  3259. message: string;
  3260. closable?: boolean;
  3261. duration?: number;
  3262. } | null,
  3263. ) => {
  3264. this.setState({ toast });
  3265. };
  3266. restoreFileFromShare = async () => {
  3267. try {
  3268. const webShareTargetCache = await caches.open("web-share-target");
  3269. const response = await webShareTargetCache.match("shared-file");
  3270. if (response) {
  3271. const blob = await response.blob();
  3272. const file = new File([blob], blob.name || "", { type: blob.type });
  3273. this.loadFileToCanvas(file, null);
  3274. await webShareTargetCache.delete("shared-file");
  3275. window.history.replaceState(null, APP_NAME, window.location.pathname);
  3276. }
  3277. } catch (error: any) {
  3278. this.setState({ errorMessage: error.message });
  3279. }
  3280. };
  3281. /** adds supplied files to existing files in the appState */
  3282. public addFiles: ExcalidrawImperativeAPI["addFiles"] = withBatchedUpdates(
  3283. (files) => {
  3284. const filesMap = files.reduce((acc, fileData) => {
  3285. acc.set(fileData.id, fileData);
  3286. return acc;
  3287. }, new Map<FileId, BinaryFileData>());
  3288. this.files = { ...this.files, ...Object.fromEntries(filesMap) };
  3289. this.scene.getNonDeletedElements().forEach((element) => {
  3290. if (
  3291. isInitializedImageElement(element) &&
  3292. filesMap.has(element.fileId)
  3293. ) {
  3294. this.imageCache.delete(element.fileId);
  3295. ShapeCache.delete(element);
  3296. }
  3297. });
  3298. this.scene.informMutation();
  3299. this.addNewImagesToImageCache();
  3300. },
  3301. );
  3302. public updateScene = withBatchedUpdates(
  3303. <K extends keyof AppState>(sceneData: {
  3304. elements?: SceneData["elements"];
  3305. appState?: Pick<AppState, K> | null;
  3306. collaborators?: SceneData["collaborators"];
  3307. commitToHistory?: SceneData["commitToHistory"];
  3308. }) => {
  3309. if (sceneData.commitToHistory) {
  3310. this.history.resumeRecording();
  3311. }
  3312. if (sceneData.appState) {
  3313. this.setState(sceneData.appState);
  3314. }
  3315. if (sceneData.elements) {
  3316. this.scene.replaceAllElements(sceneData.elements);
  3317. }
  3318. if (sceneData.collaborators) {
  3319. this.setState({ collaborators: sceneData.collaborators });
  3320. }
  3321. },
  3322. );
  3323. private onSceneUpdated = () => {
  3324. this.setState({});
  3325. };
  3326. /**
  3327. * @returns whether the menu was toggled on or off
  3328. */
  3329. public toggleSidebar = ({
  3330. name,
  3331. tab,
  3332. force,
  3333. }: {
  3334. name: SidebarName;
  3335. tab?: SidebarTabName;
  3336. force?: boolean;
  3337. }): boolean => {
  3338. let nextName;
  3339. if (force === undefined) {
  3340. nextName = this.state.openSidebar?.name === name ? null : name;
  3341. } else {
  3342. nextName = force ? name : null;
  3343. }
  3344. this.setState({ openSidebar: nextName ? { name: nextName, tab } : null });
  3345. return !!nextName;
  3346. };
  3347. private updateCurrentCursorPosition = withBatchedUpdates(
  3348. (event: MouseEvent) => {
  3349. this.lastViewportPosition.x = event.clientX;
  3350. this.lastViewportPosition.y = event.clientY;
  3351. },
  3352. );
  3353. // Input handling
  3354. private onKeyDown = withBatchedUpdates(
  3355. (event: React.KeyboardEvent | KeyboardEvent) => {
  3356. // normalize `event.key` when CapsLock is pressed #2372
  3357. if (
  3358. "Proxy" in window &&
  3359. ((!event.shiftKey && /^[A-Z]$/.test(event.key)) ||
  3360. (event.shiftKey && /^[a-z]$/.test(event.key)))
  3361. ) {
  3362. event = new Proxy(event, {
  3363. get(ev: any, prop) {
  3364. const value = ev[prop];
  3365. if (typeof value === "function") {
  3366. // fix for Proxies hijacking `this`
  3367. return value.bind(ev);
  3368. }
  3369. return prop === "key"
  3370. ? // CapsLock inverts capitalization based on ShiftKey, so invert
  3371. // it back
  3372. event.shiftKey
  3373. ? ev.key.toUpperCase()
  3374. : ev.key.toLowerCase()
  3375. : value;
  3376. },
  3377. });
  3378. }
  3379. if (event[KEYS.CTRL_OR_CMD] && event.key.toLowerCase() === KEYS.V) {
  3380. IS_PLAIN_PASTE = event.shiftKey;
  3381. clearTimeout(IS_PLAIN_PASTE_TIMER);
  3382. // reset (100ms to be safe that we it runs after the ensuing
  3383. // paste event). Though, technically unnecessary to reset since we
  3384. // (re)set the flag before each paste event.
  3385. IS_PLAIN_PASTE_TIMER = window.setTimeout(() => {
  3386. IS_PLAIN_PASTE = false;
  3387. }, 100);
  3388. }
  3389. // prevent browser zoom in input fields
  3390. if (event[KEYS.CTRL_OR_CMD] && isWritableElement(event.target)) {
  3391. if (event.code === CODES.MINUS || event.code === CODES.EQUAL) {
  3392. event.preventDefault();
  3393. return;
  3394. }
  3395. }
  3396. // bail if
  3397. if (
  3398. // inside an input
  3399. (isWritableElement(event.target) &&
  3400. // unless pressing escape (finalize action)
  3401. event.key !== KEYS.ESCAPE) ||
  3402. // or unless using arrows (to move between buttons)
  3403. (isArrowKey(event.key) && isInputLike(event.target))
  3404. ) {
  3405. return;
  3406. }
  3407. if (event.key === KEYS.QUESTION_MARK) {
  3408. this.setState({
  3409. openDialog: { name: "help" },
  3410. });
  3411. return;
  3412. } else if (
  3413. event.key.toLowerCase() === KEYS.E &&
  3414. event.shiftKey &&
  3415. event[KEYS.CTRL_OR_CMD]
  3416. ) {
  3417. event.preventDefault();
  3418. this.setState({ openDialog: { name: "imageExport" } });
  3419. return;
  3420. }
  3421. if (event.key === KEYS.PAGE_UP || event.key === KEYS.PAGE_DOWN) {
  3422. let offset =
  3423. (event.shiftKey ? this.state.width : this.state.height) /
  3424. this.state.zoom.value;
  3425. if (event.key === KEYS.PAGE_DOWN) {
  3426. offset = -offset;
  3427. }
  3428. if (event.shiftKey) {
  3429. this.translateCanvas((state) => ({
  3430. scrollX: state.scrollX + offset,
  3431. }));
  3432. } else {
  3433. this.translateCanvas((state) => ({
  3434. scrollY: state.scrollY + offset,
  3435. }));
  3436. }
  3437. }
  3438. if (this.actionManager.handleKeyDown(event)) {
  3439. return;
  3440. }
  3441. if (this.state.viewModeEnabled) {
  3442. return;
  3443. }
  3444. if (event[KEYS.CTRL_OR_CMD] && this.state.isBindingEnabled) {
  3445. this.setState({ isBindingEnabled: false });
  3446. }
  3447. if (isArrowKey(event.key)) {
  3448. const step =
  3449. (this.state.gridSize &&
  3450. (event.shiftKey
  3451. ? ELEMENT_TRANSLATE_AMOUNT
  3452. : this.state.gridSize)) ||
  3453. (event.shiftKey
  3454. ? ELEMENT_SHIFT_TRANSLATE_AMOUNT
  3455. : ELEMENT_TRANSLATE_AMOUNT);
  3456. let offsetX = 0;
  3457. let offsetY = 0;
  3458. if (event.key === KEYS.ARROW_LEFT) {
  3459. offsetX = -step;
  3460. } else if (event.key === KEYS.ARROW_RIGHT) {
  3461. offsetX = step;
  3462. } else if (event.key === KEYS.ARROW_UP) {
  3463. offsetY = -step;
  3464. } else if (event.key === KEYS.ARROW_DOWN) {
  3465. offsetY = step;
  3466. }
  3467. const selectedElements = this.scene.getSelectedElements({
  3468. selectedElementIds: this.state.selectedElementIds,
  3469. includeBoundTextElement: true,
  3470. includeElementsInFrames: true,
  3471. });
  3472. selectedElements.forEach((element) => {
  3473. mutateElement(element, {
  3474. x: element.x + offsetX,
  3475. y: element.y + offsetY,
  3476. });
  3477. updateBoundElements(element, {
  3478. simultaneouslyUpdated: selectedElements,
  3479. });
  3480. });
  3481. this.maybeSuggestBindingForAll(selectedElements);
  3482. event.preventDefault();
  3483. } else if (event.key === KEYS.ENTER) {
  3484. const selectedElements = this.scene.getSelectedElements(this.state);
  3485. if (selectedElements.length === 1) {
  3486. const selectedElement = selectedElements[0];
  3487. if (event[KEYS.CTRL_OR_CMD]) {
  3488. if (isLinearElement(selectedElement)) {
  3489. if (
  3490. !this.state.editingLinearElement ||
  3491. this.state.editingLinearElement.elementId !==
  3492. selectedElements[0].id
  3493. ) {
  3494. this.history.resumeRecording();
  3495. this.setState({
  3496. editingLinearElement: new LinearElementEditor(
  3497. selectedElement,
  3498. this.scene,
  3499. ),
  3500. });
  3501. }
  3502. }
  3503. } else if (
  3504. isTextElement(selectedElement) ||
  3505. isValidTextContainer(selectedElement)
  3506. ) {
  3507. let container;
  3508. if (!isTextElement(selectedElement)) {
  3509. container = selectedElement as ExcalidrawTextContainer;
  3510. }
  3511. const midPoint = getContainerCenter(selectedElement, this.state);
  3512. const sceneX = midPoint.x;
  3513. const sceneY = midPoint.y;
  3514. this.startTextEditing({
  3515. sceneX,
  3516. sceneY,
  3517. container,
  3518. });
  3519. event.preventDefault();
  3520. return;
  3521. } else if (isFrameLikeElement(selectedElement)) {
  3522. this.setState({
  3523. editingFrame: selectedElement.id,
  3524. });
  3525. }
  3526. }
  3527. } else if (
  3528. !event.ctrlKey &&
  3529. !event.altKey &&
  3530. !event.metaKey &&
  3531. this.state.draggingElement === null
  3532. ) {
  3533. const shape = findShapeByKey(event.key);
  3534. if (shape) {
  3535. if (this.state.activeTool.type !== shape) {
  3536. trackEvent(
  3537. "toolbar",
  3538. shape,
  3539. `keyboard (${
  3540. this.device.editor.isMobile ? "mobile" : "desktop"
  3541. })`,
  3542. );
  3543. }
  3544. this.setActiveTool({ type: shape });
  3545. event.stopPropagation();
  3546. } else if (event.key === KEYS.Q) {
  3547. this.toggleLock("keyboard");
  3548. event.stopPropagation();
  3549. }
  3550. }
  3551. if (event.key === KEYS.SPACE && gesture.pointers.size === 0) {
  3552. isHoldingSpace = true;
  3553. setCursor(this.interactiveCanvas, CURSOR_TYPE.GRAB);
  3554. event.preventDefault();
  3555. }
  3556. if (
  3557. (event.key === KEYS.G || event.key === KEYS.S) &&
  3558. !event.altKey &&
  3559. !event[KEYS.CTRL_OR_CMD]
  3560. ) {
  3561. const selectedElements = this.scene.getSelectedElements(this.state);
  3562. if (
  3563. this.state.activeTool.type === "selection" &&
  3564. !selectedElements.length
  3565. ) {
  3566. return;
  3567. }
  3568. if (
  3569. event.key === KEYS.G &&
  3570. (hasBackground(this.state.activeTool.type) ||
  3571. selectedElements.some((element) => hasBackground(element.type)))
  3572. ) {
  3573. this.setState({ openPopup: "elementBackground" });
  3574. event.stopPropagation();
  3575. }
  3576. if (event.key === KEYS.S) {
  3577. this.setState({ openPopup: "elementStroke" });
  3578. event.stopPropagation();
  3579. }
  3580. }
  3581. if (event.key === KEYS.K && !event.altKey && !event[KEYS.CTRL_OR_CMD]) {
  3582. if (this.state.activeTool.type === "laser") {
  3583. this.setActiveTool({ type: "selection" });
  3584. } else {
  3585. this.setActiveTool({ type: "laser" });
  3586. }
  3587. return;
  3588. }
  3589. if (
  3590. event[KEYS.CTRL_OR_CMD] &&
  3591. (event.key === KEYS.BACKSPACE || event.key === KEYS.DELETE)
  3592. ) {
  3593. jotaiStore.set(activeConfirmDialogAtom, "clearCanvas");
  3594. }
  3595. // eye dropper
  3596. // -----------------------------------------------------------------------
  3597. const lowerCased = event.key.toLocaleLowerCase();
  3598. const isPickingStroke = lowerCased === KEYS.S && event.shiftKey;
  3599. const isPickingBackground =
  3600. event.key === KEYS.I || (lowerCased === KEYS.G && event.shiftKey);
  3601. if (isPickingStroke || isPickingBackground) {
  3602. this.openEyeDropper({
  3603. type: isPickingStroke ? "stroke" : "background",
  3604. });
  3605. }
  3606. // -----------------------------------------------------------------------
  3607. },
  3608. );
  3609. private onWheel = withBatchedUpdates((event: WheelEvent) => {
  3610. // prevent browser pinch zoom on DOM elements
  3611. if (!(event.target instanceof HTMLCanvasElement) && event.ctrlKey) {
  3612. event.preventDefault();
  3613. }
  3614. });
  3615. private onKeyUp = withBatchedUpdates((event: KeyboardEvent) => {
  3616. if (event.key === KEYS.SPACE) {
  3617. if (this.state.viewModeEnabled) {
  3618. setCursor(this.interactiveCanvas, CURSOR_TYPE.GRAB);
  3619. } else if (this.state.activeTool.type === "selection") {
  3620. resetCursor(this.interactiveCanvas);
  3621. } else {
  3622. setCursorForShape(this.interactiveCanvas, this.state);
  3623. this.setState({
  3624. selectedElementIds: makeNextSelectedElementIds({}, this.state),
  3625. selectedGroupIds: {},
  3626. editingGroupId: null,
  3627. activeEmbeddable: null,
  3628. });
  3629. }
  3630. isHoldingSpace = false;
  3631. }
  3632. if (!event[KEYS.CTRL_OR_CMD] && !this.state.isBindingEnabled) {
  3633. this.setState({ isBindingEnabled: true });
  3634. }
  3635. if (isArrowKey(event.key)) {
  3636. const selectedElements = this.scene.getSelectedElements(this.state);
  3637. isBindingEnabled(this.state)
  3638. ? bindOrUnbindSelectedElements(selectedElements)
  3639. : unbindLinearElements(selectedElements);
  3640. this.setState({ suggestedBindings: [] });
  3641. }
  3642. });
  3643. // We purposely widen the `tool` type so this helper can be called with
  3644. // any tool without having to type check it
  3645. private isToolSupported = <T extends ToolType | "custom">(tool: T) => {
  3646. return (
  3647. this.props.UIOptions.tools?.[
  3648. tool as Extract<T, keyof AppProps["UIOptions"]["tools"]>
  3649. ] !== false
  3650. );
  3651. };
  3652. setActiveTool = (
  3653. tool: (
  3654. | (
  3655. | { type: Exclude<ToolType, "image"> }
  3656. | {
  3657. type: Extract<ToolType, "image">;
  3658. insertOnCanvasDirectly?: boolean;
  3659. }
  3660. )
  3661. | { type: "custom"; customType: string }
  3662. ) & { locked?: boolean },
  3663. ) => {
  3664. if (!this.isToolSupported(tool.type)) {
  3665. console.warn(
  3666. `"${tool.type}" tool is disabled via "UIOptions.canvasActions.tools.${tool.type}"`,
  3667. );
  3668. return;
  3669. }
  3670. const nextActiveTool = updateActiveTool(this.state, tool);
  3671. if (nextActiveTool.type === "hand") {
  3672. setCursor(this.interactiveCanvas, CURSOR_TYPE.GRAB);
  3673. } else if (!isHoldingSpace) {
  3674. setCursorForShape(this.interactiveCanvas, this.state);
  3675. }
  3676. if (isToolIcon(document.activeElement)) {
  3677. this.focusContainer();
  3678. }
  3679. if (!isLinearElementType(nextActiveTool.type)) {
  3680. this.setState({ suggestedBindings: [] });
  3681. }
  3682. if (nextActiveTool.type === "image") {
  3683. this.onImageAction({
  3684. insertOnCanvasDirectly:
  3685. (tool.type === "image" && tool.insertOnCanvasDirectly) ?? false,
  3686. });
  3687. }
  3688. this.setState((prevState) => {
  3689. const commonResets = {
  3690. snapLines: prevState.snapLines.length ? [] : prevState.snapLines,
  3691. originSnapOffset: null,
  3692. activeEmbeddable: null,
  3693. } as const;
  3694. if (nextActiveTool.type !== "selection") {
  3695. return {
  3696. ...prevState,
  3697. activeTool: nextActiveTool,
  3698. selectedElementIds: makeNextSelectedElementIds({}, prevState),
  3699. selectedGroupIds: makeNextSelectedElementIds({}, prevState),
  3700. editingGroupId: null,
  3701. multiElement: null,
  3702. ...commonResets,
  3703. };
  3704. }
  3705. return {
  3706. ...prevState,
  3707. activeTool: nextActiveTool,
  3708. ...commonResets,
  3709. };
  3710. });
  3711. };
  3712. setOpenDialog = (dialogType: AppState["openDialog"]) => {
  3713. this.setState({ openDialog: dialogType });
  3714. };
  3715. private setCursor = (cursor: string) => {
  3716. setCursor(this.interactiveCanvas, cursor);
  3717. };
  3718. private resetCursor = () => {
  3719. resetCursor(this.interactiveCanvas);
  3720. };
  3721. /**
  3722. * returns whether user is making a gesture with >= 2 fingers (points)
  3723. * on o touch screen (not on a trackpad). Currently only relates to Darwin
  3724. * (iOS/iPadOS,MacOS), but may work on other devices in the future if
  3725. * GestureEvent is standardized.
  3726. */
  3727. private isTouchScreenMultiTouchGesture = () => {
  3728. // we don't want to deselect when using trackpad, and multi-point gestures
  3729. // only work on touch screens, so checking for >= pointers means we're on a
  3730. // touchscreen
  3731. return gesture.pointers.size >= 2;
  3732. };
  3733. // fires only on Safari
  3734. private onGestureStart = withBatchedUpdates((event: GestureEvent) => {
  3735. event.preventDefault();
  3736. // we only want to deselect on touch screens because user may have selected
  3737. // elements by mistake while zooming
  3738. if (this.isTouchScreenMultiTouchGesture()) {
  3739. this.setState({
  3740. selectedElementIds: makeNextSelectedElementIds({}, this.state),
  3741. activeEmbeddable: null,
  3742. });
  3743. }
  3744. gesture.initialScale = this.state.zoom.value;
  3745. });
  3746. // fires only on Safari
  3747. private onGestureChange = withBatchedUpdates((event: GestureEvent) => {
  3748. event.preventDefault();
  3749. // onGestureChange only has zoom factor but not the center.
  3750. // If we're on iPad or iPhone, then we recognize multi-touch and will
  3751. // zoom in at the right location in the touchmove handler
  3752. // (handleCanvasPointerMove).
  3753. //
  3754. // On Macbook trackpad, we don't have those events so will zoom in at the
  3755. // current location instead.
  3756. //
  3757. // As such, bail from this handler on touch devices.
  3758. if (this.isTouchScreenMultiTouchGesture()) {
  3759. return;
  3760. }
  3761. const initialScale = gesture.initialScale;
  3762. if (initialScale) {
  3763. this.setState((state) => ({
  3764. ...getStateForZoom(
  3765. {
  3766. viewportX: this.lastViewportPosition.x,
  3767. viewportY: this.lastViewportPosition.y,
  3768. nextZoom: getNormalizedZoom(initialScale * event.scale),
  3769. },
  3770. state,
  3771. ),
  3772. }));
  3773. }
  3774. });
  3775. // fires only on Safari
  3776. private onGestureEnd = withBatchedUpdates((event: GestureEvent) => {
  3777. event.preventDefault();
  3778. // reselect elements only on touch screens (see onGestureStart)
  3779. if (this.isTouchScreenMultiTouchGesture()) {
  3780. this.setState({
  3781. previousSelectedElementIds: {},
  3782. selectedElementIds: makeNextSelectedElementIds(
  3783. this.state.previousSelectedElementIds,
  3784. this.state,
  3785. ),
  3786. });
  3787. }
  3788. gesture.initialScale = null;
  3789. });
  3790. private handleTextWysiwyg(
  3791. element: ExcalidrawTextElement,
  3792. {
  3793. isExistingElement = false,
  3794. }: {
  3795. isExistingElement?: boolean;
  3796. },
  3797. ) {
  3798. const updateElement = (
  3799. text: string,
  3800. originalText: string,
  3801. isDeleted: boolean,
  3802. ) => {
  3803. this.scene.replaceAllElements([
  3804. ...this.scene.getElementsIncludingDeleted().map((_element) => {
  3805. if (_element.id === element.id && isTextElement(_element)) {
  3806. return updateTextElement(_element, {
  3807. text,
  3808. isDeleted,
  3809. originalText,
  3810. });
  3811. }
  3812. return _element;
  3813. }),
  3814. ]);
  3815. };
  3816. textWysiwyg({
  3817. id: element.id,
  3818. canvas: this.canvas,
  3819. getViewportCoords: (x, y) => {
  3820. const { x: viewportX, y: viewportY } = sceneCoordsToViewportCoords(
  3821. {
  3822. sceneX: x,
  3823. sceneY: y,
  3824. },
  3825. this.state,
  3826. );
  3827. return [
  3828. viewportX - this.state.offsetLeft,
  3829. viewportY - this.state.offsetTop,
  3830. ];
  3831. },
  3832. onChange: withBatchedUpdates((text) => {
  3833. updateElement(text, text, false);
  3834. if (isNonDeletedElement(element)) {
  3835. updateBoundElements(element);
  3836. }
  3837. }),
  3838. onSubmit: withBatchedUpdates(({ text, viaKeyboard, originalText }) => {
  3839. const isDeleted = !text.trim();
  3840. updateElement(text, originalText, isDeleted);
  3841. // select the created text element only if submitting via keyboard
  3842. // (when submitting via click it should act as signal to deselect)
  3843. if (!isDeleted && viaKeyboard) {
  3844. const elementIdToSelect = element.containerId
  3845. ? element.containerId
  3846. : element.id;
  3847. this.setState((prevState) => ({
  3848. selectedElementIds: makeNextSelectedElementIds(
  3849. {
  3850. ...prevState.selectedElementIds,
  3851. [elementIdToSelect]: true,
  3852. },
  3853. prevState,
  3854. ),
  3855. }));
  3856. }
  3857. if (isDeleted) {
  3858. fixBindingsAfterDeletion(this.scene.getNonDeletedElements(), [
  3859. element,
  3860. ]);
  3861. }
  3862. if (!isDeleted || isExistingElement) {
  3863. this.history.resumeRecording();
  3864. }
  3865. this.setState({
  3866. draggingElement: null,
  3867. editingElement: null,
  3868. });
  3869. if (this.state.activeTool.locked) {
  3870. setCursorForShape(this.interactiveCanvas, this.state);
  3871. }
  3872. this.focusContainer();
  3873. }),
  3874. element,
  3875. excalidrawContainer: this.excalidrawContainerRef.current,
  3876. app: this,
  3877. });
  3878. // deselect all other elements when inserting text
  3879. this.deselectElements();
  3880. // do an initial update to re-initialize element position since we were
  3881. // modifying element's x/y for sake of editor (case: syncing to remote)
  3882. updateElement(element.text, element.originalText, false);
  3883. }
  3884. private deselectElements() {
  3885. this.setState({
  3886. selectedElementIds: makeNextSelectedElementIds({}, this.state),
  3887. selectedGroupIds: {},
  3888. editingGroupId: null,
  3889. activeEmbeddable: null,
  3890. });
  3891. }
  3892. private getTextElementAtPosition(
  3893. x: number,
  3894. y: number,
  3895. ): NonDeleted<ExcalidrawTextElement> | null {
  3896. const element = this.getElementAtPosition(x, y, {
  3897. includeBoundTextElement: true,
  3898. });
  3899. if (element && isTextElement(element) && !element.isDeleted) {
  3900. return element;
  3901. }
  3902. return null;
  3903. }
  3904. private getElementAtPosition(
  3905. x: number,
  3906. y: number,
  3907. opts?: {
  3908. /** if true, returns the first selected element (with highest z-index)
  3909. of all hit elements */
  3910. preferSelected?: boolean;
  3911. includeBoundTextElement?: boolean;
  3912. includeLockedElements?: boolean;
  3913. },
  3914. ): NonDeleted<ExcalidrawElement> | null {
  3915. const allHitElements = this.getElementsAtPosition(
  3916. x,
  3917. y,
  3918. opts?.includeBoundTextElement,
  3919. opts?.includeLockedElements,
  3920. );
  3921. if (allHitElements.length > 1) {
  3922. if (opts?.preferSelected) {
  3923. for (let index = allHitElements.length - 1; index > -1; index--) {
  3924. if (this.state.selectedElementIds[allHitElements[index].id]) {
  3925. return allHitElements[index];
  3926. }
  3927. }
  3928. }
  3929. const elementWithHighestZIndex =
  3930. allHitElements[allHitElements.length - 1];
  3931. // If we're hitting element with highest z-index only on its bounding box
  3932. // while also hitting other element figure, the latter should be considered.
  3933. return isHittingElementBoundingBoxWithoutHittingElement(
  3934. elementWithHighestZIndex,
  3935. this.state,
  3936. this.frameNameBoundsCache,
  3937. x,
  3938. y,
  3939. )
  3940. ? allHitElements[allHitElements.length - 2]
  3941. : elementWithHighestZIndex;
  3942. }
  3943. if (allHitElements.length === 1) {
  3944. return allHitElements[0];
  3945. }
  3946. return null;
  3947. }
  3948. private getElementsAtPosition(
  3949. x: number,
  3950. y: number,
  3951. includeBoundTextElement: boolean = false,
  3952. includeLockedElements: boolean = false,
  3953. ): NonDeleted<ExcalidrawElement>[] {
  3954. const elements =
  3955. includeBoundTextElement && includeLockedElements
  3956. ? this.scene.getNonDeletedElements()
  3957. : this.scene
  3958. .getNonDeletedElements()
  3959. .filter(
  3960. (element) =>
  3961. (includeLockedElements || !element.locked) &&
  3962. (includeBoundTextElement ||
  3963. !(isTextElement(element) && element.containerId)),
  3964. );
  3965. return getElementsAtPosition(elements, (element) =>
  3966. hitTest(element, this.state, this.frameNameBoundsCache, x, y),
  3967. ).filter((element) => {
  3968. // hitting a frame's element from outside the frame is not considered a hit
  3969. const containingFrame = getContainingFrame(element);
  3970. return containingFrame &&
  3971. this.state.frameRendering.enabled &&
  3972. this.state.frameRendering.clip
  3973. ? isCursorInFrame({ x, y }, containingFrame)
  3974. : true;
  3975. });
  3976. }
  3977. private startTextEditing = ({
  3978. sceneX,
  3979. sceneY,
  3980. insertAtParentCenter = true,
  3981. container,
  3982. }: {
  3983. /** X position to insert text at */
  3984. sceneX: number;
  3985. /** Y position to insert text at */
  3986. sceneY: number;
  3987. /** whether to attempt to insert at element center if applicable */
  3988. insertAtParentCenter?: boolean;
  3989. container?: ExcalidrawTextContainer | null;
  3990. }) => {
  3991. let shouldBindToContainer = false;
  3992. let parentCenterPosition =
  3993. insertAtParentCenter &&
  3994. this.getTextWysiwygSnappedToCenterPosition(
  3995. sceneX,
  3996. sceneY,
  3997. this.state,
  3998. container,
  3999. );
  4000. if (container && parentCenterPosition) {
  4001. const boundTextElementToContainer = getBoundTextElement(container);
  4002. if (!boundTextElementToContainer) {
  4003. shouldBindToContainer = true;
  4004. }
  4005. }
  4006. let existingTextElement: NonDeleted<ExcalidrawTextElement> | null = null;
  4007. const selectedElements = this.scene.getSelectedElements(this.state);
  4008. if (selectedElements.length === 1) {
  4009. if (isTextElement(selectedElements[0])) {
  4010. existingTextElement = selectedElements[0];
  4011. } else if (container) {
  4012. existingTextElement = getBoundTextElement(selectedElements[0]);
  4013. } else {
  4014. existingTextElement = this.getTextElementAtPosition(sceneX, sceneY);
  4015. }
  4016. } else {
  4017. existingTextElement = this.getTextElementAtPosition(sceneX, sceneY);
  4018. }
  4019. const fontFamily =
  4020. existingTextElement?.fontFamily || this.state.currentItemFontFamily;
  4021. const lineHeight =
  4022. existingTextElement?.lineHeight || getDefaultLineHeight(fontFamily);
  4023. const fontSize = this.state.currentItemFontSize;
  4024. if (
  4025. !existingTextElement &&
  4026. shouldBindToContainer &&
  4027. container &&
  4028. !isArrowElement(container)
  4029. ) {
  4030. const fontString = {
  4031. fontSize,
  4032. fontFamily,
  4033. };
  4034. const minWidth = getApproxMinLineWidth(
  4035. getFontString(fontString),
  4036. lineHeight,
  4037. );
  4038. const minHeight = getApproxMinLineHeight(fontSize, lineHeight);
  4039. const newHeight = Math.max(container.height, minHeight);
  4040. const newWidth = Math.max(container.width, minWidth);
  4041. mutateElement(container, { height: newHeight, width: newWidth });
  4042. sceneX = container.x + newWidth / 2;
  4043. sceneY = container.y + newHeight / 2;
  4044. if (parentCenterPosition) {
  4045. parentCenterPosition = this.getTextWysiwygSnappedToCenterPosition(
  4046. sceneX,
  4047. sceneY,
  4048. this.state,
  4049. container,
  4050. );
  4051. }
  4052. }
  4053. const topLayerFrame = this.getTopLayerFrameAtSceneCoords({
  4054. x: sceneX,
  4055. y: sceneY,
  4056. });
  4057. const element = existingTextElement
  4058. ? existingTextElement
  4059. : newTextElement({
  4060. x: parentCenterPosition
  4061. ? parentCenterPosition.elementCenterX
  4062. : sceneX,
  4063. y: parentCenterPosition
  4064. ? parentCenterPosition.elementCenterY
  4065. : sceneY,
  4066. strokeColor: this.state.currentItemStrokeColor,
  4067. backgroundColor: this.state.currentItemBackgroundColor,
  4068. fillStyle: this.state.currentItemFillStyle,
  4069. strokeWidth: this.state.currentItemStrokeWidth,
  4070. strokeStyle: this.state.currentItemStrokeStyle,
  4071. roughness: this.state.currentItemRoughness,
  4072. opacity: this.state.currentItemOpacity,
  4073. text: "",
  4074. fontSize,
  4075. fontFamily,
  4076. textAlign: parentCenterPosition
  4077. ? "center"
  4078. : this.state.currentItemTextAlign,
  4079. verticalAlign: parentCenterPosition
  4080. ? VERTICAL_ALIGN.MIDDLE
  4081. : DEFAULT_VERTICAL_ALIGN,
  4082. containerId: shouldBindToContainer ? container?.id : undefined,
  4083. groupIds: container?.groupIds ?? [],
  4084. lineHeight,
  4085. angle: container?.angle ?? 0,
  4086. frameId: topLayerFrame ? topLayerFrame.id : null,
  4087. });
  4088. if (!existingTextElement && shouldBindToContainer && container) {
  4089. mutateElement(container, {
  4090. boundElements: (container.boundElements || []).concat({
  4091. type: "text",
  4092. id: element.id,
  4093. }),
  4094. });
  4095. }
  4096. this.setState({ editingElement: element });
  4097. if (!existingTextElement) {
  4098. if (container && shouldBindToContainer) {
  4099. const containerIndex = this.scene.getElementIndex(container.id);
  4100. this.scene.insertElementAtIndex(element, containerIndex + 1);
  4101. } else {
  4102. this.scene.addNewElement(element);
  4103. }
  4104. }
  4105. this.setState({
  4106. editingElement: element,
  4107. });
  4108. this.handleTextWysiwyg(element, {
  4109. isExistingElement: !!existingTextElement,
  4110. });
  4111. };
  4112. private handleCanvasDoubleClick = (
  4113. event: React.MouseEvent<HTMLCanvasElement>,
  4114. ) => {
  4115. // case: double-clicking with arrow/line tool selected would both create
  4116. // text and enter multiElement mode
  4117. if (this.state.multiElement) {
  4118. return;
  4119. }
  4120. // we should only be able to double click when mode is selection
  4121. if (this.state.activeTool.type !== "selection") {
  4122. return;
  4123. }
  4124. const selectedElements = this.scene.getSelectedElements(this.state);
  4125. if (selectedElements.length === 1 && isLinearElement(selectedElements[0])) {
  4126. if (
  4127. event[KEYS.CTRL_OR_CMD] &&
  4128. (!this.state.editingLinearElement ||
  4129. this.state.editingLinearElement.elementId !== selectedElements[0].id)
  4130. ) {
  4131. this.history.resumeRecording();
  4132. this.setState({
  4133. editingLinearElement: new LinearElementEditor(
  4134. selectedElements[0],
  4135. this.scene,
  4136. ),
  4137. });
  4138. return;
  4139. } else if (
  4140. this.state.editingLinearElement &&
  4141. this.state.editingLinearElement.elementId === selectedElements[0].id
  4142. ) {
  4143. return;
  4144. }
  4145. }
  4146. resetCursor(this.interactiveCanvas);
  4147. let { x: sceneX, y: sceneY } = viewportCoordsToSceneCoords(
  4148. event,
  4149. this.state,
  4150. );
  4151. const selectedGroupIds = getSelectedGroupIds(this.state);
  4152. if (selectedGroupIds.length > 0) {
  4153. const hitElement = this.getElementAtPosition(sceneX, sceneY);
  4154. const selectedGroupId =
  4155. hitElement &&
  4156. getSelectedGroupIdForElement(hitElement, this.state.selectedGroupIds);
  4157. if (selectedGroupId) {
  4158. this.setState((prevState) => ({
  4159. ...prevState,
  4160. ...selectGroupsForSelectedElements(
  4161. {
  4162. editingGroupId: selectedGroupId,
  4163. selectedElementIds: { [hitElement!.id]: true },
  4164. },
  4165. this.scene.getNonDeletedElements(),
  4166. prevState,
  4167. this,
  4168. ),
  4169. }));
  4170. return;
  4171. }
  4172. }
  4173. resetCursor(this.interactiveCanvas);
  4174. if (!event[KEYS.CTRL_OR_CMD] && !this.state.viewModeEnabled) {
  4175. const hitElement = this.getElementAtPosition(sceneX, sceneY);
  4176. if (isIframeLikeElement(hitElement)) {
  4177. this.setState({
  4178. activeEmbeddable: { element: hitElement, state: "active" },
  4179. });
  4180. return;
  4181. }
  4182. const container = getTextBindableContainerAtPosition(
  4183. this.scene.getNonDeletedElements(),
  4184. this.state,
  4185. sceneX,
  4186. sceneY,
  4187. );
  4188. if (container) {
  4189. if (
  4190. hasBoundTextElement(container) ||
  4191. !isTransparent(container.backgroundColor) ||
  4192. isHittingElementNotConsideringBoundingBox(
  4193. container,
  4194. this.state,
  4195. this.frameNameBoundsCache,
  4196. [sceneX, sceneY],
  4197. )
  4198. ) {
  4199. const midPoint = getContainerCenter(container, this.state);
  4200. sceneX = midPoint.x;
  4201. sceneY = midPoint.y;
  4202. }
  4203. }
  4204. this.startTextEditing({
  4205. sceneX,
  4206. sceneY,
  4207. insertAtParentCenter: !event.altKey,
  4208. container,
  4209. });
  4210. }
  4211. };
  4212. private getElementLinkAtPosition = (
  4213. scenePointer: Readonly<{ x: number; y: number }>,
  4214. hitElement: NonDeletedExcalidrawElement | null,
  4215. ): ExcalidrawElement | undefined => {
  4216. // Reversing so we traverse the elements in decreasing order
  4217. // of z-index
  4218. const elements = this.scene.getNonDeletedElements().slice().reverse();
  4219. let hitElementIndex = Infinity;
  4220. return elements.find((element, index) => {
  4221. if (hitElement && element.id === hitElement.id) {
  4222. hitElementIndex = index;
  4223. }
  4224. return (
  4225. element.link &&
  4226. index <= hitElementIndex &&
  4227. isPointHittingLink(
  4228. element,
  4229. this.state,
  4230. [scenePointer.x, scenePointer.y],
  4231. this.device.editor.isMobile,
  4232. )
  4233. );
  4234. });
  4235. };
  4236. private redirectToLink = (
  4237. event: React.PointerEvent<HTMLCanvasElement>,
  4238. isTouchScreen: boolean,
  4239. ) => {
  4240. const draggedDistance = distance2d(
  4241. this.lastPointerDownEvent!.clientX,
  4242. this.lastPointerDownEvent!.clientY,
  4243. this.lastPointerUpEvent!.clientX,
  4244. this.lastPointerUpEvent!.clientY,
  4245. );
  4246. if (
  4247. !this.hitLinkElement ||
  4248. // For touch screen allow dragging threshold else strict check
  4249. (isTouchScreen && draggedDistance > DRAGGING_THRESHOLD) ||
  4250. (!isTouchScreen && draggedDistance !== 0)
  4251. ) {
  4252. return;
  4253. }
  4254. const lastPointerDownCoords = viewportCoordsToSceneCoords(
  4255. this.lastPointerDownEvent!,
  4256. this.state,
  4257. );
  4258. const lastPointerDownHittingLinkIcon = isPointHittingLink(
  4259. this.hitLinkElement,
  4260. this.state,
  4261. [lastPointerDownCoords.x, lastPointerDownCoords.y],
  4262. this.device.editor.isMobile,
  4263. );
  4264. const lastPointerUpCoords = viewportCoordsToSceneCoords(
  4265. this.lastPointerUpEvent!,
  4266. this.state,
  4267. );
  4268. const lastPointerUpHittingLinkIcon = isPointHittingLink(
  4269. this.hitLinkElement,
  4270. this.state,
  4271. [lastPointerUpCoords.x, lastPointerUpCoords.y],
  4272. this.device.editor.isMobile,
  4273. );
  4274. if (lastPointerDownHittingLinkIcon && lastPointerUpHittingLinkIcon) {
  4275. let url = this.hitLinkElement.link;
  4276. if (url) {
  4277. url = normalizeLink(url);
  4278. let customEvent;
  4279. if (this.props.onLinkOpen) {
  4280. customEvent = wrapEvent(EVENT.EXCALIDRAW_LINK, event.nativeEvent);
  4281. this.props.onLinkOpen(
  4282. {
  4283. ...this.hitLinkElement,
  4284. link: url,
  4285. },
  4286. customEvent,
  4287. );
  4288. }
  4289. if (!customEvent?.defaultPrevented) {
  4290. const target = isLocalLink(url) ? "_self" : "_blank";
  4291. const newWindow = window.open(undefined, target);
  4292. // https://mathiasbynens.github.io/rel-noopener/
  4293. if (newWindow) {
  4294. newWindow.opener = null;
  4295. newWindow.location = url;
  4296. }
  4297. }
  4298. }
  4299. }
  4300. };
  4301. private getTopLayerFrameAtSceneCoords = (sceneCoords: {
  4302. x: number;
  4303. y: number;
  4304. }) => {
  4305. const frames = this.scene
  4306. .getNonDeletedFramesLikes()
  4307. .filter((frame): frame is ExcalidrawFrameLikeElement =>
  4308. isCursorInFrame(sceneCoords, frame),
  4309. );
  4310. return frames.length ? frames[frames.length - 1] : null;
  4311. };
  4312. private handleCanvasPointerMove = (
  4313. event: React.PointerEvent<HTMLCanvasElement>,
  4314. ) => {
  4315. this.savePointer(event.clientX, event.clientY, this.state.cursorButton);
  4316. this.lastPointerMoveEvent = event.nativeEvent;
  4317. if (gesture.pointers.has(event.pointerId)) {
  4318. gesture.pointers.set(event.pointerId, {
  4319. x: event.clientX,
  4320. y: event.clientY,
  4321. });
  4322. }
  4323. const initialScale = gesture.initialScale;
  4324. if (
  4325. gesture.pointers.size === 2 &&
  4326. gesture.lastCenter &&
  4327. initialScale &&
  4328. gesture.initialDistance
  4329. ) {
  4330. const center = getCenter(gesture.pointers);
  4331. const deltaX = center.x - gesture.lastCenter.x;
  4332. const deltaY = center.y - gesture.lastCenter.y;
  4333. gesture.lastCenter = center;
  4334. const distance = getDistance(Array.from(gesture.pointers.values()));
  4335. const scaleFactor =
  4336. this.state.activeTool.type === "freedraw" && this.state.penMode
  4337. ? 1
  4338. : distance / gesture.initialDistance;
  4339. const nextZoom = scaleFactor
  4340. ? getNormalizedZoom(initialScale * scaleFactor)
  4341. : this.state.zoom.value;
  4342. this.setState((state) => {
  4343. const zoomState = getStateForZoom(
  4344. {
  4345. viewportX: center.x,
  4346. viewportY: center.y,
  4347. nextZoom,
  4348. },
  4349. state,
  4350. );
  4351. this.translateCanvas({
  4352. zoom: zoomState.zoom,
  4353. scrollX: zoomState.scrollX + deltaX / nextZoom,
  4354. scrollY: zoomState.scrollY + deltaY / nextZoom,
  4355. shouldCacheIgnoreZoom: true,
  4356. });
  4357. });
  4358. this.resetShouldCacheIgnoreZoomDebounced();
  4359. } else {
  4360. gesture.lastCenter =
  4361. gesture.initialDistance =
  4362. gesture.initialScale =
  4363. null;
  4364. }
  4365. if (
  4366. isHoldingSpace ||
  4367. isPanning ||
  4368. isDraggingScrollBar ||
  4369. isHandToolActive(this.state)
  4370. ) {
  4371. return;
  4372. }
  4373. const isPointerOverScrollBars = isOverScrollBars(
  4374. currentScrollBars,
  4375. event.clientX - this.state.offsetLeft,
  4376. event.clientY - this.state.offsetTop,
  4377. );
  4378. const isOverScrollBar = isPointerOverScrollBars.isOverEither;
  4379. if (!this.state.draggingElement && !this.state.multiElement) {
  4380. if (isOverScrollBar) {
  4381. resetCursor(this.interactiveCanvas);
  4382. } else {
  4383. setCursorForShape(this.interactiveCanvas, this.state);
  4384. }
  4385. }
  4386. const scenePointer = viewportCoordsToSceneCoords(event, this.state);
  4387. const { x: scenePointerX, y: scenePointerY } = scenePointer;
  4388. if (
  4389. !this.state.draggingElement &&
  4390. isActiveToolNonLinearSnappable(this.state.activeTool.type)
  4391. ) {
  4392. const { originOffset, snapLines } = getSnapLinesAtPointer(
  4393. this.scene.getNonDeletedElements(),
  4394. this.state,
  4395. {
  4396. x: scenePointerX,
  4397. y: scenePointerY,
  4398. },
  4399. event,
  4400. );
  4401. this.setState((prevState) => {
  4402. const nextSnapLines = updateStable(prevState.snapLines, snapLines);
  4403. const nextOriginOffset = prevState.originSnapOffset
  4404. ? updateStable(prevState.originSnapOffset, originOffset)
  4405. : originOffset;
  4406. if (
  4407. prevState.snapLines === nextSnapLines &&
  4408. prevState.originSnapOffset === nextOriginOffset
  4409. ) {
  4410. return null;
  4411. }
  4412. return {
  4413. snapLines: nextSnapLines,
  4414. originSnapOffset: nextOriginOffset,
  4415. };
  4416. });
  4417. } else if (!this.state.draggingElement) {
  4418. this.setState((prevState) => {
  4419. if (prevState.snapLines.length) {
  4420. return {
  4421. snapLines: [],
  4422. };
  4423. }
  4424. return null;
  4425. });
  4426. }
  4427. if (
  4428. this.state.editingLinearElement &&
  4429. !this.state.editingLinearElement.isDragging
  4430. ) {
  4431. const editingLinearElement = LinearElementEditor.handlePointerMove(
  4432. event,
  4433. scenePointerX,
  4434. scenePointerY,
  4435. this.state,
  4436. );
  4437. if (
  4438. editingLinearElement &&
  4439. editingLinearElement !== this.state.editingLinearElement
  4440. ) {
  4441. // Since we are reading from previous state which is not possible with
  4442. // automatic batching in React 18 hence using flush sync to synchronously
  4443. // update the state. Check https://github.com/excalidraw/excalidraw/pull/5508 for more details.
  4444. flushSync(() => {
  4445. this.setState({
  4446. editingLinearElement,
  4447. });
  4448. });
  4449. }
  4450. if (editingLinearElement?.lastUncommittedPoint != null) {
  4451. this.maybeSuggestBindingAtCursor(scenePointer);
  4452. } else {
  4453. // causes stack overflow if not sync
  4454. flushSync(() => {
  4455. this.setState({ suggestedBindings: [] });
  4456. });
  4457. }
  4458. }
  4459. if (isBindingElementType(this.state.activeTool.type)) {
  4460. // Hovering with a selected tool or creating new linear element via click
  4461. // and point
  4462. const { draggingElement } = this.state;
  4463. if (isBindingElement(draggingElement, false)) {
  4464. this.maybeSuggestBindingsForLinearElementAtCoords(
  4465. draggingElement,
  4466. [scenePointer],
  4467. this.state.startBoundElement,
  4468. );
  4469. } else {
  4470. this.maybeSuggestBindingAtCursor(scenePointer);
  4471. }
  4472. }
  4473. if (this.state.multiElement) {
  4474. const { multiElement } = this.state;
  4475. const { x: rx, y: ry } = multiElement;
  4476. const { points, lastCommittedPoint } = multiElement;
  4477. const lastPoint = points[points.length - 1];
  4478. setCursorForShape(this.interactiveCanvas, this.state);
  4479. if (lastPoint === lastCommittedPoint) {
  4480. // if we haven't yet created a temp point and we're beyond commit-zone
  4481. // threshold, add a point
  4482. if (
  4483. distance2d(
  4484. scenePointerX - rx,
  4485. scenePointerY - ry,
  4486. lastPoint[0],
  4487. lastPoint[1],
  4488. ) >= LINE_CONFIRM_THRESHOLD
  4489. ) {
  4490. mutateElement(multiElement, {
  4491. points: [...points, [scenePointerX - rx, scenePointerY - ry]],
  4492. });
  4493. } else {
  4494. setCursor(this.interactiveCanvas, CURSOR_TYPE.POINTER);
  4495. // in this branch, we're inside the commit zone, and no uncommitted
  4496. // point exists. Thus do nothing (don't add/remove points).
  4497. }
  4498. } else if (
  4499. points.length > 2 &&
  4500. lastCommittedPoint &&
  4501. distance2d(
  4502. scenePointerX - rx,
  4503. scenePointerY - ry,
  4504. lastCommittedPoint[0],
  4505. lastCommittedPoint[1],
  4506. ) < LINE_CONFIRM_THRESHOLD
  4507. ) {
  4508. setCursor(this.interactiveCanvas, CURSOR_TYPE.POINTER);
  4509. mutateElement(multiElement, {
  4510. points: points.slice(0, -1),
  4511. });
  4512. } else {
  4513. const [gridX, gridY] = getGridPoint(
  4514. scenePointerX,
  4515. scenePointerY,
  4516. event[KEYS.CTRL_OR_CMD] ? null : this.state.gridSize,
  4517. );
  4518. const [lastCommittedX, lastCommittedY] =
  4519. multiElement?.lastCommittedPoint ?? [0, 0];
  4520. let dxFromLastCommitted = gridX - rx - lastCommittedX;
  4521. let dyFromLastCommitted = gridY - ry - lastCommittedY;
  4522. if (shouldRotateWithDiscreteAngle(event)) {
  4523. ({ width: dxFromLastCommitted, height: dyFromLastCommitted } =
  4524. getLockedLinearCursorAlignSize(
  4525. // actual coordinate of the last committed point
  4526. lastCommittedX + rx,
  4527. lastCommittedY + ry,
  4528. // cursor-grid coordinate
  4529. gridX,
  4530. gridY,
  4531. ));
  4532. }
  4533. if (isPathALoop(points, this.state.zoom.value)) {
  4534. setCursor(this.interactiveCanvas, CURSOR_TYPE.POINTER);
  4535. }
  4536. // update last uncommitted point
  4537. mutateElement(multiElement, {
  4538. points: [
  4539. ...points.slice(0, -1),
  4540. [
  4541. lastCommittedX + dxFromLastCommitted,
  4542. lastCommittedY + dyFromLastCommitted,
  4543. ],
  4544. ],
  4545. });
  4546. }
  4547. return;
  4548. }
  4549. const hasDeselectedButton = Boolean(event.buttons);
  4550. if (
  4551. hasDeselectedButton ||
  4552. (this.state.activeTool.type !== "selection" &&
  4553. this.state.activeTool.type !== "text" &&
  4554. this.state.activeTool.type !== "eraser")
  4555. ) {
  4556. return;
  4557. }
  4558. const elements = this.scene.getNonDeletedElements();
  4559. const selectedElements = this.scene.getSelectedElements(this.state);
  4560. if (
  4561. selectedElements.length === 1 &&
  4562. !isOverScrollBar &&
  4563. !this.state.editingLinearElement
  4564. ) {
  4565. const elementWithTransformHandleType = getElementWithTransformHandleType(
  4566. elements,
  4567. this.state,
  4568. scenePointerX,
  4569. scenePointerY,
  4570. this.state.zoom,
  4571. event.pointerType,
  4572. );
  4573. if (
  4574. elementWithTransformHandleType &&
  4575. elementWithTransformHandleType.transformHandleType
  4576. ) {
  4577. setCursor(
  4578. this.interactiveCanvas,
  4579. getCursorForResizingElement(elementWithTransformHandleType),
  4580. );
  4581. return;
  4582. }
  4583. } else if (selectedElements.length > 1 && !isOverScrollBar) {
  4584. const transformHandleType = getTransformHandleTypeFromCoords(
  4585. getCommonBounds(selectedElements),
  4586. scenePointerX,
  4587. scenePointerY,
  4588. this.state.zoom,
  4589. event.pointerType,
  4590. );
  4591. if (transformHandleType) {
  4592. setCursor(
  4593. this.interactiveCanvas,
  4594. getCursorForResizingElement({
  4595. transformHandleType,
  4596. }),
  4597. );
  4598. return;
  4599. }
  4600. }
  4601. const hitElement = this.getElementAtPosition(
  4602. scenePointer.x,
  4603. scenePointer.y,
  4604. );
  4605. this.hitLinkElement = this.getElementLinkAtPosition(
  4606. scenePointer,
  4607. hitElement,
  4608. );
  4609. if (isEraserActive(this.state)) {
  4610. return;
  4611. }
  4612. if (
  4613. this.hitLinkElement &&
  4614. !this.state.selectedElementIds[this.hitLinkElement.id]
  4615. ) {
  4616. setCursor(this.interactiveCanvas, CURSOR_TYPE.POINTER);
  4617. showHyperlinkTooltip(this.hitLinkElement, this.state);
  4618. } else {
  4619. hideHyperlinkToolip();
  4620. if (
  4621. hitElement &&
  4622. (hitElement.link || isEmbeddableElement(hitElement)) &&
  4623. this.state.selectedElementIds[hitElement.id] &&
  4624. !this.state.contextMenu &&
  4625. !this.state.showHyperlinkPopup
  4626. ) {
  4627. this.setState({ showHyperlinkPopup: "info" });
  4628. } else if (this.state.activeTool.type === "text") {
  4629. setCursor(
  4630. this.interactiveCanvas,
  4631. isTextElement(hitElement) ? CURSOR_TYPE.TEXT : CURSOR_TYPE.CROSSHAIR,
  4632. );
  4633. } else if (this.state.viewModeEnabled) {
  4634. setCursor(this.interactiveCanvas, CURSOR_TYPE.GRAB);
  4635. } else if (isOverScrollBar) {
  4636. setCursor(this.interactiveCanvas, CURSOR_TYPE.AUTO);
  4637. } else if (this.state.selectedLinearElement) {
  4638. this.handleHoverSelectedLinearElement(
  4639. this.state.selectedLinearElement,
  4640. scenePointerX,
  4641. scenePointerY,
  4642. );
  4643. } else if (
  4644. // if using cmd/ctrl, we're not dragging
  4645. !event[KEYS.CTRL_OR_CMD]
  4646. ) {
  4647. if (
  4648. (hitElement ||
  4649. this.isHittingCommonBoundingBoxOfSelectedElements(
  4650. scenePointer,
  4651. selectedElements,
  4652. )) &&
  4653. !hitElement?.locked
  4654. ) {
  4655. if (
  4656. hitElement &&
  4657. isIframeLikeElement(hitElement) &&
  4658. this.isIframeLikeElementCenter(
  4659. hitElement,
  4660. event,
  4661. scenePointerX,
  4662. scenePointerY,
  4663. )
  4664. ) {
  4665. setCursor(this.interactiveCanvas, CURSOR_TYPE.POINTER);
  4666. this.setState({
  4667. activeEmbeddable: { element: hitElement, state: "hover" },
  4668. });
  4669. } else {
  4670. setCursor(this.interactiveCanvas, CURSOR_TYPE.MOVE);
  4671. if (this.state.activeEmbeddable?.state === "hover") {
  4672. this.setState({ activeEmbeddable: null });
  4673. }
  4674. }
  4675. }
  4676. } else {
  4677. setCursor(this.interactiveCanvas, CURSOR_TYPE.AUTO);
  4678. }
  4679. }
  4680. };
  4681. private handleEraser = (
  4682. event: PointerEvent,
  4683. pointerDownState: PointerDownState,
  4684. scenePointer: { x: number; y: number },
  4685. ) => {
  4686. this.eraserTrail.addPointToPath(scenePointer.x, scenePointer.y);
  4687. let didChange = false;
  4688. const processElements = (elements: ExcalidrawElement[]) => {
  4689. for (const element of elements) {
  4690. if (element.locked) {
  4691. return;
  4692. }
  4693. if (event.altKey) {
  4694. if (this.elementsPendingErasure.delete(element.id)) {
  4695. didChange = true;
  4696. }
  4697. } else if (!this.elementsPendingErasure.has(element.id)) {
  4698. didChange = true;
  4699. this.elementsPendingErasure.add(element.id);
  4700. }
  4701. }
  4702. };
  4703. const distance = distance2d(
  4704. pointerDownState.lastCoords.x,
  4705. pointerDownState.lastCoords.y,
  4706. scenePointer.x,
  4707. scenePointer.y,
  4708. );
  4709. const threshold = 10 / this.state.zoom.value;
  4710. const point = { ...pointerDownState.lastCoords };
  4711. let samplingInterval = 0;
  4712. while (samplingInterval <= distance) {
  4713. const hitElements = this.getElementsAtPosition(point.x, point.y);
  4714. processElements(hitElements);
  4715. // Exit since we reached current point
  4716. if (samplingInterval === distance) {
  4717. break;
  4718. }
  4719. // Calculate next point in the line at a distance of sampling interval
  4720. samplingInterval = Math.min(samplingInterval + threshold, distance);
  4721. const distanceRatio = samplingInterval / distance;
  4722. const nextX =
  4723. (1 - distanceRatio) * point.x + distanceRatio * scenePointer.x;
  4724. const nextY =
  4725. (1 - distanceRatio) * point.y + distanceRatio * scenePointer.y;
  4726. point.x = nextX;
  4727. point.y = nextY;
  4728. }
  4729. pointerDownState.lastCoords.x = scenePointer.x;
  4730. pointerDownState.lastCoords.y = scenePointer.y;
  4731. if (didChange) {
  4732. for (const element of this.scene.getNonDeletedElements()) {
  4733. if (
  4734. isBoundToContainer(element) &&
  4735. (this.elementsPendingErasure.has(element.id) ||
  4736. this.elementsPendingErasure.has(element.containerId))
  4737. ) {
  4738. if (event.altKey) {
  4739. this.elementsPendingErasure.delete(element.id);
  4740. this.elementsPendingErasure.delete(element.containerId);
  4741. } else {
  4742. this.elementsPendingErasure.add(element.id);
  4743. this.elementsPendingErasure.add(element.containerId);
  4744. }
  4745. }
  4746. }
  4747. this.elementsPendingErasure = new Set(this.elementsPendingErasure);
  4748. this.onSceneUpdated();
  4749. }
  4750. };
  4751. // set touch moving for mobile context menu
  4752. private handleTouchMove = (event: React.TouchEvent<HTMLCanvasElement>) => {
  4753. invalidateContextMenu = true;
  4754. };
  4755. handleHoverSelectedLinearElement(
  4756. linearElementEditor: LinearElementEditor,
  4757. scenePointerX: number,
  4758. scenePointerY: number,
  4759. ) {
  4760. const element = LinearElementEditor.getElement(
  4761. linearElementEditor.elementId,
  4762. );
  4763. const boundTextElement = getBoundTextElement(element);
  4764. if (!element) {
  4765. return;
  4766. }
  4767. if (this.state.selectedLinearElement) {
  4768. let hoverPointIndex = -1;
  4769. let segmentMidPointHoveredCoords = null;
  4770. if (
  4771. isHittingElementNotConsideringBoundingBox(
  4772. element,
  4773. this.state,
  4774. this.frameNameBoundsCache,
  4775. [scenePointerX, scenePointerY],
  4776. )
  4777. ) {
  4778. hoverPointIndex = LinearElementEditor.getPointIndexUnderCursor(
  4779. element,
  4780. this.state.zoom,
  4781. scenePointerX,
  4782. scenePointerY,
  4783. );
  4784. segmentMidPointHoveredCoords =
  4785. LinearElementEditor.getSegmentMidpointHitCoords(
  4786. linearElementEditor,
  4787. { x: scenePointerX, y: scenePointerY },
  4788. this.state,
  4789. );
  4790. if (hoverPointIndex >= 0 || segmentMidPointHoveredCoords) {
  4791. setCursor(this.interactiveCanvas, CURSOR_TYPE.POINTER);
  4792. } else {
  4793. setCursor(this.interactiveCanvas, CURSOR_TYPE.MOVE);
  4794. }
  4795. } else if (
  4796. shouldShowBoundingBox([element], this.state) &&
  4797. isHittingElementBoundingBoxWithoutHittingElement(
  4798. element,
  4799. this.state,
  4800. this.frameNameBoundsCache,
  4801. scenePointerX,
  4802. scenePointerY,
  4803. )
  4804. ) {
  4805. setCursor(this.interactiveCanvas, CURSOR_TYPE.MOVE);
  4806. } else if (
  4807. boundTextElement &&
  4808. hitTest(
  4809. boundTextElement,
  4810. this.state,
  4811. this.frameNameBoundsCache,
  4812. scenePointerX,
  4813. scenePointerY,
  4814. )
  4815. ) {
  4816. setCursor(this.interactiveCanvas, CURSOR_TYPE.MOVE);
  4817. }
  4818. if (
  4819. this.state.selectedLinearElement.hoverPointIndex !== hoverPointIndex
  4820. ) {
  4821. this.setState({
  4822. selectedLinearElement: {
  4823. ...this.state.selectedLinearElement,
  4824. hoverPointIndex,
  4825. },
  4826. });
  4827. }
  4828. if (
  4829. !LinearElementEditor.arePointsEqual(
  4830. this.state.selectedLinearElement.segmentMidPointHoveredCoords,
  4831. segmentMidPointHoveredCoords,
  4832. )
  4833. ) {
  4834. this.setState({
  4835. selectedLinearElement: {
  4836. ...this.state.selectedLinearElement,
  4837. segmentMidPointHoveredCoords,
  4838. },
  4839. });
  4840. }
  4841. } else {
  4842. setCursor(this.interactiveCanvas, CURSOR_TYPE.AUTO);
  4843. }
  4844. }
  4845. private handleCanvasPointerDown = (
  4846. event: React.PointerEvent<HTMLElement>,
  4847. ) => {
  4848. this.maybeCleanupAfterMissingPointerUp(event.nativeEvent);
  4849. this.maybeUnfollowRemoteUser();
  4850. // since contextMenu options are potentially evaluated on each render,
  4851. // and an contextMenu action may depend on selection state, we must
  4852. // close the contextMenu before we update the selection on pointerDown
  4853. // (e.g. resetting selection)
  4854. if (this.state.contextMenu) {
  4855. this.setState({ contextMenu: null });
  4856. }
  4857. if (this.state.snapLines) {
  4858. this.setAppState({ snapLines: [] });
  4859. }
  4860. this.updateGestureOnPointerDown(event);
  4861. // if dragging element is freedraw and another pointerdown event occurs
  4862. // a second finger is on the screen
  4863. // discard the freedraw element if it is very short because it is likely
  4864. // just a spike, otherwise finalize the freedraw element when the second
  4865. // finger is lifted
  4866. if (
  4867. event.pointerType === "touch" &&
  4868. this.state.draggingElement &&
  4869. this.state.draggingElement.type === "freedraw"
  4870. ) {
  4871. const element = this.state.draggingElement as ExcalidrawFreeDrawElement;
  4872. this.updateScene({
  4873. ...(element.points.length < 10
  4874. ? {
  4875. elements: this.scene
  4876. .getElementsIncludingDeleted()
  4877. .filter((el) => el.id !== element.id),
  4878. }
  4879. : {}),
  4880. appState: {
  4881. draggingElement: null,
  4882. editingElement: null,
  4883. startBoundElement: null,
  4884. suggestedBindings: [],
  4885. selectedElementIds: makeNextSelectedElementIds(
  4886. Object.keys(this.state.selectedElementIds)
  4887. .filter((key) => key !== element.id)
  4888. .reduce((obj: { [id: string]: true }, key) => {
  4889. obj[key] = this.state.selectedElementIds[key];
  4890. return obj;
  4891. }, {}),
  4892. this.state,
  4893. ),
  4894. },
  4895. });
  4896. return;
  4897. }
  4898. // remove any active selection when we start to interact with canvas
  4899. // (mainly, we care about removing selection outside the component which
  4900. // would prevent our copy handling otherwise)
  4901. const selection = document.getSelection();
  4902. if (selection?.anchorNode) {
  4903. selection.removeAllRanges();
  4904. }
  4905. this.maybeOpenContextMenuAfterPointerDownOnTouchDevices(event);
  4906. //fires only once, if pen is detected, penMode is enabled
  4907. //the user can disable this by toggling the penMode button
  4908. if (!this.state.penDetected && event.pointerType === "pen") {
  4909. this.setState((prevState) => {
  4910. return {
  4911. penMode: true,
  4912. penDetected: true,
  4913. };
  4914. });
  4915. }
  4916. if (
  4917. !this.device.isTouchScreen &&
  4918. ["pen", "touch"].includes(event.pointerType)
  4919. ) {
  4920. this.device = updateObject(this.device, { isTouchScreen: true });
  4921. }
  4922. if (isPanning) {
  4923. return;
  4924. }
  4925. this.lastPointerDownEvent = event;
  4926. // we must exit before we set `cursorButton` state and `savePointer`
  4927. // else it will send pointer state & laser pointer events in collab when
  4928. // panning
  4929. if (this.handleCanvasPanUsingWheelOrSpaceDrag(event)) {
  4930. return;
  4931. }
  4932. this.setState({
  4933. lastPointerDownWith: event.pointerType,
  4934. cursorButton: "down",
  4935. });
  4936. this.savePointer(event.clientX, event.clientY, "down");
  4937. if (
  4938. event.button === POINTER_BUTTON.ERASER &&
  4939. this.state.activeTool.type !== TOOL_TYPE.eraser
  4940. ) {
  4941. this.setState(
  4942. {
  4943. activeTool: updateActiveTool(this.state, {
  4944. type: TOOL_TYPE.eraser,
  4945. lastActiveToolBeforeEraser: this.state.activeTool,
  4946. }),
  4947. },
  4948. () => {
  4949. this.handleCanvasPointerDown(event);
  4950. const onPointerUp = () => {
  4951. unsubPointerUp();
  4952. unsubCleanup?.();
  4953. if (isEraserActive(this.state)) {
  4954. this.setState({
  4955. activeTool: updateActiveTool(this.state, {
  4956. ...(this.state.activeTool.lastActiveTool || {
  4957. type: TOOL_TYPE.selection,
  4958. }),
  4959. lastActiveToolBeforeEraser: null,
  4960. }),
  4961. });
  4962. }
  4963. };
  4964. const unsubPointerUp = addEventListener(
  4965. window,
  4966. EVENT.POINTER_UP,
  4967. onPointerUp,
  4968. {
  4969. once: true,
  4970. },
  4971. );
  4972. let unsubCleanup: UnsubscribeCallback | undefined;
  4973. // subscribe inside rAF lest it'd be triggered on the same pointerdown
  4974. // if we start erasing while coming from blurred document since
  4975. // we cleanup pointer events on focus
  4976. requestAnimationFrame(() => {
  4977. unsubCleanup =
  4978. this.missingPointerEventCleanupEmitter.once(onPointerUp);
  4979. });
  4980. },
  4981. );
  4982. return;
  4983. }
  4984. // only handle left mouse button or touch
  4985. if (
  4986. event.button !== POINTER_BUTTON.MAIN &&
  4987. event.button !== POINTER_BUTTON.TOUCH &&
  4988. event.button !== POINTER_BUTTON.ERASER
  4989. ) {
  4990. return;
  4991. }
  4992. // don't select while panning
  4993. if (gesture.pointers.size > 1) {
  4994. return;
  4995. }
  4996. // State for the duration of a pointer interaction, which starts with a
  4997. // pointerDown event, ends with a pointerUp event (or another pointerDown)
  4998. const pointerDownState = this.initialPointerDownState(event);
  4999. this.setState({
  5000. selectedElementsAreBeingDragged: false,
  5001. });
  5002. if (this.handleDraggingScrollBar(event, pointerDownState)) {
  5003. return;
  5004. }
  5005. this.clearSelectionIfNotUsingSelection();
  5006. this.updateBindingEnabledOnPointerMove(event);
  5007. if (this.handleSelectionOnPointerDown(event, pointerDownState)) {
  5008. return;
  5009. }
  5010. const allowOnPointerDown =
  5011. !this.state.penMode ||
  5012. event.pointerType !== "touch" ||
  5013. this.state.activeTool.type === "selection" ||
  5014. this.state.activeTool.type === "text" ||
  5015. this.state.activeTool.type === "image";
  5016. if (!allowOnPointerDown) {
  5017. return;
  5018. }
  5019. if (this.state.activeTool.type === "text") {
  5020. this.handleTextOnPointerDown(event, pointerDownState);
  5021. return;
  5022. } else if (
  5023. this.state.activeTool.type === "arrow" ||
  5024. this.state.activeTool.type === "line"
  5025. ) {
  5026. this.handleLinearElementOnPointerDown(
  5027. event,
  5028. this.state.activeTool.type,
  5029. pointerDownState,
  5030. );
  5031. } else if (this.state.activeTool.type === "image") {
  5032. // reset image preview on pointerdown
  5033. setCursor(this.interactiveCanvas, CURSOR_TYPE.CROSSHAIR);
  5034. // retrieve the latest element as the state may be stale
  5035. const pendingImageElement =
  5036. this.state.pendingImageElementId &&
  5037. this.scene.getElement(this.state.pendingImageElementId);
  5038. if (!pendingImageElement) {
  5039. return;
  5040. }
  5041. this.setState({
  5042. draggingElement: pendingImageElement,
  5043. editingElement: pendingImageElement,
  5044. pendingImageElementId: null,
  5045. multiElement: null,
  5046. });
  5047. const { x, y } = viewportCoordsToSceneCoords(event, this.state);
  5048. const frame = this.getTopLayerFrameAtSceneCoords({ x, y });
  5049. mutateElement(pendingImageElement, {
  5050. x,
  5051. y,
  5052. frameId: frame ? frame.id : null,
  5053. });
  5054. } else if (this.state.activeTool.type === "freedraw") {
  5055. this.handleFreeDrawElementOnPointerDown(
  5056. event,
  5057. this.state.activeTool.type,
  5058. pointerDownState,
  5059. );
  5060. } else if (this.state.activeTool.type === "custom") {
  5061. setCursorForShape(this.interactiveCanvas, this.state);
  5062. } else if (
  5063. this.state.activeTool.type === TOOL_TYPE.frame ||
  5064. this.state.activeTool.type === TOOL_TYPE.magicframe
  5065. ) {
  5066. this.createFrameElementOnPointerDown(
  5067. pointerDownState,
  5068. this.state.activeTool.type,
  5069. );
  5070. } else if (this.state.activeTool.type === "laser") {
  5071. this.laserTrails.startPath(
  5072. pointerDownState.lastCoords.x,
  5073. pointerDownState.lastCoords.y,
  5074. );
  5075. } else if (
  5076. this.state.activeTool.type !== "eraser" &&
  5077. this.state.activeTool.type !== "hand"
  5078. ) {
  5079. this.createGenericElementOnPointerDown(
  5080. this.state.activeTool.type,
  5081. pointerDownState,
  5082. );
  5083. }
  5084. this.props?.onPointerDown?.(this.state.activeTool, pointerDownState);
  5085. this.onPointerDownEmitter.trigger(
  5086. this.state.activeTool,
  5087. pointerDownState,
  5088. event,
  5089. );
  5090. if (this.state.activeTool.type === "eraser") {
  5091. this.eraserTrail.startPath(
  5092. pointerDownState.lastCoords.x,
  5093. pointerDownState.lastCoords.y,
  5094. );
  5095. }
  5096. const onPointerMove =
  5097. this.onPointerMoveFromPointerDownHandler(pointerDownState);
  5098. const onPointerUp =
  5099. this.onPointerUpFromPointerDownHandler(pointerDownState);
  5100. const onKeyDown = this.onKeyDownFromPointerDownHandler(pointerDownState);
  5101. const onKeyUp = this.onKeyUpFromPointerDownHandler(pointerDownState);
  5102. this.missingPointerEventCleanupEmitter.once((_event) =>
  5103. onPointerUp(_event || event.nativeEvent),
  5104. );
  5105. if (!this.state.viewModeEnabled || this.state.activeTool.type === "laser") {
  5106. window.addEventListener(EVENT.POINTER_MOVE, onPointerMove);
  5107. window.addEventListener(EVENT.POINTER_UP, onPointerUp);
  5108. window.addEventListener(EVENT.KEYDOWN, onKeyDown);
  5109. window.addEventListener(EVENT.KEYUP, onKeyUp);
  5110. pointerDownState.eventListeners.onMove = onPointerMove;
  5111. pointerDownState.eventListeners.onUp = onPointerUp;
  5112. pointerDownState.eventListeners.onKeyUp = onKeyUp;
  5113. pointerDownState.eventListeners.onKeyDown = onKeyDown;
  5114. }
  5115. };
  5116. private handleCanvasPointerUp = (
  5117. event: React.PointerEvent<HTMLCanvasElement>,
  5118. ) => {
  5119. this.removePointer(event);
  5120. this.lastPointerUpEvent = event;
  5121. const scenePointer = viewportCoordsToSceneCoords(
  5122. { clientX: event.clientX, clientY: event.clientY },
  5123. this.state,
  5124. );
  5125. const clicklength =
  5126. event.timeStamp - (this.lastPointerDownEvent?.timeStamp ?? 0);
  5127. if (this.device.editor.isMobile && clicklength < 300) {
  5128. const hitElement = this.getElementAtPosition(
  5129. scenePointer.x,
  5130. scenePointer.y,
  5131. );
  5132. if (
  5133. isIframeLikeElement(hitElement) &&
  5134. this.isIframeLikeElementCenter(
  5135. hitElement,
  5136. event,
  5137. scenePointer.x,
  5138. scenePointer.y,
  5139. )
  5140. ) {
  5141. this.handleEmbeddableCenterClick(hitElement);
  5142. return;
  5143. }
  5144. }
  5145. if (this.device.isTouchScreen) {
  5146. const hitElement = this.getElementAtPosition(
  5147. scenePointer.x,
  5148. scenePointer.y,
  5149. );
  5150. this.hitLinkElement = this.getElementLinkAtPosition(
  5151. scenePointer,
  5152. hitElement,
  5153. );
  5154. }
  5155. if (
  5156. this.hitLinkElement &&
  5157. !this.state.selectedElementIds[this.hitLinkElement.id]
  5158. ) {
  5159. if (
  5160. clicklength < 300 &&
  5161. isIframeLikeElement(this.hitLinkElement) &&
  5162. !isPointHittingLinkIcon(this.hitLinkElement, this.state, [
  5163. scenePointer.x,
  5164. scenePointer.y,
  5165. ])
  5166. ) {
  5167. this.handleEmbeddableCenterClick(this.hitLinkElement);
  5168. } else {
  5169. this.redirectToLink(event, this.device.isTouchScreen);
  5170. }
  5171. } else if (this.state.viewModeEnabled) {
  5172. this.setState({
  5173. activeEmbeddable: null,
  5174. selectedElementIds: {},
  5175. });
  5176. }
  5177. };
  5178. private maybeOpenContextMenuAfterPointerDownOnTouchDevices = (
  5179. event: React.PointerEvent<HTMLElement>,
  5180. ): void => {
  5181. // deal with opening context menu on touch devices
  5182. if (event.pointerType === "touch") {
  5183. invalidateContextMenu = false;
  5184. if (touchTimeout) {
  5185. // If there's already a touchTimeout, this means that there's another
  5186. // touch down and we are doing another touch, so we shouldn't open the
  5187. // context menu.
  5188. invalidateContextMenu = true;
  5189. } else {
  5190. // open the context menu with the first touch's clientX and clientY
  5191. // if the touch is not moving
  5192. touchTimeout = window.setTimeout(() => {
  5193. touchTimeout = 0;
  5194. if (!invalidateContextMenu) {
  5195. this.handleCanvasContextMenu(event);
  5196. }
  5197. }, TOUCH_CTX_MENU_TIMEOUT);
  5198. }
  5199. }
  5200. };
  5201. private resetContextMenuTimer = () => {
  5202. clearTimeout(touchTimeout);
  5203. touchTimeout = 0;
  5204. invalidateContextMenu = false;
  5205. };
  5206. /**
  5207. * pointerup may not fire in certian cases (user tabs away...), so in order
  5208. * to properly cleanup pointerdown state, we need to fire any hanging
  5209. * pointerup handlers manually
  5210. */
  5211. private maybeCleanupAfterMissingPointerUp = (event: PointerEvent | null) => {
  5212. lastPointerUp?.();
  5213. this.missingPointerEventCleanupEmitter.trigger(event).clear();
  5214. };
  5215. // Returns whether the event is a panning
  5216. private handleCanvasPanUsingWheelOrSpaceDrag = (
  5217. event: React.PointerEvent<HTMLElement>,
  5218. ): boolean => {
  5219. if (
  5220. !(
  5221. gesture.pointers.size <= 1 &&
  5222. (event.button === POINTER_BUTTON.WHEEL ||
  5223. (event.button === POINTER_BUTTON.MAIN && isHoldingSpace) ||
  5224. isHandToolActive(this.state) ||
  5225. this.state.viewModeEnabled)
  5226. ) ||
  5227. isTextElement(this.state.editingElement)
  5228. ) {
  5229. return false;
  5230. }
  5231. isPanning = true;
  5232. event.preventDefault();
  5233. let nextPastePrevented = false;
  5234. const isLinux = /Linux/.test(window.navigator.platform);
  5235. setCursor(this.interactiveCanvas, CURSOR_TYPE.GRABBING);
  5236. let { clientX: lastX, clientY: lastY } = event;
  5237. const onPointerMove = withBatchedUpdatesThrottled((event: PointerEvent) => {
  5238. const deltaX = lastX - event.clientX;
  5239. const deltaY = lastY - event.clientY;
  5240. lastX = event.clientX;
  5241. lastY = event.clientY;
  5242. /*
  5243. * Prevent paste event if we move while middle clicking on Linux.
  5244. * See issue #1383.
  5245. */
  5246. if (
  5247. isLinux &&
  5248. !nextPastePrevented &&
  5249. (Math.abs(deltaX) > 1 || Math.abs(deltaY) > 1)
  5250. ) {
  5251. nextPastePrevented = true;
  5252. /* Prevent the next paste event */
  5253. const preventNextPaste = (event: ClipboardEvent) => {
  5254. document.body.removeEventListener(EVENT.PASTE, preventNextPaste);
  5255. event.stopPropagation();
  5256. };
  5257. /*
  5258. * Reenable next paste in case of disabled middle click paste for
  5259. * any reason:
  5260. * - right click paste
  5261. * - empty clipboard
  5262. */
  5263. const enableNextPaste = () => {
  5264. setTimeout(() => {
  5265. document.body.removeEventListener(EVENT.PASTE, preventNextPaste);
  5266. window.removeEventListener(EVENT.POINTER_UP, enableNextPaste);
  5267. }, 100);
  5268. };
  5269. document.body.addEventListener(EVENT.PASTE, preventNextPaste);
  5270. window.addEventListener(EVENT.POINTER_UP, enableNextPaste);
  5271. }
  5272. this.translateCanvas({
  5273. scrollX: this.state.scrollX - deltaX / this.state.zoom.value,
  5274. scrollY: this.state.scrollY - deltaY / this.state.zoom.value,
  5275. });
  5276. });
  5277. const teardown = withBatchedUpdates(
  5278. (lastPointerUp = () => {
  5279. lastPointerUp = null;
  5280. isPanning = false;
  5281. if (!isHoldingSpace) {
  5282. if (this.state.viewModeEnabled) {
  5283. setCursor(this.interactiveCanvas, CURSOR_TYPE.GRAB);
  5284. } else {
  5285. setCursorForShape(this.interactiveCanvas, this.state);
  5286. }
  5287. }
  5288. this.setState({
  5289. cursorButton: "up",
  5290. });
  5291. this.savePointer(event.clientX, event.clientY, "up");
  5292. window.removeEventListener(EVENT.POINTER_MOVE, onPointerMove);
  5293. window.removeEventListener(EVENT.POINTER_UP, teardown);
  5294. window.removeEventListener(EVENT.BLUR, teardown);
  5295. onPointerMove.flush();
  5296. }),
  5297. );
  5298. window.addEventListener(EVENT.BLUR, teardown);
  5299. window.addEventListener(EVENT.POINTER_MOVE, onPointerMove, {
  5300. passive: true,
  5301. });
  5302. window.addEventListener(EVENT.POINTER_UP, teardown);
  5303. return true;
  5304. };
  5305. private updateGestureOnPointerDown(
  5306. event: React.PointerEvent<HTMLElement>,
  5307. ): void {
  5308. gesture.pointers.set(event.pointerId, {
  5309. x: event.clientX,
  5310. y: event.clientY,
  5311. });
  5312. if (gesture.pointers.size === 2) {
  5313. gesture.lastCenter = getCenter(gesture.pointers);
  5314. gesture.initialScale = this.state.zoom.value;
  5315. gesture.initialDistance = getDistance(
  5316. Array.from(gesture.pointers.values()),
  5317. );
  5318. }
  5319. }
  5320. private initialPointerDownState(
  5321. event: React.PointerEvent<HTMLElement>,
  5322. ): PointerDownState {
  5323. const origin = viewportCoordsToSceneCoords(event, this.state);
  5324. const selectedElements = this.scene.getSelectedElements(this.state);
  5325. const [minX, minY, maxX, maxY] = getCommonBounds(selectedElements);
  5326. return {
  5327. origin,
  5328. withCmdOrCtrl: event[KEYS.CTRL_OR_CMD],
  5329. originInGrid: tupleToCoors(
  5330. getGridPoint(
  5331. origin.x,
  5332. origin.y,
  5333. event[KEYS.CTRL_OR_CMD] ? null : this.state.gridSize,
  5334. ),
  5335. ),
  5336. scrollbars: isOverScrollBars(
  5337. currentScrollBars,
  5338. event.clientX - this.state.offsetLeft,
  5339. event.clientY - this.state.offsetTop,
  5340. ),
  5341. // we need to duplicate because we'll be updating this state
  5342. lastCoords: { ...origin },
  5343. originalElements: this.scene
  5344. .getNonDeletedElements()
  5345. .reduce((acc, element) => {
  5346. acc.set(element.id, deepCopyElement(element));
  5347. return acc;
  5348. }, new Map() as PointerDownState["originalElements"]),
  5349. resize: {
  5350. handleType: false,
  5351. isResizing: false,
  5352. offset: { x: 0, y: 0 },
  5353. arrowDirection: "origin",
  5354. center: { x: (maxX + minX) / 2, y: (maxY + minY) / 2 },
  5355. },
  5356. hit: {
  5357. element: null,
  5358. allHitElements: [],
  5359. wasAddedToSelection: false,
  5360. hasBeenDuplicated: false,
  5361. hasHitCommonBoundingBoxOfSelectedElements:
  5362. this.isHittingCommonBoundingBoxOfSelectedElements(
  5363. origin,
  5364. selectedElements,
  5365. ),
  5366. },
  5367. drag: {
  5368. hasOccurred: false,
  5369. offset: null,
  5370. },
  5371. eventListeners: {
  5372. onMove: null,
  5373. onUp: null,
  5374. onKeyUp: null,
  5375. onKeyDown: null,
  5376. },
  5377. boxSelection: {
  5378. hasOccurred: false,
  5379. },
  5380. };
  5381. }
  5382. // Returns whether the event is a dragging a scrollbar
  5383. private handleDraggingScrollBar(
  5384. event: React.PointerEvent<HTMLElement>,
  5385. pointerDownState: PointerDownState,
  5386. ): boolean {
  5387. if (
  5388. !(pointerDownState.scrollbars.isOverEither && !this.state.multiElement)
  5389. ) {
  5390. return false;
  5391. }
  5392. isDraggingScrollBar = true;
  5393. pointerDownState.lastCoords.x = event.clientX;
  5394. pointerDownState.lastCoords.y = event.clientY;
  5395. const onPointerMove = withBatchedUpdatesThrottled((event: PointerEvent) => {
  5396. const target = event.target;
  5397. if (!(target instanceof HTMLElement)) {
  5398. return;
  5399. }
  5400. this.handlePointerMoveOverScrollbars(event, pointerDownState);
  5401. });
  5402. const onPointerUp = withBatchedUpdates(() => {
  5403. lastPointerUp = null;
  5404. isDraggingScrollBar = false;
  5405. setCursorForShape(this.interactiveCanvas, this.state);
  5406. this.setState({
  5407. cursorButton: "up",
  5408. });
  5409. this.savePointer(event.clientX, event.clientY, "up");
  5410. window.removeEventListener(EVENT.POINTER_MOVE, onPointerMove);
  5411. window.removeEventListener(EVENT.POINTER_UP, onPointerUp);
  5412. onPointerMove.flush();
  5413. });
  5414. lastPointerUp = onPointerUp;
  5415. window.addEventListener(EVENT.POINTER_MOVE, onPointerMove);
  5416. window.addEventListener(EVENT.POINTER_UP, onPointerUp);
  5417. return true;
  5418. }
  5419. private clearSelectionIfNotUsingSelection = (): void => {
  5420. if (this.state.activeTool.type !== "selection") {
  5421. this.setState({
  5422. selectedElementIds: makeNextSelectedElementIds({}, this.state),
  5423. selectedGroupIds: {},
  5424. editingGroupId: null,
  5425. activeEmbeddable: null,
  5426. });
  5427. }
  5428. };
  5429. /**
  5430. * @returns whether the pointer event has been completely handled
  5431. */
  5432. private handleSelectionOnPointerDown = (
  5433. event: React.PointerEvent<HTMLElement>,
  5434. pointerDownState: PointerDownState,
  5435. ): boolean => {
  5436. if (this.state.activeTool.type === "selection") {
  5437. const elements = this.scene.getNonDeletedElements();
  5438. const selectedElements = this.scene.getSelectedElements(this.state);
  5439. if (selectedElements.length === 1 && !this.state.editingLinearElement) {
  5440. const elementWithTransformHandleType =
  5441. getElementWithTransformHandleType(
  5442. elements,
  5443. this.state,
  5444. pointerDownState.origin.x,
  5445. pointerDownState.origin.y,
  5446. this.state.zoom,
  5447. event.pointerType,
  5448. );
  5449. if (elementWithTransformHandleType != null) {
  5450. this.setState({
  5451. resizingElement: elementWithTransformHandleType.element,
  5452. });
  5453. pointerDownState.resize.handleType =
  5454. elementWithTransformHandleType.transformHandleType;
  5455. }
  5456. } else if (selectedElements.length > 1) {
  5457. pointerDownState.resize.handleType = getTransformHandleTypeFromCoords(
  5458. getCommonBounds(selectedElements),
  5459. pointerDownState.origin.x,
  5460. pointerDownState.origin.y,
  5461. this.state.zoom,
  5462. event.pointerType,
  5463. );
  5464. }
  5465. if (pointerDownState.resize.handleType) {
  5466. pointerDownState.resize.isResizing = true;
  5467. pointerDownState.resize.offset = tupleToCoors(
  5468. getResizeOffsetXY(
  5469. pointerDownState.resize.handleType,
  5470. selectedElements,
  5471. pointerDownState.origin.x,
  5472. pointerDownState.origin.y,
  5473. ),
  5474. );
  5475. if (
  5476. selectedElements.length === 1 &&
  5477. isLinearElement(selectedElements[0]) &&
  5478. selectedElements[0].points.length === 2
  5479. ) {
  5480. pointerDownState.resize.arrowDirection = getResizeArrowDirection(
  5481. pointerDownState.resize.handleType,
  5482. selectedElements[0],
  5483. );
  5484. }
  5485. } else {
  5486. if (this.state.selectedLinearElement) {
  5487. const linearElementEditor =
  5488. this.state.editingLinearElement || this.state.selectedLinearElement;
  5489. const ret = LinearElementEditor.handlePointerDown(
  5490. event,
  5491. this.state,
  5492. this.history,
  5493. pointerDownState.origin,
  5494. linearElementEditor,
  5495. );
  5496. if (ret.hitElement) {
  5497. pointerDownState.hit.element = ret.hitElement;
  5498. }
  5499. if (ret.linearElementEditor) {
  5500. this.setState({ selectedLinearElement: ret.linearElementEditor });
  5501. if (this.state.editingLinearElement) {
  5502. this.setState({ editingLinearElement: ret.linearElementEditor });
  5503. }
  5504. }
  5505. if (ret.didAddPoint) {
  5506. return true;
  5507. }
  5508. }
  5509. // hitElement may already be set above, so check first
  5510. pointerDownState.hit.element =
  5511. pointerDownState.hit.element ??
  5512. this.getElementAtPosition(
  5513. pointerDownState.origin.x,
  5514. pointerDownState.origin.y,
  5515. );
  5516. if (pointerDownState.hit.element) {
  5517. // Early return if pointer is hitting link icon
  5518. const hitLinkElement = this.getElementLinkAtPosition(
  5519. {
  5520. x: pointerDownState.origin.x,
  5521. y: pointerDownState.origin.y,
  5522. },
  5523. pointerDownState.hit.element,
  5524. );
  5525. if (hitLinkElement) {
  5526. return false;
  5527. }
  5528. }
  5529. // For overlapped elements one position may hit
  5530. // multiple elements
  5531. pointerDownState.hit.allHitElements = this.getElementsAtPosition(
  5532. pointerDownState.origin.x,
  5533. pointerDownState.origin.y,
  5534. );
  5535. const hitElement = pointerDownState.hit.element;
  5536. const someHitElementIsSelected =
  5537. pointerDownState.hit.allHitElements.some((element) =>
  5538. this.isASelectedElement(element),
  5539. );
  5540. if (
  5541. (hitElement === null || !someHitElementIsSelected) &&
  5542. !event.shiftKey &&
  5543. !pointerDownState.hit.hasHitCommonBoundingBoxOfSelectedElements
  5544. ) {
  5545. this.clearSelection(hitElement);
  5546. }
  5547. if (this.state.editingLinearElement) {
  5548. this.setState({
  5549. selectedElementIds: makeNextSelectedElementIds(
  5550. {
  5551. [this.state.editingLinearElement.elementId]: true,
  5552. },
  5553. this.state,
  5554. ),
  5555. });
  5556. // If we click on something
  5557. } else if (hitElement != null) {
  5558. // on CMD/CTRL, drill down to hit element regardless of groups etc.
  5559. if (event[KEYS.CTRL_OR_CMD]) {
  5560. if (!this.state.selectedElementIds[hitElement.id]) {
  5561. pointerDownState.hit.wasAddedToSelection = true;
  5562. }
  5563. this.setState((prevState) => ({
  5564. ...editGroupForSelectedElement(prevState, hitElement),
  5565. previousSelectedElementIds: this.state.selectedElementIds,
  5566. }));
  5567. // mark as not completely handled so as to allow dragging etc.
  5568. return false;
  5569. }
  5570. // deselect if item is selected
  5571. // if shift is not clicked, this will always return true
  5572. // otherwise, it will trigger selection based on current
  5573. // state of the box
  5574. if (!this.state.selectedElementIds[hitElement.id]) {
  5575. // if we are currently editing a group, exiting editing mode and deselect the group.
  5576. if (
  5577. this.state.editingGroupId &&
  5578. !isElementInGroup(hitElement, this.state.editingGroupId)
  5579. ) {
  5580. this.setState({
  5581. selectedElementIds: makeNextSelectedElementIds({}, this.state),
  5582. selectedGroupIds: {},
  5583. editingGroupId: null,
  5584. activeEmbeddable: null,
  5585. });
  5586. }
  5587. // Add hit element to selection. At this point if we're not holding
  5588. // SHIFT the previously selected element(s) were deselected above
  5589. // (make sure you use setState updater to use latest state)
  5590. // With shift-selection, we want to make sure that frames and their containing
  5591. // elements are not selected at the same time.
  5592. if (
  5593. !someHitElementIsSelected &&
  5594. !pointerDownState.hit.hasHitCommonBoundingBoxOfSelectedElements
  5595. ) {
  5596. this.setState((prevState) => {
  5597. const nextSelectedElementIds: { [id: string]: true } = {
  5598. ...prevState.selectedElementIds,
  5599. [hitElement.id]: true,
  5600. };
  5601. const previouslySelectedElements: ExcalidrawElement[] = [];
  5602. Object.keys(prevState.selectedElementIds).forEach((id) => {
  5603. const element = this.scene.getElement(id);
  5604. element && previouslySelectedElements.push(element);
  5605. });
  5606. // if hitElement is frame-like, deselect all of its elements
  5607. // if they are selected
  5608. if (isFrameLikeElement(hitElement)) {
  5609. getFrameChildren(
  5610. previouslySelectedElements,
  5611. hitElement.id,
  5612. ).forEach((element) => {
  5613. delete nextSelectedElementIds[element.id];
  5614. });
  5615. } else if (hitElement.frameId) {
  5616. // if hitElement is in a frame and its frame has been selected
  5617. // disable selection for the given element
  5618. if (nextSelectedElementIds[hitElement.frameId]) {
  5619. delete nextSelectedElementIds[hitElement.id];
  5620. }
  5621. } else {
  5622. // hitElement is neither a frame nor an element in a frame
  5623. // but since hitElement could be in a group with some frames
  5624. // this means selecting hitElement will have the frames selected as well
  5625. // because we want to keep the invariant:
  5626. // - frames and their elements are not selected at the same time
  5627. // we deselect elements in those frames that were previously selected
  5628. const groupIds = hitElement.groupIds;
  5629. const framesInGroups = new Set(
  5630. groupIds
  5631. .flatMap((gid) =>
  5632. getElementsInGroup(
  5633. this.scene.getNonDeletedElements(),
  5634. gid,
  5635. ),
  5636. )
  5637. .filter((element) => isFrameLikeElement(element))
  5638. .map((frame) => frame.id),
  5639. );
  5640. if (framesInGroups.size > 0) {
  5641. previouslySelectedElements.forEach((element) => {
  5642. if (
  5643. element.frameId &&
  5644. framesInGroups.has(element.frameId)
  5645. ) {
  5646. // deselect element and groups containing the element
  5647. delete nextSelectedElementIds[element.id];
  5648. element.groupIds
  5649. .flatMap((gid) =>
  5650. getElementsInGroup(
  5651. this.scene.getNonDeletedElements(),
  5652. gid,
  5653. ),
  5654. )
  5655. .forEach((element) => {
  5656. delete nextSelectedElementIds[element.id];
  5657. });
  5658. }
  5659. });
  5660. }
  5661. }
  5662. return {
  5663. ...selectGroupsForSelectedElements(
  5664. {
  5665. editingGroupId: prevState.editingGroupId,
  5666. selectedElementIds: nextSelectedElementIds,
  5667. },
  5668. this.scene.getNonDeletedElements(),
  5669. prevState,
  5670. this,
  5671. ),
  5672. showHyperlinkPopup:
  5673. hitElement.link || isEmbeddableElement(hitElement)
  5674. ? "info"
  5675. : false,
  5676. };
  5677. });
  5678. pointerDownState.hit.wasAddedToSelection = true;
  5679. }
  5680. }
  5681. }
  5682. this.setState({
  5683. previousSelectedElementIds: this.state.selectedElementIds,
  5684. });
  5685. }
  5686. }
  5687. return false;
  5688. };
  5689. private isASelectedElement(hitElement: ExcalidrawElement | null): boolean {
  5690. return hitElement != null && this.state.selectedElementIds[hitElement.id];
  5691. }
  5692. private isHittingCommonBoundingBoxOfSelectedElements(
  5693. point: Readonly<{ x: number; y: number }>,
  5694. selectedElements: readonly ExcalidrawElement[],
  5695. ): boolean {
  5696. if (selectedElements.length < 2) {
  5697. return false;
  5698. }
  5699. // How many pixels off the shape boundary we still consider a hit
  5700. const threshold = 10 / this.state.zoom.value;
  5701. const [x1, y1, x2, y2] = getCommonBounds(selectedElements);
  5702. return (
  5703. point.x > x1 - threshold &&
  5704. point.x < x2 + threshold &&
  5705. point.y > y1 - threshold &&
  5706. point.y < y2 + threshold
  5707. );
  5708. }
  5709. private handleTextOnPointerDown = (
  5710. event: React.PointerEvent<HTMLElement>,
  5711. pointerDownState: PointerDownState,
  5712. ): void => {
  5713. // if we're currently still editing text, clicking outside
  5714. // should only finalize it, not create another (irrespective
  5715. // of state.activeTool.locked)
  5716. if (isTextElement(this.state.editingElement)) {
  5717. return;
  5718. }
  5719. let sceneX = pointerDownState.origin.x;
  5720. let sceneY = pointerDownState.origin.y;
  5721. const element = this.getElementAtPosition(sceneX, sceneY, {
  5722. includeBoundTextElement: true,
  5723. });
  5724. // FIXME
  5725. let container = getTextBindableContainerAtPosition(
  5726. this.scene.getNonDeletedElements(),
  5727. this.state,
  5728. sceneX,
  5729. sceneY,
  5730. );
  5731. if (hasBoundTextElement(element)) {
  5732. container = element as ExcalidrawTextContainer;
  5733. sceneX = element.x + element.width / 2;
  5734. sceneY = element.y + element.height / 2;
  5735. }
  5736. this.startTextEditing({
  5737. sceneX,
  5738. sceneY,
  5739. insertAtParentCenter: !event.altKey,
  5740. container,
  5741. });
  5742. resetCursor(this.interactiveCanvas);
  5743. if (!this.state.activeTool.locked) {
  5744. this.setState({
  5745. activeTool: updateActiveTool(this.state, { type: "selection" }),
  5746. });
  5747. }
  5748. };
  5749. private handleFreeDrawElementOnPointerDown = (
  5750. event: React.PointerEvent<HTMLElement>,
  5751. elementType: ExcalidrawFreeDrawElement["type"],
  5752. pointerDownState: PointerDownState,
  5753. ) => {
  5754. // Begin a mark capture. This does not have to update state yet.
  5755. const [gridX, gridY] = getGridPoint(
  5756. pointerDownState.origin.x,
  5757. pointerDownState.origin.y,
  5758. null,
  5759. );
  5760. const topLayerFrame = this.getTopLayerFrameAtSceneCoords({
  5761. x: gridX,
  5762. y: gridY,
  5763. });
  5764. const element = newFreeDrawElement({
  5765. type: elementType,
  5766. x: gridX,
  5767. y: gridY,
  5768. strokeColor: this.state.currentItemStrokeColor,
  5769. backgroundColor: this.state.currentItemBackgroundColor,
  5770. fillStyle: this.state.currentItemFillStyle,
  5771. strokeWidth: this.state.currentItemStrokeWidth,
  5772. strokeStyle: this.state.currentItemStrokeStyle,
  5773. roughness: this.state.currentItemRoughness,
  5774. opacity: this.state.currentItemOpacity,
  5775. roundness: null,
  5776. simulatePressure: event.pressure === 0.5,
  5777. locked: false,
  5778. frameId: topLayerFrame ? topLayerFrame.id : null,
  5779. });
  5780. this.setState((prevState) => {
  5781. const nextSelectedElementIds = {
  5782. ...prevState.selectedElementIds,
  5783. };
  5784. delete nextSelectedElementIds[element.id];
  5785. return {
  5786. selectedElementIds: makeNextSelectedElementIds(
  5787. nextSelectedElementIds,
  5788. prevState,
  5789. ),
  5790. };
  5791. });
  5792. const pressures = element.simulatePressure
  5793. ? element.pressures
  5794. : [...element.pressures, event.pressure];
  5795. mutateElement(element, {
  5796. points: [[0, 0]],
  5797. pressures,
  5798. });
  5799. const boundElement = getHoveredElementForBinding(
  5800. pointerDownState.origin,
  5801. this.scene,
  5802. );
  5803. this.scene.addNewElement(element);
  5804. this.setState({
  5805. draggingElement: element,
  5806. editingElement: element,
  5807. startBoundElement: boundElement,
  5808. suggestedBindings: [],
  5809. });
  5810. };
  5811. public insertIframeElement = ({
  5812. sceneX,
  5813. sceneY,
  5814. width,
  5815. height,
  5816. }: {
  5817. sceneX: number;
  5818. sceneY: number;
  5819. width: number;
  5820. height: number;
  5821. }) => {
  5822. const [gridX, gridY] = getGridPoint(
  5823. sceneX,
  5824. sceneY,
  5825. this.lastPointerDownEvent?.[KEYS.CTRL_OR_CMD]
  5826. ? null
  5827. : this.state.gridSize,
  5828. );
  5829. const element = newIframeElement({
  5830. type: "iframe",
  5831. x: gridX,
  5832. y: gridY,
  5833. strokeColor: "transparent",
  5834. backgroundColor: "transparent",
  5835. fillStyle: this.state.currentItemFillStyle,
  5836. strokeWidth: this.state.currentItemStrokeWidth,
  5837. strokeStyle: this.state.currentItemStrokeStyle,
  5838. roughness: this.state.currentItemRoughness,
  5839. roundness: this.getCurrentItemRoundness("iframe"),
  5840. opacity: this.state.currentItemOpacity,
  5841. locked: false,
  5842. width,
  5843. height,
  5844. });
  5845. this.scene.replaceAllElements([
  5846. ...this.scene.getElementsIncludingDeleted(),
  5847. element,
  5848. ]);
  5849. return element;
  5850. };
  5851. //create rectangle element with youtube top left on nearest grid point width / hight 640/360
  5852. public insertEmbeddableElement = ({
  5853. sceneX,
  5854. sceneY,
  5855. link,
  5856. }: {
  5857. sceneX: number;
  5858. sceneY: number;
  5859. link: string;
  5860. }) => {
  5861. const [gridX, gridY] = getGridPoint(
  5862. sceneX,
  5863. sceneY,
  5864. this.lastPointerDownEvent?.[KEYS.CTRL_OR_CMD]
  5865. ? null
  5866. : this.state.gridSize,
  5867. );
  5868. const embedLink = getEmbedLink(link);
  5869. if (!embedLink) {
  5870. return;
  5871. }
  5872. if (embedLink.warning) {
  5873. this.setToast({ message: embedLink.warning, closable: true });
  5874. }
  5875. const element = newEmbeddableElement({
  5876. type: "embeddable",
  5877. x: gridX,
  5878. y: gridY,
  5879. strokeColor: "transparent",
  5880. backgroundColor: "transparent",
  5881. fillStyle: this.state.currentItemFillStyle,
  5882. strokeWidth: this.state.currentItemStrokeWidth,
  5883. strokeStyle: this.state.currentItemStrokeStyle,
  5884. roughness: this.state.currentItemRoughness,
  5885. roundness: this.getCurrentItemRoundness("embeddable"),
  5886. opacity: this.state.currentItemOpacity,
  5887. locked: false,
  5888. width: embedLink.intrinsicSize.w,
  5889. height: embedLink.intrinsicSize.h,
  5890. link,
  5891. validated: null,
  5892. });
  5893. this.scene.replaceAllElements([
  5894. ...this.scene.getElementsIncludingDeleted(),
  5895. element,
  5896. ]);
  5897. return element;
  5898. };
  5899. private createImageElement = ({
  5900. sceneX,
  5901. sceneY,
  5902. addToFrameUnderCursor = true,
  5903. }: {
  5904. sceneX: number;
  5905. sceneY: number;
  5906. addToFrameUnderCursor?: boolean;
  5907. }) => {
  5908. const [gridX, gridY] = getGridPoint(
  5909. sceneX,
  5910. sceneY,
  5911. this.lastPointerDownEvent?.[KEYS.CTRL_OR_CMD]
  5912. ? null
  5913. : this.state.gridSize,
  5914. );
  5915. const topLayerFrame = addToFrameUnderCursor
  5916. ? this.getTopLayerFrameAtSceneCoords({
  5917. x: gridX,
  5918. y: gridY,
  5919. })
  5920. : null;
  5921. const element = newImageElement({
  5922. type: "image",
  5923. x: gridX,
  5924. y: gridY,
  5925. strokeColor: this.state.currentItemStrokeColor,
  5926. backgroundColor: this.state.currentItemBackgroundColor,
  5927. fillStyle: this.state.currentItemFillStyle,
  5928. strokeWidth: this.state.currentItemStrokeWidth,
  5929. strokeStyle: this.state.currentItemStrokeStyle,
  5930. roughness: this.state.currentItemRoughness,
  5931. roundness: null,
  5932. opacity: this.state.currentItemOpacity,
  5933. locked: false,
  5934. frameId: topLayerFrame ? topLayerFrame.id : null,
  5935. });
  5936. return element;
  5937. };
  5938. private handleLinearElementOnPointerDown = (
  5939. event: React.PointerEvent<HTMLElement>,
  5940. elementType: ExcalidrawLinearElement["type"],
  5941. pointerDownState: PointerDownState,
  5942. ): void => {
  5943. if (this.state.multiElement) {
  5944. const { multiElement } = this.state;
  5945. // finalize if completing a loop
  5946. if (
  5947. multiElement.type === "line" &&
  5948. isPathALoop(multiElement.points, this.state.zoom.value)
  5949. ) {
  5950. mutateElement(multiElement, {
  5951. lastCommittedPoint:
  5952. multiElement.points[multiElement.points.length - 1],
  5953. });
  5954. this.actionManager.executeAction(actionFinalize);
  5955. return;
  5956. }
  5957. const { x: rx, y: ry, lastCommittedPoint } = multiElement;
  5958. // clicking inside commit zone → finalize arrow
  5959. if (
  5960. multiElement.points.length > 1 &&
  5961. lastCommittedPoint &&
  5962. distance2d(
  5963. pointerDownState.origin.x - rx,
  5964. pointerDownState.origin.y - ry,
  5965. lastCommittedPoint[0],
  5966. lastCommittedPoint[1],
  5967. ) < LINE_CONFIRM_THRESHOLD
  5968. ) {
  5969. this.actionManager.executeAction(actionFinalize);
  5970. return;
  5971. }
  5972. this.setState((prevState) => ({
  5973. selectedElementIds: makeNextSelectedElementIds(
  5974. {
  5975. ...prevState.selectedElementIds,
  5976. [multiElement.id]: true,
  5977. },
  5978. prevState,
  5979. ),
  5980. }));
  5981. // clicking outside commit zone → update reference for last committed
  5982. // point
  5983. mutateElement(multiElement, {
  5984. lastCommittedPoint: multiElement.points[multiElement.points.length - 1],
  5985. });
  5986. setCursor(this.interactiveCanvas, CURSOR_TYPE.POINTER);
  5987. } else {
  5988. const [gridX, gridY] = getGridPoint(
  5989. pointerDownState.origin.x,
  5990. pointerDownState.origin.y,
  5991. event[KEYS.CTRL_OR_CMD] ? null : this.state.gridSize,
  5992. );
  5993. const topLayerFrame = this.getTopLayerFrameAtSceneCoords({
  5994. x: gridX,
  5995. y: gridY,
  5996. });
  5997. /* If arrow is pre-arrowheads, it will have undefined for both start and end arrowheads.
  5998. If so, we want it to be null for start and "arrow" for end. If the linear item is not
  5999. an arrow, we want it to be null for both. Otherwise, we want it to use the
  6000. values from appState. */
  6001. const { currentItemStartArrowhead, currentItemEndArrowhead } = this.state;
  6002. const [startArrowhead, endArrowhead] =
  6003. elementType === "arrow"
  6004. ? [currentItemStartArrowhead, currentItemEndArrowhead]
  6005. : [null, null];
  6006. const element = newLinearElement({
  6007. type: elementType,
  6008. x: gridX,
  6009. y: gridY,
  6010. strokeColor: this.state.currentItemStrokeColor,
  6011. backgroundColor: this.state.currentItemBackgroundColor,
  6012. fillStyle: this.state.currentItemFillStyle,
  6013. strokeWidth: this.state.currentItemStrokeWidth,
  6014. strokeStyle: this.state.currentItemStrokeStyle,
  6015. roughness: this.state.currentItemRoughness,
  6016. opacity: this.state.currentItemOpacity,
  6017. roundness:
  6018. this.state.currentItemRoundness === "round"
  6019. ? { type: ROUNDNESS.PROPORTIONAL_RADIUS }
  6020. : null,
  6021. startArrowhead,
  6022. endArrowhead,
  6023. locked: false,
  6024. frameId: topLayerFrame ? topLayerFrame.id : null,
  6025. });
  6026. this.setState((prevState) => {
  6027. const nextSelectedElementIds = {
  6028. ...prevState.selectedElementIds,
  6029. };
  6030. delete nextSelectedElementIds[element.id];
  6031. return {
  6032. selectedElementIds: makeNextSelectedElementIds(
  6033. nextSelectedElementIds,
  6034. prevState,
  6035. ),
  6036. };
  6037. });
  6038. mutateElement(element, {
  6039. points: [...element.points, [0, 0]],
  6040. });
  6041. const boundElement = getHoveredElementForBinding(
  6042. pointerDownState.origin,
  6043. this.scene,
  6044. );
  6045. this.scene.addNewElement(element);
  6046. this.setState({
  6047. draggingElement: element,
  6048. editingElement: element,
  6049. startBoundElement: boundElement,
  6050. suggestedBindings: [],
  6051. });
  6052. }
  6053. };
  6054. private getCurrentItemRoundness(
  6055. elementType:
  6056. | "selection"
  6057. | "rectangle"
  6058. | "diamond"
  6059. | "ellipse"
  6060. | "iframe"
  6061. | "embeddable",
  6062. ) {
  6063. return this.state.currentItemRoundness === "round"
  6064. ? {
  6065. type: isUsingAdaptiveRadius(elementType)
  6066. ? ROUNDNESS.ADAPTIVE_RADIUS
  6067. : ROUNDNESS.PROPORTIONAL_RADIUS,
  6068. }
  6069. : null;
  6070. }
  6071. private createGenericElementOnPointerDown = (
  6072. elementType: ExcalidrawGenericElement["type"] | "embeddable",
  6073. pointerDownState: PointerDownState,
  6074. ): void => {
  6075. const [gridX, gridY] = getGridPoint(
  6076. pointerDownState.origin.x,
  6077. pointerDownState.origin.y,
  6078. this.lastPointerDownEvent?.[KEYS.CTRL_OR_CMD]
  6079. ? null
  6080. : this.state.gridSize,
  6081. );
  6082. const topLayerFrame = this.getTopLayerFrameAtSceneCoords({
  6083. x: gridX,
  6084. y: gridY,
  6085. });
  6086. const baseElementAttributes = {
  6087. x: gridX,
  6088. y: gridY,
  6089. strokeColor: this.state.currentItemStrokeColor,
  6090. backgroundColor: this.state.currentItemBackgroundColor,
  6091. fillStyle: this.state.currentItemFillStyle,
  6092. strokeWidth: this.state.currentItemStrokeWidth,
  6093. strokeStyle: this.state.currentItemStrokeStyle,
  6094. roughness: this.state.currentItemRoughness,
  6095. opacity: this.state.currentItemOpacity,
  6096. roundness: this.getCurrentItemRoundness(elementType),
  6097. locked: false,
  6098. frameId: topLayerFrame ? topLayerFrame.id : null,
  6099. } as const;
  6100. let element;
  6101. if (elementType === "embeddable") {
  6102. element = newEmbeddableElement({
  6103. type: "embeddable",
  6104. validated: null,
  6105. ...baseElementAttributes,
  6106. });
  6107. } else {
  6108. element = newElement({
  6109. type: elementType,
  6110. ...baseElementAttributes,
  6111. });
  6112. }
  6113. if (element.type === "selection") {
  6114. this.setState({
  6115. selectionElement: element,
  6116. draggingElement: element,
  6117. });
  6118. } else {
  6119. this.scene.addNewElement(element);
  6120. this.setState({
  6121. multiElement: null,
  6122. draggingElement: element,
  6123. editingElement: element,
  6124. });
  6125. }
  6126. };
  6127. private createFrameElementOnPointerDown = (
  6128. pointerDownState: PointerDownState,
  6129. type: Extract<ToolType, "frame" | "magicframe">,
  6130. ): void => {
  6131. const [gridX, gridY] = getGridPoint(
  6132. pointerDownState.origin.x,
  6133. pointerDownState.origin.y,
  6134. this.lastPointerDownEvent?.[KEYS.CTRL_OR_CMD]
  6135. ? null
  6136. : this.state.gridSize,
  6137. );
  6138. const constructorOpts = {
  6139. x: gridX,
  6140. y: gridY,
  6141. opacity: this.state.currentItemOpacity,
  6142. locked: false,
  6143. ...FRAME_STYLE,
  6144. } as const;
  6145. const frame =
  6146. type === TOOL_TYPE.magicframe
  6147. ? newMagicFrameElement(constructorOpts)
  6148. : newFrameElement(constructorOpts);
  6149. this.scene.replaceAllElements([
  6150. ...this.scene.getElementsIncludingDeleted(),
  6151. frame,
  6152. ]);
  6153. this.setState({
  6154. multiElement: null,
  6155. draggingElement: frame,
  6156. editingElement: frame,
  6157. });
  6158. };
  6159. private maybeCacheReferenceSnapPoints(
  6160. event: KeyboardModifiersObject,
  6161. selectedElements: ExcalidrawElement[],
  6162. recomputeAnyways: boolean = false,
  6163. ) {
  6164. if (
  6165. isSnappingEnabled({
  6166. event,
  6167. appState: this.state,
  6168. selectedElements,
  6169. }) &&
  6170. (recomputeAnyways || !SnapCache.getReferenceSnapPoints())
  6171. ) {
  6172. SnapCache.setReferenceSnapPoints(
  6173. getReferenceSnapPoints(
  6174. this.scene.getNonDeletedElements(),
  6175. selectedElements,
  6176. this.state,
  6177. ),
  6178. );
  6179. }
  6180. }
  6181. private maybeCacheVisibleGaps(
  6182. event: KeyboardModifiersObject,
  6183. selectedElements: ExcalidrawElement[],
  6184. recomputeAnyways: boolean = false,
  6185. ) {
  6186. if (
  6187. isSnappingEnabled({
  6188. event,
  6189. appState: this.state,
  6190. selectedElements,
  6191. }) &&
  6192. (recomputeAnyways || !SnapCache.getVisibleGaps())
  6193. ) {
  6194. SnapCache.setVisibleGaps(
  6195. getVisibleGaps(
  6196. this.scene.getNonDeletedElements(),
  6197. selectedElements,
  6198. this.state,
  6199. ),
  6200. );
  6201. }
  6202. }
  6203. private onKeyDownFromPointerDownHandler(
  6204. pointerDownState: PointerDownState,
  6205. ): (event: KeyboardEvent) => void {
  6206. return withBatchedUpdates((event: KeyboardEvent) => {
  6207. if (this.maybeHandleResize(pointerDownState, event)) {
  6208. return;
  6209. }
  6210. this.maybeDragNewGenericElement(pointerDownState, event);
  6211. });
  6212. }
  6213. private onKeyUpFromPointerDownHandler(
  6214. pointerDownState: PointerDownState,
  6215. ): (event: KeyboardEvent) => void {
  6216. return withBatchedUpdates((event: KeyboardEvent) => {
  6217. // Prevents focus from escaping excalidraw tab
  6218. event.key === KEYS.ALT && event.preventDefault();
  6219. if (this.maybeHandleResize(pointerDownState, event)) {
  6220. return;
  6221. }
  6222. this.maybeDragNewGenericElement(pointerDownState, event);
  6223. });
  6224. }
  6225. private onPointerMoveFromPointerDownHandler(
  6226. pointerDownState: PointerDownState,
  6227. ) {
  6228. return withBatchedUpdatesThrottled((event: PointerEvent) => {
  6229. // We need to initialize dragOffsetXY only after we've updated
  6230. // `state.selectedElementIds` on pointerDown. Doing it here in pointerMove
  6231. // event handler should hopefully ensure we're already working with
  6232. // the updated state.
  6233. if (pointerDownState.drag.offset === null) {
  6234. pointerDownState.drag.offset = tupleToCoors(
  6235. getDragOffsetXY(
  6236. this.scene.getSelectedElements(this.state),
  6237. pointerDownState.origin.x,
  6238. pointerDownState.origin.y,
  6239. ),
  6240. );
  6241. }
  6242. const target = event.target;
  6243. if (!(target instanceof HTMLElement)) {
  6244. return;
  6245. }
  6246. if (this.handlePointerMoveOverScrollbars(event, pointerDownState)) {
  6247. return;
  6248. }
  6249. const pointerCoords = viewportCoordsToSceneCoords(event, this.state);
  6250. if (isEraserActive(this.state)) {
  6251. this.handleEraser(event, pointerDownState, pointerCoords);
  6252. return;
  6253. }
  6254. if (this.state.activeTool.type === "laser") {
  6255. this.laserTrails.addPointToPath(pointerCoords.x, pointerCoords.y);
  6256. }
  6257. const [gridX, gridY] = getGridPoint(
  6258. pointerCoords.x,
  6259. pointerCoords.y,
  6260. event[KEYS.CTRL_OR_CMD] ? null : this.state.gridSize,
  6261. );
  6262. // for arrows/lines, don't start dragging until a given threshold
  6263. // to ensure we don't create a 2-point arrow by mistake when
  6264. // user clicks mouse in a way that it moves a tiny bit (thus
  6265. // triggering pointermove)
  6266. if (
  6267. !pointerDownState.drag.hasOccurred &&
  6268. (this.state.activeTool.type === "arrow" ||
  6269. this.state.activeTool.type === "line")
  6270. ) {
  6271. if (
  6272. distance2d(
  6273. pointerCoords.x,
  6274. pointerCoords.y,
  6275. pointerDownState.origin.x,
  6276. pointerDownState.origin.y,
  6277. ) < DRAGGING_THRESHOLD
  6278. ) {
  6279. return;
  6280. }
  6281. }
  6282. if (pointerDownState.resize.isResizing) {
  6283. pointerDownState.lastCoords.x = pointerCoords.x;
  6284. pointerDownState.lastCoords.y = pointerCoords.y;
  6285. if (this.maybeHandleResize(pointerDownState, event)) {
  6286. return true;
  6287. }
  6288. }
  6289. if (this.state.selectedLinearElement) {
  6290. const linearElementEditor =
  6291. this.state.editingLinearElement || this.state.selectedLinearElement;
  6292. if (
  6293. LinearElementEditor.shouldAddMidpoint(
  6294. this.state.selectedLinearElement,
  6295. pointerCoords,
  6296. this.state,
  6297. )
  6298. ) {
  6299. const ret = LinearElementEditor.addMidpoint(
  6300. this.state.selectedLinearElement,
  6301. pointerCoords,
  6302. this.state,
  6303. !event[KEYS.CTRL_OR_CMD],
  6304. );
  6305. if (!ret) {
  6306. return;
  6307. }
  6308. // Since we are reading from previous state which is not possible with
  6309. // automatic batching in React 18 hence using flush sync to synchronously
  6310. // update the state. Check https://github.com/excalidraw/excalidraw/pull/5508 for more details.
  6311. flushSync(() => {
  6312. if (this.state.selectedLinearElement) {
  6313. this.setState({
  6314. selectedLinearElement: {
  6315. ...this.state.selectedLinearElement,
  6316. pointerDownState: ret.pointerDownState,
  6317. selectedPointsIndices: ret.selectedPointsIndices,
  6318. },
  6319. });
  6320. }
  6321. if (this.state.editingLinearElement) {
  6322. this.setState({
  6323. editingLinearElement: {
  6324. ...this.state.editingLinearElement,
  6325. pointerDownState: ret.pointerDownState,
  6326. selectedPointsIndices: ret.selectedPointsIndices,
  6327. },
  6328. });
  6329. }
  6330. });
  6331. return;
  6332. } else if (
  6333. linearElementEditor.pointerDownState.segmentMidpoint.value !== null &&
  6334. !linearElementEditor.pointerDownState.segmentMidpoint.added
  6335. ) {
  6336. return;
  6337. }
  6338. const didDrag = LinearElementEditor.handlePointDragging(
  6339. event,
  6340. this.state,
  6341. pointerCoords.x,
  6342. pointerCoords.y,
  6343. (element, pointsSceneCoords) => {
  6344. this.maybeSuggestBindingsForLinearElementAtCoords(
  6345. element,
  6346. pointsSceneCoords,
  6347. );
  6348. },
  6349. linearElementEditor,
  6350. );
  6351. if (didDrag) {
  6352. pointerDownState.lastCoords.x = pointerCoords.x;
  6353. pointerDownState.lastCoords.y = pointerCoords.y;
  6354. pointerDownState.drag.hasOccurred = true;
  6355. if (
  6356. this.state.editingLinearElement &&
  6357. !this.state.editingLinearElement.isDragging
  6358. ) {
  6359. this.setState({
  6360. editingLinearElement: {
  6361. ...this.state.editingLinearElement,
  6362. isDragging: true,
  6363. },
  6364. });
  6365. }
  6366. if (!this.state.selectedLinearElement.isDragging) {
  6367. this.setState({
  6368. selectedLinearElement: {
  6369. ...this.state.selectedLinearElement,
  6370. isDragging: true,
  6371. },
  6372. });
  6373. }
  6374. return;
  6375. }
  6376. }
  6377. const hasHitASelectedElement = pointerDownState.hit.allHitElements.some(
  6378. (element) => this.isASelectedElement(element),
  6379. );
  6380. const isSelectingPointsInLineEditor =
  6381. this.state.editingLinearElement &&
  6382. event.shiftKey &&
  6383. this.state.editingLinearElement.elementId ===
  6384. pointerDownState.hit.element?.id;
  6385. if (
  6386. (hasHitASelectedElement ||
  6387. pointerDownState.hit.hasHitCommonBoundingBoxOfSelectedElements) &&
  6388. !isSelectingPointsInLineEditor
  6389. ) {
  6390. const selectedElements = this.scene.getSelectedElements(this.state);
  6391. if (selectedElements.every((element) => element.locked)) {
  6392. return;
  6393. }
  6394. const selectedElementsHasAFrame = selectedElements.find((e) =>
  6395. isFrameLikeElement(e),
  6396. );
  6397. const topLayerFrame = this.getTopLayerFrameAtSceneCoords(pointerCoords);
  6398. this.setState({
  6399. frameToHighlight:
  6400. topLayerFrame && !selectedElementsHasAFrame ? topLayerFrame : null,
  6401. });
  6402. // Marking that click was used for dragging to check
  6403. // if elements should be deselected on pointerup
  6404. pointerDownState.drag.hasOccurred = true;
  6405. this.setState({
  6406. selectedElementsAreBeingDragged: true,
  6407. });
  6408. // prevent dragging even if we're no longer holding cmd/ctrl otherwise
  6409. // it would have weird results (stuff jumping all over the screen)
  6410. // Checking for editingElement to avoid jump while editing on mobile #6503
  6411. if (
  6412. selectedElements.length > 0 &&
  6413. !pointerDownState.withCmdOrCtrl &&
  6414. !this.state.editingElement &&
  6415. this.state.activeEmbeddable?.state !== "active"
  6416. ) {
  6417. const dragOffset = {
  6418. x: pointerCoords.x - pointerDownState.origin.x,
  6419. y: pointerCoords.y - pointerDownState.origin.y,
  6420. };
  6421. const originalElements = [
  6422. ...pointerDownState.originalElements.values(),
  6423. ];
  6424. // We only drag in one direction if shift is pressed
  6425. const lockDirection = event.shiftKey;
  6426. if (lockDirection) {
  6427. const distanceX = Math.abs(dragOffset.x);
  6428. const distanceY = Math.abs(dragOffset.y);
  6429. const lockX = lockDirection && distanceX < distanceY;
  6430. const lockY = lockDirection && distanceX > distanceY;
  6431. if (lockX) {
  6432. dragOffset.x = 0;
  6433. }
  6434. if (lockY) {
  6435. dragOffset.y = 0;
  6436. }
  6437. }
  6438. // Snap cache *must* be synchronously popuplated before initial drag,
  6439. // otherwise the first drag even will not snap, causing a jump before
  6440. // it snaps to its position if previously snapped already.
  6441. this.maybeCacheVisibleGaps(event, selectedElements);
  6442. this.maybeCacheReferenceSnapPoints(event, selectedElements);
  6443. const { snapOffset, snapLines } = snapDraggedElements(
  6444. getSelectedElements(originalElements, this.state),
  6445. dragOffset,
  6446. this.state,
  6447. event,
  6448. );
  6449. this.setState({ snapLines });
  6450. // when we're editing the name of a frame, we want the user to be
  6451. // able to select and interact with the text input
  6452. !this.state.editingFrame &&
  6453. dragSelectedElements(
  6454. pointerDownState,
  6455. selectedElements,
  6456. dragOffset,
  6457. this.state,
  6458. this.scene,
  6459. snapOffset,
  6460. event[KEYS.CTRL_OR_CMD] ? null : this.state.gridSize,
  6461. );
  6462. this.maybeSuggestBindingForAll(selectedElements);
  6463. // We duplicate the selected element if alt is pressed on pointer move
  6464. if (event.altKey && !pointerDownState.hit.hasBeenDuplicated) {
  6465. // Move the currently selected elements to the top of the z index stack, and
  6466. // put the duplicates where the selected elements used to be.
  6467. // (the origin point where the dragging started)
  6468. pointerDownState.hit.hasBeenDuplicated = true;
  6469. const nextElements = [];
  6470. const elementsToAppend = [];
  6471. const groupIdMap = new Map();
  6472. const oldIdToDuplicatedId = new Map();
  6473. const hitElement = pointerDownState.hit.element;
  6474. const selectedElementIds = new Set(
  6475. this.scene
  6476. .getSelectedElements({
  6477. selectedElementIds: this.state.selectedElementIds,
  6478. includeBoundTextElement: true,
  6479. includeElementsInFrames: true,
  6480. })
  6481. .map((element) => element.id),
  6482. );
  6483. const elements = this.scene.getElementsIncludingDeleted();
  6484. for (const element of elements) {
  6485. if (
  6486. selectedElementIds.has(element.id) ||
  6487. // case: the state.selectedElementIds might not have been
  6488. // updated yet by the time this mousemove event is fired
  6489. (element.id === hitElement?.id &&
  6490. pointerDownState.hit.wasAddedToSelection)
  6491. ) {
  6492. const duplicatedElement = duplicateElement(
  6493. this.state.editingGroupId,
  6494. groupIdMap,
  6495. element,
  6496. );
  6497. const origElement = pointerDownState.originalElements.get(
  6498. element.id,
  6499. )!;
  6500. mutateElement(duplicatedElement, {
  6501. x: origElement.x,
  6502. y: origElement.y,
  6503. });
  6504. // put duplicated element to pointerDownState.originalElements
  6505. // so that we can snap to the duplicated element without releasing
  6506. pointerDownState.originalElements.set(
  6507. duplicatedElement.id,
  6508. duplicatedElement,
  6509. );
  6510. nextElements.push(duplicatedElement);
  6511. elementsToAppend.push(element);
  6512. oldIdToDuplicatedId.set(element.id, duplicatedElement.id);
  6513. } else {
  6514. nextElements.push(element);
  6515. }
  6516. }
  6517. const nextSceneElements = [...nextElements, ...elementsToAppend];
  6518. bindTextToShapeAfterDuplication(
  6519. nextElements,
  6520. elementsToAppend,
  6521. oldIdToDuplicatedId,
  6522. );
  6523. fixBindingsAfterDuplication(
  6524. nextSceneElements,
  6525. elementsToAppend,
  6526. oldIdToDuplicatedId,
  6527. "duplicatesServeAsOld",
  6528. );
  6529. bindElementsToFramesAfterDuplication(
  6530. nextSceneElements,
  6531. elementsToAppend,
  6532. oldIdToDuplicatedId,
  6533. );
  6534. this.scene.replaceAllElements(nextSceneElements);
  6535. this.maybeCacheVisibleGaps(event, selectedElements, true);
  6536. this.maybeCacheReferenceSnapPoints(event, selectedElements, true);
  6537. }
  6538. return;
  6539. }
  6540. }
  6541. // It is very important to read this.state within each move event,
  6542. // otherwise we would read a stale one!
  6543. const draggingElement = this.state.draggingElement;
  6544. if (!draggingElement) {
  6545. return;
  6546. }
  6547. if (draggingElement.type === "freedraw") {
  6548. const points = draggingElement.points;
  6549. const dx = pointerCoords.x - draggingElement.x;
  6550. const dy = pointerCoords.y - draggingElement.y;
  6551. const lastPoint = points.length > 0 && points[points.length - 1];
  6552. const discardPoint =
  6553. lastPoint && lastPoint[0] === dx && lastPoint[1] === dy;
  6554. if (!discardPoint) {
  6555. const pressures = draggingElement.simulatePressure
  6556. ? draggingElement.pressures
  6557. : [...draggingElement.pressures, event.pressure];
  6558. mutateElement(draggingElement, {
  6559. points: [...points, [dx, dy]],
  6560. pressures,
  6561. });
  6562. }
  6563. } else if (isLinearElement(draggingElement)) {
  6564. pointerDownState.drag.hasOccurred = true;
  6565. this.setState({
  6566. selectedElementsAreBeingDragged: true,
  6567. });
  6568. const points = draggingElement.points;
  6569. let dx = gridX - draggingElement.x;
  6570. let dy = gridY - draggingElement.y;
  6571. if (shouldRotateWithDiscreteAngle(event) && points.length === 2) {
  6572. ({ width: dx, height: dy } = getLockedLinearCursorAlignSize(
  6573. draggingElement.x,
  6574. draggingElement.y,
  6575. pointerCoords.x,
  6576. pointerCoords.y,
  6577. ));
  6578. }
  6579. if (points.length === 1) {
  6580. mutateElement(draggingElement, {
  6581. points: [...points, [dx, dy]],
  6582. });
  6583. } else if (points.length === 2) {
  6584. mutateElement(draggingElement, {
  6585. points: [...points.slice(0, -1), [dx, dy]],
  6586. });
  6587. }
  6588. if (isBindingElement(draggingElement, false)) {
  6589. // When creating a linear element by dragging
  6590. this.maybeSuggestBindingsForLinearElementAtCoords(
  6591. draggingElement,
  6592. [pointerCoords],
  6593. this.state.startBoundElement,
  6594. );
  6595. }
  6596. } else {
  6597. pointerDownState.lastCoords.x = pointerCoords.x;
  6598. pointerDownState.lastCoords.y = pointerCoords.y;
  6599. this.maybeDragNewGenericElement(pointerDownState, event);
  6600. }
  6601. if (this.state.activeTool.type === "selection") {
  6602. pointerDownState.boxSelection.hasOccurred = true;
  6603. const elements = this.scene.getNonDeletedElements();
  6604. // box-select line editor points
  6605. if (this.state.editingLinearElement) {
  6606. LinearElementEditor.handleBoxSelection(
  6607. event,
  6608. this.state,
  6609. this.setState.bind(this),
  6610. );
  6611. // regular box-select
  6612. } else {
  6613. let shouldReuseSelection = true;
  6614. if (!event.shiftKey && isSomeElementSelected(elements, this.state)) {
  6615. if (
  6616. pointerDownState.withCmdOrCtrl &&
  6617. pointerDownState.hit.element
  6618. ) {
  6619. this.setState((prevState) =>
  6620. selectGroupsForSelectedElements(
  6621. {
  6622. ...prevState,
  6623. selectedElementIds: {
  6624. [pointerDownState.hit.element!.id]: true,
  6625. },
  6626. },
  6627. this.scene.getNonDeletedElements(),
  6628. prevState,
  6629. this,
  6630. ),
  6631. );
  6632. } else {
  6633. shouldReuseSelection = false;
  6634. }
  6635. }
  6636. const elementsWithinSelection = getElementsWithinSelection(
  6637. elements,
  6638. draggingElement,
  6639. );
  6640. this.setState((prevState) => {
  6641. const nextSelectedElementIds = {
  6642. ...(shouldReuseSelection && prevState.selectedElementIds),
  6643. ...elementsWithinSelection.reduce(
  6644. (acc: Record<ExcalidrawElement["id"], true>, element) => {
  6645. acc[element.id] = true;
  6646. return acc;
  6647. },
  6648. {},
  6649. ),
  6650. };
  6651. if (pointerDownState.hit.element) {
  6652. // if using ctrl/cmd, select the hitElement only if we
  6653. // haven't box-selected anything else
  6654. if (!elementsWithinSelection.length) {
  6655. nextSelectedElementIds[pointerDownState.hit.element.id] = true;
  6656. } else {
  6657. delete nextSelectedElementIds[pointerDownState.hit.element.id];
  6658. }
  6659. }
  6660. prevState = !shouldReuseSelection
  6661. ? { ...prevState, selectedGroupIds: {}, editingGroupId: null }
  6662. : prevState;
  6663. return {
  6664. ...selectGroupsForSelectedElements(
  6665. {
  6666. editingGroupId: prevState.editingGroupId,
  6667. selectedElementIds: nextSelectedElementIds,
  6668. },
  6669. this.scene.getNonDeletedElements(),
  6670. prevState,
  6671. this,
  6672. ),
  6673. // select linear element only when we haven't box-selected anything else
  6674. selectedLinearElement:
  6675. elementsWithinSelection.length === 1 &&
  6676. isLinearElement(elementsWithinSelection[0])
  6677. ? new LinearElementEditor(
  6678. elementsWithinSelection[0],
  6679. this.scene,
  6680. )
  6681. : null,
  6682. showHyperlinkPopup:
  6683. elementsWithinSelection.length === 1 &&
  6684. (elementsWithinSelection[0].link ||
  6685. isEmbeddableElement(elementsWithinSelection[0]))
  6686. ? "info"
  6687. : false,
  6688. };
  6689. });
  6690. }
  6691. }
  6692. });
  6693. }
  6694. // Returns whether the pointer move happened over either scrollbar
  6695. private handlePointerMoveOverScrollbars(
  6696. event: PointerEvent,
  6697. pointerDownState: PointerDownState,
  6698. ): boolean {
  6699. if (pointerDownState.scrollbars.isOverHorizontal) {
  6700. const x = event.clientX;
  6701. const dx = x - pointerDownState.lastCoords.x;
  6702. this.translateCanvas({
  6703. scrollX: this.state.scrollX - dx / this.state.zoom.value,
  6704. });
  6705. pointerDownState.lastCoords.x = x;
  6706. return true;
  6707. }
  6708. if (pointerDownState.scrollbars.isOverVertical) {
  6709. const y = event.clientY;
  6710. const dy = y - pointerDownState.lastCoords.y;
  6711. this.translateCanvas({
  6712. scrollY: this.state.scrollY - dy / this.state.zoom.value,
  6713. });
  6714. pointerDownState.lastCoords.y = y;
  6715. return true;
  6716. }
  6717. return false;
  6718. }
  6719. private onPointerUpFromPointerDownHandler(
  6720. pointerDownState: PointerDownState,
  6721. ): (event: PointerEvent) => void {
  6722. return withBatchedUpdates((childEvent: PointerEvent) => {
  6723. this.removePointer(childEvent);
  6724. if (pointerDownState.eventListeners.onMove) {
  6725. pointerDownState.eventListeners.onMove.flush();
  6726. }
  6727. const {
  6728. draggingElement,
  6729. resizingElement,
  6730. multiElement,
  6731. activeTool,
  6732. isResizing,
  6733. isRotating,
  6734. } = this.state;
  6735. this.setState((prevState) => ({
  6736. isResizing: false,
  6737. isRotating: false,
  6738. resizingElement: null,
  6739. selectionElement: null,
  6740. frameToHighlight: null,
  6741. elementsToHighlight: null,
  6742. cursorButton: "up",
  6743. // text elements are reset on finalize, and resetting on pointerup
  6744. // may cause issues with double taps
  6745. editingElement:
  6746. multiElement || isTextElement(this.state.editingElement)
  6747. ? this.state.editingElement
  6748. : null,
  6749. snapLines: updateStable(prevState.snapLines, []),
  6750. originSnapOffset: null,
  6751. }));
  6752. SnapCache.setReferenceSnapPoints(null);
  6753. SnapCache.setVisibleGaps(null);
  6754. this.savePointer(childEvent.clientX, childEvent.clientY, "up");
  6755. this.setState({
  6756. selectedElementsAreBeingDragged: false,
  6757. });
  6758. // Handle end of dragging a point of a linear element, might close a loop
  6759. // and sets binding element
  6760. if (this.state.editingLinearElement) {
  6761. if (
  6762. !pointerDownState.boxSelection.hasOccurred &&
  6763. pointerDownState.hit?.element?.id !==
  6764. this.state.editingLinearElement.elementId
  6765. ) {
  6766. this.actionManager.executeAction(actionFinalize);
  6767. } else {
  6768. const editingLinearElement = LinearElementEditor.handlePointerUp(
  6769. childEvent,
  6770. this.state.editingLinearElement,
  6771. this.state,
  6772. );
  6773. if (editingLinearElement !== this.state.editingLinearElement) {
  6774. this.setState({
  6775. editingLinearElement,
  6776. suggestedBindings: [],
  6777. });
  6778. }
  6779. }
  6780. } else if (this.state.selectedLinearElement) {
  6781. if (
  6782. pointerDownState.hit?.element?.id !==
  6783. this.state.selectedLinearElement.elementId
  6784. ) {
  6785. const selectedELements = this.scene.getSelectedElements(this.state);
  6786. // set selectedLinearElement to null if there is more than one element selected since we don't want to show linear element handles
  6787. if (selectedELements.length > 1) {
  6788. this.setState({ selectedLinearElement: null });
  6789. }
  6790. } else {
  6791. const linearElementEditor = LinearElementEditor.handlePointerUp(
  6792. childEvent,
  6793. this.state.selectedLinearElement,
  6794. this.state,
  6795. );
  6796. const { startBindingElement, endBindingElement } =
  6797. linearElementEditor;
  6798. const element = this.scene.getElement(linearElementEditor.elementId);
  6799. if (isBindingElement(element)) {
  6800. bindOrUnbindLinearElement(
  6801. element,
  6802. startBindingElement,
  6803. endBindingElement,
  6804. );
  6805. }
  6806. if (linearElementEditor !== this.state.selectedLinearElement) {
  6807. this.setState({
  6808. selectedLinearElement: {
  6809. ...linearElementEditor,
  6810. selectedPointsIndices: null,
  6811. },
  6812. suggestedBindings: [],
  6813. });
  6814. }
  6815. }
  6816. }
  6817. this.missingPointerEventCleanupEmitter.clear();
  6818. window.removeEventListener(
  6819. EVENT.POINTER_MOVE,
  6820. pointerDownState.eventListeners.onMove!,
  6821. );
  6822. window.removeEventListener(
  6823. EVENT.POINTER_UP,
  6824. pointerDownState.eventListeners.onUp!,
  6825. );
  6826. window.removeEventListener(
  6827. EVENT.KEYDOWN,
  6828. pointerDownState.eventListeners.onKeyDown!,
  6829. );
  6830. window.removeEventListener(
  6831. EVENT.KEYUP,
  6832. pointerDownState.eventListeners.onKeyUp!,
  6833. );
  6834. if (this.state.pendingImageElementId) {
  6835. this.setState({ pendingImageElementId: null });
  6836. }
  6837. this.onPointerUpEmitter.trigger(
  6838. this.state.activeTool,
  6839. pointerDownState,
  6840. childEvent,
  6841. );
  6842. if (draggingElement?.type === "freedraw") {
  6843. const pointerCoords = viewportCoordsToSceneCoords(
  6844. childEvent,
  6845. this.state,
  6846. );
  6847. const points = draggingElement.points;
  6848. let dx = pointerCoords.x - draggingElement.x;
  6849. let dy = pointerCoords.y - draggingElement.y;
  6850. // Allows dots to avoid being flagged as infinitely small
  6851. if (dx === points[0][0] && dy === points[0][1]) {
  6852. dy += 0.0001;
  6853. dx += 0.0001;
  6854. }
  6855. const pressures = draggingElement.simulatePressure
  6856. ? []
  6857. : [...draggingElement.pressures, childEvent.pressure];
  6858. mutateElement(draggingElement, {
  6859. points: [...points, [dx, dy]],
  6860. pressures,
  6861. lastCommittedPoint: [dx, dy],
  6862. });
  6863. this.actionManager.executeAction(actionFinalize);
  6864. return;
  6865. }
  6866. if (isImageElement(draggingElement)) {
  6867. const imageElement = draggingElement;
  6868. try {
  6869. this.initializeImageDimensions(imageElement);
  6870. this.setState(
  6871. {
  6872. selectedElementIds: makeNextSelectedElementIds(
  6873. { [imageElement.id]: true },
  6874. this.state,
  6875. ),
  6876. },
  6877. () => {
  6878. this.actionManager.executeAction(actionFinalize);
  6879. },
  6880. );
  6881. } catch (error: any) {
  6882. console.error(error);
  6883. this.scene.replaceAllElements(
  6884. this.scene
  6885. .getElementsIncludingDeleted()
  6886. .filter((el) => el.id !== imageElement.id),
  6887. );
  6888. this.actionManager.executeAction(actionFinalize);
  6889. }
  6890. return;
  6891. }
  6892. if (isLinearElement(draggingElement)) {
  6893. if (draggingElement!.points.length > 1) {
  6894. this.history.resumeRecording();
  6895. }
  6896. const pointerCoords = viewportCoordsToSceneCoords(
  6897. childEvent,
  6898. this.state,
  6899. );
  6900. if (
  6901. !pointerDownState.drag.hasOccurred &&
  6902. draggingElement &&
  6903. !multiElement
  6904. ) {
  6905. mutateElement(draggingElement, {
  6906. points: [
  6907. ...draggingElement.points,
  6908. [
  6909. pointerCoords.x - draggingElement.x,
  6910. pointerCoords.y - draggingElement.y,
  6911. ],
  6912. ],
  6913. });
  6914. this.setState({
  6915. multiElement: draggingElement,
  6916. editingElement: this.state.draggingElement,
  6917. });
  6918. } else if (pointerDownState.drag.hasOccurred && !multiElement) {
  6919. if (
  6920. isBindingEnabled(this.state) &&
  6921. isBindingElement(draggingElement, false)
  6922. ) {
  6923. maybeBindLinearElement(
  6924. draggingElement,
  6925. this.state,
  6926. this.scene,
  6927. pointerCoords,
  6928. );
  6929. }
  6930. this.setState({ suggestedBindings: [], startBoundElement: null });
  6931. if (!activeTool.locked) {
  6932. resetCursor(this.interactiveCanvas);
  6933. this.setState((prevState) => ({
  6934. draggingElement: null,
  6935. activeTool: updateActiveTool(this.state, {
  6936. type: "selection",
  6937. }),
  6938. selectedElementIds: makeNextSelectedElementIds(
  6939. {
  6940. ...prevState.selectedElementIds,
  6941. [draggingElement.id]: true,
  6942. },
  6943. prevState,
  6944. ),
  6945. selectedLinearElement: new LinearElementEditor(
  6946. draggingElement,
  6947. this.scene,
  6948. ),
  6949. }));
  6950. } else {
  6951. this.setState((prevState) => ({
  6952. draggingElement: null,
  6953. }));
  6954. }
  6955. }
  6956. return;
  6957. }
  6958. if (
  6959. activeTool.type !== "selection" &&
  6960. draggingElement &&
  6961. isInvisiblySmallElement(draggingElement)
  6962. ) {
  6963. // remove invisible element which was added in onPointerDown
  6964. this.scene.replaceAllElements(
  6965. this.scene
  6966. .getElementsIncludingDeleted()
  6967. .filter((el) => el.id !== draggingElement.id),
  6968. );
  6969. this.setState({
  6970. draggingElement: null,
  6971. });
  6972. return;
  6973. }
  6974. if (draggingElement) {
  6975. if (pointerDownState.drag.hasOccurred) {
  6976. const sceneCoords = viewportCoordsToSceneCoords(
  6977. childEvent,
  6978. this.state,
  6979. );
  6980. // when editing the points of a linear element, we check if the
  6981. // linear element still is in the frame afterwards
  6982. // if not, the linear element will be removed from its frame (if any)
  6983. if (
  6984. this.state.selectedLinearElement &&
  6985. this.state.selectedLinearElement.isDragging
  6986. ) {
  6987. const linearElement = this.scene.getElement(
  6988. this.state.selectedLinearElement.elementId,
  6989. );
  6990. if (linearElement?.frameId) {
  6991. const frame = getContainingFrame(linearElement);
  6992. if (frame && linearElement) {
  6993. if (!elementOverlapsWithFrame(linearElement, frame)) {
  6994. // remove the linear element from all groups
  6995. // before removing it from the frame as well
  6996. mutateElement(linearElement, {
  6997. groupIds: [],
  6998. });
  6999. this.scene.replaceAllElements(
  7000. removeElementsFromFrame(
  7001. this.scene.getElementsIncludingDeleted(),
  7002. [linearElement],
  7003. this.state,
  7004. ),
  7005. );
  7006. }
  7007. }
  7008. }
  7009. } else {
  7010. // update the relationships between selected elements and frames
  7011. const topLayerFrame =
  7012. this.getTopLayerFrameAtSceneCoords(sceneCoords);
  7013. const selectedElements = this.scene.getSelectedElements(this.state);
  7014. let nextElements = this.scene.getElementsIncludingDeleted();
  7015. const updateGroupIdsAfterEditingGroup = (
  7016. elements: ExcalidrawElement[],
  7017. ) => {
  7018. if (elements.length > 0) {
  7019. for (const element of elements) {
  7020. const index = element.groupIds.indexOf(
  7021. this.state.editingGroupId!,
  7022. );
  7023. mutateElement(
  7024. element,
  7025. {
  7026. groupIds: element.groupIds.slice(0, index),
  7027. },
  7028. false,
  7029. );
  7030. }
  7031. nextElements.forEach((element) => {
  7032. if (
  7033. element.groupIds.length &&
  7034. getElementsInGroup(
  7035. nextElements,
  7036. element.groupIds[element.groupIds.length - 1],
  7037. ).length < 2
  7038. ) {
  7039. mutateElement(
  7040. element,
  7041. {
  7042. groupIds: [],
  7043. },
  7044. false,
  7045. );
  7046. }
  7047. });
  7048. this.setState({
  7049. editingGroupId: null,
  7050. });
  7051. }
  7052. };
  7053. if (
  7054. topLayerFrame &&
  7055. !this.state.selectedElementIds[topLayerFrame.id]
  7056. ) {
  7057. const elementsToAdd = selectedElements.filter(
  7058. (element) =>
  7059. element.frameId !== topLayerFrame.id &&
  7060. isElementInFrame(element, nextElements, this.state),
  7061. );
  7062. if (this.state.editingGroupId) {
  7063. updateGroupIdsAfterEditingGroup(elementsToAdd);
  7064. }
  7065. nextElements = addElementsToFrame(
  7066. nextElements,
  7067. elementsToAdd,
  7068. topLayerFrame,
  7069. );
  7070. } else if (!topLayerFrame) {
  7071. if (this.state.editingGroupId) {
  7072. const elementsToRemove = selectedElements.filter(
  7073. (element) =>
  7074. element.frameId &&
  7075. !isElementInFrame(element, nextElements, this.state),
  7076. );
  7077. updateGroupIdsAfterEditingGroup(elementsToRemove);
  7078. }
  7079. }
  7080. nextElements = updateFrameMembershipOfSelectedElements(
  7081. nextElements,
  7082. this.state,
  7083. this,
  7084. );
  7085. this.scene.replaceAllElements(nextElements);
  7086. }
  7087. }
  7088. if (isFrameLikeElement(draggingElement)) {
  7089. const elementsInsideFrame = getElementsInNewFrame(
  7090. this.scene.getElementsIncludingDeleted(),
  7091. draggingElement,
  7092. );
  7093. this.scene.replaceAllElements(
  7094. addElementsToFrame(
  7095. this.scene.getElementsIncludingDeleted(),
  7096. elementsInsideFrame,
  7097. draggingElement,
  7098. ),
  7099. );
  7100. }
  7101. mutateElement(
  7102. draggingElement,
  7103. getNormalizedDimensions(draggingElement),
  7104. );
  7105. }
  7106. if (resizingElement) {
  7107. this.history.resumeRecording();
  7108. }
  7109. if (resizingElement && isInvisiblySmallElement(resizingElement)) {
  7110. this.scene.replaceAllElements(
  7111. this.scene
  7112. .getElementsIncludingDeleted()
  7113. .filter((el) => el.id !== resizingElement.id),
  7114. );
  7115. }
  7116. // handle frame membership for resizing frames and/or selected elements
  7117. if (pointerDownState.resize.isResizing) {
  7118. let nextElements = updateFrameMembershipOfSelectedElements(
  7119. this.scene.getElementsIncludingDeleted(),
  7120. this.state,
  7121. this,
  7122. );
  7123. const selectedFrames = this.scene
  7124. .getSelectedElements(this.state)
  7125. .filter((element): element is ExcalidrawFrameLikeElement =>
  7126. isFrameLikeElement(element),
  7127. );
  7128. for (const frame of selectedFrames) {
  7129. nextElements = replaceAllElementsInFrame(
  7130. nextElements,
  7131. getElementsInResizingFrame(
  7132. this.scene.getElementsIncludingDeleted(),
  7133. frame,
  7134. this.state,
  7135. ),
  7136. frame,
  7137. this.state,
  7138. );
  7139. }
  7140. this.scene.replaceAllElements(nextElements);
  7141. }
  7142. // Code below handles selection when element(s) weren't
  7143. // drag or added to selection on pointer down phase.
  7144. const hitElement = pointerDownState.hit.element;
  7145. if (
  7146. this.state.selectedLinearElement?.elementId !== hitElement?.id &&
  7147. isLinearElement(hitElement)
  7148. ) {
  7149. const selectedELements = this.scene.getSelectedElements(this.state);
  7150. // set selectedLinearElement when no other element selected except
  7151. // the one we've hit
  7152. if (selectedELements.length === 1) {
  7153. this.setState({
  7154. selectedLinearElement: new LinearElementEditor(
  7155. hitElement,
  7156. this.scene,
  7157. ),
  7158. });
  7159. }
  7160. }
  7161. const pointerStart = this.lastPointerDownEvent;
  7162. const pointerEnd = this.lastPointerUpEvent || this.lastPointerMoveEvent;
  7163. if (isEraserActive(this.state) && pointerStart && pointerEnd) {
  7164. this.eraserTrail.endPath();
  7165. const draggedDistance = distance2d(
  7166. pointerStart.clientX,
  7167. pointerStart.clientY,
  7168. pointerEnd.clientX,
  7169. pointerEnd.clientY,
  7170. );
  7171. if (draggedDistance === 0) {
  7172. const scenePointer = viewportCoordsToSceneCoords(
  7173. {
  7174. clientX: pointerEnd.clientX,
  7175. clientY: pointerEnd.clientY,
  7176. },
  7177. this.state,
  7178. );
  7179. const hitElements = this.getElementsAtPosition(
  7180. scenePointer.x,
  7181. scenePointer.y,
  7182. );
  7183. hitElements.forEach((hitElement) =>
  7184. this.elementsPendingErasure.add(hitElement.id),
  7185. );
  7186. }
  7187. this.eraseElements();
  7188. return;
  7189. } else if (this.elementsPendingErasure.size) {
  7190. this.restoreReadyToEraseElements();
  7191. }
  7192. if (
  7193. hitElement &&
  7194. !pointerDownState.drag.hasOccurred &&
  7195. !pointerDownState.hit.wasAddedToSelection &&
  7196. // if we're editing a line, pointerup shouldn't switch selection if
  7197. // box selected
  7198. (!this.state.editingLinearElement ||
  7199. !pointerDownState.boxSelection.hasOccurred)
  7200. ) {
  7201. // when inside line editor, shift selects points instead
  7202. if (childEvent.shiftKey && !this.state.editingLinearElement) {
  7203. if (this.state.selectedElementIds[hitElement.id]) {
  7204. if (isSelectedViaGroup(this.state, hitElement)) {
  7205. this.setState((_prevState) => {
  7206. const nextSelectedElementIds = {
  7207. ..._prevState.selectedElementIds,
  7208. };
  7209. // We want to unselect all groups hitElement is part of
  7210. // as well as all elements that are part of the groups
  7211. // hitElement is part of
  7212. for (const groupedElement of hitElement.groupIds.flatMap(
  7213. (groupId) =>
  7214. getElementsInGroup(
  7215. this.scene.getNonDeletedElements(),
  7216. groupId,
  7217. ),
  7218. )) {
  7219. delete nextSelectedElementIds[groupedElement.id];
  7220. }
  7221. return {
  7222. selectedGroupIds: {
  7223. ..._prevState.selectedElementIds,
  7224. ...hitElement.groupIds
  7225. .map((gId) => ({ [gId]: false }))
  7226. .reduce((prev, acc) => ({ ...prev, ...acc }), {}),
  7227. },
  7228. selectedElementIds: makeNextSelectedElementIds(
  7229. nextSelectedElementIds,
  7230. _prevState,
  7231. ),
  7232. };
  7233. });
  7234. // if not dragging a linear element point (outside editor)
  7235. } else if (!this.state.selectedLinearElement?.isDragging) {
  7236. // remove element from selection while
  7237. // keeping prev elements selected
  7238. this.setState((prevState) => {
  7239. const newSelectedElementIds = {
  7240. ...prevState.selectedElementIds,
  7241. };
  7242. delete newSelectedElementIds[hitElement!.id];
  7243. const newSelectedElements = getSelectedElements(
  7244. this.scene.getNonDeletedElements(),
  7245. { selectedElementIds: newSelectedElementIds },
  7246. );
  7247. return {
  7248. ...selectGroupsForSelectedElements(
  7249. {
  7250. editingGroupId: prevState.editingGroupId,
  7251. selectedElementIds: newSelectedElementIds,
  7252. },
  7253. this.scene.getNonDeletedElements(),
  7254. prevState,
  7255. this,
  7256. ),
  7257. // set selectedLinearElement only if thats the only element selected
  7258. selectedLinearElement:
  7259. newSelectedElements.length === 1 &&
  7260. isLinearElement(newSelectedElements[0])
  7261. ? new LinearElementEditor(
  7262. newSelectedElements[0],
  7263. this.scene,
  7264. )
  7265. : prevState.selectedLinearElement,
  7266. };
  7267. });
  7268. }
  7269. } else if (
  7270. hitElement.frameId &&
  7271. this.state.selectedElementIds[hitElement.frameId]
  7272. ) {
  7273. // when hitElement is part of a selected frame, deselect the frame
  7274. // to avoid frame and containing elements selected simultaneously
  7275. this.setState((prevState) => {
  7276. const nextSelectedElementIds: {
  7277. [id: string]: true;
  7278. } = {
  7279. ...prevState.selectedElementIds,
  7280. [hitElement.id]: true,
  7281. };
  7282. // deselect the frame
  7283. delete nextSelectedElementIds[hitElement.frameId!];
  7284. // deselect groups containing the frame
  7285. (this.scene.getElement(hitElement.frameId!)?.groupIds ?? [])
  7286. .flatMap((gid) =>
  7287. getElementsInGroup(this.scene.getNonDeletedElements(), gid),
  7288. )
  7289. .forEach((element) => {
  7290. delete nextSelectedElementIds[element.id];
  7291. });
  7292. return {
  7293. ...selectGroupsForSelectedElements(
  7294. {
  7295. editingGroupId: prevState.editingGroupId,
  7296. selectedElementIds: nextSelectedElementIds,
  7297. },
  7298. this.scene.getNonDeletedElements(),
  7299. prevState,
  7300. this,
  7301. ),
  7302. showHyperlinkPopup:
  7303. hitElement.link || isEmbeddableElement(hitElement)
  7304. ? "info"
  7305. : false,
  7306. };
  7307. });
  7308. } else {
  7309. // add element to selection while keeping prev elements selected
  7310. this.setState((_prevState) => ({
  7311. selectedElementIds: makeNextSelectedElementIds(
  7312. {
  7313. ..._prevState.selectedElementIds,
  7314. [hitElement!.id]: true,
  7315. },
  7316. _prevState,
  7317. ),
  7318. }));
  7319. }
  7320. } else {
  7321. this.setState((prevState) => ({
  7322. ...selectGroupsForSelectedElements(
  7323. {
  7324. editingGroupId: prevState.editingGroupId,
  7325. selectedElementIds: { [hitElement.id]: true },
  7326. },
  7327. this.scene.getNonDeletedElements(),
  7328. prevState,
  7329. this,
  7330. ),
  7331. selectedLinearElement:
  7332. isLinearElement(hitElement) &&
  7333. // Don't set `selectedLinearElement` if its same as the hitElement, this is mainly to prevent resetting the `hoverPointIndex` to -1.
  7334. // Future we should update the API to take care of setting the correct `hoverPointIndex` when initialized
  7335. prevState.selectedLinearElement?.elementId !== hitElement.id
  7336. ? new LinearElementEditor(hitElement, this.scene)
  7337. : prevState.selectedLinearElement,
  7338. }));
  7339. }
  7340. }
  7341. if (
  7342. !pointerDownState.drag.hasOccurred &&
  7343. !this.state.isResizing &&
  7344. ((hitElement &&
  7345. isHittingElementBoundingBoxWithoutHittingElement(
  7346. hitElement,
  7347. this.state,
  7348. this.frameNameBoundsCache,
  7349. pointerDownState.origin.x,
  7350. pointerDownState.origin.y,
  7351. )) ||
  7352. (!hitElement &&
  7353. pointerDownState.hit.hasHitCommonBoundingBoxOfSelectedElements))
  7354. ) {
  7355. if (this.state.editingLinearElement) {
  7356. this.setState({ editingLinearElement: null });
  7357. } else {
  7358. // Deselect selected elements
  7359. this.setState({
  7360. selectedElementIds: makeNextSelectedElementIds({}, this.state),
  7361. selectedGroupIds: {},
  7362. editingGroupId: null,
  7363. activeEmbeddable: null,
  7364. });
  7365. }
  7366. return;
  7367. }
  7368. if (
  7369. !activeTool.locked &&
  7370. activeTool.type !== "freedraw" &&
  7371. draggingElement &&
  7372. draggingElement.type !== "selection"
  7373. ) {
  7374. this.setState((prevState) => ({
  7375. selectedElementIds: makeNextSelectedElementIds(
  7376. {
  7377. ...prevState.selectedElementIds,
  7378. [draggingElement.id]: true,
  7379. },
  7380. prevState,
  7381. ),
  7382. showHyperlinkPopup:
  7383. isEmbeddableElement(draggingElement) && !draggingElement.link
  7384. ? "editor"
  7385. : prevState.showHyperlinkPopup,
  7386. }));
  7387. }
  7388. if (
  7389. activeTool.type !== "selection" ||
  7390. isSomeElementSelected(this.scene.getNonDeletedElements(), this.state)
  7391. ) {
  7392. this.history.resumeRecording();
  7393. }
  7394. if (pointerDownState.drag.hasOccurred || isResizing || isRotating) {
  7395. (isBindingEnabled(this.state)
  7396. ? bindOrUnbindSelectedElements
  7397. : unbindLinearElements)(this.scene.getSelectedElements(this.state));
  7398. }
  7399. if (activeTool.type === "laser") {
  7400. this.laserTrails.endPath();
  7401. return;
  7402. }
  7403. if (!activeTool.locked && activeTool.type !== "freedraw") {
  7404. resetCursor(this.interactiveCanvas);
  7405. this.setState({
  7406. draggingElement: null,
  7407. suggestedBindings: [],
  7408. activeTool: updateActiveTool(this.state, { type: "selection" }),
  7409. });
  7410. } else {
  7411. this.setState({
  7412. draggingElement: null,
  7413. suggestedBindings: [],
  7414. });
  7415. }
  7416. if (
  7417. hitElement &&
  7418. this.lastPointerUpEvent &&
  7419. this.lastPointerDownEvent &&
  7420. this.lastPointerUpEvent.timeStamp -
  7421. this.lastPointerDownEvent.timeStamp <
  7422. 300 &&
  7423. gesture.pointers.size <= 1 &&
  7424. isIframeLikeElement(hitElement) &&
  7425. this.isIframeLikeElementCenter(
  7426. hitElement,
  7427. this.lastPointerUpEvent,
  7428. pointerDownState.origin.x,
  7429. pointerDownState.origin.y,
  7430. )
  7431. ) {
  7432. this.handleEmbeddableCenterClick(hitElement);
  7433. }
  7434. });
  7435. }
  7436. private restoreReadyToEraseElements = () => {
  7437. this.elementsPendingErasure = new Set();
  7438. this.onSceneUpdated();
  7439. };
  7440. private eraseElements = () => {
  7441. let didChange = false;
  7442. const elements = this.scene.getElementsIncludingDeleted().map((ele) => {
  7443. if (
  7444. this.elementsPendingErasure.has(ele.id) ||
  7445. (ele.frameId && this.elementsPendingErasure.has(ele.frameId)) ||
  7446. (isBoundToContainer(ele) &&
  7447. this.elementsPendingErasure.has(ele.containerId))
  7448. ) {
  7449. didChange = true;
  7450. return newElementWith(ele, { isDeleted: true });
  7451. }
  7452. return ele;
  7453. });
  7454. this.elementsPendingErasure = new Set();
  7455. if (didChange) {
  7456. this.history.resumeRecording();
  7457. this.scene.replaceAllElements(elements);
  7458. }
  7459. };
  7460. private initializeImage = async ({
  7461. imageFile,
  7462. imageElement: _imageElement,
  7463. showCursorImagePreview = false,
  7464. }: {
  7465. imageFile: File;
  7466. imageElement: ExcalidrawImageElement;
  7467. showCursorImagePreview?: boolean;
  7468. }) => {
  7469. // at this point this should be guaranteed image file, but we do this check
  7470. // to satisfy TS down the line
  7471. if (!isSupportedImageFile(imageFile)) {
  7472. throw new Error(t("errors.unsupportedFileType"));
  7473. }
  7474. const mimeType = imageFile.type;
  7475. setCursor(this.interactiveCanvas, "wait");
  7476. if (mimeType === MIME_TYPES.svg) {
  7477. try {
  7478. imageFile = SVGStringToFile(
  7479. await normalizeSVG(await imageFile.text()),
  7480. imageFile.name,
  7481. );
  7482. } catch (error: any) {
  7483. console.warn(error);
  7484. throw new Error(t("errors.svgImageInsertError"));
  7485. }
  7486. }
  7487. // generate image id (by default the file digest) before any
  7488. // resizing/compression takes place to keep it more portable
  7489. const fileId = await ((this.props.generateIdForFile?.(
  7490. imageFile,
  7491. ) as Promise<FileId>) || generateIdFromFile(imageFile));
  7492. if (!fileId) {
  7493. console.warn(
  7494. "Couldn't generate file id or the supplied `generateIdForFile` didn't resolve to one.",
  7495. );
  7496. throw new Error(t("errors.imageInsertError"));
  7497. }
  7498. const existingFileData = this.files[fileId];
  7499. if (!existingFileData?.dataURL) {
  7500. try {
  7501. imageFile = await resizeImageFile(imageFile, {
  7502. maxWidthOrHeight: DEFAULT_MAX_IMAGE_WIDTH_OR_HEIGHT,
  7503. });
  7504. } catch (error: any) {
  7505. console.error(
  7506. "Error trying to resizing image file on insertion",
  7507. error,
  7508. );
  7509. }
  7510. if (imageFile.size > MAX_ALLOWED_FILE_BYTES) {
  7511. throw new Error(
  7512. t("errors.fileTooBig", {
  7513. maxSize: `${Math.trunc(MAX_ALLOWED_FILE_BYTES / 1024 / 1024)}MB`,
  7514. }),
  7515. );
  7516. }
  7517. }
  7518. if (showCursorImagePreview) {
  7519. const dataURL = this.files[fileId]?.dataURL;
  7520. // optimization so that we don't unnecessarily resize the original
  7521. // full-size file for cursor preview
  7522. // (it's much faster to convert the resized dataURL to File)
  7523. const resizedFile = dataURL && dataURLToFile(dataURL);
  7524. this.setImagePreviewCursor(resizedFile || imageFile);
  7525. }
  7526. const dataURL =
  7527. this.files[fileId]?.dataURL || (await getDataURL(imageFile));
  7528. const imageElement = mutateElement(
  7529. _imageElement,
  7530. {
  7531. fileId,
  7532. },
  7533. false,
  7534. ) as NonDeleted<InitializedExcalidrawImageElement>;
  7535. return new Promise<NonDeleted<InitializedExcalidrawImageElement>>(
  7536. async (resolve, reject) => {
  7537. try {
  7538. this.files = {
  7539. ...this.files,
  7540. [fileId]: {
  7541. mimeType,
  7542. id: fileId,
  7543. dataURL,
  7544. created: Date.now(),
  7545. lastRetrieved: Date.now(),
  7546. },
  7547. };
  7548. const cachedImageData = this.imageCache.get(fileId);
  7549. if (!cachedImageData) {
  7550. this.addNewImagesToImageCache();
  7551. await this.updateImageCache([imageElement]);
  7552. }
  7553. if (cachedImageData?.image instanceof Promise) {
  7554. await cachedImageData.image;
  7555. }
  7556. if (
  7557. this.state.pendingImageElementId !== imageElement.id &&
  7558. this.state.draggingElement?.id !== imageElement.id
  7559. ) {
  7560. this.initializeImageDimensions(imageElement, true);
  7561. }
  7562. resolve(imageElement);
  7563. } catch (error: any) {
  7564. console.error(error);
  7565. reject(new Error(t("errors.imageInsertError")));
  7566. } finally {
  7567. if (!showCursorImagePreview) {
  7568. resetCursor(this.interactiveCanvas);
  7569. }
  7570. }
  7571. },
  7572. );
  7573. };
  7574. /**
  7575. * inserts image into elements array and rerenders
  7576. */
  7577. private insertImageElement = async (
  7578. imageElement: ExcalidrawImageElement,
  7579. imageFile: File,
  7580. showCursorImagePreview?: boolean,
  7581. ) => {
  7582. // we should be handling all cases upstream, but in case we forget to handle
  7583. // a future case, let's throw here
  7584. if (!this.isToolSupported("image")) {
  7585. this.setState({ errorMessage: t("errors.imageToolNotSupported") });
  7586. return;
  7587. }
  7588. this.scene.addNewElement(imageElement);
  7589. try {
  7590. return await this.initializeImage({
  7591. imageFile,
  7592. imageElement,
  7593. showCursorImagePreview,
  7594. });
  7595. } catch (error: any) {
  7596. mutateElement(imageElement, {
  7597. isDeleted: true,
  7598. });
  7599. this.actionManager.executeAction(actionFinalize);
  7600. this.setState({
  7601. errorMessage: error.message || t("errors.imageInsertError"),
  7602. });
  7603. return null;
  7604. }
  7605. };
  7606. private setImagePreviewCursor = async (imageFile: File) => {
  7607. // mustn't be larger than 128 px
  7608. // https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Basic_User_Interface/Using_URL_values_for_the_cursor_property
  7609. const cursorImageSizePx = 96;
  7610. const imagePreview = await resizeImageFile(imageFile, {
  7611. maxWidthOrHeight: cursorImageSizePx,
  7612. });
  7613. let previewDataURL = await getDataURL(imagePreview);
  7614. // SVG cannot be resized via `resizeImageFile` so we resize by rendering to
  7615. // a small canvas
  7616. if (imageFile.type === MIME_TYPES.svg) {
  7617. const img = await loadHTMLImageElement(previewDataURL);
  7618. let height = Math.min(img.height, cursorImageSizePx);
  7619. let width = height * (img.width / img.height);
  7620. if (width > cursorImageSizePx) {
  7621. width = cursorImageSizePx;
  7622. height = width * (img.height / img.width);
  7623. }
  7624. const canvas = document.createElement("canvas");
  7625. canvas.height = height;
  7626. canvas.width = width;
  7627. const context = canvas.getContext("2d")!;
  7628. context.drawImage(img, 0, 0, width, height);
  7629. previewDataURL = canvas.toDataURL(MIME_TYPES.svg) as DataURL;
  7630. }
  7631. if (this.state.pendingImageElementId) {
  7632. setCursor(this.interactiveCanvas, `url(${previewDataURL}) 4 4, auto`);
  7633. }
  7634. };
  7635. private onImageAction = async ({
  7636. insertOnCanvasDirectly,
  7637. }: {
  7638. insertOnCanvasDirectly: boolean;
  7639. }) => {
  7640. try {
  7641. const clientX = this.state.width / 2 + this.state.offsetLeft;
  7642. const clientY = this.state.height / 2 + this.state.offsetTop;
  7643. const { x, y } = viewportCoordsToSceneCoords(
  7644. { clientX, clientY },
  7645. this.state,
  7646. );
  7647. const imageFile = await fileOpen({
  7648. description: "Image",
  7649. extensions: Object.keys(
  7650. IMAGE_MIME_TYPES,
  7651. ) as (keyof typeof IMAGE_MIME_TYPES)[],
  7652. });
  7653. const imageElement = this.createImageElement({
  7654. sceneX: x,
  7655. sceneY: y,
  7656. addToFrameUnderCursor: false,
  7657. });
  7658. if (insertOnCanvasDirectly) {
  7659. this.insertImageElement(imageElement, imageFile);
  7660. this.initializeImageDimensions(imageElement);
  7661. this.setState(
  7662. {
  7663. selectedElementIds: makeNextSelectedElementIds(
  7664. { [imageElement.id]: true },
  7665. this.state,
  7666. ),
  7667. },
  7668. () => {
  7669. this.actionManager.executeAction(actionFinalize);
  7670. },
  7671. );
  7672. } else {
  7673. this.setState(
  7674. {
  7675. pendingImageElementId: imageElement.id,
  7676. },
  7677. () => {
  7678. this.insertImageElement(
  7679. imageElement,
  7680. imageFile,
  7681. /* showCursorImagePreview */ true,
  7682. );
  7683. },
  7684. );
  7685. }
  7686. } catch (error: any) {
  7687. if (error.name !== "AbortError") {
  7688. console.error(error);
  7689. } else {
  7690. console.warn(error);
  7691. }
  7692. this.setState(
  7693. {
  7694. pendingImageElementId: null,
  7695. editingElement: null,
  7696. activeTool: updateActiveTool(this.state, { type: "selection" }),
  7697. },
  7698. () => {
  7699. this.actionManager.executeAction(actionFinalize);
  7700. },
  7701. );
  7702. }
  7703. };
  7704. private initializeImageDimensions = (
  7705. imageElement: ExcalidrawImageElement,
  7706. forceNaturalSize = false,
  7707. ) => {
  7708. const image =
  7709. isInitializedImageElement(imageElement) &&
  7710. this.imageCache.get(imageElement.fileId)?.image;
  7711. if (!image || image instanceof Promise) {
  7712. if (
  7713. imageElement.width < DRAGGING_THRESHOLD / this.state.zoom.value &&
  7714. imageElement.height < DRAGGING_THRESHOLD / this.state.zoom.value
  7715. ) {
  7716. const placeholderSize = 100 / this.state.zoom.value;
  7717. mutateElement(imageElement, {
  7718. x: imageElement.x - placeholderSize / 2,
  7719. y: imageElement.y - placeholderSize / 2,
  7720. width: placeholderSize,
  7721. height: placeholderSize,
  7722. });
  7723. }
  7724. return;
  7725. }
  7726. if (
  7727. forceNaturalSize ||
  7728. // if user-created bounding box is below threshold, assume the
  7729. // intention was to click instead of drag, and use the image's
  7730. // intrinsic size
  7731. (imageElement.width < DRAGGING_THRESHOLD / this.state.zoom.value &&
  7732. imageElement.height < DRAGGING_THRESHOLD / this.state.zoom.value)
  7733. ) {
  7734. const minHeight = Math.max(this.state.height - 120, 160);
  7735. // max 65% of canvas height, clamped to <300px, vh - 120px>
  7736. const maxHeight = Math.min(
  7737. minHeight,
  7738. Math.floor(this.state.height * 0.5) / this.state.zoom.value,
  7739. );
  7740. const height = Math.min(image.naturalHeight, maxHeight);
  7741. const width = height * (image.naturalWidth / image.naturalHeight);
  7742. // add current imageElement width/height to account for previous centering
  7743. // of the placeholder image
  7744. const x = imageElement.x + imageElement.width / 2 - width / 2;
  7745. const y = imageElement.y + imageElement.height / 2 - height / 2;
  7746. mutateElement(imageElement, { x, y, width, height });
  7747. }
  7748. };
  7749. /** updates image cache, refreshing updated elements and/or setting status
  7750. to error for images that fail during <img> element creation */
  7751. private updateImageCache = async (
  7752. elements: readonly InitializedExcalidrawImageElement[],
  7753. files = this.files,
  7754. ) => {
  7755. const { updatedFiles, erroredFiles } = await _updateImageCache({
  7756. imageCache: this.imageCache,
  7757. fileIds: elements.map((element) => element.fileId),
  7758. files,
  7759. });
  7760. if (updatedFiles.size || erroredFiles.size) {
  7761. for (const element of elements) {
  7762. if (updatedFiles.has(element.fileId)) {
  7763. ShapeCache.delete(element);
  7764. }
  7765. }
  7766. }
  7767. if (erroredFiles.size) {
  7768. this.scene.replaceAllElements(
  7769. this.scene.getElementsIncludingDeleted().map((element) => {
  7770. if (
  7771. isInitializedImageElement(element) &&
  7772. erroredFiles.has(element.fileId)
  7773. ) {
  7774. return newElementWith(element, {
  7775. status: "error",
  7776. });
  7777. }
  7778. return element;
  7779. }),
  7780. );
  7781. }
  7782. return { updatedFiles, erroredFiles };
  7783. };
  7784. /** adds new images to imageCache and re-renders if needed */
  7785. private addNewImagesToImageCache = async (
  7786. imageElements: InitializedExcalidrawImageElement[] = getInitializedImageElements(
  7787. this.scene.getNonDeletedElements(),
  7788. ),
  7789. files: BinaryFiles = this.files,
  7790. ) => {
  7791. const uncachedImageElements = imageElements.filter(
  7792. (element) => !element.isDeleted && !this.imageCache.has(element.fileId),
  7793. );
  7794. if (uncachedImageElements.length) {
  7795. const { updatedFiles } = await this.updateImageCache(
  7796. uncachedImageElements,
  7797. files,
  7798. );
  7799. if (updatedFiles.size) {
  7800. this.scene.informMutation();
  7801. }
  7802. }
  7803. };
  7804. /** generally you should use `addNewImagesToImageCache()` directly if you need
  7805. * to render new images. This is just a failsafe */
  7806. private scheduleImageRefresh = throttle(() => {
  7807. this.addNewImagesToImageCache();
  7808. }, IMAGE_RENDER_TIMEOUT);
  7809. private updateBindingEnabledOnPointerMove = (
  7810. event: React.PointerEvent<HTMLElement>,
  7811. ) => {
  7812. const shouldEnableBinding = shouldEnableBindingForPointerEvent(event);
  7813. if (this.state.isBindingEnabled !== shouldEnableBinding) {
  7814. this.setState({ isBindingEnabled: shouldEnableBinding });
  7815. }
  7816. };
  7817. private maybeSuggestBindingAtCursor = (pointerCoords: {
  7818. x: number;
  7819. y: number;
  7820. }): void => {
  7821. const hoveredBindableElement = getHoveredElementForBinding(
  7822. pointerCoords,
  7823. this.scene,
  7824. );
  7825. this.setState({
  7826. suggestedBindings:
  7827. hoveredBindableElement != null ? [hoveredBindableElement] : [],
  7828. });
  7829. };
  7830. private maybeSuggestBindingsForLinearElementAtCoords = (
  7831. linearElement: NonDeleted<ExcalidrawLinearElement>,
  7832. /** scene coords */
  7833. pointerCoords: {
  7834. x: number;
  7835. y: number;
  7836. }[],
  7837. // During line creation the start binding hasn't been written yet
  7838. // into `linearElement`
  7839. oppositeBindingBoundElement?: ExcalidrawBindableElement | null,
  7840. ): void => {
  7841. if (!pointerCoords.length) {
  7842. return;
  7843. }
  7844. const suggestedBindings = pointerCoords.reduce(
  7845. (acc: NonDeleted<ExcalidrawBindableElement>[], coords) => {
  7846. const hoveredBindableElement = getHoveredElementForBinding(
  7847. coords,
  7848. this.scene,
  7849. );
  7850. if (
  7851. hoveredBindableElement != null &&
  7852. !isLinearElementSimpleAndAlreadyBound(
  7853. linearElement,
  7854. oppositeBindingBoundElement?.id,
  7855. hoveredBindableElement,
  7856. )
  7857. ) {
  7858. acc.push(hoveredBindableElement);
  7859. }
  7860. return acc;
  7861. },
  7862. [],
  7863. );
  7864. this.setState({ suggestedBindings });
  7865. };
  7866. private maybeSuggestBindingForAll(
  7867. selectedElements: NonDeleted<ExcalidrawElement>[],
  7868. ): void {
  7869. if (selectedElements.length > 50) {
  7870. return;
  7871. }
  7872. const suggestedBindings = getEligibleElementsForBinding(selectedElements);
  7873. this.setState({ suggestedBindings });
  7874. }
  7875. private clearSelection(hitElement: ExcalidrawElement | null): void {
  7876. this.setState((prevState) => ({
  7877. selectedElementIds: makeNextSelectedElementIds({}, prevState),
  7878. activeEmbeddable: null,
  7879. selectedGroupIds: {},
  7880. // Continue editing the same group if the user selected a different
  7881. // element from it
  7882. editingGroupId:
  7883. prevState.editingGroupId &&
  7884. hitElement != null &&
  7885. isElementInGroup(hitElement, prevState.editingGroupId)
  7886. ? prevState.editingGroupId
  7887. : null,
  7888. }));
  7889. this.setState({
  7890. selectedElementIds: makeNextSelectedElementIds({}, this.state),
  7891. activeEmbeddable: null,
  7892. previousSelectedElementIds: this.state.selectedElementIds,
  7893. });
  7894. }
  7895. private handleInteractiveCanvasRef = (canvas: HTMLCanvasElement | null) => {
  7896. // canvas is null when unmounting
  7897. if (canvas !== null) {
  7898. this.interactiveCanvas = canvas;
  7899. // -----------------------------------------------------------------------
  7900. // NOTE wheel, touchstart, touchend events must be registered outside
  7901. // of react because react binds them them passively (so we can't prevent
  7902. // default on them)
  7903. this.interactiveCanvas.addEventListener(EVENT.WHEEL, this.handleWheel);
  7904. this.interactiveCanvas.addEventListener(
  7905. EVENT.TOUCH_START,
  7906. this.onTouchStart,
  7907. );
  7908. this.interactiveCanvas.addEventListener(EVENT.TOUCH_END, this.onTouchEnd);
  7909. // -----------------------------------------------------------------------
  7910. } else {
  7911. this.interactiveCanvas?.removeEventListener(
  7912. EVENT.WHEEL,
  7913. this.handleWheel,
  7914. );
  7915. this.interactiveCanvas?.removeEventListener(
  7916. EVENT.TOUCH_START,
  7917. this.onTouchStart,
  7918. );
  7919. this.interactiveCanvas?.removeEventListener(
  7920. EVENT.TOUCH_END,
  7921. this.onTouchEnd,
  7922. );
  7923. }
  7924. };
  7925. private handleAppOnDrop = async (event: React.DragEvent<HTMLDivElement>) => {
  7926. // must be retrieved first, in the same frame
  7927. const { file, fileHandle } = await getFileFromEvent(event);
  7928. const { x: sceneX, y: sceneY } = viewportCoordsToSceneCoords(
  7929. event,
  7930. this.state,
  7931. );
  7932. try {
  7933. // if image tool not supported, don't show an error here and let it fall
  7934. // through so we still support importing scene data from images. If no
  7935. // scene data encoded, we'll show an error then
  7936. if (isSupportedImageFile(file) && this.isToolSupported("image")) {
  7937. // first attempt to decode scene from the image if it's embedded
  7938. // ---------------------------------------------------------------------
  7939. if (file?.type === MIME_TYPES.png || file?.type === MIME_TYPES.svg) {
  7940. try {
  7941. const scene = await loadFromBlob(
  7942. file,
  7943. this.state,
  7944. this.scene.getElementsIncludingDeleted(),
  7945. fileHandle,
  7946. );
  7947. this.syncActionResult({
  7948. ...scene,
  7949. appState: {
  7950. ...(scene.appState || this.state),
  7951. isLoading: false,
  7952. },
  7953. replaceFiles: true,
  7954. commitToHistory: true,
  7955. });
  7956. return;
  7957. } catch (error: any) {
  7958. if (error.name !== "EncodingError") {
  7959. throw error;
  7960. }
  7961. }
  7962. }
  7963. // if no scene is embedded or we fail for whatever reason, fall back
  7964. // to importing as regular image
  7965. // ---------------------------------------------------------------------
  7966. const imageElement = this.createImageElement({ sceneX, sceneY });
  7967. this.insertImageElement(imageElement, file);
  7968. this.initializeImageDimensions(imageElement);
  7969. this.setState({
  7970. selectedElementIds: makeNextSelectedElementIds(
  7971. { [imageElement.id]: true },
  7972. this.state,
  7973. ),
  7974. });
  7975. return;
  7976. }
  7977. } catch (error: any) {
  7978. return this.setState({
  7979. isLoading: false,
  7980. errorMessage: error.message,
  7981. });
  7982. }
  7983. const libraryJSON = event.dataTransfer.getData(MIME_TYPES.excalidrawlib);
  7984. if (libraryJSON && typeof libraryJSON === "string") {
  7985. try {
  7986. const libraryItems = parseLibraryJSON(libraryJSON);
  7987. this.addElementsFromPasteOrLibrary({
  7988. elements: distributeLibraryItemsOnSquareGrid(libraryItems),
  7989. position: event,
  7990. files: null,
  7991. });
  7992. } catch (error: any) {
  7993. this.setState({ errorMessage: error.message });
  7994. }
  7995. return;
  7996. }
  7997. if (file) {
  7998. // Attempt to parse an excalidraw/excalidrawlib file
  7999. await this.loadFileToCanvas(file, fileHandle);
  8000. }
  8001. if (event.dataTransfer?.types?.includes("text/plain")) {
  8002. const text = event.dataTransfer?.getData("text");
  8003. if (
  8004. text &&
  8005. embeddableURLValidator(text, this.props.validateEmbeddable) &&
  8006. (/^(http|https):\/\/[^\s/$.?#].[^\s]*$/.test(text) ||
  8007. getEmbedLink(text)?.type === "video")
  8008. ) {
  8009. const embeddable = this.insertEmbeddableElement({
  8010. sceneX,
  8011. sceneY,
  8012. link: normalizeLink(text),
  8013. });
  8014. if (embeddable) {
  8015. this.setState({ selectedElementIds: { [embeddable.id]: true } });
  8016. }
  8017. }
  8018. }
  8019. };
  8020. loadFileToCanvas = async (
  8021. file: File,
  8022. fileHandle: FileSystemHandle | null,
  8023. ) => {
  8024. file = await normalizeFile(file);
  8025. try {
  8026. const ret = await loadSceneOrLibraryFromBlob(
  8027. file,
  8028. this.state,
  8029. this.scene.getElementsIncludingDeleted(),
  8030. fileHandle,
  8031. );
  8032. if (ret.type === MIME_TYPES.excalidraw) {
  8033. this.setState({ isLoading: true });
  8034. this.syncActionResult({
  8035. ...ret.data,
  8036. appState: {
  8037. ...(ret.data.appState || this.state),
  8038. isLoading: false,
  8039. },
  8040. replaceFiles: true,
  8041. commitToHistory: true,
  8042. });
  8043. } else if (ret.type === MIME_TYPES.excalidrawlib) {
  8044. await this.library
  8045. .updateLibrary({
  8046. libraryItems: file,
  8047. merge: true,
  8048. openLibraryMenu: true,
  8049. })
  8050. .catch((error) => {
  8051. console.error(error);
  8052. this.setState({ errorMessage: t("errors.importLibraryError") });
  8053. });
  8054. }
  8055. } catch (error: any) {
  8056. if (
  8057. error instanceof ImageSceneDataError &&
  8058. error.code === "IMAGE_NOT_CONTAINS_SCENE_DATA" &&
  8059. !this.isToolSupported("image")
  8060. ) {
  8061. this.setState({
  8062. isLoading: false,
  8063. errorMessage: t("errors.imageToolNotSupported"),
  8064. });
  8065. return;
  8066. }
  8067. this.setState({ isLoading: false, errorMessage: error.message });
  8068. }
  8069. };
  8070. private handleCanvasContextMenu = (
  8071. event: React.MouseEvent<HTMLElement | HTMLCanvasElement>,
  8072. ) => {
  8073. event.preventDefault();
  8074. if (
  8075. (("pointerType" in event.nativeEvent &&
  8076. event.nativeEvent.pointerType === "touch") ||
  8077. ("pointerType" in event.nativeEvent &&
  8078. event.nativeEvent.pointerType === "pen" &&
  8079. // always allow if user uses a pen secondary button
  8080. event.button !== POINTER_BUTTON.SECONDARY)) &&
  8081. this.state.activeTool.type !== "selection"
  8082. ) {
  8083. return;
  8084. }
  8085. const { x, y } = viewportCoordsToSceneCoords(event, this.state);
  8086. const element = this.getElementAtPosition(x, y, {
  8087. preferSelected: true,
  8088. includeLockedElements: true,
  8089. });
  8090. const selectedElements = this.scene.getSelectedElements(this.state);
  8091. const isHittingCommonBoundBox =
  8092. this.isHittingCommonBoundingBoxOfSelectedElements(
  8093. { x, y },
  8094. selectedElements,
  8095. );
  8096. const type = element || isHittingCommonBoundBox ? "element" : "canvas";
  8097. const container = this.excalidrawContainerRef.current!;
  8098. const { top: offsetTop, left: offsetLeft } =
  8099. container.getBoundingClientRect();
  8100. const left = event.clientX - offsetLeft;
  8101. const top = event.clientY - offsetTop;
  8102. trackEvent("contextMenu", "openContextMenu", type);
  8103. this.setState(
  8104. {
  8105. ...(element && !this.state.selectedElementIds[element.id]
  8106. ? {
  8107. ...this.state,
  8108. ...selectGroupsForSelectedElements(
  8109. {
  8110. editingGroupId: this.state.editingGroupId,
  8111. selectedElementIds: { [element.id]: true },
  8112. },
  8113. this.scene.getNonDeletedElements(),
  8114. this.state,
  8115. this,
  8116. ),
  8117. selectedLinearElement: isLinearElement(element)
  8118. ? new LinearElementEditor(element, this.scene)
  8119. : null,
  8120. }
  8121. : this.state),
  8122. showHyperlinkPopup: false,
  8123. },
  8124. () => {
  8125. this.setState({
  8126. contextMenu: { top, left, items: this.getContextMenuItems(type) },
  8127. });
  8128. },
  8129. );
  8130. };
  8131. private maybeDragNewGenericElement = (
  8132. pointerDownState: PointerDownState,
  8133. event: MouseEvent | KeyboardEvent,
  8134. ): void => {
  8135. const draggingElement = this.state.draggingElement;
  8136. const pointerCoords = pointerDownState.lastCoords;
  8137. if (!draggingElement) {
  8138. return;
  8139. }
  8140. if (
  8141. draggingElement.type === "selection" &&
  8142. this.state.activeTool.type !== "eraser"
  8143. ) {
  8144. dragNewElement(
  8145. draggingElement,
  8146. this.state.activeTool.type,
  8147. pointerDownState.origin.x,
  8148. pointerDownState.origin.y,
  8149. pointerCoords.x,
  8150. pointerCoords.y,
  8151. distance(pointerDownState.origin.x, pointerCoords.x),
  8152. distance(pointerDownState.origin.y, pointerCoords.y),
  8153. shouldMaintainAspectRatio(event),
  8154. shouldResizeFromCenter(event),
  8155. );
  8156. } else {
  8157. let [gridX, gridY] = getGridPoint(
  8158. pointerCoords.x,
  8159. pointerCoords.y,
  8160. event[KEYS.CTRL_OR_CMD] ? null : this.state.gridSize,
  8161. );
  8162. const image =
  8163. isInitializedImageElement(draggingElement) &&
  8164. this.imageCache.get(draggingElement.fileId)?.image;
  8165. const aspectRatio =
  8166. image && !(image instanceof Promise)
  8167. ? image.width / image.height
  8168. : null;
  8169. this.maybeCacheReferenceSnapPoints(event, [draggingElement]);
  8170. const { snapOffset, snapLines } = snapNewElement(
  8171. draggingElement,
  8172. this.state,
  8173. event,
  8174. {
  8175. x:
  8176. pointerDownState.originInGrid.x +
  8177. (this.state.originSnapOffset?.x ?? 0),
  8178. y:
  8179. pointerDownState.originInGrid.y +
  8180. (this.state.originSnapOffset?.y ?? 0),
  8181. },
  8182. {
  8183. x: gridX - pointerDownState.originInGrid.x,
  8184. y: gridY - pointerDownState.originInGrid.y,
  8185. },
  8186. );
  8187. gridX += snapOffset.x;
  8188. gridY += snapOffset.y;
  8189. this.setState({
  8190. snapLines,
  8191. });
  8192. dragNewElement(
  8193. draggingElement,
  8194. this.state.activeTool.type,
  8195. pointerDownState.originInGrid.x,
  8196. pointerDownState.originInGrid.y,
  8197. gridX,
  8198. gridY,
  8199. distance(pointerDownState.originInGrid.x, gridX),
  8200. distance(pointerDownState.originInGrid.y, gridY),
  8201. isImageElement(draggingElement)
  8202. ? !shouldMaintainAspectRatio(event)
  8203. : shouldMaintainAspectRatio(event),
  8204. shouldResizeFromCenter(event),
  8205. aspectRatio,
  8206. this.state.originSnapOffset,
  8207. );
  8208. this.maybeSuggestBindingForAll([draggingElement]);
  8209. // highlight elements that are to be added to frames on frames creation
  8210. if (
  8211. this.state.activeTool.type === TOOL_TYPE.frame ||
  8212. this.state.activeTool.type === TOOL_TYPE.magicframe
  8213. ) {
  8214. this.setState({
  8215. elementsToHighlight: getElementsInResizingFrame(
  8216. this.scene.getNonDeletedElements(),
  8217. draggingElement as ExcalidrawFrameLikeElement,
  8218. this.state,
  8219. ),
  8220. });
  8221. }
  8222. }
  8223. };
  8224. private maybeHandleResize = (
  8225. pointerDownState: PointerDownState,
  8226. event: MouseEvent | KeyboardEvent,
  8227. ): boolean => {
  8228. const selectedElements = this.scene.getSelectedElements(this.state);
  8229. const selectedFrames = selectedElements.filter(
  8230. (element): element is ExcalidrawFrameLikeElement =>
  8231. isFrameLikeElement(element),
  8232. );
  8233. const transformHandleType = pointerDownState.resize.handleType;
  8234. if (selectedFrames.length > 0 && transformHandleType === "rotation") {
  8235. return false;
  8236. }
  8237. this.setState({
  8238. // TODO: rename this state field to "isScaling" to distinguish
  8239. // it from the generic "isResizing" which includes scaling and
  8240. // rotating
  8241. isResizing: transformHandleType && transformHandleType !== "rotation",
  8242. isRotating: transformHandleType === "rotation",
  8243. activeEmbeddable: null,
  8244. });
  8245. const pointerCoords = pointerDownState.lastCoords;
  8246. let [resizeX, resizeY] = getGridPoint(
  8247. pointerCoords.x - pointerDownState.resize.offset.x,
  8248. pointerCoords.y - pointerDownState.resize.offset.y,
  8249. event[KEYS.CTRL_OR_CMD] ? null : this.state.gridSize,
  8250. );
  8251. const frameElementsOffsetsMap = new Map<
  8252. string,
  8253. {
  8254. x: number;
  8255. y: number;
  8256. }
  8257. >();
  8258. selectedFrames.forEach((frame) => {
  8259. const elementsInFrame = getFrameChildren(
  8260. this.scene.getNonDeletedElements(),
  8261. frame.id,
  8262. );
  8263. elementsInFrame.forEach((element) => {
  8264. frameElementsOffsetsMap.set(frame.id + element.id, {
  8265. x: element.x - frame.x,
  8266. y: element.y - frame.y,
  8267. });
  8268. });
  8269. });
  8270. // check needed for avoiding flickering when a key gets pressed
  8271. // during dragging
  8272. if (!this.state.selectedElementsAreBeingDragged) {
  8273. const [gridX, gridY] = getGridPoint(
  8274. pointerCoords.x,
  8275. pointerCoords.y,
  8276. event[KEYS.CTRL_OR_CMD] ? null : this.state.gridSize,
  8277. );
  8278. const dragOffset = {
  8279. x: gridX - pointerDownState.originInGrid.x,
  8280. y: gridY - pointerDownState.originInGrid.y,
  8281. };
  8282. const originalElements = [...pointerDownState.originalElements.values()];
  8283. this.maybeCacheReferenceSnapPoints(event, selectedElements);
  8284. const { snapOffset, snapLines } = snapResizingElements(
  8285. selectedElements,
  8286. getSelectedElements(originalElements, this.state),
  8287. this.state,
  8288. event,
  8289. dragOffset,
  8290. transformHandleType,
  8291. );
  8292. resizeX += snapOffset.x;
  8293. resizeY += snapOffset.y;
  8294. this.setState({
  8295. snapLines,
  8296. });
  8297. }
  8298. if (
  8299. transformElements(
  8300. pointerDownState,
  8301. transformHandleType,
  8302. selectedElements,
  8303. pointerDownState.resize.arrowDirection,
  8304. shouldRotateWithDiscreteAngle(event),
  8305. shouldResizeFromCenter(event),
  8306. selectedElements.length === 1 && isImageElement(selectedElements[0])
  8307. ? !shouldMaintainAspectRatio(event)
  8308. : shouldMaintainAspectRatio(event),
  8309. resizeX,
  8310. resizeY,
  8311. pointerDownState.resize.center.x,
  8312. pointerDownState.resize.center.y,
  8313. this.state,
  8314. )
  8315. ) {
  8316. this.maybeSuggestBindingForAll(selectedElements);
  8317. const elementsToHighlight = new Set<ExcalidrawElement>();
  8318. selectedFrames.forEach((frame) => {
  8319. getElementsInResizingFrame(
  8320. this.scene.getNonDeletedElements(),
  8321. frame,
  8322. this.state,
  8323. ).forEach((element) => elementsToHighlight.add(element));
  8324. });
  8325. this.setState({
  8326. elementsToHighlight: [...elementsToHighlight],
  8327. });
  8328. return true;
  8329. }
  8330. return false;
  8331. };
  8332. private getContextMenuItems = (
  8333. type: "canvas" | "element",
  8334. ): ContextMenuItems => {
  8335. const options: ContextMenuItems = [];
  8336. options.push(actionCopyAsPng, actionCopyAsSvg);
  8337. // canvas contextMenu
  8338. // -------------------------------------------------------------------------
  8339. if (type === "canvas") {
  8340. if (this.state.viewModeEnabled) {
  8341. return [
  8342. ...options,
  8343. actionToggleGridMode,
  8344. actionToggleZenMode,
  8345. actionToggleViewMode,
  8346. actionToggleStats,
  8347. ];
  8348. }
  8349. return [
  8350. actionPaste,
  8351. CONTEXT_MENU_SEPARATOR,
  8352. actionCopyAsPng,
  8353. actionCopyAsSvg,
  8354. copyText,
  8355. CONTEXT_MENU_SEPARATOR,
  8356. actionSelectAll,
  8357. actionUnlockAllElements,
  8358. CONTEXT_MENU_SEPARATOR,
  8359. actionToggleGridMode,
  8360. actionToggleObjectsSnapMode,
  8361. actionToggleZenMode,
  8362. actionToggleViewMode,
  8363. actionToggleStats,
  8364. ];
  8365. }
  8366. // element contextMenu
  8367. // -------------------------------------------------------------------------
  8368. options.push(copyText);
  8369. if (this.state.viewModeEnabled) {
  8370. return [actionCopy, ...options];
  8371. }
  8372. return [
  8373. actionCut,
  8374. actionCopy,
  8375. actionPaste,
  8376. actionSelectAllElementsInFrame,
  8377. actionRemoveAllElementsFromFrame,
  8378. CONTEXT_MENU_SEPARATOR,
  8379. ...options,
  8380. CONTEXT_MENU_SEPARATOR,
  8381. actionCopyStyles,
  8382. actionPasteStyles,
  8383. CONTEXT_MENU_SEPARATOR,
  8384. actionGroup,
  8385. actionUnbindText,
  8386. actionBindText,
  8387. actionWrapTextInContainer,
  8388. actionUngroup,
  8389. CONTEXT_MENU_SEPARATOR,
  8390. actionAddToLibrary,
  8391. CONTEXT_MENU_SEPARATOR,
  8392. actionSendBackward,
  8393. actionBringForward,
  8394. actionSendToBack,
  8395. actionBringToFront,
  8396. CONTEXT_MENU_SEPARATOR,
  8397. actionFlipHorizontal,
  8398. actionFlipVertical,
  8399. CONTEXT_MENU_SEPARATOR,
  8400. actionToggleLinearEditor,
  8401. actionLink,
  8402. actionDuplicateSelection,
  8403. actionToggleElementLock,
  8404. CONTEXT_MENU_SEPARATOR,
  8405. actionDeleteSelected,
  8406. ];
  8407. };
  8408. private handleWheel = withBatchedUpdates(
  8409. (
  8410. event: WheelEvent | React.WheelEvent<HTMLDivElement | HTMLCanvasElement>,
  8411. ) => {
  8412. event.preventDefault();
  8413. if (isPanning) {
  8414. return;
  8415. }
  8416. const { deltaX, deltaY } = event;
  8417. // note that event.ctrlKey is necessary to handle pinch zooming
  8418. if (event.metaKey || event.ctrlKey) {
  8419. const sign = Math.sign(deltaY);
  8420. const MAX_STEP = ZOOM_STEP * 100;
  8421. const absDelta = Math.abs(deltaY);
  8422. let delta = deltaY;
  8423. if (absDelta > MAX_STEP) {
  8424. delta = MAX_STEP * sign;
  8425. }
  8426. let newZoom = this.state.zoom.value - delta / 100;
  8427. // increase zoom steps the more zoomed-in we are (applies to >100% only)
  8428. newZoom +=
  8429. Math.log10(Math.max(1, this.state.zoom.value)) *
  8430. -sign *
  8431. // reduced amplification for small deltas (small movements on a trackpad)
  8432. Math.min(1, absDelta / 20);
  8433. this.translateCanvas((state) => ({
  8434. ...getStateForZoom(
  8435. {
  8436. viewportX: this.lastViewportPosition.x,
  8437. viewportY: this.lastViewportPosition.y,
  8438. nextZoom: getNormalizedZoom(newZoom),
  8439. },
  8440. state,
  8441. ),
  8442. shouldCacheIgnoreZoom: true,
  8443. }));
  8444. this.resetShouldCacheIgnoreZoomDebounced();
  8445. return;
  8446. }
  8447. // scroll horizontally when shift pressed
  8448. if (event.shiftKey) {
  8449. this.translateCanvas(({ zoom, scrollX }) => ({
  8450. // on Mac, shift+wheel tends to result in deltaX
  8451. scrollX: scrollX - (deltaY || deltaX) / zoom.value,
  8452. }));
  8453. return;
  8454. }
  8455. this.translateCanvas(({ zoom, scrollX, scrollY }) => ({
  8456. scrollX: scrollX - deltaX / zoom.value,
  8457. scrollY: scrollY - deltaY / zoom.value,
  8458. }));
  8459. },
  8460. );
  8461. private getTextWysiwygSnappedToCenterPosition(
  8462. x: number,
  8463. y: number,
  8464. appState: AppState,
  8465. container?: ExcalidrawTextContainer | null,
  8466. ) {
  8467. if (container) {
  8468. let elementCenterX = container.x + container.width / 2;
  8469. let elementCenterY = container.y + container.height / 2;
  8470. const elementCenter = getContainerCenter(container, appState);
  8471. if (elementCenter) {
  8472. elementCenterX = elementCenter.x;
  8473. elementCenterY = elementCenter.y;
  8474. }
  8475. const distanceToCenter = Math.hypot(
  8476. x - elementCenterX,
  8477. y - elementCenterY,
  8478. );
  8479. const isSnappedToCenter =
  8480. distanceToCenter < TEXT_TO_CENTER_SNAP_THRESHOLD;
  8481. if (isSnappedToCenter) {
  8482. const { x: viewportX, y: viewportY } = sceneCoordsToViewportCoords(
  8483. { sceneX: elementCenterX, sceneY: elementCenterY },
  8484. appState,
  8485. );
  8486. return { viewportX, viewportY, elementCenterX, elementCenterY };
  8487. }
  8488. }
  8489. }
  8490. private savePointer = (x: number, y: number, button: "up" | "down") => {
  8491. if (!x || !y) {
  8492. return;
  8493. }
  8494. const { x: sceneX, y: sceneY } = viewportCoordsToSceneCoords(
  8495. { clientX: x, clientY: y },
  8496. this.state,
  8497. );
  8498. if (isNaN(sceneX) || isNaN(sceneY)) {
  8499. // sometimes the pointer goes off screen
  8500. }
  8501. const pointer: CollaboratorPointer = {
  8502. x: sceneX,
  8503. y: sceneY,
  8504. tool: this.state.activeTool.type === "laser" ? "laser" : "pointer",
  8505. };
  8506. this.props.onPointerUpdate?.({
  8507. pointer,
  8508. button,
  8509. pointersMap: gesture.pointers,
  8510. });
  8511. };
  8512. private resetShouldCacheIgnoreZoomDebounced = debounce(() => {
  8513. if (!this.unmounted) {
  8514. this.setState({ shouldCacheIgnoreZoom: false });
  8515. }
  8516. }, 300);
  8517. private updateDOMRect = (cb?: () => void) => {
  8518. if (this.excalidrawContainerRef?.current) {
  8519. const excalidrawContainer = this.excalidrawContainerRef.current;
  8520. const {
  8521. width,
  8522. height,
  8523. left: offsetLeft,
  8524. top: offsetTop,
  8525. } = excalidrawContainer.getBoundingClientRect();
  8526. const {
  8527. width: currentWidth,
  8528. height: currentHeight,
  8529. offsetTop: currentOffsetTop,
  8530. offsetLeft: currentOffsetLeft,
  8531. } = this.state;
  8532. if (
  8533. width === currentWidth &&
  8534. height === currentHeight &&
  8535. offsetLeft === currentOffsetLeft &&
  8536. offsetTop === currentOffsetTop
  8537. ) {
  8538. if (cb) {
  8539. cb();
  8540. }
  8541. return;
  8542. }
  8543. this.setState(
  8544. {
  8545. width,
  8546. height,
  8547. offsetLeft,
  8548. offsetTop,
  8549. },
  8550. () => {
  8551. cb && cb();
  8552. },
  8553. );
  8554. }
  8555. };
  8556. public refresh = () => {
  8557. this.setState({ ...this.getCanvasOffsets() });
  8558. };
  8559. private getCanvasOffsets(): Pick<AppState, "offsetTop" | "offsetLeft"> {
  8560. if (this.excalidrawContainerRef?.current) {
  8561. const excalidrawContainer = this.excalidrawContainerRef.current;
  8562. const { left, top } = excalidrawContainer.getBoundingClientRect();
  8563. return {
  8564. offsetLeft: left,
  8565. offsetTop: top,
  8566. };
  8567. }
  8568. return {
  8569. offsetLeft: 0,
  8570. offsetTop: 0,
  8571. };
  8572. }
  8573. private async updateLanguage() {
  8574. const currentLang =
  8575. languages.find((lang) => lang.code === this.props.langCode) ||
  8576. defaultLang;
  8577. await setLanguage(currentLang);
  8578. this.setAppState({});
  8579. }
  8580. }
  8581. // -----------------------------------------------------------------------------
  8582. // TEST HOOKS
  8583. // -----------------------------------------------------------------------------
  8584. declare global {
  8585. interface Window {
  8586. h: {
  8587. elements: readonly ExcalidrawElement[];
  8588. state: AppState;
  8589. setState: React.Component<any, AppState>["setState"];
  8590. app: InstanceType<typeof App>;
  8591. history: History;
  8592. };
  8593. }
  8594. }
  8595. if (import.meta.env.MODE === ENV.TEST || import.meta.env.DEV) {
  8596. window.h = window.h || ({} as Window["h"]);
  8597. Object.defineProperties(window.h, {
  8598. elements: {
  8599. configurable: true,
  8600. get() {
  8601. return this.app?.scene.getElementsIncludingDeleted();
  8602. },
  8603. set(elements: ExcalidrawElement[]) {
  8604. return this.app?.scene.replaceAllElements(elements);
  8605. },
  8606. },
  8607. });
  8608. }
  8609. export default App;