App.tsx 307 KB

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