App.tsx 178 KB

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