App.tsx 169 KB

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