App.tsx 173 KB

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