tiny-whiteboard.es.js 130 KB

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