App.tsx 196 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440
  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. actionToggleLock,
  35. actionToggleLinearEditor,
  36. } from "../actions";
  37. import { createRedoAction, createUndoAction } from "../actions/actionHistory";
  38. import { ActionManager } from "../actions/manager";
  39. import { actions } from "../actions/register";
  40. import { ActionResult } from "../actions/types";
  41. import { trackEvent } from "../analytics";
  42. import { getDefaultAppState, isEraserActive } from "../appState";
  43. import { parseClipboard } from "../clipboard";
  44. import {
  45. APP_NAME,
  46. CURSOR_TYPE,
  47. DEFAULT_MAX_IMAGE_WIDTH_OR_HEIGHT,
  48. DEFAULT_UI_OPTIONS,
  49. DEFAULT_VERTICAL_ALIGN,
  50. DRAGGING_THRESHOLD,
  51. ELEMENT_READY_TO_ERASE_OPACITY,
  52. ELEMENT_SHIFT_TRANSLATE_AMOUNT,
  53. ELEMENT_TRANSLATE_AMOUNT,
  54. ENV,
  55. EVENT,
  56. GRID_SIZE,
  57. IMAGE_RENDER_TIMEOUT,
  58. isAndroid,
  59. LINE_CONFIRM_THRESHOLD,
  60. MAX_ALLOWED_FILE_BYTES,
  61. MIME_TYPES,
  62. MQ_MAX_HEIGHT_LANDSCAPE,
  63. MQ_MAX_WIDTH_LANDSCAPE,
  64. MQ_MAX_WIDTH_PORTRAIT,
  65. MQ_RIGHT_SIDEBAR_MIN_WIDTH,
  66. MQ_SM_MAX_WIDTH,
  67. POINTER_BUTTON,
  68. ROUNDNESS,
  69. SCROLL_TIMEOUT,
  70. TAP_TWICE_TIMEOUT,
  71. TEXT_TO_CENTER_SNAP_THRESHOLD,
  72. THEME,
  73. TOUCH_CTX_MENU_TIMEOUT,
  74. VERTICAL_ALIGN,
  75. ZOOM_STEP,
  76. } from "../constants";
  77. import { loadFromBlob } from "../data";
  78. import Library, { distributeLibraryItemsOnSquareGrid } from "../data/library";
  79. import { restore, restoreElements } from "../data/restore";
  80. import {
  81. dragNewElement,
  82. dragSelectedElements,
  83. duplicateElement,
  84. getCommonBounds,
  85. getCursorForResizingElement,
  86. getDragOffsetXY,
  87. getElementWithTransformHandleType,
  88. getNormalizedDimensions,
  89. getResizeArrowDirection,
  90. getResizeOffsetXY,
  91. getLockedLinearCursorAlignSize,
  92. getTransformHandleTypeFromCoords,
  93. hitTest,
  94. isHittingElementBoundingBoxWithoutHittingElement,
  95. isInvisiblySmallElement,
  96. isNonDeletedElement,
  97. isTextElement,
  98. newElement,
  99. newLinearElement,
  100. newTextElement,
  101. newImageElement,
  102. textWysiwyg,
  103. transformElements,
  104. updateTextElement,
  105. } from "../element";
  106. import {
  107. bindOrUnbindLinearElement,
  108. bindOrUnbindSelectedElements,
  109. fixBindingsAfterDeletion,
  110. fixBindingsAfterDuplication,
  111. getEligibleElementsForBinding,
  112. getHoveredElementForBinding,
  113. isBindingEnabled,
  114. isLinearElementSimpleAndAlreadyBound,
  115. maybeBindLinearElement,
  116. shouldEnableBindingForPointerEvent,
  117. unbindLinearElements,
  118. updateBoundElements,
  119. } from "../element/binding";
  120. import { LinearElementEditor } from "../element/linearElementEditor";
  121. import { mutateElement, newElementWith } from "../element/mutateElement";
  122. import { deepCopyElement, newFreeDrawElement } from "../element/newElement";
  123. import {
  124. hasBoundTextElement,
  125. isArrowElement,
  126. isBindingElement,
  127. isBindingElementType,
  128. isBoundToContainer,
  129. isImageElement,
  130. isInitializedImageElement,
  131. isLinearElement,
  132. isLinearElementType,
  133. isUsingAdaptiveRadius,
  134. } from "../element/typeChecks";
  135. import {
  136. ExcalidrawBindableElement,
  137. ExcalidrawElement,
  138. ExcalidrawFreeDrawElement,
  139. ExcalidrawGenericElement,
  140. ExcalidrawLinearElement,
  141. ExcalidrawTextElement,
  142. NonDeleted,
  143. InitializedExcalidrawImageElement,
  144. ExcalidrawImageElement,
  145. FileId,
  146. NonDeletedExcalidrawElement,
  147. ExcalidrawTextContainer,
  148. } from "../element/types";
  149. import { getCenter, getDistance } from "../gesture";
  150. import {
  151. editGroupForSelectedElement,
  152. getElementsInGroup,
  153. getSelectedGroupIdForElement,
  154. getSelectedGroupIds,
  155. isElementInGroup,
  156. isSelectedViaGroup,
  157. selectGroupsForSelectedElements,
  158. } from "../groups";
  159. import History from "../history";
  160. import { defaultLang, getLanguage, languages, setLanguage, t } from "../i18n";
  161. import {
  162. CODES,
  163. shouldResizeFromCenter,
  164. shouldMaintainAspectRatio,
  165. shouldRotateWithDiscreteAngle,
  166. isArrowKey,
  167. KEYS,
  168. } from "../keys";
  169. import { distance2d, getGridPoint, isPathALoop } from "../math";
  170. import { renderScene } from "../renderer/renderScene";
  171. import { invalidateShapeForElement } from "../renderer/renderElement";
  172. import {
  173. calculateScrollCenter,
  174. getElementsAtPosition,
  175. getElementsWithinSelection,
  176. getNormalizedZoom,
  177. getSelectedElements,
  178. hasBackground,
  179. isOverScrollBars,
  180. isSomeElementSelected,
  181. } from "../scene";
  182. import Scene from "../scene/Scene";
  183. import { RenderConfig, ScrollBars } from "../scene/types";
  184. import { getStateForZoom } from "../scene/zoom";
  185. import { findShapeByKey, SHAPES } from "../shapes";
  186. import {
  187. AppClassProperties,
  188. AppProps,
  189. AppState,
  190. BinaryFileData,
  191. DataURL,
  192. ExcalidrawImperativeAPI,
  193. BinaryFiles,
  194. Gesture,
  195. GestureEvent,
  196. LibraryItems,
  197. PointerDownState,
  198. SceneData,
  199. Device,
  200. } from "../types";
  201. import {
  202. debounce,
  203. distance,
  204. getFontString,
  205. getNearestScrollableContainer,
  206. isInputLike,
  207. isToolIcon,
  208. isWritableElement,
  209. resetCursor,
  210. resolvablePromise,
  211. sceneCoordsToViewportCoords,
  212. setCursor,
  213. setCursorForShape,
  214. tupleToCoors,
  215. viewportCoordsToSceneCoords,
  216. withBatchedUpdates,
  217. wrapEvent,
  218. withBatchedUpdatesThrottled,
  219. updateObject,
  220. setEraserCursor,
  221. updateActiveTool,
  222. getShortcutKey,
  223. } from "../utils";
  224. import {
  225. ContextMenu,
  226. ContextMenuItems,
  227. CONTEXT_MENU_SEPARATOR,
  228. } from "./ContextMenu";
  229. import LayerUI from "./LayerUI";
  230. import { Toast } from "./Toast";
  231. import { actionToggleViewMode } from "../actions/actionToggleViewMode";
  232. import {
  233. dataURLToFile,
  234. generateIdFromFile,
  235. getDataURL,
  236. getFileFromEvent,
  237. isSupportedImageFile,
  238. loadSceneOrLibraryFromBlob,
  239. normalizeFile,
  240. parseLibraryJSON,
  241. resizeImageFile,
  242. SVGStringToFile,
  243. } from "../data/blob";
  244. import {
  245. getInitializedImageElements,
  246. loadHTMLImageElement,
  247. normalizeSVG,
  248. updateImageCache as _updateImageCache,
  249. } from "../element/image";
  250. import throttle from "lodash.throttle";
  251. import { fileOpen, FileSystemHandle } from "../data/filesystem";
  252. import {
  253. bindTextToShapeAfterDuplication,
  254. getApproxLineHeight,
  255. getApproxMinLineHeight,
  256. getApproxMinLineWidth,
  257. getBoundTextElement,
  258. getContainerCenter,
  259. getContainerDims,
  260. getTextBindableContainerAtPosition,
  261. isValidTextContainer,
  262. } from "../element/textElement";
  263. import { isHittingElementNotConsideringBoundingBox } from "../element/collision";
  264. import {
  265. normalizeLink,
  266. showHyperlinkTooltip,
  267. hideHyperlinkToolip,
  268. Hyperlink,
  269. isPointHittingLinkIcon,
  270. isLocalLink,
  271. } from "../element/Hyperlink";
  272. import { shouldShowBoundingBox } from "../element/transformHandles";
  273. import { Fonts } from "../scene/Fonts";
  274. import { actionPaste } from "../actions/actionClipboard";
  275. const deviceContextInitialValue = {
  276. isSmScreen: false,
  277. isMobile: false,
  278. isTouchScreen: false,
  279. canDeviceFitSidebar: false,
  280. };
  281. const DeviceContext = React.createContext<Device>(deviceContextInitialValue);
  282. DeviceContext.displayName = "DeviceContext";
  283. export const ExcalidrawContainerContext = React.createContext<{
  284. container: HTMLDivElement | null;
  285. id: string | null;
  286. }>({ container: null, id: null });
  287. ExcalidrawContainerContext.displayName = "ExcalidrawContainerContext";
  288. const ExcalidrawElementsContext = React.createContext<
  289. readonly NonDeletedExcalidrawElement[]
  290. >([]);
  291. ExcalidrawElementsContext.displayName = "ExcalidrawElementsContext";
  292. const ExcalidrawAppStateContext = React.createContext<AppState>({
  293. ...getDefaultAppState(),
  294. width: 0,
  295. height: 0,
  296. offsetLeft: 0,
  297. offsetTop: 0,
  298. });
  299. ExcalidrawAppStateContext.displayName = "ExcalidrawAppStateContext";
  300. const ExcalidrawSetAppStateContext = React.createContext<
  301. React.Component<any, AppState>["setState"]
  302. >(() => {
  303. console.warn("unitialized ExcalidrawSetAppStateContext context!");
  304. });
  305. ExcalidrawSetAppStateContext.displayName = "ExcalidrawSetAppStateContext";
  306. const ExcalidrawActionManagerContext = React.createContext<ActionManager>(
  307. null!,
  308. );
  309. ExcalidrawActionManagerContext.displayName = "ExcalidrawActionManagerContext";
  310. export const useDevice = () => useContext<Device>(DeviceContext);
  311. export const useExcalidrawContainer = () =>
  312. useContext(ExcalidrawContainerContext);
  313. export const useExcalidrawElements = () =>
  314. useContext(ExcalidrawElementsContext);
  315. export const useExcalidrawAppState = () =>
  316. useContext(ExcalidrawAppStateContext);
  317. export const useExcalidrawSetAppState = () =>
  318. useContext(ExcalidrawSetAppStateContext);
  319. export const useExcalidrawActionManager = () =>
  320. useContext(ExcalidrawActionManagerContext);
  321. let didTapTwice: boolean = false;
  322. let tappedTwiceTimer = 0;
  323. let cursorX = 0;
  324. let cursorY = 0;
  325. let isHoldingSpace: boolean = false;
  326. let isPanning: boolean = false;
  327. let isDraggingScrollBar: boolean = false;
  328. let currentScrollBars: ScrollBars = { horizontal: null, vertical: null };
  329. let touchTimeout = 0;
  330. let invalidateContextMenu = false;
  331. // remove this hack when we can sync render & resizeObserver (state update)
  332. // to rAF. See #5439
  333. let THROTTLE_NEXT_RENDER = true;
  334. let IS_PLAIN_PASTE = false;
  335. let IS_PLAIN_PASTE_TIMER = 0;
  336. let PLAIN_PASTE_TOAST_SHOWN = false;
  337. let lastPointerUp: ((event: any) => void) | null = null;
  338. const gesture: Gesture = {
  339. pointers: new Map(),
  340. lastCenter: null,
  341. initialDistance: null,
  342. initialScale: null,
  343. };
  344. class App extends React.Component<AppProps, AppState> {
  345. canvas: AppClassProperties["canvas"] = null;
  346. rc: RoughCanvas | null = null;
  347. unmounted: boolean = false;
  348. actionManager: ActionManager;
  349. device: Device = deviceContextInitialValue;
  350. detachIsMobileMqHandler?: () => void;
  351. private excalidrawContainerRef = React.createRef<HTMLDivElement>();
  352. public static defaultProps: Partial<AppProps> = {
  353. // needed for tests to pass since we directly render App in many tests
  354. UIOptions: DEFAULT_UI_OPTIONS,
  355. };
  356. public scene: Scene;
  357. private fonts: Fonts;
  358. private resizeObserver: ResizeObserver | undefined;
  359. private nearestScrollableContainer: HTMLElement | Document | undefined;
  360. public library: AppClassProperties["library"];
  361. public libraryItemsFromStorage: LibraryItems | undefined;
  362. private id: string;
  363. private history: History;
  364. private excalidrawContainerValue: {
  365. container: HTMLDivElement | null;
  366. id: string;
  367. };
  368. public files: BinaryFiles = {};
  369. public imageCache: AppClassProperties["imageCache"] = new Map();
  370. hitLinkElement?: NonDeletedExcalidrawElement;
  371. lastPointerDown: React.PointerEvent<HTMLCanvasElement> | null = null;
  372. lastPointerUp: React.PointerEvent<HTMLElement> | PointerEvent | null = null;
  373. lastScenePointer: { x: number; y: number } | null = null;
  374. constructor(props: AppProps) {
  375. super(props);
  376. const defaultAppState = getDefaultAppState();
  377. const {
  378. excalidrawRef,
  379. viewModeEnabled = false,
  380. zenModeEnabled = false,
  381. gridModeEnabled = false,
  382. theme = defaultAppState.theme,
  383. name = defaultAppState.name,
  384. } = props;
  385. this.state = {
  386. ...defaultAppState,
  387. theme,
  388. isLoading: true,
  389. ...this.getCanvasOffsets(),
  390. viewModeEnabled,
  391. zenModeEnabled,
  392. gridSize: gridModeEnabled ? GRID_SIZE : null,
  393. name,
  394. width: window.innerWidth,
  395. height: window.innerHeight,
  396. showHyperlinkPopup: false,
  397. isSidebarDocked: false,
  398. };
  399. this.id = nanoid();
  400. this.library = new Library(this);
  401. if (excalidrawRef) {
  402. const readyPromise =
  403. ("current" in excalidrawRef && excalidrawRef.current?.readyPromise) ||
  404. resolvablePromise<ExcalidrawImperativeAPI>();
  405. const api: ExcalidrawImperativeAPI = {
  406. ready: true,
  407. readyPromise,
  408. updateScene: this.updateScene,
  409. updateLibrary: this.library.updateLibrary,
  410. addFiles: this.addFiles,
  411. resetScene: this.resetScene,
  412. getSceneElementsIncludingDeleted: this.getSceneElementsIncludingDeleted,
  413. history: {
  414. clear: this.resetHistory,
  415. },
  416. scrollToContent: this.scrollToContent,
  417. getSceneElements: this.getSceneElements,
  418. getAppState: () => this.state,
  419. getFiles: () => this.files,
  420. refresh: this.refresh,
  421. setToast: this.setToast,
  422. id: this.id,
  423. setActiveTool: this.setActiveTool,
  424. setCursor: this.setCursor,
  425. resetCursor: this.resetCursor,
  426. toggleMenu: this.toggleMenu,
  427. } as const;
  428. if (typeof excalidrawRef === "function") {
  429. excalidrawRef(api);
  430. } else {
  431. excalidrawRef.current = api;
  432. }
  433. readyPromise.resolve(api);
  434. }
  435. this.excalidrawContainerValue = {
  436. container: this.excalidrawContainerRef.current,
  437. id: this.id,
  438. };
  439. this.scene = new Scene();
  440. this.fonts = new Fonts({
  441. scene: this.scene,
  442. onSceneUpdated: this.onSceneUpdated,
  443. });
  444. this.history = new History();
  445. this.actionManager = new ActionManager(
  446. this.syncActionResult,
  447. () => this.state,
  448. () => this.scene.getElementsIncludingDeleted(),
  449. this,
  450. );
  451. this.actionManager.registerAll(actions);
  452. this.actionManager.registerAction(createUndoAction(this.history));
  453. this.actionManager.registerAction(createRedoAction(this.history));
  454. }
  455. private renderCanvas() {
  456. const canvasScale = window.devicePixelRatio;
  457. const {
  458. width: canvasDOMWidth,
  459. height: canvasDOMHeight,
  460. viewModeEnabled,
  461. } = this.state;
  462. const canvasWidth = canvasDOMWidth * canvasScale;
  463. const canvasHeight = canvasDOMHeight * canvasScale;
  464. if (viewModeEnabled) {
  465. return (
  466. <canvas
  467. className="excalidraw__canvas"
  468. style={{
  469. width: canvasDOMWidth,
  470. height: canvasDOMHeight,
  471. cursor: CURSOR_TYPE.GRAB,
  472. }}
  473. width={canvasWidth}
  474. height={canvasHeight}
  475. ref={this.handleCanvasRef}
  476. onContextMenu={this.handleCanvasContextMenu}
  477. onPointerMove={this.handleCanvasPointerMove}
  478. onPointerUp={this.handleCanvasPointerUp}
  479. onPointerCancel={this.removePointer}
  480. onTouchMove={this.handleTouchMove}
  481. onPointerDown={this.handleCanvasPointerDown}
  482. >
  483. {t("labels.drawingCanvas")}
  484. </canvas>
  485. );
  486. }
  487. return (
  488. <canvas
  489. className="excalidraw__canvas"
  490. style={{
  491. width: canvasDOMWidth,
  492. height: canvasDOMHeight,
  493. }}
  494. width={canvasWidth}
  495. height={canvasHeight}
  496. ref={this.handleCanvasRef}
  497. onContextMenu={this.handleCanvasContextMenu}
  498. onPointerDown={this.handleCanvasPointerDown}
  499. onDoubleClick={this.handleCanvasDoubleClick}
  500. onPointerMove={this.handleCanvasPointerMove}
  501. onPointerUp={this.handleCanvasPointerUp}
  502. onPointerCancel={this.removePointer}
  503. onTouchMove={this.handleTouchMove}
  504. >
  505. {t("labels.drawingCanvas")}
  506. </canvas>
  507. );
  508. }
  509. public render() {
  510. const selectedElement = getSelectedElements(
  511. this.scene.getNonDeletedElements(),
  512. this.state,
  513. );
  514. const { renderTopRightUI, renderCustomStats } = this.props;
  515. return (
  516. <div
  517. className={clsx("excalidraw excalidraw-container", {
  518. "excalidraw--view-mode": this.state.viewModeEnabled,
  519. "excalidraw--mobile": this.device.isMobile,
  520. })}
  521. ref={this.excalidrawContainerRef}
  522. onDrop={this.handleAppOnDrop}
  523. tabIndex={0}
  524. onKeyDown={
  525. this.props.handleKeyboardGlobally ? undefined : this.onKeyDown
  526. }
  527. >
  528. <ExcalidrawContainerContext.Provider
  529. value={this.excalidrawContainerValue}
  530. >
  531. <DeviceContext.Provider value={this.device}>
  532. <ExcalidrawSetAppStateContext.Provider value={this.setAppState}>
  533. <ExcalidrawAppStateContext.Provider value={this.state}>
  534. <ExcalidrawElementsContext.Provider
  535. value={this.scene.getNonDeletedElements()}
  536. >
  537. <ExcalidrawActionManagerContext.Provider
  538. value={this.actionManager}
  539. >
  540. <LayerUI
  541. canvas={this.canvas}
  542. appState={this.state}
  543. files={this.files}
  544. setAppState={this.setAppState}
  545. actionManager={this.actionManager}
  546. elements={this.scene.getNonDeletedElements()}
  547. onLockToggle={this.toggleLock}
  548. onPenModeToggle={this.togglePenMode}
  549. onInsertElements={(elements) =>
  550. this.addElementsFromPasteOrLibrary({
  551. elements,
  552. position: "center",
  553. files: null,
  554. })
  555. }
  556. langCode={getLanguage().code}
  557. isCollaborating={this.props.isCollaborating}
  558. renderTopRightUI={renderTopRightUI}
  559. renderCustomStats={renderCustomStats}
  560. renderCustomSidebar={this.props.renderSidebar}
  561. showExitZenModeBtn={
  562. typeof this.props?.zenModeEnabled === "undefined" &&
  563. this.state.zenModeEnabled
  564. }
  565. libraryReturnUrl={this.props.libraryReturnUrl}
  566. UIOptions={this.props.UIOptions}
  567. focusContainer={this.focusContainer}
  568. library={this.library}
  569. id={this.id}
  570. onImageAction={this.onImageAction}
  571. renderWelcomeScreen={
  572. !this.state.isLoading &&
  573. this.props.UIOptions.welcomeScreen &&
  574. this.state.showWelcomeScreen &&
  575. this.state.activeTool.type === "selection" &&
  576. !this.scene.getElementsIncludingDeleted().length
  577. }
  578. >
  579. {this.props.children}
  580. </LayerUI>
  581. <div className="excalidraw-textEditorContainer" />
  582. <div className="excalidraw-contextMenuContainer" />
  583. {selectedElement.length === 1 &&
  584. !this.state.contextMenu &&
  585. this.state.showHyperlinkPopup && (
  586. <Hyperlink
  587. key={selectedElement[0].id}
  588. element={selectedElement[0]}
  589. setAppState={this.setAppState}
  590. onLinkOpen={this.props.onLinkOpen}
  591. />
  592. )}
  593. {this.state.toast !== null && (
  594. <Toast
  595. message={this.state.toast.message}
  596. onClose={() => this.setToast(null)}
  597. duration={this.state.toast.duration}
  598. closable={this.state.toast.closable}
  599. />
  600. )}
  601. {this.state.contextMenu && (
  602. <ContextMenu
  603. items={this.state.contextMenu.items}
  604. top={this.state.contextMenu.top}
  605. left={this.state.contextMenu.left}
  606. actionManager={this.actionManager}
  607. />
  608. )}
  609. <main>{this.renderCanvas()}</main>
  610. </ExcalidrawActionManagerContext.Provider>
  611. </ExcalidrawElementsContext.Provider>{" "}
  612. </ExcalidrawAppStateContext.Provider>
  613. </ExcalidrawSetAppStateContext.Provider>
  614. </DeviceContext.Provider>
  615. </ExcalidrawContainerContext.Provider>
  616. </div>
  617. );
  618. }
  619. public focusContainer: AppClassProperties["focusContainer"] = () => {
  620. if (this.props.autoFocus) {
  621. this.excalidrawContainerRef.current?.focus();
  622. }
  623. };
  624. public getSceneElementsIncludingDeleted = () => {
  625. return this.scene.getElementsIncludingDeleted();
  626. };
  627. public getSceneElements = () => {
  628. return this.scene.getNonDeletedElements();
  629. };
  630. private syncActionResult = withBatchedUpdates(
  631. (actionResult: ActionResult) => {
  632. if (this.unmounted || actionResult === false) {
  633. return;
  634. }
  635. let editingElement: AppState["editingElement"] | null = null;
  636. if (actionResult.elements) {
  637. actionResult.elements.forEach((element) => {
  638. if (
  639. this.state.editingElement?.id === element.id &&
  640. this.state.editingElement !== element &&
  641. isNonDeletedElement(element)
  642. ) {
  643. editingElement = element;
  644. }
  645. });
  646. this.scene.replaceAllElements(actionResult.elements);
  647. if (actionResult.commitToHistory) {
  648. this.history.resumeRecording();
  649. }
  650. }
  651. if (actionResult.files) {
  652. this.files = actionResult.replaceFiles
  653. ? actionResult.files
  654. : { ...this.files, ...actionResult.files };
  655. this.addNewImagesToImageCache();
  656. }
  657. if (actionResult.appState || editingElement || this.state.contextMenu) {
  658. if (actionResult.commitToHistory) {
  659. this.history.resumeRecording();
  660. }
  661. let viewModeEnabled = actionResult?.appState?.viewModeEnabled || false;
  662. let zenModeEnabled = actionResult?.appState?.zenModeEnabled || false;
  663. let gridSize = actionResult?.appState?.gridSize || null;
  664. const theme =
  665. actionResult?.appState?.theme || this.props.theme || THEME.LIGHT;
  666. let name = actionResult?.appState?.name ?? this.state.name;
  667. if (typeof this.props.viewModeEnabled !== "undefined") {
  668. viewModeEnabled = this.props.viewModeEnabled;
  669. }
  670. if (typeof this.props.zenModeEnabled !== "undefined") {
  671. zenModeEnabled = this.props.zenModeEnabled;
  672. }
  673. if (typeof this.props.gridModeEnabled !== "undefined") {
  674. gridSize = this.props.gridModeEnabled ? GRID_SIZE : null;
  675. }
  676. if (typeof this.props.name !== "undefined") {
  677. name = this.props.name;
  678. }
  679. this.setState(
  680. (state) => {
  681. // using Object.assign instead of spread to fool TS 4.2.2+ into
  682. // regarding the resulting type as not containing undefined
  683. // (which the following expression will never contain)
  684. return Object.assign(actionResult.appState || {}, {
  685. // NOTE this will prevent opening context menu using an action
  686. // or programmatically from the host, so it will need to be
  687. // rewritten later
  688. contextMenu: null,
  689. editingElement:
  690. editingElement || actionResult.appState?.editingElement || null,
  691. viewModeEnabled,
  692. zenModeEnabled,
  693. gridSize,
  694. theme,
  695. name,
  696. });
  697. },
  698. () => {
  699. if (actionResult.syncHistory) {
  700. this.history.setCurrentState(
  701. this.state,
  702. this.scene.getElementsIncludingDeleted(),
  703. );
  704. }
  705. },
  706. );
  707. }
  708. },
  709. );
  710. // Lifecycle
  711. private onBlur = withBatchedUpdates(() => {
  712. isHoldingSpace = false;
  713. this.setState({ isBindingEnabled: true });
  714. });
  715. private onUnload = () => {
  716. this.onBlur();
  717. };
  718. private disableEvent: EventListener = (event) => {
  719. event.preventDefault();
  720. };
  721. private resetHistory = () => {
  722. this.history.clear();
  723. };
  724. /**
  725. * Resets scene & history.
  726. * ! Do not use to clear scene user action !
  727. */
  728. private resetScene = withBatchedUpdates(
  729. (opts?: { resetLoadingState: boolean }) => {
  730. this.scene.replaceAllElements([]);
  731. this.setState((state) => ({
  732. ...getDefaultAppState(),
  733. isLoading: opts?.resetLoadingState ? false : state.isLoading,
  734. theme: this.state.theme,
  735. }));
  736. this.resetHistory();
  737. },
  738. );
  739. private initializeScene = async () => {
  740. if ("launchQueue" in window && "LaunchParams" in window) {
  741. (window as any).launchQueue.setConsumer(
  742. async (launchParams: { files: any[] }) => {
  743. if (!launchParams.files.length) {
  744. return;
  745. }
  746. const fileHandle = launchParams.files[0];
  747. const blob: Blob = await fileHandle.getFile();
  748. this.loadFileToCanvas(
  749. new File([blob], blob.name || "", { type: blob.type }),
  750. fileHandle,
  751. );
  752. },
  753. );
  754. }
  755. if (this.props.theme) {
  756. this.setState({ theme: this.props.theme });
  757. }
  758. if (!this.state.isLoading) {
  759. this.setState({ isLoading: true });
  760. }
  761. let initialData = null;
  762. try {
  763. initialData = (await this.props.initialData) || null;
  764. if (initialData?.libraryItems) {
  765. this.library
  766. .updateLibrary({
  767. libraryItems: initialData.libraryItems,
  768. merge: true,
  769. })
  770. .catch((error) => {
  771. console.error(error);
  772. });
  773. }
  774. } catch (error: any) {
  775. console.error(error);
  776. initialData = {
  777. appState: {
  778. errorMessage:
  779. error.message ||
  780. "Encountered an error during importing or restoring scene data",
  781. },
  782. };
  783. }
  784. const scene = restore(initialData, null, null);
  785. scene.appState = {
  786. ...scene.appState,
  787. theme: this.props.theme || scene.appState.theme,
  788. // we're falling back to current (pre-init) state when deciding
  789. // whether to open the library, to handle a case where we
  790. // update the state outside of initialData (e.g. when loading the app
  791. // with a library install link, which should auto-open the library)
  792. openSidebar: scene.appState?.openSidebar || this.state.openSidebar,
  793. activeTool:
  794. scene.appState.activeTool.type === "image"
  795. ? { ...scene.appState.activeTool, type: "selection" }
  796. : scene.appState.activeTool,
  797. isLoading: false,
  798. toast: this.state.toast,
  799. };
  800. if (initialData?.scrollToContent) {
  801. scene.appState = {
  802. ...scene.appState,
  803. ...calculateScrollCenter(
  804. scene.elements,
  805. {
  806. ...scene.appState,
  807. width: this.state.width,
  808. height: this.state.height,
  809. offsetTop: this.state.offsetTop,
  810. offsetLeft: this.state.offsetLeft,
  811. },
  812. null,
  813. ),
  814. };
  815. }
  816. // FontFaceSet loadingdone event we listen on may not always fire
  817. // (looking at you Safari), so on init we manually load fonts for current
  818. // text elements on canvas, and rerender them once done. This also
  819. // seems faster even in browsers that do fire the loadingdone event.
  820. this.fonts.loadFontsForElements(scene.elements);
  821. this.resetHistory();
  822. this.syncActionResult({
  823. ...scene,
  824. commitToHistory: true,
  825. });
  826. };
  827. private refreshDeviceState = (container: HTMLDivElement) => {
  828. const { width, height } = container.getBoundingClientRect();
  829. const sidebarBreakpoint =
  830. this.props.UIOptions.dockedSidebarBreakpoint != null
  831. ? this.props.UIOptions.dockedSidebarBreakpoint
  832. : MQ_RIGHT_SIDEBAR_MIN_WIDTH;
  833. this.device = updateObject(this.device, {
  834. isSmScreen: width < MQ_SM_MAX_WIDTH,
  835. isMobile:
  836. width < MQ_MAX_WIDTH_PORTRAIT ||
  837. (height < MQ_MAX_HEIGHT_LANDSCAPE && width < MQ_MAX_WIDTH_LANDSCAPE),
  838. canDeviceFitSidebar: width > sidebarBreakpoint,
  839. });
  840. };
  841. public async componentDidMount() {
  842. this.unmounted = false;
  843. this.excalidrawContainerValue.container =
  844. this.excalidrawContainerRef.current;
  845. if (
  846. process.env.NODE_ENV === ENV.TEST ||
  847. process.env.NODE_ENV === ENV.DEVELOPMENT
  848. ) {
  849. const setState = this.setState.bind(this);
  850. Object.defineProperties(window.h, {
  851. state: {
  852. configurable: true,
  853. get: () => {
  854. return this.state;
  855. },
  856. },
  857. setState: {
  858. configurable: true,
  859. value: (...args: Parameters<typeof setState>) => {
  860. return this.setState(...args);
  861. },
  862. },
  863. app: {
  864. configurable: true,
  865. value: this,
  866. },
  867. history: {
  868. configurable: true,
  869. value: this.history,
  870. },
  871. });
  872. }
  873. this.scene.addCallback(this.onSceneUpdated);
  874. this.addEventListeners();
  875. if (this.excalidrawContainerRef.current) {
  876. this.focusContainer();
  877. }
  878. if (
  879. this.excalidrawContainerRef.current &&
  880. // bounding rects don't work in tests so updating
  881. // the state on init would result in making the test enviro run
  882. // in mobile breakpoint (0 width/height), making everything fail
  883. process.env.NODE_ENV !== "test"
  884. ) {
  885. this.refreshDeviceState(this.excalidrawContainerRef.current);
  886. }
  887. if ("ResizeObserver" in window && this.excalidrawContainerRef?.current) {
  888. this.resizeObserver = new ResizeObserver(() => {
  889. THROTTLE_NEXT_RENDER = false;
  890. // recompute device dimensions state
  891. // ---------------------------------------------------------------------
  892. this.refreshDeviceState(this.excalidrawContainerRef.current!);
  893. // refresh offsets
  894. // ---------------------------------------------------------------------
  895. this.updateDOMRect();
  896. });
  897. this.resizeObserver?.observe(this.excalidrawContainerRef.current);
  898. } else if (window.matchMedia) {
  899. const mdScreenQuery = window.matchMedia(
  900. `(max-width: ${MQ_MAX_WIDTH_PORTRAIT}px), (max-height: ${MQ_MAX_HEIGHT_LANDSCAPE}px) and (max-width: ${MQ_MAX_WIDTH_LANDSCAPE}px)`,
  901. );
  902. const smScreenQuery = window.matchMedia(
  903. `(max-width: ${MQ_SM_MAX_WIDTH}px)`,
  904. );
  905. const canDeviceFitSidebarMediaQuery = window.matchMedia(
  906. `(min-width: ${
  907. // NOTE this won't update if a different breakpoint is supplied
  908. // after mount
  909. this.props.UIOptions.dockedSidebarBreakpoint != null
  910. ? this.props.UIOptions.dockedSidebarBreakpoint
  911. : MQ_RIGHT_SIDEBAR_MIN_WIDTH
  912. }px)`,
  913. );
  914. const handler = () => {
  915. this.excalidrawContainerRef.current!.getBoundingClientRect();
  916. this.device = updateObject(this.device, {
  917. isSmScreen: smScreenQuery.matches,
  918. isMobile: mdScreenQuery.matches,
  919. canDeviceFitSidebar: canDeviceFitSidebarMediaQuery.matches,
  920. });
  921. };
  922. mdScreenQuery.addListener(handler);
  923. this.detachIsMobileMqHandler = () =>
  924. mdScreenQuery.removeListener(handler);
  925. }
  926. const searchParams = new URLSearchParams(window.location.search.slice(1));
  927. if (searchParams.has("web-share-target")) {
  928. // Obtain a file that was shared via the Web Share Target API.
  929. this.restoreFileFromShare();
  930. } else {
  931. this.updateDOMRect(this.initializeScene);
  932. }
  933. }
  934. public componentWillUnmount() {
  935. this.files = {};
  936. this.imageCache.clear();
  937. this.resizeObserver?.disconnect();
  938. this.unmounted = true;
  939. this.removeEventListeners();
  940. this.scene.destroy();
  941. clearTimeout(touchTimeout);
  942. touchTimeout = 0;
  943. }
  944. private onResize = withBatchedUpdates(() => {
  945. this.scene
  946. .getElementsIncludingDeleted()
  947. .forEach((element) => invalidateShapeForElement(element));
  948. this.setState({});
  949. });
  950. private removeEventListeners() {
  951. document.removeEventListener(EVENT.POINTER_UP, this.removePointer);
  952. document.removeEventListener(EVENT.COPY, this.onCopy);
  953. document.removeEventListener(EVENT.PASTE, this.pasteFromClipboard);
  954. document.removeEventListener(EVENT.CUT, this.onCut);
  955. this.excalidrawContainerRef.current?.removeEventListener(
  956. EVENT.WHEEL,
  957. this.onWheel,
  958. );
  959. this.nearestScrollableContainer?.removeEventListener(
  960. EVENT.SCROLL,
  961. this.onScroll,
  962. );
  963. document.removeEventListener(EVENT.KEYDOWN, this.onKeyDown, false);
  964. document.removeEventListener(
  965. EVENT.MOUSE_MOVE,
  966. this.updateCurrentCursorPosition,
  967. false,
  968. );
  969. document.removeEventListener(EVENT.KEYUP, this.onKeyUp);
  970. window.removeEventListener(EVENT.RESIZE, this.onResize, false);
  971. window.removeEventListener(EVENT.UNLOAD, this.onUnload, false);
  972. window.removeEventListener(EVENT.BLUR, this.onBlur, false);
  973. this.excalidrawContainerRef.current?.removeEventListener(
  974. EVENT.DRAG_OVER,
  975. this.disableEvent,
  976. false,
  977. );
  978. this.excalidrawContainerRef.current?.removeEventListener(
  979. EVENT.DROP,
  980. this.disableEvent,
  981. false,
  982. );
  983. document.removeEventListener(
  984. EVENT.GESTURE_START,
  985. this.onGestureStart as any,
  986. false,
  987. );
  988. document.removeEventListener(
  989. EVENT.GESTURE_CHANGE,
  990. this.onGestureChange as any,
  991. false,
  992. );
  993. document.removeEventListener(
  994. EVENT.GESTURE_END,
  995. this.onGestureEnd as any,
  996. false,
  997. );
  998. this.detachIsMobileMqHandler?.();
  999. }
  1000. private addEventListeners() {
  1001. this.removeEventListeners();
  1002. document.addEventListener(EVENT.POINTER_UP, this.removePointer); // #3553
  1003. document.addEventListener(EVENT.COPY, this.onCopy);
  1004. this.excalidrawContainerRef.current?.addEventListener(
  1005. EVENT.WHEEL,
  1006. this.onWheel,
  1007. { passive: false },
  1008. );
  1009. if (this.props.handleKeyboardGlobally) {
  1010. document.addEventListener(EVENT.KEYDOWN, this.onKeyDown, false);
  1011. }
  1012. document.addEventListener(EVENT.KEYUP, this.onKeyUp, { passive: true });
  1013. document.addEventListener(
  1014. EVENT.MOUSE_MOVE,
  1015. this.updateCurrentCursorPosition,
  1016. );
  1017. // rerender text elements on font load to fix #637 && #1553
  1018. document.fonts?.addEventListener?.("loadingdone", (event) => {
  1019. const loadedFontFaces = (event as FontFaceSetLoadEvent).fontfaces;
  1020. this.fonts.onFontsLoaded(loadedFontFaces);
  1021. });
  1022. // Safari-only desktop pinch zoom
  1023. document.addEventListener(
  1024. EVENT.GESTURE_START,
  1025. this.onGestureStart as any,
  1026. false,
  1027. );
  1028. document.addEventListener(
  1029. EVENT.GESTURE_CHANGE,
  1030. this.onGestureChange as any,
  1031. false,
  1032. );
  1033. document.addEventListener(
  1034. EVENT.GESTURE_END,
  1035. this.onGestureEnd as any,
  1036. false,
  1037. );
  1038. if (this.state.viewModeEnabled) {
  1039. return;
  1040. }
  1041. document.addEventListener(EVENT.PASTE, this.pasteFromClipboard);
  1042. document.addEventListener(EVENT.CUT, this.onCut);
  1043. if (this.props.detectScroll) {
  1044. this.nearestScrollableContainer = getNearestScrollableContainer(
  1045. this.excalidrawContainerRef.current!,
  1046. );
  1047. this.nearestScrollableContainer.addEventListener(
  1048. EVENT.SCROLL,
  1049. this.onScroll,
  1050. );
  1051. }
  1052. window.addEventListener(EVENT.RESIZE, this.onResize, false);
  1053. window.addEventListener(EVENT.UNLOAD, this.onUnload, false);
  1054. window.addEventListener(EVENT.BLUR, this.onBlur, false);
  1055. this.excalidrawContainerRef.current?.addEventListener(
  1056. EVENT.DRAG_OVER,
  1057. this.disableEvent,
  1058. false,
  1059. );
  1060. this.excalidrawContainerRef.current?.addEventListener(
  1061. EVENT.DROP,
  1062. this.disableEvent,
  1063. false,
  1064. );
  1065. }
  1066. componentDidUpdate(prevProps: AppProps, prevState: AppState) {
  1067. if (
  1068. !this.state.showWelcomeScreen &&
  1069. !this.scene.getElementsIncludingDeleted().length
  1070. ) {
  1071. this.setState({ showWelcomeScreen: true });
  1072. }
  1073. if (
  1074. this.excalidrawContainerRef.current &&
  1075. prevProps.UIOptions.dockedSidebarBreakpoint !==
  1076. this.props.UIOptions.dockedSidebarBreakpoint
  1077. ) {
  1078. this.refreshDeviceState(this.excalidrawContainerRef.current);
  1079. }
  1080. if (
  1081. prevState.scrollX !== this.state.scrollX ||
  1082. prevState.scrollY !== this.state.scrollY
  1083. ) {
  1084. this.props?.onScrollChange?.(this.state.scrollX, this.state.scrollY);
  1085. }
  1086. if (
  1087. Object.keys(this.state.selectedElementIds).length &&
  1088. isEraserActive(this.state)
  1089. ) {
  1090. this.setState({
  1091. activeTool: updateActiveTool(this.state, { type: "selection" }),
  1092. });
  1093. }
  1094. if (
  1095. this.state.activeTool.type === "eraser" &&
  1096. prevState.theme !== this.state.theme
  1097. ) {
  1098. setEraserCursor(this.canvas, this.state.theme);
  1099. }
  1100. // Hide hyperlink popup if shown when element type is not selection
  1101. if (
  1102. prevState.activeTool.type === "selection" &&
  1103. this.state.activeTool.type !== "selection" &&
  1104. this.state.showHyperlinkPopup
  1105. ) {
  1106. this.setState({ showHyperlinkPopup: false });
  1107. }
  1108. if (prevProps.langCode !== this.props.langCode) {
  1109. this.updateLanguage();
  1110. }
  1111. if (prevProps.viewModeEnabled !== this.props.viewModeEnabled) {
  1112. this.setState({ viewModeEnabled: !!this.props.viewModeEnabled });
  1113. }
  1114. if (prevState.viewModeEnabled !== this.state.viewModeEnabled) {
  1115. this.addEventListeners();
  1116. this.deselectElements();
  1117. }
  1118. if (prevProps.zenModeEnabled !== this.props.zenModeEnabled) {
  1119. this.setState({ zenModeEnabled: !!this.props.zenModeEnabled });
  1120. }
  1121. if (prevProps.theme !== this.props.theme && this.props.theme) {
  1122. this.setState({ theme: this.props.theme });
  1123. }
  1124. if (prevProps.gridModeEnabled !== this.props.gridModeEnabled) {
  1125. this.setState({
  1126. gridSize: this.props.gridModeEnabled ? GRID_SIZE : null,
  1127. });
  1128. }
  1129. if (this.props.name && prevProps.name !== this.props.name) {
  1130. this.setState({
  1131. name: this.props.name,
  1132. });
  1133. }
  1134. this.excalidrawContainerRef.current?.classList.toggle(
  1135. "theme--dark",
  1136. this.state.theme === "dark",
  1137. );
  1138. if (
  1139. this.state.editingLinearElement &&
  1140. !this.state.selectedElementIds[this.state.editingLinearElement.elementId]
  1141. ) {
  1142. // defer so that the commitToHistory flag isn't reset via current update
  1143. setTimeout(() => {
  1144. // execute only if the condition still holds when the deferred callback
  1145. // executes (it can be scheduled multiple times depending on how
  1146. // many times the component renders)
  1147. this.state.editingLinearElement &&
  1148. this.actionManager.executeAction(actionFinalize);
  1149. });
  1150. }
  1151. if (
  1152. this.state.selectedLinearElement &&
  1153. !this.state.selectedElementIds[this.state.selectedLinearElement.elementId]
  1154. ) {
  1155. // To make sure `selectedLinearElement` is in sync with `selectedElementIds`, however this shouldn't be needed once
  1156. // we have a single API to update `selectedElementIds`
  1157. this.setState({ selectedLinearElement: null });
  1158. }
  1159. const { multiElement } = prevState;
  1160. if (
  1161. prevState.activeTool !== this.state.activeTool &&
  1162. multiElement != null &&
  1163. isBindingEnabled(this.state) &&
  1164. isBindingElement(multiElement, false)
  1165. ) {
  1166. maybeBindLinearElement(
  1167. multiElement,
  1168. this.state,
  1169. this.scene,
  1170. tupleToCoors(
  1171. LinearElementEditor.getPointAtIndexGlobalCoordinates(
  1172. multiElement,
  1173. -1,
  1174. ),
  1175. ),
  1176. );
  1177. }
  1178. this.renderScene();
  1179. this.history.record(this.state, this.scene.getElementsIncludingDeleted());
  1180. // Do not notify consumers if we're still loading the scene. Among other
  1181. // potential issues, this fixes a case where the tab isn't focused during
  1182. // init, which would trigger onChange with empty elements, which would then
  1183. // override whatever is in localStorage currently.
  1184. if (!this.state.isLoading) {
  1185. this.props.onChange?.(
  1186. this.scene.getElementsIncludingDeleted(),
  1187. this.state,
  1188. this.files,
  1189. );
  1190. }
  1191. }
  1192. private renderScene = () => {
  1193. const cursorButton: {
  1194. [id: string]: string | undefined;
  1195. } = {};
  1196. const pointerViewportCoords: RenderConfig["remotePointerViewportCoords"] =
  1197. {};
  1198. const remoteSelectedElementIds: RenderConfig["remoteSelectedElementIds"] =
  1199. {};
  1200. const pointerUsernames: { [id: string]: string } = {};
  1201. const pointerUserStates: { [id: string]: string } = {};
  1202. this.state.collaborators.forEach((user, socketId) => {
  1203. if (user.selectedElementIds) {
  1204. for (const id of Object.keys(user.selectedElementIds)) {
  1205. if (!(id in remoteSelectedElementIds)) {
  1206. remoteSelectedElementIds[id] = [];
  1207. }
  1208. remoteSelectedElementIds[id].push(socketId);
  1209. }
  1210. }
  1211. if (!user.pointer) {
  1212. return;
  1213. }
  1214. if (user.username) {
  1215. pointerUsernames[socketId] = user.username;
  1216. }
  1217. if (user.userState) {
  1218. pointerUserStates[socketId] = user.userState;
  1219. }
  1220. pointerViewportCoords[socketId] = sceneCoordsToViewportCoords(
  1221. {
  1222. sceneX: user.pointer.x,
  1223. sceneY: user.pointer.y,
  1224. },
  1225. this.state,
  1226. );
  1227. cursorButton[socketId] = user.button;
  1228. });
  1229. const renderingElements = this.scene
  1230. .getNonDeletedElements()
  1231. .filter((element) => {
  1232. if (isImageElement(element)) {
  1233. if (
  1234. // not placed on canvas yet (but in elements array)
  1235. this.state.pendingImageElementId === element.id
  1236. ) {
  1237. return false;
  1238. }
  1239. }
  1240. // don't render text element that's being currently edited (it's
  1241. // rendered on remote only)
  1242. return (
  1243. !this.state.editingElement ||
  1244. this.state.editingElement.type !== "text" ||
  1245. element.id !== this.state.editingElement.id
  1246. );
  1247. });
  1248. const selectionColor = getComputedStyle(
  1249. document.querySelector(".excalidraw")!,
  1250. ).getPropertyValue("--color-selection");
  1251. renderScene(
  1252. {
  1253. elements: renderingElements,
  1254. appState: this.state,
  1255. scale: window.devicePixelRatio,
  1256. rc: this.rc!,
  1257. canvas: this.canvas!,
  1258. renderConfig: {
  1259. selectionColor,
  1260. scrollX: this.state.scrollX,
  1261. scrollY: this.state.scrollY,
  1262. viewBackgroundColor: this.state.viewBackgroundColor,
  1263. zoom: this.state.zoom,
  1264. remotePointerViewportCoords: pointerViewportCoords,
  1265. remotePointerButton: cursorButton,
  1266. remoteSelectedElementIds,
  1267. remotePointerUsernames: pointerUsernames,
  1268. remotePointerUserStates: pointerUserStates,
  1269. shouldCacheIgnoreZoom: this.state.shouldCacheIgnoreZoom,
  1270. theme: this.state.theme,
  1271. imageCache: this.imageCache,
  1272. isExporting: false,
  1273. renderScrollbars: !this.device.isMobile,
  1274. },
  1275. callback: ({ atLeastOneVisibleElement, scrollBars }) => {
  1276. if (scrollBars) {
  1277. currentScrollBars = scrollBars;
  1278. }
  1279. const scrolledOutside =
  1280. // hide when editing text
  1281. isTextElement(this.state.editingElement)
  1282. ? false
  1283. : !atLeastOneVisibleElement && renderingElements.length > 0;
  1284. if (this.state.scrolledOutside !== scrolledOutside) {
  1285. this.setState({ scrolledOutside });
  1286. }
  1287. this.scheduleImageRefresh();
  1288. },
  1289. },
  1290. THROTTLE_NEXT_RENDER && window.EXCALIDRAW_THROTTLE_RENDER === true,
  1291. );
  1292. if (!THROTTLE_NEXT_RENDER) {
  1293. THROTTLE_NEXT_RENDER = true;
  1294. }
  1295. };
  1296. private onScroll = debounce(() => {
  1297. const { offsetTop, offsetLeft } = this.getCanvasOffsets();
  1298. this.setState((state) => {
  1299. if (state.offsetLeft === offsetLeft && state.offsetTop === offsetTop) {
  1300. return null;
  1301. }
  1302. return { offsetTop, offsetLeft };
  1303. });
  1304. }, SCROLL_TIMEOUT);
  1305. // Copy/paste
  1306. private onCut = withBatchedUpdates((event: ClipboardEvent) => {
  1307. const isExcalidrawActive = this.excalidrawContainerRef.current?.contains(
  1308. document.activeElement,
  1309. );
  1310. if (!isExcalidrawActive || isWritableElement(event.target)) {
  1311. return;
  1312. }
  1313. this.cutAll();
  1314. event.preventDefault();
  1315. event.stopPropagation();
  1316. });
  1317. private onCopy = withBatchedUpdates((event: ClipboardEvent) => {
  1318. const isExcalidrawActive = this.excalidrawContainerRef.current?.contains(
  1319. document.activeElement,
  1320. );
  1321. if (!isExcalidrawActive || isWritableElement(event.target)) {
  1322. return;
  1323. }
  1324. this.copyAll();
  1325. event.preventDefault();
  1326. event.stopPropagation();
  1327. });
  1328. private cutAll = () => {
  1329. this.actionManager.executeAction(actionCut, "keyboard");
  1330. };
  1331. private copyAll = () => {
  1332. this.actionManager.executeAction(actionCopy, "keyboard");
  1333. };
  1334. private static resetTapTwice() {
  1335. didTapTwice = false;
  1336. }
  1337. private onTapStart = (event: TouchEvent) => {
  1338. // fix for Apple Pencil Scribble
  1339. // On Android, preventing the event would disable contextMenu on tap-hold
  1340. if (!isAndroid) {
  1341. event.preventDefault();
  1342. }
  1343. if (!didTapTwice) {
  1344. didTapTwice = true;
  1345. clearTimeout(tappedTwiceTimer);
  1346. tappedTwiceTimer = window.setTimeout(
  1347. App.resetTapTwice,
  1348. TAP_TWICE_TIMEOUT,
  1349. );
  1350. return;
  1351. }
  1352. // insert text only if we tapped twice with a single finger
  1353. // event.touches.length === 1 will also prevent inserting text when user's zooming
  1354. if (didTapTwice && event.touches.length === 1) {
  1355. const [touch] = event.touches;
  1356. // @ts-ignore
  1357. this.handleCanvasDoubleClick({
  1358. clientX: touch.clientX,
  1359. clientY: touch.clientY,
  1360. });
  1361. didTapTwice = false;
  1362. clearTimeout(tappedTwiceTimer);
  1363. }
  1364. if (isAndroid) {
  1365. event.preventDefault();
  1366. }
  1367. if (event.touches.length === 2) {
  1368. this.setState({
  1369. selectedElementIds: {},
  1370. });
  1371. }
  1372. };
  1373. private onTapEnd = (event: TouchEvent) => {
  1374. this.resetContextMenuTimer();
  1375. if (event.touches.length > 0) {
  1376. this.setState({
  1377. previousSelectedElementIds: {},
  1378. selectedElementIds: this.state.previousSelectedElementIds,
  1379. });
  1380. } else {
  1381. gesture.pointers.clear();
  1382. }
  1383. };
  1384. public pasteFromClipboard = withBatchedUpdates(
  1385. async (event: ClipboardEvent | null) => {
  1386. const isPlainPaste = !!(IS_PLAIN_PASTE && event);
  1387. // #686
  1388. const target = document.activeElement;
  1389. const isExcalidrawActive =
  1390. this.excalidrawContainerRef.current?.contains(target);
  1391. if (event && !isExcalidrawActive) {
  1392. return;
  1393. }
  1394. const elementUnderCursor = document.elementFromPoint(cursorX, cursorY);
  1395. if (
  1396. event &&
  1397. (!(elementUnderCursor instanceof HTMLCanvasElement) ||
  1398. isWritableElement(target))
  1399. ) {
  1400. return;
  1401. }
  1402. // must be called in the same frame (thus before any awaits) as the paste
  1403. // event else some browsers (FF...) will clear the clipboardData
  1404. // (something something security)
  1405. let file = event?.clipboardData?.files[0];
  1406. const data = await parseClipboard(event, isPlainPaste);
  1407. if (!file && data.text && !isPlainPaste) {
  1408. const string = data.text.trim();
  1409. if (string.startsWith("<svg") && string.endsWith("</svg>")) {
  1410. // ignore SVG validation/normalization which will be done during image
  1411. // initialization
  1412. file = SVGStringToFile(string);
  1413. }
  1414. }
  1415. // prefer spreadsheet data over image file (MS Office/Libre Office)
  1416. if (isSupportedImageFile(file) && !data.spreadsheet) {
  1417. const { x: sceneX, y: sceneY } = viewportCoordsToSceneCoords(
  1418. { clientX: cursorX, clientY: cursorY },
  1419. this.state,
  1420. );
  1421. const imageElement = this.createImageElement({ sceneX, sceneY });
  1422. this.insertImageElement(imageElement, file);
  1423. this.initializeImageDimensions(imageElement);
  1424. this.setState({ selectedElementIds: { [imageElement.id]: true } });
  1425. return;
  1426. }
  1427. if (this.props.onPaste) {
  1428. try {
  1429. if ((await this.props.onPaste(data, event)) === false) {
  1430. return;
  1431. }
  1432. } catch (error: any) {
  1433. console.error(error);
  1434. }
  1435. }
  1436. if (data.errorMessage) {
  1437. this.setState({ errorMessage: data.errorMessage });
  1438. } else if (data.spreadsheet && !isPlainPaste) {
  1439. this.setState({
  1440. pasteDialog: {
  1441. data: data.spreadsheet,
  1442. shown: true,
  1443. },
  1444. });
  1445. } else if (data.elements) {
  1446. // TODO remove formatting from elements if isPlainPaste
  1447. this.addElementsFromPasteOrLibrary({
  1448. elements: data.elements,
  1449. files: data.files || null,
  1450. position: "cursor",
  1451. });
  1452. } else if (data.text) {
  1453. this.addTextFromPaste(data.text, isPlainPaste);
  1454. }
  1455. this.setActiveTool({ type: "selection" });
  1456. event?.preventDefault();
  1457. },
  1458. );
  1459. private addElementsFromPasteOrLibrary = (opts: {
  1460. elements: readonly ExcalidrawElement[];
  1461. files: BinaryFiles | null;
  1462. position: { clientX: number; clientY: number } | "cursor" | "center";
  1463. }) => {
  1464. const elements = restoreElements(opts.elements, null);
  1465. const [minX, minY, maxX, maxY] = getCommonBounds(elements);
  1466. const elementsCenterX = distance(minX, maxX) / 2;
  1467. const elementsCenterY = distance(minY, maxY) / 2;
  1468. const clientX =
  1469. typeof opts.position === "object"
  1470. ? opts.position.clientX
  1471. : opts.position === "cursor"
  1472. ? cursorX
  1473. : this.state.width / 2 + this.state.offsetLeft;
  1474. const clientY =
  1475. typeof opts.position === "object"
  1476. ? opts.position.clientY
  1477. : opts.position === "cursor"
  1478. ? cursorY
  1479. : this.state.height / 2 + this.state.offsetTop;
  1480. const { x, y } = viewportCoordsToSceneCoords(
  1481. { clientX, clientY },
  1482. this.state,
  1483. );
  1484. const dx = x - elementsCenterX;
  1485. const dy = y - elementsCenterY;
  1486. const groupIdMap = new Map();
  1487. const [gridX, gridY] = getGridPoint(dx, dy, this.state.gridSize);
  1488. const oldIdToDuplicatedId = new Map();
  1489. const newElements = elements.map((element) => {
  1490. const newElement = duplicateElement(
  1491. this.state.editingGroupId,
  1492. groupIdMap,
  1493. element,
  1494. {
  1495. x: element.x + gridX - minX,
  1496. y: element.y + gridY - minY,
  1497. },
  1498. );
  1499. oldIdToDuplicatedId.set(element.id, newElement.id);
  1500. return newElement;
  1501. });
  1502. bindTextToShapeAfterDuplication(newElements, elements, oldIdToDuplicatedId);
  1503. const nextElements = [
  1504. ...this.scene.getElementsIncludingDeleted(),
  1505. ...newElements,
  1506. ];
  1507. fixBindingsAfterDuplication(nextElements, elements, oldIdToDuplicatedId);
  1508. if (opts.files) {
  1509. this.files = { ...this.files, ...opts.files };
  1510. }
  1511. this.scene.replaceAllElements(nextElements);
  1512. this.history.resumeRecording();
  1513. this.setState(
  1514. selectGroupsForSelectedElements(
  1515. {
  1516. ...this.state,
  1517. // keep sidebar (presumably the library) open if it's docked and
  1518. // can fit.
  1519. //
  1520. // Note, we should close the sidebar only if we're dropping items
  1521. // from library, not when pasting from clipboard. Alas.
  1522. openSidebar:
  1523. this.state.openSidebar &&
  1524. this.device.canDeviceFitSidebar &&
  1525. this.state.isSidebarDocked
  1526. ? this.state.openSidebar
  1527. : null,
  1528. selectedElementIds: newElements.reduce(
  1529. (acc: Record<ExcalidrawElement["id"], true>, element) => {
  1530. if (!isBoundToContainer(element)) {
  1531. acc[element.id] = true;
  1532. }
  1533. return acc;
  1534. },
  1535. {},
  1536. ),
  1537. selectedGroupIds: {},
  1538. },
  1539. this.scene.getNonDeletedElements(),
  1540. ),
  1541. () => {
  1542. if (opts.files) {
  1543. this.addNewImagesToImageCache();
  1544. }
  1545. },
  1546. );
  1547. this.setActiveTool({ type: "selection" });
  1548. };
  1549. private addTextFromPaste(text: string, isPlainPaste = false) {
  1550. const { x, y } = viewportCoordsToSceneCoords(
  1551. { clientX: cursorX, clientY: cursorY },
  1552. this.state,
  1553. );
  1554. const textElementProps = {
  1555. x,
  1556. y,
  1557. strokeColor: this.state.currentItemStrokeColor,
  1558. backgroundColor: this.state.currentItemBackgroundColor,
  1559. fillStyle: this.state.currentItemFillStyle,
  1560. strokeWidth: this.state.currentItemStrokeWidth,
  1561. strokeStyle: this.state.currentItemStrokeStyle,
  1562. roundness: null,
  1563. roughness: this.state.currentItemRoughness,
  1564. opacity: this.state.currentItemOpacity,
  1565. text,
  1566. fontSize: this.state.currentItemFontSize,
  1567. fontFamily: this.state.currentItemFontFamily,
  1568. textAlign: this.state.currentItemTextAlign,
  1569. verticalAlign: DEFAULT_VERTICAL_ALIGN,
  1570. locked: false,
  1571. };
  1572. const LINE_GAP = 10;
  1573. let currentY = y;
  1574. const lines = isPlainPaste ? [text] : text.split("\n");
  1575. const textElements = lines.reduce(
  1576. (acc: ExcalidrawTextElement[], line, idx) => {
  1577. const text = line.trim();
  1578. if (text.length) {
  1579. const element = newTextElement({
  1580. ...textElementProps,
  1581. x,
  1582. y: currentY,
  1583. text,
  1584. });
  1585. acc.push(element);
  1586. currentY += element.height + LINE_GAP;
  1587. } else {
  1588. const prevLine = lines[idx - 1]?.trim();
  1589. // add paragraph only if previous line was not empty, IOW don't add
  1590. // more than one empty line
  1591. if (prevLine) {
  1592. const defaultLineHeight = getApproxLineHeight(
  1593. getFontString({
  1594. fontSize: textElementProps.fontSize,
  1595. fontFamily: textElementProps.fontFamily,
  1596. }),
  1597. );
  1598. currentY += defaultLineHeight + LINE_GAP;
  1599. }
  1600. }
  1601. return acc;
  1602. },
  1603. [],
  1604. );
  1605. if (textElements.length === 0) {
  1606. return;
  1607. }
  1608. this.scene.replaceAllElements([
  1609. ...this.scene.getElementsIncludingDeleted(),
  1610. ...textElements,
  1611. ]);
  1612. this.setState({
  1613. selectedElementIds: Object.fromEntries(
  1614. textElements.map((el) => [el.id, true]),
  1615. ),
  1616. });
  1617. if (
  1618. !isPlainPaste &&
  1619. textElements.length > 1 &&
  1620. PLAIN_PASTE_TOAST_SHOWN === false &&
  1621. !this.device.isMobile
  1622. ) {
  1623. this.setToast({
  1624. message: t("toast.pasteAsSingleElement", {
  1625. shortcut: getShortcutKey("CtrlOrCmd+Shift+V"),
  1626. }),
  1627. duration: 5000,
  1628. });
  1629. PLAIN_PASTE_TOAST_SHOWN = true;
  1630. }
  1631. this.history.resumeRecording();
  1632. }
  1633. setAppState: React.Component<any, AppState>["setState"] = (
  1634. state,
  1635. callback,
  1636. ) => {
  1637. this.setState(state, callback);
  1638. };
  1639. removePointer = (event: React.PointerEvent<HTMLElement> | PointerEvent) => {
  1640. if (touchTimeout) {
  1641. this.resetContextMenuTimer();
  1642. }
  1643. gesture.pointers.delete(event.pointerId);
  1644. };
  1645. toggleLock = (source: "keyboard" | "ui" = "ui") => {
  1646. if (!this.state.activeTool.locked) {
  1647. trackEvent(
  1648. "toolbar",
  1649. "toggleLock",
  1650. `${source} (${this.device.isMobile ? "mobile" : "desktop"})`,
  1651. );
  1652. }
  1653. this.setState((prevState) => {
  1654. return {
  1655. activeTool: {
  1656. ...prevState.activeTool,
  1657. ...updateActiveTool(
  1658. this.state,
  1659. prevState.activeTool.locked
  1660. ? { type: "selection" }
  1661. : prevState.activeTool,
  1662. ),
  1663. locked: !prevState.activeTool.locked,
  1664. },
  1665. };
  1666. });
  1667. };
  1668. togglePenMode = () => {
  1669. this.setState((prevState) => {
  1670. return {
  1671. penMode: !prevState.penMode,
  1672. };
  1673. });
  1674. };
  1675. scrollToContent = (
  1676. target:
  1677. | ExcalidrawElement
  1678. | readonly ExcalidrawElement[] = this.scene.getNonDeletedElements(),
  1679. ) => {
  1680. this.setState({
  1681. ...calculateScrollCenter(
  1682. Array.isArray(target) ? target : [target],
  1683. this.state,
  1684. this.canvas,
  1685. ),
  1686. });
  1687. };
  1688. setToast = (
  1689. toast: {
  1690. message: string;
  1691. closable?: boolean;
  1692. duration?: number;
  1693. } | null,
  1694. ) => {
  1695. this.setState({ toast });
  1696. };
  1697. restoreFileFromShare = async () => {
  1698. try {
  1699. const webShareTargetCache = await caches.open("web-share-target");
  1700. const response = await webShareTargetCache.match("shared-file");
  1701. if (response) {
  1702. const blob = await response.blob();
  1703. const file = new File([blob], blob.name || "", { type: blob.type });
  1704. this.loadFileToCanvas(file, null);
  1705. await webShareTargetCache.delete("shared-file");
  1706. window.history.replaceState(null, APP_NAME, window.location.pathname);
  1707. }
  1708. } catch (error: any) {
  1709. this.setState({ errorMessage: error.message });
  1710. }
  1711. };
  1712. /** adds supplied files to existing files in the appState */
  1713. public addFiles: ExcalidrawImperativeAPI["addFiles"] = withBatchedUpdates(
  1714. (files) => {
  1715. const filesMap = files.reduce((acc, fileData) => {
  1716. acc.set(fileData.id, fileData);
  1717. return acc;
  1718. }, new Map<FileId, BinaryFileData>());
  1719. this.files = { ...this.files, ...Object.fromEntries(filesMap) };
  1720. this.scene.getNonDeletedElements().forEach((element) => {
  1721. if (
  1722. isInitializedImageElement(element) &&
  1723. filesMap.has(element.fileId)
  1724. ) {
  1725. this.imageCache.delete(element.fileId);
  1726. invalidateShapeForElement(element);
  1727. }
  1728. });
  1729. this.scene.informMutation();
  1730. this.addNewImagesToImageCache();
  1731. },
  1732. );
  1733. public updateScene = withBatchedUpdates(
  1734. <K extends keyof AppState>(sceneData: {
  1735. elements?: SceneData["elements"];
  1736. appState?: Pick<AppState, K> | null;
  1737. collaborators?: SceneData["collaborators"];
  1738. commitToHistory?: SceneData["commitToHistory"];
  1739. }) => {
  1740. if (sceneData.commitToHistory) {
  1741. this.history.resumeRecording();
  1742. }
  1743. if (sceneData.appState) {
  1744. this.setState(sceneData.appState);
  1745. }
  1746. if (sceneData.elements) {
  1747. this.scene.replaceAllElements(sceneData.elements);
  1748. }
  1749. if (sceneData.collaborators) {
  1750. this.setState({ collaborators: sceneData.collaborators });
  1751. }
  1752. },
  1753. );
  1754. private onSceneUpdated = () => {
  1755. this.setState({});
  1756. };
  1757. /**
  1758. * @returns whether the menu was toggled on or off
  1759. */
  1760. public toggleMenu = (
  1761. type: "library" | "customSidebar",
  1762. force?: boolean,
  1763. ): boolean => {
  1764. if (type === "customSidebar" && !this.props.renderSidebar) {
  1765. console.warn(
  1766. `attempting to toggle "customSidebar", but no "props.renderSidebar" is defined`,
  1767. );
  1768. return false;
  1769. }
  1770. if (type === "library" || type === "customSidebar") {
  1771. let nextValue;
  1772. if (force === undefined) {
  1773. nextValue = this.state.openSidebar === type ? null : type;
  1774. } else {
  1775. nextValue = force ? type : null;
  1776. }
  1777. this.setState({ openSidebar: nextValue });
  1778. return !!nextValue;
  1779. }
  1780. return false;
  1781. };
  1782. private updateCurrentCursorPosition = withBatchedUpdates(
  1783. (event: MouseEvent) => {
  1784. cursorX = event.clientX;
  1785. cursorY = event.clientY;
  1786. },
  1787. );
  1788. // Input handling
  1789. private onKeyDown = withBatchedUpdates(
  1790. (event: React.KeyboardEvent | KeyboardEvent) => {
  1791. // normalize `event.key` when CapsLock is pressed #2372
  1792. if (
  1793. "Proxy" in window &&
  1794. ((!event.shiftKey && /^[A-Z]$/.test(event.key)) ||
  1795. (event.shiftKey && /^[a-z]$/.test(event.key)))
  1796. ) {
  1797. event = new Proxy(event, {
  1798. get(ev: any, prop) {
  1799. const value = ev[prop];
  1800. if (typeof value === "function") {
  1801. // fix for Proxies hijacking `this`
  1802. return value.bind(ev);
  1803. }
  1804. return prop === "key"
  1805. ? // CapsLock inverts capitalization based on ShiftKey, so invert
  1806. // it back
  1807. event.shiftKey
  1808. ? ev.key.toUpperCase()
  1809. : ev.key.toLowerCase()
  1810. : value;
  1811. },
  1812. });
  1813. }
  1814. if (event[KEYS.CTRL_OR_CMD] && event.key.toLowerCase() === KEYS.V) {
  1815. IS_PLAIN_PASTE = event.shiftKey;
  1816. clearTimeout(IS_PLAIN_PASTE_TIMER);
  1817. // reset (100ms to be safe that we it runs after the ensuing
  1818. // paste event). Though, technically unnecessary to reset since we
  1819. // (re)set the flag before each paste event.
  1820. IS_PLAIN_PASTE_TIMER = window.setTimeout(() => {
  1821. IS_PLAIN_PASTE = false;
  1822. }, 100);
  1823. }
  1824. // prevent browser zoom in input fields
  1825. if (event[KEYS.CTRL_OR_CMD] && isWritableElement(event.target)) {
  1826. if (event.code === CODES.MINUS || event.code === CODES.EQUAL) {
  1827. event.preventDefault();
  1828. return;
  1829. }
  1830. }
  1831. // bail if
  1832. if (
  1833. // inside an input
  1834. (isWritableElement(event.target) &&
  1835. // unless pressing escape (finalize action)
  1836. event.key !== KEYS.ESCAPE) ||
  1837. // or unless using arrows (to move between buttons)
  1838. (isArrowKey(event.key) && isInputLike(event.target))
  1839. ) {
  1840. return;
  1841. }
  1842. if (event.key === KEYS.QUESTION_MARK) {
  1843. this.setState({
  1844. openDialog: "help",
  1845. });
  1846. return;
  1847. } else if (
  1848. event.key.toLowerCase() === KEYS.E &&
  1849. event.shiftKey &&
  1850. event[KEYS.CTRL_OR_CMD]
  1851. ) {
  1852. this.setState({ openDialog: "imageExport" });
  1853. return;
  1854. }
  1855. if (event.key === KEYS.PAGE_UP || event.key === KEYS.PAGE_DOWN) {
  1856. let offset =
  1857. (event.shiftKey ? this.state.width : this.state.height) /
  1858. this.state.zoom.value;
  1859. if (event.key === KEYS.PAGE_DOWN) {
  1860. offset = -offset;
  1861. }
  1862. if (event.shiftKey) {
  1863. this.setState((state) => ({ scrollX: state.scrollX + offset }));
  1864. } else {
  1865. this.setState((state) => ({ scrollY: state.scrollY + offset }));
  1866. }
  1867. }
  1868. if (this.actionManager.handleKeyDown(event)) {
  1869. return;
  1870. }
  1871. if (this.state.viewModeEnabled) {
  1872. return;
  1873. }
  1874. if (event[KEYS.CTRL_OR_CMD] && this.state.isBindingEnabled) {
  1875. this.setState({ isBindingEnabled: false });
  1876. }
  1877. if (isArrowKey(event.key)) {
  1878. const step =
  1879. (this.state.gridSize &&
  1880. (event.shiftKey
  1881. ? ELEMENT_TRANSLATE_AMOUNT
  1882. : this.state.gridSize)) ||
  1883. (event.shiftKey
  1884. ? ELEMENT_SHIFT_TRANSLATE_AMOUNT
  1885. : ELEMENT_TRANSLATE_AMOUNT);
  1886. let offsetX = 0;
  1887. let offsetY = 0;
  1888. if (event.key === KEYS.ARROW_LEFT) {
  1889. offsetX = -step;
  1890. } else if (event.key === KEYS.ARROW_RIGHT) {
  1891. offsetX = step;
  1892. } else if (event.key === KEYS.ARROW_UP) {
  1893. offsetY = -step;
  1894. } else if (event.key === KEYS.ARROW_DOWN) {
  1895. offsetY = step;
  1896. }
  1897. const selectedElements = getSelectedElements(
  1898. this.scene.getNonDeletedElements(),
  1899. this.state,
  1900. true,
  1901. );
  1902. selectedElements.forEach((element) => {
  1903. mutateElement(element, {
  1904. x: element.x + offsetX,
  1905. y: element.y + offsetY,
  1906. });
  1907. updateBoundElements(element, {
  1908. simultaneouslyUpdated: selectedElements,
  1909. });
  1910. });
  1911. this.maybeSuggestBindingForAll(selectedElements);
  1912. event.preventDefault();
  1913. } else if (event.key === KEYS.ENTER) {
  1914. const selectedElements = getSelectedElements(
  1915. this.scene.getNonDeletedElements(),
  1916. this.state,
  1917. );
  1918. if (selectedElements.length === 1) {
  1919. const selectedElement = selectedElements[0];
  1920. if (event[KEYS.CTRL_OR_CMD]) {
  1921. if (isLinearElement(selectedElement)) {
  1922. if (
  1923. !this.state.editingLinearElement ||
  1924. this.state.editingLinearElement.elementId !==
  1925. selectedElements[0].id
  1926. ) {
  1927. this.history.resumeRecording();
  1928. this.setState({
  1929. editingLinearElement: new LinearElementEditor(
  1930. selectedElement,
  1931. this.scene,
  1932. ),
  1933. });
  1934. }
  1935. }
  1936. } else if (
  1937. isTextElement(selectedElement) ||
  1938. isValidTextContainer(selectedElement)
  1939. ) {
  1940. let container;
  1941. if (!isTextElement(selectedElement)) {
  1942. container = selectedElement as ExcalidrawTextContainer;
  1943. }
  1944. const midPoint = getContainerCenter(selectedElement, this.state);
  1945. const sceneX = midPoint.x;
  1946. const sceneY = midPoint.y;
  1947. this.startTextEditing({
  1948. sceneX,
  1949. sceneY,
  1950. container,
  1951. });
  1952. event.preventDefault();
  1953. return;
  1954. }
  1955. }
  1956. } else if (
  1957. !event.ctrlKey &&
  1958. !event.altKey &&
  1959. !event.metaKey &&
  1960. this.state.draggingElement === null
  1961. ) {
  1962. const shape = findShapeByKey(event.key);
  1963. if (shape) {
  1964. if (this.state.activeTool.type !== shape) {
  1965. trackEvent(
  1966. "toolbar",
  1967. shape,
  1968. `keyboard (${this.device.isMobile ? "mobile" : "desktop"})`,
  1969. );
  1970. }
  1971. this.setActiveTool({ type: shape });
  1972. event.stopPropagation();
  1973. } else if (event.key === KEYS.Q) {
  1974. this.toggleLock("keyboard");
  1975. event.stopPropagation();
  1976. }
  1977. }
  1978. if (event.key === KEYS.SPACE && gesture.pointers.size === 0) {
  1979. isHoldingSpace = true;
  1980. setCursor(this.canvas, CURSOR_TYPE.GRAB);
  1981. event.preventDefault();
  1982. }
  1983. if (
  1984. (event.key === KEYS.G || event.key === KEYS.S) &&
  1985. !event.altKey &&
  1986. !event[KEYS.CTRL_OR_CMD]
  1987. ) {
  1988. const selectedElements = getSelectedElements(
  1989. this.scene.getNonDeletedElements(),
  1990. this.state,
  1991. );
  1992. if (
  1993. this.state.activeTool.type === "selection" &&
  1994. !selectedElements.length
  1995. ) {
  1996. return;
  1997. }
  1998. if (
  1999. event.key === KEYS.G &&
  2000. (hasBackground(this.state.activeTool.type) ||
  2001. selectedElements.some((element) => hasBackground(element.type)))
  2002. ) {
  2003. this.setState({ openPopup: "backgroundColorPicker" });
  2004. event.stopPropagation();
  2005. }
  2006. if (event.key === KEYS.S) {
  2007. this.setState({ openPopup: "strokeColorPicker" });
  2008. event.stopPropagation();
  2009. }
  2010. }
  2011. },
  2012. );
  2013. private onWheel = withBatchedUpdates((event: WheelEvent) => {
  2014. // prevent browser pinch zoom on DOM elements
  2015. if (!(event.target instanceof HTMLCanvasElement) && event.ctrlKey) {
  2016. event.preventDefault();
  2017. }
  2018. });
  2019. private onKeyUp = withBatchedUpdates((event: KeyboardEvent) => {
  2020. if (event.key === KEYS.SPACE) {
  2021. if (this.state.viewModeEnabled) {
  2022. setCursor(this.canvas, CURSOR_TYPE.GRAB);
  2023. } else if (this.state.activeTool.type === "selection") {
  2024. resetCursor(this.canvas);
  2025. } else {
  2026. setCursorForShape(this.canvas, this.state);
  2027. this.setState({
  2028. selectedElementIds: {},
  2029. selectedGroupIds: {},
  2030. editingGroupId: null,
  2031. });
  2032. }
  2033. isHoldingSpace = false;
  2034. }
  2035. if (!event[KEYS.CTRL_OR_CMD] && !this.state.isBindingEnabled) {
  2036. this.setState({ isBindingEnabled: true });
  2037. }
  2038. if (isArrowKey(event.key)) {
  2039. const selectedElements = getSelectedElements(
  2040. this.scene.getNonDeletedElements(),
  2041. this.state,
  2042. );
  2043. isBindingEnabled(this.state)
  2044. ? bindOrUnbindSelectedElements(selectedElements)
  2045. : unbindLinearElements(selectedElements);
  2046. this.setState({ suggestedBindings: [] });
  2047. }
  2048. });
  2049. private setActiveTool = (
  2050. tool:
  2051. | { type: typeof SHAPES[number]["value"] | "eraser" }
  2052. | { type: "custom"; customType: string },
  2053. ) => {
  2054. const nextActiveTool = updateActiveTool(this.state, tool);
  2055. if (!isHoldingSpace) {
  2056. setCursorForShape(this.canvas, this.state);
  2057. }
  2058. if (isToolIcon(document.activeElement)) {
  2059. this.focusContainer();
  2060. }
  2061. if (!isLinearElementType(nextActiveTool.type)) {
  2062. this.setState({ suggestedBindings: [] });
  2063. }
  2064. if (nextActiveTool.type === "image") {
  2065. this.onImageAction();
  2066. }
  2067. if (nextActiveTool.type !== "selection") {
  2068. this.setState({
  2069. activeTool: nextActiveTool,
  2070. selectedElementIds: {},
  2071. selectedGroupIds: {},
  2072. editingGroupId: null,
  2073. });
  2074. } else {
  2075. this.setState({ activeTool: nextActiveTool });
  2076. }
  2077. };
  2078. private setCursor = (cursor: string) => {
  2079. setCursor(this.canvas, cursor);
  2080. };
  2081. private resetCursor = () => {
  2082. resetCursor(this.canvas);
  2083. };
  2084. /**
  2085. * returns whether user is making a gesture with >= 2 fingers (points)
  2086. * on o touch screen (not on a trackpad). Currently only relates to Darwin
  2087. * (iOS/iPadOS,MacOS), but may work on other devices in the future if
  2088. * GestureEvent is standardized.
  2089. */
  2090. private isTouchScreenMultiTouchGesture = () => {
  2091. // we don't want to deselect when using trackpad, and multi-point gestures
  2092. // only work on touch screens, so checking for >= pointers means we're on a
  2093. // touchscreen
  2094. return gesture.pointers.size >= 2;
  2095. };
  2096. // fires only on Safari
  2097. private onGestureStart = withBatchedUpdates((event: GestureEvent) => {
  2098. event.preventDefault();
  2099. // we only want to deselect on touch screens because user may have selected
  2100. // elements by mistake while zooming
  2101. if (this.isTouchScreenMultiTouchGesture()) {
  2102. this.setState({
  2103. selectedElementIds: {},
  2104. });
  2105. }
  2106. gesture.initialScale = this.state.zoom.value;
  2107. });
  2108. // fires only on Safari
  2109. private onGestureChange = withBatchedUpdates((event: GestureEvent) => {
  2110. event.preventDefault();
  2111. // onGestureChange only has zoom factor but not the center.
  2112. // If we're on iPad or iPhone, then we recognize multi-touch and will
  2113. // zoom in at the right location in the touchmove handler
  2114. // (handleCanvasPointerMove).
  2115. //
  2116. // On Macbook trackpad, we don't have those events so will zoom in at the
  2117. // current location instead.
  2118. //
  2119. // As such, bail from this handler on touch devices.
  2120. if (this.isTouchScreenMultiTouchGesture()) {
  2121. return;
  2122. }
  2123. const initialScale = gesture.initialScale;
  2124. if (initialScale) {
  2125. this.setState((state) => ({
  2126. ...getStateForZoom(
  2127. {
  2128. viewportX: cursorX,
  2129. viewportY: cursorY,
  2130. nextZoom: getNormalizedZoom(initialScale * event.scale),
  2131. },
  2132. state,
  2133. ),
  2134. }));
  2135. }
  2136. });
  2137. // fires only on Safari
  2138. private onGestureEnd = withBatchedUpdates((event: GestureEvent) => {
  2139. event.preventDefault();
  2140. // reselect elements only on touch screens (see onGestureStart)
  2141. if (this.isTouchScreenMultiTouchGesture()) {
  2142. this.setState({
  2143. previousSelectedElementIds: {},
  2144. selectedElementIds: this.state.previousSelectedElementIds,
  2145. });
  2146. }
  2147. gesture.initialScale = null;
  2148. });
  2149. private handleTextWysiwyg(
  2150. element: ExcalidrawTextElement,
  2151. {
  2152. isExistingElement = false,
  2153. }: {
  2154. isExistingElement?: boolean;
  2155. },
  2156. ) {
  2157. const updateElement = (
  2158. text: string,
  2159. originalText: string,
  2160. isDeleted: boolean,
  2161. ) => {
  2162. this.scene.replaceAllElements([
  2163. ...this.scene.getElementsIncludingDeleted().map((_element) => {
  2164. if (_element.id === element.id && isTextElement(_element)) {
  2165. return updateTextElement(_element, {
  2166. text,
  2167. isDeleted,
  2168. originalText,
  2169. });
  2170. }
  2171. return _element;
  2172. }),
  2173. ]);
  2174. };
  2175. textWysiwyg({
  2176. id: element.id,
  2177. canvas: this.canvas,
  2178. getViewportCoords: (x, y) => {
  2179. const { x: viewportX, y: viewportY } = sceneCoordsToViewportCoords(
  2180. {
  2181. sceneX: x,
  2182. sceneY: y,
  2183. },
  2184. this.state,
  2185. );
  2186. return [
  2187. viewportX - this.state.offsetLeft,
  2188. viewportY - this.state.offsetTop,
  2189. ];
  2190. },
  2191. onChange: withBatchedUpdates((text) => {
  2192. updateElement(text, text, false);
  2193. if (isNonDeletedElement(element)) {
  2194. updateBoundElements(element);
  2195. }
  2196. }),
  2197. onSubmit: withBatchedUpdates(({ text, viaKeyboard, originalText }) => {
  2198. const isDeleted = !text.trim();
  2199. updateElement(text, originalText, isDeleted);
  2200. // select the created text element only if submitting via keyboard
  2201. // (when submitting via click it should act as signal to deselect)
  2202. if (!isDeleted && viaKeyboard) {
  2203. const elementIdToSelect = element.containerId
  2204. ? element.containerId
  2205. : element.id;
  2206. this.setState((prevState) => ({
  2207. selectedElementIds: {
  2208. ...prevState.selectedElementIds,
  2209. [elementIdToSelect]: true,
  2210. },
  2211. }));
  2212. }
  2213. if (isDeleted) {
  2214. fixBindingsAfterDeletion(this.scene.getNonDeletedElements(), [
  2215. element,
  2216. ]);
  2217. }
  2218. if (!isDeleted || isExistingElement) {
  2219. this.history.resumeRecording();
  2220. }
  2221. this.setState({
  2222. draggingElement: null,
  2223. editingElement: null,
  2224. });
  2225. if (this.state.activeTool.locked) {
  2226. setCursorForShape(this.canvas, this.state);
  2227. }
  2228. this.focusContainer();
  2229. }),
  2230. element,
  2231. excalidrawContainer: this.excalidrawContainerRef.current,
  2232. app: this,
  2233. });
  2234. // deselect all other elements when inserting text
  2235. this.deselectElements();
  2236. // do an initial update to re-initialize element position since we were
  2237. // modifying element's x/y for sake of editor (case: syncing to remote)
  2238. updateElement(element.text, element.originalText, false);
  2239. }
  2240. private deselectElements() {
  2241. this.setState({
  2242. selectedElementIds: {},
  2243. selectedGroupIds: {},
  2244. editingGroupId: null,
  2245. });
  2246. }
  2247. private getTextElementAtPosition(
  2248. x: number,
  2249. y: number,
  2250. ): NonDeleted<ExcalidrawTextElement> | null {
  2251. const element = this.getElementAtPosition(x, y, {
  2252. includeBoundTextElement: true,
  2253. });
  2254. if (element && isTextElement(element) && !element.isDeleted) {
  2255. return element;
  2256. }
  2257. return null;
  2258. }
  2259. private getElementAtPosition(
  2260. x: number,
  2261. y: number,
  2262. opts?: {
  2263. /** if true, returns the first selected element (with highest z-index)
  2264. of all hit elements */
  2265. preferSelected?: boolean;
  2266. includeBoundTextElement?: boolean;
  2267. includeLockedElements?: boolean;
  2268. },
  2269. ): NonDeleted<ExcalidrawElement> | null {
  2270. const allHitElements = this.getElementsAtPosition(
  2271. x,
  2272. y,
  2273. opts?.includeBoundTextElement,
  2274. opts?.includeLockedElements,
  2275. );
  2276. if (allHitElements.length > 1) {
  2277. if (opts?.preferSelected) {
  2278. for (let index = allHitElements.length - 1; index > -1; index--) {
  2279. if (this.state.selectedElementIds[allHitElements[index].id]) {
  2280. return allHitElements[index];
  2281. }
  2282. }
  2283. }
  2284. const elementWithHighestZIndex =
  2285. allHitElements[allHitElements.length - 1];
  2286. // If we're hitting element with highest z-index only on its bounding box
  2287. // while also hitting other element figure, the latter should be considered.
  2288. return isHittingElementBoundingBoxWithoutHittingElement(
  2289. elementWithHighestZIndex,
  2290. this.state,
  2291. x,
  2292. y,
  2293. )
  2294. ? allHitElements[allHitElements.length - 2]
  2295. : elementWithHighestZIndex;
  2296. }
  2297. if (allHitElements.length === 1) {
  2298. return allHitElements[0];
  2299. }
  2300. return null;
  2301. }
  2302. private getElementsAtPosition(
  2303. x: number,
  2304. y: number,
  2305. includeBoundTextElement: boolean = false,
  2306. includeLockedElements: boolean = false,
  2307. ): NonDeleted<ExcalidrawElement>[] {
  2308. const elements =
  2309. includeBoundTextElement && includeLockedElements
  2310. ? this.scene.getNonDeletedElements()
  2311. : this.scene
  2312. .getNonDeletedElements()
  2313. .filter(
  2314. (element) =>
  2315. (includeLockedElements || !element.locked) &&
  2316. (includeBoundTextElement ||
  2317. !(isTextElement(element) && element.containerId)),
  2318. );
  2319. return getElementsAtPosition(elements, (element) =>
  2320. hitTest(element, this.state, x, y),
  2321. );
  2322. }
  2323. private startTextEditing = ({
  2324. sceneX,
  2325. sceneY,
  2326. insertAtParentCenter = true,
  2327. container,
  2328. }: {
  2329. /** X position to insert text at */
  2330. sceneX: number;
  2331. /** Y position to insert text at */
  2332. sceneY: number;
  2333. /** whether to attempt to insert at element center if applicable */
  2334. insertAtParentCenter?: boolean;
  2335. container?: ExcalidrawTextContainer | null;
  2336. }) => {
  2337. let shouldBindToContainer = false;
  2338. let parentCenterPosition =
  2339. insertAtParentCenter &&
  2340. this.getTextWysiwygSnappedToCenterPosition(
  2341. sceneX,
  2342. sceneY,
  2343. this.state,
  2344. container,
  2345. );
  2346. if (container && parentCenterPosition) {
  2347. shouldBindToContainer = true;
  2348. }
  2349. let existingTextElement: NonDeleted<ExcalidrawTextElement> | null = null;
  2350. const selectedElements = getSelectedElements(
  2351. this.scene.getNonDeletedElements(),
  2352. this.state,
  2353. );
  2354. if (selectedElements.length === 1) {
  2355. if (isTextElement(selectedElements[0])) {
  2356. existingTextElement = selectedElements[0];
  2357. } else if (container) {
  2358. existingTextElement = getBoundTextElement(selectedElements[0]);
  2359. } else {
  2360. existingTextElement = this.getTextElementAtPosition(sceneX, sceneY);
  2361. }
  2362. } else {
  2363. existingTextElement = this.getTextElementAtPosition(sceneX, sceneY);
  2364. }
  2365. if (
  2366. !existingTextElement &&
  2367. shouldBindToContainer &&
  2368. container &&
  2369. !isArrowElement(container)
  2370. ) {
  2371. const fontString = {
  2372. fontSize: this.state.currentItemFontSize,
  2373. fontFamily: this.state.currentItemFontFamily,
  2374. };
  2375. const minWidth = getApproxMinLineWidth(getFontString(fontString));
  2376. const minHeight = getApproxMinLineHeight(getFontString(fontString));
  2377. const containerDims = getContainerDims(container);
  2378. const newHeight = Math.max(containerDims.height, minHeight);
  2379. const newWidth = Math.max(containerDims.width, minWidth);
  2380. mutateElement(container, { height: newHeight, width: newWidth });
  2381. sceneX = container.x + newWidth / 2;
  2382. sceneY = container.y + newHeight / 2;
  2383. if (parentCenterPosition) {
  2384. parentCenterPosition = this.getTextWysiwygSnappedToCenterPosition(
  2385. sceneX,
  2386. sceneY,
  2387. this.state,
  2388. container,
  2389. );
  2390. }
  2391. }
  2392. const element = existingTextElement
  2393. ? existingTextElement
  2394. : newTextElement({
  2395. x: parentCenterPosition
  2396. ? parentCenterPosition.elementCenterX
  2397. : sceneX,
  2398. y: parentCenterPosition
  2399. ? parentCenterPosition.elementCenterY
  2400. : sceneY,
  2401. strokeColor: this.state.currentItemStrokeColor,
  2402. backgroundColor: this.state.currentItemBackgroundColor,
  2403. fillStyle: this.state.currentItemFillStyle,
  2404. strokeWidth: this.state.currentItemStrokeWidth,
  2405. strokeStyle: this.state.currentItemStrokeStyle,
  2406. roughness: this.state.currentItemRoughness,
  2407. opacity: this.state.currentItemOpacity,
  2408. roundness: null,
  2409. text: "",
  2410. fontSize: this.state.currentItemFontSize,
  2411. fontFamily: this.state.currentItemFontFamily,
  2412. textAlign: parentCenterPosition
  2413. ? "center"
  2414. : this.state.currentItemTextAlign,
  2415. verticalAlign: parentCenterPosition
  2416. ? VERTICAL_ALIGN.MIDDLE
  2417. : DEFAULT_VERTICAL_ALIGN,
  2418. containerId: shouldBindToContainer ? container?.id : undefined,
  2419. groupIds: container?.groupIds ?? [],
  2420. locked: false,
  2421. });
  2422. if (!existingTextElement && shouldBindToContainer && container) {
  2423. mutateElement(container, {
  2424. boundElements: (container.boundElements || []).concat({
  2425. type: "text",
  2426. id: element.id,
  2427. }),
  2428. });
  2429. }
  2430. this.setState({ editingElement: element });
  2431. if (!existingTextElement) {
  2432. if (container && shouldBindToContainer) {
  2433. const containerIndex = this.scene.getElementIndex(container.id);
  2434. this.scene.insertElementAtIndex(element, containerIndex + 1);
  2435. } else {
  2436. this.scene.replaceAllElements([
  2437. ...this.scene.getElementsIncludingDeleted(),
  2438. element,
  2439. ]);
  2440. }
  2441. // case: creating new text not centered to parent element → offset Y
  2442. // so that the text is centered to cursor position
  2443. if (!parentCenterPosition) {
  2444. mutateElement(element, {
  2445. y: element.y - element.baseline / 2,
  2446. });
  2447. }
  2448. }
  2449. this.setState({
  2450. editingElement: element,
  2451. });
  2452. this.handleTextWysiwyg(element, {
  2453. isExistingElement: !!existingTextElement,
  2454. });
  2455. };
  2456. private handleCanvasDoubleClick = (
  2457. event: React.MouseEvent<HTMLCanvasElement>,
  2458. ) => {
  2459. // case: double-clicking with arrow/line tool selected would both create
  2460. // text and enter multiElement mode
  2461. if (this.state.multiElement) {
  2462. return;
  2463. }
  2464. // we should only be able to double click when mode is selection
  2465. if (this.state.activeTool.type !== "selection") {
  2466. return;
  2467. }
  2468. const selectedElements = getSelectedElements(
  2469. this.scene.getNonDeletedElements(),
  2470. this.state,
  2471. );
  2472. if (selectedElements.length === 1 && isLinearElement(selectedElements[0])) {
  2473. if (
  2474. event[KEYS.CTRL_OR_CMD] &&
  2475. (!this.state.editingLinearElement ||
  2476. this.state.editingLinearElement.elementId !== selectedElements[0].id)
  2477. ) {
  2478. this.history.resumeRecording();
  2479. this.setState({
  2480. editingLinearElement: new LinearElementEditor(
  2481. selectedElements[0],
  2482. this.scene,
  2483. ),
  2484. });
  2485. return;
  2486. } else if (
  2487. this.state.editingLinearElement &&
  2488. this.state.editingLinearElement.elementId === selectedElements[0].id
  2489. ) {
  2490. return;
  2491. }
  2492. }
  2493. resetCursor(this.canvas);
  2494. let { x: sceneX, y: sceneY } = viewportCoordsToSceneCoords(
  2495. event,
  2496. this.state,
  2497. );
  2498. const selectedGroupIds = getSelectedGroupIds(this.state);
  2499. if (selectedGroupIds.length > 0) {
  2500. const hitElement = this.getElementAtPosition(sceneX, sceneY);
  2501. const selectedGroupId =
  2502. hitElement &&
  2503. getSelectedGroupIdForElement(hitElement, this.state.selectedGroupIds);
  2504. if (selectedGroupId) {
  2505. this.setState((prevState) =>
  2506. selectGroupsForSelectedElements(
  2507. {
  2508. ...prevState,
  2509. editingGroupId: selectedGroupId,
  2510. selectedElementIds: { [hitElement!.id]: true },
  2511. selectedGroupIds: {},
  2512. },
  2513. this.scene.getNonDeletedElements(),
  2514. ),
  2515. );
  2516. return;
  2517. }
  2518. }
  2519. resetCursor(this.canvas);
  2520. if (!event[KEYS.CTRL_OR_CMD] && !this.state.viewModeEnabled) {
  2521. const container = getTextBindableContainerAtPosition(
  2522. this.scene.getNonDeletedElements(),
  2523. this.state,
  2524. sceneX,
  2525. sceneY,
  2526. );
  2527. if (container) {
  2528. if (isArrowElement(container) || hasBoundTextElement(container)) {
  2529. const midPoint = getContainerCenter(container, this.state);
  2530. sceneX = midPoint.x;
  2531. sceneY = midPoint.y;
  2532. }
  2533. }
  2534. this.startTextEditing({
  2535. sceneX,
  2536. sceneY,
  2537. insertAtParentCenter: !event.altKey,
  2538. container,
  2539. });
  2540. }
  2541. };
  2542. private getElementLinkAtPosition = (
  2543. scenePointer: Readonly<{ x: number; y: number }>,
  2544. hitElement: NonDeletedExcalidrawElement | null,
  2545. ): ExcalidrawElement | undefined => {
  2546. // Reversing so we traverse the elements in decreasing order
  2547. // of z-index
  2548. const elements = this.scene.getNonDeletedElements().slice().reverse();
  2549. let hitElementIndex = Infinity;
  2550. return elements.find((element, index) => {
  2551. if (hitElement && element.id === hitElement.id) {
  2552. hitElementIndex = index;
  2553. }
  2554. return (
  2555. element.link &&
  2556. index <= hitElementIndex &&
  2557. isPointHittingLinkIcon(
  2558. element,
  2559. this.state,
  2560. [scenePointer.x, scenePointer.y],
  2561. this.device.isMobile,
  2562. )
  2563. );
  2564. });
  2565. };
  2566. private redirectToLink = (
  2567. event: React.PointerEvent<HTMLCanvasElement>,
  2568. isTouchScreen: boolean,
  2569. ) => {
  2570. const draggedDistance = distance2d(
  2571. this.lastPointerDown!.clientX,
  2572. this.lastPointerDown!.clientY,
  2573. this.lastPointerUp!.clientX,
  2574. this.lastPointerUp!.clientY,
  2575. );
  2576. if (
  2577. !this.hitLinkElement ||
  2578. // For touch screen allow dragging threshold else strict check
  2579. (isTouchScreen && draggedDistance > DRAGGING_THRESHOLD) ||
  2580. (!isTouchScreen && draggedDistance !== 0)
  2581. ) {
  2582. return;
  2583. }
  2584. const lastPointerDownCoords = viewportCoordsToSceneCoords(
  2585. this.lastPointerDown!,
  2586. this.state,
  2587. );
  2588. const lastPointerDownHittingLinkIcon = isPointHittingLinkIcon(
  2589. this.hitLinkElement,
  2590. this.state,
  2591. [lastPointerDownCoords.x, lastPointerDownCoords.y],
  2592. this.device.isMobile,
  2593. );
  2594. const lastPointerUpCoords = viewportCoordsToSceneCoords(
  2595. this.lastPointerUp!,
  2596. this.state,
  2597. );
  2598. const lastPointerUpHittingLinkIcon = isPointHittingLinkIcon(
  2599. this.hitLinkElement,
  2600. this.state,
  2601. [lastPointerUpCoords.x, lastPointerUpCoords.y],
  2602. this.device.isMobile,
  2603. );
  2604. if (lastPointerDownHittingLinkIcon && lastPointerUpHittingLinkIcon) {
  2605. const url = this.hitLinkElement.link;
  2606. if (url) {
  2607. let customEvent;
  2608. if (this.props.onLinkOpen) {
  2609. customEvent = wrapEvent(EVENT.EXCALIDRAW_LINK, event.nativeEvent);
  2610. this.props.onLinkOpen(this.hitLinkElement, customEvent);
  2611. }
  2612. if (!customEvent?.defaultPrevented) {
  2613. const target = isLocalLink(url) ? "_self" : "_blank";
  2614. const newWindow = window.open(undefined, target);
  2615. // https://mathiasbynens.github.io/rel-noopener/
  2616. if (newWindow) {
  2617. newWindow.opener = null;
  2618. newWindow.location = normalizeLink(url);
  2619. }
  2620. }
  2621. }
  2622. }
  2623. };
  2624. private handleCanvasPointerMove = (
  2625. event: React.PointerEvent<HTMLCanvasElement>,
  2626. ) => {
  2627. this.savePointer(event.clientX, event.clientY, this.state.cursorButton);
  2628. if (gesture.pointers.has(event.pointerId)) {
  2629. gesture.pointers.set(event.pointerId, {
  2630. x: event.clientX,
  2631. y: event.clientY,
  2632. });
  2633. }
  2634. const initialScale = gesture.initialScale;
  2635. if (
  2636. gesture.pointers.size === 2 &&
  2637. gesture.lastCenter &&
  2638. initialScale &&
  2639. gesture.initialDistance
  2640. ) {
  2641. const center = getCenter(gesture.pointers);
  2642. const deltaX = center.x - gesture.lastCenter.x;
  2643. const deltaY = center.y - gesture.lastCenter.y;
  2644. gesture.lastCenter = center;
  2645. const distance = getDistance(Array.from(gesture.pointers.values()));
  2646. const scaleFactor =
  2647. this.state.activeTool.type === "freedraw" && this.state.penMode
  2648. ? 1
  2649. : distance / gesture.initialDistance;
  2650. const nextZoom = scaleFactor
  2651. ? getNormalizedZoom(initialScale * scaleFactor)
  2652. : this.state.zoom.value;
  2653. this.setState((state) => {
  2654. const zoomState = getStateForZoom(
  2655. {
  2656. viewportX: center.x,
  2657. viewportY: center.y,
  2658. nextZoom,
  2659. },
  2660. state,
  2661. );
  2662. return {
  2663. zoom: zoomState.zoom,
  2664. scrollX: zoomState.scrollX + deltaX / nextZoom,
  2665. scrollY: zoomState.scrollY + deltaY / nextZoom,
  2666. shouldCacheIgnoreZoom: true,
  2667. };
  2668. });
  2669. this.resetShouldCacheIgnoreZoomDebounced();
  2670. } else {
  2671. gesture.lastCenter =
  2672. gesture.initialDistance =
  2673. gesture.initialScale =
  2674. null;
  2675. }
  2676. if (isHoldingSpace || isPanning || isDraggingScrollBar) {
  2677. return;
  2678. }
  2679. const isPointerOverScrollBars = isOverScrollBars(
  2680. currentScrollBars,
  2681. event.clientX - this.state.offsetLeft,
  2682. event.clientY - this.state.offsetTop,
  2683. );
  2684. const isOverScrollBar = isPointerOverScrollBars.isOverEither;
  2685. if (!this.state.draggingElement && !this.state.multiElement) {
  2686. if (isOverScrollBar) {
  2687. resetCursor(this.canvas);
  2688. } else {
  2689. setCursorForShape(this.canvas, this.state);
  2690. }
  2691. }
  2692. const scenePointer = viewportCoordsToSceneCoords(event, this.state);
  2693. const { x: scenePointerX, y: scenePointerY } = scenePointer;
  2694. if (
  2695. this.state.editingLinearElement &&
  2696. !this.state.editingLinearElement.isDragging
  2697. ) {
  2698. const editingLinearElement = LinearElementEditor.handlePointerMove(
  2699. event,
  2700. scenePointerX,
  2701. scenePointerY,
  2702. this.state,
  2703. );
  2704. if (
  2705. editingLinearElement &&
  2706. editingLinearElement !== this.state.editingLinearElement
  2707. ) {
  2708. // Since we are reading from previous state which is not possible with
  2709. // automatic batching in React 18 hence using flush sync to synchronously
  2710. // update the state. Check https://github.com/excalidraw/excalidraw/pull/5508 for more details.
  2711. flushSync(() => {
  2712. this.setState({
  2713. editingLinearElement,
  2714. });
  2715. });
  2716. }
  2717. if (editingLinearElement?.lastUncommittedPoint != null) {
  2718. this.maybeSuggestBindingAtCursor(scenePointer);
  2719. } else {
  2720. // causes stack overflow if not sync
  2721. flushSync(() => {
  2722. this.setState({ suggestedBindings: [] });
  2723. });
  2724. }
  2725. }
  2726. if (isBindingElementType(this.state.activeTool.type)) {
  2727. // Hovering with a selected tool or creating new linear element via click
  2728. // and point
  2729. const { draggingElement } = this.state;
  2730. if (isBindingElement(draggingElement, false)) {
  2731. this.maybeSuggestBindingsForLinearElementAtCoords(
  2732. draggingElement,
  2733. [scenePointer],
  2734. this.state.startBoundElement,
  2735. );
  2736. } else {
  2737. this.maybeSuggestBindingAtCursor(scenePointer);
  2738. }
  2739. }
  2740. if (this.state.multiElement) {
  2741. const { multiElement } = this.state;
  2742. const { x: rx, y: ry } = multiElement;
  2743. const { points, lastCommittedPoint } = multiElement;
  2744. const lastPoint = points[points.length - 1];
  2745. setCursorForShape(this.canvas, this.state);
  2746. if (lastPoint === lastCommittedPoint) {
  2747. // if we haven't yet created a temp point and we're beyond commit-zone
  2748. // threshold, add a point
  2749. if (
  2750. distance2d(
  2751. scenePointerX - rx,
  2752. scenePointerY - ry,
  2753. lastPoint[0],
  2754. lastPoint[1],
  2755. ) >= LINE_CONFIRM_THRESHOLD
  2756. ) {
  2757. mutateElement(multiElement, {
  2758. points: [...points, [scenePointerX - rx, scenePointerY - ry]],
  2759. });
  2760. } else {
  2761. setCursor(this.canvas, CURSOR_TYPE.POINTER);
  2762. // in this branch, we're inside the commit zone, and no uncommitted
  2763. // point exists. Thus do nothing (don't add/remove points).
  2764. }
  2765. } else if (
  2766. points.length > 2 &&
  2767. lastCommittedPoint &&
  2768. distance2d(
  2769. scenePointerX - rx,
  2770. scenePointerY - ry,
  2771. lastCommittedPoint[0],
  2772. lastCommittedPoint[1],
  2773. ) < LINE_CONFIRM_THRESHOLD
  2774. ) {
  2775. setCursor(this.canvas, CURSOR_TYPE.POINTER);
  2776. mutateElement(multiElement, {
  2777. points: points.slice(0, -1),
  2778. });
  2779. } else {
  2780. const [gridX, gridY] = getGridPoint(
  2781. scenePointerX,
  2782. scenePointerY,
  2783. this.state.gridSize,
  2784. );
  2785. const [lastCommittedX, lastCommittedY] =
  2786. multiElement?.lastCommittedPoint ?? [0, 0];
  2787. let dxFromLastCommitted = gridX - rx - lastCommittedX;
  2788. let dyFromLastCommitted = gridY - ry - lastCommittedY;
  2789. if (shouldRotateWithDiscreteAngle(event)) {
  2790. ({ width: dxFromLastCommitted, height: dyFromLastCommitted } =
  2791. getLockedLinearCursorAlignSize(
  2792. // actual coordinate of the last committed point
  2793. lastCommittedX + rx,
  2794. lastCommittedY + ry,
  2795. // cursor-grid coordinate
  2796. gridX,
  2797. gridY,
  2798. ));
  2799. }
  2800. if (isPathALoop(points, this.state.zoom.value)) {
  2801. setCursor(this.canvas, CURSOR_TYPE.POINTER);
  2802. }
  2803. // update last uncommitted point
  2804. mutateElement(multiElement, {
  2805. points: [
  2806. ...points.slice(0, -1),
  2807. [
  2808. lastCommittedX + dxFromLastCommitted,
  2809. lastCommittedY + dyFromLastCommitted,
  2810. ],
  2811. ],
  2812. });
  2813. }
  2814. return;
  2815. }
  2816. const hasDeselectedButton = Boolean(event.buttons);
  2817. if (
  2818. hasDeselectedButton ||
  2819. (this.state.activeTool.type !== "selection" &&
  2820. this.state.activeTool.type !== "text" &&
  2821. this.state.activeTool.type !== "eraser")
  2822. ) {
  2823. return;
  2824. }
  2825. const elements = this.scene.getNonDeletedElements();
  2826. const selectedElements = getSelectedElements(elements, this.state);
  2827. if (
  2828. selectedElements.length === 1 &&
  2829. !isOverScrollBar &&
  2830. !this.state.editingLinearElement
  2831. ) {
  2832. const elementWithTransformHandleType = getElementWithTransformHandleType(
  2833. elements,
  2834. this.state,
  2835. scenePointerX,
  2836. scenePointerY,
  2837. this.state.zoom,
  2838. event.pointerType,
  2839. );
  2840. if (
  2841. elementWithTransformHandleType &&
  2842. elementWithTransformHandleType.transformHandleType
  2843. ) {
  2844. setCursor(
  2845. this.canvas,
  2846. getCursorForResizingElement(elementWithTransformHandleType),
  2847. );
  2848. return;
  2849. }
  2850. } else if (selectedElements.length > 1 && !isOverScrollBar) {
  2851. const transformHandleType = getTransformHandleTypeFromCoords(
  2852. getCommonBounds(selectedElements),
  2853. scenePointerX,
  2854. scenePointerY,
  2855. this.state.zoom,
  2856. event.pointerType,
  2857. );
  2858. if (transformHandleType) {
  2859. setCursor(
  2860. this.canvas,
  2861. getCursorForResizingElement({
  2862. transformHandleType,
  2863. }),
  2864. );
  2865. return;
  2866. }
  2867. }
  2868. const hitElement = this.getElementAtPosition(
  2869. scenePointer.x,
  2870. scenePointer.y,
  2871. );
  2872. this.hitLinkElement = this.getElementLinkAtPosition(
  2873. scenePointer,
  2874. hitElement,
  2875. );
  2876. if (isEraserActive(this.state)) {
  2877. return;
  2878. }
  2879. if (
  2880. this.hitLinkElement &&
  2881. !this.state.selectedElementIds[this.hitLinkElement.id]
  2882. ) {
  2883. setCursor(this.canvas, CURSOR_TYPE.POINTER);
  2884. showHyperlinkTooltip(this.hitLinkElement, this.state);
  2885. } else {
  2886. hideHyperlinkToolip();
  2887. if (
  2888. hitElement &&
  2889. hitElement.link &&
  2890. this.state.selectedElementIds[hitElement.id] &&
  2891. !this.state.contextMenu &&
  2892. !this.state.showHyperlinkPopup
  2893. ) {
  2894. this.setState({ showHyperlinkPopup: "info" });
  2895. } else if (this.state.activeTool.type === "text") {
  2896. setCursor(
  2897. this.canvas,
  2898. isTextElement(hitElement) ? CURSOR_TYPE.TEXT : CURSOR_TYPE.CROSSHAIR,
  2899. );
  2900. } else if (this.state.viewModeEnabled) {
  2901. setCursor(this.canvas, CURSOR_TYPE.GRAB);
  2902. } else if (isOverScrollBar) {
  2903. setCursor(this.canvas, CURSOR_TYPE.AUTO);
  2904. } else if (this.state.selectedLinearElement) {
  2905. this.handleHoverSelectedLinearElement(
  2906. this.state.selectedLinearElement,
  2907. scenePointerX,
  2908. scenePointerY,
  2909. );
  2910. } else if (
  2911. // if using cmd/ctrl, we're not dragging
  2912. !event[KEYS.CTRL_OR_CMD]
  2913. ) {
  2914. if (
  2915. (hitElement ||
  2916. this.isHittingCommonBoundingBoxOfSelectedElements(
  2917. scenePointer,
  2918. selectedElements,
  2919. )) &&
  2920. !hitElement?.locked
  2921. ) {
  2922. setCursor(this.canvas, CURSOR_TYPE.MOVE);
  2923. }
  2924. } else {
  2925. setCursor(this.canvas, CURSOR_TYPE.AUTO);
  2926. }
  2927. }
  2928. };
  2929. private handleEraser = (
  2930. event: PointerEvent,
  2931. pointerDownState: PointerDownState,
  2932. scenePointer: { x: number; y: number },
  2933. ) => {
  2934. const updateElementIds = (elements: ExcalidrawElement[]) => {
  2935. elements.forEach((element) => {
  2936. if (element.locked) {
  2937. return;
  2938. }
  2939. idsToUpdate.push(element.id);
  2940. if (event.altKey) {
  2941. if (
  2942. pointerDownState.elementIdsToErase[element.id] &&
  2943. pointerDownState.elementIdsToErase[element.id].erase
  2944. ) {
  2945. pointerDownState.elementIdsToErase[element.id].erase = false;
  2946. }
  2947. } else if (!pointerDownState.elementIdsToErase[element.id]) {
  2948. pointerDownState.elementIdsToErase[element.id] = {
  2949. erase: true,
  2950. opacity: element.opacity,
  2951. };
  2952. }
  2953. });
  2954. };
  2955. const idsToUpdate: Array<string> = [];
  2956. const distance = distance2d(
  2957. pointerDownState.lastCoords.x,
  2958. pointerDownState.lastCoords.y,
  2959. scenePointer.x,
  2960. scenePointer.y,
  2961. );
  2962. const threshold = 10 / this.state.zoom.value;
  2963. const point = { ...pointerDownState.lastCoords };
  2964. let samplingInterval = 0;
  2965. while (samplingInterval <= distance) {
  2966. const hitElements = this.getElementsAtPosition(point.x, point.y);
  2967. updateElementIds(hitElements);
  2968. // Exit since we reached current point
  2969. if (samplingInterval === distance) {
  2970. break;
  2971. }
  2972. // Calculate next point in the line at a distance of sampling interval
  2973. samplingInterval = Math.min(samplingInterval + threshold, distance);
  2974. const distanceRatio = samplingInterval / distance;
  2975. const nextX =
  2976. (1 - distanceRatio) * point.x + distanceRatio * scenePointer.x;
  2977. const nextY =
  2978. (1 - distanceRatio) * point.y + distanceRatio * scenePointer.y;
  2979. point.x = nextX;
  2980. point.y = nextY;
  2981. }
  2982. const elements = this.scene.getElementsIncludingDeleted().map((ele) => {
  2983. const id =
  2984. isBoundToContainer(ele) && idsToUpdate.includes(ele.containerId)
  2985. ? ele.containerId
  2986. : ele.id;
  2987. if (idsToUpdate.includes(id)) {
  2988. if (event.altKey) {
  2989. if (
  2990. pointerDownState.elementIdsToErase[id] &&
  2991. pointerDownState.elementIdsToErase[id].erase === false
  2992. ) {
  2993. return newElementWith(ele, {
  2994. opacity: pointerDownState.elementIdsToErase[id].opacity,
  2995. });
  2996. }
  2997. } else {
  2998. return newElementWith(ele, {
  2999. opacity: ELEMENT_READY_TO_ERASE_OPACITY,
  3000. });
  3001. }
  3002. }
  3003. return ele;
  3004. });
  3005. this.scene.replaceAllElements(elements);
  3006. pointerDownState.lastCoords.x = scenePointer.x;
  3007. pointerDownState.lastCoords.y = scenePointer.y;
  3008. };
  3009. // set touch moving for mobile context menu
  3010. private handleTouchMove = (event: React.TouchEvent<HTMLCanvasElement>) => {
  3011. invalidateContextMenu = true;
  3012. };
  3013. handleHoverSelectedLinearElement(
  3014. linearElementEditor: LinearElementEditor,
  3015. scenePointerX: number,
  3016. scenePointerY: number,
  3017. ) {
  3018. const element = LinearElementEditor.getElement(
  3019. linearElementEditor.elementId,
  3020. );
  3021. const boundTextElement = getBoundTextElement(element);
  3022. if (!element) {
  3023. return;
  3024. }
  3025. if (this.state.selectedLinearElement) {
  3026. let hoverPointIndex = -1;
  3027. let segmentMidPointHoveredCoords = null;
  3028. if (
  3029. isHittingElementNotConsideringBoundingBox(element, this.state, [
  3030. scenePointerX,
  3031. scenePointerY,
  3032. ])
  3033. ) {
  3034. hoverPointIndex = LinearElementEditor.getPointIndexUnderCursor(
  3035. element,
  3036. this.state.zoom,
  3037. scenePointerX,
  3038. scenePointerY,
  3039. );
  3040. segmentMidPointHoveredCoords =
  3041. LinearElementEditor.getSegmentMidpointHitCoords(
  3042. linearElementEditor,
  3043. { x: scenePointerX, y: scenePointerY },
  3044. this.state,
  3045. );
  3046. if (hoverPointIndex >= 0 || segmentMidPointHoveredCoords) {
  3047. setCursor(this.canvas, CURSOR_TYPE.POINTER);
  3048. } else {
  3049. setCursor(this.canvas, CURSOR_TYPE.MOVE);
  3050. }
  3051. } else if (
  3052. shouldShowBoundingBox([element], this.state) &&
  3053. isHittingElementBoundingBoxWithoutHittingElement(
  3054. element,
  3055. this.state,
  3056. scenePointerX,
  3057. scenePointerY,
  3058. )
  3059. ) {
  3060. setCursor(this.canvas, CURSOR_TYPE.MOVE);
  3061. } else if (
  3062. boundTextElement &&
  3063. hitTest(boundTextElement, this.state, scenePointerX, scenePointerY)
  3064. ) {
  3065. setCursor(this.canvas, CURSOR_TYPE.MOVE);
  3066. }
  3067. if (
  3068. this.state.selectedLinearElement.hoverPointIndex !== hoverPointIndex
  3069. ) {
  3070. this.setState({
  3071. selectedLinearElement: {
  3072. ...this.state.selectedLinearElement,
  3073. hoverPointIndex,
  3074. },
  3075. });
  3076. }
  3077. if (
  3078. !LinearElementEditor.arePointsEqual(
  3079. this.state.selectedLinearElement.segmentMidPointHoveredCoords,
  3080. segmentMidPointHoveredCoords,
  3081. )
  3082. ) {
  3083. this.setState({
  3084. selectedLinearElement: {
  3085. ...this.state.selectedLinearElement,
  3086. segmentMidPointHoveredCoords,
  3087. },
  3088. });
  3089. }
  3090. } else {
  3091. setCursor(this.canvas, CURSOR_TYPE.AUTO);
  3092. }
  3093. }
  3094. private handleCanvasPointerDown = (
  3095. event: React.PointerEvent<HTMLCanvasElement>,
  3096. ) => {
  3097. // since contextMenu options are potentially evaluated on each render,
  3098. // and an contextMenu action may depend on selection state, we must
  3099. // close the contextMenu before we update the selection on pointerDown
  3100. // (e.g. resetting selection)
  3101. if (this.state.contextMenu) {
  3102. this.setState({ contextMenu: null });
  3103. }
  3104. // remove any active selection when we start to interact with canvas
  3105. // (mainly, we care about removing selection outside the component which
  3106. // would prevent our copy handling otherwise)
  3107. const selection = document.getSelection();
  3108. if (selection?.anchorNode) {
  3109. selection.removeAllRanges();
  3110. }
  3111. this.maybeOpenContextMenuAfterPointerDownOnTouchDevices(event);
  3112. this.maybeCleanupAfterMissingPointerUp(event);
  3113. //fires only once, if pen is detected, penMode is enabled
  3114. //the user can disable this by toggling the penMode button
  3115. if (!this.state.penDetected && event.pointerType === "pen") {
  3116. this.setState((prevState) => {
  3117. return {
  3118. penMode: true,
  3119. penDetected: true,
  3120. };
  3121. });
  3122. }
  3123. if (
  3124. !this.device.isTouchScreen &&
  3125. ["pen", "touch"].includes(event.pointerType)
  3126. ) {
  3127. this.device = updateObject(this.device, { isTouchScreen: true });
  3128. }
  3129. if (isPanning) {
  3130. return;
  3131. }
  3132. this.lastPointerDown = event;
  3133. this.setState({
  3134. lastPointerDownWith: event.pointerType,
  3135. cursorButton: "down",
  3136. });
  3137. this.savePointer(event.clientX, event.clientY, "down");
  3138. this.updateGestureOnPointerDown(event);
  3139. if (this.handleCanvasPanUsingWheelOrSpaceDrag(event)) {
  3140. return;
  3141. }
  3142. // only handle left mouse button or touch
  3143. if (
  3144. event.button !== POINTER_BUTTON.MAIN &&
  3145. event.button !== POINTER_BUTTON.TOUCH
  3146. ) {
  3147. return;
  3148. }
  3149. // don't select while panning
  3150. if (gesture.pointers.size > 1) {
  3151. return;
  3152. }
  3153. // State for the duration of a pointer interaction, which starts with a
  3154. // pointerDown event, ends with a pointerUp event (or another pointerDown)
  3155. const pointerDownState = this.initialPointerDownState(event);
  3156. if (this.handleDraggingScrollBar(event, pointerDownState)) {
  3157. return;
  3158. }
  3159. this.clearSelectionIfNotUsingSelection();
  3160. this.updateBindingEnabledOnPointerMove(event);
  3161. if (this.handleSelectionOnPointerDown(event, pointerDownState)) {
  3162. return;
  3163. }
  3164. const allowOnPointerDown =
  3165. !this.state.penMode ||
  3166. event.pointerType !== "touch" ||
  3167. this.state.activeTool.type === "selection" ||
  3168. this.state.activeTool.type === "text" ||
  3169. this.state.activeTool.type === "image";
  3170. if (!allowOnPointerDown) {
  3171. return;
  3172. }
  3173. if (this.state.activeTool.type === "text") {
  3174. this.handleTextOnPointerDown(event, pointerDownState);
  3175. return;
  3176. } else if (
  3177. this.state.activeTool.type === "arrow" ||
  3178. this.state.activeTool.type === "line"
  3179. ) {
  3180. this.handleLinearElementOnPointerDown(
  3181. event,
  3182. this.state.activeTool.type,
  3183. pointerDownState,
  3184. );
  3185. } else if (this.state.activeTool.type === "image") {
  3186. // reset image preview on pointerdown
  3187. setCursor(this.canvas, CURSOR_TYPE.CROSSHAIR);
  3188. // retrieve the latest element as the state may be stale
  3189. const pendingImageElement =
  3190. this.state.pendingImageElementId &&
  3191. this.scene.getElement(this.state.pendingImageElementId);
  3192. if (!pendingImageElement) {
  3193. return;
  3194. }
  3195. this.setState({
  3196. draggingElement: pendingImageElement,
  3197. editingElement: pendingImageElement,
  3198. pendingImageElementId: null,
  3199. multiElement: null,
  3200. });
  3201. const { x, y } = viewportCoordsToSceneCoords(event, this.state);
  3202. mutateElement(pendingImageElement, {
  3203. x,
  3204. y,
  3205. });
  3206. } else if (this.state.activeTool.type === "freedraw") {
  3207. this.handleFreeDrawElementOnPointerDown(
  3208. event,
  3209. this.state.activeTool.type,
  3210. pointerDownState,
  3211. );
  3212. } else if (this.state.activeTool.type === "custom") {
  3213. setCursor(this.canvas, CURSOR_TYPE.AUTO);
  3214. } else if (this.state.activeTool.type !== "eraser") {
  3215. this.createGenericElementOnPointerDown(
  3216. this.state.activeTool.type,
  3217. pointerDownState,
  3218. );
  3219. }
  3220. this.props?.onPointerDown?.(this.state.activeTool, pointerDownState);
  3221. const onPointerMove =
  3222. this.onPointerMoveFromPointerDownHandler(pointerDownState);
  3223. const onPointerUp =
  3224. this.onPointerUpFromPointerDownHandler(pointerDownState);
  3225. const onKeyDown = this.onKeyDownFromPointerDownHandler(pointerDownState);
  3226. const onKeyUp = this.onKeyUpFromPointerDownHandler(pointerDownState);
  3227. lastPointerUp = onPointerUp;
  3228. if (!this.state.viewModeEnabled) {
  3229. window.addEventListener(EVENT.POINTER_MOVE, onPointerMove);
  3230. window.addEventListener(EVENT.POINTER_UP, onPointerUp);
  3231. window.addEventListener(EVENT.KEYDOWN, onKeyDown);
  3232. window.addEventListener(EVENT.KEYUP, onKeyUp);
  3233. pointerDownState.eventListeners.onMove = onPointerMove;
  3234. pointerDownState.eventListeners.onUp = onPointerUp;
  3235. pointerDownState.eventListeners.onKeyUp = onKeyUp;
  3236. pointerDownState.eventListeners.onKeyDown = onKeyDown;
  3237. }
  3238. };
  3239. private handleCanvasPointerUp = (
  3240. event: React.PointerEvent<HTMLCanvasElement>,
  3241. ) => {
  3242. this.lastPointerUp = event;
  3243. if (this.device.isTouchScreen) {
  3244. const scenePointer = viewportCoordsToSceneCoords(
  3245. { clientX: event.clientX, clientY: event.clientY },
  3246. this.state,
  3247. );
  3248. const hitElement = this.getElementAtPosition(
  3249. scenePointer.x,
  3250. scenePointer.y,
  3251. );
  3252. this.hitLinkElement = this.getElementLinkAtPosition(
  3253. scenePointer,
  3254. hitElement,
  3255. );
  3256. }
  3257. if (
  3258. this.hitLinkElement &&
  3259. !this.state.selectedElementIds[this.hitLinkElement.id]
  3260. ) {
  3261. this.redirectToLink(event, this.device.isTouchScreen);
  3262. }
  3263. this.removePointer(event);
  3264. };
  3265. private maybeOpenContextMenuAfterPointerDownOnTouchDevices = (
  3266. event: React.PointerEvent<HTMLCanvasElement>,
  3267. ): void => {
  3268. // deal with opening context menu on touch devices
  3269. if (event.pointerType === "touch") {
  3270. invalidateContextMenu = false;
  3271. if (touchTimeout) {
  3272. // If there's already a touchTimeout, this means that there's another
  3273. // touch down and we are doing another touch, so we shouldn't open the
  3274. // context menu.
  3275. invalidateContextMenu = true;
  3276. } else {
  3277. // open the context menu with the first touch's clientX and clientY
  3278. // if the touch is not moving
  3279. touchTimeout = window.setTimeout(() => {
  3280. touchTimeout = 0;
  3281. if (!invalidateContextMenu) {
  3282. this.handleCanvasContextMenu(event);
  3283. }
  3284. }, TOUCH_CTX_MENU_TIMEOUT);
  3285. }
  3286. }
  3287. };
  3288. private resetContextMenuTimer = () => {
  3289. clearTimeout(touchTimeout);
  3290. touchTimeout = 0;
  3291. invalidateContextMenu = false;
  3292. };
  3293. private maybeCleanupAfterMissingPointerUp(
  3294. event: React.PointerEvent<HTMLCanvasElement>,
  3295. ): void {
  3296. if (lastPointerUp !== null) {
  3297. // Unfortunately, sometimes we don't get a pointerup after a pointerdown,
  3298. // this can happen when a contextual menu or alert is triggered. In order to avoid
  3299. // being in a weird state, we clean up on the next pointerdown
  3300. lastPointerUp(event);
  3301. }
  3302. }
  3303. // Returns whether the event is a panning
  3304. private handleCanvasPanUsingWheelOrSpaceDrag = (
  3305. event: React.PointerEvent<HTMLCanvasElement>,
  3306. ): boolean => {
  3307. if (
  3308. !(
  3309. gesture.pointers.size <= 1 &&
  3310. (event.button === POINTER_BUTTON.WHEEL ||
  3311. (event.button === POINTER_BUTTON.MAIN && isHoldingSpace) ||
  3312. this.state.viewModeEnabled)
  3313. ) ||
  3314. isTextElement(this.state.editingElement)
  3315. ) {
  3316. return false;
  3317. }
  3318. isPanning = true;
  3319. event.preventDefault();
  3320. let nextPastePrevented = false;
  3321. const isLinux = /Linux/.test(window.navigator.platform);
  3322. setCursor(this.canvas, CURSOR_TYPE.GRABBING);
  3323. let { clientX: lastX, clientY: lastY } = event;
  3324. const onPointerMove = withBatchedUpdatesThrottled((event: PointerEvent) => {
  3325. const deltaX = lastX - event.clientX;
  3326. const deltaY = lastY - event.clientY;
  3327. lastX = event.clientX;
  3328. lastY = event.clientY;
  3329. /*
  3330. * Prevent paste event if we move while middle clicking on Linux.
  3331. * See issue #1383.
  3332. */
  3333. if (
  3334. isLinux &&
  3335. !nextPastePrevented &&
  3336. (Math.abs(deltaX) > 1 || Math.abs(deltaY) > 1)
  3337. ) {
  3338. nextPastePrevented = true;
  3339. /* Prevent the next paste event */
  3340. const preventNextPaste = (event: ClipboardEvent) => {
  3341. document.body.removeEventListener(EVENT.PASTE, preventNextPaste);
  3342. event.stopPropagation();
  3343. };
  3344. /*
  3345. * Reenable next paste in case of disabled middle click paste for
  3346. * any reason:
  3347. * - right click paste
  3348. * - empty clipboard
  3349. */
  3350. const enableNextPaste = () => {
  3351. setTimeout(() => {
  3352. document.body.removeEventListener(EVENT.PASTE, preventNextPaste);
  3353. window.removeEventListener(EVENT.POINTER_UP, enableNextPaste);
  3354. }, 100);
  3355. };
  3356. document.body.addEventListener(EVENT.PASTE, preventNextPaste);
  3357. window.addEventListener(EVENT.POINTER_UP, enableNextPaste);
  3358. }
  3359. this.setState({
  3360. scrollX: this.state.scrollX - deltaX / this.state.zoom.value,
  3361. scrollY: this.state.scrollY - deltaY / this.state.zoom.value,
  3362. });
  3363. });
  3364. const teardown = withBatchedUpdates(
  3365. (lastPointerUp = () => {
  3366. lastPointerUp = null;
  3367. isPanning = false;
  3368. if (!isHoldingSpace) {
  3369. if (this.state.viewModeEnabled) {
  3370. setCursor(this.canvas, CURSOR_TYPE.GRAB);
  3371. } else {
  3372. setCursorForShape(this.canvas, this.state);
  3373. }
  3374. }
  3375. this.setState({
  3376. cursorButton: "up",
  3377. });
  3378. this.savePointer(event.clientX, event.clientY, "up");
  3379. window.removeEventListener(EVENT.POINTER_MOVE, onPointerMove);
  3380. window.removeEventListener(EVENT.POINTER_UP, teardown);
  3381. window.removeEventListener(EVENT.BLUR, teardown);
  3382. onPointerMove.flush();
  3383. }),
  3384. );
  3385. window.addEventListener(EVENT.BLUR, teardown);
  3386. window.addEventListener(EVENT.POINTER_MOVE, onPointerMove, {
  3387. passive: true,
  3388. });
  3389. window.addEventListener(EVENT.POINTER_UP, teardown);
  3390. return true;
  3391. };
  3392. private updateGestureOnPointerDown(
  3393. event: React.PointerEvent<HTMLCanvasElement>,
  3394. ): void {
  3395. gesture.pointers.set(event.pointerId, {
  3396. x: event.clientX,
  3397. y: event.clientY,
  3398. });
  3399. if (gesture.pointers.size === 2) {
  3400. gesture.lastCenter = getCenter(gesture.pointers);
  3401. gesture.initialScale = this.state.zoom.value;
  3402. gesture.initialDistance = getDistance(
  3403. Array.from(gesture.pointers.values()),
  3404. );
  3405. }
  3406. }
  3407. private initialPointerDownState(
  3408. event: React.PointerEvent<HTMLCanvasElement>,
  3409. ): PointerDownState {
  3410. const origin = viewportCoordsToSceneCoords(event, this.state);
  3411. const selectedElements = getSelectedElements(
  3412. this.scene.getNonDeletedElements(),
  3413. this.state,
  3414. );
  3415. const [minX, minY, maxX, maxY] = getCommonBounds(selectedElements);
  3416. return {
  3417. origin,
  3418. withCmdOrCtrl: event[KEYS.CTRL_OR_CMD],
  3419. originInGrid: tupleToCoors(
  3420. getGridPoint(origin.x, origin.y, this.state.gridSize),
  3421. ),
  3422. scrollbars: isOverScrollBars(
  3423. currentScrollBars,
  3424. event.clientX - this.state.offsetLeft,
  3425. event.clientY - this.state.offsetTop,
  3426. ),
  3427. // we need to duplicate because we'll be updating this state
  3428. lastCoords: { ...origin },
  3429. originalElements: this.scene
  3430. .getNonDeletedElements()
  3431. .reduce((acc, element) => {
  3432. acc.set(element.id, deepCopyElement(element));
  3433. return acc;
  3434. }, new Map() as PointerDownState["originalElements"]),
  3435. resize: {
  3436. handleType: false,
  3437. isResizing: false,
  3438. offset: { x: 0, y: 0 },
  3439. arrowDirection: "origin",
  3440. center: { x: (maxX + minX) / 2, y: (maxY + minY) / 2 },
  3441. },
  3442. hit: {
  3443. element: null,
  3444. allHitElements: [],
  3445. wasAddedToSelection: false,
  3446. hasBeenDuplicated: false,
  3447. hasHitCommonBoundingBoxOfSelectedElements:
  3448. this.isHittingCommonBoundingBoxOfSelectedElements(
  3449. origin,
  3450. selectedElements,
  3451. ),
  3452. },
  3453. drag: {
  3454. hasOccurred: false,
  3455. offset: null,
  3456. },
  3457. eventListeners: {
  3458. onMove: null,
  3459. onUp: null,
  3460. onKeyUp: null,
  3461. onKeyDown: null,
  3462. },
  3463. boxSelection: {
  3464. hasOccurred: false,
  3465. },
  3466. elementIdsToErase: {},
  3467. };
  3468. }
  3469. // Returns whether the event is a dragging a scrollbar
  3470. private handleDraggingScrollBar(
  3471. event: React.PointerEvent<HTMLCanvasElement>,
  3472. pointerDownState: PointerDownState,
  3473. ): boolean {
  3474. if (
  3475. !(pointerDownState.scrollbars.isOverEither && !this.state.multiElement)
  3476. ) {
  3477. return false;
  3478. }
  3479. isDraggingScrollBar = true;
  3480. pointerDownState.lastCoords.x = event.clientX;
  3481. pointerDownState.lastCoords.y = event.clientY;
  3482. const onPointerMove = withBatchedUpdatesThrottled((event: PointerEvent) => {
  3483. const target = event.target;
  3484. if (!(target instanceof HTMLElement)) {
  3485. return;
  3486. }
  3487. this.handlePointerMoveOverScrollbars(event, pointerDownState);
  3488. });
  3489. const onPointerUp = withBatchedUpdates(() => {
  3490. isDraggingScrollBar = false;
  3491. setCursorForShape(this.canvas, this.state);
  3492. lastPointerUp = null;
  3493. this.setState({
  3494. cursorButton: "up",
  3495. });
  3496. this.savePointer(event.clientX, event.clientY, "up");
  3497. window.removeEventListener(EVENT.POINTER_MOVE, onPointerMove);
  3498. window.removeEventListener(EVENT.POINTER_UP, onPointerUp);
  3499. onPointerMove.flush();
  3500. });
  3501. lastPointerUp = onPointerUp;
  3502. window.addEventListener(EVENT.POINTER_MOVE, onPointerMove);
  3503. window.addEventListener(EVENT.POINTER_UP, onPointerUp);
  3504. return true;
  3505. }
  3506. private clearSelectionIfNotUsingSelection = (): void => {
  3507. if (this.state.activeTool.type !== "selection") {
  3508. this.setState({
  3509. selectedElementIds: {},
  3510. selectedGroupIds: {},
  3511. editingGroupId: null,
  3512. });
  3513. }
  3514. };
  3515. /**
  3516. * @returns whether the pointer event has been completely handled
  3517. */
  3518. private handleSelectionOnPointerDown = (
  3519. event: React.PointerEvent<HTMLCanvasElement>,
  3520. pointerDownState: PointerDownState,
  3521. ): boolean => {
  3522. if (this.state.activeTool.type === "selection") {
  3523. const elements = this.scene.getNonDeletedElements();
  3524. const selectedElements = getSelectedElements(elements, this.state);
  3525. if (selectedElements.length === 1 && !this.state.editingLinearElement) {
  3526. const elementWithTransformHandleType =
  3527. getElementWithTransformHandleType(
  3528. elements,
  3529. this.state,
  3530. pointerDownState.origin.x,
  3531. pointerDownState.origin.y,
  3532. this.state.zoom,
  3533. event.pointerType,
  3534. );
  3535. if (elementWithTransformHandleType != null) {
  3536. this.setState({
  3537. resizingElement: elementWithTransformHandleType.element,
  3538. });
  3539. pointerDownState.resize.handleType =
  3540. elementWithTransformHandleType.transformHandleType;
  3541. }
  3542. } else if (selectedElements.length > 1) {
  3543. pointerDownState.resize.handleType = getTransformHandleTypeFromCoords(
  3544. getCommonBounds(selectedElements),
  3545. pointerDownState.origin.x,
  3546. pointerDownState.origin.y,
  3547. this.state.zoom,
  3548. event.pointerType,
  3549. );
  3550. }
  3551. if (pointerDownState.resize.handleType) {
  3552. setCursor(
  3553. this.canvas,
  3554. getCursorForResizingElement({
  3555. transformHandleType: pointerDownState.resize.handleType,
  3556. }),
  3557. );
  3558. pointerDownState.resize.isResizing = true;
  3559. pointerDownState.resize.offset = tupleToCoors(
  3560. getResizeOffsetXY(
  3561. pointerDownState.resize.handleType,
  3562. selectedElements,
  3563. pointerDownState.origin.x,
  3564. pointerDownState.origin.y,
  3565. ),
  3566. );
  3567. if (
  3568. selectedElements.length === 1 &&
  3569. isLinearElement(selectedElements[0]) &&
  3570. selectedElements[0].points.length === 2
  3571. ) {
  3572. pointerDownState.resize.arrowDirection = getResizeArrowDirection(
  3573. pointerDownState.resize.handleType,
  3574. selectedElements[0],
  3575. );
  3576. }
  3577. } else {
  3578. if (this.state.selectedLinearElement) {
  3579. const linearElementEditor =
  3580. this.state.editingLinearElement || this.state.selectedLinearElement;
  3581. const ret = LinearElementEditor.handlePointerDown(
  3582. event,
  3583. this.state,
  3584. this.history,
  3585. pointerDownState.origin,
  3586. linearElementEditor,
  3587. );
  3588. if (ret.hitElement) {
  3589. pointerDownState.hit.element = ret.hitElement;
  3590. }
  3591. if (ret.linearElementEditor) {
  3592. this.setState({ selectedLinearElement: ret.linearElementEditor });
  3593. if (this.state.editingLinearElement) {
  3594. this.setState({ editingLinearElement: ret.linearElementEditor });
  3595. }
  3596. }
  3597. if (ret.didAddPoint) {
  3598. return true;
  3599. }
  3600. }
  3601. // hitElement may already be set above, so check first
  3602. pointerDownState.hit.element =
  3603. pointerDownState.hit.element ??
  3604. this.getElementAtPosition(
  3605. pointerDownState.origin.x,
  3606. pointerDownState.origin.y,
  3607. );
  3608. if (pointerDownState.hit.element) {
  3609. // Early return if pointer is hitting link icon
  3610. const hitLinkElement = this.getElementLinkAtPosition(
  3611. {
  3612. x: pointerDownState.origin.x,
  3613. y: pointerDownState.origin.y,
  3614. },
  3615. pointerDownState.hit.element,
  3616. );
  3617. if (hitLinkElement) {
  3618. return false;
  3619. }
  3620. }
  3621. // For overlapped elements one position may hit
  3622. // multiple elements
  3623. pointerDownState.hit.allHitElements = this.getElementsAtPosition(
  3624. pointerDownState.origin.x,
  3625. pointerDownState.origin.y,
  3626. );
  3627. const hitElement = pointerDownState.hit.element;
  3628. const someHitElementIsSelected =
  3629. pointerDownState.hit.allHitElements.some((element) =>
  3630. this.isASelectedElement(element),
  3631. );
  3632. if (
  3633. (hitElement === null || !someHitElementIsSelected) &&
  3634. !event.shiftKey &&
  3635. !pointerDownState.hit.hasHitCommonBoundingBoxOfSelectedElements
  3636. ) {
  3637. this.clearSelection(hitElement);
  3638. }
  3639. if (this.state.editingLinearElement) {
  3640. this.setState({
  3641. selectedElementIds: {
  3642. [this.state.editingLinearElement.elementId]: true,
  3643. },
  3644. });
  3645. // If we click on something
  3646. } else if (hitElement != null) {
  3647. // on CMD/CTRL, drill down to hit element regardless of groups etc.
  3648. if (event[KEYS.CTRL_OR_CMD]) {
  3649. if (!this.state.selectedElementIds[hitElement.id]) {
  3650. pointerDownState.hit.wasAddedToSelection = true;
  3651. }
  3652. this.setState((prevState) => ({
  3653. ...editGroupForSelectedElement(prevState, hitElement),
  3654. previousSelectedElementIds: this.state.selectedElementIds,
  3655. }));
  3656. // mark as not completely handled so as to allow dragging etc.
  3657. return false;
  3658. }
  3659. // deselect if item is selected
  3660. // if shift is not clicked, this will always return true
  3661. // otherwise, it will trigger selection based on current
  3662. // state of the box
  3663. if (!this.state.selectedElementIds[hitElement.id]) {
  3664. // if we are currently editing a group, exiting editing mode and deselect the group.
  3665. if (
  3666. this.state.editingGroupId &&
  3667. !isElementInGroup(hitElement, this.state.editingGroupId)
  3668. ) {
  3669. this.setState({
  3670. selectedElementIds: {},
  3671. selectedGroupIds: {},
  3672. editingGroupId: null,
  3673. });
  3674. }
  3675. // Add hit element to selection. At this point if we're not holding
  3676. // SHIFT the previously selected element(s) were deselected above
  3677. // (make sure you use setState updater to use latest state)
  3678. if (
  3679. !someHitElementIsSelected &&
  3680. !pointerDownState.hit.hasHitCommonBoundingBoxOfSelectedElements
  3681. ) {
  3682. this.setState((prevState) => {
  3683. return selectGroupsForSelectedElements(
  3684. {
  3685. ...prevState,
  3686. selectedElementIds: {
  3687. ...prevState.selectedElementIds,
  3688. [hitElement.id]: true,
  3689. },
  3690. showHyperlinkPopup: hitElement.link ? "info" : false,
  3691. },
  3692. this.scene.getNonDeletedElements(),
  3693. );
  3694. });
  3695. pointerDownState.hit.wasAddedToSelection = true;
  3696. }
  3697. }
  3698. }
  3699. this.setState({
  3700. previousSelectedElementIds: this.state.selectedElementIds,
  3701. });
  3702. }
  3703. }
  3704. return false;
  3705. };
  3706. private isASelectedElement(hitElement: ExcalidrawElement | null): boolean {
  3707. return hitElement != null && this.state.selectedElementIds[hitElement.id];
  3708. }
  3709. private isHittingCommonBoundingBoxOfSelectedElements(
  3710. point: Readonly<{ x: number; y: number }>,
  3711. selectedElements: readonly ExcalidrawElement[],
  3712. ): boolean {
  3713. if (selectedElements.length < 2) {
  3714. return false;
  3715. }
  3716. // How many pixels off the shape boundary we still consider a hit
  3717. const threshold = 10 / this.state.zoom.value;
  3718. const [x1, y1, x2, y2] = getCommonBounds(selectedElements);
  3719. return (
  3720. point.x > x1 - threshold &&
  3721. point.x < x2 + threshold &&
  3722. point.y > y1 - threshold &&
  3723. point.y < y2 + threshold
  3724. );
  3725. }
  3726. private handleTextOnPointerDown = (
  3727. event: React.PointerEvent<HTMLCanvasElement>,
  3728. pointerDownState: PointerDownState,
  3729. ): void => {
  3730. // if we're currently still editing text, clicking outside
  3731. // should only finalize it, not create another (irrespective
  3732. // of state.activeTool.locked)
  3733. if (isTextElement(this.state.editingElement)) {
  3734. return;
  3735. }
  3736. let sceneX = pointerDownState.origin.x;
  3737. let sceneY = pointerDownState.origin.y;
  3738. const element = this.getElementAtPosition(sceneX, sceneY, {
  3739. includeBoundTextElement: true,
  3740. });
  3741. let container = getTextBindableContainerAtPosition(
  3742. this.scene.getNonDeletedElements(),
  3743. this.state,
  3744. sceneX,
  3745. sceneY,
  3746. );
  3747. if (hasBoundTextElement(element)) {
  3748. container = element as ExcalidrawTextContainer;
  3749. sceneX = element.x + element.width / 2;
  3750. sceneY = element.y + element.height / 2;
  3751. }
  3752. this.startTextEditing({
  3753. sceneX,
  3754. sceneY,
  3755. insertAtParentCenter: !event.altKey,
  3756. container,
  3757. });
  3758. resetCursor(this.canvas);
  3759. if (!this.state.activeTool.locked) {
  3760. this.setState({
  3761. activeTool: updateActiveTool(this.state, { type: "selection" }),
  3762. });
  3763. }
  3764. };
  3765. private handleFreeDrawElementOnPointerDown = (
  3766. event: React.PointerEvent<HTMLCanvasElement>,
  3767. elementType: ExcalidrawFreeDrawElement["type"],
  3768. pointerDownState: PointerDownState,
  3769. ) => {
  3770. // Begin a mark capture. This does not have to update state yet.
  3771. const [gridX, gridY] = getGridPoint(
  3772. pointerDownState.origin.x,
  3773. pointerDownState.origin.y,
  3774. null,
  3775. );
  3776. const element = newFreeDrawElement({
  3777. type: elementType,
  3778. x: gridX,
  3779. y: gridY,
  3780. strokeColor: this.state.currentItemStrokeColor,
  3781. backgroundColor: this.state.currentItemBackgroundColor,
  3782. fillStyle: this.state.currentItemFillStyle,
  3783. strokeWidth: this.state.currentItemStrokeWidth,
  3784. strokeStyle: this.state.currentItemStrokeStyle,
  3785. roughness: this.state.currentItemRoughness,
  3786. opacity: this.state.currentItemOpacity,
  3787. roundness: null,
  3788. simulatePressure: event.pressure === 0.5,
  3789. locked: false,
  3790. });
  3791. this.setState((prevState) => ({
  3792. selectedElementIds: {
  3793. ...prevState.selectedElementIds,
  3794. [element.id]: false,
  3795. },
  3796. }));
  3797. const pressures = element.simulatePressure
  3798. ? element.pressures
  3799. : [...element.pressures, event.pressure];
  3800. mutateElement(element, {
  3801. points: [[0, 0]],
  3802. pressures,
  3803. });
  3804. const boundElement = getHoveredElementForBinding(
  3805. pointerDownState.origin,
  3806. this.scene,
  3807. );
  3808. this.scene.replaceAllElements([
  3809. ...this.scene.getElementsIncludingDeleted(),
  3810. element,
  3811. ]);
  3812. this.setState({
  3813. draggingElement: element,
  3814. editingElement: element,
  3815. startBoundElement: boundElement,
  3816. suggestedBindings: [],
  3817. });
  3818. };
  3819. private createImageElement = ({
  3820. sceneX,
  3821. sceneY,
  3822. }: {
  3823. sceneX: number;
  3824. sceneY: number;
  3825. }) => {
  3826. const [gridX, gridY] = getGridPoint(sceneX, sceneY, this.state.gridSize);
  3827. const element = newImageElement({
  3828. type: "image",
  3829. x: gridX,
  3830. y: gridY,
  3831. strokeColor: this.state.currentItemStrokeColor,
  3832. backgroundColor: this.state.currentItemBackgroundColor,
  3833. fillStyle: this.state.currentItemFillStyle,
  3834. strokeWidth: this.state.currentItemStrokeWidth,
  3835. strokeStyle: this.state.currentItemStrokeStyle,
  3836. roughness: this.state.currentItemRoughness,
  3837. roundness: null,
  3838. opacity: this.state.currentItemOpacity,
  3839. locked: false,
  3840. });
  3841. return element;
  3842. };
  3843. private handleLinearElementOnPointerDown = (
  3844. event: React.PointerEvent<HTMLCanvasElement>,
  3845. elementType: ExcalidrawLinearElement["type"],
  3846. pointerDownState: PointerDownState,
  3847. ): void => {
  3848. if (this.state.multiElement) {
  3849. const { multiElement } = this.state;
  3850. // finalize if completing a loop
  3851. if (
  3852. multiElement.type === "line" &&
  3853. isPathALoop(multiElement.points, this.state.zoom.value)
  3854. ) {
  3855. mutateElement(multiElement, {
  3856. lastCommittedPoint:
  3857. multiElement.points[multiElement.points.length - 1],
  3858. });
  3859. this.actionManager.executeAction(actionFinalize);
  3860. return;
  3861. }
  3862. const { x: rx, y: ry, lastCommittedPoint } = multiElement;
  3863. // clicking inside commit zone → finalize arrow
  3864. if (
  3865. multiElement.points.length > 1 &&
  3866. lastCommittedPoint &&
  3867. distance2d(
  3868. pointerDownState.origin.x - rx,
  3869. pointerDownState.origin.y - ry,
  3870. lastCommittedPoint[0],
  3871. lastCommittedPoint[1],
  3872. ) < LINE_CONFIRM_THRESHOLD
  3873. ) {
  3874. this.actionManager.executeAction(actionFinalize);
  3875. return;
  3876. }
  3877. this.setState((prevState) => ({
  3878. selectedElementIds: {
  3879. ...prevState.selectedElementIds,
  3880. [multiElement.id]: true,
  3881. },
  3882. }));
  3883. // clicking outside commit zone → update reference for last committed
  3884. // point
  3885. mutateElement(multiElement, {
  3886. lastCommittedPoint: multiElement.points[multiElement.points.length - 1],
  3887. });
  3888. setCursor(this.canvas, CURSOR_TYPE.POINTER);
  3889. } else {
  3890. const [gridX, gridY] = getGridPoint(
  3891. pointerDownState.origin.x,
  3892. pointerDownState.origin.y,
  3893. this.state.gridSize,
  3894. );
  3895. /* If arrow is pre-arrowheads, it will have undefined for both start and end arrowheads.
  3896. If so, we want it to be null for start and "arrow" for end. If the linear item is not
  3897. an arrow, we want it to be null for both. Otherwise, we want it to use the
  3898. values from appState. */
  3899. const { currentItemStartArrowhead, currentItemEndArrowhead } = this.state;
  3900. const [startArrowhead, endArrowhead] =
  3901. elementType === "arrow"
  3902. ? [currentItemStartArrowhead, currentItemEndArrowhead]
  3903. : [null, null];
  3904. const element = newLinearElement({
  3905. type: elementType,
  3906. x: gridX,
  3907. y: gridY,
  3908. strokeColor: this.state.currentItemStrokeColor,
  3909. backgroundColor: this.state.currentItemBackgroundColor,
  3910. fillStyle: this.state.currentItemFillStyle,
  3911. strokeWidth: this.state.currentItemStrokeWidth,
  3912. strokeStyle: this.state.currentItemStrokeStyle,
  3913. roughness: this.state.currentItemRoughness,
  3914. opacity: this.state.currentItemOpacity,
  3915. roundness:
  3916. this.state.currentItemRoundness === "round"
  3917. ? { type: ROUNDNESS.PROPORTIONAL_RADIUS }
  3918. : null,
  3919. startArrowhead,
  3920. endArrowhead,
  3921. locked: false,
  3922. });
  3923. this.setState((prevState) => ({
  3924. selectedElementIds: {
  3925. ...prevState.selectedElementIds,
  3926. [element.id]: false,
  3927. },
  3928. }));
  3929. mutateElement(element, {
  3930. points: [...element.points, [0, 0]],
  3931. });
  3932. const boundElement = getHoveredElementForBinding(
  3933. pointerDownState.origin,
  3934. this.scene,
  3935. );
  3936. this.scene.replaceAllElements([
  3937. ...this.scene.getElementsIncludingDeleted(),
  3938. element,
  3939. ]);
  3940. this.setState({
  3941. draggingElement: element,
  3942. editingElement: element,
  3943. startBoundElement: boundElement,
  3944. suggestedBindings: [],
  3945. });
  3946. }
  3947. };
  3948. private createGenericElementOnPointerDown = (
  3949. elementType: ExcalidrawGenericElement["type"],
  3950. pointerDownState: PointerDownState,
  3951. ): void => {
  3952. const [gridX, gridY] = getGridPoint(
  3953. pointerDownState.origin.x,
  3954. pointerDownState.origin.y,
  3955. this.state.gridSize,
  3956. );
  3957. const element = newElement({
  3958. type: elementType,
  3959. x: gridX,
  3960. y: gridY,
  3961. strokeColor: this.state.currentItemStrokeColor,
  3962. backgroundColor: this.state.currentItemBackgroundColor,
  3963. fillStyle: this.state.currentItemFillStyle,
  3964. strokeWidth: this.state.currentItemStrokeWidth,
  3965. strokeStyle: this.state.currentItemStrokeStyle,
  3966. roughness: this.state.currentItemRoughness,
  3967. opacity: this.state.currentItemOpacity,
  3968. roundness:
  3969. this.state.currentItemRoundness === "round"
  3970. ? {
  3971. type: isUsingAdaptiveRadius(elementType)
  3972. ? ROUNDNESS.ADAPTIVE_RADIUS
  3973. : ROUNDNESS.PROPORTIONAL_RADIUS,
  3974. }
  3975. : null,
  3976. locked: false,
  3977. });
  3978. if (element.type === "selection") {
  3979. this.setState({
  3980. selectionElement: element,
  3981. draggingElement: element,
  3982. });
  3983. } else {
  3984. this.scene.replaceAllElements([
  3985. ...this.scene.getElementsIncludingDeleted(),
  3986. element,
  3987. ]);
  3988. this.setState({
  3989. multiElement: null,
  3990. draggingElement: element,
  3991. editingElement: element,
  3992. });
  3993. }
  3994. };
  3995. private onKeyDownFromPointerDownHandler(
  3996. pointerDownState: PointerDownState,
  3997. ): (event: KeyboardEvent) => void {
  3998. return withBatchedUpdates((event: KeyboardEvent) => {
  3999. if (this.maybeHandleResize(pointerDownState, event)) {
  4000. return;
  4001. }
  4002. this.maybeDragNewGenericElement(pointerDownState, event);
  4003. });
  4004. }
  4005. private onKeyUpFromPointerDownHandler(
  4006. pointerDownState: PointerDownState,
  4007. ): (event: KeyboardEvent) => void {
  4008. return withBatchedUpdates((event: KeyboardEvent) => {
  4009. // Prevents focus from escaping excalidraw tab
  4010. event.key === KEYS.ALT && event.preventDefault();
  4011. if (this.maybeHandleResize(pointerDownState, event)) {
  4012. return;
  4013. }
  4014. this.maybeDragNewGenericElement(pointerDownState, event);
  4015. });
  4016. }
  4017. private onPointerMoveFromPointerDownHandler(
  4018. pointerDownState: PointerDownState,
  4019. ) {
  4020. return withBatchedUpdatesThrottled((event: PointerEvent) => {
  4021. // We need to initialize dragOffsetXY only after we've updated
  4022. // `state.selectedElementIds` on pointerDown. Doing it here in pointerMove
  4023. // event handler should hopefully ensure we're already working with
  4024. // the updated state.
  4025. if (pointerDownState.drag.offset === null) {
  4026. pointerDownState.drag.offset = tupleToCoors(
  4027. getDragOffsetXY(
  4028. getSelectedElements(this.scene.getNonDeletedElements(), this.state),
  4029. pointerDownState.origin.x,
  4030. pointerDownState.origin.y,
  4031. ),
  4032. );
  4033. }
  4034. const target = event.target;
  4035. if (!(target instanceof HTMLElement)) {
  4036. return;
  4037. }
  4038. if (this.handlePointerMoveOverScrollbars(event, pointerDownState)) {
  4039. return;
  4040. }
  4041. const pointerCoords = viewportCoordsToSceneCoords(event, this.state);
  4042. if (isEraserActive(this.state)) {
  4043. this.handleEraser(event, pointerDownState, pointerCoords);
  4044. return;
  4045. }
  4046. const [gridX, gridY] = getGridPoint(
  4047. pointerCoords.x,
  4048. pointerCoords.y,
  4049. this.state.gridSize,
  4050. );
  4051. // for arrows/lines, don't start dragging until a given threshold
  4052. // to ensure we don't create a 2-point arrow by mistake when
  4053. // user clicks mouse in a way that it moves a tiny bit (thus
  4054. // triggering pointermove)
  4055. if (
  4056. !pointerDownState.drag.hasOccurred &&
  4057. (this.state.activeTool.type === "arrow" ||
  4058. this.state.activeTool.type === "line")
  4059. ) {
  4060. if (
  4061. distance2d(
  4062. pointerCoords.x,
  4063. pointerCoords.y,
  4064. pointerDownState.origin.x,
  4065. pointerDownState.origin.y,
  4066. ) < DRAGGING_THRESHOLD
  4067. ) {
  4068. return;
  4069. }
  4070. }
  4071. if (pointerDownState.resize.isResizing) {
  4072. pointerDownState.lastCoords.x = pointerCoords.x;
  4073. pointerDownState.lastCoords.y = pointerCoords.y;
  4074. if (this.maybeHandleResize(pointerDownState, event)) {
  4075. return true;
  4076. }
  4077. }
  4078. if (this.state.selectedLinearElement) {
  4079. const linearElementEditor =
  4080. this.state.editingLinearElement || this.state.selectedLinearElement;
  4081. if (
  4082. LinearElementEditor.shouldAddMidpoint(
  4083. this.state.selectedLinearElement,
  4084. pointerCoords,
  4085. this.state,
  4086. )
  4087. ) {
  4088. const ret = LinearElementEditor.addMidpoint(
  4089. this.state.selectedLinearElement,
  4090. pointerCoords,
  4091. this.state,
  4092. );
  4093. if (!ret) {
  4094. return;
  4095. }
  4096. // Since we are reading from previous state which is not possible with
  4097. // automatic batching in React 18 hence using flush sync to synchronously
  4098. // update the state. Check https://github.com/excalidraw/excalidraw/pull/5508 for more details.
  4099. flushSync(() => {
  4100. if (this.state.selectedLinearElement) {
  4101. this.setState({
  4102. selectedLinearElement: {
  4103. ...this.state.selectedLinearElement,
  4104. pointerDownState: ret.pointerDownState,
  4105. selectedPointsIndices: ret.selectedPointsIndices,
  4106. },
  4107. });
  4108. }
  4109. if (this.state.editingLinearElement) {
  4110. this.setState({
  4111. editingLinearElement: {
  4112. ...this.state.editingLinearElement,
  4113. pointerDownState: ret.pointerDownState,
  4114. selectedPointsIndices: ret.selectedPointsIndices,
  4115. },
  4116. });
  4117. }
  4118. });
  4119. return;
  4120. } else if (
  4121. linearElementEditor.pointerDownState.segmentMidpoint.value !== null &&
  4122. !linearElementEditor.pointerDownState.segmentMidpoint.added
  4123. ) {
  4124. return;
  4125. }
  4126. const didDrag = LinearElementEditor.handlePointDragging(
  4127. event,
  4128. this.state,
  4129. pointerCoords.x,
  4130. pointerCoords.y,
  4131. (element, pointsSceneCoords) => {
  4132. this.maybeSuggestBindingsForLinearElementAtCoords(
  4133. element,
  4134. pointsSceneCoords,
  4135. );
  4136. },
  4137. linearElementEditor,
  4138. );
  4139. if (didDrag) {
  4140. pointerDownState.lastCoords.x = pointerCoords.x;
  4141. pointerDownState.lastCoords.y = pointerCoords.y;
  4142. pointerDownState.drag.hasOccurred = true;
  4143. if (
  4144. this.state.editingLinearElement &&
  4145. !this.state.editingLinearElement.isDragging
  4146. ) {
  4147. this.setState({
  4148. editingLinearElement: {
  4149. ...this.state.editingLinearElement,
  4150. isDragging: true,
  4151. },
  4152. });
  4153. }
  4154. if (!this.state.selectedLinearElement.isDragging) {
  4155. this.setState({
  4156. selectedLinearElement: {
  4157. ...this.state.selectedLinearElement,
  4158. isDragging: true,
  4159. },
  4160. });
  4161. }
  4162. return;
  4163. }
  4164. }
  4165. const hasHitASelectedElement = pointerDownState.hit.allHitElements.some(
  4166. (element) => this.isASelectedElement(element),
  4167. );
  4168. const isSelectingPointsInLineEditor =
  4169. this.state.editingLinearElement &&
  4170. event.shiftKey &&
  4171. this.state.editingLinearElement.elementId ===
  4172. pointerDownState.hit.element?.id;
  4173. if (
  4174. (hasHitASelectedElement ||
  4175. pointerDownState.hit.hasHitCommonBoundingBoxOfSelectedElements) &&
  4176. !isSelectingPointsInLineEditor
  4177. ) {
  4178. const selectedElements = getSelectedElements(
  4179. this.scene.getNonDeletedElements(),
  4180. this.state,
  4181. );
  4182. if (selectedElements.every((element) => element.locked)) {
  4183. return;
  4184. }
  4185. // Marking that click was used for dragging to check
  4186. // if elements should be deselected on pointerup
  4187. pointerDownState.drag.hasOccurred = true;
  4188. // prevent dragging even if we're no longer holding cmd/ctrl otherwise
  4189. // it would have weird results (stuff jumping all over the screen)
  4190. if (selectedElements.length > 0 && !pointerDownState.withCmdOrCtrl) {
  4191. const [dragX, dragY] = getGridPoint(
  4192. pointerCoords.x - pointerDownState.drag.offset.x,
  4193. pointerCoords.y - pointerDownState.drag.offset.y,
  4194. this.state.gridSize,
  4195. );
  4196. const [dragDistanceX, dragDistanceY] = [
  4197. Math.abs(pointerCoords.x - pointerDownState.origin.x),
  4198. Math.abs(pointerCoords.y - pointerDownState.origin.y),
  4199. ];
  4200. // We only drag in one direction if shift is pressed
  4201. const lockDirection = event.shiftKey;
  4202. dragSelectedElements(
  4203. pointerDownState,
  4204. selectedElements,
  4205. dragX,
  4206. dragY,
  4207. lockDirection,
  4208. dragDistanceX,
  4209. dragDistanceY,
  4210. this.state,
  4211. );
  4212. this.maybeSuggestBindingForAll(selectedElements);
  4213. // We duplicate the selected element if alt is pressed on pointer move
  4214. if (event.altKey && !pointerDownState.hit.hasBeenDuplicated) {
  4215. // Move the currently selected elements to the top of the z index stack, and
  4216. // put the duplicates where the selected elements used to be.
  4217. // (the origin point where the dragging started)
  4218. pointerDownState.hit.hasBeenDuplicated = true;
  4219. const nextElements = [];
  4220. const elementsToAppend = [];
  4221. const groupIdMap = new Map();
  4222. const oldIdToDuplicatedId = new Map();
  4223. const hitElement = pointerDownState.hit.element;
  4224. const elements = this.scene.getElementsIncludingDeleted();
  4225. const selectedElementIds: Array<ExcalidrawElement["id"]> =
  4226. getSelectedElements(elements, this.state, true).map(
  4227. (element) => element.id,
  4228. );
  4229. for (const element of elements) {
  4230. if (
  4231. selectedElementIds.includes(element.id) ||
  4232. // case: the state.selectedElementIds might not have been
  4233. // updated yet by the time this mousemove event is fired
  4234. (element.id === hitElement?.id &&
  4235. pointerDownState.hit.wasAddedToSelection)
  4236. ) {
  4237. const duplicatedElement = duplicateElement(
  4238. this.state.editingGroupId,
  4239. groupIdMap,
  4240. element,
  4241. );
  4242. const [originDragX, originDragY] = getGridPoint(
  4243. pointerDownState.origin.x - pointerDownState.drag.offset.x,
  4244. pointerDownState.origin.y - pointerDownState.drag.offset.y,
  4245. this.state.gridSize,
  4246. );
  4247. mutateElement(duplicatedElement, {
  4248. x: duplicatedElement.x + (originDragX - dragX),
  4249. y: duplicatedElement.y + (originDragY - dragY),
  4250. });
  4251. nextElements.push(duplicatedElement);
  4252. elementsToAppend.push(element);
  4253. oldIdToDuplicatedId.set(element.id, duplicatedElement.id);
  4254. } else {
  4255. nextElements.push(element);
  4256. }
  4257. }
  4258. const nextSceneElements = [...nextElements, ...elementsToAppend];
  4259. bindTextToShapeAfterDuplication(
  4260. nextElements,
  4261. elementsToAppend,
  4262. oldIdToDuplicatedId,
  4263. );
  4264. fixBindingsAfterDuplication(
  4265. nextSceneElements,
  4266. elementsToAppend,
  4267. oldIdToDuplicatedId,
  4268. "duplicatesServeAsOld",
  4269. );
  4270. this.scene.replaceAllElements(nextSceneElements);
  4271. }
  4272. return;
  4273. }
  4274. }
  4275. // It is very important to read this.state within each move event,
  4276. // otherwise we would read a stale one!
  4277. const draggingElement = this.state.draggingElement;
  4278. if (!draggingElement) {
  4279. return;
  4280. }
  4281. if (draggingElement.type === "freedraw") {
  4282. const points = draggingElement.points;
  4283. const dx = pointerCoords.x - draggingElement.x;
  4284. const dy = pointerCoords.y - draggingElement.y;
  4285. const lastPoint = points.length > 0 && points[points.length - 1];
  4286. const discardPoint =
  4287. lastPoint && lastPoint[0] === dx && lastPoint[1] === dy;
  4288. if (!discardPoint) {
  4289. const pressures = draggingElement.simulatePressure
  4290. ? draggingElement.pressures
  4291. : [...draggingElement.pressures, event.pressure];
  4292. mutateElement(draggingElement, {
  4293. points: [...points, [dx, dy]],
  4294. pressures,
  4295. });
  4296. }
  4297. } else if (isLinearElement(draggingElement)) {
  4298. pointerDownState.drag.hasOccurred = true;
  4299. const points = draggingElement.points;
  4300. let dx = gridX - draggingElement.x;
  4301. let dy = gridY - draggingElement.y;
  4302. if (shouldRotateWithDiscreteAngle(event) && points.length === 2) {
  4303. ({ width: dx, height: dy } = getLockedLinearCursorAlignSize(
  4304. draggingElement.x,
  4305. draggingElement.y,
  4306. pointerCoords.x,
  4307. pointerCoords.y,
  4308. ));
  4309. }
  4310. if (points.length === 1) {
  4311. mutateElement(draggingElement, {
  4312. points: [...points, [dx, dy]],
  4313. });
  4314. } else if (points.length === 2) {
  4315. mutateElement(draggingElement, {
  4316. points: [...points.slice(0, -1), [dx, dy]],
  4317. });
  4318. }
  4319. if (isBindingElement(draggingElement, false)) {
  4320. // When creating a linear element by dragging
  4321. this.maybeSuggestBindingsForLinearElementAtCoords(
  4322. draggingElement,
  4323. [pointerCoords],
  4324. this.state.startBoundElement,
  4325. );
  4326. }
  4327. } else {
  4328. pointerDownState.lastCoords.x = pointerCoords.x;
  4329. pointerDownState.lastCoords.y = pointerCoords.y;
  4330. this.maybeDragNewGenericElement(pointerDownState, event);
  4331. }
  4332. if (this.state.activeTool.type === "selection") {
  4333. pointerDownState.boxSelection.hasOccurred = true;
  4334. const elements = this.scene.getNonDeletedElements();
  4335. if (
  4336. !event.shiftKey &&
  4337. // allows for box-selecting points (without shift)
  4338. !this.state.editingLinearElement &&
  4339. isSomeElementSelected(elements, this.state)
  4340. ) {
  4341. if (pointerDownState.withCmdOrCtrl && pointerDownState.hit.element) {
  4342. this.setState((prevState) =>
  4343. selectGroupsForSelectedElements(
  4344. {
  4345. ...prevState,
  4346. selectedElementIds: {
  4347. [pointerDownState.hit.element!.id]: true,
  4348. },
  4349. },
  4350. this.scene.getNonDeletedElements(),
  4351. ),
  4352. );
  4353. } else {
  4354. this.setState({
  4355. selectedElementIds: {},
  4356. selectedGroupIds: {},
  4357. editingGroupId: null,
  4358. });
  4359. }
  4360. }
  4361. // box-select line editor points
  4362. if (this.state.editingLinearElement) {
  4363. LinearElementEditor.handleBoxSelection(
  4364. event,
  4365. this.state,
  4366. this.setState.bind(this),
  4367. );
  4368. // regular box-select
  4369. } else {
  4370. const elementsWithinSelection = getElementsWithinSelection(
  4371. elements,
  4372. draggingElement,
  4373. );
  4374. this.setState((prevState) =>
  4375. selectGroupsForSelectedElements(
  4376. {
  4377. ...prevState,
  4378. selectedElementIds: {
  4379. ...prevState.selectedElementIds,
  4380. ...elementsWithinSelection.reduce(
  4381. (acc: Record<ExcalidrawElement["id"], true>, element) => {
  4382. acc[element.id] = true;
  4383. return acc;
  4384. },
  4385. {},
  4386. ),
  4387. ...(pointerDownState.hit.element
  4388. ? {
  4389. // if using ctrl/cmd, select the hitElement only if we
  4390. // haven't box-selected anything else
  4391. [pointerDownState.hit.element.id]:
  4392. !elementsWithinSelection.length,
  4393. }
  4394. : null),
  4395. },
  4396. showHyperlinkPopup:
  4397. elementsWithinSelection.length === 1 &&
  4398. elementsWithinSelection[0].link
  4399. ? "info"
  4400. : false,
  4401. // select linear element only when we haven't box-selected anything else
  4402. selectedLinearElement:
  4403. elementsWithinSelection.length === 1 &&
  4404. isLinearElement(elementsWithinSelection[0])
  4405. ? new LinearElementEditor(
  4406. elementsWithinSelection[0],
  4407. this.scene,
  4408. )
  4409. : null,
  4410. },
  4411. this.scene.getNonDeletedElements(),
  4412. ),
  4413. );
  4414. }
  4415. }
  4416. });
  4417. }
  4418. // Returns whether the pointer move happened over either scrollbar
  4419. private handlePointerMoveOverScrollbars(
  4420. event: PointerEvent,
  4421. pointerDownState: PointerDownState,
  4422. ): boolean {
  4423. if (pointerDownState.scrollbars.isOverHorizontal) {
  4424. const x = event.clientX;
  4425. const dx = x - pointerDownState.lastCoords.x;
  4426. this.setState({
  4427. scrollX: this.state.scrollX - dx / this.state.zoom.value,
  4428. });
  4429. pointerDownState.lastCoords.x = x;
  4430. return true;
  4431. }
  4432. if (pointerDownState.scrollbars.isOverVertical) {
  4433. const y = event.clientY;
  4434. const dy = y - pointerDownState.lastCoords.y;
  4435. this.setState({
  4436. scrollY: this.state.scrollY - dy / this.state.zoom.value,
  4437. });
  4438. pointerDownState.lastCoords.y = y;
  4439. return true;
  4440. }
  4441. return false;
  4442. }
  4443. private onPointerUpFromPointerDownHandler(
  4444. pointerDownState: PointerDownState,
  4445. ): (event: PointerEvent) => void {
  4446. return withBatchedUpdates((childEvent: PointerEvent) => {
  4447. const {
  4448. draggingElement,
  4449. resizingElement,
  4450. multiElement,
  4451. activeTool,
  4452. isResizing,
  4453. isRotating,
  4454. } = this.state;
  4455. this.setState({
  4456. isResizing: false,
  4457. isRotating: false,
  4458. resizingElement: null,
  4459. selectionElement: null,
  4460. cursorButton: "up",
  4461. // text elements are reset on finalize, and resetting on pointerup
  4462. // may cause issues with double taps
  4463. editingElement:
  4464. multiElement || isTextElement(this.state.editingElement)
  4465. ? this.state.editingElement
  4466. : null,
  4467. });
  4468. this.savePointer(childEvent.clientX, childEvent.clientY, "up");
  4469. // Handle end of dragging a point of a linear element, might close a loop
  4470. // and sets binding element
  4471. if (this.state.editingLinearElement) {
  4472. if (
  4473. !pointerDownState.boxSelection.hasOccurred &&
  4474. pointerDownState.hit?.element?.id !==
  4475. this.state.editingLinearElement.elementId
  4476. ) {
  4477. this.actionManager.executeAction(actionFinalize);
  4478. } else {
  4479. const editingLinearElement = LinearElementEditor.handlePointerUp(
  4480. childEvent,
  4481. this.state.editingLinearElement,
  4482. this.state,
  4483. );
  4484. if (editingLinearElement !== this.state.editingLinearElement) {
  4485. this.setState({
  4486. editingLinearElement,
  4487. suggestedBindings: [],
  4488. });
  4489. }
  4490. }
  4491. } else if (this.state.selectedLinearElement) {
  4492. if (
  4493. pointerDownState.hit?.element?.id !==
  4494. this.state.selectedLinearElement.elementId
  4495. ) {
  4496. const selectedELements = getSelectedElements(
  4497. this.scene.getNonDeletedElements(),
  4498. this.state,
  4499. );
  4500. // set selectedLinearElement to null if there is more than one element selected since we don't want to show linear element handles
  4501. if (selectedELements.length > 1) {
  4502. this.setState({ selectedLinearElement: null });
  4503. }
  4504. } else {
  4505. const linearElementEditor = LinearElementEditor.handlePointerUp(
  4506. childEvent,
  4507. this.state.selectedLinearElement,
  4508. this.state,
  4509. );
  4510. const { startBindingElement, endBindingElement } =
  4511. linearElementEditor;
  4512. const element = this.scene.getElement(linearElementEditor.elementId);
  4513. if (isBindingElement(element)) {
  4514. bindOrUnbindLinearElement(
  4515. element,
  4516. startBindingElement,
  4517. endBindingElement,
  4518. );
  4519. }
  4520. if (linearElementEditor !== this.state.selectedLinearElement) {
  4521. this.setState({
  4522. selectedLinearElement: {
  4523. ...linearElementEditor,
  4524. selectedPointsIndices: null,
  4525. },
  4526. suggestedBindings: [],
  4527. });
  4528. }
  4529. }
  4530. }
  4531. lastPointerUp = null;
  4532. if (pointerDownState.eventListeners.onMove) {
  4533. pointerDownState.eventListeners.onMove.flush();
  4534. }
  4535. window.removeEventListener(
  4536. EVENT.POINTER_MOVE,
  4537. pointerDownState.eventListeners.onMove!,
  4538. );
  4539. window.removeEventListener(
  4540. EVENT.POINTER_UP,
  4541. pointerDownState.eventListeners.onUp!,
  4542. );
  4543. window.removeEventListener(
  4544. EVENT.KEYDOWN,
  4545. pointerDownState.eventListeners.onKeyDown!,
  4546. );
  4547. window.removeEventListener(
  4548. EVENT.KEYUP,
  4549. pointerDownState.eventListeners.onKeyUp!,
  4550. );
  4551. if (this.state.pendingImageElementId) {
  4552. this.setState({ pendingImageElementId: null });
  4553. }
  4554. if (draggingElement?.type === "freedraw") {
  4555. const pointerCoords = viewportCoordsToSceneCoords(
  4556. childEvent,
  4557. this.state,
  4558. );
  4559. const points = draggingElement.points;
  4560. let dx = pointerCoords.x - draggingElement.x;
  4561. let dy = pointerCoords.y - draggingElement.y;
  4562. // Allows dots to avoid being flagged as infinitely small
  4563. if (dx === points[0][0] && dy === points[0][1]) {
  4564. dy += 0.0001;
  4565. dx += 0.0001;
  4566. }
  4567. const pressures = draggingElement.simulatePressure
  4568. ? []
  4569. : [...draggingElement.pressures, childEvent.pressure];
  4570. mutateElement(draggingElement, {
  4571. points: [...points, [dx, dy]],
  4572. pressures,
  4573. lastCommittedPoint: [dx, dy],
  4574. });
  4575. this.actionManager.executeAction(actionFinalize);
  4576. return;
  4577. }
  4578. if (isImageElement(draggingElement)) {
  4579. const imageElement = draggingElement;
  4580. try {
  4581. this.initializeImageDimensions(imageElement);
  4582. this.setState(
  4583. { selectedElementIds: { [imageElement.id]: true } },
  4584. () => {
  4585. this.actionManager.executeAction(actionFinalize);
  4586. },
  4587. );
  4588. } catch (error: any) {
  4589. console.error(error);
  4590. this.scene.replaceAllElements(
  4591. this.scene
  4592. .getElementsIncludingDeleted()
  4593. .filter((el) => el.id !== imageElement.id),
  4594. );
  4595. this.actionManager.executeAction(actionFinalize);
  4596. }
  4597. return;
  4598. }
  4599. if (isLinearElement(draggingElement)) {
  4600. if (draggingElement!.points.length > 1) {
  4601. this.history.resumeRecording();
  4602. }
  4603. const pointerCoords = viewportCoordsToSceneCoords(
  4604. childEvent,
  4605. this.state,
  4606. );
  4607. if (
  4608. !pointerDownState.drag.hasOccurred &&
  4609. draggingElement &&
  4610. !multiElement
  4611. ) {
  4612. mutateElement(draggingElement, {
  4613. points: [
  4614. ...draggingElement.points,
  4615. [
  4616. pointerCoords.x - draggingElement.x,
  4617. pointerCoords.y - draggingElement.y,
  4618. ],
  4619. ],
  4620. });
  4621. this.setState({
  4622. multiElement: draggingElement,
  4623. editingElement: this.state.draggingElement,
  4624. });
  4625. } else if (pointerDownState.drag.hasOccurred && !multiElement) {
  4626. if (
  4627. isBindingEnabled(this.state) &&
  4628. isBindingElement(draggingElement, false)
  4629. ) {
  4630. maybeBindLinearElement(
  4631. draggingElement,
  4632. this.state,
  4633. this.scene,
  4634. pointerCoords,
  4635. );
  4636. }
  4637. this.setState({ suggestedBindings: [], startBoundElement: null });
  4638. if (!activeTool.locked) {
  4639. resetCursor(this.canvas);
  4640. this.setState((prevState) => ({
  4641. draggingElement: null,
  4642. activeTool: updateActiveTool(this.state, {
  4643. type: "selection",
  4644. }),
  4645. selectedElementIds: {
  4646. ...prevState.selectedElementIds,
  4647. [draggingElement.id]: true,
  4648. },
  4649. selectedLinearElement: new LinearElementEditor(
  4650. draggingElement,
  4651. this.scene,
  4652. ),
  4653. }));
  4654. } else {
  4655. this.setState((prevState) => ({
  4656. draggingElement: null,
  4657. }));
  4658. }
  4659. }
  4660. return;
  4661. }
  4662. if (
  4663. activeTool.type !== "selection" &&
  4664. draggingElement &&
  4665. isInvisiblySmallElement(draggingElement)
  4666. ) {
  4667. // remove invisible element which was added in onPointerDown
  4668. this.scene.replaceAllElements(
  4669. this.scene.getElementsIncludingDeleted().slice(0, -1),
  4670. );
  4671. this.setState({
  4672. draggingElement: null,
  4673. });
  4674. return;
  4675. }
  4676. if (draggingElement) {
  4677. mutateElement(
  4678. draggingElement,
  4679. getNormalizedDimensions(draggingElement),
  4680. );
  4681. }
  4682. if (resizingElement) {
  4683. this.history.resumeRecording();
  4684. }
  4685. if (resizingElement && isInvisiblySmallElement(resizingElement)) {
  4686. this.scene.replaceAllElements(
  4687. this.scene
  4688. .getElementsIncludingDeleted()
  4689. .filter((el) => el.id !== resizingElement.id),
  4690. );
  4691. }
  4692. // Code below handles selection when element(s) weren't
  4693. // drag or added to selection on pointer down phase.
  4694. const hitElement = pointerDownState.hit.element;
  4695. if (
  4696. this.state.selectedLinearElement?.elementId !== hitElement?.id &&
  4697. isLinearElement(hitElement)
  4698. ) {
  4699. const selectedELements = getSelectedElements(
  4700. this.scene.getNonDeletedElements(),
  4701. this.state,
  4702. );
  4703. // set selectedLinearElement when no other element selected except
  4704. // the one we've hit
  4705. if (selectedELements.length === 1) {
  4706. this.setState({
  4707. selectedLinearElement: new LinearElementEditor(
  4708. hitElement,
  4709. this.scene,
  4710. ),
  4711. });
  4712. }
  4713. }
  4714. if (isEraserActive(this.state)) {
  4715. const draggedDistance = distance2d(
  4716. this.lastPointerDown!.clientX,
  4717. this.lastPointerDown!.clientY,
  4718. this.lastPointerUp!.clientX,
  4719. this.lastPointerUp!.clientY,
  4720. );
  4721. if (draggedDistance === 0) {
  4722. const scenePointer = viewportCoordsToSceneCoords(
  4723. {
  4724. clientX: this.lastPointerUp!.clientX,
  4725. clientY: this.lastPointerUp!.clientY,
  4726. },
  4727. this.state,
  4728. );
  4729. const hitElements = this.getElementsAtPosition(
  4730. scenePointer.x,
  4731. scenePointer.y,
  4732. );
  4733. hitElements.forEach(
  4734. (hitElement) =>
  4735. (pointerDownState.elementIdsToErase[hitElement.id] = {
  4736. erase: true,
  4737. opacity: hitElement.opacity,
  4738. }),
  4739. );
  4740. }
  4741. this.eraseElements(pointerDownState);
  4742. return;
  4743. } else if (Object.keys(pointerDownState.elementIdsToErase).length) {
  4744. this.restoreReadyToEraseElements(pointerDownState);
  4745. }
  4746. if (
  4747. hitElement &&
  4748. !pointerDownState.drag.hasOccurred &&
  4749. !pointerDownState.hit.wasAddedToSelection &&
  4750. // if we're editing a line, pointerup shouldn't switch selection if
  4751. // box selected
  4752. (!this.state.editingLinearElement ||
  4753. !pointerDownState.boxSelection.hasOccurred)
  4754. ) {
  4755. // when inside line editor, shift selects points instead
  4756. if (childEvent.shiftKey && !this.state.editingLinearElement) {
  4757. if (this.state.selectedElementIds[hitElement.id]) {
  4758. if (isSelectedViaGroup(this.state, hitElement)) {
  4759. // We want to unselect all groups hitElement is part of
  4760. // as well as all elements that are part of the groups
  4761. // hitElement is part of
  4762. const idsOfSelectedElementsThatAreInGroups = hitElement.groupIds
  4763. .flatMap((groupId) =>
  4764. getElementsInGroup(
  4765. this.scene.getNonDeletedElements(),
  4766. groupId,
  4767. ),
  4768. )
  4769. .map((element) => ({ [element.id]: false }))
  4770. .reduce((prevId, acc) => ({ ...prevId, ...acc }), {});
  4771. this.setState((_prevState) => ({
  4772. selectedGroupIds: {
  4773. ..._prevState.selectedElementIds,
  4774. ...hitElement.groupIds
  4775. .map((gId) => ({ [gId]: false }))
  4776. .reduce((prev, acc) => ({ ...prev, ...acc }), {}),
  4777. },
  4778. selectedElementIds: {
  4779. ..._prevState.selectedElementIds,
  4780. ...idsOfSelectedElementsThatAreInGroups,
  4781. },
  4782. }));
  4783. // if not gragging a linear element point (outside editor)
  4784. } else if (!this.state.selectedLinearElement?.isDragging) {
  4785. // remove element from selection while
  4786. // keeping prev elements selected
  4787. this.setState((prevState) => {
  4788. const newSelectedElementIds = {
  4789. ...prevState.selectedElementIds,
  4790. [hitElement!.id]: false,
  4791. };
  4792. const newSelectedElements = getSelectedElements(
  4793. this.scene.getNonDeletedElements(),
  4794. { ...prevState, selectedElementIds: newSelectedElementIds },
  4795. );
  4796. return selectGroupsForSelectedElements(
  4797. {
  4798. ...prevState,
  4799. selectedElementIds: newSelectedElementIds,
  4800. // set selectedLinearElement only if thats the only element selected
  4801. selectedLinearElement:
  4802. newSelectedElements.length === 1 &&
  4803. isLinearElement(newSelectedElements[0])
  4804. ? new LinearElementEditor(
  4805. newSelectedElements[0],
  4806. this.scene,
  4807. )
  4808. : prevState.selectedLinearElement,
  4809. },
  4810. this.scene.getNonDeletedElements(),
  4811. );
  4812. });
  4813. }
  4814. } else {
  4815. // add element to selection while
  4816. // keeping prev elements selected
  4817. this.setState((_prevState) => ({
  4818. selectedElementIds: {
  4819. ..._prevState.selectedElementIds,
  4820. [hitElement!.id]: true,
  4821. },
  4822. }));
  4823. }
  4824. } else {
  4825. this.setState((prevState) => ({
  4826. ...selectGroupsForSelectedElements(
  4827. {
  4828. ...prevState,
  4829. selectedElementIds: { [hitElement.id]: true },
  4830. selectedLinearElement:
  4831. isLinearElement(hitElement) &&
  4832. // Don't set `selectedLinearElement` if its same as the hitElement, this is mainly to prevent resetting the `hoverPointIndex` to -1.
  4833. // Future we should update the API to take care of setting the correct `hoverPointIndex` when initialized
  4834. prevState.selectedLinearElement?.elementId !== hitElement.id
  4835. ? new LinearElementEditor(hitElement, this.scene)
  4836. : prevState.selectedLinearElement,
  4837. },
  4838. this.scene.getNonDeletedElements(),
  4839. ),
  4840. }));
  4841. }
  4842. }
  4843. if (
  4844. !pointerDownState.drag.hasOccurred &&
  4845. !this.state.isResizing &&
  4846. ((hitElement &&
  4847. isHittingElementBoundingBoxWithoutHittingElement(
  4848. hitElement,
  4849. this.state,
  4850. pointerDownState.origin.x,
  4851. pointerDownState.origin.y,
  4852. )) ||
  4853. (!hitElement &&
  4854. pointerDownState.hit.hasHitCommonBoundingBoxOfSelectedElements))
  4855. ) {
  4856. if (this.state.editingLinearElement) {
  4857. this.setState({ editingLinearElement: null });
  4858. } else {
  4859. // Deselect selected elements
  4860. this.setState({
  4861. selectedElementIds: {},
  4862. selectedGroupIds: {},
  4863. editingGroupId: null,
  4864. });
  4865. }
  4866. return;
  4867. }
  4868. if (
  4869. !activeTool.locked &&
  4870. activeTool.type !== "freedraw" &&
  4871. draggingElement
  4872. ) {
  4873. this.setState((prevState) => ({
  4874. selectedElementIds: {
  4875. ...prevState.selectedElementIds,
  4876. [draggingElement.id]: true,
  4877. },
  4878. }));
  4879. }
  4880. if (
  4881. activeTool.type !== "selection" ||
  4882. isSomeElementSelected(this.scene.getNonDeletedElements(), this.state)
  4883. ) {
  4884. this.history.resumeRecording();
  4885. }
  4886. if (pointerDownState.drag.hasOccurred || isResizing || isRotating) {
  4887. (isBindingEnabled(this.state)
  4888. ? bindOrUnbindSelectedElements
  4889. : unbindLinearElements)(
  4890. getSelectedElements(this.scene.getNonDeletedElements(), this.state),
  4891. );
  4892. }
  4893. if (!activeTool.locked && activeTool.type !== "freedraw") {
  4894. resetCursor(this.canvas);
  4895. this.setState({
  4896. draggingElement: null,
  4897. suggestedBindings: [],
  4898. activeTool: updateActiveTool(this.state, { type: "selection" }),
  4899. });
  4900. } else {
  4901. this.setState({
  4902. draggingElement: null,
  4903. suggestedBindings: [],
  4904. });
  4905. }
  4906. });
  4907. }
  4908. private restoreReadyToEraseElements = (
  4909. pointerDownState: PointerDownState,
  4910. ) => {
  4911. const elements = this.scene.getElementsIncludingDeleted().map((ele) => {
  4912. if (
  4913. pointerDownState.elementIdsToErase[ele.id] &&
  4914. pointerDownState.elementIdsToErase[ele.id].erase
  4915. ) {
  4916. return newElementWith(ele, {
  4917. opacity: pointerDownState.elementIdsToErase[ele.id].opacity,
  4918. });
  4919. } else if (
  4920. isBoundToContainer(ele) &&
  4921. pointerDownState.elementIdsToErase[ele.containerId] &&
  4922. pointerDownState.elementIdsToErase[ele.containerId].erase
  4923. ) {
  4924. return newElementWith(ele, {
  4925. opacity: pointerDownState.elementIdsToErase[ele.containerId].opacity,
  4926. });
  4927. }
  4928. return ele;
  4929. });
  4930. this.scene.replaceAllElements(elements);
  4931. };
  4932. private eraseElements = (pointerDownState: PointerDownState) => {
  4933. const elements = this.scene.getElementsIncludingDeleted().map((ele) => {
  4934. if (
  4935. pointerDownState.elementIdsToErase[ele.id] &&
  4936. pointerDownState.elementIdsToErase[ele.id].erase
  4937. ) {
  4938. return newElementWith(ele, { isDeleted: true });
  4939. } else if (
  4940. isBoundToContainer(ele) &&
  4941. pointerDownState.elementIdsToErase[ele.containerId] &&
  4942. pointerDownState.elementIdsToErase[ele.containerId].erase
  4943. ) {
  4944. return newElementWith(ele, { isDeleted: true });
  4945. }
  4946. return ele;
  4947. });
  4948. this.history.resumeRecording();
  4949. this.scene.replaceAllElements(elements);
  4950. };
  4951. private initializeImage = async ({
  4952. imageFile,
  4953. imageElement: _imageElement,
  4954. showCursorImagePreview = false,
  4955. }: {
  4956. imageFile: File;
  4957. imageElement: ExcalidrawImageElement;
  4958. showCursorImagePreview?: boolean;
  4959. }) => {
  4960. // at this point this should be guaranteed image file, but we do this check
  4961. // to satisfy TS down the line
  4962. if (!isSupportedImageFile(imageFile)) {
  4963. throw new Error(t("errors.unsupportedFileType"));
  4964. }
  4965. const mimeType = imageFile.type;
  4966. setCursor(this.canvas, "wait");
  4967. if (mimeType === MIME_TYPES.svg) {
  4968. try {
  4969. imageFile = SVGStringToFile(
  4970. await normalizeSVG(await imageFile.text()),
  4971. imageFile.name,
  4972. );
  4973. } catch (error: any) {
  4974. console.warn(error);
  4975. throw new Error(t("errors.svgImageInsertError"));
  4976. }
  4977. }
  4978. // generate image id (by default the file digest) before any
  4979. // resizing/compression takes place to keep it more portable
  4980. const fileId = await ((this.props.generateIdForFile?.(
  4981. imageFile,
  4982. ) as Promise<FileId>) || generateIdFromFile(imageFile));
  4983. if (!fileId) {
  4984. console.warn(
  4985. "Couldn't generate file id or the supplied `generateIdForFile` didn't resolve to one.",
  4986. );
  4987. throw new Error(t("errors.imageInsertError"));
  4988. }
  4989. const existingFileData = this.files[fileId];
  4990. if (!existingFileData?.dataURL) {
  4991. try {
  4992. imageFile = await resizeImageFile(imageFile, {
  4993. maxWidthOrHeight: DEFAULT_MAX_IMAGE_WIDTH_OR_HEIGHT,
  4994. });
  4995. } catch (error: any) {
  4996. console.error("error trying to resing image file on insertion", error);
  4997. }
  4998. if (imageFile.size > MAX_ALLOWED_FILE_BYTES) {
  4999. throw new Error(
  5000. t("errors.fileTooBig", {
  5001. maxSize: `${Math.trunc(MAX_ALLOWED_FILE_BYTES / 1024 / 1024)}MB`,
  5002. }),
  5003. );
  5004. }
  5005. }
  5006. if (showCursorImagePreview) {
  5007. const dataURL = this.files[fileId]?.dataURL;
  5008. // optimization so that we don't unnecessarily resize the original
  5009. // full-size file for cursor preview
  5010. // (it's much faster to convert the resized dataURL to File)
  5011. const resizedFile = dataURL && dataURLToFile(dataURL);
  5012. this.setImagePreviewCursor(resizedFile || imageFile);
  5013. }
  5014. const dataURL =
  5015. this.files[fileId]?.dataURL || (await getDataURL(imageFile));
  5016. const imageElement = mutateElement(
  5017. _imageElement,
  5018. {
  5019. fileId,
  5020. },
  5021. false,
  5022. ) as NonDeleted<InitializedExcalidrawImageElement>;
  5023. return new Promise<NonDeleted<InitializedExcalidrawImageElement>>(
  5024. async (resolve, reject) => {
  5025. try {
  5026. this.files = {
  5027. ...this.files,
  5028. [fileId]: {
  5029. mimeType,
  5030. id: fileId,
  5031. dataURL,
  5032. created: Date.now(),
  5033. lastRetrieved: Date.now(),
  5034. },
  5035. };
  5036. const cachedImageData = this.imageCache.get(fileId);
  5037. if (!cachedImageData) {
  5038. this.addNewImagesToImageCache();
  5039. await this.updateImageCache([imageElement]);
  5040. }
  5041. if (cachedImageData?.image instanceof Promise) {
  5042. await cachedImageData.image;
  5043. }
  5044. if (
  5045. this.state.pendingImageElementId !== imageElement.id &&
  5046. this.state.draggingElement?.id !== imageElement.id
  5047. ) {
  5048. this.initializeImageDimensions(imageElement, true);
  5049. }
  5050. resolve(imageElement);
  5051. } catch (error: any) {
  5052. console.error(error);
  5053. reject(new Error(t("errors.imageInsertError")));
  5054. } finally {
  5055. if (!showCursorImagePreview) {
  5056. resetCursor(this.canvas);
  5057. }
  5058. }
  5059. },
  5060. );
  5061. };
  5062. /**
  5063. * inserts image into elements array and rerenders
  5064. */
  5065. private insertImageElement = async (
  5066. imageElement: ExcalidrawImageElement,
  5067. imageFile: File,
  5068. showCursorImagePreview?: boolean,
  5069. ) => {
  5070. this.scene.replaceAllElements([
  5071. ...this.scene.getElementsIncludingDeleted(),
  5072. imageElement,
  5073. ]);
  5074. try {
  5075. await this.initializeImage({
  5076. imageFile,
  5077. imageElement,
  5078. showCursorImagePreview,
  5079. });
  5080. } catch (error: any) {
  5081. mutateElement(imageElement, {
  5082. isDeleted: true,
  5083. });
  5084. this.actionManager.executeAction(actionFinalize);
  5085. this.setState({
  5086. errorMessage: error.message || t("errors.imageInsertError"),
  5087. });
  5088. }
  5089. };
  5090. private setImagePreviewCursor = async (imageFile: File) => {
  5091. // mustn't be larger than 128 px
  5092. // https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Basic_User_Interface/Using_URL_values_for_the_cursor_property
  5093. const cursorImageSizePx = 96;
  5094. const imagePreview = await resizeImageFile(imageFile, {
  5095. maxWidthOrHeight: cursorImageSizePx,
  5096. });
  5097. let previewDataURL = await getDataURL(imagePreview);
  5098. // SVG cannot be resized via `resizeImageFile` so we resize by rendering to
  5099. // a small canvas
  5100. if (imageFile.type === MIME_TYPES.svg) {
  5101. const img = await loadHTMLImageElement(previewDataURL);
  5102. let height = Math.min(img.height, cursorImageSizePx);
  5103. let width = height * (img.width / img.height);
  5104. if (width > cursorImageSizePx) {
  5105. width = cursorImageSizePx;
  5106. height = width * (img.height / img.width);
  5107. }
  5108. const canvas = document.createElement("canvas");
  5109. canvas.height = height;
  5110. canvas.width = width;
  5111. const context = canvas.getContext("2d")!;
  5112. context.drawImage(img, 0, 0, width, height);
  5113. previewDataURL = canvas.toDataURL(MIME_TYPES.svg) as DataURL;
  5114. }
  5115. if (this.state.pendingImageElementId) {
  5116. setCursor(this.canvas, `url(${previewDataURL}) 4 4, auto`);
  5117. }
  5118. };
  5119. private onImageAction = async (
  5120. { insertOnCanvasDirectly } = { insertOnCanvasDirectly: false },
  5121. ) => {
  5122. try {
  5123. const clientX = this.state.width / 2 + this.state.offsetLeft;
  5124. const clientY = this.state.height / 2 + this.state.offsetTop;
  5125. const { x, y } = viewportCoordsToSceneCoords(
  5126. { clientX, clientY },
  5127. this.state,
  5128. );
  5129. const imageFile = await fileOpen({
  5130. description: "Image",
  5131. extensions: ["jpg", "png", "svg", "gif"],
  5132. });
  5133. const imageElement = this.createImageElement({
  5134. sceneX: x,
  5135. sceneY: y,
  5136. });
  5137. if (insertOnCanvasDirectly) {
  5138. this.insertImageElement(imageElement, imageFile);
  5139. this.initializeImageDimensions(imageElement);
  5140. this.setState(
  5141. {
  5142. selectedElementIds: { [imageElement.id]: true },
  5143. },
  5144. () => {
  5145. this.actionManager.executeAction(actionFinalize);
  5146. },
  5147. );
  5148. } else {
  5149. this.setState(
  5150. {
  5151. pendingImageElementId: imageElement.id,
  5152. },
  5153. () => {
  5154. this.insertImageElement(
  5155. imageElement,
  5156. imageFile,
  5157. /* showCursorImagePreview */ true,
  5158. );
  5159. },
  5160. );
  5161. }
  5162. } catch (error: any) {
  5163. if (error.name !== "AbortError") {
  5164. console.error(error);
  5165. } else {
  5166. console.warn(error);
  5167. }
  5168. this.setState(
  5169. {
  5170. pendingImageElementId: null,
  5171. editingElement: null,
  5172. activeTool: updateActiveTool(this.state, { type: "selection" }),
  5173. },
  5174. () => {
  5175. this.actionManager.executeAction(actionFinalize);
  5176. },
  5177. );
  5178. }
  5179. };
  5180. private initializeImageDimensions = (
  5181. imageElement: ExcalidrawImageElement,
  5182. forceNaturalSize = false,
  5183. ) => {
  5184. const image =
  5185. isInitializedImageElement(imageElement) &&
  5186. this.imageCache.get(imageElement.fileId)?.image;
  5187. if (!image || image instanceof Promise) {
  5188. if (
  5189. imageElement.width < DRAGGING_THRESHOLD / this.state.zoom.value &&
  5190. imageElement.height < DRAGGING_THRESHOLD / this.state.zoom.value
  5191. ) {
  5192. const placeholderSize = 100 / this.state.zoom.value;
  5193. mutateElement(imageElement, {
  5194. x: imageElement.x - placeholderSize / 2,
  5195. y: imageElement.y - placeholderSize / 2,
  5196. width: placeholderSize,
  5197. height: placeholderSize,
  5198. });
  5199. }
  5200. return;
  5201. }
  5202. if (
  5203. forceNaturalSize ||
  5204. // if user-created bounding box is below threshold, assume the
  5205. // intention was to click instead of drag, and use the image's
  5206. // intrinsic size
  5207. (imageElement.width < DRAGGING_THRESHOLD / this.state.zoom.value &&
  5208. imageElement.height < DRAGGING_THRESHOLD / this.state.zoom.value)
  5209. ) {
  5210. const minHeight = Math.max(this.state.height - 120, 160);
  5211. // max 65% of canvas height, clamped to <300px, vh - 120px>
  5212. const maxHeight = Math.min(
  5213. minHeight,
  5214. Math.floor(this.state.height * 0.5) / this.state.zoom.value,
  5215. );
  5216. const height = Math.min(image.naturalHeight, maxHeight);
  5217. const width = height * (image.naturalWidth / image.naturalHeight);
  5218. // add current imageElement width/height to account for previous centering
  5219. // of the placeholder image
  5220. const x = imageElement.x + imageElement.width / 2 - width / 2;
  5221. const y = imageElement.y + imageElement.height / 2 - height / 2;
  5222. mutateElement(imageElement, { x, y, width, height });
  5223. }
  5224. };
  5225. /** updates image cache, refreshing updated elements and/or setting status
  5226. to error for images that fail during <img> element creation */
  5227. private updateImageCache = async (
  5228. elements: readonly InitializedExcalidrawImageElement[],
  5229. files = this.files,
  5230. ) => {
  5231. const { updatedFiles, erroredFiles } = await _updateImageCache({
  5232. imageCache: this.imageCache,
  5233. fileIds: elements.map((element) => element.fileId),
  5234. files,
  5235. });
  5236. if (updatedFiles.size || erroredFiles.size) {
  5237. for (const element of elements) {
  5238. if (updatedFiles.has(element.fileId)) {
  5239. invalidateShapeForElement(element);
  5240. }
  5241. }
  5242. }
  5243. if (erroredFiles.size) {
  5244. this.scene.replaceAllElements(
  5245. this.scene.getElementsIncludingDeleted().map((element) => {
  5246. if (
  5247. isInitializedImageElement(element) &&
  5248. erroredFiles.has(element.fileId)
  5249. ) {
  5250. return newElementWith(element, {
  5251. status: "error",
  5252. });
  5253. }
  5254. return element;
  5255. }),
  5256. );
  5257. }
  5258. return { updatedFiles, erroredFiles };
  5259. };
  5260. /** adds new images to imageCache and re-renders if needed */
  5261. private addNewImagesToImageCache = async (
  5262. imageElements: InitializedExcalidrawImageElement[] = getInitializedImageElements(
  5263. this.scene.getNonDeletedElements(),
  5264. ),
  5265. files: BinaryFiles = this.files,
  5266. ) => {
  5267. const uncachedImageElements = imageElements.filter(
  5268. (element) => !element.isDeleted && !this.imageCache.has(element.fileId),
  5269. );
  5270. if (uncachedImageElements.length) {
  5271. const { updatedFiles } = await this.updateImageCache(
  5272. uncachedImageElements,
  5273. files,
  5274. );
  5275. if (updatedFiles.size) {
  5276. this.scene.informMutation();
  5277. }
  5278. }
  5279. };
  5280. /** generally you should use `addNewImagesToImageCache()` directly if you need
  5281. * to render new images. This is just a failsafe */
  5282. private scheduleImageRefresh = throttle(() => {
  5283. this.addNewImagesToImageCache();
  5284. }, IMAGE_RENDER_TIMEOUT);
  5285. private updateBindingEnabledOnPointerMove = (
  5286. event: React.PointerEvent<HTMLCanvasElement>,
  5287. ) => {
  5288. const shouldEnableBinding = shouldEnableBindingForPointerEvent(event);
  5289. if (this.state.isBindingEnabled !== shouldEnableBinding) {
  5290. this.setState({ isBindingEnabled: shouldEnableBinding });
  5291. }
  5292. };
  5293. private maybeSuggestBindingAtCursor = (pointerCoords: {
  5294. x: number;
  5295. y: number;
  5296. }): void => {
  5297. const hoveredBindableElement = getHoveredElementForBinding(
  5298. pointerCoords,
  5299. this.scene,
  5300. );
  5301. this.setState({
  5302. suggestedBindings:
  5303. hoveredBindableElement != null ? [hoveredBindableElement] : [],
  5304. });
  5305. };
  5306. private maybeSuggestBindingsForLinearElementAtCoords = (
  5307. linearElement: NonDeleted<ExcalidrawLinearElement>,
  5308. /** scene coords */
  5309. pointerCoords: {
  5310. x: number;
  5311. y: number;
  5312. }[],
  5313. // During line creation the start binding hasn't been written yet
  5314. // into `linearElement`
  5315. oppositeBindingBoundElement?: ExcalidrawBindableElement | null,
  5316. ): void => {
  5317. if (!pointerCoords.length) {
  5318. return;
  5319. }
  5320. const suggestedBindings = pointerCoords.reduce(
  5321. (acc: NonDeleted<ExcalidrawBindableElement>[], coords) => {
  5322. const hoveredBindableElement = getHoveredElementForBinding(
  5323. coords,
  5324. this.scene,
  5325. );
  5326. if (
  5327. hoveredBindableElement != null &&
  5328. !isLinearElementSimpleAndAlreadyBound(
  5329. linearElement,
  5330. oppositeBindingBoundElement?.id,
  5331. hoveredBindableElement,
  5332. )
  5333. ) {
  5334. acc.push(hoveredBindableElement);
  5335. }
  5336. return acc;
  5337. },
  5338. [],
  5339. );
  5340. this.setState({ suggestedBindings });
  5341. };
  5342. private maybeSuggestBindingForAll(
  5343. selectedElements: NonDeleted<ExcalidrawElement>[],
  5344. ): void {
  5345. const suggestedBindings = getEligibleElementsForBinding(selectedElements);
  5346. this.setState({ suggestedBindings });
  5347. }
  5348. private clearSelection(hitElement: ExcalidrawElement | null): void {
  5349. this.setState((prevState) => ({
  5350. selectedElementIds: {},
  5351. selectedGroupIds: {},
  5352. // Continue editing the same group if the user selected a different
  5353. // element from it
  5354. editingGroupId:
  5355. prevState.editingGroupId &&
  5356. hitElement != null &&
  5357. isElementInGroup(hitElement, prevState.editingGroupId)
  5358. ? prevState.editingGroupId
  5359. : null,
  5360. }));
  5361. this.setState({
  5362. selectedElementIds: {},
  5363. previousSelectedElementIds: this.state.selectedElementIds,
  5364. });
  5365. }
  5366. private handleCanvasRef = (canvas: HTMLCanvasElement) => {
  5367. // canvas is null when unmounting
  5368. if (canvas !== null) {
  5369. this.canvas = canvas;
  5370. this.rc = rough.canvas(this.canvas);
  5371. this.canvas.addEventListener(EVENT.WHEEL, this.handleWheel, {
  5372. passive: false,
  5373. });
  5374. this.canvas.addEventListener(EVENT.TOUCH_START, this.onTapStart);
  5375. this.canvas.addEventListener(EVENT.TOUCH_END, this.onTapEnd);
  5376. } else {
  5377. this.canvas?.removeEventListener(EVENT.WHEEL, this.handleWheel);
  5378. this.canvas?.removeEventListener(EVENT.TOUCH_START, this.onTapStart);
  5379. this.canvas?.removeEventListener(EVENT.TOUCH_END, this.onTapEnd);
  5380. }
  5381. };
  5382. private handleAppOnDrop = async (event: React.DragEvent<HTMLDivElement>) => {
  5383. // must be retrieved first, in the same frame
  5384. const { file, fileHandle } = await getFileFromEvent(event);
  5385. try {
  5386. if (isSupportedImageFile(file)) {
  5387. // first attempt to decode scene from the image if it's embedded
  5388. // ---------------------------------------------------------------------
  5389. if (file?.type === MIME_TYPES.png || file?.type === MIME_TYPES.svg) {
  5390. try {
  5391. const scene = await loadFromBlob(
  5392. file,
  5393. this.state,
  5394. this.scene.getElementsIncludingDeleted(),
  5395. fileHandle,
  5396. );
  5397. this.syncActionResult({
  5398. ...scene,
  5399. appState: {
  5400. ...(scene.appState || this.state),
  5401. isLoading: false,
  5402. },
  5403. replaceFiles: true,
  5404. commitToHistory: true,
  5405. });
  5406. return;
  5407. } catch (error: any) {
  5408. if (error.name !== "EncodingError") {
  5409. throw error;
  5410. }
  5411. }
  5412. }
  5413. // if no scene is embedded or we fail for whatever reason, fall back
  5414. // to importing as regular image
  5415. // ---------------------------------------------------------------------
  5416. const { x: sceneX, y: sceneY } = viewportCoordsToSceneCoords(
  5417. event,
  5418. this.state,
  5419. );
  5420. const imageElement = this.createImageElement({ sceneX, sceneY });
  5421. this.insertImageElement(imageElement, file);
  5422. this.initializeImageDimensions(imageElement);
  5423. this.setState({ selectedElementIds: { [imageElement.id]: true } });
  5424. return;
  5425. }
  5426. } catch (error: any) {
  5427. return this.setState({
  5428. isLoading: false,
  5429. errorMessage: error.message,
  5430. });
  5431. }
  5432. const libraryJSON = event.dataTransfer.getData(MIME_TYPES.excalidrawlib);
  5433. if (libraryJSON && typeof libraryJSON === "string") {
  5434. try {
  5435. const libraryItems = parseLibraryJSON(libraryJSON);
  5436. this.addElementsFromPasteOrLibrary({
  5437. elements: distributeLibraryItemsOnSquareGrid(libraryItems),
  5438. position: event,
  5439. files: null,
  5440. });
  5441. } catch (error: any) {
  5442. this.setState({ errorMessage: error.message });
  5443. }
  5444. return;
  5445. }
  5446. if (file) {
  5447. // atetmpt to parse an excalidraw/excalidrawlib file
  5448. await this.loadFileToCanvas(file, fileHandle);
  5449. }
  5450. };
  5451. loadFileToCanvas = async (
  5452. file: File,
  5453. fileHandle: FileSystemHandle | null,
  5454. ) => {
  5455. file = await normalizeFile(file);
  5456. try {
  5457. const ret = await loadSceneOrLibraryFromBlob(
  5458. file,
  5459. this.state,
  5460. this.scene.getElementsIncludingDeleted(),
  5461. fileHandle,
  5462. );
  5463. if (ret.type === MIME_TYPES.excalidraw) {
  5464. this.setState({ isLoading: true });
  5465. this.syncActionResult({
  5466. ...ret.data,
  5467. appState: {
  5468. ...(ret.data.appState || this.state),
  5469. isLoading: false,
  5470. },
  5471. replaceFiles: true,
  5472. commitToHistory: true,
  5473. });
  5474. } else if (ret.type === MIME_TYPES.excalidrawlib) {
  5475. await this.library
  5476. .updateLibrary({
  5477. libraryItems: file,
  5478. merge: true,
  5479. openLibraryMenu: true,
  5480. })
  5481. .catch((error) => {
  5482. console.error(error);
  5483. this.setState({ errorMessage: t("errors.importLibraryError") });
  5484. });
  5485. }
  5486. } catch (error: any) {
  5487. this.setState({ isLoading: false, errorMessage: error.message });
  5488. }
  5489. };
  5490. private handleCanvasContextMenu = (
  5491. event: React.PointerEvent<HTMLCanvasElement>,
  5492. ) => {
  5493. event.preventDefault();
  5494. if (
  5495. (event.nativeEvent.pointerType === "touch" ||
  5496. (event.nativeEvent.pointerType === "pen" &&
  5497. // always allow if user uses a pen secondary button
  5498. event.button !== POINTER_BUTTON.SECONDARY)) &&
  5499. this.state.activeTool.type !== "selection"
  5500. ) {
  5501. return;
  5502. }
  5503. const { x, y } = viewportCoordsToSceneCoords(event, this.state);
  5504. const element = this.getElementAtPosition(x, y, {
  5505. preferSelected: true,
  5506. includeLockedElements: true,
  5507. });
  5508. const selectedElements = getSelectedElements(
  5509. this.scene.getNonDeletedElements(),
  5510. this.state,
  5511. );
  5512. const isHittignCommonBoundBox =
  5513. this.isHittingCommonBoundingBoxOfSelectedElements(
  5514. { x, y },
  5515. selectedElements,
  5516. );
  5517. const type = element || isHittignCommonBoundBox ? "element" : "canvas";
  5518. const container = this.excalidrawContainerRef.current!;
  5519. const { top: offsetTop, left: offsetLeft } =
  5520. container.getBoundingClientRect();
  5521. const left = event.clientX - offsetLeft;
  5522. const top = event.clientY - offsetTop;
  5523. trackEvent("contextMenu", "openContextMenu", type);
  5524. this.setState(
  5525. {
  5526. ...(element && !this.state.selectedElementIds[element.id]
  5527. ? selectGroupsForSelectedElements(
  5528. {
  5529. ...this.state,
  5530. selectedElementIds: { [element.id]: true },
  5531. selectedLinearElement: isLinearElement(element)
  5532. ? new LinearElementEditor(element, this.scene)
  5533. : null,
  5534. },
  5535. this.scene.getNonDeletedElements(),
  5536. )
  5537. : this.state),
  5538. showHyperlinkPopup: false,
  5539. },
  5540. () => {
  5541. this.setState({
  5542. contextMenu: { top, left, items: this.getContextMenuItems(type) },
  5543. });
  5544. },
  5545. );
  5546. };
  5547. private maybeDragNewGenericElement = (
  5548. pointerDownState: PointerDownState,
  5549. event: MouseEvent | KeyboardEvent,
  5550. ): void => {
  5551. const draggingElement = this.state.draggingElement;
  5552. const pointerCoords = pointerDownState.lastCoords;
  5553. if (!draggingElement) {
  5554. return;
  5555. }
  5556. if (
  5557. draggingElement.type === "selection" &&
  5558. this.state.activeTool.type !== "eraser"
  5559. ) {
  5560. dragNewElement(
  5561. draggingElement,
  5562. this.state.activeTool.type,
  5563. pointerDownState.origin.x,
  5564. pointerDownState.origin.y,
  5565. pointerCoords.x,
  5566. pointerCoords.y,
  5567. distance(pointerDownState.origin.x, pointerCoords.x),
  5568. distance(pointerDownState.origin.y, pointerCoords.y),
  5569. shouldMaintainAspectRatio(event),
  5570. shouldResizeFromCenter(event),
  5571. );
  5572. } else {
  5573. const [gridX, gridY] = getGridPoint(
  5574. pointerCoords.x,
  5575. pointerCoords.y,
  5576. this.state.gridSize,
  5577. );
  5578. const image =
  5579. isInitializedImageElement(draggingElement) &&
  5580. this.imageCache.get(draggingElement.fileId)?.image;
  5581. const aspectRatio =
  5582. image && !(image instanceof Promise)
  5583. ? image.width / image.height
  5584. : null;
  5585. dragNewElement(
  5586. draggingElement,
  5587. this.state.activeTool.type,
  5588. pointerDownState.originInGrid.x,
  5589. pointerDownState.originInGrid.y,
  5590. gridX,
  5591. gridY,
  5592. distance(pointerDownState.originInGrid.x, gridX),
  5593. distance(pointerDownState.originInGrid.y, gridY),
  5594. isImageElement(draggingElement)
  5595. ? !shouldMaintainAspectRatio(event)
  5596. : shouldMaintainAspectRatio(event),
  5597. shouldResizeFromCenter(event),
  5598. aspectRatio,
  5599. );
  5600. this.maybeSuggestBindingForAll([draggingElement]);
  5601. }
  5602. };
  5603. private maybeHandleResize = (
  5604. pointerDownState: PointerDownState,
  5605. event: MouseEvent | KeyboardEvent,
  5606. ): boolean => {
  5607. const selectedElements = getSelectedElements(
  5608. this.scene.getNonDeletedElements(),
  5609. this.state,
  5610. );
  5611. const transformHandleType = pointerDownState.resize.handleType;
  5612. this.setState({
  5613. // TODO: rename this state field to "isScaling" to distinguish
  5614. // it from the generic "isResizing" which includes scaling and
  5615. // rotating
  5616. isResizing: transformHandleType && transformHandleType !== "rotation",
  5617. isRotating: transformHandleType === "rotation",
  5618. });
  5619. const pointerCoords = pointerDownState.lastCoords;
  5620. const [resizeX, resizeY] = getGridPoint(
  5621. pointerCoords.x - pointerDownState.resize.offset.x,
  5622. pointerCoords.y - pointerDownState.resize.offset.y,
  5623. this.state.gridSize,
  5624. );
  5625. if (
  5626. transformElements(
  5627. pointerDownState,
  5628. transformHandleType,
  5629. selectedElements,
  5630. pointerDownState.resize.arrowDirection,
  5631. shouldRotateWithDiscreteAngle(event),
  5632. shouldResizeFromCenter(event),
  5633. selectedElements.length === 1 && isImageElement(selectedElements[0])
  5634. ? !shouldMaintainAspectRatio(event)
  5635. : shouldMaintainAspectRatio(event),
  5636. resizeX,
  5637. resizeY,
  5638. pointerDownState.resize.center.x,
  5639. pointerDownState.resize.center.y,
  5640. )
  5641. ) {
  5642. this.maybeSuggestBindingForAll(selectedElements);
  5643. return true;
  5644. }
  5645. return false;
  5646. };
  5647. private getContextMenuItems = (
  5648. type: "canvas" | "element",
  5649. ): ContextMenuItems => {
  5650. const options: ContextMenuItems = [];
  5651. options.push(actionCopyAsPng, actionCopyAsSvg);
  5652. // canvas contextMenu
  5653. // -------------------------------------------------------------------------
  5654. if (type === "canvas") {
  5655. if (this.state.viewModeEnabled) {
  5656. return [
  5657. ...options,
  5658. actionToggleGridMode,
  5659. actionToggleZenMode,
  5660. actionToggleViewMode,
  5661. actionToggleStats,
  5662. ];
  5663. }
  5664. return [
  5665. actionPaste,
  5666. CONTEXT_MENU_SEPARATOR,
  5667. actionCopyAsPng,
  5668. actionCopyAsSvg,
  5669. copyText,
  5670. CONTEXT_MENU_SEPARATOR,
  5671. actionSelectAll,
  5672. CONTEXT_MENU_SEPARATOR,
  5673. actionToggleGridMode,
  5674. actionToggleZenMode,
  5675. actionToggleViewMode,
  5676. actionToggleStats,
  5677. ];
  5678. }
  5679. // element contextMenu
  5680. // -------------------------------------------------------------------------
  5681. options.push(copyText);
  5682. if (this.state.viewModeEnabled) {
  5683. return [actionCopy, ...options];
  5684. }
  5685. return [
  5686. actionCut,
  5687. actionCopy,
  5688. actionPaste,
  5689. CONTEXT_MENU_SEPARATOR,
  5690. ...options,
  5691. CONTEXT_MENU_SEPARATOR,
  5692. actionCopyStyles,
  5693. actionPasteStyles,
  5694. CONTEXT_MENU_SEPARATOR,
  5695. actionGroup,
  5696. actionUnbindText,
  5697. actionBindText,
  5698. actionUngroup,
  5699. CONTEXT_MENU_SEPARATOR,
  5700. actionAddToLibrary,
  5701. CONTEXT_MENU_SEPARATOR,
  5702. actionSendBackward,
  5703. actionBringForward,
  5704. actionSendToBack,
  5705. actionBringToFront,
  5706. CONTEXT_MENU_SEPARATOR,
  5707. actionFlipHorizontal,
  5708. actionFlipVertical,
  5709. CONTEXT_MENU_SEPARATOR,
  5710. actionToggleLinearEditor,
  5711. actionLink,
  5712. actionDuplicateSelection,
  5713. actionToggleLock,
  5714. CONTEXT_MENU_SEPARATOR,
  5715. actionDeleteSelected,
  5716. ];
  5717. };
  5718. private handleWheel = withBatchedUpdates((event: WheelEvent) => {
  5719. event.preventDefault();
  5720. if (isPanning) {
  5721. return;
  5722. }
  5723. const { deltaX, deltaY } = event;
  5724. // note that event.ctrlKey is necessary to handle pinch zooming
  5725. if (event.metaKey || event.ctrlKey) {
  5726. const sign = Math.sign(deltaY);
  5727. const MAX_STEP = ZOOM_STEP * 100;
  5728. const absDelta = Math.abs(deltaY);
  5729. let delta = deltaY;
  5730. if (absDelta > MAX_STEP) {
  5731. delta = MAX_STEP * sign;
  5732. }
  5733. let newZoom = this.state.zoom.value - delta / 100;
  5734. // increase zoom steps the more zoomed-in we are (applies to >100% only)
  5735. newZoom +=
  5736. Math.log10(Math.max(1, this.state.zoom.value)) *
  5737. -sign *
  5738. // reduced amplification for small deltas (small movements on a trackpad)
  5739. Math.min(1, absDelta / 20);
  5740. this.setState((state) => ({
  5741. ...getStateForZoom(
  5742. {
  5743. viewportX: cursorX,
  5744. viewportY: cursorY,
  5745. nextZoom: getNormalizedZoom(newZoom),
  5746. },
  5747. state,
  5748. ),
  5749. shouldCacheIgnoreZoom: true,
  5750. }));
  5751. this.resetShouldCacheIgnoreZoomDebounced();
  5752. return;
  5753. }
  5754. // scroll horizontally when shift pressed
  5755. if (event.shiftKey) {
  5756. this.setState(({ zoom, scrollX }) => ({
  5757. // on Mac, shift+wheel tends to result in deltaX
  5758. scrollX: scrollX - (deltaY || deltaX) / zoom.value,
  5759. }));
  5760. return;
  5761. }
  5762. this.setState(({ zoom, scrollX, scrollY }) => ({
  5763. scrollX: scrollX - deltaX / zoom.value,
  5764. scrollY: scrollY - deltaY / zoom.value,
  5765. }));
  5766. });
  5767. private getTextWysiwygSnappedToCenterPosition(
  5768. x: number,
  5769. y: number,
  5770. appState: AppState,
  5771. container?: ExcalidrawTextContainer | null,
  5772. ) {
  5773. if (container) {
  5774. let elementCenterX = container.x + container.width / 2;
  5775. let elementCenterY = container.y + container.height / 2;
  5776. const elementCenter = getContainerCenter(container, appState);
  5777. if (elementCenter) {
  5778. elementCenterX = elementCenter.x;
  5779. elementCenterY = elementCenter.y;
  5780. }
  5781. const distanceToCenter = Math.hypot(
  5782. x - elementCenterX,
  5783. y - elementCenterY,
  5784. );
  5785. const isSnappedToCenter =
  5786. distanceToCenter < TEXT_TO_CENTER_SNAP_THRESHOLD;
  5787. if (isSnappedToCenter) {
  5788. const { x: viewportX, y: viewportY } = sceneCoordsToViewportCoords(
  5789. { sceneX: elementCenterX, sceneY: elementCenterY },
  5790. appState,
  5791. );
  5792. return { viewportX, viewportY, elementCenterX, elementCenterY };
  5793. }
  5794. }
  5795. }
  5796. private savePointer = (x: number, y: number, button: "up" | "down") => {
  5797. if (!x || !y) {
  5798. return;
  5799. }
  5800. const pointer = viewportCoordsToSceneCoords(
  5801. { clientX: x, clientY: y },
  5802. this.state,
  5803. );
  5804. if (isNaN(pointer.x) || isNaN(pointer.y)) {
  5805. // sometimes the pointer goes off screen
  5806. }
  5807. this.props.onPointerUpdate?.({
  5808. pointer,
  5809. button,
  5810. pointersMap: gesture.pointers,
  5811. });
  5812. };
  5813. private resetShouldCacheIgnoreZoomDebounced = debounce(() => {
  5814. if (!this.unmounted) {
  5815. this.setState({ shouldCacheIgnoreZoom: false });
  5816. }
  5817. }, 300);
  5818. private updateDOMRect = (cb?: () => void) => {
  5819. if (this.excalidrawContainerRef?.current) {
  5820. const excalidrawContainer = this.excalidrawContainerRef.current;
  5821. const {
  5822. width,
  5823. height,
  5824. left: offsetLeft,
  5825. top: offsetTop,
  5826. } = excalidrawContainer.getBoundingClientRect();
  5827. const {
  5828. width: currentWidth,
  5829. height: currentHeight,
  5830. offsetTop: currentOffsetTop,
  5831. offsetLeft: currentOffsetLeft,
  5832. } = this.state;
  5833. if (
  5834. width === currentWidth &&
  5835. height === currentHeight &&
  5836. offsetLeft === currentOffsetLeft &&
  5837. offsetTop === currentOffsetTop
  5838. ) {
  5839. if (cb) {
  5840. cb();
  5841. }
  5842. return;
  5843. }
  5844. this.setState(
  5845. {
  5846. width,
  5847. height,
  5848. offsetLeft,
  5849. offsetTop,
  5850. },
  5851. () => {
  5852. cb && cb();
  5853. },
  5854. );
  5855. }
  5856. };
  5857. public refresh = () => {
  5858. this.setState({ ...this.getCanvasOffsets() });
  5859. };
  5860. private getCanvasOffsets(): Pick<AppState, "offsetTop" | "offsetLeft"> {
  5861. if (this.excalidrawContainerRef?.current) {
  5862. const excalidrawContainer = this.excalidrawContainerRef.current;
  5863. const { left, top } = excalidrawContainer.getBoundingClientRect();
  5864. return {
  5865. offsetLeft: left,
  5866. offsetTop: top,
  5867. };
  5868. }
  5869. return {
  5870. offsetLeft: 0,
  5871. offsetTop: 0,
  5872. };
  5873. }
  5874. private async updateLanguage() {
  5875. const currentLang =
  5876. languages.find((lang) => lang.code === this.props.langCode) ||
  5877. defaultLang;
  5878. await setLanguage(currentLang);
  5879. this.setAppState({});
  5880. }
  5881. }
  5882. // -----------------------------------------------------------------------------
  5883. // TEST HOOKS
  5884. // -----------------------------------------------------------------------------
  5885. declare global {
  5886. interface Window {
  5887. h: {
  5888. elements: readonly ExcalidrawElement[];
  5889. state: AppState;
  5890. setState: React.Component<any, AppState>["setState"];
  5891. app: InstanceType<typeof App>;
  5892. history: History;
  5893. };
  5894. }
  5895. }
  5896. if (
  5897. process.env.NODE_ENV === ENV.TEST ||
  5898. process.env.NODE_ENV === ENV.DEVELOPMENT
  5899. ) {
  5900. window.h = window.h || ({} as Window["h"]);
  5901. Object.defineProperties(window.h, {
  5902. elements: {
  5903. configurable: true,
  5904. get() {
  5905. return this.app?.scene.getElementsIncludingDeleted();
  5906. },
  5907. set(elements: ExcalidrawElement[]) {
  5908. return this.app?.scene.replaceAllElements(elements);
  5909. },
  5910. },
  5911. });
  5912. }
  5913. export default App;