From e150791f97617e30d283fb6cfcfd3f03637cbeec Mon Sep 17 00:00:00 2001 From: Anton Lavrenov Date: Sun, 10 Mar 2019 10:31:13 -0500 Subject: [PATCH] huge typescript fixes, remove Object.assign usage --- konva.js | 21 +++-- konva.min.js | 4 +- package.json | 4 +- rollup.config.js | 2 +- src/BaseLayer.ts | 9 +- src/Container.ts | 13 ++- src/Core.ts | 2 + src/Global.ts | 4 + src/Node.ts | 29 ++++++- src/Shape.ts | 64 +++++++++++++- src/Stage.ts | 8 +- src/Util.ts | 7 ++ src/_CoreInternals.ts | 5 +- src/_FullInternals.ts | 2 +- src/index-types.d.ts | 159 ++++++++++++++++++++++++++++++++++ src/index-types.ts | 3 - src/{_UMD.ts => index-umd.ts} | 2 - src/index.ts | 2 + src/shapes/Arc.ts | 11 ++- src/shapes/Arrow.ts | 13 ++- src/shapes/Circle.ts | 8 +- src/shapes/Ellipse.ts | 9 +- src/shapes/Image.ts | 10 ++- src/shapes/Label.ts | 14 ++- src/shapes/Line.ts | 15 +++- src/shapes/Path.ts | 11 ++- src/shapes/Rect.ts | 7 +- src/shapes/RegularPolygon.ts | 10 ++- src/shapes/Ring.ts | 10 ++- src/shapes/Sprite.ts | 13 ++- src/shapes/Star.ts | 10 ++- src/shapes/Text.ts | 19 +++- src/shapes/TextPath.ts | 18 ++-- src/shapes/Transformer.ts | 27 +++++- src/shapes/Wedge.ts | 10 ++- src/types.ts | 38 ++++++++ 36 files changed, 520 insertions(+), 73 deletions(-) create mode 100644 src/index-types.d.ts delete mode 100644 src/index-types.ts rename src/{_UMD.ts => index-umd.ts} (75%) diff --git a/konva.js b/konva.js index 7e8262ac..bab4fa46 100644 --- a/konva.js +++ b/konva.js @@ -8,7 +8,7 @@ * Konva JavaScript Framework v3.1.7 * http://konvajs.org/ * Licensed under the MIT - * Date: Wed Mar 06 2019 + * Date: Sun Mar 10 2019 * * Original work Copyright (C) 2011 - 2013 by Eric Rowell (KineticJS) * Modified work Copyright (C) 2014 - present by Anton Lavrenov (Konva) @@ -74,6 +74,10 @@ : typeof WorkerGlobalScope !== 'undefined' ? self : {}; + var Konva2; + (function (Konva2) { + Konva2.version = '3.1.7'; + })(Konva2 || (Konva2 = {})); var Konva = { version: '3.1.7', isBrowser: detectBrowser(), @@ -1060,6 +1064,13 @@ } delete obj.visitedByCircularReferenceRemoval; return obj; + }, + // very simplified version of Object.assign + _assign: function (target, source) { + for (var key in source) { + target[key] = source[key]; + } + return target; } }; @@ -9102,7 +9113,7 @@ }; // what is core parts of Konva? - var Konva$1 = Object.assign(Konva, { + var Konva$1 = Util._assign(Konva, { Collection: Collection, Util: Util, Node: Node, @@ -13265,9 +13276,9 @@ }); // update text data for certain attr changes _this.on('textChange.konva alignChange.konva letterSpacingChange.konva kerningFuncChange.konva', _this._setTextData); - if (config && config.getKerning) { + if (config && config['getKerning']) { Util.warn('getKerning TextPath API is deprecated. Please use "kerningFunc" instead.'); - _this.kerningFunc(config.getKerning); + _this.kerningFunc(config['getKerning']); } _this._setTextData(); return _this; @@ -16998,7 +17009,7 @@ */ // we need to import core of the Konva and then extend it with all additional objects - var Konva$2 = Object.assign(Konva$1, { + var Konva$2 = Konva$1.Util._assign(Konva$1, { Arc: Arc, Arrow: Arrow, Circle: Circle, diff --git a/konva.min.js b/konva.min.js index 97542a52..42255e8a 100644 --- a/konva.min.js +++ b/konva.min.js @@ -3,10 +3,10 @@ * Konva JavaScript Framework v3.1.7 * http://konvajs.org/ * Licensed under the MIT - * Date: Wed Mar 06 2019 + * Date: Sun Mar 10 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(W,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;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}(),Ut=function(){function u(t){var e,i,n=this,r=t.node,a=r._id,o=t.easing||qt.Linear,s=!!t.yoyo;e=void 0===t.duration?.3:0===t.duration?.001:t.duration,this.node=r,this._id=Yt++;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 jt(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===Ht[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,k+1),T=this._getTextWidth(P)+v;T<=l?(b=k+1,w=P+(g?"…":""),C=T):x=k}if(!w)break;if(f){var A,M=_[w.length];0<(A=(" "===M||"-"===M)&&C<=l?w.length:Math.max(w.lastIndexOf(" "),w.lastIndexOf("-"))+1)&&(b=A,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=he.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>N,0!==C?(C=255/C,P[s]=(l*z>>N)*C,P[s+1]=(c*z>>N)*C,P[s+2]=(d*z>>N)*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)>N,0>N)*C,P[a+1]=(c*z>>N)*C,P[a+2]=(d*z>>N)*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 d?{r:(e=d[t])[0],g:e[1],b:e[2]}:"#"===t[0]?this._hexToRgb(t.substring(1)):"rgb("===t.substr(0,4)?(e=p.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=d[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(H,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;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 F(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,k+1),T=this._getTextWidth(P)+v;T<=l?(b=k+1,w=P+(g?"…":""),C=T):x=k}if(!w)break;if(f){var A,M=_[w.length];0<(A=(" "===M||"-"===M)&&C<=l?w.length:Math.max(w.lastIndexOf(" "),w.lastIndexOf("-"))+1)&&(b=A,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>N,0!==C?(C=255/C,P[s]=(l*z>>N)*C,P[s+1]=(c*z>>N)*C,P[s+2]=(d*z>>N)*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)>N,0>N)*C,P[a+1]=(c*z>>N)*C,P[a+2]=(d*z>>N)*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) void; + clipX?: number; + clipY?: number; + clipWidth?: number; + clipHeight?: number; +} + /** * Container constructor.  Containers are used to contain nodes or other containers * @constructor @@ -16,7 +25,7 @@ import { GetSet, IRect } from './types'; * @@nodeParams * @@containerParams */ -export abstract class Container extends Node { +export abstract class Container extends Node { children = new Collection(); /** diff --git a/src/Core.ts b/src/Core.ts index 3f6239c2..9e054f5e 100644 --- a/src/Core.ts +++ b/src/Core.ts @@ -1,3 +1,5 @@ +// enter file of limited Konva version with only core functions + var Konva = require('./_CoreInternals').Konva; // add Konva to global variable Konva._injectGlobal(Konva); diff --git a/src/Global.ts b/src/Global.ts index 7db88562..7907f100 100644 --- a/src/Global.ts +++ b/src/Global.ts @@ -86,6 +86,10 @@ export const glob: any = ? self : {}; +export namespace Konva2 { + export const version = '@@version'; +} + export const Konva = { version: '@@version', isBrowser: detectBrowser(), diff --git a/src/Node.ts b/src/Node.ts index fcc0c596..0f4b2204 100644 --- a/src/Node.ts +++ b/src/Node.ts @@ -100,6 +100,31 @@ type globalCompositeOperationType = | 'color' | 'luminosity'; +export interface NodeConfig { + x?: number; + y?: number; + width?: number; + height?: number; + visible?: boolean; + listening?: boolean; + id?: string; + name?: string; + opacity?: Number; + scale?: Vector2d; + scaleX?: number; + scaleY?: number; + rotation?: number; + rotationDeg?: number; + offset?: Vector2d; + offsetX?: number; + offsetY?: number; + draggable?: boolean; + dragDistance?: number; + dragBoundFunc?: (pos: Vector2d) => Vector2d; + preventDefault?: boolean; + globalCompositeOperation?: globalCompositeOperationType; +} + // CONSTANTS var ABSOLUTE_OPACITY = 'absoluteOpacity', ABSOLUTE_TRANSFORM = 'absoluteTransform', @@ -145,7 +170,7 @@ let idCounter = 1; * @param {Object} config * @@nodeParams */ -export abstract class Node { +export abstract class Node { _id = idCounter++; eventListeners = {}; attrs: any = {}; @@ -161,7 +186,7 @@ export abstract class Node { nodeType: string; className: string; - constructor(config) { + constructor(config?: Config) { this.setAttrs(config); // event bindings for cache handling diff --git a/src/Shape.ts b/src/Shape.ts index 1fd05d1c..bd58941f 100644 --- a/src/Shape.ts +++ b/src/Shape.ts @@ -1,16 +1,70 @@ import { Util, Collection } from './Util'; import { Factory } from './Factory'; -import { Node } from './Node'; +import { Node, NodeConfig } from './Node'; import { getNumberValidator, getStringValidator, getBooleanValidator } from './Validators'; -import { GetSet, Vector2d } from './types'; import { Context } from './Context'; import { _registerNode } from './Global'; +import { GetSet, Vector2d } from './types'; + +export interface ShapeConfig extends NodeConfig { + fill?: string; + fillPatternImage?: HTMLImageElement; + fillPatternX?: number; + fillPatternY?: number; + fillPatternOffset?: Vector2d; + fillPatternOffsetX?: number; + fillPatternOffsetY?: number; + fillPatternScale?: Vector2d; + fillPatternScaleX?: number; + fillPatternScaleY?: number; + fillPatternRotation?: number; + fillPatternRepeat?: string; + fillLinearGradientStartPoint?: Vector2d; + fillLinearGradientStartPointX?: number; + fillLinearGradientStartPointY?: number; + fillLinearGradientEndPoint?: Vector2d; + fillLinearGradientEndPointX?: number; + fillLinearGradientEndPointY?: number; + fillLinearGradientColorStops?: Array; + fillRadialGradientStartPoint?: Vector2d; + fillRadialGradientStartPointX?: number; + fillRadialGradientStartPointY?: number; + fillRadialGradientEndPoint?: Vector2d; + fillRadialGradientEndPointX?: number; + fillRadialGradientEndPointY?: number; + fillRadialGradientStartRadius?: number; + fillRadialGradientEndRadius?: number; + fillRadialGradientColorStops?: Array; + fillEnabled?: boolean; + fillPriority?: string; + stroke?: string; + strokeWidth?: number; + strokeScaleEnabled?: boolean; + strokeHitEnabled?: boolean; + strokeEnabled?: boolean; + lineJoin?: string; + lineCap?: string; + sceneFunc?: (con: Context, shape: Shape) => void; + hitFunc?: (con: Context, shape: Shape) => void; + shadowColor?: string; + shadowBlur?: number; + shadowOffset?: Vector2d; + shadowOffsetX?: number; + shadowOffsetY?: number; + shadowOpacity?: number; + shadowEnabled?: boolean; + shadowForStrokeEnabled?: boolean; + dash?: number[]; + dashEnabled?: boolean; + perfectDrawEnabled?: boolean; +} + var HAS_SHADOW = 'hasShadow'; var SHADOW_RGBA = 'shadowRGBA'; var patternImage = 'patternImage'; @@ -93,7 +147,9 @@ function _clearRadialGradientCache() { * } *}); */ -export class Shape extends Node { +export class Shape extends Node< + Config +> { _centroid: boolean; colorKey: string; @@ -102,7 +158,7 @@ export class Shape extends Node { _fillFuncHit: (ctx: Context) => void; _strokeFuncHit: (ctx: Context) => void; - constructor(config) { + constructor(config?: Config) { super(config); // set colorKey var key; diff --git a/src/Stage.ts b/src/Stage.ts index 54d51993..e8a7257a 100644 --- a/src/Stage.ts +++ b/src/Stage.ts @@ -1,6 +1,6 @@ import { Util, Collection } from './Util'; import { Factory } from './Factory'; -import { Container } from './Container'; +import { Container, ContainerConfig } from './Container'; import { Konva } from './Global'; import { SceneCanvas, HitCanvas } from './Canvas'; import { GetSet, Vector2d } from './types'; @@ -9,6 +9,10 @@ import { BaseLayer } from './BaseLayer'; import { DD } from './DragAndDrop'; import { _registerNode } from './Global'; +export interface StageConfig extends ContainerConfig { + container: HTMLDivElement | string; +} + // CONSTANTS var STAGE = 'Stage', STRING = 'string', @@ -117,7 +121,7 @@ export class Stage extends Container { children: Collection; - constructor(config) { + constructor(config: StageConfig) { super(checkNoClip(config)); this._buildDOM(); this._bindContentEvents(); diff --git a/src/Util.ts b/src/Util.ts index 09fa453f..1c935ca5 100644 --- a/src/Util.ts +++ b/src/Util.ts @@ -997,5 +997,12 @@ export const Util = { delete obj.visitedByCircularReferenceRemoval; return obj; + }, + // very simplified version of Object.assign + _assign(target: T, source: U) { + for (var key in source) { + (target)[key] = source[key]; + } + return target as T & U; } }; diff --git a/src/_CoreInternals.ts b/src/_CoreInternals.ts index 3befa1dc..5ba442bd 100644 --- a/src/_CoreInternals.ts +++ b/src/_CoreInternals.ts @@ -1,5 +1,4 @@ // what is core parts of Konva? - import { Konva as Global } from './Global'; import { Collection, Util } from './Util'; @@ -20,7 +19,9 @@ import { Shape, shapes } from './Shape'; import { Animation } from './Animation'; import { Tween, Easings } from './Tween'; -export const Konva = Object.assign(Global, { +Object.assign; + +export const Konva = Util._assign(Global, { Collection, Util, Node, diff --git a/src/_FullInternals.ts b/src/_FullInternals.ts index 85221596..86c7a3f2 100644 --- a/src/_FullInternals.ts +++ b/src/_FullInternals.ts @@ -42,7 +42,7 @@ import { Sepia } from './filters/Sepia'; import { Solarize } from './filters/Solarize'; import { Threshold } from './filters/Threshold'; -export const Konva = Object.assign(Core, { +export const Konva = Core.Util._assign(Core, { Arc, Arrow, Circle, diff --git a/src/index-types.d.ts b/src/index-types.d.ts new file mode 100644 index 00000000..6939e3a9 --- /dev/null +++ b/src/index-types.d.ts @@ -0,0 +1,159 @@ +// the purpose of that file is very stupid +// I was not able to generate correct typescript declarations from the main source code +// because right now Konva is an object. Typescript can not define types from object like this: +// const stage : Konva.Stage = new Konva.Stage(); +// we can convert Konva to namespace +// but I was not able to find a way to extend it +// so here we just need to define full API of Konva manually + +// filters +import { Blur } from './filters/Blur'; +import { Brighten } from './filters/Brighten'; +import { Contrast } from './filters/Contrast'; +import { Emboss } from './filters/Emboss'; +import { Enhance } from './filters/Enhance'; +import { Grayscale } from './filters/Grayscale'; +import { HSL } from './filters/HSL'; +import { HSV } from './filters/HSV'; +import { Invert } from './filters/Invert'; +import { Kaleidoscope } from './filters/Kaleidoscope'; +import { Mask } from './filters/Mask'; +import { Noise } from './filters/Noise'; +import { Pixelate } from './filters/Pixelate'; +import { Posterize } from './filters/Posterize'; +import { RGB } from './filters/RGB'; +import { RGBA } from './filters/RGBA'; +import { Sepia } from './filters/Sepia'; +import { Solarize } from './filters/Solarize'; +import { Threshold } from './filters/Threshold'; + +declare namespace Konva { + export let pixelRatio: number; + export let dragDistance: number; + export let angleDeg: boolean; + export let showWarnings: boolean; + export let dragButtons: Array; + export const isDragging: () => boolean; + export const isDragReady: () => boolean; + + export const Node: typeof import('./Node').Node; + export type Node = import('./Node').Node; + export type NodeConfig = import('./Node').NodeConfig; + + export const Container: typeof import('./Container').Container; + export type Container = import('./Container').Container; + export type ContainerConfig = import('./Container').ContainerConfig; + + export const Collection: typeof import('./Util').Collection; + export type Collection = import('./Util').Collection; + export const Util: typeof import('./Util').Util; + + export const Stage: typeof import('./Stage').Stage; + export type Stage = import('./Stage').Stage; + export const stages: typeof import('./Stage').stages; + + export const Layer: typeof import('./Layer').Layer; + export type Layer = import('./Layer').Layer; + export type LayerConfig = import('./BaseLayer').LayerConfig; + + export const FastLayer: typeof import('./FastLayer').FastLayer; + export type FastLayer = import('./FastLayer').FastLayer; + + export const Group: typeof import('./Group').Group; + export type Group = import('./Group').Group; + + export const DD: typeof import('./DragAndDrop').DD; + + export const Shape: typeof import('./Shape').Shape; + export type Shape = import('./Shape').Shape; + export type ShapeConfig = import('./Shape').ShapeConfig; + export const shapes: typeof import('./Shape').shapes; + + export const Animation: typeof import('./Animation').Animation; + export type Animation = import('./Animation').Animation; + + export const Tween: typeof import('./Tween').Tween; + export type Tween = import('./Tween').Tween; + export const Easings: typeof import('./Tween').Easings; + + export const Arc: typeof import('./shapes/Arc').Arc; + export type Arc = import('./shapes/Arc').Arc; + export type ArcConfig = import('./shapes/Arc').ArcConfig; + export const Arrow: typeof import('./shapes/Arrow').Arrow; + export type Arrow = import('./shapes/Arrow').Arrow; + export type ArrowConfig = import('./shapes/Arrow').ArrowConfig; + export const Circle: typeof import('./shapes/Circle').Circle; + export type Circle = import('./shapes/Circle').Circle; + export type CircleConfig = import('./shapes/Circle').CircleConfig; + export const Ellipse: typeof import('./shapes/Ellipse').Ellipse; + export type Ellipse = import('./shapes/Ellipse').Ellipse; + export type EllipseConfig = import('./shapes/Ellipse').EllipseConfig; + export const Image: typeof import('./shapes/Image').Image; + export type Image = import('./shapes/Image').Image; + export type ImageConfig = import('./shapes/Image').ImageConfig; + export const Label: typeof import('./shapes/Label').Label; + export type Label = import('./shapes/Label').Label; + export type LabelConfig = import('./shapes/Label').LabelConfig; + export const Tag: typeof import('./shapes/Label').Tag; + export type Tag = import('./shapes/Label').Tag; + export type TagConfig = import('./shapes/Label').TagConfig; + export const Line: typeof import('./shapes/Line').Line; + export type Line = import('./shapes/Line').Line; + export type LineConfig = import('./shapes/Line').LineConfig; + export const Path: typeof import('./shapes/Path').Path; + export type Path = import('./shapes/Path').Path; + export type PathConfig = import('./shapes/Path').PathConfig; + export const Rect: typeof import('./shapes/Rect').Rect; + export type Rect = import('./shapes/Rect').Rect; + export type RectConfig = import('./shapes/Rect').RectConfig; + export const RegularPolygon: typeof import('./shapes/RegularPolygon').RegularPolygon; + export type RegularPolygon = import('./shapes/RegularPolygon').RegularPolygon; + export type RegularPolygonConfig = import('./shapes/RegularPolygon').RegularPolygonConfig; + export const Ring: typeof import('./shapes/Ring').Ring; + export type Ring = import('./shapes/Ring').Ring; + export type RingConfig = import('./shapes/Ring').RingConfig; + export const Sprite: typeof import('./shapes/Sprite').Sprite; + export type Sprite = import('./shapes/Sprite').Sprite; + export type SpriteConfig = import('./shapes/Sprite').SpriteConfig; + export const Star: typeof import('./shapes/Star').Star; + export type Star = import('./shapes/Star').Star; + export type StarConfig = import('./shapes/Star').StarConfig; + export const Text: typeof import('./shapes/Text').Text; + export type Text = import('./shapes/Text').Text; + export type TextConfig = import('./shapes/Text').TextConfig; + export const TextPath: typeof import('./shapes/TextPath').TextPath; + export type TextPath = import('./shapes/TextPath').TextPath; + export type TextPathConfig = import('./shapes/TextPath').TextPathConfig; + export const Transformer: typeof import('./shapes/Transformer').Transformer; + export type Transformer = import('./shapes/Transformer').Transformer; + export type TransformerConfig = import('./shapes/Transformer').TransformerConfig; + export const Wedge: typeof import('./shapes/Wedge').Wedge; + export type Wedge = import('./shapes/Wedge').Wedge; + export type WedgeConfig = import('./shapes/Wedge').WedgeConfig; + + export type KonvaEventObject = import('./types').KonvaEventObject; + + export const Filters: { + Blur; + Brighten; + Contrast; + Emboss; + Enhance; + Grayscale; + HSL; + HSV; + Invert; + Kaleidoscope; + Mask; + Noise; + Pixelate; + Posterize; + RGB; + RGBA; + Sepia; + Solarize; + Threshold; + }; +} + +export default Konva; diff --git a/src/index-types.ts b/src/index-types.ts deleted file mode 100644 index f7fbc591..00000000 --- a/src/index-types.ts +++ /dev/null @@ -1,3 +0,0 @@ -import { Konva as Core } from './_FullInternals'; - -export default Core; diff --git a/src/_UMD.ts b/src/index-umd.ts similarity index 75% rename from src/_UMD.ts rename to src/index-umd.ts index d329ca6b..38140997 100644 --- a/src/_UMD.ts +++ b/src/index-umd.ts @@ -1,6 +1,4 @@ // main entry for umd build for rollup -// and for typescript generation - import { Konva } from './_FullInternals'; export default Konva; diff --git a/src/index.ts b/src/index.ts index 5cac3d89..08cfb979 100644 --- a/src/index.ts +++ b/src/index.ts @@ -1,3 +1,5 @@ +// main enter file of full Konva version + var Konva = require('./_FullInternals').Konva; // add Konva to global variable Konva._injectGlobal(Konva); diff --git a/src/shapes/Arc.ts b/src/shapes/Arc.ts index 731328d1..e26e7b77 100644 --- a/src/shapes/Arc.ts +++ b/src/shapes/Arc.ts @@ -1,11 +1,18 @@ import { Collection } from '../Util'; import { Factory } from '../Factory'; -import { Shape } from '../Shape'; +import { Shape, ShapeConfig } from '../Shape'; import { Konva } from '../Global'; import { GetSet } from '../types'; import { getNumberValidator, getBooleanValidator } from '../Validators'; import { _registerNode } from '../Global'; +export interface ArcConfig extends ShapeConfig { + angle: number; + innerRadius: number; + outerRadius: number; + clockwise?: boolean; +} + /** * Arc constructor * @constructor @@ -30,7 +37,7 @@ import { _registerNode } from '../Global'; * rotationDeg: -120 * }); */ -export class Arc extends Shape { +export class Arc extends Shape { _sceneFunc(context) { var angle = Konva.getAngle(this.angle()), clockwise = this.clockwise(); diff --git a/src/shapes/Arrow.ts b/src/shapes/Arrow.ts index c6fa6b41..4d3a5b94 100644 --- a/src/shapes/Arrow.ts +++ b/src/shapes/Arrow.ts @@ -5,6 +5,17 @@ import { GetSet } from '../types'; import { getNumberValidator } from '../Validators'; import { _registerNode } from '../Global'; +import { ShapeConfig } from '../Shape'; + +export interface ArrowConfig extends ShapeConfig { + points: number[]; + tension?: number; + closed?: boolean; + pointerLength?: number; + pointerWidth?: number; + pointerAtBeginning?: boolean; +} + /** * Arrow constructor * @constructor @@ -28,7 +39,7 @@ import { _registerNode } from '../Global'; * pointerWidth : 12 * }); */ -export class Arrow extends Line { +export class Arrow extends Line { _sceneFunc(ctx) { super._sceneFunc(ctx); var PI2 = Math.PI * 2; diff --git a/src/shapes/Circle.ts b/src/shapes/Circle.ts index 4af78fb5..ea35c960 100644 --- a/src/shapes/Circle.ts +++ b/src/shapes/Circle.ts @@ -1,10 +1,14 @@ import { Collection } from '../Util'; import { Factory } from '../Factory'; -import { Shape } from '../Shape'; +import { Shape, ShapeConfig } from '../Shape'; import { GetSet } from '../types'; import { getNumberValidator } from '../Validators'; import { _registerNode } from '../Global'; +export interface CircleConfig extends ShapeConfig { + radius: number; +} + /** * Circle constructor * @constructor @@ -23,7 +27,7 @@ import { _registerNode } from '../Global'; * strokeWidth: 5 * }); */ -export class Circle extends Shape { +export class Circle extends Shape { _sceneFunc(context) { context.beginPath(); context.arc(0, 0, this.radius(), 0, Math.PI * 2, false); diff --git a/src/shapes/Ellipse.ts b/src/shapes/Ellipse.ts index 4e95919b..1da532a6 100644 --- a/src/shapes/Ellipse.ts +++ b/src/shapes/Ellipse.ts @@ -1,11 +1,16 @@ import { Collection } from '../Util'; import { Factory } from '../Factory'; -import { Shape } from '../Shape'; +import { Shape, ShapeConfig } from '../Shape'; import { getNumberValidator } from '../Validators'; import { _registerNode } from '../Global'; import { GetSet, Vector2d } from '../types'; +export interface EllipseConfig extends ShapeConfig { + radiusX: number; + radiusY: number; +} + /** * Ellipse constructor * @constructor @@ -23,7 +28,7 @@ import { GetSet, Vector2d } from '../types'; * } * fill: 'red' * }); */ -export class Ellipse extends Shape { +export class Ellipse extends Shape { _sceneFunc(context) { var rx = this.radiusX(), ry = this.radiusY(); diff --git a/src/shapes/Image.ts b/src/shapes/Image.ts index 12426df7..60dacf56 100644 --- a/src/shapes/Image.ts +++ b/src/shapes/Image.ts @@ -1,13 +1,15 @@ import { Util, Collection } from '../Util'; import { Factory } from '../Factory'; -import { Shape } from '../Shape'; +import { Shape, ShapeConfig } from '../Shape'; import { getNumberValidator } from '../Validators'; import { _registerNode } from '../Global'; import { GetSet, IRect } from '../types'; -// CONSTANTS -var IMAGE = 'Image'; +export interface ImageConfig extends ShapeConfig { + image: ImageBitmapSource; + crop?: IRect; +} /** * Image constructor @@ -32,7 +34,7 @@ var IMAGE = 'Image'; * }; * imageObj.src = '/path/to/image.jpg' */ -export class Image extends Shape { +export class Image extends Shape { _useBufferCanvas() { return ( (this.hasShadow() || this.getAbsoluteOpacity() !== 1) && diff --git a/src/shapes/Label.ts b/src/shapes/Label.ts index b575d834..6a4fedae 100644 --- a/src/shapes/Label.ts +++ b/src/shapes/Label.ts @@ -1,12 +1,15 @@ import { Collection } from '../Util'; import { Factory } from '../Factory'; -import { Shape } from '../Shape'; +import { Shape, ShapeConfig } from '../Shape'; import { Group } from '../Group'; +import { ContainerConfig } from '../Container'; import { getNumberValidator } from '../Validators'; import { _registerNode } from '../Global'; import { GetSet } from '../types'; +export interface LabelConfig extends ContainerConfig {} + // constants var ATTR_CHANGE_LIST = [ 'fontFamily', @@ -170,6 +173,13 @@ _registerNode(Label); Collection.mapMethods(Label); +export interface TagConfig extends ShapeConfig { + pointerDirection?: string; + pointerWidth?: number; + pointerHeight?: number; + cornerRadius?: number; +} + /** * Tag constructor.  A Tag can be configured * to have a pointer element that points up, right, down, or left @@ -182,7 +192,7 @@ Collection.mapMethods(Label); * @param {Number} [config.pointerHeight] * @param {Number} [config.cornerRadius] */ -export class Tag extends Shape { +export class Tag extends Shape { _sceneFunc(context) { var width = this.width(), height = this.height(), diff --git a/src/shapes/Line.ts b/src/shapes/Line.ts index 5c29d830..253da802 100644 --- a/src/shapes/Line.ts +++ b/src/shapes/Line.ts @@ -1,11 +1,18 @@ import { Util, Collection } from '../Util'; import { Factory } from '../Factory'; -import { Shape } from '../Shape'; +import { Shape, ShapeConfig } from '../Shape'; import { getNumberValidator, getNumberArrayValidator } from '../Validators'; import { _registerNode } from '../Global'; import { GetSet } from '../types'; +export interface LineConfig extends ShapeConfig { + points: number[]; + tension?: number; + closed?: boolean; + bezier?: boolean; +} + /** * Line constructor.  Lines are defined by an array of points and * a tension @@ -30,8 +37,10 @@ import { GetSet } from '../types'; * }); */ -export class Line extends Shape { - constructor(config) { +export class Line extends Shape< + Config +> { + constructor(config?: Config) { super(config); this.on( 'pointsChange.konva tensionChange.konva closedChange.konva bezierChange.konva', diff --git a/src/shapes/Path.ts b/src/shapes/Path.ts index be13daa4..9ad9af42 100644 --- a/src/shapes/Path.ts +++ b/src/shapes/Path.ts @@ -1,10 +1,13 @@ -import { Util, Collection } from '../Util'; +import { Collection } from '../Util'; import { Factory } from '../Factory'; -import { Shape } from '../Shape'; +import { Shape, ShapeConfig } from '../Shape'; import { _registerNode } from '../Global'; import { GetSet } from '../types'; +export interface PathConfig extends ShapeConfig { + data: string; +} /** * Path constructor. * @author Jason Follas @@ -25,11 +28,11 @@ import { GetSet } from '../types'; * scaleY: 2 * }); */ -export class Path extends Shape { +export class Path extends Shape { dataArray = []; pathLength = 0; - constructor(config) { + constructor(config?: PathConfig) { super(config); this.dataArray = Path.parsePathData(this.data()); this.pathLength = 0; diff --git a/src/shapes/Rect.ts b/src/shapes/Rect.ts index 3e864095..8d5b6d57 100644 --- a/src/shapes/Rect.ts +++ b/src/shapes/Rect.ts @@ -1,10 +1,13 @@ import { Collection } from '../Util'; import { Factory } from '../Factory'; -import { Shape } from '../Shape'; +import { Shape, ShapeConfig } from '../Shape'; import { getNumberValidator } from '../Validators'; import { _registerNode } from '../Global'; import { GetSet } from '../types'; +export interface RectConfig extends ShapeConfig { + cornerRadius?: number; +} /** * Rect constructor @@ -24,7 +27,7 @@ import { GetSet } from '../types'; * strokeWidth: 5 * }); */ -export class Rect extends Shape { +export class Rect extends Shape { _sceneFunc(context) { var cornerRadius = this.cornerRadius(), width = this.width(), diff --git a/src/shapes/RegularPolygon.ts b/src/shapes/RegularPolygon.ts index 449f96a2..97852f58 100644 --- a/src/shapes/RegularPolygon.ts +++ b/src/shapes/RegularPolygon.ts @@ -1,10 +1,14 @@ import { Collection } from '../Util'; import { Factory } from '../Factory'; -import { Shape } from '../Shape'; +import { Shape, ShapeConfig } from '../Shape'; import { GetSet } from '../types'; import { getNumberValidator } from '../Validators'; import { _registerNode } from '../Global'; +export interface RegularPolygonConfig extends ShapeConfig { + sides: number; + radius: number; +} /** * RegularPolygon constructor. Examples include triangles, squares, pentagons, hexagons, etc. * @constructor @@ -26,7 +30,7 @@ import { _registerNode } from '../Global'; * strokeWidth: 4 * }); */ -export class RegularPolygon extends Shape { +export class RegularPolygon extends Shape { _sceneFunc(context) { var sides = this.sides(), radius = this.radius(), @@ -65,7 +69,7 @@ export class RegularPolygon extends Shape { RegularPolygon.prototype.className = 'RegularPolygon'; RegularPolygon.prototype._centroid = true; RegularPolygon.prototype._attrsAffectingSize = ['radius']; -_registerNode(RegularPolygon) +_registerNode(RegularPolygon); /** * get/set radius diff --git a/src/shapes/Ring.ts b/src/shapes/Ring.ts index af2a0bdc..79133e06 100644 --- a/src/shapes/Ring.ts +++ b/src/shapes/Ring.ts @@ -1,10 +1,16 @@ import { Collection } from '../Util'; import { Factory } from '../Factory'; -import { Shape } from '../Shape'; +import { Shape, ShapeConfig } from '../Shape'; import { GetSet } from '../types'; import { getNumberValidator } from '../Validators'; import { _registerNode } from '../Global'; +export interface RingConfig extends ShapeConfig { + innerRadius: number; + outerRadius: number; + clockwise?: boolean; +} + var PIx2 = Math.PI * 2; /** * Ring constructor @@ -26,7 +32,7 @@ var PIx2 = Math.PI * 2; * strokeWidth: 5 * }); */ -export class Ring extends Shape { +export class Ring extends Shape { _sceneFunc(context) { context.beginPath(); context.arc(0, 0, this.innerRadius(), 0, PIx2, false); diff --git a/src/shapes/Sprite.ts b/src/shapes/Sprite.ts index 2e514084..6626301f 100644 --- a/src/shapes/Sprite.ts +++ b/src/shapes/Sprite.ts @@ -1,12 +1,20 @@ import { Collection } from '../Util'; import { Factory } from '../Factory'; -import { Shape } from '../Shape'; +import { Shape, ShapeConfig } from '../Shape'; import { Animation } from '../Animation'; import { getNumberValidator } from '../Validators'; import { _registerNode } from '../Global'; import { GetSet } from '../types'; +export interface SpriteConfig extends ShapeConfig { + animation: string; + animations: any; + frameIndex?: number; + image: HTMLImageElement; + frameRate?: number; +} + /** * Sprite constructor * @constructor @@ -53,7 +61,7 @@ import { GetSet } from '../types'; * }; * imageObj.src = '/path/to/image.jpg' */ -export class Sprite extends Shape { +export class Sprite extends Shape { _updated = true; anim: Animation; interval: any; @@ -216,7 +224,6 @@ export class Sprite extends Shape { Sprite.prototype.className = 'Sprite'; _registerNode(Sprite); - // add getters setters Factory.addGetterSetter(Sprite, 'animation'); diff --git a/src/shapes/Star.ts b/src/shapes/Star.ts index 3fe2ce9a..98eff44e 100644 --- a/src/shapes/Star.ts +++ b/src/shapes/Star.ts @@ -1,11 +1,17 @@ import { Collection } from '../Util'; import { Factory } from '../Factory'; -import { Shape } from '../Shape'; +import { Shape, ShapeConfig } from '../Shape'; import { getNumberValidator } from '../Validators'; import { _registerNode } from '../Global'; import { GetSet } from '../types'; +export interface StarConfig extends ShapeConfig { + numPoints: number; + innerRadius: number; + outerRadius: number; +} + /** * Star constructor * @constructor @@ -29,7 +35,7 @@ import { GetSet } from '../types'; * strokeWidth: 4 * }); */ -export class Star extends Shape { +export class Star extends Shape { _sceneFunc(context) { var innerRadius = this.innerRadius(), outerRadius = this.outerRadius(), diff --git a/src/shapes/Text.ts b/src/shapes/Text.ts index 64eac3aa..889736ba 100644 --- a/src/shapes/Text.ts +++ b/src/shapes/Text.ts @@ -1,6 +1,6 @@ import { Util, Collection } from '../Util'; import { Factory } from '../Factory'; -import { Shape } from '../Shape'; +import { Shape, ShapeConfig } from '../Shape'; import { Konva } from '../Global'; import { getNumberValidator, @@ -11,6 +11,19 @@ import { _registerNode } from '../Global'; import { GetSet } from '../types'; +export interface TextConfig extends ShapeConfig { + text?: string; + fontFamily?: string; + fontSize?: number; + fontStyle?: string; + align?: string; + verticalAlign?: string; + padding?: number; + lineHeight?: number; + wrap?: string; + ellipsis?: boolean; +} + // constants var AUTO = 'auto', //CANVAS = 'canvas', @@ -111,7 +124,7 @@ function checkDefaultFill(config) { * fill: 'green' * }); */ -export class Text extends Shape { +export class Text extends Shape { textArr: Array<{ text: string; width: number }>; _partialText: string; _partialTextX = 0; @@ -119,7 +132,7 @@ export class Text extends Shape { textWidth: number; textHeight: number; - constructor(config) { + constructor(config?: TextConfig) { super(checkDefaultFill(config)); // update text data for certain attr changes for (var n = 0; n < attrChangeListLen; n++) { diff --git a/src/shapes/TextPath.ts b/src/shapes/TextPath.ts index 068eef8f..f425c485 100644 --- a/src/shapes/TextPath.ts +++ b/src/shapes/TextPath.ts @@ -1,6 +1,6 @@ import { Util, Collection } from '../Util'; import { Factory } from '../Factory'; -import { Shape } from '../Shape'; +import { Shape, ShapeConfig } from '../Shape'; import { Path } from './Path'; import { Text } from './Text'; import { getNumberValidator } from '../Validators'; @@ -8,6 +8,14 @@ import { _registerNode } from '../Global'; import { GetSet, Vector2d } from '../types'; +export interface TextPathConfig extends ShapeConfig { + text?: string; + data?: string; + fontFamily?: string; + fontSize?: number; + fontStyle?: string; +} + var EMPTY_STRING = '', NORMAL = 'normal'; @@ -62,7 +70,7 @@ function _strokeFunc(context) { * } * }); */ -export class TextPath extends Shape { +export class TextPath extends Shape { dummyCanvas = Util.createCanvasElement(); dataArray = []; glyphInfo: Array<{ @@ -77,7 +85,7 @@ export class TextPath extends Shape { textWidth: number; textHeight: number; - constructor(config) { + constructor(config?: TextPathConfig) { // call super constructor super(config); @@ -93,11 +101,11 @@ export class TextPath extends Shape { this._setTextData ); - if (config && config.getKerning) { + if (config && config['getKerning']) { Util.warn( 'getKerning TextPath API is deprecated. Please use "kerningFunc" instead.' ); - this.kerningFunc(config.getKerning); + this.kerningFunc(config['getKerning']); } this._setTextData(); diff --git a/src/shapes/Transformer.ts b/src/shapes/Transformer.ts index b2dd7293..2e20f7d2 100644 --- a/src/shapes/Transformer.ts +++ b/src/shapes/Transformer.ts @@ -4,12 +4,37 @@ import { Node } from '../Node'; import { Shape } from '../Shape'; import { Rect } from './Rect'; import { Group } from '../Group'; +import { ContainerConfig } from '../Container'; import { Konva } from '../Global'; import { getNumberValidator } from '../Validators'; import { _registerNode } from '../Global'; import { GetSet, IRect } from '../types'; +interface Box extends IRect { + rotation: number; +} + +export interface TransformerConfig extends ContainerConfig { + resizeEnabled?: boolean; + rotateEnabled?: boolean; + rotationSnaps?: Array; + rotateAnchorOffset?: number; + borderEnabled?: boolean; + borderStroke?: string; + borderStrokeWidth?: number; + borderDash?: Array; + anchorFill?: string; + anchorStroke?: string; + anchorStrokeWidth?: number; + anchorSize?: number; + keepRatio?: boolean; + centeredScaling?: boolean; + enabledAnchors?: Array; + node?: Rect; + boundBoxFunc?: (oldBox: Box, newBox: Box) => Box; +} + var ATTR_CHANGE_LIST = [ 'resizeEnabledChange', 'rotateAnchorOffsetChange', @@ -155,7 +180,7 @@ export class Transformer extends Group { cos: number; _cursorChange: boolean; - constructor(config) { + constructor(config?: TransformerConfig) { // call super constructor super(config); this._createElements(); diff --git a/src/shapes/Wedge.ts b/src/shapes/Wedge.ts index 3bfe1612..4e20fc14 100644 --- a/src/shapes/Wedge.ts +++ b/src/shapes/Wedge.ts @@ -1,12 +1,18 @@ import { Collection } from '../Util'; import { Factory } from '../Factory'; -import { Shape } from '../Shape'; +import { Shape, ShapeConfig } from '../Shape'; import { Konva } from '../Global'; import { getNumberValidator } from '../Validators'; import { _registerNode } from '../Global'; import { GetSet } from '../types'; +export interface WedgeConfig extends ShapeConfig { + angle: number; + radius: number; + clockwise?: boolean; +} + /** * Wedge constructor * @constructor @@ -29,7 +35,7 @@ import { GetSet } from '../types'; * rotationDeg: -120 * }); */ -export class Wedge extends Shape { +export class Wedge extends Shape { _sceneFunc(context) { context.beginPath(); context.arc( diff --git a/src/types.ts b/src/types.ts index ffb7166c..aca2fcf5 100644 --- a/src/types.ts +++ b/src/types.ts @@ -1,3 +1,6 @@ +import { Shape } from './Shape'; +import { Stage } from './Stage'; + export interface GetSet { (this: This): Type; (this: This, v: Type): This; @@ -14,3 +17,38 @@ export interface IRect { width: number; height: number; } + +export interface KonvaEventObject { + target: Shape | Stage; + evt: E; + currentTarget: Node; + cancelBubble: boolean; +} + +export type HandlerFunc = (e: KonvaEventObject) => void; + +export enum KonvaNodeEvent { + mouseover = 'mouseover', + mouseout = 'mouseout', + mousemove = 'mousemove', + mouseleave = 'mouseleave', + mouseenter = 'mouseenter', + mousedown = 'mousedown', + mouseup = 'mouseup', + wheel = 'wheel', + contextmenu = 'contextmenu', + click = 'click', + dblclick = 'dblclick', + touchstart = 'touchstart', + touchmove = 'touchmove', + touchend = 'touchend', + tap = 'tap', + dbltap = 'dbltap', + dragstart = 'dragstart', + dragmove = 'dragmove', + dragend = 'dragend' +} + +type KonvaEvent = KonvaNodeEvent; + +type KonvaEventString = KonvaEvent | string;