tiny-whiteboard.es.js 131 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842
  1. var __defProp = Object.defineProperty;
  2. var __defProps = Object.defineProperties;
  3. var __getOwnPropDescs = Object.getOwnPropertyDescriptors;
  4. var __getOwnPropSymbols = Object.getOwnPropertySymbols;
  5. var __hasOwnProp = Object.prototype.hasOwnProperty;
  6. var __propIsEnum = Object.prototype.propertyIsEnumerable;
  7. var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
  8. var __spreadValues = (a, b) => {
  9. for (var prop in b || (b = {}))
  10. if (__hasOwnProp.call(b, prop))
  11. __defNormalProp(a, prop, b[prop]);
  12. if (__getOwnPropSymbols)
  13. for (var prop of __getOwnPropSymbols(b)) {
  14. if (__propIsEnum.call(b, prop))
  15. __defNormalProp(a, prop, b[prop]);
  16. }
  17. return a;
  18. };
  19. var __spreadProps = (a, b) => __defProps(a, __getOwnPropDescs(b));
  20. var __async = (__this, __arguments, generator) => {
  21. return new Promise((resolve, reject) => {
  22. var fulfilled = (value) => {
  23. try {
  24. step(generator.next(value));
  25. } catch (e) {
  26. reject(e);
  27. }
  28. };
  29. var rejected = (value) => {
  30. try {
  31. step(generator.throw(value));
  32. } catch (e) {
  33. reject(e);
  34. }
  35. };
  36. var step = (x) => x.done ? resolve(x.value) : Promise.resolve(x.value).then(fulfilled, rejected);
  37. step((generator = generator.apply(__this, __arguments)).next());
  38. });
  39. };
  40. var eventemitter3 = { exports: {} };
  41. (function(module) {
  42. var has = Object.prototype.hasOwnProperty, prefix = "~";
  43. function Events() {
  44. }
  45. if (Object.create) {
  46. Events.prototype = /* @__PURE__ */ Object.create(null);
  47. if (!new Events().__proto__)
  48. prefix = false;
  49. }
  50. function EE(fn, context, once) {
  51. this.fn = fn;
  52. this.context = context;
  53. this.once = once || false;
  54. }
  55. function addListener(emitter, event, fn, context, once) {
  56. if (typeof fn !== "function") {
  57. throw new TypeError("The listener must be a function");
  58. }
  59. var listener = new EE(fn, context || emitter, once), evt = prefix ? prefix + event : event;
  60. if (!emitter._events[evt])
  61. emitter._events[evt] = listener, emitter._eventsCount++;
  62. else if (!emitter._events[evt].fn)
  63. emitter._events[evt].push(listener);
  64. else
  65. emitter._events[evt] = [emitter._events[evt], listener];
  66. return emitter;
  67. }
  68. function clearEvent(emitter, evt) {
  69. if (--emitter._eventsCount === 0)
  70. emitter._events = new Events();
  71. else
  72. delete emitter._events[evt];
  73. }
  74. function EventEmitter2() {
  75. this._events = new Events();
  76. this._eventsCount = 0;
  77. }
  78. EventEmitter2.prototype.eventNames = function eventNames() {
  79. var names = [], events, name;
  80. if (this._eventsCount === 0)
  81. return names;
  82. for (name in events = this._events) {
  83. if (has.call(events, name))
  84. names.push(prefix ? name.slice(1) : name);
  85. }
  86. if (Object.getOwnPropertySymbols) {
  87. return names.concat(Object.getOwnPropertySymbols(events));
  88. }
  89. return names;
  90. };
  91. EventEmitter2.prototype.listeners = function listeners(event) {
  92. var evt = prefix ? prefix + event : event, handlers = this._events[evt];
  93. if (!handlers)
  94. return [];
  95. if (handlers.fn)
  96. return [handlers.fn];
  97. for (var i = 0, l = handlers.length, ee = new Array(l); i < l; i++) {
  98. ee[i] = handlers[i].fn;
  99. }
  100. return ee;
  101. };
  102. EventEmitter2.prototype.listenerCount = function listenerCount(event) {
  103. var evt = prefix ? prefix + event : event, listeners = this._events[evt];
  104. if (!listeners)
  105. return 0;
  106. if (listeners.fn)
  107. return 1;
  108. return listeners.length;
  109. };
  110. EventEmitter2.prototype.emit = function emit(event, a1, a2, a3, a4, a5) {
  111. var evt = prefix ? prefix + event : event;
  112. if (!this._events[evt])
  113. return false;
  114. var listeners = this._events[evt], len = arguments.length, args, i;
  115. if (listeners.fn) {
  116. if (listeners.once)
  117. this.removeListener(event, listeners.fn, void 0, true);
  118. switch (len) {
  119. case 1:
  120. return listeners.fn.call(listeners.context), true;
  121. case 2:
  122. return listeners.fn.call(listeners.context, a1), true;
  123. case 3:
  124. return listeners.fn.call(listeners.context, a1, a2), true;
  125. case 4:
  126. return listeners.fn.call(listeners.context, a1, a2, a3), true;
  127. case 5:
  128. return listeners.fn.call(listeners.context, a1, a2, a3, a4), true;
  129. case 6:
  130. return listeners.fn.call(listeners.context, a1, a2, a3, a4, a5), true;
  131. }
  132. for (i = 1, args = new Array(len - 1); i < len; i++) {
  133. args[i - 1] = arguments[i];
  134. }
  135. listeners.fn.apply(listeners.context, args);
  136. } else {
  137. var length = listeners.length, j;
  138. for (i = 0; i < length; i++) {
  139. if (listeners[i].once)
  140. this.removeListener(event, listeners[i].fn, void 0, true);
  141. switch (len) {
  142. case 1:
  143. listeners[i].fn.call(listeners[i].context);
  144. break;
  145. case 2:
  146. listeners[i].fn.call(listeners[i].context, a1);
  147. break;
  148. case 3:
  149. listeners[i].fn.call(listeners[i].context, a1, a2);
  150. break;
  151. case 4:
  152. listeners[i].fn.call(listeners[i].context, a1, a2, a3);
  153. break;
  154. default:
  155. if (!args)
  156. for (j = 1, args = new Array(len - 1); j < len; j++) {
  157. args[j - 1] = arguments[j];
  158. }
  159. listeners[i].fn.apply(listeners[i].context, args);
  160. }
  161. }
  162. }
  163. return true;
  164. };
  165. EventEmitter2.prototype.on = function on(event, fn, context) {
  166. return addListener(this, event, fn, context, false);
  167. };
  168. EventEmitter2.prototype.once = function once(event, fn, context) {
  169. return addListener(this, event, fn, context, true);
  170. };
  171. EventEmitter2.prototype.removeListener = function removeListener(event, fn, context, once) {
  172. var evt = prefix ? prefix + event : event;
  173. if (!this._events[evt])
  174. return this;
  175. if (!fn) {
  176. clearEvent(this, evt);
  177. return this;
  178. }
  179. var listeners = this._events[evt];
  180. if (listeners.fn) {
  181. if (listeners.fn === fn && (!once || listeners.once) && (!context || listeners.context === context)) {
  182. clearEvent(this, evt);
  183. }
  184. } else {
  185. for (var i = 0, events = [], length = listeners.length; i < length; i++) {
  186. if (listeners[i].fn !== fn || once && !listeners[i].once || context && listeners[i].context !== context) {
  187. events.push(listeners[i]);
  188. }
  189. }
  190. if (events.length)
  191. this._events[evt] = events.length === 1 ? events[0] : events;
  192. else
  193. clearEvent(this, evt);
  194. }
  195. return this;
  196. };
  197. EventEmitter2.prototype.removeAllListeners = function removeAllListeners(event) {
  198. var evt;
  199. if (event) {
  200. evt = prefix ? prefix + event : event;
  201. if (this._events[evt])
  202. clearEvent(this, evt);
  203. } else {
  204. this._events = new Events();
  205. this._eventsCount = 0;
  206. }
  207. return this;
  208. };
  209. EventEmitter2.prototype.off = EventEmitter2.prototype.removeListener;
  210. EventEmitter2.prototype.addListener = EventEmitter2.prototype.on;
  211. EventEmitter2.prefixed = prefix;
  212. EventEmitter2.EventEmitter = EventEmitter2;
  213. {
  214. module.exports = EventEmitter2;
  215. }
  216. })(eventemitter3);
  217. var EventEmitter = eventemitter3.exports;
  218. const createCanvas = (width, height, opt = { noStyle: false, noTranslate: false, className: "" }) => {
  219. let canvas = document.createElement("canvas");
  220. if (!opt.noStyle) {
  221. canvas.style.cssText = `
  222. position: absolute;
  223. left: 0;
  224. top: 0;
  225. `;
  226. }
  227. if (opt.className) {
  228. canvas.className = opt.className;
  229. }
  230. let ctx = canvas.getContext("2d");
  231. canvas.width = width;
  232. canvas.height = height;
  233. if (!opt.noTranslate) {
  234. ctx.translate(canvas.width / 2, canvas.height / 2);
  235. }
  236. return {
  237. canvas,
  238. ctx
  239. };
  240. };
  241. const getTowPointDistance = (x1, y1, x2, y2) => {
  242. return Math.sqrt(Math.pow(x1 - x2, 2) + Math.pow(y1 - y2, 2));
  243. };
  244. const getPointToLineDistance = (x, y, x1, y1, x2, y2) => {
  245. if (x1 === x2) {
  246. return Math.abs(x - x1);
  247. } else {
  248. let B = 1;
  249. let A, C;
  250. A = (y1 - y2) / (x2 - x1);
  251. C = 0 - B * y1 - A * x1;
  252. return Math.abs((A * x + B * y + C) / Math.sqrt(A * A + B * B));
  253. }
  254. };
  255. const checkIsAtSegment = (x, y, x1, y1, x2, y2, dis = 10) => {
  256. if (getPointToLineDistance(x, y, x1, y1, x2, y2) > dis) {
  257. return false;
  258. }
  259. let dis1 = getTowPointDistance(x, y, x1, y1);
  260. let dis2 = getTowPointDistance(x, y, x2, y2);
  261. let dis3 = getTowPointDistance(x1, y1, x2, y2);
  262. let max = Math.sqrt(dis * dis + dis3 * dis3);
  263. if (dis1 <= max && dis2 <= max) {
  264. return true;
  265. }
  266. return false;
  267. };
  268. const radToDeg = (rad) => {
  269. return rad * (180 / Math.PI);
  270. };
  271. const degToRad = (deg) => {
  272. return deg * (Math.PI / 180);
  273. };
  274. const getTowPointRotate = (cx, cy, tx, ty, fx, fy) => {
  275. return radToDeg(Math.atan2(ty - cy, tx - cx) - Math.atan2(fy - cy, fx - cx));
  276. };
  277. const getRotatedPoint = (x, y, cx, cy, rotate) => {
  278. let deg = radToDeg(Math.atan2(y - cy, x - cx));
  279. let del = deg + rotate;
  280. let dis = getTowPointDistance(x, y, cx, cy);
  281. return {
  282. x: Math.cos(degToRad(del)) * dis + cx,
  283. y: Math.sin(degToRad(del)) * dis + cy
  284. };
  285. };
  286. const getElementCenterPoint = (element) => {
  287. let { x, y, width, height } = element;
  288. return {
  289. x: x + width / 2,
  290. y: y + height / 2
  291. };
  292. };
  293. const transformPointReverseRotate = (x, y, cx, cy, rotate) => {
  294. if (rotate !== 0) {
  295. let rp = getRotatedPoint(x, y, cx, cy, -rotate);
  296. x = rp.x;
  297. y = rp.y;
  298. }
  299. return {
  300. x,
  301. y
  302. };
  303. };
  304. const transformPointOnElement = (x, y, element) => {
  305. let center = getElementCenterPoint(element);
  306. return transformPointReverseRotate(x, y, center.x, center.y, element.rotate);
  307. };
  308. const getElementCornerPoint = (element, dir) => {
  309. let { x, y, width, height } = element;
  310. switch (dir) {
  311. case "topLeft":
  312. return {
  313. x,
  314. y
  315. };
  316. case "topRight":
  317. return {
  318. x: x + width,
  319. y
  320. };
  321. case "bottomRight":
  322. return {
  323. x: x + width,
  324. y: y + height
  325. };
  326. case "bottomLeft":
  327. return {
  328. x,
  329. y: y + height
  330. };
  331. }
  332. };
  333. const getElementRotatedCornerPoint = (element, dir) => {
  334. let center = getElementCenterPoint(element);
  335. let dirPos = getElementCornerPoint(element, dir);
  336. return getRotatedPoint(dirPos.x, dirPos.y, center.x, center.y, element.rotate);
  337. };
  338. const checkPointIsInRectangle = (x, y, rx, ry, rw, rh) => {
  339. if (typeof rx === "object") {
  340. let element = rx;
  341. rx = element.x;
  342. ry = element.y;
  343. rw = element.width;
  344. rh = element.height;
  345. }
  346. return x >= rx && x <= rx + rw && y >= ry && y <= ry + rh;
  347. };
  348. const getBoundingRect = (pointArr = [], returnCorners = false) => {
  349. let minX = Infinity;
  350. let maxX = -Infinity;
  351. let minY = Infinity;
  352. let maxY = -Infinity;
  353. pointArr.forEach((point) => {
  354. let [x2, y2] = point;
  355. if (x2 < minX) {
  356. minX = x2;
  357. }
  358. if (x2 > maxX) {
  359. maxX = x2;
  360. }
  361. if (y2 < minY) {
  362. minY = y2;
  363. }
  364. if (y2 > maxY) {
  365. maxY = y2;
  366. }
  367. });
  368. let x = minX;
  369. let y = minY;
  370. let width = maxX - minX;
  371. let height = maxY - minY;
  372. if (returnCorners) {
  373. return [
  374. {
  375. x,
  376. y
  377. },
  378. {
  379. x: x + width,
  380. y
  381. },
  382. {
  383. x: x + width,
  384. y: y + height
  385. },
  386. {
  387. x,
  388. y: y + height
  389. }
  390. ];
  391. }
  392. return {
  393. x,
  394. y,
  395. width,
  396. height
  397. };
  398. };
  399. const deepCopy = (obj) => {
  400. return JSON.parse(JSON.stringify(obj));
  401. };
  402. const getFontString = (fontSize, fontFamily) => {
  403. return `${fontSize}px ${fontFamily}`;
  404. };
  405. const splitTextLines = (text) => {
  406. return text.replace(/\r\n?/g, "\n").split("\n");
  407. };
  408. let textCheckEl = null;
  409. const getTextActWidth = (text, style) => {
  410. if (!textCheckEl) {
  411. textCheckEl = document.createElement("div");
  412. textCheckEl.style.position = "fixed";
  413. textCheckEl.style.left = "-99999px";
  414. document.body.appendChild(textCheckEl);
  415. }
  416. let { fontSize, fontFamily } = style;
  417. textCheckEl.innerText = text;
  418. textCheckEl.style.fontSize = fontSize + "px";
  419. textCheckEl.style.fontFamily = fontFamily;
  420. let { width } = textCheckEl.getBoundingClientRect();
  421. return width;
  422. };
  423. const getMaxFontSizeInWidth = (text, width, style) => {
  424. let fontSize = 12;
  425. while (getTextActWidth(text, __spreadProps(__spreadValues({}, style), {
  426. fontSize: fontSize + 1
  427. })) < width) {
  428. fontSize++;
  429. }
  430. return fontSize;
  431. };
  432. const getWrapTextActWidth = (element) => {
  433. let { text } = element;
  434. let textArr = splitTextLines(text);
  435. let maxWidth = -Infinity;
  436. textArr.forEach((textRow) => {
  437. let width = getTextActWidth(textRow, element.style);
  438. if (width > maxWidth) {
  439. maxWidth = width;
  440. }
  441. });
  442. return maxWidth;
  443. };
  444. const getWrapTextMaxRowTextNumber = (text) => {
  445. let textArr = splitTextLines(text);
  446. let maxNumber = -Infinity;
  447. textArr.forEach((textRow) => {
  448. if (textRow.length > maxNumber) {
  449. maxNumber = textRow.length;
  450. }
  451. });
  452. return maxNumber;
  453. };
  454. const getTextElementSize = (element) => {
  455. let { text, style } = element;
  456. let width = getWrapTextActWidth(element);
  457. const lines = Math.max(splitTextLines(text).length, 1);
  458. let lineHeight = style.fontSize * style.lineHeightRatio;
  459. let height = lines * lineHeight;
  460. return {
  461. width,
  462. height
  463. };
  464. };
  465. const throttle = (fn, ctx, time = 100) => {
  466. let timer = null;
  467. return (...args) => {
  468. if (timer) {
  469. return;
  470. }
  471. timer = setTimeout(() => {
  472. fn.call(ctx, ...args);
  473. timer = null;
  474. }, time);
  475. };
  476. };
  477. const computedLineWidthBySpeed = (speed, lastLineWidth, baseLineWidth = 2) => {
  478. let lineWidth = 0;
  479. let maxLineWidth = baseLineWidth;
  480. let maxSpeed = 10;
  481. let minSpeed = 0.5;
  482. if (speed >= maxSpeed) {
  483. lineWidth = baseLineWidth;
  484. } else if (speed <= minSpeed) {
  485. lineWidth = maxLineWidth + 1;
  486. } else {
  487. lineWidth = maxLineWidth - (speed - minSpeed) / (maxSpeed - minSpeed) * maxLineWidth;
  488. }
  489. if (lastLineWidth === -1) {
  490. lastLineWidth = maxLineWidth;
  491. }
  492. return lineWidth * (1 / 2) + lastLineWidth * (1 / 2);
  493. };
  494. const downloadFile = (file, fileName) => {
  495. let a = document.createElement("a");
  496. a.href = file;
  497. a.download = fileName;
  498. a.click();
  499. };
  500. const getElementCorners = (element) => {
  501. let topLeft = getElementRotatedCornerPoint(element, "topLeft");
  502. let topRight = getElementRotatedCornerPoint(element, "topRight");
  503. let bottomLeft = getElementRotatedCornerPoint(element, "bottomLeft");
  504. let bottomRight = getElementRotatedCornerPoint(element, "bottomRight");
  505. return [topLeft, topRight, bottomLeft, bottomRight];
  506. };
  507. const getMultiElementRectInfo = (elementList = []) => {
  508. if (elementList.length <= 0) {
  509. return {
  510. minx: 0,
  511. maxx: 0,
  512. miny: 0,
  513. maxy: 0
  514. };
  515. }
  516. let minx = Infinity;
  517. let maxx = -Infinity;
  518. let miny = Infinity;
  519. let maxy = -Infinity;
  520. elementList.forEach((element) => {
  521. let pointList = element.getEndpointList();
  522. pointList.forEach(({ x, y }) => {
  523. if (x < minx) {
  524. minx = x;
  525. }
  526. if (x > maxx) {
  527. maxx = x;
  528. }
  529. if (y < miny) {
  530. miny = y;
  531. }
  532. if (y > maxy) {
  533. maxy = y;
  534. }
  535. });
  536. });
  537. return {
  538. minx,
  539. maxx,
  540. miny,
  541. maxy
  542. };
  543. };
  544. const createImageObj = (url) => {
  545. return new Promise((resolve) => {
  546. let img = new Image();
  547. img.setAttribute("crossOrigin", "anonymous");
  548. img.onload = () => {
  549. resolve(img);
  550. };
  551. img.onerror = () => {
  552. resolve(null);
  553. };
  554. img.src = url;
  555. });
  556. };
  557. let nodeKeyIndex = 0;
  558. const createNodeKey = () => {
  559. return nodeKeyIndex++;
  560. };
  561. var utils = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
  562. __proto__: null,
  563. createCanvas,
  564. getTowPointDistance,
  565. getPointToLineDistance,
  566. checkIsAtSegment,
  567. radToDeg,
  568. degToRad,
  569. getTowPointRotate,
  570. getRotatedPoint,
  571. getElementCenterPoint,
  572. transformPointReverseRotate,
  573. transformPointOnElement,
  574. getElementCornerPoint,
  575. getElementRotatedCornerPoint,
  576. checkPointIsInRectangle,
  577. getBoundingRect,
  578. deepCopy,
  579. getFontString,
  580. splitTextLines,
  581. getTextActWidth,
  582. getMaxFontSizeInWidth,
  583. getWrapTextActWidth,
  584. getWrapTextMaxRowTextNumber,
  585. getTextElementSize,
  586. throttle,
  587. computedLineWidthBySpeed,
  588. downloadFile,
  589. getElementCorners,
  590. getMultiElementRectInfo,
  591. createImageObj,
  592. createNodeKey
  593. }, Symbol.toStringTag, { value: "Module" }));
  594. const CORNERS = {
  595. TOP_LEFT: "topLeft",
  596. TOP_RIGHT: "topRight",
  597. BOTTOM_RIGHT: "bottomRight",
  598. BOTTOM_LEFT: "bottomLeft"
  599. };
  600. const DRAG_ELEMENT_PARTS = {
  601. BODY: "body",
  602. ROTATE: "rotate",
  603. TOP_LEFT_BTN: "topLeftBtn",
  604. TOP_RIGHT_BTN: "topRightBtn",
  605. BOTTOM_RIGHT_BTN: "bottomRightBtn",
  606. BOTTOM_LEFT_BTN: "bottomLeftBtn"
  607. };
  608. const HIT_DISTANCE = 10;
  609. const checkIsAtMultiSegment = (segments, rp) => {
  610. let res = false;
  611. segments.forEach((seg) => {
  612. if (res)
  613. return;
  614. if (checkIsAtSegment(rp.x, rp.y, ...seg, HIT_DISTANCE)) {
  615. res = true;
  616. }
  617. });
  618. return res;
  619. };
  620. const checkIsAtRectangleEdge = (element, rp) => {
  621. let { x, y, width, height } = element;
  622. let segments = [
  623. [x, y, x + width, y],
  624. [x + width, y, x + width, y + height],
  625. [x + width, y + height, x, y + height],
  626. [x, y + height, x, y]
  627. ];
  628. return checkIsAtMultiSegment(segments, rp) ? element : null;
  629. };
  630. const checkIsAtRectangleInner = (element, rp) => {
  631. return checkPointIsInRectangle(rp.x, rp.y, element) ? element : null;
  632. };
  633. const getCircleRadius = (width, height) => {
  634. return Math.min(Math.abs(width), Math.abs(height)) / 2;
  635. };
  636. const checkIsAtCircleEdge = (element, rp) => {
  637. let { width, height, x, y } = element;
  638. let radius = getCircleRadius(width, height);
  639. let dis = getTowPointDistance(rp.x, rp.y, x + radius, y + radius);
  640. let onCircle = dis >= radius - HIT_DISTANCE && dis <= radius + HIT_DISTANCE;
  641. return onCircle ? element : null;
  642. };
  643. const checkIsAtLineEdge = (element, rp) => {
  644. let segments = [];
  645. let len = element.pointArr.length;
  646. let arr = element.pointArr;
  647. for (let i = 0; i < len - 1; i++) {
  648. segments.push([...arr[i], ...arr[i + 1]]);
  649. }
  650. return checkIsAtMultiSegment(segments, rp) ? element : null;
  651. };
  652. const checkIsAtFreedrawLineEdge = (element, rp) => {
  653. let res = null;
  654. element.pointArr.forEach((point) => {
  655. if (res)
  656. return;
  657. let dis = getTowPointDistance(rp.x, rp.y, point[0], point[1]);
  658. if (dis <= HIT_DISTANCE) {
  659. res = element;
  660. }
  661. });
  662. return res;
  663. };
  664. const checkIsAtDiamondEdge = (element, rp) => {
  665. let { x, y, width, height } = element;
  666. let segments = [
  667. [x + width / 2, y, x + width, y + height / 2],
  668. [x + width, y + height / 2, x + width / 2, y + height],
  669. [x + width / 2, y + height, x, y + height / 2],
  670. [x, y + height / 2, x + width / 2, y]
  671. ];
  672. return checkIsAtMultiSegment(segments, rp) ? element : null;
  673. };
  674. const checkIsAtTriangleEdge = (element, rp) => {
  675. let { x, y, width, height } = element;
  676. let segments = [
  677. [x + width / 2, y, x + width, y + height],
  678. [x + width, y + height, x, y + height],
  679. [x, y + height, x + width / 2, y]
  680. ];
  681. return checkIsAtMultiSegment(segments, rp) ? element : null;
  682. };
  683. const checkIsAtArrowEdge = (element, rp) => {
  684. let pointArr = element.pointArr;
  685. let x = pointArr[0][0];
  686. let y = pointArr[0][1];
  687. let tx = pointArr[pointArr.length - 1][0];
  688. let ty = pointArr[pointArr.length - 1][1];
  689. let segments = [[x, y, tx, ty]];
  690. return checkIsAtMultiSegment(segments, rp) ? element : null;
  691. };
  692. var checkHit = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
  693. __proto__: null,
  694. checkIsAtMultiSegment,
  695. checkIsAtRectangleEdge,
  696. checkIsAtRectangleInner,
  697. getCircleRadius,
  698. checkIsAtCircleEdge,
  699. checkIsAtLineEdge,
  700. checkIsAtFreedrawLineEdge,
  701. checkIsAtDiamondEdge,
  702. checkIsAtTriangleEdge,
  703. checkIsAtArrowEdge
  704. }, Symbol.toStringTag, { value: "Module" }));
  705. const drawWrap = (ctx, fn, fill = false) => {
  706. ctx.beginPath();
  707. fn();
  708. ctx.stroke();
  709. if (fill) {
  710. ctx.fill();
  711. }
  712. };
  713. const drawRect = (ctx, x, y, width, height, fill = false) => {
  714. drawWrap(ctx, () => {
  715. ctx.rect(x, y, width, height);
  716. if (fill) {
  717. ctx.fillRect(x, y, width, height);
  718. }
  719. });
  720. };
  721. const drawDiamond = (ctx, x, y, width, height, fill = false) => {
  722. drawWrap(
  723. ctx,
  724. () => {
  725. ctx.moveTo(x + width / 2, y);
  726. ctx.lineTo(x + width, y + height / 2);
  727. ctx.lineTo(x + width / 2, y + height);
  728. ctx.lineTo(x, y + height / 2);
  729. ctx.closePath();
  730. },
  731. fill
  732. );
  733. };
  734. const drawTriangle = (ctx, x, y, width, height, fill = false) => {
  735. drawWrap(
  736. ctx,
  737. () => {
  738. ctx.moveTo(x + width / 2, y);
  739. ctx.lineTo(x + width, y + height);
  740. ctx.lineTo(x, y + height);
  741. ctx.closePath();
  742. },
  743. fill
  744. );
  745. };
  746. const drawCircle = (ctx, x, y, r, fill = false) => {
  747. drawWrap(
  748. ctx,
  749. () => {
  750. ctx.arc(x, y, r, 0, 2 * Math.PI);
  751. },
  752. fill
  753. );
  754. };
  755. const drawLine = (ctx, points) => {
  756. drawWrap(ctx, () => {
  757. let first = true;
  758. points.forEach((point) => {
  759. if (first) {
  760. first = false;
  761. ctx.moveTo(point[0], point[1]);
  762. } else {
  763. ctx.lineTo(point[0], point[1]);
  764. }
  765. });
  766. });
  767. };
  768. const drawArrow = (ctx, pointArr) => {
  769. let x = pointArr[0][0];
  770. let y = pointArr[0][1];
  771. let tx = pointArr[pointArr.length - 1][0];
  772. let ty = pointArr[pointArr.length - 1][1];
  773. drawWrap(
  774. ctx,
  775. () => {
  776. ctx.moveTo(x, y);
  777. ctx.lineTo(tx, ty);
  778. },
  779. true
  780. );
  781. let l = 30;
  782. let deg = 30;
  783. let lineDeg = radToDeg(Math.atan2(ty - y, tx - x));
  784. drawWrap(
  785. ctx,
  786. () => {
  787. let plusDeg = deg - lineDeg;
  788. let _x = tx - l * Math.cos(degToRad(plusDeg));
  789. let _y = ty + l * Math.sin(degToRad(plusDeg));
  790. ctx.moveTo(_x, _y);
  791. ctx.lineTo(tx, ty);
  792. },
  793. true
  794. );
  795. drawWrap(ctx, () => {
  796. let plusDeg = 90 - lineDeg - deg;
  797. let _x = tx - l * Math.sin(degToRad(plusDeg));
  798. let _y = ty - l * Math.cos(degToRad(plusDeg));
  799. ctx.moveTo(_x, _y);
  800. ctx.lineTo(tx, ty);
  801. });
  802. };
  803. const transformFreeLinePoint = (point, opt) => {
  804. let { x, y } = opt.app.coordinate.transform(point[0], point[1]);
  805. return [x - opt.cx, y - opt.cy, ...point.slice(2)];
  806. };
  807. const drawFreeLine = (ctx, points, opt) => {
  808. for (let i = 0; i < points.length - 1; i++) {
  809. drawWrap(
  810. ctx,
  811. () => {
  812. let point = transformFreeLinePoint(points[i], opt);
  813. let nextPoint = transformFreeLinePoint(points[i + 1], opt);
  814. drawLineSegment(
  815. ctx,
  816. point[0],
  817. point[1],
  818. nextPoint[0],
  819. nextPoint[1],
  820. nextPoint[2]
  821. );
  822. },
  823. true
  824. );
  825. }
  826. };
  827. const drawLineSegment = (ctx, mx, my, tx, ty, lineWidth = 0) => {
  828. drawWrap(ctx, () => {
  829. if (lineWidth > 0) {
  830. ctx.lineWidth = lineWidth;
  831. }
  832. ctx.moveTo(mx, my);
  833. ctx.lineTo(tx, ty);
  834. ctx.lineCap = "round";
  835. ctx.lineJoin = "round";
  836. });
  837. };
  838. const drawText = (ctx, textObj, x, y, width, height) => {
  839. let { text, style } = textObj;
  840. let lineHeight = style.fontSize * style.lineHeightRatio;
  841. drawWrap(ctx, () => {
  842. ctx.font = getFontString(style.fontSize, style.fontFamily);
  843. ctx.textBaseline = "middle";
  844. let textArr = splitTextLines(text);
  845. textArr.forEach((textRow, index) => {
  846. ctx.fillText(textRow, x, y + (index * lineHeight + lineHeight / 2));
  847. });
  848. });
  849. };
  850. const drawImage = (ctx, element, x, y, width, height) => {
  851. drawWrap(ctx, () => {
  852. let ratio = width / height;
  853. let showWidth = 0;
  854. let showHeight = 0;
  855. if (ratio > element.ratio) {
  856. showHeight = height;
  857. showWidth = element.ratio * height;
  858. } else {
  859. showWidth = width;
  860. showHeight = width / element.ratio;
  861. }
  862. ctx.drawImage(element.imageObj, x, y, showWidth, showHeight);
  863. });
  864. };
  865. var draw = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
  866. __proto__: null,
  867. drawWrap,
  868. drawRect,
  869. drawDiamond,
  870. drawTriangle,
  871. drawCircle,
  872. drawLine,
  873. drawArrow,
  874. drawFreeLine,
  875. drawLineSegment,
  876. drawText,
  877. drawImage
  878. }, Symbol.toStringTag, { value: "Module" }));
  879. class Coordinate {
  880. constructor(app) {
  881. this.app = app;
  882. }
  883. addScrollY(y) {
  884. return y + this.app.state.scrollY;
  885. }
  886. addScrollX(x) {
  887. return x + this.app.state.scrollX;
  888. }
  889. subScrollY(y) {
  890. return y - this.app.state.scrollY;
  891. }
  892. subScrollX(x) {
  893. return x - this.app.state.scrollX;
  894. }
  895. transformToCanvasCoordinate(x, y) {
  896. x -= this.app.width / 2;
  897. y -= this.app.height / 2;
  898. return {
  899. x,
  900. y
  901. };
  902. }
  903. transformToScreenCoordinate(x, y) {
  904. x += this.app.width / 2;
  905. y += this.app.height / 2;
  906. return {
  907. x,
  908. y
  909. };
  910. }
  911. transform(x, y) {
  912. let t = this.transformToCanvasCoordinate(x, y);
  913. return {
  914. x: this.subScrollX(t.x),
  915. y: this.subScrollY(t.y)
  916. };
  917. }
  918. windowToContainer(x, y) {
  919. return {
  920. x: x - this.app.left,
  921. y: y - this.app.top
  922. };
  923. }
  924. containerToWindow(x, y) {
  925. return {
  926. x: x + this.app.left,
  927. y: y + this.app.top
  928. };
  929. }
  930. scale(x, y) {
  931. let { state } = this.app;
  932. let wp = this.transformToCanvasCoordinate(x, y);
  933. let sp = this.transformToScreenCoordinate(
  934. wp.x * state.scale,
  935. wp.y * state.scale
  936. );
  937. return {
  938. x: sp.x,
  939. y: sp.y
  940. };
  941. }
  942. reverseScale(x, y) {
  943. let { state } = this.app;
  944. let tp = this.transformToCanvasCoordinate(x, y);
  945. let sp = this.transformToScreenCoordinate(
  946. tp.x / state.scale,
  947. tp.y / state.scale
  948. );
  949. return {
  950. x: sp.x,
  951. y: sp.y
  952. };
  953. }
  954. gridAdsorbent(x, y) {
  955. let { gridConfig, showGrid } = this.app.state;
  956. if (!showGrid) {
  957. return {
  958. x,
  959. y
  960. };
  961. }
  962. let gridSize = gridConfig.size;
  963. return {
  964. x: x - x % gridSize,
  965. y: y - y % gridSize
  966. };
  967. }
  968. }
  969. class Event extends EventEmitter {
  970. constructor(app) {
  971. super();
  972. this.app = app;
  973. this.coordinate = app.coordinate;
  974. this.isMousedown = false;
  975. this.mousedownPos = {
  976. x: 0,
  977. y: 0,
  978. unGridClientX: 0,
  979. unGridClientY: 0,
  980. originClientX: 0,
  981. originClientY: 0
  982. };
  983. this.mouseOffset = {
  984. x: 0,
  985. y: 0,
  986. originX: 0,
  987. originY: 0
  988. };
  989. this.lastMousePos = {
  990. x: 0,
  991. y: 0
  992. };
  993. this.mouseDistance = 0;
  994. this.lastMouseTime = Date.now();
  995. this.mouseDuration = 0;
  996. this.mouseSpeed = 0;
  997. this.onMousedown = this.onMousedown.bind(this);
  998. this.onMousemove = this.onMousemove.bind(this);
  999. this.onMouseup = this.onMouseup.bind(this);
  1000. this.onDblclick = this.onDblclick.bind(this);
  1001. this.onMousewheel = this.onMousewheel.bind(this);
  1002. this.onKeydown = this.onKeydown.bind(this);
  1003. this.onKeyup = this.onKeyup.bind(this);
  1004. this.onContextmenu = this.onContextmenu.bind(this);
  1005. this.bindEvent();
  1006. }
  1007. bindEvent() {
  1008. this.app.container.addEventListener("mousedown", this.onMousedown);
  1009. this.app.container.addEventListener("mousemove", this.onMousemove);
  1010. this.app.container.addEventListener("mouseup", this.onMouseup);
  1011. this.app.container.addEventListener("dblclick", this.onDblclick);
  1012. this.app.container.addEventListener("mousewheel", this.onMousewheel);
  1013. this.app.container.addEventListener("contextmenu", this.onContextmenu);
  1014. window.addEventListener("keydown", this.onKeydown);
  1015. window.addEventListener("keyup", this.onKeyup);
  1016. }
  1017. unbindEvent() {
  1018. this.app.container.removeEventListener("mousedown", this.onMousedown);
  1019. this.app.container.removeEventListener("mousemove", this.onMousemove);
  1020. this.app.container.removeEventListener("mouseup", this.onMouseup);
  1021. this.app.container.removeEventListener("dblclick", this.onDblclick);
  1022. this.app.container.removeEventListener("mousewheel", this.onMousewheel);
  1023. this.app.container.removeEventListener("contextmenu", this.onContextmenu);
  1024. window.removeEventListener("keydown", this.onKeydown);
  1025. window.removeEventListener("keyup", this.onKeyup);
  1026. }
  1027. transformEvent(e) {
  1028. let { coordinate } = this.app;
  1029. let wp = coordinate.windowToContainer(e.clientX, e.clientY);
  1030. let { x, y } = coordinate.reverseScale(wp.x, wp.y);
  1031. x = coordinate.addScrollX(x);
  1032. y = coordinate.addScrollY(y);
  1033. let unGridClientX = x;
  1034. let unGridClientY = y;
  1035. let gp = coordinate.gridAdsorbent(x, y);
  1036. let newEvent = {
  1037. originEvent: e,
  1038. unGridClientX,
  1039. unGridClientY,
  1040. clientX: gp.x,
  1041. clientY: gp.y
  1042. };
  1043. return newEvent;
  1044. }
  1045. onMousedown(e) {
  1046. e = this.transformEvent(e);
  1047. this.isMousedown = true;
  1048. this.mousedownPos.x = e.clientX;
  1049. this.mousedownPos.y = e.clientY;
  1050. this.mousedownPos.unGridClientX = e.unGridClientX;
  1051. this.mousedownPos.unGridClientY = e.unGridClientY;
  1052. this.mousedownPos.originClientX = e.originEvent.clientX;
  1053. this.mousedownPos.originClientY = e.originEvent.clientY;
  1054. this.emit("mousedown", e, this);
  1055. }
  1056. onMousemove(e) {
  1057. e = this.transformEvent(e);
  1058. let x = e.clientX;
  1059. let y = e.clientY;
  1060. if (this.isMousedown) {
  1061. this.mouseOffset.x = x - this.mousedownPos.x;
  1062. this.mouseOffset.y = y - this.mousedownPos.y;
  1063. this.mouseOffset.originX = e.originEvent.clientX - this.mousedownPos.originClientX;
  1064. this.mouseOffset.originY = e.originEvent.clientY - this.mousedownPos.originClientY;
  1065. }
  1066. let curTime = Date.now();
  1067. this.mouseDuration = curTime - this.lastMouseTime;
  1068. this.mouseDistance = getTowPointDistance(
  1069. x,
  1070. y,
  1071. this.lastMousePos.x,
  1072. this.lastMousePos.y
  1073. );
  1074. this.mouseSpeed = this.mouseDistance / this.mouseDuration;
  1075. this.emit("mousemove", e, this);
  1076. this.lastMouseTime = curTime;
  1077. this.lastMousePos.x = x;
  1078. this.lastMousePos.y = y;
  1079. }
  1080. onMouseup(e) {
  1081. e = this.transformEvent(e);
  1082. this.isMousedown = false;
  1083. this.mousedownPos.x = 0;
  1084. this.mousedownPos.y = 0;
  1085. this.emit("mouseup", e, this);
  1086. }
  1087. onDblclick(e) {
  1088. e = this.transformEvent(e);
  1089. this.emit("dblclick", e, this);
  1090. }
  1091. onMousewheel(e) {
  1092. e = this.transformEvent(e);
  1093. this.emit("mousewheel", e.originEvent.wheelDelta < 0 ? "down" : "up");
  1094. }
  1095. onContextmenu(e) {
  1096. e.stopPropagation();
  1097. e.preventDefault();
  1098. e = this.transformEvent(e);
  1099. this.emit("contextmenu", e, this);
  1100. }
  1101. onKeydown(e) {
  1102. this.emit("keydown", e, this);
  1103. }
  1104. onKeyup(e) {
  1105. this.emit("keyup", e, this);
  1106. }
  1107. }
  1108. class BaseElement extends EventEmitter {
  1109. constructor(opts = {}, app) {
  1110. super();
  1111. this.app = app;
  1112. this.groupId = opts.groupId || "";
  1113. this.type = opts.type || "";
  1114. this.key = createNodeKey();
  1115. this.isCreating = true;
  1116. this.isActive = true;
  1117. this.isSelected = false;
  1118. this.startX = 0;
  1119. this.startY = 0;
  1120. this.x = opts.x || 0;
  1121. this.y = opts.y || 0;
  1122. this.width = opts.width || 0;
  1123. this.height = opts.height || 0;
  1124. this.startRotate = 0;
  1125. this.rotate = opts.rotate || 0;
  1126. this.noRender = false;
  1127. this.style = __spreadValues({
  1128. strokeStyle: "",
  1129. fillStyle: "",
  1130. lineWidth: "small",
  1131. lineDash: 0,
  1132. globalAlpha: 1
  1133. }, opts.style || {});
  1134. this.dragElement = null;
  1135. }
  1136. serialize() {
  1137. return {
  1138. groupId: this.groupId,
  1139. type: this.type,
  1140. width: this.width,
  1141. height: this.height,
  1142. x: this.x,
  1143. y: this.y,
  1144. rotate: this.rotate,
  1145. style: __spreadValues({}, this.style)
  1146. };
  1147. }
  1148. render() {
  1149. throw new Error("\u5B50\u7C7B\u9700\u8981\u5B9E\u73B0\u8BE5\u65B9\u6CD5\uFF01");
  1150. }
  1151. setGroupId(groupId) {
  1152. this.groupId = groupId;
  1153. }
  1154. getGroupId() {
  1155. return this.groupId;
  1156. }
  1157. removeGroupId() {
  1158. this.groupId = "";
  1159. }
  1160. hasGroup() {
  1161. return !!this.groupId;
  1162. }
  1163. renderDragElement() {
  1164. if (this.isActive && !this.isCreating) {
  1165. this.dragElement.showAll();
  1166. this.dragElement.render();
  1167. } else if (this.isSelected) {
  1168. this.dragElement.onlyShowBody();
  1169. this.dragElement.render();
  1170. }
  1171. }
  1172. handleStyle(style) {
  1173. Object.keys(style).forEach((key) => {
  1174. if (key === "lineWidth") {
  1175. if (style[key] === "small") {
  1176. style[key] = 2;
  1177. } else if (style[key] === "middle") {
  1178. style[key] = 4;
  1179. } else if (style[key] === "large") {
  1180. style[key] = 6;
  1181. }
  1182. }
  1183. if (style[key] === "") {
  1184. if (this.app.state[key] !== void 0 && this.app.state[key] !== null && this.app.state[key] !== "") {
  1185. style[key] = this.app.state[key];
  1186. }
  1187. }
  1188. });
  1189. return style;
  1190. }
  1191. setStyle(style = {}) {
  1192. let _style = this.handleStyle(style);
  1193. Object.keys(_style).forEach((key) => {
  1194. if (key === "lineDash") {
  1195. if (_style.lineDash > 0) {
  1196. this.app.ctx.setLineDash([_style.lineDash]);
  1197. }
  1198. } else if (_style[key] !== void 0 && _style[key] !== "" && _style[key] !== null) {
  1199. this.app.ctx[key] = _style[key];
  1200. }
  1201. });
  1202. return this;
  1203. }
  1204. warpRender(renderFn) {
  1205. let { x, y, width, height, rotate, style } = this;
  1206. let { x: tx, y: ty } = this.app.coordinate.transform(x, y);
  1207. let halfWidth = width / 2;
  1208. let halfHeight = height / 2;
  1209. let cx = tx + halfWidth;
  1210. let cy = ty + halfHeight;
  1211. this.app.ctx.save();
  1212. this.app.ctx.translate(cx, cy);
  1213. this.app.ctx.rotate(degToRad(rotate));
  1214. this.setStyle(style);
  1215. renderFn({
  1216. halfWidth,
  1217. halfHeight,
  1218. tx,
  1219. ty,
  1220. cx,
  1221. cy
  1222. });
  1223. this.app.ctx.restore();
  1224. return this;
  1225. }
  1226. saveState() {
  1227. let { rotate, x, y } = this;
  1228. this.startRotate = rotate;
  1229. this.startX = x;
  1230. this.startY = y;
  1231. return this;
  1232. }
  1233. move(ox, oy) {
  1234. let { startX, startY } = this;
  1235. this.x = startX + ox;
  1236. this.y = startY + oy;
  1237. this.emit("elementPositionChange", this.x, this.y);
  1238. return this;
  1239. }
  1240. updateRect(x, y, width, height) {
  1241. this.updatePos(x, y);
  1242. this.updateSize(width, height);
  1243. return this;
  1244. }
  1245. updateSize(width, height) {
  1246. this.width = width;
  1247. this.height = height;
  1248. this.emit("elementSizeChange", this.width, this.height);
  1249. return this;
  1250. }
  1251. updatePos(x, y) {
  1252. this.x = x;
  1253. this.y = y;
  1254. this.emit("elementPositionChange", this.x, this.y);
  1255. return this;
  1256. }
  1257. offsetRotate(or) {
  1258. this.updateRotate(this.startRotate + or);
  1259. return this;
  1260. }
  1261. updateRotate(rotate) {
  1262. rotate = rotate % 360;
  1263. if (rotate < 0) {
  1264. rotate = 360 + rotate;
  1265. }
  1266. this.rotate = parseInt(rotate);
  1267. this.emit("elementRotateChange", this.rotate);
  1268. }
  1269. rotateByCenter(rotate, cx, cy) {
  1270. this.offsetRotate(rotate);
  1271. let np = getRotatedPoint(this.startX, this.startY, cx, cy, rotate);
  1272. this.updatePos(np.x, np.y);
  1273. }
  1274. isHit(x, y) {
  1275. throw new Error("\u5B50\u7C7B\u9700\u8981\u5B9E\u73B0\u8BE5\u65B9\u6CD5!");
  1276. }
  1277. startResize(resizeType, e) {
  1278. this.dragElement.startResize(resizeType, e);
  1279. return this;
  1280. }
  1281. endResize() {
  1282. this.dragElement.endResize();
  1283. return this;
  1284. }
  1285. resize(...args) {
  1286. this.dragElement.handleResizeElement(...args);
  1287. return this;
  1288. }
  1289. getEndpointList() {
  1290. return getElementCorners(this);
  1291. }
  1292. }
  1293. class DragElement extends BaseElement {
  1294. constructor(element, app, opts = {}) {
  1295. super(
  1296. {
  1297. type: "dragElement",
  1298. notNeedDragElement: true
  1299. },
  1300. app
  1301. );
  1302. this.opts = __spreadValues({
  1303. lockRatio: false
  1304. }, opts);
  1305. this.style = {
  1306. strokeStyle: this.app.state.dragStrokeStyle,
  1307. fillStyle: "transparent",
  1308. lineWidth: "small",
  1309. lineDash: 0,
  1310. globalAlpha: 1
  1311. };
  1312. this.element = element;
  1313. this.offset = 5;
  1314. this.size = 10;
  1315. this.resizeType = "";
  1316. this.diagonalPoint = {
  1317. x: 0,
  1318. y: 0
  1319. };
  1320. this.mousedownPosAndElementPosOffset = {
  1321. x: 0,
  1322. y: 0
  1323. };
  1324. this.elementRatio = 0;
  1325. this.hideParts = [];
  1326. }
  1327. setHideParts(parts = []) {
  1328. this.hideParts = parts;
  1329. }
  1330. showAll() {
  1331. this.setHideParts([]);
  1332. }
  1333. onlyShowBody() {
  1334. this.setHideParts([
  1335. DRAG_ELEMENT_PARTS.ROTATE,
  1336. DRAG_ELEMENT_PARTS.TOP_LEFT_BTN,
  1337. DRAG_ELEMENT_PARTS.TOP_RIGHT_BTN,
  1338. DRAG_ELEMENT_PARTS.BOTTOM_RIGHT_BTN,
  1339. DRAG_ELEMENT_PARTS.BOTTOM_LEFT_BTN
  1340. ]);
  1341. }
  1342. update() {
  1343. this.x = this.element.x - this.offset;
  1344. this.y = this.element.y - this.offset;
  1345. this.width = this.element.width + this.offset * 2;
  1346. this.height = this.element.height + this.offset * 2;
  1347. this.rotate = this.element.rotate;
  1348. }
  1349. render() {
  1350. if (this.element.hasGroup())
  1351. return;
  1352. this.update();
  1353. let { width, height } = this;
  1354. this.warpRender(({ halfWidth, halfHeight }) => {
  1355. this.app.ctx.save();
  1356. if (!this.hideParts.includes(DRAG_ELEMENT_PARTS.BODY)) {
  1357. this.app.ctx.setLineDash([5]);
  1358. drawRect(this.app.ctx, -halfWidth, -halfHeight, width, height);
  1359. this.app.ctx.restore();
  1360. }
  1361. if (!this.hideParts.includes(DRAG_ELEMENT_PARTS.TOP_LEFT_BTN)) {
  1362. drawRect(
  1363. this.app.ctx,
  1364. -halfWidth - this.size,
  1365. -halfHeight - this.size,
  1366. this.size,
  1367. this.size
  1368. );
  1369. }
  1370. if (!this.hideParts.includes(DRAG_ELEMENT_PARTS.TOP_RIGHT_BTN)) {
  1371. drawRect(
  1372. this.app.ctx,
  1373. -halfWidth + this.element.width + this.size,
  1374. -halfHeight - this.size,
  1375. this.size,
  1376. this.size
  1377. );
  1378. }
  1379. if (!this.hideParts.includes(DRAG_ELEMENT_PARTS.BOTTOM_RIGHT_BTN)) {
  1380. drawRect(
  1381. this.app.ctx,
  1382. -halfWidth + this.element.width + this.size,
  1383. -halfHeight + this.element.height + this.size,
  1384. this.size,
  1385. this.size
  1386. );
  1387. }
  1388. if (!this.hideParts.includes(DRAG_ELEMENT_PARTS.BOTTOM_LEFT_BTN)) {
  1389. drawRect(
  1390. this.app.ctx,
  1391. -halfWidth - this.size,
  1392. -halfHeight + this.element.height + this.size,
  1393. this.size,
  1394. this.size
  1395. );
  1396. }
  1397. if (!this.hideParts.includes(DRAG_ELEMENT_PARTS.ROTATE)) {
  1398. drawCircle(
  1399. this.app.ctx,
  1400. -halfWidth + this.element.width / 2 + this.size / 2,
  1401. -halfHeight - this.size * 2,
  1402. this.size
  1403. );
  1404. }
  1405. });
  1406. }
  1407. checkPointInDragElementWhere(x, y) {
  1408. let part = "";
  1409. let rp = transformPointOnElement(x, y, this.element);
  1410. if (checkPointIsInRectangle(rp.x, rp.y, this)) {
  1411. part = DRAG_ELEMENT_PARTS.BODY;
  1412. } else if (getTowPointDistance(
  1413. rp.x,
  1414. rp.y,
  1415. this.x + this.width / 2,
  1416. this.y - this.size * 2
  1417. ) <= this.size) {
  1418. part = DRAG_ELEMENT_PARTS.ROTATE;
  1419. } else if (this._checkPointIsInBtn(rp.x, rp.y, CORNERS.TOP_LEFT)) {
  1420. part = DRAG_ELEMENT_PARTS.TOP_LEFT_BTN;
  1421. } else if (this._checkPointIsInBtn(rp.x, rp.y, CORNERS.TOP_RIGHT)) {
  1422. part = DRAG_ELEMENT_PARTS.TOP_RIGHT_BTN;
  1423. } else if (this._checkPointIsInBtn(rp.x, rp.y, CORNERS.BOTTOM_RIGHT)) {
  1424. part = DRAG_ELEMENT_PARTS.BOTTOM_RIGHT_BTN;
  1425. } else if (this._checkPointIsInBtn(rp.x, rp.y, CORNERS.BOTTOM_LEFT)) {
  1426. part = DRAG_ELEMENT_PARTS.BOTTOM_LEFT_BTN;
  1427. }
  1428. if (this.hideParts.includes(part)) {
  1429. part = "";
  1430. }
  1431. return part;
  1432. }
  1433. _checkPointIsInBtn(x, y, dir) {
  1434. let _x = 0;
  1435. let _y = 0;
  1436. switch (dir) {
  1437. case CORNERS.TOP_LEFT:
  1438. _x = this.x - this.size;
  1439. _y = this.y - this.size;
  1440. break;
  1441. case CORNERS.TOP_RIGHT:
  1442. _x = this.x + this.width;
  1443. _y = this.y - this.size;
  1444. break;
  1445. case CORNERS.BOTTOM_RIGHT:
  1446. _x = this.x + this.width;
  1447. _y = this.y + this.height;
  1448. break;
  1449. case CORNERS.BOTTOM_LEFT:
  1450. _x = this.x - this.size;
  1451. _y = this.y + this.height;
  1452. break;
  1453. }
  1454. return checkPointIsInRectangle(x, y, _x, _y, this.size, this.size);
  1455. }
  1456. startResize(resizeType, e) {
  1457. this.resizeType = resizeType;
  1458. if (this.opts.lockRatio) {
  1459. this.elementRatio = this.element.width / this.element.height;
  1460. }
  1461. if (resizeType === DRAG_ELEMENT_PARTS.BODY) {
  1462. this.element.saveState();
  1463. } else if (resizeType === DRAG_ELEMENT_PARTS.ROTATE) {
  1464. this.element.saveState();
  1465. } else if (resizeType === DRAG_ELEMENT_PARTS.TOP_LEFT_BTN) {
  1466. this.handleDragMousedown(e, CORNERS.TOP_LEFT);
  1467. } else if (resizeType === DRAG_ELEMENT_PARTS.TOP_RIGHT_BTN) {
  1468. this.handleDragMousedown(e, CORNERS.TOP_RIGHT);
  1469. } else if (resizeType === DRAG_ELEMENT_PARTS.BOTTOM_RIGHT_BTN) {
  1470. this.handleDragMousedown(e, CORNERS.BOTTOM_RIGHT);
  1471. } else if (resizeType === DRAG_ELEMENT_PARTS.BOTTOM_LEFT_BTN) {
  1472. this.handleDragMousedown(e, CORNERS.BOTTOM_LEFT);
  1473. }
  1474. }
  1475. endResize() {
  1476. this.resizeType = "";
  1477. this.diagonalPoint = {
  1478. x: 0,
  1479. y: 0
  1480. };
  1481. this.mousedownPosAndElementPosOffset = {
  1482. x: 0,
  1483. y: 0
  1484. };
  1485. this.elementRatio = 0;
  1486. }
  1487. handleDragMousedown(e, corner) {
  1488. let centerPos = getElementCenterPoint(this.element);
  1489. let pos = getElementRotatedCornerPoint(this.element, corner);
  1490. this.diagonalPoint.x = 2 * centerPos.x - pos.x;
  1491. this.diagonalPoint.y = 2 * centerPos.y - pos.y;
  1492. this.mousedownPosAndElementPosOffset.x = e.clientX - pos.x;
  1493. this.mousedownPosAndElementPosOffset.y = e.clientY - pos.y;
  1494. this.element.saveState();
  1495. }
  1496. handleResizeElement(e, mx, my, offsetX, offsetY) {
  1497. let resizeType = this.resizeType;
  1498. if (resizeType === DRAG_ELEMENT_PARTS.BODY) {
  1499. this.handleMoveElement(offsetX, offsetY);
  1500. } else if (resizeType === DRAG_ELEMENT_PARTS.ROTATE) {
  1501. this.handleRotateElement(e, mx, my);
  1502. } else if (resizeType === DRAG_ELEMENT_PARTS.TOP_LEFT_BTN) {
  1503. this.handleStretchElement(
  1504. e,
  1505. (newCenter, rp) => {
  1506. return {
  1507. width: (newCenter.x - rp.x) * 2,
  1508. height: (newCenter.y - rp.y) * 2
  1509. };
  1510. },
  1511. (rp) => {
  1512. return {
  1513. x: rp.x,
  1514. y: rp.y
  1515. };
  1516. },
  1517. (newRatio, newRect) => {
  1518. let x = newRect.x;
  1519. let y = newRect.y;
  1520. if (newRatio > this.elementRatio) {
  1521. x = newRect.x + newRect.width - this.elementRatio * newRect.height;
  1522. } else if (newRatio < this.elementRatio) {
  1523. y = newRect.y + (newRect.height - newRect.width / this.elementRatio);
  1524. }
  1525. return {
  1526. x,
  1527. y
  1528. };
  1529. }
  1530. );
  1531. } else if (resizeType === DRAG_ELEMENT_PARTS.TOP_RIGHT_BTN) {
  1532. this.handleStretchElement(
  1533. e,
  1534. (newCenter, rp) => {
  1535. return {
  1536. width: (rp.x - newCenter.x) * 2,
  1537. height: (newCenter.y - rp.y) * 2
  1538. };
  1539. },
  1540. (rp, newSize) => {
  1541. return {
  1542. x: rp.x - newSize.width,
  1543. y: rp.y
  1544. };
  1545. },
  1546. (newRatio, newRect) => {
  1547. let x = newRect.x;
  1548. let y = newRect.y;
  1549. if (newRatio > this.elementRatio) {
  1550. x = newRect.x + this.elementRatio * newRect.height;
  1551. } else if (newRatio < this.elementRatio) {
  1552. x = newRect.x + newRect.width;
  1553. y = newRect.y + (newRect.height - newRect.width / this.elementRatio);
  1554. }
  1555. return {
  1556. x,
  1557. y
  1558. };
  1559. }
  1560. );
  1561. } else if (resizeType === DRAG_ELEMENT_PARTS.BOTTOM_RIGHT_BTN) {
  1562. this.handleStretchElement(
  1563. e,
  1564. (newCenter, rp) => {
  1565. return {
  1566. width: (rp.x - newCenter.x) * 2,
  1567. height: (rp.y - newCenter.y) * 2
  1568. };
  1569. },
  1570. (rp, newSize) => {
  1571. return {
  1572. x: rp.x - newSize.width,
  1573. y: rp.y - newSize.height
  1574. };
  1575. },
  1576. (newRatio, newRect) => {
  1577. let x = newRect.x;
  1578. let y = newRect.y;
  1579. if (newRatio > this.elementRatio) {
  1580. x = newRect.x + this.elementRatio * newRect.height;
  1581. y = newRect.y + newRect.height;
  1582. } else if (newRatio < this.elementRatio) {
  1583. x = newRect.x + newRect.width;
  1584. y = newRect.y + newRect.width / this.elementRatio;
  1585. }
  1586. return {
  1587. x,
  1588. y
  1589. };
  1590. }
  1591. );
  1592. } else if (resizeType === DRAG_ELEMENT_PARTS.BOTTOM_LEFT_BTN) {
  1593. this.handleStretchElement(
  1594. e,
  1595. (newCenter, rp) => {
  1596. return {
  1597. width: (newCenter.x - rp.x) * 2,
  1598. height: (rp.y - newCenter.y) * 2
  1599. };
  1600. },
  1601. (rp, newSize) => {
  1602. return {
  1603. x: rp.x,
  1604. y: rp.y - newSize.height
  1605. };
  1606. },
  1607. (newRatio, newRect) => {
  1608. let x = newRect.x;
  1609. let y = newRect.y;
  1610. if (newRatio > this.elementRatio) {
  1611. x = newRect.x + newRect.width - this.elementRatio * newRect.height;
  1612. y = newRect.y + newRect.height;
  1613. } else if (newRatio < this.elementRatio) {
  1614. y = newRect.y + newRect.width / this.elementRatio;
  1615. }
  1616. return {
  1617. x,
  1618. y
  1619. };
  1620. }
  1621. );
  1622. }
  1623. }
  1624. handleMoveElement(offsetX, offsetY) {
  1625. this.element.move(offsetX, offsetY);
  1626. }
  1627. handleRotateElement(e, mx, my) {
  1628. let centerPos = getElementCenterPoint(this.element);
  1629. let rotate = getTowPointRotate(
  1630. centerPos.x,
  1631. centerPos.y,
  1632. e.clientX,
  1633. e.clientY,
  1634. mx,
  1635. my
  1636. );
  1637. this.element.offsetRotate(rotate);
  1638. }
  1639. stretchCalc(x, y, calcSize, calcPos) {
  1640. let newCenter = {
  1641. x: (x + this.diagonalPoint.x) / 2,
  1642. y: (y + this.diagonalPoint.y) / 2
  1643. };
  1644. let rp = transformPointReverseRotate(
  1645. x,
  1646. y,
  1647. newCenter.x,
  1648. newCenter.y,
  1649. this.element.rotate
  1650. );
  1651. let newSize = calcSize(newCenter, rp);
  1652. let isWidthReverse = false;
  1653. if (newSize.width < 0) {
  1654. newSize.width = 0;
  1655. isWidthReverse = true;
  1656. }
  1657. let isHeightReverse = false;
  1658. if (newSize.height < 0) {
  1659. newSize.height = 0;
  1660. isHeightReverse = true;
  1661. }
  1662. let newPos = calcPos(rp, newSize);
  1663. let newRect = {
  1664. x: newPos.x,
  1665. y: newPos.y,
  1666. width: newSize.width,
  1667. height: newSize.height
  1668. };
  1669. if (isWidthReverse || isHeightReverse) {
  1670. newRect.x = this.element.x;
  1671. newRect.y = this.element.y;
  1672. }
  1673. return {
  1674. newRect,
  1675. newCenter
  1676. };
  1677. }
  1678. handleStretchElement(e, calcSize, calcPos, fixPos) {
  1679. let actClientX = e.clientX - this.mousedownPosAndElementPosOffset.x;
  1680. let actClientY = e.clientY - this.mousedownPosAndElementPosOffset.y;
  1681. let { newRect, newCenter } = this.stretchCalc(
  1682. actClientX,
  1683. actClientY,
  1684. calcSize,
  1685. calcPos
  1686. );
  1687. if (this.opts.lockRatio) {
  1688. this.fixStretch(newRect, newCenter, calcSize, calcPos, fixPos);
  1689. return;
  1690. }
  1691. this.element.updateRect(newRect.x, newRect.y, newRect.width, newRect.height);
  1692. }
  1693. fixStretch(newRect, newCenter, calcSize, calcPos, fixPos) {
  1694. let newRatio = newRect.width / newRect.height;
  1695. let fp = fixPos(newRatio, newRect);
  1696. let rp = getRotatedPoint(
  1697. fp.x,
  1698. fp.y,
  1699. newCenter.x,
  1700. newCenter.y,
  1701. this.element.rotate
  1702. );
  1703. let fixNewRect = this.stretchCalc(rp.x, rp.y, calcSize, calcPos).newRect;
  1704. if (fixNewRect.width === 0 && fixNewRect.height === 0) {
  1705. return;
  1706. }
  1707. this.element.updateRect(
  1708. fixNewRect.x,
  1709. fixNewRect.y,
  1710. fixNewRect.width,
  1711. fixNewRect.height
  1712. );
  1713. }
  1714. }
  1715. class Rectangle extends BaseElement {
  1716. constructor(...args) {
  1717. super(...args);
  1718. this.dragElement = new DragElement(this, this.app);
  1719. }
  1720. render() {
  1721. let { width, height } = this;
  1722. this.warpRender(({ halfWidth, halfHeight }) => {
  1723. drawRect(this.app.ctx, -halfWidth, -halfHeight, width, height, true);
  1724. });
  1725. this.renderDragElement();
  1726. }
  1727. isHit(x, y) {
  1728. let rp = transformPointOnElement(x, y, this);
  1729. return checkIsAtRectangleEdge(this, rp);
  1730. }
  1731. }
  1732. class Circle extends BaseElement {
  1733. constructor(...args) {
  1734. super(...args);
  1735. this.dragElement = new DragElement(this, this.app, {
  1736. lockRatio: true
  1737. });
  1738. }
  1739. render() {
  1740. let { width, height } = this;
  1741. this.warpRender(({ halfWidth, halfHeight }) => {
  1742. drawCircle(this.app.ctx, 0, 0, getCircleRadius(width, height), true);
  1743. });
  1744. this.renderDragElement();
  1745. }
  1746. isHit(x, y) {
  1747. let rp = transformPointOnElement(x, y, this);
  1748. return checkIsAtCircleEdge(this, rp);
  1749. }
  1750. }
  1751. class Diamond extends BaseElement {
  1752. constructor(...args) {
  1753. super(...args);
  1754. this.dragElement = new DragElement(this, this.app);
  1755. }
  1756. render() {
  1757. let { width, height } = this;
  1758. this.warpRender(({ halfWidth, halfHeight }) => {
  1759. drawDiamond(this.app.ctx, -halfWidth, -halfHeight, width, height, true);
  1760. });
  1761. this.renderDragElement();
  1762. }
  1763. isHit(x, y) {
  1764. let rp = transformPointOnElement(x, y, this);
  1765. return checkIsAtDiamondEdge(this, rp);
  1766. }
  1767. getEndpointList() {
  1768. let { x, y, width, height, rotate } = this;
  1769. let points = [
  1770. [x + width / 2, y],
  1771. [x + width, y + height / 2],
  1772. [x + width / 2, y + height],
  1773. [x, y + height / 2]
  1774. ];
  1775. let center = getElementCenterPoint(this);
  1776. return points.map((point) => {
  1777. return getRotatedPoint(point[0], point[1], center.x, center.y, rotate);
  1778. });
  1779. }
  1780. }
  1781. class Triangle extends BaseElement {
  1782. constructor(...args) {
  1783. super(...args);
  1784. this.dragElement = new DragElement(this, this.app);
  1785. }
  1786. render() {
  1787. let { width, height } = this;
  1788. this.warpRender(({ halfWidth, halfHeight }) => {
  1789. drawTriangle(this.app.ctx, -halfWidth, -halfHeight, width, height, true);
  1790. });
  1791. this.renderDragElement();
  1792. }
  1793. isHit(x, y) {
  1794. let rp = transformPointOnElement(x, y, this);
  1795. return checkIsAtTriangleEdge(this, rp);
  1796. }
  1797. getEndpointList() {
  1798. let { x, y, width, height, rotate } = this;
  1799. let points = [
  1800. [x + width / 2, y],
  1801. [x + width, y + height],
  1802. [x, y + height]
  1803. ];
  1804. let center = getElementCenterPoint(this);
  1805. return points.map((point) => {
  1806. return getRotatedPoint(point[0], point[1], center.x, center.y, rotate);
  1807. });
  1808. }
  1809. }
  1810. class BaseMultiPointElement extends BaseElement {
  1811. constructor(opts = {}, app) {
  1812. super(opts, app);
  1813. this.startPointArr = [];
  1814. this.pointArr = opts.pointArr || [];
  1815. this.startWidth = 0;
  1816. this.startHeight = 0;
  1817. this.fictitiousPoint = {
  1818. x: 0,
  1819. y: 0
  1820. };
  1821. }
  1822. serialize() {
  1823. let base = super.serialize();
  1824. return __spreadProps(__spreadValues({}, base), {
  1825. pointArr: [...this.pointArr]
  1826. });
  1827. }
  1828. addPoint(x, y, ...args) {
  1829. if (!Array.isArray(this.pointArr)) {
  1830. return;
  1831. }
  1832. this.pointArr.push([x, y, ...args]);
  1833. return this;
  1834. }
  1835. updateMultiPointBoundingRect() {
  1836. let rect = getBoundingRect(this.pointArr);
  1837. this.x = rect.x;
  1838. this.y = rect.y;
  1839. this.width = rect.width;
  1840. this.height = rect.height;
  1841. return this;
  1842. }
  1843. updateFictitiousPoint(x, y) {
  1844. this.fictitiousPoint.x = x;
  1845. this.fictitiousPoint.y = y;
  1846. }
  1847. saveState() {
  1848. let { rotate, x, y, width, height, pointArr } = this;
  1849. this.startRotate = rotate;
  1850. this.startX = x;
  1851. this.startY = y;
  1852. this.startPointArr = deepCopy(pointArr);
  1853. this.startWidth = width;
  1854. this.startHeight = height;
  1855. return this;
  1856. }
  1857. move(ox, oy) {
  1858. this.pointArr = this.startPointArr.map((point) => {
  1859. return [point[0] + ox, point[1] + oy, ...point.slice(2)];
  1860. });
  1861. let { startX, startY } = this;
  1862. this.x = startX + ox;
  1863. this.y = startY + oy;
  1864. return this;
  1865. }
  1866. updateRect(x, y, width, height) {
  1867. let { startWidth, startHeight, startPointArr } = this;
  1868. let scaleX = width / startWidth;
  1869. let scaleY = height / startHeight;
  1870. this.pointArr = startPointArr.map((point) => {
  1871. let nx = point[0] * scaleX;
  1872. let ny = point[1] * scaleY;
  1873. return [nx, ny, ...point.slice(2)];
  1874. });
  1875. let rect = getBoundingRect(this.pointArr);
  1876. let offsetX = rect.x - x;
  1877. let offsetY = rect.y - y;
  1878. this.pointArr = this.pointArr.map((point) => {
  1879. return [point[0] - offsetX, point[1] - offsetY, ...point.slice(2)];
  1880. });
  1881. this.updatePos(x, y);
  1882. this.updateSize(width, height);
  1883. return this;
  1884. }
  1885. rotateByCenter(rotate, cx, cy) {
  1886. this.pointArr = this.startPointArr.map((point) => {
  1887. let np = getRotatedPoint(point[0], point[1], cx, cy, rotate);
  1888. return [np.x, np.y, ...point.slice(2)];
  1889. });
  1890. this.updateMultiPointBoundingRect();
  1891. }
  1892. getEndpointList() {
  1893. return this.pointArr.map((point) => {
  1894. let center = getElementCenterPoint(this);
  1895. let np = getRotatedPoint(
  1896. point[0],
  1897. point[1],
  1898. center.x,
  1899. center.y,
  1900. this.rotate
  1901. );
  1902. return {
  1903. x: np.x,
  1904. y: np.y
  1905. };
  1906. });
  1907. }
  1908. }
  1909. class Freedraw extends BaseMultiPointElement {
  1910. constructor(...args) {
  1911. super(...args);
  1912. this.dragElement = new DragElement(this, this.app);
  1913. this.lastLineWidth = -1;
  1914. }
  1915. render() {
  1916. let { pointArr } = this;
  1917. this.warpRender(({ cx, cy }) => {
  1918. drawFreeLine(this.app.ctx, pointArr, {
  1919. app: this.app,
  1920. cx,
  1921. cy
  1922. });
  1923. });
  1924. this.renderDragElement();
  1925. }
  1926. isHit(x, y) {
  1927. let rp = transformPointOnElement(x, y, this);
  1928. return checkIsAtFreedrawLineEdge(this, rp);
  1929. }
  1930. singleRender(mx, my, tx, ty, lineWidth) {
  1931. this.app.ctx.save();
  1932. this.setStyle(this.style);
  1933. drawLineSegment(this.app.ctx, mx, my, tx, ty, lineWidth);
  1934. this.app.ctx.restore();
  1935. }
  1936. }
  1937. class Arrow extends BaseMultiPointElement {
  1938. constructor(...args) {
  1939. super(...args);
  1940. this.dragElement = new DragElement(this, this.app);
  1941. }
  1942. render() {
  1943. let { pointArr, fictitiousPoint } = this;
  1944. this.warpRender(({ cx, cy }) => {
  1945. let realtimePoint = [];
  1946. if (pointArr.length > 0 && this.isCreating) {
  1947. let { x: fx, y: fy } = this.app.coordinate.transform(
  1948. fictitiousPoint.x - cx,
  1949. fictitiousPoint.y - cy
  1950. );
  1951. realtimePoint = [[fx, fy]];
  1952. }
  1953. drawArrow(
  1954. this.app.ctx,
  1955. pointArr.map((point) => {
  1956. let { x, y } = this.app.coordinate.transform(point[0], point[1]);
  1957. return [x - cx, y - cy];
  1958. }).concat(realtimePoint)
  1959. );
  1960. });
  1961. this.renderDragElement();
  1962. }
  1963. isHit(x, y) {
  1964. let rp = transformPointOnElement(x, y, this);
  1965. return checkIsAtArrowEdge(this, rp);
  1966. }
  1967. }
  1968. class Image$1 extends BaseElement {
  1969. constructor(opts = {}, app) {
  1970. super(opts, app);
  1971. this.dragElement = new DragElement(this, this.app, {
  1972. lockRatio: true
  1973. });
  1974. this.url = opts.url || "";
  1975. this.imageObj = opts.imageObj || null;
  1976. this.ratio = opts.ratio || 1;
  1977. }
  1978. serialize() {
  1979. let base = super.serialize();
  1980. return __spreadProps(__spreadValues({}, base), {
  1981. url: this.url,
  1982. ratio: this.ratio
  1983. });
  1984. }
  1985. render() {
  1986. let { width, height } = this;
  1987. this.warpRender(({ halfWidth, halfHeight }) => {
  1988. drawImage(this.app.ctx, this, -halfWidth, -halfHeight, width, height);
  1989. });
  1990. this.renderDragElement();
  1991. }
  1992. isHit(x, y) {
  1993. let rp = transformPointOnElement(x, y, this);
  1994. return checkIsAtRectangleInner(this, rp);
  1995. }
  1996. }
  1997. class Line extends BaseMultiPointElement {
  1998. constructor(opts = {}, app) {
  1999. super(opts, app);
  2000. this.dragElement = new DragElement(this, this.app);
  2001. this.isSingle = opts.isSingle;
  2002. }
  2003. render() {
  2004. let { pointArr, fictitiousPoint } = this;
  2005. this.warpRender(({ cx, cy }) => {
  2006. let realtimePoint = [];
  2007. if (pointArr.length > 0 && this.isCreating) {
  2008. let { x: fx, y: fy } = this.app.coordinate.transform(
  2009. fictitiousPoint.x - cx,
  2010. fictitiousPoint.y - cy
  2011. );
  2012. realtimePoint = [[fx, fy]];
  2013. }
  2014. drawLine(
  2015. this.app.ctx,
  2016. pointArr.map((point) => {
  2017. let { x, y } = this.app.coordinate.transform(point[0], point[1]);
  2018. return [x - cx, y - cy];
  2019. }).concat(realtimePoint)
  2020. );
  2021. });
  2022. this.renderDragElement();
  2023. }
  2024. isHit(x, y) {
  2025. let rp = transformPointOnElement(x, y, this);
  2026. return checkIsAtLineEdge(this, rp);
  2027. }
  2028. }
  2029. class Text extends BaseElement {
  2030. constructor(opts = {}, app) {
  2031. var _a, _b, _c, _d;
  2032. super(opts, app);
  2033. this.dragElement = new DragElement(this, this.app, {
  2034. lockRatio: true
  2035. });
  2036. this.text = opts.text || "";
  2037. this.style.fillStyle = ((_a = opts.style) == null ? void 0 : _a.fillStyle) || this.app.state.strokeStyle || "#000";
  2038. this.style.fontSize = ((_b = opts.style) == null ? void 0 : _b.fontSize) || this.app.state.fontSize || 18;
  2039. this.style.lineHeightRatio = ((_c = opts.style) == null ? void 0 : _c.lineHeightRatio) || 1.5;
  2040. this.style.fontFamily = ((_d = opts.style) == null ? void 0 : _d.fontFamily) || this.app.state.fontFamily || "\u5FAE\u8F6F\u96C5\u9ED1, Microsoft YaHei";
  2041. }
  2042. serialize() {
  2043. let base = super.serialize();
  2044. return __spreadProps(__spreadValues({}, base), {
  2045. text: this.text
  2046. });
  2047. }
  2048. render() {
  2049. this.warpRender(({ halfWidth, halfHeight }) => {
  2050. drawText(this.app.ctx, this, -halfWidth, -halfHeight);
  2051. });
  2052. this.renderDragElement();
  2053. }
  2054. isHit(x, y) {
  2055. let rp = transformPointOnElement(x, y, this);
  2056. return checkIsAtRectangleInner(this, rp);
  2057. }
  2058. updateRect(x, y, width, height) {
  2059. let { text, style } = this;
  2060. let fontSize = Math.floor(
  2061. height / splitTextLines(text).length / style.lineHeightRatio
  2062. );
  2063. this.style.fontSize = fontSize;
  2064. super.updateRect(x, y, width, height);
  2065. }
  2066. updateTextSize() {
  2067. let { width, height } = getTextElementSize(this);
  2068. this.width = width;
  2069. this.height = height;
  2070. }
  2071. }
  2072. class Elements$1 {
  2073. constructor(app) {
  2074. this.app = app;
  2075. this.elementList = [];
  2076. this.activeElement = null;
  2077. this.isCreatingElement = false;
  2078. this.isResizing = false;
  2079. this.resizingElement = null;
  2080. this.handleResize = throttle(this.handleResize, this, 16);
  2081. }
  2082. serialize(stringify = false) {
  2083. let data = this.elementList.map((element) => {
  2084. return element.serialize();
  2085. });
  2086. return stringify ? JSON.stringify(data) : data;
  2087. }
  2088. getElementsNum() {
  2089. return this.elementList.length;
  2090. }
  2091. hasElements() {
  2092. return this.elementList.length > 0;
  2093. }
  2094. addElement(element) {
  2095. this.elementList.push(element);
  2096. return this;
  2097. }
  2098. unshiftElement(element) {
  2099. this.elementList.unshift(element);
  2100. return this;
  2101. }
  2102. insertElement(element, index) {
  2103. this.elementList.splice(index, 0, element);
  2104. }
  2105. deleteElement(element) {
  2106. let index = this.getElementIndex(element);
  2107. if (index !== -1) {
  2108. this.elementList.splice(index, 1);
  2109. if (element.isActive) {
  2110. this.cancelActiveElement(element);
  2111. }
  2112. }
  2113. return this;
  2114. }
  2115. deleteAllElements() {
  2116. this.activeElement = null;
  2117. this.elementList = [];
  2118. this.isCreatingElement = false;
  2119. this.isResizing = false;
  2120. this.resizingElement = null;
  2121. return this;
  2122. }
  2123. getElementIndex(element) {
  2124. return this.elementList.findIndex((item) => {
  2125. return item === element;
  2126. });
  2127. }
  2128. createElementsFromData(data) {
  2129. data.forEach((item) => {
  2130. let element = this.pureCreateElement(item);
  2131. element.isActive = false;
  2132. element.isCreating = false;
  2133. this.addElement(element);
  2134. });
  2135. this.app.group.initIdToElementList(this.elementList);
  2136. return this;
  2137. }
  2138. hasActiveElement() {
  2139. return !!this.activeElement;
  2140. }
  2141. setActiveElement(element) {
  2142. this.cancelActiveElement();
  2143. this.activeElement = element;
  2144. if (element) {
  2145. element.isActive = true;
  2146. }
  2147. this.app.emit("activeElementChange", this.activeElement);
  2148. return this;
  2149. }
  2150. cancelActiveElement() {
  2151. if (!this.hasActiveElement()) {
  2152. return this;
  2153. }
  2154. this.activeElement.isActive = false;
  2155. this.activeElement = null;
  2156. this.app.emit("activeElementChange", this.activeElement);
  2157. return this;
  2158. }
  2159. checkIsHitElement(e) {
  2160. let x = e.unGridClientX;
  2161. let y = e.unGridClientY;
  2162. for (let i = this.elementList.length - 1; i >= 0; i--) {
  2163. let element = this.elementList[i];
  2164. if (element.isHit(x, y)) {
  2165. return element;
  2166. }
  2167. }
  2168. return null;
  2169. }
  2170. pureCreateElement(opts = {}) {
  2171. switch (opts.type) {
  2172. case "rectangle":
  2173. return new Rectangle(opts, this.app);
  2174. case "diamond":
  2175. return new Diamond(opts, this.app);
  2176. case "triangle":
  2177. return new Triangle(opts, this.app);
  2178. case "circle":
  2179. return new Circle(opts, this.app);
  2180. case "freedraw":
  2181. return new Freedraw(opts, this.app);
  2182. case "image":
  2183. return new Image$1(opts, this.app);
  2184. case "arrow":
  2185. return new Arrow(opts, this.app);
  2186. case "line":
  2187. return new Line(opts, this.app);
  2188. case "text":
  2189. return new Text(opts, this.app);
  2190. default:
  2191. return null;
  2192. }
  2193. }
  2194. createElement(opts = {}, callback = () => {
  2195. }, ctx = null, notActive) {
  2196. if (this.hasActiveElement() || this.isCreatingElement) {
  2197. return this;
  2198. }
  2199. let element = this.pureCreateElement(opts);
  2200. if (!element) {
  2201. return this;
  2202. }
  2203. this.addElement(element);
  2204. if (!notActive) {
  2205. this.setActiveElement(element);
  2206. }
  2207. this.isCreatingElement = true;
  2208. callback.call(ctx, element);
  2209. return this;
  2210. }
  2211. copyElement(element, notActive = false, pos) {
  2212. return new Promise((resolve) => __async(this, null, function* () {
  2213. if (!element) {
  2214. return resolve();
  2215. }
  2216. let data = this.app.group.handleCopyElementData(element.serialize());
  2217. if (data.type === "image") {
  2218. data.imageObj = yield createImageObj(data.url);
  2219. }
  2220. if (data.type === "text") {
  2221. if (typeof data.text === "string") {
  2222. if (isNumeric$1(data.text)) {
  2223. const num = parseFloat(data.text);
  2224. const incrementedNum = num + 1;
  2225. data.text = incrementedNum.toString(10).padStart(data.text.length, "0");
  2226. }
  2227. }
  2228. }
  2229. this.createElement(
  2230. data,
  2231. (element2) => {
  2232. this.app.group.handleCopyElement(element2);
  2233. element2.startResize(DRAG_ELEMENT_PARTS.BODY);
  2234. let ox = 20;
  2235. let oy = 20;
  2236. if (pos) {
  2237. ox = pos.x - element2.x - element2.width / 2;
  2238. oy = pos.y - element2.y - element2.height / 2;
  2239. }
  2240. let gridAdsorbentPos = this.app.coordinate.gridAdsorbent(ox, oy);
  2241. element2.resize(
  2242. null,
  2243. null,
  2244. null,
  2245. gridAdsorbentPos.x,
  2246. gridAdsorbentPos.y
  2247. );
  2248. element2.isCreating = false;
  2249. if (notActive) {
  2250. element2.isActive = false;
  2251. }
  2252. this.isCreatingElement = false;
  2253. resolve(element2);
  2254. },
  2255. this,
  2256. notActive
  2257. );
  2258. }));
  2259. }
  2260. creatingRectangleLikeElement(type, x, y, offsetX, offsetY) {
  2261. this.createElement({
  2262. type,
  2263. x,
  2264. y,
  2265. width: offsetX,
  2266. height: offsetY
  2267. });
  2268. this.activeElement.updateSize(offsetX, offsetY);
  2269. }
  2270. creatingCircle(x, y, e) {
  2271. this.createElement({
  2272. type: "circle",
  2273. x,
  2274. y
  2275. });
  2276. let radius = getTowPointDistance(e.clientX, e.clientY, x, y);
  2277. this.activeElement.updateSize(radius, radius);
  2278. }
  2279. creatingFreedraw(e, event) {
  2280. this.createElement({
  2281. type: "freedraw"
  2282. });
  2283. let element = this.activeElement;
  2284. let lineWidth = computedLineWidthBySpeed(
  2285. event.mouseSpeed,
  2286. element.lastLineWidth
  2287. );
  2288. element.lastLineWidth = lineWidth;
  2289. element.addPoint(e.clientX, e.clientY, lineWidth);
  2290. let { coordinate, ctx, state } = this.app;
  2291. let tfp = coordinate.transformToCanvasCoordinate(
  2292. coordinate.subScrollX(event.lastMousePos.x),
  2293. coordinate.subScrollY(event.lastMousePos.y)
  2294. );
  2295. let ttp = coordinate.transformToCanvasCoordinate(
  2296. coordinate.subScrollX(e.clientX),
  2297. coordinate.subScrollY(e.clientY)
  2298. );
  2299. ctx.save();
  2300. ctx.scale(state.scale, state.scale);
  2301. element.singleRender(tfp.x, tfp.y, ttp.x, ttp.y, lineWidth);
  2302. ctx.restore();
  2303. }
  2304. creatingImage(e, { width, height, imageObj, url, ratio }) {
  2305. let gp = this.app.coordinate.gridAdsorbent(
  2306. e.unGridClientX - width / 2,
  2307. e.unGridClientY - height / 2
  2308. );
  2309. this.createElement({
  2310. type: "image",
  2311. x: gp.x,
  2312. y: gp.y,
  2313. url,
  2314. imageObj,
  2315. width,
  2316. height,
  2317. ratio
  2318. });
  2319. }
  2320. editingText(element) {
  2321. if (element.type !== "text") {
  2322. return;
  2323. }
  2324. element.noRender = true;
  2325. this.setActiveElement(element);
  2326. }
  2327. completeEditingText() {
  2328. let element = this.activeElement;
  2329. if (!element || element.type !== "text") {
  2330. return;
  2331. }
  2332. if (!element.text.trim()) {
  2333. this.deleteElement(element);
  2334. this.setActiveElement(null);
  2335. return;
  2336. }
  2337. element.noRender = false;
  2338. }
  2339. completeCreateArrow(e) {
  2340. this.activeElement.addPoint(e.clientX, e.clientY);
  2341. }
  2342. creatingArrow(x, y, e) {
  2343. this.createElement(
  2344. {
  2345. type: "arrow",
  2346. x,
  2347. y
  2348. },
  2349. (element) => {
  2350. element.addPoint(x, y);
  2351. }
  2352. );
  2353. this.activeElement.updateFictitiousPoint(e.clientX, e.clientY);
  2354. }
  2355. creatingLine(x, y, e, isSingle = false, notCreate = false) {
  2356. if (!notCreate) {
  2357. this.createElement(
  2358. {
  2359. type: "line",
  2360. x,
  2361. y,
  2362. isSingle
  2363. },
  2364. (element2) => {
  2365. element2.addPoint(x, y);
  2366. }
  2367. );
  2368. }
  2369. let element = this.activeElement;
  2370. if (element) {
  2371. element.updateFictitiousPoint(e.clientX, e.clientY);
  2372. }
  2373. }
  2374. completeCreateLine(e, completeCallback = () => {
  2375. }) {
  2376. let element = this.activeElement;
  2377. let x = e.clientX;
  2378. let y = e.clientY;
  2379. if (element && element.isSingle) {
  2380. element.addPoint(x, y);
  2381. completeCallback();
  2382. } else {
  2383. this.createElement({
  2384. type: "line",
  2385. isSingle: false
  2386. });
  2387. element = this.activeElement;
  2388. element.addPoint(x, y);
  2389. element.updateFictitiousPoint(x, y);
  2390. }
  2391. }
  2392. completeCreateElement() {
  2393. this.isCreatingElement = false;
  2394. let element = this.activeElement;
  2395. if (!element) {
  2396. return this;
  2397. }
  2398. if (["freedraw", "arrow", "line"].includes(element.type)) {
  2399. element.updateMultiPointBoundingRect();
  2400. }
  2401. element.isCreating = false;
  2402. this.app.emitChange();
  2403. return this;
  2404. }
  2405. setActiveElementStyle(style = {}) {
  2406. if (!this.hasActiveElement()) {
  2407. return this;
  2408. }
  2409. Object.keys(style).forEach((key) => {
  2410. this.activeElement.style[key] = style[key];
  2411. if (key === "fontSize" && this.activeElement.type === "text") {
  2412. this.activeElement.updateTextSize();
  2413. }
  2414. });
  2415. return this;
  2416. }
  2417. checkInResizeHand(x, y) {
  2418. let element = this.activeElement;
  2419. let hand = element.dragElement.checkPointInDragElementWhere(x, y);
  2420. if (hand) {
  2421. return {
  2422. element,
  2423. hand
  2424. };
  2425. }
  2426. return null;
  2427. }
  2428. checkIsResize(x, y, e) {
  2429. if (!this.hasActiveElement()) {
  2430. return false;
  2431. }
  2432. let res = this.checkInResizeHand(x, y);
  2433. if (res) {
  2434. this.isResizing = true;
  2435. this.resizingElement = res.element;
  2436. this.resizingElement.startResize(res.hand, e);
  2437. this.app.cursor.setResize(res.hand);
  2438. return true;
  2439. }
  2440. return false;
  2441. }
  2442. handleResize(...args) {
  2443. if (!this.isResizing) {
  2444. return;
  2445. }
  2446. this.resizingElement.resize(...args);
  2447. this.app.render.render();
  2448. }
  2449. endResize() {
  2450. this.isResizing = false;
  2451. this.resizingElement.endResize();
  2452. this.resizingElement = null;
  2453. }
  2454. }
  2455. function isNumeric$1(str) {
  2456. const trimmedStr = str.trim();
  2457. const num = Number(trimmedStr);
  2458. return !isNaN(num) && trimmedStr === num.toString().padStart(trimmedStr.length, "0");
  2459. }
  2460. class ImageEdit extends EventEmitter {
  2461. constructor(app) {
  2462. super();
  2463. this.app = app;
  2464. this.el = null;
  2465. this.isReady = false;
  2466. this.previewEl = null;
  2467. this.imageData = null;
  2468. this.maxWidth = 750;
  2469. this.maxHeight = 450;
  2470. this.maxRatio = this.maxWidth / this.maxHeight;
  2471. this.onImageSelectChange = this.onImageSelectChange.bind(this);
  2472. }
  2473. reset() {
  2474. this.el.value = "";
  2475. this.isReady = false;
  2476. document.body.removeChild(this.previewEl);
  2477. this.previewEl = null;
  2478. this.imageData = null;
  2479. }
  2480. selectImage() {
  2481. if (!this.el) {
  2482. this.el = document.createElement("input");
  2483. this.el.type = "file";
  2484. this.el.accept = "image/*";
  2485. this.el.style.position = "fixed";
  2486. this.el.style.left = "-999999px";
  2487. this.el.addEventListener("change", this.onImageSelectChange);
  2488. document.body.appendChild(this.el);
  2489. }
  2490. this.el.click();
  2491. }
  2492. updatePreviewElPos(x, y) {
  2493. let width = 100;
  2494. let height = width / this.imageData.ratio;
  2495. if (!this.previewEl) {
  2496. this.previewEl = document.createElement("div");
  2497. this.previewEl.style.position = "fixed";
  2498. this.previewEl.style.width = width + "px";
  2499. this.previewEl.style.height = height + "px";
  2500. this.previewEl.style.backgroundImage = `url('${this.imageData.url}')`;
  2501. this.previewEl.style.backgroundSize = "cover";
  2502. this.previewEl.style.pointerEvents = "none";
  2503. document.body.appendChild(this.previewEl);
  2504. }
  2505. let tp = this.app.coordinate.containerToWindow(x, y);
  2506. this.previewEl.style.left = tp.x - width / 2 + "px";
  2507. this.previewEl.style.top = tp.y - height / 2 + "px";
  2508. }
  2509. getImageSize(url) {
  2510. return __async(this, null, function* () {
  2511. return new Promise((resolve, reject) => {
  2512. let img = new Image();
  2513. img.setAttribute("crossOrigin", "anonymous");
  2514. img.onload = () => {
  2515. let width = img.width;
  2516. let height = img.height;
  2517. let ratio = img.width / img.height;
  2518. if (img.width > this.maxWidth || img.height > this.maxHeight) {
  2519. if (ratio > this.maxRatio) {
  2520. width = this.maxWidth;
  2521. height = this.maxWidth / ratio;
  2522. } else {
  2523. height = this.maxHeight;
  2524. width = this.maxHeight * ratio;
  2525. }
  2526. }
  2527. resolve({
  2528. imageObj: img,
  2529. size: {
  2530. width,
  2531. height
  2532. },
  2533. ratio
  2534. });
  2535. };
  2536. img.onerror = () => {
  2537. reject();
  2538. };
  2539. img.src = url;
  2540. });
  2541. });
  2542. }
  2543. onImageSelectChange(e) {
  2544. return __async(this, null, function* () {
  2545. let url = yield this.getImageUrl(e.target.files[0]);
  2546. let { imageObj, size, ratio } = yield this.getImageSize(url);
  2547. this.isReady = true;
  2548. this.imageData = __spreadProps(__spreadValues({
  2549. url
  2550. }, size), {
  2551. ratio,
  2552. imageObj
  2553. });
  2554. this.emit("imageSelectChange", this.imageData);
  2555. });
  2556. }
  2557. getImageUrl(file) {
  2558. return __async(this, null, function* () {
  2559. return new Promise((resolve, reject) => {
  2560. let reader = new FileReader();
  2561. reader.onloadend = () => {
  2562. resolve(reader.result);
  2563. };
  2564. reader.onerror = () => {
  2565. reject();
  2566. };
  2567. reader.readAsDataURL(file);
  2568. });
  2569. });
  2570. }
  2571. }
  2572. class Cursor {
  2573. constructor(app) {
  2574. this.app = app;
  2575. this.currentType = "default";
  2576. }
  2577. set(type = "default") {
  2578. this.currentType = type;
  2579. let style = type;
  2580. if (type === "eraser") {
  2581. style = `url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABQAAAAUCAYAAACNiR0NAAAAAXNSR0IArs4c6QAAARRJREFUOE/dlDFLxEAQhd+BVouFZ3vlQuwSyI+5a7PBRkk6k9KzTOwStJFsWv0xgaQzkNLWszim0kL2OOFc9oKRYHFTz37Lm/dmJhi5JiPzcBjAOYDz7WheADz3jalP8oIxds85P3Zd90RBqqpad133SUSXAJ5M4H3AhWVZd1EUzYQQP96VZYkkSV7btr02QY1Axtgqz/NTz/OM6qSUCMNwRURneoMJOLdt+7Gu643MfeU4zrppmgt9pibgjRBiWRRFb0R934eUcgngdrfxX4CjSwZj7C3Lsqnu8Lc05XQQBO9ENP2NKapnE5s4jme608rhNE2HxWb7qwr2A+f8SAv2BxFdDQ32rpLRVu9Pl+0wztcg6V/VPW4Vw1FsawAAAABJRU5ErkJggg==) 10 10, auto`;
  2582. }
  2583. this.app.container.style.cursor = style;
  2584. }
  2585. hide() {
  2586. this.set("none");
  2587. }
  2588. reset() {
  2589. this.set();
  2590. }
  2591. setCrosshair() {
  2592. this.set("crosshair");
  2593. }
  2594. setMove() {
  2595. this.set("move");
  2596. }
  2597. setResize(dir) {
  2598. let type = "";
  2599. switch (dir) {
  2600. case DRAG_ELEMENT_PARTS.BODY:
  2601. type = "move";
  2602. break;
  2603. case DRAG_ELEMENT_PARTS.ROTATE:
  2604. type = "grab";
  2605. break;
  2606. case DRAG_ELEMENT_PARTS.TOP_LEFT_BTN:
  2607. type = "nw-resize";
  2608. break;
  2609. case DRAG_ELEMENT_PARTS.TOP_RIGHT_BTN:
  2610. type = "ne-resize";
  2611. break;
  2612. case DRAG_ELEMENT_PARTS.BOTTOM_RIGHT_BTN:
  2613. type = "se-resize";
  2614. break;
  2615. case DRAG_ELEMENT_PARTS.BOTTOM_LEFT_BTN:
  2616. type = "sw-resize";
  2617. break;
  2618. }
  2619. this.set(type);
  2620. }
  2621. setEraser() {
  2622. this.set("eraser");
  2623. }
  2624. }
  2625. class TextEdit extends EventEmitter {
  2626. constructor(app) {
  2627. super();
  2628. this.app = app;
  2629. this.editable = null;
  2630. this.isEditing = false;
  2631. this.onTextInput = this.onTextInput.bind(this);
  2632. this.onTextBlur = this.onTextBlur.bind(this);
  2633. }
  2634. crateTextInputEl() {
  2635. this.editable = document.createElement("textarea");
  2636. this.editable.dir = "auto";
  2637. this.editable.tabIndex = 0;
  2638. this.editable.wrap = "off";
  2639. this.editable.className = "textInput";
  2640. Object.assign(this.editable.style, {
  2641. position: "fixed",
  2642. display: "block",
  2643. minHeight: "1em",
  2644. backfaceVisibility: "hidden",
  2645. margin: 0,
  2646. padding: 0,
  2647. border: 0,
  2648. outline: 0,
  2649. resize: "none",
  2650. background: "transparent",
  2651. overflow: "hidden",
  2652. whiteSpace: "pre"
  2653. });
  2654. this.editable.addEventListener("input", this.onTextInput);
  2655. this.editable.addEventListener("blur", this.onTextBlur);
  2656. document.body.appendChild(this.editable);
  2657. }
  2658. updateTextInputStyle() {
  2659. let activeElement = this.app.elements.activeElement;
  2660. if (!activeElement) {
  2661. return;
  2662. }
  2663. let { x, y, width, height, style, text, rotate } = activeElement;
  2664. let { coordinate, state } = this.app;
  2665. this.editable.value = text;
  2666. x = coordinate.subScrollX(x);
  2667. y = coordinate.subScrollY(y);
  2668. let sp = coordinate.scale(x, y);
  2669. let tp = coordinate.containerToWindow(sp.x, sp.y);
  2670. let fontSize = style.fontSize * state.scale;
  2671. let styles = {
  2672. font: getFontString(fontSize, style.fontFamily),
  2673. lineHeight: `${fontSize * style.lineHeightRatio}px`,
  2674. left: `${tp.x}px`,
  2675. top: `${tp.y}px`,
  2676. color: style.fillStyle,
  2677. width: Math.max(width, 100) * state.scale + "px",
  2678. height: height * state.scale + "px",
  2679. transform: `rotate(${rotate}deg)`,
  2680. opacity: style.globalAlpha
  2681. };
  2682. Object.assign(this.editable.style, styles);
  2683. }
  2684. onTextInput() {
  2685. let activeElement = this.app.elements.activeElement;
  2686. if (!activeElement) {
  2687. return;
  2688. }
  2689. activeElement.text = this.editable.value;
  2690. let { width, height } = getTextElementSize(activeElement);
  2691. activeElement.width = width;
  2692. activeElement.height = height;
  2693. this.updateTextInputStyle();
  2694. }
  2695. onTextBlur() {
  2696. this.editable.style.display = "none";
  2697. this.editable.value = "";
  2698. this.emit("blur");
  2699. this.isEditing = false;
  2700. }
  2701. showTextEdit() {
  2702. if (!this.editable) {
  2703. this.crateTextInputEl();
  2704. } else {
  2705. this.editable.style.display = "block";
  2706. }
  2707. this.updateTextInputStyle();
  2708. this.editable.focus();
  2709. this.editable.select();
  2710. this.isEditing = true;
  2711. }
  2712. }
  2713. class History {
  2714. constructor(app) {
  2715. this.app = app;
  2716. this.historyStack = [];
  2717. this.length = 0;
  2718. this.index = -1;
  2719. }
  2720. add(data) {
  2721. let prev = this.length > 0 ? this.historyStack[this.length - 1] : null;
  2722. let copyData = deepCopy(data);
  2723. if (copyData === prev) {
  2724. return;
  2725. }
  2726. this.historyStack.push(copyData);
  2727. this.length++;
  2728. this.index = this.length - 1;
  2729. this.emitChange();
  2730. }
  2731. undo() {
  2732. if (this.index <= 0) {
  2733. return;
  2734. }
  2735. this.index--;
  2736. this.shuttle();
  2737. }
  2738. redo() {
  2739. if (this.index >= this.length - 1) {
  2740. return;
  2741. }
  2742. this.index++;
  2743. this.shuttle();
  2744. }
  2745. shuttle() {
  2746. return __async(this, null, function* () {
  2747. let data = this.historyStack[this.index];
  2748. yield this.app.setData(data, true);
  2749. this.emitChange();
  2750. this.app.emit("change", data);
  2751. });
  2752. }
  2753. clear() {
  2754. this.index = -1;
  2755. this.length = 0;
  2756. this.historyStack = [];
  2757. this.emitChange();
  2758. }
  2759. emitChange() {
  2760. this.app.emit("shuttle", this.index, this.length);
  2761. }
  2762. }
  2763. class Export {
  2764. constructor(app) {
  2765. this.app = app;
  2766. this.openTest = false;
  2767. this.saveState = {
  2768. scale: 0,
  2769. scrollX: 0,
  2770. scrollY: 0,
  2771. width: 0,
  2772. height: 0
  2773. };
  2774. }
  2775. show(canvas) {
  2776. if (this.openTest) {
  2777. canvas.style.cssText = `
  2778. position: absolute;
  2779. left: 0;
  2780. top: 0;
  2781. background-color: #fff;
  2782. `;
  2783. document.body.appendChild(canvas);
  2784. }
  2785. }
  2786. getElementList(onlySelected = true) {
  2787. if (!onlySelected) {
  2788. return this.app.elements.elementList;
  2789. } else {
  2790. let selectedElements = [];
  2791. if (this.app.elements.activeElement) {
  2792. selectedElements.push(this.app.elements.activeElement);
  2793. } else if (this.app.selection.hasSelectionElements()) {
  2794. selectedElements = this.app.selection.getSelectionElements();
  2795. }
  2796. let res = this.app.elements.elementList.filter((element) => {
  2797. return selectedElements.includes(element);
  2798. });
  2799. return res;
  2800. }
  2801. }
  2802. exportImage({
  2803. type = "image/png",
  2804. renderBg = true,
  2805. useBlob = false,
  2806. paddingX = 10,
  2807. paddingY = 10,
  2808. onlySelected
  2809. } = {}) {
  2810. let { minx, maxx, miny, maxy } = getMultiElementRectInfo(
  2811. this.getElementList(onlySelected)
  2812. );
  2813. let width = maxx - minx + paddingX * 2;
  2814. let height = maxy - miny + paddingY * 2;
  2815. let { canvas, ctx } = createCanvas(width, height, {
  2816. noStyle: true,
  2817. noTranslate: true
  2818. });
  2819. this.show(canvas);
  2820. this.saveAppState();
  2821. this.changeAppState(minx - paddingX, miny - paddingY, ctx);
  2822. if (renderBg && this.app.state.backgroundColor) {
  2823. this.app.background.canvasAddBackgroundColor(
  2824. ctx,
  2825. width,
  2826. height,
  2827. this.app.state.backgroundColor
  2828. );
  2829. }
  2830. this.render(ctx, onlySelected);
  2831. this.recoveryAppState();
  2832. if (useBlob) {
  2833. return new Promise((resolve, reject) => {
  2834. canvas.toBlob((blob) => {
  2835. if (blob) {
  2836. resolve(blob);
  2837. } else {
  2838. reject();
  2839. }
  2840. }, type);
  2841. });
  2842. } else {
  2843. return canvas.toDataURL(type);
  2844. }
  2845. }
  2846. saveAppState() {
  2847. let { width, height, state, ctx } = this.app;
  2848. this.saveState.width = width;
  2849. this.saveState.height = height;
  2850. this.saveState.scale = state.scale;
  2851. this.saveState.scrollX = state.scrollX;
  2852. this.saveState.scrollY = state.scrollY;
  2853. this.saveState.ctx = ctx;
  2854. }
  2855. changeAppState(minx, miny, ctx) {
  2856. this.app.ctx = ctx;
  2857. this.app.state.scale = 1;
  2858. this.app.state.scrollX = 0;
  2859. this.app.state.scrollY = 0;
  2860. this.app.width = minx * 2;
  2861. this.app.height = miny * 2;
  2862. }
  2863. recoveryAppState() {
  2864. let { width, height, scale, scrollX, scrollY, ctx } = this.saveState;
  2865. this.app.state.scale = scale;
  2866. this.app.state.scrollX = scrollX;
  2867. this.app.state.scrollY = scrollY;
  2868. this.app.width = width;
  2869. this.app.height = height;
  2870. this.app.ctx = ctx;
  2871. }
  2872. render(ctx, onlySelected) {
  2873. ctx.save();
  2874. this.getElementList(onlySelected).forEach((element) => {
  2875. if (element.noRender) {
  2876. return;
  2877. }
  2878. let cacheActive = element.isActive;
  2879. let cacheSelected = element.isSelected;
  2880. element.isActive = false;
  2881. element.isSelected = false;
  2882. element.render();
  2883. element.isActive = cacheActive;
  2884. element.isSelected = cacheSelected;
  2885. });
  2886. ctx.restore();
  2887. }
  2888. exportJson() {
  2889. return this.app.getData();
  2890. }
  2891. }
  2892. class Background {
  2893. constructor(app) {
  2894. this.app = app;
  2895. }
  2896. set() {
  2897. if (this.app.state.backgroundColor) {
  2898. this.addBackgroundColor();
  2899. } else {
  2900. this.remove();
  2901. }
  2902. }
  2903. addBackgroundColor() {
  2904. this.app.container.style.backgroundColor = this.app.state.backgroundColor;
  2905. }
  2906. remove() {
  2907. this.app.container.style.backgroundColor = "";
  2908. }
  2909. canvasAddBackgroundColor(ctx, width, height, backgroundColor) {
  2910. ctx.save();
  2911. ctx.rect(0, 0, width, height);
  2912. ctx.fillStyle = backgroundColor;
  2913. ctx.fill();
  2914. ctx.restore();
  2915. }
  2916. }
  2917. class Canvas {
  2918. constructor(width, height, opt) {
  2919. this.width = width;
  2920. this.height = height;
  2921. let { canvas, ctx } = createCanvas(width, height, opt);
  2922. this.el = canvas;
  2923. this.ctx = ctx;
  2924. }
  2925. clearCanvas() {
  2926. let { width, height } = this;
  2927. this.ctx.clearRect(-width / 2, -height / 2, width, height);
  2928. }
  2929. }
  2930. class MultiSelectElement extends BaseElement {
  2931. constructor(opts = {}, app) {
  2932. super(opts, app);
  2933. this.dragElement = new DragElement(this, this.app);
  2934. this.selectedElementList = [];
  2935. this.wholeCenterPos = { x: 0, y: 0 };
  2936. }
  2937. setSelectedElementList(list) {
  2938. this.selectedElementList.forEach((element) => {
  2939. element.isSelected = false;
  2940. });
  2941. this.selectedElementList = list;
  2942. this.selectedElementList.forEach((element) => {
  2943. element.isSelected = true;
  2944. });
  2945. }
  2946. updateElements(elements) {
  2947. let exists = [];
  2948. this.selectedElementList.forEach((element) => {
  2949. if (elements.includes(element)) {
  2950. exists.push(element);
  2951. }
  2952. });
  2953. this.setSelectedElementList(exists);
  2954. }
  2955. updateRect() {
  2956. if (this.selectedElementList.length <= 0) {
  2957. super.updateRect(0, 0, 0, 0);
  2958. return;
  2959. }
  2960. let { minx, maxx, miny, maxy } = getMultiElementRectInfo(
  2961. this.selectedElementList
  2962. );
  2963. super.updateRect(minx, miny, maxx - minx, maxy - miny);
  2964. }
  2965. startResize(...args) {
  2966. this.selectedElementList.forEach((element) => {
  2967. if (args[0] === "rotate") {
  2968. this.wholeCenterPos = getElementCenterPoint(this);
  2969. }
  2970. element.startResize(...args);
  2971. });
  2972. }
  2973. resize(...args) {
  2974. this.selectedElementList.forEach((element) => {
  2975. if (element.dragElement.resizeType === "rotate") {
  2976. this.handleRotate(element, ...args);
  2977. } else {
  2978. element.resize(...args);
  2979. }
  2980. });
  2981. }
  2982. handleRotate(element, e, mx, my, offsetX, offsetY) {
  2983. let rotate = getTowPointRotate(
  2984. this.wholeCenterPos.x,
  2985. this.wholeCenterPos.y,
  2986. e.clientX,
  2987. e.clientY,
  2988. mx,
  2989. my
  2990. );
  2991. element.rotateByCenter(rotate, this.wholeCenterPos.x, this.wholeCenterPos.y);
  2992. }
  2993. endResize() {
  2994. this.selectedElementList.forEach((element) => {
  2995. element.endResize();
  2996. });
  2997. }
  2998. render() {
  2999. if (this.selectedElementList.length > 0) {
  3000. if (this.width <= 0 || this.height <= 0) {
  3001. return;
  3002. }
  3003. this.dragElement.render();
  3004. }
  3005. }
  3006. }
  3007. class Selection {
  3008. constructor(app) {
  3009. this.app = app;
  3010. this.canvas = null;
  3011. this.ctx = null;
  3012. this.creatingSelection = false;
  3013. this.hasSelection = false;
  3014. this.isResizing = false;
  3015. this.state = this.app.state;
  3016. this.width = this.app.width;
  3017. this.height = this.app.height;
  3018. this.coordinate = new Coordinate(this);
  3019. this.rectangle = new Rectangle(
  3020. {
  3021. type: "rectangle",
  3022. style: {
  3023. strokeStyle: "rgba(9,132,227,0.3)",
  3024. fillStyle: "rgba(9,132,227,0.3)"
  3025. }
  3026. },
  3027. this
  3028. );
  3029. this.multiSelectElement = new MultiSelectElement(
  3030. {
  3031. type: "multiSelectElement"
  3032. },
  3033. this
  3034. );
  3035. this.checkInNodes = throttle(this.checkInNodes, this, 500);
  3036. this.handleResize = throttle(this.handleResize, this, 16);
  3037. this.init();
  3038. this.bindEvent();
  3039. }
  3040. init() {
  3041. if (this.canvas) {
  3042. this.app.container.removeChild(this.canvas.el);
  3043. }
  3044. this.width = this.app.width;
  3045. this.height = this.app.height;
  3046. this.canvas = new Canvas(this.width, this.height, {
  3047. className: "selection"
  3048. });
  3049. this.ctx = this.canvas.ctx;
  3050. this.app.container.appendChild(this.canvas.el);
  3051. }
  3052. bindEvent() {
  3053. this.app.on("change", () => {
  3054. this.state = this.app.state;
  3055. this.multiSelectElement.updateElements(this.app.elements.elementList);
  3056. this.renderSelection();
  3057. });
  3058. this.app.on("scrollChange", () => {
  3059. this.renderSelection();
  3060. });
  3061. this.app.on("zoomChange", () => {
  3062. this.renderSelection();
  3063. });
  3064. }
  3065. onMousedown(e, event) {
  3066. if (e.originEvent.which !== 1) {
  3067. return;
  3068. }
  3069. this.creatingSelection = true;
  3070. this.rectangle.updatePos(event.mousedownPos.x, event.mousedownPos.y);
  3071. }
  3072. onMousemove(e, event) {
  3073. if (Math.abs(event.mouseOffset.x) <= 10 && Math.abs(event.mouseOffset.y) <= 10) {
  3074. return;
  3075. }
  3076. this.onMove(e, event);
  3077. }
  3078. onMouseup() {
  3079. this.creatingSelection = false;
  3080. this.rectangle.updateRect(0, 0, 0, 0);
  3081. this.hasSelection = this.hasSelectionElements();
  3082. this.multiSelectElement.updateRect();
  3083. this.renderSelection();
  3084. this.emitChange();
  3085. }
  3086. reset() {
  3087. this.setMultiSelectElements([]);
  3088. this.hasSelection = false;
  3089. this.renderSelection();
  3090. this.emitChange();
  3091. }
  3092. renderSelection() {
  3093. this.canvas.clearCanvas();
  3094. this.ctx.save();
  3095. this.ctx.scale(this.app.state.scale, this.app.state.scale);
  3096. this.rectangle.render();
  3097. this.multiSelectElement.render();
  3098. this.ctx.restore();
  3099. }
  3100. onMove(e, event) {
  3101. this.rectangle.updateSize(event.mouseOffset.x, event.mouseOffset.y);
  3102. this.renderSelection();
  3103. this.checkInElements(e, event);
  3104. }
  3105. checkInElements(e, event) {
  3106. let minx = Math.min(event.mousedownPos.x, e.clientX);
  3107. let miny = Math.min(event.mousedownPos.y, e.clientY);
  3108. let maxx = Math.max(event.mousedownPos.x, e.clientX);
  3109. let maxy = Math.max(event.mousedownPos.y, e.clientY);
  3110. let selectedElementList = [];
  3111. this.app.elements.elementList.forEach((element) => {
  3112. let _minx = Infinity;
  3113. let _maxx = -Infinity;
  3114. let _miny = Infinity;
  3115. let _maxy = -Infinity;
  3116. let endPointList = element.getEndpointList();
  3117. let rect = getBoundingRect(
  3118. endPointList.map((point) => {
  3119. return [point.x, point.y];
  3120. }),
  3121. true
  3122. );
  3123. rect.forEach(({ x, y }) => {
  3124. if (x < _minx) {
  3125. _minx = x;
  3126. }
  3127. if (x > _maxx) {
  3128. _maxx = x;
  3129. }
  3130. if (y < _miny) {
  3131. _miny = y;
  3132. }
  3133. if (y > _maxy) {
  3134. _maxy = y;
  3135. }
  3136. });
  3137. if (_minx >= minx && _maxx <= maxx && _miny >= miny && _maxy <= maxy) {
  3138. selectedElementList.push(element);
  3139. }
  3140. });
  3141. let finalList = [...selectedElementList];
  3142. selectedElementList.forEach((item) => {
  3143. if (item.hasGroup()) {
  3144. finalList.push(...this.app.group.getGroupElements(item));
  3145. }
  3146. });
  3147. finalList = new Set(finalList);
  3148. finalList = Array.from(finalList);
  3149. this.setMultiSelectElements(finalList, true);
  3150. this.app.render.render();
  3151. }
  3152. checkInResizeHand(x, y) {
  3153. return this.multiSelectElement.dragElement.checkPointInDragElementWhere(
  3154. x,
  3155. y
  3156. );
  3157. }
  3158. checkIsResize(x, y, e) {
  3159. if (!this.hasSelection) {
  3160. return false;
  3161. }
  3162. let hand = this.multiSelectElement.dragElement.checkPointInDragElementWhere(
  3163. x,
  3164. y
  3165. );
  3166. if (hand) {
  3167. this.isResizing = true;
  3168. this.multiSelectElement.startResize(hand, e);
  3169. this.app.cursor.setResize(hand);
  3170. return true;
  3171. }
  3172. return false;
  3173. }
  3174. handleResize(...args) {
  3175. if (!this.isResizing) {
  3176. return;
  3177. }
  3178. this.multiSelectElement.resize(...args);
  3179. this.app.render.render();
  3180. this.multiSelectElement.updateRect();
  3181. this.renderSelection();
  3182. }
  3183. endResize() {
  3184. this.isResizing = false;
  3185. this.multiSelectElement.endResize();
  3186. }
  3187. setSelectedElementStyle(style = {}) {
  3188. if (!this.hasSelectionElements()) {
  3189. return;
  3190. }
  3191. Object.keys(style).forEach((key) => {
  3192. this.getSelectionElements().forEach((element) => {
  3193. element.style[key] = style[key];
  3194. if (key === "fontSize" && element.type === "text") {
  3195. element.updateTextSize();
  3196. this.multiSelectElement.updateRect();
  3197. }
  3198. });
  3199. });
  3200. this.app.render.render();
  3201. this.app.emitChange();
  3202. }
  3203. deleteSelectedElements() {
  3204. this.getSelectionElements().forEach((element) => {
  3205. this.app.elements.deleteElement(element);
  3206. });
  3207. this.selectElements([]);
  3208. this.app.emitChange();
  3209. }
  3210. hasSelectionElements() {
  3211. return this.getSelectionElements().length > 0;
  3212. }
  3213. getSelectionElements() {
  3214. return this.multiSelectElement.selectedElementList;
  3215. }
  3216. copySelectionElements(pos) {
  3217. return __async(this, null, function* () {
  3218. let task = this.getSelectionElements().map((element) => {
  3219. return this.app.elements.copyElement(element, true);
  3220. });
  3221. this.app.group.clearCopyMap();
  3222. let elements = yield Promise.all(task);
  3223. this.setMultiSelectElements(elements);
  3224. if (pos) {
  3225. this.multiSelectElement.startResize(DRAG_ELEMENT_PARTS.BODY);
  3226. let ox = pos.x - this.multiSelectElement.x - this.multiSelectElement.width / 2;
  3227. let oy = pos.y - this.multiSelectElement.y - this.multiSelectElement.height / 2;
  3228. let gridAdsorbentPos = this.app.coordinate.gridAdsorbent(ox, oy);
  3229. this.multiSelectElement.resize(
  3230. null,
  3231. null,
  3232. null,
  3233. gridAdsorbentPos.x,
  3234. gridAdsorbentPos.y
  3235. );
  3236. this.multiSelectElement.endResize();
  3237. this.multiSelectElement.updateRect();
  3238. }
  3239. this.app.render.render();
  3240. this.renderSelection();
  3241. this.app.emitChange();
  3242. });
  3243. }
  3244. selectElements(elements = []) {
  3245. this.hasSelection = elements.length > 0;
  3246. this.setMultiSelectElements(elements);
  3247. this.app.render.render();
  3248. this.renderSelection();
  3249. this.emitChange();
  3250. }
  3251. setMultiSelectElements(elements = [], notUpdateRect) {
  3252. this.multiSelectElement.setSelectedElementList(elements);
  3253. if (!notUpdateRect) {
  3254. this.multiSelectElement.updateRect();
  3255. }
  3256. }
  3257. emitChange() {
  3258. this.app.emit("multiSelectChange", this.getSelectionElements());
  3259. }
  3260. }
  3261. class Grid {
  3262. constructor(app) {
  3263. this.app = app;
  3264. this.canvas = null;
  3265. this.ctx = null;
  3266. this.init();
  3267. this.app.on("zoomChange", this.renderGrid, this);
  3268. this.app.on("scrollChange", this.renderGrid, this);
  3269. }
  3270. init() {
  3271. if (this.canvas) {
  3272. this.app.container.removeChild(this.canvas.el);
  3273. }
  3274. let { width, height } = this.app;
  3275. this.canvas = new Canvas(width, height, {
  3276. className: "grid"
  3277. });
  3278. this.ctx = this.canvas.ctx;
  3279. this.app.container.insertBefore(
  3280. this.canvas.el,
  3281. this.app.container.children[0]
  3282. );
  3283. }
  3284. drawHorizontalLine(i) {
  3285. let { coordinate, width, state } = this.app;
  3286. let _i = coordinate.subScrollY(i);
  3287. this.ctx.beginPath();
  3288. this.ctx.moveTo(-width / state.scale / 2, _i);
  3289. this.ctx.lineTo(width / state.scale / 2, _i);
  3290. this.ctx.stroke();
  3291. }
  3292. renderHorizontalLines() {
  3293. let { coordinate, height, state } = this.app;
  3294. let { gridConfig, scale } = state;
  3295. let maxBottom = 0;
  3296. for (let i = -height / 2; i < height / 2; i += gridConfig.size) {
  3297. this.drawHorizontalLine(i);
  3298. maxBottom = i;
  3299. }
  3300. for (let i = -height / 2 - gridConfig.size; i > -coordinate.subScrollY(height / scale / 2); i -= gridConfig.size) {
  3301. this.drawHorizontalLine(i);
  3302. }
  3303. for (let i = maxBottom + gridConfig.size; i < coordinate.addScrollY(height / scale / 2); i += gridConfig.size) {
  3304. this.drawHorizontalLine(i);
  3305. }
  3306. }
  3307. drawVerticalLine(i) {
  3308. let { coordinate, height, state } = this.app;
  3309. let _i = coordinate.subScrollX(i);
  3310. this.ctx.beginPath();
  3311. this.ctx.moveTo(_i, -height / state.scale / 2);
  3312. this.ctx.lineTo(_i, height / state.scale / 2);
  3313. this.ctx.stroke();
  3314. }
  3315. renderVerticalLines() {
  3316. let { coordinate, width, state } = this.app;
  3317. let { gridConfig, scale } = state;
  3318. let maxRight = 0;
  3319. for (let i = -width / 2; i < width / 2; i += gridConfig.size) {
  3320. this.drawVerticalLine(i);
  3321. maxRight = i;
  3322. }
  3323. for (let i = -width / 2 - gridConfig.size; i > -coordinate.subScrollX(width / scale / 2); i -= gridConfig.size) {
  3324. this.drawVerticalLine(i);
  3325. }
  3326. for (let i = maxRight + gridConfig.size; i < coordinate.addScrollX(width / scale / 2); i += gridConfig.size) {
  3327. this.drawVerticalLine(i);
  3328. }
  3329. }
  3330. renderGrid() {
  3331. this.canvas.clearCanvas();
  3332. let { gridConfig, scale, showGrid } = this.app.state;
  3333. if (!showGrid) {
  3334. return;
  3335. }
  3336. this.ctx.save();
  3337. this.ctx.scale(scale, scale);
  3338. this.ctx.strokeStyle = gridConfig.strokeStyle;
  3339. this.ctx.lineWidth = gridConfig.lineWidth;
  3340. this.renderHorizontalLines();
  3341. this.renderVerticalLines();
  3342. this.ctx.restore();
  3343. }
  3344. showGrid() {
  3345. this.app.updateState({
  3346. showGrid: true
  3347. });
  3348. this.renderGrid();
  3349. }
  3350. hideGrid() {
  3351. this.app.updateState({
  3352. showGrid: false
  3353. });
  3354. this.canvas.clearCanvas();
  3355. }
  3356. updateGrid(config = {}) {
  3357. this.app.updateState({
  3358. gridConfig: __spreadValues(__spreadValues({}, this.app.state.gridConfig), config)
  3359. });
  3360. if (this.app.state.showGrid) {
  3361. this.hideGrid();
  3362. this.showGrid();
  3363. }
  3364. }
  3365. }
  3366. const map = {
  3367. Tab: 9,
  3368. Enter: 13,
  3369. Shift: 16,
  3370. Control: 17,
  3371. Alt: 18,
  3372. CapsLock: 20,
  3373. Esc: 27,
  3374. Space: 32,
  3375. PageUp: 33,
  3376. PageDown: 34,
  3377. End: 35,
  3378. Home: 36,
  3379. Insert: 45,
  3380. Left: 37,
  3381. Up: 38,
  3382. Right: 39,
  3383. Down: 40,
  3384. Del: 46,
  3385. NumLock: 144,
  3386. Cmd: 91,
  3387. CmdFF: 224,
  3388. F1: 112,
  3389. F2: 113,
  3390. F3: 114,
  3391. F4: 115,
  3392. F5: 116,
  3393. F6: 117,
  3394. F7: 118,
  3395. F8: 119,
  3396. F9: 120,
  3397. F10: 121,
  3398. F11: 122,
  3399. F12: 123,
  3400. "`": 192,
  3401. "=": 187,
  3402. "+": 187,
  3403. "-": 189,
  3404. "'": 222,
  3405. "/": 191,
  3406. ".": 190
  3407. };
  3408. for (let i = 0; i <= 9; i++) {
  3409. map[i] = i + 48;
  3410. }
  3411. "abcdefghijklmnopqrstuvwxyz".split("").forEach((n, index) => {
  3412. map[n] = index + 65;
  3413. });
  3414. const keyMap = map;
  3415. class Mode {
  3416. constructor(app) {
  3417. this.app = app;
  3418. this.startScrollX = 0;
  3419. this.startScrollY = 0;
  3420. this.isDragMode = false;
  3421. this.onMove = throttle(this.onMove, this, 16);
  3422. this.bindEvent();
  3423. }
  3424. bindEvent() {
  3425. this.app.event.on("keydown", (e) => {
  3426. if (e.keyCode === keyMap.Space) {
  3427. this.isDragMode = true;
  3428. this.app.cursor.set("grab");
  3429. }
  3430. });
  3431. this.app.event.on("keyup", (e) => {
  3432. if (this.isDragMode) {
  3433. this.isDragMode = false;
  3434. this.app.cursor.set("default");
  3435. }
  3436. });
  3437. }
  3438. setEditMode() {
  3439. this.app.cursor.set("default");
  3440. this.app.updateState({
  3441. readonly: false
  3442. });
  3443. }
  3444. setReadonlyMode() {
  3445. this.app.cursor.set("grab");
  3446. this.app.updateState({
  3447. readonly: true
  3448. });
  3449. }
  3450. onStart() {
  3451. this.startScrollX = this.app.state.scrollX;
  3452. this.startScrollY = this.app.state.scrollY;
  3453. }
  3454. onMove(e, event) {
  3455. this.app.scrollTo(
  3456. this.startScrollX - event.mouseOffset.originX / this.app.state.scale,
  3457. this.startScrollY - event.mouseOffset.originY / this.app.state.scale
  3458. );
  3459. }
  3460. onEnd() {
  3461. this.startScrollX = 0;
  3462. this.startScrollY = 0;
  3463. }
  3464. }
  3465. class KeyCommand {
  3466. constructor(app) {
  3467. this.app = app;
  3468. this.keyMap = keyMap;
  3469. this.shortcutMap = {};
  3470. this.bindEvent();
  3471. }
  3472. bindEvent() {
  3473. this.app.event.on("keydown", this.onKeydown, this);
  3474. }
  3475. unBindEvent() {
  3476. this.app.event.off("keydown", this.onKeydown);
  3477. }
  3478. onKeydown(e) {
  3479. Object.keys(this.shortcutMap).forEach((key) => {
  3480. if (this.checkKey(e, key)) {
  3481. e.stopPropagation();
  3482. e.preventDefault();
  3483. this.shortcutMap[key].forEach((f) => {
  3484. f.fn.call(f.ctx);
  3485. });
  3486. }
  3487. });
  3488. }
  3489. checkKey(e, key) {
  3490. let o = this.getOriginEventCodeArr(e);
  3491. let k = this.getKeyCodeArr(key);
  3492. if (o.length !== k.length) {
  3493. return false;
  3494. }
  3495. for (let i = 0; i < o.length; i++) {
  3496. let index = k.findIndex((item) => {
  3497. return item === o[i];
  3498. });
  3499. if (index === -1) {
  3500. return false;
  3501. } else {
  3502. k.splice(index, 1);
  3503. }
  3504. }
  3505. return true;
  3506. }
  3507. getOriginEventCodeArr(e) {
  3508. let arr = [];
  3509. if (e.ctrlKey || e.metaKey) {
  3510. arr.push(keyMap["Control"]);
  3511. }
  3512. if (e.altKey) {
  3513. arr.push(keyMap["Alt"]);
  3514. }
  3515. if (e.shiftKey) {
  3516. arr.push(keyMap["Shift"]);
  3517. }
  3518. if (!arr.includes(e.keyCode)) {
  3519. arr.push(e.keyCode);
  3520. }
  3521. return arr;
  3522. }
  3523. getKeyCodeArr(key) {
  3524. key = key.replace(/\+\+/, "+add");
  3525. let keyArr = key.split(/\s*\+\s*/).map((item) => {
  3526. return item === "add" ? "+" : item;
  3527. });
  3528. let arr = [];
  3529. keyArr.forEach((item) => {
  3530. arr.push(keyMap[item]);
  3531. });
  3532. return arr;
  3533. }
  3534. addShortcut(key, fn, ctx) {
  3535. key.split(/\s*\|\s*/).forEach((item) => {
  3536. if (this.shortcutMap[item]) {
  3537. this.shortcutMap[item].push({
  3538. fn,
  3539. ctx
  3540. });
  3541. } else {
  3542. this.shortcutMap[item] = [
  3543. {
  3544. fn,
  3545. ctx
  3546. }
  3547. ];
  3548. }
  3549. });
  3550. }
  3551. removeShortcut(key, fn) {
  3552. key.split(/\s*\|\s*/).forEach((item) => {
  3553. if (this.shortcutMap[item]) {
  3554. if (fn) {
  3555. let index = this.shortcutMap[item].findIndex((f) => {
  3556. return f.fn === fn;
  3557. });
  3558. if (index !== -1) {
  3559. this.shortcutMap[item].splice(index, 1);
  3560. }
  3561. } else {
  3562. this.shortcutMap[item] = [];
  3563. delete this.shortcutMap[item];
  3564. }
  3565. }
  3566. });
  3567. }
  3568. }
  3569. class Render {
  3570. constructor(app) {
  3571. this.app = app;
  3572. this.beingCopyActiveElement = null;
  3573. this.beingCopySelectedElements = [];
  3574. this.registerShortcutKeys();
  3575. }
  3576. clearCanvas() {
  3577. let { width, height } = this.app;
  3578. this.app.ctx.clearRect(-width / 2, -height / 2, width, height);
  3579. return this;
  3580. }
  3581. render() {
  3582. let { state } = this.app;
  3583. this.clearCanvas();
  3584. this.app.ctx.save();
  3585. this.app.ctx.scale(state.scale, state.scale);
  3586. this.app.elements.elementList.forEach((element) => {
  3587. if (element.noRender) {
  3588. return;
  3589. }
  3590. element.render();
  3591. });
  3592. this.app.group.render();
  3593. this.app.ctx.restore();
  3594. return this;
  3595. }
  3596. registerShortcutKeys() {
  3597. this.app.keyCommand.addShortcut("Del|Backspace", () => {
  3598. this.deleteCurrentElements();
  3599. });
  3600. this.app.keyCommand.addShortcut("Control+c", () => {
  3601. this.copyCurrentElement();
  3602. });
  3603. this.app.keyCommand.addShortcut("Control+x", () => {
  3604. this.cutCurrentElement();
  3605. });
  3606. this.app.keyCommand.addShortcut("Control+z", () => {
  3607. this.app.history.undo();
  3608. });
  3609. this.app.keyCommand.addShortcut("Control+y", () => {
  3610. this.app.history.redo();
  3611. });
  3612. this.app.keyCommand.addShortcut("Control+v", () => {
  3613. this.pasteCurrentElement(true);
  3614. });
  3615. this.app.keyCommand.addShortcut("Control++", () => {
  3616. this.zoomIn();
  3617. });
  3618. this.app.keyCommand.addShortcut("Control+-", () => {
  3619. this.zoomOut();
  3620. });
  3621. this.app.keyCommand.addShortcut("Shift+1", () => {
  3622. this.fit();
  3623. });
  3624. this.app.keyCommand.addShortcut("Control+a", () => {
  3625. this.selectAll();
  3626. });
  3627. this.app.keyCommand.addShortcut("Control+0", () => {
  3628. this.setZoom(1);
  3629. });
  3630. this.app.keyCommand.addShortcut("Control+'", () => {
  3631. if (this.app.state.showGrid) {
  3632. this.app.grid.hideGrid();
  3633. } else {
  3634. this.app.grid.showGrid();
  3635. }
  3636. });
  3637. }
  3638. copyCurrentElement() {
  3639. if (this.app.elements.activeElement) {
  3640. this.beingCopySelectedElements = [];
  3641. this.beingCopyElement = this.app.elements.activeElement;
  3642. } else if (this.app.selection.hasSelectionElements()) {
  3643. this.beingCopyElement = null;
  3644. this.beingCopySelectedElements = this.app.selection.getSelectionElements();
  3645. }
  3646. }
  3647. cutCurrentElement() {
  3648. if (this.app.elements.activeElement) {
  3649. this.copyCurrentElement();
  3650. this.deleteCurrentElements();
  3651. } else if (this.app.selection.hasSelectionElements()) {
  3652. this.copyCurrentElement();
  3653. this.deleteCurrentElements();
  3654. this.app.selection.setMultiSelectElements(this.beingCopySelectedElements);
  3655. this.app.selection.emitChange();
  3656. }
  3657. }
  3658. pasteCurrentElement(useCurrentEventPos = false) {
  3659. let pos = null;
  3660. if (useCurrentEventPos) {
  3661. let x = this.app.event.lastMousePos.x;
  3662. let y = this.app.event.lastMousePos.y;
  3663. pos = {
  3664. x,
  3665. y
  3666. };
  3667. }
  3668. if (this.beingCopyElement) {
  3669. this.copyElement(this.beingCopyElement, false, pos);
  3670. } else if (this.beingCopySelectedElements.length > 0) {
  3671. this.app.selection.selectElements(this.beingCopySelectedElements);
  3672. this.app.selection.copySelectionElements(useCurrentEventPos ? pos : null);
  3673. }
  3674. }
  3675. deleteElement(element) {
  3676. this.app.elements.deleteElement(element);
  3677. this.render();
  3678. this.app.emitChange();
  3679. }
  3680. copyElement(element, notActive = false, pos) {
  3681. return __async(this, null, function* () {
  3682. this.app.elements.cancelActiveElement();
  3683. yield this.app.elements.copyElement(element, notActive, pos);
  3684. this.app.group.clearCopyMap();
  3685. this.render();
  3686. this.app.emitChange();
  3687. });
  3688. }
  3689. deleteActiveElement() {
  3690. if (!this.app.elements.hasActiveElement()) {
  3691. return;
  3692. }
  3693. this.deleteElement(this.app.elements.activeElement);
  3694. }
  3695. deleteCurrentElements() {
  3696. this.deleteActiveElement();
  3697. this.app.selection.deleteSelectedElements();
  3698. }
  3699. moveUpCurrentElement() {
  3700. this.moveLevelCurrentElement("up");
  3701. }
  3702. moveDownCurrentElement() {
  3703. this.moveLevelCurrentElement("down");
  3704. }
  3705. moveTopCurrentElement() {
  3706. this.moveLevelCurrentElement("top");
  3707. }
  3708. moveBottomCurrentElement() {
  3709. this.moveLevelCurrentElement("bottom");
  3710. }
  3711. moveLevelCurrentElement(level) {
  3712. let element = null;
  3713. if (this.app.elements.hasActiveElement()) {
  3714. element = this.app.elements.activeElement;
  3715. } else if (this.app.selection.getSelectionElements().length === 1) {
  3716. element = this.app.selection.getSelectionElements()[0];
  3717. }
  3718. if (!element) {
  3719. return;
  3720. }
  3721. let index = this.app.elements.getElementIndex(element);
  3722. this.app.elements.elementList.splice(index, 1);
  3723. if (level === "up") {
  3724. this.app.elements.insertElement(element, index + 1);
  3725. } else if (level === "down") {
  3726. this.app.elements.insertElement(element, index - 1);
  3727. } else if (level === "top") {
  3728. this.app.elements.addElement(element);
  3729. } else if (level === "bottom") {
  3730. this.app.elements.unshiftElement(element);
  3731. }
  3732. }
  3733. setActiveElementStyle(style = {}) {
  3734. if (!this.app.elements.hasActiveElement()) {
  3735. return this;
  3736. }
  3737. this.app.elements.setActiveElementStyle(style);
  3738. this.render();
  3739. if (!this.app.elements.isCreatingElement) {
  3740. this.app.emitChange();
  3741. }
  3742. return this;
  3743. }
  3744. setCurrentElementsStyle(style = {}) {
  3745. this.setActiveElementStyle(style);
  3746. this.app.selection.setSelectedElementStyle(style);
  3747. }
  3748. cancelActiveElement() {
  3749. if (!this.app.elements.hasActiveElement()) {
  3750. return this;
  3751. }
  3752. this.app.elements.cancelActiveElement();
  3753. this.render();
  3754. return this;
  3755. }
  3756. updateActiveElementPosition(x, y) {
  3757. if (!this.app.elements.hasActiveElement()) {
  3758. return this;
  3759. }
  3760. this.app.elements.activeElement.updatePos(x, y);
  3761. this.render();
  3762. return this;
  3763. }
  3764. updateActiveElementSize(width, height) {
  3765. if (!this.app.elements.hasActiveElement()) {
  3766. return this;
  3767. }
  3768. this.app.elements.activeElement.updateSize(width, height);
  3769. this.render();
  3770. return this;
  3771. }
  3772. updateActiveElementRotate(rotate) {
  3773. if (!this.app.elements.hasActiveElement()) {
  3774. return this;
  3775. }
  3776. this.app.elements.activeElement.updateRotate(rotate);
  3777. this.render();
  3778. return this;
  3779. }
  3780. empty() {
  3781. this.app.elements.deleteAllElements();
  3782. this.render();
  3783. this.app.history.clear();
  3784. this.app.emitChange();
  3785. }
  3786. zoomIn(num = 0.1) {
  3787. this.app.updateState({
  3788. scale: this.app.state.scale + num
  3789. });
  3790. this.render();
  3791. this.app.emit("zoomChange", this.app.state.scale);
  3792. }
  3793. zoomOut(num = 0.1) {
  3794. this.app.updateState({
  3795. scale: this.app.state.scale - num > 0 ? this.app.state.scale - num : 0
  3796. });
  3797. this.render();
  3798. this.app.emit("zoomChange", this.app.state.scale);
  3799. }
  3800. setZoom(zoom) {
  3801. if (zoom < 0) {
  3802. return;
  3803. }
  3804. this.app.updateState({
  3805. scale: zoom
  3806. });
  3807. this.render();
  3808. this.app.emit("zoomChange", this.app.state.scale);
  3809. }
  3810. fit() {
  3811. if (!this.app.elements.hasElements()) {
  3812. return;
  3813. }
  3814. this.scrollToCenter();
  3815. let { minx, maxx, miny, maxy } = getMultiElementRectInfo(
  3816. this.app.elements.elementList
  3817. );
  3818. let width = maxx - minx;
  3819. let height = maxy - miny;
  3820. let maxScale = Math.min(this.app.width / width, this.app.height / height);
  3821. console.log(maxScale);
  3822. this.setZoom(maxScale);
  3823. }
  3824. scrollTo(scrollX, scrollY) {
  3825. this.app.updateState({
  3826. scrollX,
  3827. scrollY
  3828. });
  3829. this.render();
  3830. this.app.emit(
  3831. "scrollChange",
  3832. this.app.state.scrollX,
  3833. this.app.state.scrollY
  3834. );
  3835. }
  3836. scrollToCenter() {
  3837. if (!this.app.elements.hasElements()) {
  3838. this.scrollTo(0, 0);
  3839. return;
  3840. }
  3841. let { minx, maxx, miny, maxy } = getMultiElementRectInfo(
  3842. this.app.elements.elementList
  3843. );
  3844. let width = maxx - minx;
  3845. let height = maxy - miny;
  3846. this.scrollTo(
  3847. minx - (this.app.width - width) / 2,
  3848. miny - (this.app.height - height) / 2
  3849. );
  3850. }
  3851. copyPasteCurrentElements() {
  3852. this.copyCurrentElement();
  3853. this.pasteCurrentElement();
  3854. }
  3855. setBackgroundColor(color) {
  3856. this.app.updateState({
  3857. backgroundColor: color
  3858. });
  3859. this.app.background.set();
  3860. }
  3861. selectAll() {
  3862. this.app.selection.selectElements(this.app.elements.elementList);
  3863. }
  3864. }
  3865. class Elements {
  3866. constructor(app) {
  3867. this.app = app;
  3868. this.elementList = [];
  3869. this.activeElement = null;
  3870. this.isCreatingElement = false;
  3871. this.isResizing = false;
  3872. this.resizingElement = null;
  3873. this.handleResize = throttle(this.handleResize, this, 16);
  3874. }
  3875. serialize(stringify = false) {
  3876. let data = this.elementList.map((element) => {
  3877. return element.serialize();
  3878. });
  3879. return stringify ? JSON.stringify(data) : data;
  3880. }
  3881. getElementsNum() {
  3882. return this.elementList.length;
  3883. }
  3884. hasElements() {
  3885. return this.elementList.length > 0;
  3886. }
  3887. addElement(element) {
  3888. this.elementList.push(element);
  3889. return this;
  3890. }
  3891. unshiftElement(element) {
  3892. this.elementList.unshift(element);
  3893. return this;
  3894. }
  3895. insertElement(element, index) {
  3896. this.elementList.splice(index, 0, element);
  3897. }
  3898. deleteElement(element) {
  3899. let index = this.getElementIndex(element);
  3900. if (index !== -1) {
  3901. this.elementList.splice(index, 1);
  3902. if (element.isActive) {
  3903. this.cancelActiveElement(element);
  3904. }
  3905. }
  3906. return this;
  3907. }
  3908. deleteAllElements() {
  3909. this.activeElement = null;
  3910. this.elementList = [];
  3911. this.isCreatingElement = false;
  3912. this.isResizing = false;
  3913. this.resizingElement = null;
  3914. return this;
  3915. }
  3916. getElementIndex(element) {
  3917. return this.elementList.findIndex((item) => {
  3918. return item === element;
  3919. });
  3920. }
  3921. createElementsFromData(data) {
  3922. data.forEach((item) => {
  3923. let element = this.pureCreateElement(item);
  3924. element.isActive = false;
  3925. element.isCreating = false;
  3926. this.addElement(element);
  3927. });
  3928. this.app.group.initIdToElementList(this.elementList);
  3929. return this;
  3930. }
  3931. hasActiveElement() {
  3932. return !!this.activeElement;
  3933. }
  3934. setActiveElement(element) {
  3935. this.cancelActiveElement();
  3936. this.activeElement = element;
  3937. if (element) {
  3938. element.isActive = true;
  3939. }
  3940. this.app.emit("activeElementChange", this.activeElement);
  3941. return this;
  3942. }
  3943. cancelActiveElement() {
  3944. if (!this.hasActiveElement()) {
  3945. return this;
  3946. }
  3947. this.activeElement.isActive = false;
  3948. this.activeElement = null;
  3949. this.app.emit("activeElementChange", this.activeElement);
  3950. return this;
  3951. }
  3952. checkIsHitElement(e) {
  3953. let x = e.unGridClientX;
  3954. let y = e.unGridClientY;
  3955. for (let i = this.elementList.length - 1; i >= 0; i--) {
  3956. let element = this.elementList[i];
  3957. if (element.isHit(x, y)) {
  3958. return element;
  3959. }
  3960. }
  3961. return null;
  3962. }
  3963. pureCreateElement(opts = {}) {
  3964. switch (opts.type) {
  3965. case "rectangle":
  3966. return new Rectangle(opts, this.app);
  3967. case "diamond":
  3968. return new Diamond(opts, this.app);
  3969. case "triangle":
  3970. return new Triangle(opts, this.app);
  3971. case "circle":
  3972. return new Circle(opts, this.app);
  3973. case "freedraw":
  3974. return new Freedraw(opts, this.app);
  3975. case "image":
  3976. return new Image$1(opts, this.app);
  3977. case "arrow":
  3978. return new Arrow(opts, this.app);
  3979. case "line":
  3980. return new Line(opts, this.app);
  3981. case "text":
  3982. return new Text(opts, this.app);
  3983. default:
  3984. return null;
  3985. }
  3986. }
  3987. createElement(opts = {}, callback = () => {
  3988. }, ctx = null, notActive) {
  3989. if (this.hasActiveElement() || this.isCreatingElement) {
  3990. return this;
  3991. }
  3992. let element = this.pureCreateElement(opts);
  3993. if (!element) {
  3994. return this;
  3995. }
  3996. this.addElement(element);
  3997. if (!notActive) {
  3998. this.setActiveElement(element);
  3999. }
  4000. this.isCreatingElement = true;
  4001. callback.call(ctx, element);
  4002. return this;
  4003. }
  4004. copyElement(element, notActive = false, pos) {
  4005. return new Promise((resolve) => __async(this, null, function* () {
  4006. if (!element) {
  4007. return resolve();
  4008. }
  4009. let data = this.app.group.handleCopyElementData(element.serialize());
  4010. if (data.type === "image") {
  4011. data.imageObj = yield createImageObj(data.url);
  4012. }
  4013. if (data.type === "text") {
  4014. if (typeof data.text === "string") {
  4015. if (isNumeric(data.text)) {
  4016. const num = parseFloat(data.text);
  4017. const incrementedNum = num + 1;
  4018. data.text = incrementedNum.toString(10).padStart(data.text.length, "0");
  4019. }
  4020. }
  4021. }
  4022. this.createElement(
  4023. data,
  4024. (element2) => {
  4025. this.app.group.handleCopyElement(element2);
  4026. element2.startResize(DRAG_ELEMENT_PARTS.BODY);
  4027. let ox = 20;
  4028. let oy = 20;
  4029. if (pos) {
  4030. ox = pos.x - element2.x - element2.width / 2;
  4031. oy = pos.y - element2.y - element2.height / 2;
  4032. }
  4033. let gridAdsorbentPos = this.app.coordinate.gridAdsorbent(ox, oy);
  4034. element2.resize(
  4035. null,
  4036. null,
  4037. null,
  4038. gridAdsorbentPos.x,
  4039. gridAdsorbentPos.y
  4040. );
  4041. element2.isCreating = false;
  4042. if (notActive) {
  4043. element2.isActive = false;
  4044. }
  4045. this.isCreatingElement = false;
  4046. resolve(element2);
  4047. },
  4048. this,
  4049. notActive
  4050. );
  4051. }));
  4052. }
  4053. creatingRectangleLikeElement(type, x, y, offsetX, offsetY) {
  4054. this.createElement({
  4055. type,
  4056. x,
  4057. y,
  4058. width: offsetX,
  4059. height: offsetY
  4060. });
  4061. this.activeElement.updateSize(offsetX, offsetY);
  4062. }
  4063. creatingCircle(x, y, e) {
  4064. this.createElement({
  4065. type: "circle",
  4066. x,
  4067. y
  4068. });
  4069. let radius = getTowPointDistance(e.clientX, e.clientY, x, y);
  4070. this.activeElement.updateSize(radius, radius);
  4071. }
  4072. creatingFreedraw(e, event) {
  4073. this.createElement({
  4074. type: "freedraw"
  4075. });
  4076. let element = this.activeElement;
  4077. let lineWidth = computedLineWidthBySpeed(
  4078. event.mouseSpeed,
  4079. element.lastLineWidth
  4080. );
  4081. element.lastLineWidth = lineWidth;
  4082. element.addPoint(e.clientX, e.clientY, lineWidth);
  4083. let { coordinate, ctx, state } = this.app;
  4084. let tfp = coordinate.transformToCanvasCoordinate(
  4085. coordinate.subScrollX(event.lastMousePos.x),
  4086. coordinate.subScrollY(event.lastMousePos.y)
  4087. );
  4088. let ttp = coordinate.transformToCanvasCoordinate(
  4089. coordinate.subScrollX(e.clientX),
  4090. coordinate.subScrollY(e.clientY)
  4091. );
  4092. ctx.save();
  4093. ctx.scale(state.scale, state.scale);
  4094. element.singleRender(tfp.x, tfp.y, ttp.x, ttp.y, lineWidth);
  4095. ctx.restore();
  4096. }
  4097. creatingImage(e, { width, height, imageObj, url, ratio }) {
  4098. let gp = this.app.coordinate.gridAdsorbent(
  4099. e.unGridClientX - width / 2,
  4100. e.unGridClientY - height / 2
  4101. );
  4102. this.createElement({
  4103. type: "image",
  4104. x: gp.x,
  4105. y: gp.y,
  4106. url,
  4107. imageObj,
  4108. width,
  4109. height,
  4110. ratio
  4111. });
  4112. }
  4113. editingText(element) {
  4114. if (element.type !== "text") {
  4115. return;
  4116. }
  4117. element.noRender = true;
  4118. this.setActiveElement(element);
  4119. }
  4120. completeEditingText() {
  4121. let element = this.activeElement;
  4122. if (!element || element.type !== "text") {
  4123. return;
  4124. }
  4125. if (!element.text.trim()) {
  4126. this.deleteElement(element);
  4127. this.setActiveElement(null);
  4128. return;
  4129. }
  4130. element.noRender = false;
  4131. }
  4132. completeCreateArrow(e) {
  4133. this.activeElement.addPoint(e.clientX, e.clientY);
  4134. }
  4135. creatingArrow(x, y, e) {
  4136. this.createElement(
  4137. {
  4138. type: "arrow",
  4139. x,
  4140. y
  4141. },
  4142. (element) => {
  4143. element.addPoint(x, y);
  4144. }
  4145. );
  4146. this.activeElement.updateFictitiousPoint(e.clientX, e.clientY);
  4147. }
  4148. creatingLine(x, y, e, isSingle = false, notCreate = false) {
  4149. if (!notCreate) {
  4150. this.createElement(
  4151. {
  4152. type: "line",
  4153. x,
  4154. y,
  4155. isSingle
  4156. },
  4157. (element2) => {
  4158. element2.addPoint(x, y);
  4159. }
  4160. );
  4161. }
  4162. let element = this.activeElement;
  4163. if (element) {
  4164. element.updateFictitiousPoint(e.clientX, e.clientY);
  4165. }
  4166. }
  4167. completeCreateLine(e, completeCallback = () => {
  4168. }) {
  4169. let element = this.activeElement;
  4170. let x = e.clientX;
  4171. let y = e.clientY;
  4172. if (element && element.isSingle) {
  4173. element.addPoint(x, y);
  4174. completeCallback();
  4175. } else {
  4176. this.createElement({
  4177. type: "line",
  4178. isSingle: false
  4179. });
  4180. element = this.activeElement;
  4181. element.addPoint(x, y);
  4182. element.updateFictitiousPoint(x, y);
  4183. }
  4184. }
  4185. completeCreateElement() {
  4186. this.isCreatingElement = false;
  4187. let element = this.activeElement;
  4188. if (!element) {
  4189. return this;
  4190. }
  4191. if (["freedraw", "arrow", "line"].includes(element.type)) {
  4192. element.updateMultiPointBoundingRect();
  4193. }
  4194. element.isCreating = false;
  4195. this.app.emitChange();
  4196. return this;
  4197. }
  4198. setActiveElementStyle(style = {}) {
  4199. if (!this.hasActiveElement()) {
  4200. return this;
  4201. }
  4202. Object.keys(style).forEach((key) => {
  4203. this.activeElement.style[key] = style[key];
  4204. if (key === "fontSize" && this.activeElement.type === "text") {
  4205. this.activeElement.updateTextSize();
  4206. }
  4207. });
  4208. return this;
  4209. }
  4210. checkInResizeHand(x, y) {
  4211. let element = this.activeElement;
  4212. let hand = element.dragElement.checkPointInDragElementWhere(x, y);
  4213. if (hand) {
  4214. return {
  4215. element,
  4216. hand
  4217. };
  4218. }
  4219. return null;
  4220. }
  4221. checkIsResize(x, y, e) {
  4222. if (!this.hasActiveElement()) {
  4223. return false;
  4224. }
  4225. let res = this.checkInResizeHand(x, y);
  4226. if (res) {
  4227. this.isResizing = true;
  4228. this.resizingElement = res.element;
  4229. this.resizingElement.startResize(res.hand, e);
  4230. this.app.cursor.setResize(res.hand);
  4231. return true;
  4232. }
  4233. return false;
  4234. }
  4235. handleResize(...args) {
  4236. if (!this.isResizing) {
  4237. return;
  4238. }
  4239. this.resizingElement.resize(...args);
  4240. this.app.render.render();
  4241. }
  4242. endResize() {
  4243. this.isResizing = false;
  4244. this.resizingElement.endResize();
  4245. this.resizingElement = null;
  4246. }
  4247. }
  4248. function isNumeric(str) {
  4249. const trimmedStr = str.trim();
  4250. const num = Number(trimmedStr);
  4251. return !isNaN(num) && trimmedStr === num.toString().padStart(trimmedStr.length, "0");
  4252. }
  4253. let getRandomValues;
  4254. const rnds8 = new Uint8Array(16);
  4255. function rng() {
  4256. if (!getRandomValues) {
  4257. getRandomValues = typeof crypto !== "undefined" && crypto.getRandomValues && crypto.getRandomValues.bind(crypto);
  4258. if (!getRandomValues) {
  4259. throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");
  4260. }
  4261. }
  4262. return getRandomValues(rnds8);
  4263. }
  4264. const byteToHex = [];
  4265. for (let i = 0; i < 256; ++i) {
  4266. byteToHex.push((i + 256).toString(16).slice(1));
  4267. }
  4268. function unsafeStringify(arr, offset = 0) {
  4269. return byteToHex[arr[offset + 0]] + byteToHex[arr[offset + 1]] + byteToHex[arr[offset + 2]] + byteToHex[arr[offset + 3]] + "-" + byteToHex[arr[offset + 4]] + byteToHex[arr[offset + 5]] + "-" + byteToHex[arr[offset + 6]] + byteToHex[arr[offset + 7]] + "-" + byteToHex[arr[offset + 8]] + byteToHex[arr[offset + 9]] + "-" + byteToHex[arr[offset + 10]] + byteToHex[arr[offset + 11]] + byteToHex[arr[offset + 12]] + byteToHex[arr[offset + 13]] + byteToHex[arr[offset + 14]] + byteToHex[arr[offset + 15]];
  4270. }
  4271. const randomUUID = typeof crypto !== "undefined" && crypto.randomUUID && crypto.randomUUID.bind(crypto);
  4272. var native = {
  4273. randomUUID
  4274. };
  4275. function v4(options, buf, offset) {
  4276. if (native.randomUUID && !buf && !options) {
  4277. return native.randomUUID();
  4278. }
  4279. options = options || {};
  4280. const rnds = options.random || (options.rng || rng)();
  4281. rnds[6] = rnds[6] & 15 | 64;
  4282. rnds[8] = rnds[8] & 63 | 128;
  4283. if (buf) {
  4284. offset = offset || 0;
  4285. for (let i = 0; i < 16; ++i) {
  4286. buf[offset + i] = rnds[i];
  4287. }
  4288. return buf;
  4289. }
  4290. return unsafeStringify(rnds);
  4291. }
  4292. class Group {
  4293. constructor(app) {
  4294. this.app = app;
  4295. this.groupIdToElementList = {};
  4296. this.newGroupIdMap = {};
  4297. }
  4298. render() {
  4299. Object.keys(this.groupIdToElementList).forEach((groupId) => {
  4300. let group = this.groupIdToElementList[groupId];
  4301. let selected = group[0].isSelected;
  4302. if (selected) {
  4303. let mElement = new MultiSelectElement(
  4304. {
  4305. type: "multiSelectElement"
  4306. },
  4307. this.app
  4308. );
  4309. mElement.setSelectedElementList(group);
  4310. mElement.updateRect();
  4311. mElement.dragElement.onlyShowBody();
  4312. mElement.render();
  4313. }
  4314. });
  4315. }
  4316. setToMap(element) {
  4317. let groupId = element.getGroupId();
  4318. if (groupId) {
  4319. if (!this.groupIdToElementList[groupId]) {
  4320. this.groupIdToElementList[groupId] = [];
  4321. }
  4322. this.groupIdToElementList[groupId].push(element);
  4323. }
  4324. }
  4325. initIdToElementList(elementList) {
  4326. this.groupIdToElementList = {};
  4327. elementList.forEach((element) => {
  4328. this.setToMap(element);
  4329. });
  4330. }
  4331. handleCopyElementData(data) {
  4332. if (data.groupId) {
  4333. if (this.newGroupIdMap[data.groupId]) {
  4334. data.groupId = this.newGroupIdMap[data.groupId];
  4335. } else {
  4336. data.groupId = this.newGroupIdMap[data.groupId] = v4();
  4337. }
  4338. }
  4339. return data;
  4340. }
  4341. clearCopyMap() {
  4342. this.newGroupIdMap = {};
  4343. }
  4344. handleCopyElement(element) {
  4345. this.setToMap(element);
  4346. }
  4347. dogroup() {
  4348. if (!this.app.selection.hasSelection || this.app.selection.multiSelectElement.selectedElementList.length <= 1) {
  4349. return;
  4350. }
  4351. let groupElement = this.app.selection.multiSelectElement.selectedElementList;
  4352. let groupId = v4();
  4353. this.groupIdToElementList[groupId] = groupElement;
  4354. groupElement.forEach((element) => {
  4355. element.setGroupId(groupId);
  4356. });
  4357. this.app.render.render();
  4358. this.app.emitChange();
  4359. }
  4360. ungroup() {
  4361. if (!this.app.selection.hasSelection || this.app.selection.multiSelectElement.selectedElementList.length <= 1) {
  4362. return;
  4363. }
  4364. let groupElement = this.app.selection.multiSelectElement.selectedElementList;
  4365. let groupId = groupElement[0].getGroupId();
  4366. this.groupIdToElementList[groupId] = [];
  4367. delete this.groupIdToElementList[groupId];
  4368. groupElement.forEach((element) => {
  4369. element.removeGroupId(groupId);
  4370. });
  4371. this.app.render.render();
  4372. this.app.emitChange();
  4373. }
  4374. setSelection(element) {
  4375. let groupId = element.getGroupId();
  4376. if (this.groupIdToElementList[groupId]) {
  4377. this.app.selection.selectElements(this.groupIdToElementList[groupId]);
  4378. }
  4379. }
  4380. getGroupElements(element) {
  4381. let groupId = element.getGroupId();
  4382. return this.groupIdToElementList[groupId] || [];
  4383. }
  4384. }
  4385. class TinyWhiteboard extends EventEmitter {
  4386. constructor(opts = {}) {
  4387. super();
  4388. this.opts = opts;
  4389. this.container = opts.container;
  4390. this.drawType = opts.drawType || "selection";
  4391. if (!this.container) {
  4392. throw new Error("\u7F3A\u5C11 container \u53C2\u6570\uFF01");
  4393. }
  4394. if (!["absolute", "fixed", "relative"].includes(
  4395. window.getComputedStyle(this.container).position
  4396. )) {
  4397. throw new Error("container\u5143\u7D20\u9700\u8981\u8BBE\u7F6E\u5B9A\u4F4D\uFF01");
  4398. }
  4399. this.width = 0;
  4400. this.height = 0;
  4401. this.left = 0;
  4402. this.top = 0;
  4403. this.canvas = null;
  4404. this.ctx = null;
  4405. this.state = __spreadValues({
  4406. scale: 1,
  4407. scrollX: 0,
  4408. scrollY: 0,
  4409. scrollStep: 50,
  4410. backgroundColor: "",
  4411. strokeStyle: "#000000",
  4412. fillStyle: "transparent",
  4413. fontFamily: "\u5FAE\u8F6F\u96C5\u9ED1, Microsoft YaHei",
  4414. fontSize: 18,
  4415. dragStrokeStyle: "#666",
  4416. showGrid: false,
  4417. readonly: false,
  4418. gridConfig: {
  4419. size: 20,
  4420. strokeStyle: "#dfe0e1",
  4421. lineWidth: 1
  4422. }
  4423. }, opts.state || {});
  4424. this.initCanvas();
  4425. this.coordinate = new Coordinate(this);
  4426. this.event = new Event(this);
  4427. this.event.on("mousedown", this.onMousedown, this);
  4428. this.event.on("mousemove", this.onMousemove, this);
  4429. this.event.on("mouseup", this.onMouseup, this);
  4430. this.event.on("dblclick", this.onDblclick, this);
  4431. this.event.on("mousewheel", this.onMousewheel, this);
  4432. this.event.on("contextmenu", this.onContextmenu, this);
  4433. this.keyCommand = new KeyCommand(this);
  4434. this.imageEdit = new ImageEdit(this);
  4435. this.imageEdit.on("imageSelectChange", this.onImageSelectChange, this);
  4436. this.textEdit = new TextEdit(this);
  4437. this.textEdit.on("blur", this.onTextInputBlur, this);
  4438. this.cursor = new Cursor(this);
  4439. this.history = new History(this);
  4440. this.export = new Export(this);
  4441. this.background = new Background(this);
  4442. this.selection = new Selection(this);
  4443. this.group = new Group(this);
  4444. this.grid = new Grid(this);
  4445. this.mode = new Mode(this);
  4446. this.elements = new Elements$1(this);
  4447. this.render = new Render(this);
  4448. this.proxy();
  4449. this.checkIsOnElement = throttle(this.checkIsOnElement, this);
  4450. this.emitChange();
  4451. this.helpUpdate();
  4452. }
  4453. proxy() {
  4454. ["undo", "redo"].forEach((method) => {
  4455. this[method] = this.history[method].bind(this.history);
  4456. });
  4457. [].forEach((method) => {
  4458. this[method] = this.elements[method].bind(this.elements);
  4459. });
  4460. [
  4461. "deleteElement",
  4462. "setActiveElementStyle",
  4463. "setCurrentElementsStyle",
  4464. "cancelActiveElement",
  4465. "deleteActiveElement",
  4466. "deleteCurrentElements",
  4467. "empty",
  4468. "zoomIn",
  4469. "zoomOut",
  4470. "setZoom",
  4471. "scrollTo",
  4472. "scrollToCenter",
  4473. "copyPasteCurrentElements",
  4474. "setBackgroundColor",
  4475. "copyElement",
  4476. "copyCurrentElement",
  4477. "cutCurrentElement",
  4478. "pasteCurrentElement",
  4479. "updateActiveElementRotate",
  4480. "updateActiveElementSize",
  4481. "updateActiveElementPosition",
  4482. "moveBottomCurrentElement",
  4483. "moveTopCurrentElement",
  4484. "moveUpCurrentElement",
  4485. "moveDownCurrentElement",
  4486. "selectAll",
  4487. "fit"
  4488. ].forEach((method) => {
  4489. this[method] = this.render[method].bind(this.render);
  4490. });
  4491. ["exportImage", "exportJson"].forEach((method) => {
  4492. this[method] = this.export[method].bind(this.export);
  4493. });
  4494. ["setSelectedElementStyle"].forEach((method) => {
  4495. this[method] = this.selection[method].bind(this.selection);
  4496. });
  4497. ["dogroup", "ungroup"].forEach((method) => {
  4498. this[method] = this.group[method].bind(this.group);
  4499. });
  4500. ["showGrid", "hideGrid", "updateGrid"].forEach((method) => {
  4501. this[method] = this.grid[method].bind(this.grid);
  4502. });
  4503. ["setEditMode", "setReadonlyMode"].forEach((method) => {
  4504. this[method] = this.mode[method].bind(this.mode);
  4505. });
  4506. }
  4507. getContainerRectInfo() {
  4508. let { width, height, left, top } = this.container.getBoundingClientRect();
  4509. this.width = width;
  4510. this.height = height;
  4511. this.left = left;
  4512. this.top = top;
  4513. }
  4514. helpUpdate() {
  4515. this.background.set();
  4516. if (this.state.showGrid) {
  4517. this.grid.showGrid();
  4518. }
  4519. if (this.state.readonly) {
  4520. this.setReadonlyMode();
  4521. }
  4522. }
  4523. setData(_0, _1) {
  4524. return __async(this, arguments, function* ({ state = {}, elements = [] }, noEmitChange) {
  4525. this.state = state;
  4526. for (let i = 0; i < elements.length; i++) {
  4527. if (elements[i].type === "image") {
  4528. elements[i].imageObj = yield createImageObj(elements[i].url);
  4529. }
  4530. }
  4531. this.helpUpdate();
  4532. this.elements.deleteAllElements().createElementsFromData(elements);
  4533. this.render.render();
  4534. if (!noEmitChange) {
  4535. this.emitChange();
  4536. }
  4537. });
  4538. }
  4539. initCanvas() {
  4540. this.getContainerRectInfo();
  4541. if (this.canvas) {
  4542. this.container.removeChild(this.canvas);
  4543. }
  4544. let { canvas, ctx } = createCanvas(this.width, this.height, {
  4545. className: "main"
  4546. });
  4547. this.canvas = canvas;
  4548. this.ctx = ctx;
  4549. this.container.appendChild(this.canvas);
  4550. }
  4551. resize() {
  4552. this.initCanvas();
  4553. this.render.render();
  4554. this.selection.init();
  4555. this.grid.init();
  4556. this.grid.renderGrid();
  4557. }
  4558. updateState(data = {}) {
  4559. this.state = __spreadValues(__spreadValues({}, this.state), data);
  4560. this.emitChange();
  4561. }
  4562. updateCurrentType(drawType) {
  4563. this.drawType = drawType;
  4564. if (this.drawType === "image") {
  4565. this.imageEdit.selectImage();
  4566. }
  4567. if (this.drawType === "eraser") {
  4568. this.cursor.setEraser();
  4569. this.cancelActiveElement();
  4570. } else if (this.drawType !== "selection") {
  4571. this.cursor.setCrosshair();
  4572. } else {
  4573. this.cursor.reset();
  4574. }
  4575. this.emit("currentTypeChange", this.drawType);
  4576. }
  4577. getData() {
  4578. return {
  4579. state: __spreadValues({}, this.state),
  4580. elements: this.elements.serialize()
  4581. };
  4582. }
  4583. onImageSelectChange() {
  4584. this.cursor.hide();
  4585. }
  4586. onMousedown(e, event) {
  4587. if (this.state.readonly || this.mode.isDragMode) {
  4588. this.mode.onStart();
  4589. return;
  4590. }
  4591. if (!this.elements.isCreatingElement && !this.textEdit.isEditing) {
  4592. let hitElement = this.elements.checkIsHitElement(e);
  4593. if (this.drawType === "selection") {
  4594. if (this.elements.hasActiveElement()) {
  4595. let isResizing = this.elements.checkIsResize(
  4596. event.mousedownPos.unGridClientX,
  4597. event.mousedownPos.unGridClientY,
  4598. e
  4599. );
  4600. if (!isResizing) {
  4601. this.elements.setActiveElement(hitElement);
  4602. this.render.render();
  4603. }
  4604. } else {
  4605. if (this.selection.hasSelection) {
  4606. let isResizing = this.selection.checkIsResize(
  4607. event.mousedownPos.unGridClientX,
  4608. event.mousedownPos.unGridClientY,
  4609. e
  4610. );
  4611. if (!isResizing) {
  4612. this.selection.reset();
  4613. this.elements.setActiveElement(hitElement);
  4614. this.render.render();
  4615. }
  4616. } else if (hitElement) {
  4617. if (hitElement.hasGroup()) {
  4618. this.group.setSelection(hitElement);
  4619. this.onMousedown(e, event);
  4620. } else {
  4621. this.elements.setActiveElement(hitElement);
  4622. this.render.render();
  4623. this.onMousedown(e, event);
  4624. }
  4625. } else {
  4626. this.selection.onMousedown(e, event);
  4627. }
  4628. }
  4629. } else if (this.drawType === "eraser") {
  4630. this.deleteElement(hitElement);
  4631. }
  4632. }
  4633. }
  4634. onMousemove(e, event) {
  4635. if (this.state.readonly || this.mode.isDragMode) {
  4636. if (event.isMousedown) {
  4637. this.mode.onMove(e, event);
  4638. }
  4639. return;
  4640. }
  4641. if (event.isMousedown) {
  4642. let mx = event.mousedownPos.x;
  4643. let my = event.mousedownPos.y;
  4644. let offsetX = Math.max(event.mouseOffset.x, 0);
  4645. let offsetY = Math.max(event.mouseOffset.y, 0);
  4646. if (this.drawType === "selection") {
  4647. if (this.selection.isResizing) {
  4648. this.selection.handleResize(
  4649. e,
  4650. mx,
  4651. my,
  4652. event.mouseOffset.x,
  4653. event.mouseOffset.y
  4654. );
  4655. } else if (this.selection.creatingSelection) {
  4656. this.selection.onMousemove(e, event);
  4657. } else {
  4658. this.elements.handleResize(
  4659. e,
  4660. mx,
  4661. my,
  4662. event.mouseOffset.x,
  4663. event.mouseOffset.y
  4664. );
  4665. }
  4666. } else if (["rectangle", "diamond", "triangle"].includes(this.drawType)) {
  4667. this.elements.creatingRectangleLikeElement(
  4668. this.drawType,
  4669. mx,
  4670. my,
  4671. offsetX,
  4672. offsetY
  4673. );
  4674. this.render.render();
  4675. } else if (this.drawType === "circle") {
  4676. this.elements.creatingCircle(mx, my, e);
  4677. this.render.render();
  4678. } else if (this.drawType === "freedraw") {
  4679. this.elements.creatingFreedraw(e, event);
  4680. } else if (this.drawType === "arrow") {
  4681. this.elements.creatingArrow(mx, my, e);
  4682. this.render.render();
  4683. } else if (this.drawType === "line") {
  4684. if (getTowPointDistance(mx, my, e.clientX, e.clientY) > 3) {
  4685. this.elements.creatingLine(mx, my, e, true);
  4686. this.render.render();
  4687. }
  4688. }
  4689. } else {
  4690. if (this.imageEdit.isReady) {
  4691. this.cursor.hide();
  4692. this.imageEdit.updatePreviewElPos(
  4693. e.originEvent.clientX,
  4694. e.originEvent.clientY
  4695. );
  4696. } else if (this.drawType === "selection") {
  4697. if (this.elements.hasActiveElement()) {
  4698. let handData = "";
  4699. if (handData = this.elements.checkInResizeHand(
  4700. e.unGridClientX,
  4701. e.unGridClientY
  4702. )) {
  4703. this.cursor.setResize(handData.hand);
  4704. } else {
  4705. this.checkIsOnElement(e);
  4706. }
  4707. } else if (this.selection.hasSelection) {
  4708. let hand = this.selection.checkInResizeHand(
  4709. e.unGridClientX,
  4710. e.unGridClientY
  4711. );
  4712. if (hand) {
  4713. this.cursor.setResize(hand);
  4714. } else {
  4715. this.checkIsOnElement(e);
  4716. }
  4717. } else {
  4718. this.checkIsOnElement(e);
  4719. }
  4720. } else if (this.drawType === "line") {
  4721. this.elements.creatingLine(null, null, e, false, true);
  4722. this.render.render();
  4723. }
  4724. }
  4725. }
  4726. checkIsOnElement(e) {
  4727. let hitElement = this.elements.checkIsHitElement(e);
  4728. if (hitElement) {
  4729. this.cursor.setMove();
  4730. } else {
  4731. this.cursor.reset();
  4732. }
  4733. }
  4734. resetCurrentType() {
  4735. if (this.drawType !== "selection") {
  4736. this.drawType = "selection";
  4737. this.emit("currentTypeChange", "selection");
  4738. }
  4739. }
  4740. completeCreateNewElement() {
  4741. this.resetCurrentType();
  4742. this.elements.completeCreateElement();
  4743. this.render.render();
  4744. }
  4745. onMouseup(e) {
  4746. if (this.state.readonly || this.mode.isDragMode) {
  4747. return;
  4748. }
  4749. if (this.drawType === "text") {
  4750. if (!this.textEdit.isEditing) {
  4751. this.createTextElement(e);
  4752. this.resetCurrentType();
  4753. }
  4754. } else if (this.imageEdit.isReady) {
  4755. this.elements.creatingImage(e, this.imageEdit.imageData);
  4756. this.completeCreateNewElement();
  4757. this.cursor.reset();
  4758. this.imageEdit.reset();
  4759. } else if (this.drawType === "arrow") {
  4760. this.elements.completeCreateArrow(e);
  4761. this.completeCreateNewElement();
  4762. } else if (this.drawType === "line") {
  4763. this.elements.completeCreateLine(e, () => {
  4764. this.completeCreateNewElement();
  4765. });
  4766. this.render.render();
  4767. } else if (this.elements.isCreatingElement) {
  4768. if (this.drawType === "freedraw") {
  4769. this.elements.completeCreateElement();
  4770. this.elements.setActiveElement();
  4771. } else {
  4772. this.completeCreateNewElement();
  4773. }
  4774. } else if (this.elements.isResizing) {
  4775. this.elements.endResize();
  4776. this.emitChange();
  4777. } else if (this.selection.creatingSelection) {
  4778. this.selection.onMouseup(e);
  4779. } else if (this.selection.isResizing) {
  4780. this.selection.endResize();
  4781. this.emitChange();
  4782. }
  4783. }
  4784. onDblclick(e) {
  4785. if (this.drawType === "line") {
  4786. this.completeCreateNewElement();
  4787. } else {
  4788. let hitElement = this.elements.checkIsHitElement(e);
  4789. if (hitElement) {
  4790. if (hitElement.type === "text") {
  4791. this.elements.editingText(hitElement);
  4792. this.render.render();
  4793. this.keyCommand.unBindEvent();
  4794. this.textEdit.showTextEdit();
  4795. }
  4796. } else {
  4797. if (!this.textEdit.isEditing) {
  4798. this.createTextElement(e);
  4799. }
  4800. }
  4801. }
  4802. }
  4803. onTextInputBlur() {
  4804. this.keyCommand.bindEvent();
  4805. this.elements.completeEditingText();
  4806. this.render.render();
  4807. this.emitChange();
  4808. }
  4809. createTextElement(e) {
  4810. this.elements.createElement({
  4811. type: "text",
  4812. x: e.clientX,
  4813. y: e.clientY
  4814. });
  4815. this.keyCommand.unBindEvent();
  4816. this.textEdit.showTextEdit();
  4817. }
  4818. onMousewheel(dir) {
  4819. let stepNum = this.state.scrollStep / this.state.scale;
  4820. let step = dir === "down" ? stepNum : -stepNum;
  4821. this.scrollTo(this.state.scrollX, this.state.scrollY + step);
  4822. }
  4823. onContextmenu(e) {
  4824. let elements = [];
  4825. if (this.elements.hasActiveElement()) {
  4826. elements = [this.elements.activeElement];
  4827. } else if (this.selection.hasSelectionElements()) {
  4828. elements = this.selection.getSelectionElements();
  4829. }
  4830. this.emit("contextmenu", e.originEvent, elements);
  4831. }
  4832. emitChange() {
  4833. let data = this.getData();
  4834. this.history.add(data);
  4835. this.emit("change", data);
  4836. }
  4837. }
  4838. TinyWhiteboard.utils = utils;
  4839. TinyWhiteboard.checkHit = checkHit;
  4840. TinyWhiteboard.draw = draw;
  4841. TinyWhiteboard.elements = Elements;
  4842. export { TinyWhiteboard as default };