App.tsx 181 KB

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