App.tsx 166 KB

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