App.tsx 169 KB

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