App.tsx 189 KB

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