App.tsx 190 KB

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