App.tsx 178 KB

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