tiny-whiteboard.es.js 127 KB

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