App.tsx 173 KB

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