diff --git a/konva.js b/konva.js index ecc0451d..2c47e977 100644 --- a/konva.js +++ b/konva.js @@ -8,7 +8,7 @@ * Konva JavaScript Framework v3.2.6 * http://konvajs.org/ * Licensed under the MIT - * Date: Thu May 09 2019 + * Date: Sat May 11 2019 * * Original work Copyright (C) 2011 - 2013 by Eric Rowell (KineticJS) * Modified work Copyright (C) 2014 - present by Anton Lavrenov (Konva) @@ -2483,11 +2483,12 @@ */ var Node = /** @class */ (function () { function Node(config) { + var _this = this; this._id = idCounter++; this.eventListeners = {}; this.attrs = {}; this.index = 0; - this.parent = null; + this.parent = undefined; this._cache = new Map(); this._lastPos = null; this._filterUpToDate = false; @@ -2496,20 +2497,20 @@ this.setAttrs(config); // event bindings for cache handling this.on(TRANSFORM_CHANGE_STR, function () { - this._clearCache(TRANSFORM); - this._clearSelfAndDescendantCache(ABSOLUTE_TRANSFORM); + _this._clearCache(TRANSFORM); + _this._clearSelfAndDescendantCache(ABSOLUTE_TRANSFORM); }); this.on(SCALE_CHANGE_STR, function () { - this._clearSelfAndDescendantCache(ABSOLUTE_SCALE); + _this._clearSelfAndDescendantCache(ABSOLUTE_SCALE); }); this.on('visibleChange.konva', function () { - this._clearSelfAndDescendantCache(VISIBLE); + _this._clearSelfAndDescendantCache(VISIBLE); }); this.on('listeningChange.konva', function () { - this._clearSelfAndDescendantCache(LISTENING); + _this._clearSelfAndDescendantCache(LISTENING); }); this.on('opacityChange.konva', function () { - this._clearSelfAndDescendantCache(ABSOLUTE_OPACITY); + _this._clearSelfAndDescendantCache(ABSOLUTE_OPACITY); }); } Node.prototype.hasChildren = function () { @@ -2804,67 +2805,6 @@ } return sceneCanvas; }; - /** - * bind events to the node. KonvaJS supports mouseover, mousemove, - * mouseout, mouseenter, mouseleave, mousedown, mouseup, wheel, contextmenu, click, dblclick, touchstart, touchmove, - * touchend, tap, dbltap, dragstart, dragmove, and dragend events. - * Pass in a string of events delimited by a space to bind multiple events at once - * such as 'mousedown mouseup mousemove'. Include a namespace to bind an - * event by name such as 'click.foobar'. - * @method - * @name Konva.Node#on - * @param {String} evtStr e.g. 'click', 'mousedown touchstart', 'mousedown.foo touchstart.foo' - * @param {Function} handler The handler function is passed an event object - * @returns {Konva.Node} - * @example - * // add click listener - * node.on('click', function() { - * console.log('you clicked me!'); - * }); - * - * // get the target node - * node.on('click', function(evt) { - * console.log(evt.target); - * }); - * - * // stop event propagation - * node.on('click', function(evt) { - * evt.cancelBubble = true; - * }); - * - * // bind multiple listeners - * node.on('click touchstart', function() { - * console.log('you clicked/touched me!'); - * }); - * - * // namespace listener - * node.on('click.foo', function() { - * console.log('you clicked/touched me!'); - * }); - * - * // get the event type - * node.on('click tap', function(evt) { - * var eventType = evt.type; - * }); - * - * // get native event object - * node.on('click tap', function(evt) { - * var nativeEvent = evt.evt; - * }); - * - * // for change events, get the old and new val - * node.on('xChange', function(evt) { - * var oldVal = evt.oldVal; - * var newVal = evt.newVal; - * }); - * - * // get event targets - * // with event delegations - * layer.on('click', 'Group', function(evt) { - * var shape = evt.target; - * var group = evt.currentTarget; - * }); - */ Node.prototype.on = function (evtStr, handler) { if (arguments.length === 3) { return this._delegate.apply(this, arguments); @@ -4289,8 +4229,8 @@ Node.prototype._listenDrag = function () { this._dragCleanup(); this.on('mousedown.konva touchstart.konva', function (evt) { - var shouldCheckButton = evt.evt.button !== undefined; - var canDrag = !shouldCheckButton || Konva.dragButtons.indexOf(evt.evt.button) >= 0; + var shouldCheckButton = evt.evt['button'] !== undefined; + var canDrag = !shouldCheckButton || Konva.dragButtons.indexOf(evt.evt['button']) >= 0; if (!canDrag) { return; } @@ -10798,7 +10738,7 @@ _this.pathLength += _this.dataArray[i].pathLength; } _this.on('dataChange.konva', function () { - this.dataArray = Path.parsePathData(this.getData()); + this.dataArray = Path.parsePathData(this.data()); this.pathLength = 0; for (var i = 0; i < this.dataArray.length; ++i) { this.pathLength += this.dataArray[i].pathLength; @@ -14060,6 +14000,7 @@ this._createAnchor('rotater'); }; Transformer.prototype._createAnchor = function (name) { + var _this = this; var anchor = new Rect({ stroke: 'rgb(0, 161, 255)', fill: 'white', @@ -14083,21 +14024,20 @@ }); // add hover styling anchor.on('mouseenter', function () { - var tr = this.getParent(); - var rad = Konva.getAngle(tr.rotation()); - var scale = tr.getNode().getAbsoluteScale(); + var rad = Konva.getAngle(_this.rotation()); + var scale = _this.getNode().getAbsoluteScale(); // If scale.y < 0 xor scale.x < 0 we need to flip (not rotate). var isMirrored = scale.y * scale.x < 0; var cursor = getCursor(name, rad, isMirrored); anchor.getStage().content.style.cursor = cursor; - tr._cursorChange = true; + _this._cursorChange = true; }); anchor.on('mouseout', function () { - if (!anchor.getStage() || !this.getParent()) { + if (!anchor.getStage() || !anchor.getParent()) { return; } anchor.getStage().content.style.cursor = ''; - this.getParent()._cursorChange = false; + _this._cursorChange = false; }); this.add(anchor); }; diff --git a/konva.min.js b/konva.min.js index 90f8aade..65a1e8ce 100644 --- a/konva.min.js +++ b/konva.min.js @@ -3,10 +3,10 @@ * Konva JavaScript Framework v3.2.6 * http://konvajs.org/ * Licensed under the MIT - * Date: Thu May 09 2019 + * Date: Sat May 11 2019 * * Original work Copyright (C) 2011 - 2013 by Eric Rowell (KineticJS) * Modified work Copyright (C) 2014 - present by Anton Lavrenov (Konva) * * @license - */var e=Math.PI/180;var t=function(t){var e=t.toLowerCase(),i=/(chrome)[ /]([\w.]+)/.exec(e)||/(webkit)[ /]([\w.]+)/.exec(e)||/(opera)(?:.*version|)[ /]([\w.]+)/.exec(e)||/(msie) ([\w.]+)/.exec(e)||e.indexOf("compatible")<0&&/(mozilla)(?:.*? rv:([\w.]+)|)/.exec(e)||[],n=!!t.match(/Android|BlackBerry|iPhone|iPad|iPod|Opera Mini|IEMobile/i),r=!!t.match(/IEMobile/i);return{browser:i[1]||"",version:i[2]||"0",isIE:function(t){var e=t.indexOf("msie ");if(0>16&255,g:e>>8&255,b:255&e}},getRandomColor:function(){for(var t=(16777215*Math.random()<<0).toString(16);t.length<6;)t="0"+t;return"#"+t},get:function(t,e){return void 0===t?e:t},getRGB:function(t){var e;return t in l?{r:(e=l[t])[0],g:e[1],b:e[2]}:"#"===t[0]?this._hexToRgb(t.substring(1)):"rgb("===t.substr(0,4)?(e=d.exec(t.replace(/ /g,"")),{r:parseInt(e[1],10),g:parseInt(e[2],10),b:parseInt(e[3],10)}):{r:0,g:0,b:0}},colorToRGBA:function(t){return t=t||"black",O._namedColorToRBA(t)||O._hex3ColorToRGBA(t)||O._hex6ColorToRGBA(t)||O._rgbColorToRGBA(t)||O._rgbaColorToRGBA(t)},_namedColorToRBA:function(t){var e=l[t.toLowerCase()];return e?{r:e[0],g:e[1],b:e[2],a:1}:null},_rgbColorToRGBA:function(t){if(0===t.indexOf("rgb(")){var e=(t=t.match(/rgb\(([^)]+)\)/)[1]).split(/ *, */).map(Number);return{r:e[0],g:e[1],b:e[2],a:1}}},_rgbaColorToRGBA:function(t){if(0===t.indexOf("rgba(")){var e=(t=t.match(/rgba\(([^)]+)\)/)[1]).split(/ *, */).map(Number);return{r:e[0],g:e[1],b:e[2],a:e[3]}}},_hex6ColorToRGBA:function(t){if("#"===t[0]&&7===t.length)return{r:parseInt(t.slice(1,3),16),g:parseInt(t.slice(3,5),16),b:parseInt(t.slice(5,7),16),a:1}},_hex3ColorToRGBA:function(t){if("#"===t[0]&&4===t.length)return{r:parseInt(t[1]+t[1],16),g:parseInt(t[2]+t[2],16),b:parseInt(t[3]+t[3],16),a:1}},haveIntersection:function(t,e){return!(e.x>t.x+t.width||e.x+e.widtht.y+t.height||e.y+e.heighte.length){var o=e;e=t,t=o}for(n=0;n=this.parent.children.length)&&O.warn("Unexpected value "+t+" for zIndex property. zIndex is just index of a node in children of its parent. Expected value is from 0 to "+(this.parent.children.length-1)+".");var e=this.index;return this.parent.children.splice(e,1),this.parent.children.splice(t,0,this),this.parent._setChildrenIndices(),this},s.prototype.getAbsoluteOpacity=function(){return this._getCache(N,this._getAbsoluteOpacity)},s.prototype._getAbsoluteOpacity=function(){var t=this.opacity(),e=this.getParent();return e&&!e._isUnderCache&&(t*=this.getParent().getAbsoluteOpacity()),t},s.prototype.moveTo=function(t){return this.getParent()!==t&&(this._remove(),t.add(this)),this},s.prototype.toObject=function(){var t,e,i,n={},r=this.getAttrs();for(t in n.attrs={},r)e=r[t],O.isObject(e)&&!O._isPlainObject(e)&&!O._isArray(e)||(i="function"==typeof this[t]&&this[t],delete r[t],(i?i.call(this):null)!==(r[t]=e)&&(n.attrs[t]=e));return n.className=this.getClassName(),O._prepareToStringify(n)},s.prototype.toJSON=function(){return JSON.stringify(this.toObject())},s.prototype.getParent=function(){return this.parent},s.prototype.findAncestors=function(t,e,i){var n=[];e&&this._isMatch(t)&&n.push(this);for(var r=this.parent;r;){if(r===i)return n;r._isMatch(t)&&n.push(r),r=r.parent}return n},s.prototype.isAncestorOf=function(t){return!1},s.prototype.findAncestor=function(t,e,i){return this.findAncestors(t,e,i)[0]},s.prototype._isMatch=function(t){if(!t)return!1;if("function"==typeof t)return t(this);var e,i,n=t.replace(/ /g,"").split(","),r=n.length;for(e=0;ethis.duration?this.yoyo?(this._time=this.duration,this.reverse()):this.finish():t<0?this.yoyo?(this._time=0,this.play()):this.reset():(this._time=t,this.update())},t.prototype.getTime=function(){return this._time},t.prototype.setPosition=function(t){this.prevPos=this._pos,this.propFunc(t),this._pos=t},t.prototype.getPosition=function(t){return void 0===t&&(t=this._time),this.func(t,this.begin,this._change,this.duration)},t.prototype.play=function(){this.state=2,this._startTime=this.getTimer()-this._time,this.onEnterFrame(),this.fire("onPlay")},t.prototype.reverse=function(){this.state=3,this._time=this.duration-this._time,this._startTime=this.getTimer()-this._time,this.onEnterFrame(),this.fire("onReverse")},t.prototype.seek=function(t){this.pause(),this._time=t,this.update(),this.fire("onSeek")},t.prototype.reset=function(){this.pause(),this._time=0,this.update(),this.fire("onReset")},t.prototype.finish=function(){this.pause(),this._time=this.duration,this.update(),this.fire("onFinish")},t.prototype.update=function(){this.setPosition(this.getPosition(this._time))},t.prototype.onEnterFrame=function(){var t=this.getTimer()-this._startTime;2===this.state?this.setTime(t):3===this.state&&this.setTime(this.duration-t)},t.prototype.pause=function(){this.state=1,this.fire("onPause")},t.prototype.getTimer=function(){return(new Date).getTime()},t}(),qt=function(){function u(t){var e,i,n=this,r=t.node,a=r._id,o=t.easing||Vt.Linear,s=!!t.yoyo;e=void 0===t.duration?.3:0===t.duration?.001:t.duration,this.node=r,this._id=Xt++;var h=r.getLayer()||(r instanceof L.Stage?r.getLayers():null);for(i in h||O.error("Tween constructor have `node` that is not in a layer. Please add node into layer first."),this.anim=new I(function(){n.tween.onEnterFrame()},h),this.tween=new Ut(i,function(t){n._tweenFunc(t)},o,0,1,1e3*e,s),this._addListeners(),u.attrs[a]||(u.attrs[a]={}),u.attrs[a][this._id]||(u.attrs[a][this._id]={}),u.tweens[a]||(u.tweens[a]={}),t)void 0===Yt[i]&&this._addAttr(i,t[i]);this.reset(),this.onFinish=t.onFinish,this.onReset=t.onReset}return u.prototype._addAttr=function(t,e){var i,n,r,a,o,s,h,l,c=this.node,d=c._id;if((r=u.tweens[d][t])&&delete u.attrs[d][r][t],i=c.getAttr(t),O._isArray(e))if(n=[],o=Math.max(e.length,i.length),"points"===t&&e.length!==i.length&&(e.length>i.length?(h=i,i=O._prepareArrayForTween(i,e,c.closed())):(s=e,e=O._prepareArrayForTween(e,i,c.closed()))),0===t.indexOf("fill"))for(a=0;athis.dataArray[i].pathLength;)t-=this.dataArray[i].pathLength,++i;if(i===n)return{x:(e=this.dataArray[i-1].points.slice(-2))[0],y:e[1]};if(t<.01)return{x:(e=this.dataArray[i].points.slice(0,2))[0],y:e[1]};var r=this.dataArray[i],a=r.points;switch(r.command){case"L":return u.getPointOnLine(t,r.start.x,r.start.y,a[0],a[1]);case"C":return u.getPointOnCubicBezier(t/r.pathLength,r.start.x,r.start.y,a[0],a[1],a[2],a[3],a[4],a[5]);case"Q":return u.getPointOnQuadraticBezier(t/r.pathLength,r.start.x,r.start.y,a[0],a[1],a[2],a[3]);case"A":var o=a[0],s=a[1],h=a[2],l=a[3],c=a[4],d=a[5],p=a[6];return c+=d*t/r.pathLength,u.getPointOnEllipticalArc(o,s,h,l,c,p)}return null},u.getLineLength=function(t,e,i,n){return Math.sqrt((i-t)*(i-t)+(n-e)*(n-e))},u.getPointOnLine=function(t,e,i,n,r,a,o){void 0===a&&(a=e),void 0===o&&(o=i);var s=(r-i)/(n-e+1e-8),h=Math.sqrt(t*t/(1+s*s));n>>1,P=_.slice(0,1+k),T=this._getTextWidth(P)+v;T<=l?(b=1+k,w=P+(g?"…":""),C=T):x=k}if(!w)break;if(f){var M,A=_[w.length];0<(M=(" "===A||"-"===A)&&C<=l?w.length:Math.max(w.lastIndexOf(" "),w.lastIndexOf("-"))+1)&&(b=M,w=w.slice(0,b),C=this._getTextWidth(w))}if(w=w.trimRight(),this._addTextLine(w),i=Math.max(i,C),d+=n,!u||s&&ce?g=le.getPointOnLine(e,f.x,f.y,v.points[0],v.points[1],f.x,f.y):v=void 0;break;case"A":var o=v.points[4],s=v.points[5],h=v.points[4]+s;0===m?m=o+1e-8:iv.pathLength?1e-8:e/v.pathLength:i>W,0!==C?(C=255/C,P[s]=(l*B>>W)*C,P[s+1]=(c*B>>W)*C,P[s+2]=(d*B>>W)*C):P[s]=P[s+1]=P[s+2]=0,l-=u,c-=f,d-=g,p-=v,u-=E.r,f-=E.g,g-=E.b,v-=E.a,a=h+((a=i+e+1)>W,0>W)*C,P[a+1]=(c*B>>W)*C,P[a+2]=(d*B>>W)*C):P[a]=P[a+1]=P[a+2]=0,l-=u,c-=f,d-=g,p-=v,u-=E.r,f-=E.g,g-=E.b,v-=E.a,a=i+((a=n+L)>16&255,g:e>>8&255,b:255&e}},getRandomColor:function(){for(var t=(16777215*Math.random()<<0).toString(16);t.length<6;)t="0"+t;return"#"+t},get:function(t,e){return void 0===t?e:t},getRGB:function(t){var e;return t in l?{r:(e=l[t])[0],g:e[1],b:e[2]}:"#"===t[0]?this._hexToRgb(t.substring(1)):"rgb("===t.substr(0,4)?(e=d.exec(t.replace(/ /g,"")),{r:parseInt(e[1],10),g:parseInt(e[2],10),b:parseInt(e[3],10)}):{r:0,g:0,b:0}},colorToRGBA:function(t){return t=t||"black",O._namedColorToRBA(t)||O._hex3ColorToRGBA(t)||O._hex6ColorToRGBA(t)||O._rgbColorToRGBA(t)||O._rgbaColorToRGBA(t)},_namedColorToRBA:function(t){var e=l[t.toLowerCase()];return e?{r:e[0],g:e[1],b:e[2],a:1}:null},_rgbColorToRGBA:function(t){if(0===t.indexOf("rgb(")){var e=(t=t.match(/rgb\(([^)]+)\)/)[1]).split(/ *, */).map(Number);return{r:e[0],g:e[1],b:e[2],a:1}}},_rgbaColorToRGBA:function(t){if(0===t.indexOf("rgba(")){var e=(t=t.match(/rgba\(([^)]+)\)/)[1]).split(/ *, */).map(Number);return{r:e[0],g:e[1],b:e[2],a:e[3]}}},_hex6ColorToRGBA:function(t){if("#"===t[0]&&7===t.length)return{r:parseInt(t.slice(1,3),16),g:parseInt(t.slice(3,5),16),b:parseInt(t.slice(5,7),16),a:1}},_hex3ColorToRGBA:function(t){if("#"===t[0]&&4===t.length)return{r:parseInt(t[1]+t[1],16),g:parseInt(t[2]+t[2],16),b:parseInt(t[3]+t[3],16),a:1}},haveIntersection:function(t,e){return!(e.x>t.x+t.width||e.x+e.widtht.y+t.height||e.y+e.heighte.length){var o=e;e=t,t=o}for(n=0;n=this.parent.children.length)&&O.warn("Unexpected value "+t+" for zIndex property. zIndex is just index of a node in children of its parent. Expected value is from 0 to "+(this.parent.children.length-1)+".");var e=this.index;return this.parent.children.splice(e,1),this.parent.children.splice(t,0,this),this.parent._setChildrenIndices(),this},s.prototype.getAbsoluteOpacity=function(){return this._getCache(N,this._getAbsoluteOpacity)},s.prototype._getAbsoluteOpacity=function(){var t=this.opacity(),e=this.getParent();return e&&!e._isUnderCache&&(t*=this.getParent().getAbsoluteOpacity()),t},s.prototype.moveTo=function(t){return this.getParent()!==t&&(this._remove(),t.add(this)),this},s.prototype.toObject=function(){var t,e,i,n={},r=this.getAttrs();for(t in n.attrs={},r)e=r[t],O.isObject(e)&&!O._isPlainObject(e)&&!O._isArray(e)||(i="function"==typeof this[t]&&this[t],delete r[t],(i?i.call(this):null)!==(r[t]=e)&&(n.attrs[t]=e));return n.className=this.getClassName(),O._prepareToStringify(n)},s.prototype.toJSON=function(){return JSON.stringify(this.toObject())},s.prototype.getParent=function(){return this.parent},s.prototype.findAncestors=function(t,e,i){var n=[];e&&this._isMatch(t)&&n.push(this);for(var r=this.parent;r;){if(r===i)return n;r._isMatch(t)&&n.push(r),r=r.parent}return n},s.prototype.isAncestorOf=function(t){return!1},s.prototype.findAncestor=function(t,e,i){return this.findAncestors(t,e,i)[0]},s.prototype._isMatch=function(t){if(!t)return!1;if("function"==typeof t)return t(this);var e,i,n=t.replace(/ /g,"").split(","),r=n.length;for(e=0;ethis.duration?this.yoyo?(this._time=this.duration,this.reverse()):this.finish():t<0?this.yoyo?(this._time=0,this.play()):this.reset():(this._time=t,this.update())},t.prototype.getTime=function(){return this._time},t.prototype.setPosition=function(t){this.prevPos=this._pos,this.propFunc(t),this._pos=t},t.prototype.getPosition=function(t){return void 0===t&&(t=this._time),this.func(t,this.begin,this._change,this.duration)},t.prototype.play=function(){this.state=2,this._startTime=this.getTimer()-this._time,this.onEnterFrame(),this.fire("onPlay")},t.prototype.reverse=function(){this.state=3,this._time=this.duration-this._time,this._startTime=this.getTimer()-this._time,this.onEnterFrame(),this.fire("onReverse")},t.prototype.seek=function(t){this.pause(),this._time=t,this.update(),this.fire("onSeek")},t.prototype.reset=function(){this.pause(),this._time=0,this.update(),this.fire("onReset")},t.prototype.finish=function(){this.pause(),this._time=this.duration,this.update(),this.fire("onFinish")},t.prototype.update=function(){this.setPosition(this.getPosition(this._time))},t.prototype.onEnterFrame=function(){var t=this.getTimer()-this._startTime;2===this.state?this.setTime(t):3===this.state&&this.setTime(this.duration-t)},t.prototype.pause=function(){this.state=1,this.fire("onPause")},t.prototype.getTimer=function(){return(new Date).getTime()},t}(),qt=function(){function u(t){var e,i,n=this,r=t.node,a=r._id,o=t.easing||Vt.Linear,s=!!t.yoyo;e=void 0===t.duration?.3:0===t.duration?.001:t.duration,this.node=r,this._id=Xt++;var h=r.getLayer()||(r instanceof L.Stage?r.getLayers():null);for(i in h||O.error("Tween constructor have `node` that is not in a layer. Please add node into layer first."),this.anim=new I(function(){n.tween.onEnterFrame()},h),this.tween=new Ut(i,function(t){n._tweenFunc(t)},o,0,1,1e3*e,s),this._addListeners(),u.attrs[a]||(u.attrs[a]={}),u.attrs[a][this._id]||(u.attrs[a][this._id]={}),u.tweens[a]||(u.tweens[a]={}),t)void 0===Yt[i]&&this._addAttr(i,t[i]);this.reset(),this.onFinish=t.onFinish,this.onReset=t.onReset}return u.prototype._addAttr=function(t,e){var i,n,r,a,o,s,h,l,c=this.node,d=c._id;if((r=u.tweens[d][t])&&delete u.attrs[d][r][t],i=c.getAttr(t),O._isArray(e))if(n=[],o=Math.max(e.length,i.length),"points"===t&&e.length!==i.length&&(e.length>i.length?(h=i,i=O._prepareArrayForTween(i,e,c.closed())):(s=e,e=O._prepareArrayForTween(e,i,c.closed()))),0===t.indexOf("fill"))for(a=0;athis.dataArray[i].pathLength;)t-=this.dataArray[i].pathLength,++i;if(i===n)return{x:(e=this.dataArray[i-1].points.slice(-2))[0],y:e[1]};if(t<.01)return{x:(e=this.dataArray[i].points.slice(0,2))[0],y:e[1]};var r=this.dataArray[i],a=r.points;switch(r.command){case"L":return u.getPointOnLine(t,r.start.x,r.start.y,a[0],a[1]);case"C":return u.getPointOnCubicBezier(t/r.pathLength,r.start.x,r.start.y,a[0],a[1],a[2],a[3],a[4],a[5]);case"Q":return u.getPointOnQuadraticBezier(t/r.pathLength,r.start.x,r.start.y,a[0],a[1],a[2],a[3]);case"A":var o=a[0],s=a[1],h=a[2],l=a[3],c=a[4],d=a[5],p=a[6];return c+=d*t/r.pathLength,u.getPointOnEllipticalArc(o,s,h,l,c,p)}return null},u.getLineLength=function(t,e,i,n){return Math.sqrt((i-t)*(i-t)+(n-e)*(n-e))},u.getPointOnLine=function(t,e,i,n,r,a,o){void 0===a&&(a=e),void 0===o&&(o=i);var s=(r-i)/(n-e+1e-8),h=Math.sqrt(t*t/(1+s*s));n>>1,P=_.slice(0,1+k),T=this._getTextWidth(P)+v;T<=l?(b=1+k,w=P+(g?"…":""),C=T):x=k}if(!w)break;if(f){var M,A=_[w.length];0<(M=(" "===A||"-"===A)&&C<=l?w.length:Math.max(w.lastIndexOf(" "),w.lastIndexOf("-"))+1)&&(b=M,w=w.slice(0,b),C=this._getTextWidth(w))}if(w=w.trimRight(),this._addTextLine(w),i=Math.max(i,C),d+=n,!u||s&&ce?g=le.getPointOnLine(e,f.x,f.y,v.points[0],v.points[1],f.x,f.y):v=void 0;break;case"A":var o=v.points[4],s=v.points[5],h=v.points[4]+s;0===m?m=o+1e-8:iv.pathLength?1e-8:e/v.pathLength:i>W,0!==C?(C=255/C,P[s]=(l*B>>W)*C,P[s+1]=(c*B>>W)*C,P[s+2]=(d*B>>W)*C):P[s]=P[s+1]=P[s+2]=0,l-=u,c-=f,d-=g,p-=v,u-=E.r,f-=E.g,g-=E.b,v-=E.a,a=h+((a=i+e+1)>W,0>W)*C,P[a+1]=(c*B>>W)*C,P[a+2]=(d*B>>W)*C):P[a]=P[a+1]=P[a+2]=0,l-=u,c-=f,d-=g,p-=v,u-=E.r,f-=E.g,g-=E.b,v-=E.a,a=i+((a=n+L)(); +const emptyChildren: Collection = new Collection(); let idCounter = 1; + +// create all the events here +interface NodeEventMap { + [index: string]: any; + click: MouseEvent; + touchstart: TouchEvent; +} + /** * Node constructor. Nodes are entities that can be transformed, layered, * and have bound events. The stage, layers, groups, and shapes all extend Node. @@ -167,40 +178,42 @@ let idCounter = 1; */ export abstract class Node { _id = idCounter++; - eventListeners = {}; + eventListeners: { + [index: string]: Array<{ name: string; handler: Function }>; + } = {}; attrs: any = {}; index = 0; - parent: Container | null = null; + parent: Container | undefined = undefined; _cache: Map = new Map(); - _lastPos = null; - _attrsAffectingSize: string[]; + _lastPos: Point = null; + _attrsAffectingSize!: string[]; _filterUpToDate = false; _isUnderCache = false; children = emptyChildren; - nodeType: string; - className: string; + nodeType!: string; + className!: string; constructor(config?: Config) { this.setAttrs(config); // event bindings for cache handling - this.on(TRANSFORM_CHANGE_STR, function() { + this.on(TRANSFORM_CHANGE_STR, () => { this._clearCache(TRANSFORM); this._clearSelfAndDescendantCache(ABSOLUTE_TRANSFORM); }); - this.on(SCALE_CHANGE_STR, function() { + this.on(SCALE_CHANGE_STR, () => { this._clearSelfAndDescendantCache(ABSOLUTE_SCALE); }); - this.on('visibleChange.konva', function() { + this.on('visibleChange.konva', () => { this._clearSelfAndDescendantCache(VISIBLE); }); - this.on('listeningChange.konva', function() { + this.on('listeningChange.konva', () => { this._clearSelfAndDescendantCache(LISTENING); }); - this.on('opacityChange.konva', function() { + this.on('opacityChange.konva', () => { this._clearSelfAndDescendantCache(ABSOLUTE_OPACITY); }); } @@ -214,14 +227,14 @@ export abstract class Node { } /** @lends Konva.Node.prototype */ - _clearCache(attr) { + _clearCache(attr?: string) { if (attr) { this._cache.delete(attr); } else { this._cache.clear(); } } - _getCache(attr, privateGetter) { + _getCache(attr: string, privateGetter: Function) { var cache = this._cache.get(attr); // if not cached, we need to set it using the private getter method. @@ -239,7 +252,7 @@ export abstract class Node { * when the logic for a cached result depends on ancestor propagation, use this * method to clear self and children cache */ - _clearSelfAndDescendantCache(attr?) { + _clearSelfAndDescendantCache(attr?: string) { this._clearCache(attr); // skip clearing if node is cached with canvas @@ -307,7 +320,15 @@ export abstract class Node { * drawBorder: true * }); */ - cache(config) { + cache(config?: { + x?: number; + y?: number; + width?: number; + height?: number; + drawBorder?: boolean; + offset?: number; + pixelRatio?: number; + }) { var conf = config || {}; var rect = {} as RectConf; @@ -410,8 +431,18 @@ export abstract class Node { return this; } - abstract drawScene(canvas?, top?, caching?, skipBuffer?): void; - abstract drawHit(canvas?, top?, caching?, skipBuffer?): void; + abstract drawScene( + canvas?: Canvas, + top?: Node, + caching?: boolean, + skipBuffer?: boolean + ): void; + abstract drawHit( + canvas?: Canvas, + top?: Node, + caching?: boolean, + skipBuffer?: boolean + ): void; /** * Return client rectangle {x, y, width, height} of node. This rectangle also include all styling (strokes, shadows, etc). * The rectangle position is relative to parent container. @@ -459,7 +490,7 @@ export abstract class Node { // redefine in Container and Shape throw new Error('abstract "getClientRect" method call'); } - _transformedRect(rect, top) { + _transformedRect(rect: IRect, top: Node) { var points = [ { x: rect.x, y: rect.y }, { x: rect.x + rect.width, y: rect.y }, @@ -486,7 +517,7 @@ export abstract class Node { height: maxY - minY }; } - _drawCachedSceneCanvas(context) { + _drawCachedSceneCanvas(context: Context) { context.save(); context._applyOpacity(this); context._applyGlobalCompositeOperation(this); @@ -506,7 +537,7 @@ export abstract class Node { ); context.restore(); } - _drawCachedHitCanvas(context) { + _drawCachedHitCanvas(context: Context) { var canvasCache = this._getCanvasCache(), hitCanvas = canvasCache.hit; context.save(); @@ -635,7 +666,20 @@ export abstract class Node { * var group = evt.currentTarget; * }); */ - on(evtStr, handler) { + on( + type: K, + listener: ( + this: this, + ev: { + target: Shape | Stage; + evt: NodeEventMap[K]; + currentTarget: Node; + cancelBubble: boolean; + child?: Node; + } + ) => any + ): void; + on(evtStr: string, handler: (evt: any) => void) { if (arguments.length === 3) { return this._delegate.apply(this, arguments); } @@ -692,7 +736,7 @@ export abstract class Node { * // remove listener by name * node.off('click.foo'); */ - off(evtStr, callback?) { + off(evtStr: string, callback?: Function) { var events = (evtStr || '').split(SPACE), len = events.length, n, @@ -727,7 +771,7 @@ export abstract class Node { return this; } // some event aliases for third party integration like HammerJS - dispatchEvent(evt) { + dispatchEvent(evt: any) { var e = { target: this, type: evt.type, @@ -736,19 +780,19 @@ export abstract class Node { this.fire(evt.type, e); return this; } - addEventListener(type, handler) { + addEventListener(type: string, handler: (e: Event) => void) { // we have to pass native event to handler this.on(type, function(evt) { handler.call(this, evt.evt); }); return this; } - removeEventListener(type) { + removeEventListener(type: string) { this.off(type); return this; } // like node.on - _delegate(event, selector, handler) { + _delegate(event: string, selector: string, handler: (e: Event) => void) { var stopNode = this; this.on(event, function(evt) { var targets = evt.target.findAncestors(selector, true, stopNode); @@ -821,10 +865,10 @@ export abstract class Node { * @example * var x = node.getAttr('x'); */ - getAttr(attr) { + getAttr(attr: string) { var method = 'get' + Util._capitalize(attr); - if (Util._isFunction(this[method])) { - return this[method](); + if (Util._isFunction((this as any)[method])) { + return (this as any)[method](); } // otherwise get directly return this.attrs[attr]; @@ -871,7 +915,7 @@ export abstract class Node { * fill: 'red' * }); */ - setAttrs(config) { + setAttrs(config: any) { var key, method; if (!config) { @@ -2220,9 +2264,9 @@ export abstract class Node { this._dragCleanup(); this.on('mousedown.konva touchstart.konva', function(evt) { - var shouldCheckButton = evt.evt.button !== undefined; + var shouldCheckButton = evt.evt['button'] !== undefined; var canDrag = - !shouldCheckButton || Konva.dragButtons.indexOf(evt.evt.button) >= 0; + !shouldCheckButton || Konva.dragButtons.indexOf(evt.evt['button']) >= 0; if (!canDrag) { return; } diff --git a/src/Validators.ts b/src/Validators.ts index 252a181c..1df7e317 100644 --- a/src/Validators.ts +++ b/src/Validators.ts @@ -1,7 +1,7 @@ import { Konva } from './Global'; import { Util } from './Util'; -function _formatValue(val) { +function _formatValue(val: any) { if (Util._isString(val)) { return '"' + val + '"'; } @@ -14,7 +14,7 @@ function _formatValue(val) { return Object.prototype.toString.call(val); } -export function RGBComponent(val) { +export function RGBComponent(val: number) { if (val > 255) { return 255; } else if (val < 0) { @@ -22,7 +22,7 @@ export function RGBComponent(val) { } return Math.round(val); } -export function alphaComponent(val) { +export function alphaComponent(val: number) { if (val > 1) { return 1; } else if (val < 0.0001) { @@ -35,7 +35,7 @@ export function alphaComponent(val) { export function getNumberValidator() { if (Konva.isUnminified) { - return function(val, attr) { + return function(val: any, attr: string) { if (!Util._isNumber(val)) { Util.warn( _formatValue(val) + @@ -50,7 +50,7 @@ export function getNumberValidator() { } export function getNumberOrAutoValidator() { if (Konva.isUnminified) { - return function(val, attr) { + return function(val: any, attr: string) { var isNumber = Util._isNumber(val); var isAuto = val === 'auto'; @@ -68,7 +68,7 @@ export function getNumberOrAutoValidator() { } export function getStringValidator() { if (Konva.isUnminified) { - return function(val, attr) { + return function(val: any, attr: string) { if (!Util._isString(val)) { Util.warn( _formatValue(val) + @@ -83,7 +83,7 @@ export function getStringValidator() { } export function getFunctionValidator() { if (Konva.isUnminified) { - return function(val, attr) { + return function(val: any, attr: string) { if (!Util._isFunction(val)) { Util.warn( _formatValue(val) + @@ -98,7 +98,7 @@ export function getFunctionValidator() { } export function getNumberArrayValidator() { if (Konva.isUnminified) { - return function(val, attr) { + return function(val: any, attr: string) { if (!Util._isArray(val)) { Util.warn( _formatValue(val) + @@ -107,7 +107,7 @@ export function getNumberArrayValidator() { '" attribute. The value should be a array of numbers.' ); } else { - val.forEach(function(item) { + val.forEach(function(item: any) { if (!Util._isNumber(item)) { Util.warn( '"' + @@ -125,7 +125,7 @@ export function getNumberArrayValidator() { } export function getBooleanValidator() { if (Konva.isUnminified) { - return function(val, attr) { + return function(val: any, attr: string) { var isBool = val === true || val === false; if (!isBool) { Util.warn( @@ -139,9 +139,9 @@ export function getBooleanValidator() { }; } } -export function getComponentValidator(components) { +export function getComponentValidator(components: any) { if (Konva.isUnminified) { - return function(val, attr) { + return function(val: any, attr: string) { if (!Util.isObject(val)) { Util.warn( _formatValue(val) + diff --git a/src/shapes/Path.ts b/src/shapes/Path.ts index 9ad9af42..2916007c 100644 --- a/src/shapes/Path.ts +++ b/src/shapes/Path.ts @@ -40,7 +40,7 @@ export class Path extends Shape { this.pathLength += this.dataArray[i].pathLength; } this.on('dataChange.konva', function() { - this.dataArray = Path.parsePathData(this.getData()); + this.dataArray = Path.parsePathData(this.data()); this.pathLength = 0; for (var i = 0; i < this.dataArray.length; ++i) { this.pathLength += this.dataArray[i].pathLength; diff --git a/src/shapes/Transformer.ts b/src/shapes/Transformer.ts index 68b6e341..6d61e647 100644 --- a/src/shapes/Transformer.ts +++ b/src/shapes/Transformer.ts @@ -348,24 +348,22 @@ export class Transformer extends Group { }); // add hover styling - anchor.on('mouseenter', function() { - var tr = this.getParent(); + anchor.on('mouseenter', () => { + var rad = Konva.getAngle(this.rotation()); - var rad = Konva.getAngle(tr.rotation()); - - var scale = tr.getNode().getAbsoluteScale(); + var scale = this.getNode().getAbsoluteScale(); // If scale.y < 0 xor scale.x < 0 we need to flip (not rotate). var isMirrored = scale.y * scale.x < 0; var cursor = getCursor(name, rad, isMirrored); anchor.getStage().content.style.cursor = cursor; - tr._cursorChange = true; + this._cursorChange = true; }); - anchor.on('mouseout', function() { - if (!anchor.getStage() || !this.getParent()) { + anchor.on('mouseout', () => { + if (!anchor.getStage() || !anchor.getParent()) { return; } anchor.getStage().content.style.cursor = ''; - this.getParent()._cursorChange = false; + this._cursorChange = false; }); this.add(anchor); } diff --git a/tsconfig.json b/tsconfig.json index 0cc4be34..3a146609 100644 --- a/tsconfig.json +++ b/tsconfig.json @@ -6,7 +6,7 @@ "noEmitOnError": true, "lib": ["es2015", "dom"] // "noImplicitAny": true - // "strict": true, + // "strict": true // "strictFunctionTypes": true }, "include": ["./src/*.ts"]