diff --git a/CHANGELOG.md b/CHANGELOG.md index f514cfb6b..0bd5ce86e 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -3,6 +3,11 @@ All notable changes to this project will be documented in this file. This project adheres to [Semantic Versioning](http://semver.org/). +## 9.3.16 (2024-10-21) + +- Fix freeze on ios on touch cancel event +- Typescript fixes + ## 9.3.15 (2024-09-09) - fix letter spacing for Hindi text diff --git a/package.json b/package.json index ec2414b50..d04c19d76 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "konva", - "version": "9.3.15", + "version": "9.3.16", "author": "Anton Lavrenov", "files": [ "README.md", @@ -20,7 +20,7 @@ "test": "npm run test:browser && npm run test:node", "test:build": "parcel build ./test/unit-tests.html --dist-dir ./test-build --target none --public-url ./ --no-source-maps", "test:browser": "npm run test:build && mocha-headless-chrome -f ./test-build/unit-tests.html -a disable-web-security", - "test:watch": "rm -rf ./.parcel-cache && parcel serve ./test/unit-tests.html ./test/manual-tests.html ./test/sandbox.html ./test/text-paths.html ./test/bunnies.html", + "test:watch": "rm -rf ./.parcel-cache && PARCEL_WORKERS=0 parcel serve ./test/unit-tests.html ./test/manual-tests.html ./test/sandbox.html ./test/text-paths.html ./test/bunnies.html", "test:node": "ts-mocha -r ./test/node-global-setup.mjs -p ./test/tsconfig.json test/unit/**/*.ts --exit && npm run test:import", "tsc": "tsc --removeComments", "rollup": "rollup -c --bundleConfigAsCjs", @@ -81,9 +81,6 @@ "parcel": "2.10.1", "process": "^0.11.10", "rollup": "^4.9.1", - "rollup-plugin-commonjs": "^10.1.0", - "rollup-plugin-node-resolve": "^5.2.0", - "rollup-plugin-sourcemaps": "^0.6.3", "rollup-plugin-typescript2": "^0.36.0", "size-limit": "^11.0.1", "ts-mocha": "^10.0.0", diff --git a/rollup.config.cjs b/rollup.config.cjs index d451ea781..3e7aa5100 100644 --- a/rollup.config.cjs +++ b/rollup.config.cjs @@ -1,5 +1,4 @@ // import resolve from 'rollup-plugin-node-resolve'; -import commonjs from 'rollup-plugin-commonjs'; import typescript from 'rollup-plugin-typescript2'; const pkg = require('./package.json'); diff --git a/src/Animation.ts b/src/Animation.ts index addb6aaf0..2f6bd5589 100644 --- a/src/Animation.ts +++ b/src/Animation.ts @@ -212,7 +212,7 @@ export class Animation { } } - for (let key in layerHash) { + for (const key in layerHash) { if (!layerHash.hasOwnProperty(key)) { continue; } diff --git a/src/BezierFunctions.ts b/src/BezierFunctions.ts index a05a936f9..b17a6492d 100644 --- a/src/BezierFunctions.ts +++ b/src/BezierFunctions.ts @@ -692,7 +692,6 @@ export const cValues = [ export const binomialCoefficients = [[1], [1, 1], [1, 2, 1], [1, 3, 3, 1]]; export const getCubicArcLength = (xs: number[], ys: number[], t: number) => { - let z: number; let sum: number; let correctedT: number; @@ -702,7 +701,7 @@ export const getCubicArcLength = (xs: number[], ys: number[], t: number) => { const n = 20; - z = t / 2; + const z = t / 2; sum = 0; for (let i = 0; i < n; i++) { correctedT = z * tValues[n][i] + z; diff --git a/src/Canvas.ts b/src/Canvas.ts index 62d766418..eb122941d 100644 --- a/src/Canvas.ts +++ b/src/Canvas.ts @@ -5,15 +5,15 @@ import { Factory } from './Factory'; import { getNumberValidator } from './Validators'; // calculate pixel ratio -var _pixelRatio; +let _pixelRatio; function getDevicePixelRatio() { if (_pixelRatio) { return _pixelRatio; } - var canvas = Util.createCanvasElement(); - var context = canvas.getContext('2d') as any; + const canvas = Util.createCanvasElement(); + const context = canvas.getContext('2d') as any; _pixelRatio = (function () { - var devicePixelRatio = Konva._global.devicePixelRatio || 1, + const devicePixelRatio = Konva._global.devicePixelRatio || 1, backingStoreRatio = context.webkitBackingStorePixelRatio || context.mozBackingStorePixelRatio || @@ -55,9 +55,9 @@ export class Canvas { isCache = false; constructor(config: ICanvasConfig) { - var conf = config || {}; + const conf = config || {}; - var pixelRatio = + const pixelRatio = conf.pixelRatio || Konva.pixelRatio || getDevicePixelRatio(); this.pixelRatio = pixelRatio; @@ -86,7 +86,7 @@ export class Canvas { return this.pixelRatio; } setPixelRatio(pixelRatio) { - var previousRatio = this.pixelRatio; + const previousRatio = this.pixelRatio; this.pixelRatio = pixelRatio; this.setSize( this.getWidth() / previousRatio, @@ -98,7 +98,7 @@ export class Canvas { this.width = this._canvas.width = width * this.pixelRatio; this._canvas.style.width = width + 'px'; - var pixelRatio = this.pixelRatio, + const pixelRatio = this.pixelRatio, _context = this.getContext()._context; _context.scale(pixelRatio, pixelRatio); } @@ -106,7 +106,7 @@ export class Canvas { // take into account pixel ratio this.height = this._canvas.height = height * this.pixelRatio; this._canvas.style.height = height + 'px'; - var pixelRatio = this.pixelRatio, + const pixelRatio = this.pixelRatio, _context = this.getContext()._context; _context.scale(pixelRatio, pixelRatio); } diff --git a/src/Container.ts b/src/Container.ts index d7bb54940..73d77a0b3 100644 --- a/src/Container.ts +++ b/src/Container.ts @@ -56,7 +56,7 @@ export abstract class Container< } const children = this.children || []; - var results: Array = []; + const results: Array = []; children.forEach(function (child) { if (filterFunc(child)) { results.push(child); @@ -128,7 +128,7 @@ export abstract class Container< return this; } if (children.length > 1) { - for (var i = 0; i < children.length; i++) { + for (let i = 0; i < children.length; i++) { this.add(children[i]); } return this; @@ -223,14 +223,14 @@ export abstract class Container< findOne( selector: string | Function ): ChildNode | undefined { - var result = this._generalFind(selector, true); + const result = this._generalFind(selector, true); return result.length > 0 ? result[0] : undefined; } _generalFind( selector: string | Function, findOne: boolean ) { - var retArr: Array = []; + const retArr: Array = []; this._descendants((node) => { const valid = node._isMatch(selector); @@ -265,7 +265,7 @@ export abstract class Container< } // extenders toObject() { - var obj = Node.prototype.toObject.call(this); + const obj = Node.prototype.toObject.call(this); obj.children = []; @@ -283,7 +283,7 @@ export abstract class Container< * @param {Konva.Node} node */ isAncestorOf(node: Node) { - var parent = node.getParent(); + let parent = node.getParent(); while (parent) { if (parent._id === this._id) { return true; @@ -295,7 +295,7 @@ export abstract class Container< } clone(obj?: any) { // call super method - var node = Node.prototype.clone.call(this, obj); + const node = Node.prototype.clone.call(this, obj); this.getChildren().forEach(function (no) { node.add(no.clone()); @@ -316,7 +316,7 @@ export abstract class Container< * @returns {Array} array of shapes */ getAllIntersections(pos) { - var arr: Shape[] = []; + const arr: Shape[] = []; this.find('Shape').forEach((shape) => { if (shape.isVisible() && shape.intersects(pos)) { @@ -344,20 +344,20 @@ export abstract class Container< this._requestDraw(); } drawScene(can?: SceneCanvas, top?: Node, bufferCanvas?: SceneCanvas) { - var layer = this.getLayer()!, + const layer = this.getLayer()!, canvas = can || (layer && layer.getCanvas()), context = canvas && canvas.getContext(), cachedCanvas = this._getCanvasCache(), cachedSceneCanvas = cachedCanvas && cachedCanvas.scene; - var caching = canvas && canvas.isCache; + const caching = canvas && canvas.isCache; if (!this.isVisible() && !caching) { return this; } if (cachedSceneCanvas) { context.save(); - var m = this.getAbsoluteTransform(top).getMatrix(); + const m = this.getAbsoluteTransform(top).getMatrix(); context.transform(m[0], m[1], m[2], m[3], m[4], m[5]); this._drawCachedSceneCanvas(context); context.restore(); @@ -371,7 +371,7 @@ export abstract class Container< return this; } - var layer = this.getLayer()!, + const layer = this.getLayer()!, canvas = can || (layer && layer.hitCanvas), context = canvas && canvas.getContext(), cachedCanvas = this._getCanvasCache(), @@ -379,7 +379,7 @@ export abstract class Container< if (cachedHitCanvas) { context.save(); - var m = this.getAbsoluteTransform(top).getMatrix(); + const m = this.getAbsoluteTransform(top).getMatrix(); context.transform(m[0], m[1], m[2], m[3], m[4], m[5]); this._drawCachedHitCanvas(context); context.restore(); @@ -389,7 +389,7 @@ export abstract class Container< return this; } _drawChildren(drawMethod, canvas, top, bufferCanvas?) { - var context = canvas && canvas.getContext(), + const context = canvas && canvas.getContext(), clipWidth = this.clipWidth(), clipHeight = this.clipHeight(), clipFunc = this.clipFunc(), @@ -401,16 +401,16 @@ export abstract class Container< if (hasClip) { context.save(); - var transform = this.getAbsoluteTransform(top); - var m = transform.getMatrix(); + const transform = this.getAbsoluteTransform(top); + let m = transform.getMatrix(); context.transform(m[0], m[1], m[2], m[3], m[4], m[5]); context.beginPath(); let clipArgs; if (clipFunc) { clipArgs = clipFunc.call(this, context, this); } else { - var clipX = this.clipX(); - var clipY = this.clipY(); + const clipX = this.clipX(); + const clipY = this.clipY(); context.rect(clipX || 0, clipY || 0, clipWidth, clipHeight); } context.clip.apply(context, clipArgs); @@ -418,7 +418,7 @@ export abstract class Container< context.transform(m[0], m[1], m[2], m[3], m[4], m[5]); } - var hasComposition = + const hasComposition = !selfCache && this.globalCompositeOperation() !== 'source-over' && drawMethod === 'drawScene'; @@ -448,24 +448,24 @@ export abstract class Container< relativeTo?: Container; } = {} ): IRect { - var skipTransform = config.skipTransform; - var relativeTo = config.relativeTo; + const skipTransform = config.skipTransform; + const relativeTo = config.relativeTo; - var minX, minY, maxX, maxY; - var selfRect = { + let minX, minY, maxX, maxY; + let selfRect = { x: Infinity, y: Infinity, width: 0, height: 0, }; - var that = this; + const that = this; this.children?.forEach(function (child) { // skip invisible children if (!child.visible()) { return; } - var rect = child.getClientRect({ + const rect = child.getClientRect({ relativeTo: that, skipShadow: config.skipShadow, skipStroke: config.skipStroke, @@ -491,10 +491,10 @@ export abstract class Container< }); // if child is group we need to make sure it has visible shapes inside - var shapes = this.find('Shape'); - var hasVisible = false; - for (var i = 0; i < shapes.length; i++) { - var shape = shapes[i]; + const shapes = this.find('Shape'); + let hasVisible = false; + for (let i = 0; i < shapes.length; i++) { + const shape = shapes[i]; if (shape._isVisible(this)) { hasVisible = true; break; diff --git a/src/Context.ts b/src/Context.ts index 5917a74e4..aeac2e07b 100644 --- a/src/Context.ts +++ b/src/Context.ts @@ -6,14 +6,12 @@ import { IRect } from './types'; import type { Node } from './Node'; function simplifyArray(arr: Array) { - var retArr: Array = [], + const retArr: Array = [], len = arr.length, - util = Util, - n, - val; + util = Util; - for (n = 0; n < len; n++) { - val = arr[n]; + for (let n = 0; n < len; n++) { + let val = arr[n]; if (util._isNumber(val)) { val = Math.round(val * 1000) / 1000; } else if (!util._isString(val)) { @@ -26,7 +24,7 @@ function simplifyArray(arr: Array) { return retArr; } -var COMMA = ',', +const COMMA = ',', OPEN_PAREN = '(', CLOSE_PAREN = ')', OPEN_PAREN_BRACKET = '([', @@ -71,7 +69,7 @@ var COMMA = ',', 'translate', ]; -var CONTEXT_PROPERTIES = [ +const CONTEXT_PROPERTIES = [ 'fillStyle', 'strokeStyle', 'shadowColor', @@ -124,7 +122,7 @@ interface ExtendedCanvasRenderingContext2D extends CanvasRenderingContext2D { export class Context { canvas: Canvas; _context: CanvasRenderingContext2D; - traceArr: Array; + traceArr: Array; constructor(canvas: Canvas) { this.canvas = canvas; @@ -183,7 +181,7 @@ export class Context { } getTrace(relaxed?: boolean, rounded?: boolean) { - var traceArr = this.traceArr, + let traceArr = this.traceArr, len = traceArr.length, str = '', n, @@ -231,7 +229,7 @@ export class Context { this.traceArr = []; } _trace(str) { - var traceArr = this.traceArr, + let traceArr = this.traceArr, len; traceArr.push(str); @@ -247,7 +245,7 @@ export class Context { * @name Konva.Context#reset */ reset() { - var pixelRatio = this.getCanvas().getPixelRatio(); + const pixelRatio = this.getCanvas().getPixelRatio(); this.setTransform(1 * pixelRatio, 0, 0, 1 * pixelRatio, 0, 0); } /** @@ -270,7 +268,7 @@ export class Context { * @param {Number} [bounds.height] */ clear(bounds?: IRect) { - var canvas = this.getCanvas(); + const canvas = this.getCanvas(); if (bounds) { this.clearRect( @@ -295,7 +293,7 @@ export class Context { } } _applyOpacity(shape: Node) { - var absOpacity = shape.getAbsoluteOpacity(); + const absOpacity = shape.getAbsoluteOpacity(); if (absOpacity !== 1) { this.setAttr('globalAlpha', absOpacity); } @@ -391,7 +389,7 @@ export class Context { * @name Konva.Context#createImageData */ createImageData(width, height) { - var a = arguments; + const a = arguments; if (a.length === 2) { return this._context.createImageData(width, height); } else if (a.length === 1) { @@ -446,7 +444,7 @@ export class Context { dHeight?: number ) { // this._context.drawImage(...arguments); - var a = arguments, + const a = arguments, _context = this._context; if (a.length === 3) { _context.drawImage(image, sx, sy); @@ -728,15 +726,15 @@ export class Context { this._context.translate(x, y); } _enableTrace() { - var that = this, + let that = this, len = CONTEXT_METHODS.length, origSetter = this.setAttr, n, args; // to prevent creating scope function at each loop - var func = function (methodName) { - var origMethod = that[methodName], + const func = function (methodName) { + let origMethod = that[methodName], ret; that[methodName] = function () { @@ -759,8 +757,8 @@ export class Context { // attrs that.setAttr = function () { origSetter.apply(that, arguments as any); - var prop = arguments[0]; - var val = arguments[1]; + const prop = arguments[0]; + let val = arguments[1]; if ( prop === 'shadowOffsetX' || prop === 'shadowOffsetY' || @@ -776,7 +774,7 @@ export class Context { } _applyGlobalCompositeOperation(node) { const op = node.attrs.globalCompositeOperation; - var def = !op || op === 'source-over'; + const def = !op || op === 'source-over'; if (!def) { this.setAttr('globalCompositeOperation', op); } @@ -810,7 +808,7 @@ export class SceneContext extends Context { }) as CanvasRenderingContext2D; } _fillColor(shape: Shape) { - var fill = shape.fill(); + const fill = shape.fill(); this.setAttr('fillStyle', fill); shape._fillFunc(this); @@ -820,7 +818,7 @@ export class SceneContext extends Context { shape._fillFunc(this); } _fillLinearGradient(shape: Shape) { - var grd = shape._getLinearGradient(); + const grd = shape._getLinearGradient(); if (grd) { this.setAttr('fillStyle', grd); @@ -881,21 +879,21 @@ export class SceneContext extends Context { if (colorStops) { // build color stops - for (var n = 0; n < colorStops.length; n += 2) { + for (let n = 0; n < colorStops.length; n += 2) { grd.addColorStop(colorStops[n] as number, colorStops[n + 1] as string); } this.setAttr('strokeStyle', grd); } } _stroke(shape) { - var dash = shape.dash(), + const dash = shape.dash(), // ignore strokeScaleEnabled for Text strokeScaleEnabled = shape.getStrokeScaleEnabled(); if (shape.hasStroke()) { if (!strokeScaleEnabled) { this.save(); - var pixelRatio = this.getCanvas().getPixelRatio(); + const pixelRatio = this.getCanvas().getPixelRatio(); this.setTransform(pixelRatio, 0, 0, pixelRatio, 0, 0); } @@ -911,7 +909,7 @@ export class SceneContext extends Context { this.setAttr('shadowColor', 'rgba(0,0,0,0)'); } - var hasLinearGradient = shape.getStrokeLinearGradientColorStops(); + const hasLinearGradient = shape.getStrokeLinearGradientColorStops(); if (hasLinearGradient) { this._strokeLinearGradient(shape); } else { @@ -926,7 +924,7 @@ export class SceneContext extends Context { } } _applyShadow(shape) { - var color = shape.getShadowRGBA() ?? 'black', + const color = shape.getShadowRGBA() ?? 'black', blur = shape.getShadowBlur() ?? 5, offset = shape.getShadowOffset() ?? { x: 0, @@ -971,13 +969,13 @@ export class HitContext extends Context { const strokeScaleEnabled = shape.getStrokeScaleEnabled(); if (!strokeScaleEnabled) { this.save(); - var pixelRatio = this.getCanvas().getPixelRatio(); + const pixelRatio = this.getCanvas().getPixelRatio(); this.setTransform(pixelRatio, 0, 0, pixelRatio, 0, 0); } this._applyLineCap(shape); - var hitStrokeWidth = shape.hitStrokeWidth(); - var strokeWidth = + const hitStrokeWidth = shape.hitStrokeWidth(); + const strokeWidth = hitStrokeWidth === 'auto' ? shape.strokeWidth() : hitStrokeWidth; this.setAttr('lineWidth', strokeWidth); diff --git a/src/DragAndDrop.ts b/src/DragAndDrop.ts index 271c73114..4bed333e5 100644 --- a/src/DragAndDrop.ts +++ b/src/DragAndDrop.ts @@ -6,7 +6,7 @@ import { Util } from './Util'; export const DD = { get isDragging() { - var flag = false; + let flag = false; DD._dragElements.forEach((elem) => { if (elem.dragStatus === 'dragging') { flag = true; @@ -17,7 +17,7 @@ export const DD = { justDragged: false, get node() { // return first dragging node - var node: Node | undefined; + let node: Node | undefined; DD._dragElements.forEach((elem) => { node = elem.node; }); @@ -62,8 +62,8 @@ export const DD = { return; } if (elem.dragStatus !== 'dragging') { - var dragDistance = node.dragDistance(); - var distance = Math.max( + const dragDistance = node.dragDistance(); + const distance = Math.max( Math.abs(pos.x - elem.startPointerPos.x), Math.abs(pos.y - elem.startPointerPos.y) ); @@ -161,10 +161,13 @@ export const DD = { if (Konva.isBrowser) { window.addEventListener('mouseup', DD._endDragBefore, true); window.addEventListener('touchend', DD._endDragBefore, true); + // add touchcancel to fix this: https://github.com/konvajs/konva/issues/1843 + window.addEventListener('touchcancel', DD._endDragBefore, true); window.addEventListener('mousemove', DD._drag); window.addEventListener('touchmove', DD._drag); window.addEventListener('mouseup', DD._endDragAfter, false); window.addEventListener('touchend', DD._endDragAfter, false); + window.addEventListener('touchcancel', DD._endDragAfter, false); } diff --git a/src/Factory.ts b/src/Factory.ts index e50029579..e86117b35 100644 --- a/src/Factory.ts +++ b/src/Factory.ts @@ -2,7 +2,7 @@ import { Node } from './Node'; import { Util } from './Util'; import { getComponentValidator } from './Validators'; -var GET = 'get', +const GET = 'get', SET = 'set'; export const Factory = { @@ -12,25 +12,25 @@ export const Factory = { Factory.addOverloadedGetterSetter(constructor, attr); }, addGetter(constructor, attr, def?) { - var method = GET + Util._capitalize(attr); + const method = GET + Util._capitalize(attr); constructor.prototype[method] = constructor.prototype[method] || function (this: Node) { - var val = this.attrs[attr]; + const val = this.attrs[attr]; return val === undefined ? def : val; }; }, addSetter(constructor, attr, validator?, after?) { - var method = SET + Util._capitalize(attr); + const method = SET + Util._capitalize(attr); if (!constructor.prototype[method]) { Factory.overWriteSetter(constructor, attr, validator, after); } }, overWriteSetter(constructor, attr, validator?, after?) { - var method = SET + Util._capitalize(attr); + const method = SET + Util._capitalize(attr); constructor.prototype[method] = function (val) { if (validator && val !== undefined && val !== null) { val = validator.call(this, val, attr); @@ -52,31 +52,28 @@ export const Factory = { validator?: Function, after?: Function ) { - var len = components.length, + const len = components.length, capitalize = Util._capitalize, getter = GET + capitalize(attr), - setter = SET + capitalize(attr), - n, - component; + setter = SET + capitalize(attr); // getter constructor.prototype[getter] = function () { - var ret = {}; + const ret = {}; - for (n = 0; n < len; n++) { - component = components[n]; + for (let n = 0; n < len; n++) { + const component = components[n]; ret[component] = this.getAttr(attr + capitalize(component)); } return ret; }; - var basicValidator = getComponentValidator(components); + const basicValidator = getComponentValidator(components); // setter constructor.prototype[setter] = function (val) { - var oldVal = this.attrs[attr], - key; + const oldVal = this.attrs[attr]; if (validator) { val = validator.call(this, val); @@ -86,7 +83,7 @@ export const Factory = { basicValidator.call(this, val, attr); } - for (key in val) { + for (const key in val) { if (!val.hasOwnProperty(key)) { continue; } @@ -110,7 +107,7 @@ export const Factory = { Factory.addOverloadedGetterSetter(constructor, attr); }, addOverloadedGetterSetter(constructor, attr) { - var capitalizedAttr = Util._capitalize(attr), + const capitalizedAttr = Util._capitalize(attr), setter = SET + capitalizedAttr, getter = GET + capitalizedAttr; @@ -127,14 +124,14 @@ export const Factory = { addDeprecatedGetterSetter(constructor, attr, def, validator) { Util.error('Adding deprecated ' + attr); - var method = GET + Util._capitalize(attr); + const method = GET + Util._capitalize(attr); - var message = + const message = attr + ' property is deprecated and will be removed soon. Look at Konva change log for more information.'; constructor.prototype[method] = function () { Util.error(message); - var val = this.attrs[attr]; + const val = this.attrs[attr]; return val === undefined ? def : val; }; Factory.addSetter(constructor, attr, validator, function () { @@ -144,9 +141,9 @@ export const Factory = { }, backCompat(constructor, methods) { Util.each(methods, function (oldMethodName, newMethodName) { - var method = constructor.prototype[newMethodName]; - var oldGetter = GET + Util._capitalize(oldMethodName); - var oldSetter = SET + Util._capitalize(oldMethodName); + const method = constructor.prototype[newMethodName]; + const oldGetter = GET + Util._capitalize(oldMethodName); + const oldSetter = SET + Util._capitalize(oldMethodName); function deprecated(this: Node) { method.apply(this, arguments); diff --git a/src/Group.ts b/src/Group.ts index 8992aa277..77e83ad72 100644 --- a/src/Group.ts +++ b/src/Group.ts @@ -19,7 +19,7 @@ export interface GroupConfig extends ContainerConfig {} */ export class Group extends Container { _validateAdd(child: Node) { - var type = child.getType(); + const type = child.getType(); if (type !== 'Group' && type !== 'Shape') { Util.throw('You may only add groups and shapes to groups.'); } diff --git a/src/Layer.ts b/src/Layer.ts index 4e5ff9612..8e94c1d17 100644 --- a/src/Layer.ts +++ b/src/Layer.ts @@ -18,7 +18,7 @@ export interface LayerConfig extends ContainerConfig { } // constants -var HASH = '#', +const HASH = '#', BEFORE_DRAW = 'beforeDraw', DRAW = 'draw', /* @@ -116,7 +116,7 @@ export class Layer extends Container { // extend Node.prototype.setZIndex setZIndex(index) { super.setZIndex(index); - var stage = this.getStage(); + const stage = this.getStage(); if (stage && stage.content) { stage.content.removeChild(this.getNativeCanvasElement()); @@ -133,7 +133,7 @@ export class Layer extends Container { } moveToTop() { Node.prototype.moveToTop.call(this); - var stage = this.getStage(); + const stage = this.getStage(); if (stage && stage.content) { stage.content.removeChild(this.getNativeCanvasElement()); stage.content.appendChild(this.getNativeCanvasElement()); @@ -141,11 +141,11 @@ export class Layer extends Container { return true; } moveUp() { - var moved = Node.prototype.moveUp.call(this); + const moved = Node.prototype.moveUp.call(this); if (!moved) { return false; } - var stage = this.getStage(); + const stage = this.getStage(); if (!stage || !stage.content) { return false; } @@ -164,9 +164,9 @@ export class Layer extends Container { // extend Node.prototype.moveDown moveDown() { if (Node.prototype.moveDown.call(this)) { - var stage = this.getStage(); + const stage = this.getStage(); if (stage) { - var children = stage.children; + const children = stage.children; if (stage.content) { stage.content.removeChild(this.getNativeCanvasElement()); stage.content.insertBefore( @@ -182,9 +182,9 @@ export class Layer extends Container { // extend Node.prototype.moveToBottom moveToBottom() { if (Node.prototype.moveToBottom.call(this)) { - var stage = this.getStage(); + const stage = this.getStage(); if (stage) { - var children = stage.children; + const children = stage.children; if (stage.content) { stage.content.removeChild(this.getNativeCanvasElement()); stage.content.insertBefore( @@ -201,7 +201,7 @@ export class Layer extends Container { return this; } remove() { - var _canvas = this.getNativeCanvasElement(); + const _canvas = this.getNativeCanvasElement(); Node.prototype.remove.call(this); @@ -220,7 +220,7 @@ export class Layer extends Container { return this; } _validateAdd(child) { - var type = child.getType(); + const type = child.getType(); if (type !== 'Group' && type !== 'Shape') { Util.throw('You may only add groups and shapes to a layer.'); } @@ -325,8 +325,8 @@ export class Layer extends Container { } // in some cases antialiased area may be bigger than 1px // it is possible if we will cache node, then scale it a lot - var spiralSearchDistance = 1; - var continueSearch = false; + let spiralSearchDistance = 1; + let continueSearch = false; while (true) { for (let i = 0; i < INTERSECTION_OFFSETS_LEN; i++) { const intersectionOffset = INTERSECTION_OFFSETS[i]; @@ -386,7 +386,7 @@ export class Layer extends Container { return {}; } drawScene(can?: SceneCanvas, top?: Node) { - var layer = this.getLayer(), + const layer = this.getLayer(), canvas = can || (layer && layer.getCanvas()); this._fire(BEFORE_DRAW, { @@ -406,7 +406,7 @@ export class Layer extends Container { return this; } drawHit(can?: HitCanvas, top?: Node) { - var layer = this.getLayer(), + const layer = this.getLayer(), canvas = can || (layer && layer.hitCanvas); if (layer && layer.clearBeforeDraw()) { @@ -460,8 +460,8 @@ export class Layer extends Container { if (!this.parent || !this.parent['content']) { return; } - var parent = this.parent as any; - var added = !!this.hitCanvas._canvas.parentNode; + const parent = this.parent as any; + const added = !!this.hitCanvas._canvas.parentNode; if (added) { parent.content.removeChild(this.hitCanvas._canvas); } else { diff --git a/src/Node.ts b/src/Node.ts index 98a2f1eeb..a23ad3971 100644 --- a/src/Node.ts +++ b/src/Node.ts @@ -77,7 +77,7 @@ export interface NodeConfig { } // CONSTANTS -var ABSOLUTE_OPACITY = 'absoluteOpacity', +const ABSOLUTE_OPACITY = 'absoluteOpacity', ALL_LISTENERS = 'allEventListeners', ABSOLUTE_TRANSFORM = 'absoluteTransform', ABSOLUTE_SCALE = 'absoluteScale', @@ -193,12 +193,12 @@ export abstract class Node { } } _getCache(attr: string, privateGetter: Function) { - var cache = this._cache.get(attr); + let cache = this._cache.get(attr); // for transform the cache can be NOT empty // but we still need to recalculate it if it is dirty - var isTransform = attr === TRANSFORM || attr === ABSOLUTE_TRANSFORM; - var invalid = cache === undefined || (isTransform && cache.dirty === true); + const isTransform = attr === TRANSFORM || attr === ABSOLUTE_TRANSFORM; + const invalid = cache === undefined || (isTransform && cache.dirty === true); // if not cached, we need to set it using the private getter method. if (invalid) { @@ -311,8 +311,8 @@ export abstract class Node { imageSmoothingEnabled?: boolean; hitCanvasPixelRatio?: number; }) { - var conf = config || {}; - var rect = {} as IRect; + const conf = config || {}; + let rect = {} as IRect; // don't call getClientRect if we have all attributes // it means call it only if have one undefined @@ -327,7 +327,7 @@ export abstract class Node { relativeTo: this.getParent() || undefined, }); } - var width = Math.ceil(conf.width || rect.width), + let width = Math.ceil(conf.width || rect.width), height = Math.ceil(conf.height || rect.height), pixelRatio = conf.pixelRatio, x = conf.x === undefined ? Math.floor(rect.x) : conf.x, @@ -365,7 +365,7 @@ export abstract class Node { // console.log({ x, y, width, height }, rect); - var cachedSceneCanvas = new SceneCanvas({ + const cachedSceneCanvas = new SceneCanvas({ pixelRatio: pixelRatio, width: width, height: height, @@ -498,19 +498,19 @@ export abstract class Node { throw new Error('abstract "getClientRect" method call'); } _transformedRect(rect: IRect, top?: Node | null) { - var points = [ + const points = [ { x: rect.x, y: rect.y }, { x: rect.x + rect.width, y: rect.y }, { x: rect.x + rect.width, y: rect.y + rect.height }, { x: rect.x, y: rect.y + rect.height }, ]; - var minX: number = Infinity, + let minX: number = Infinity, minY: number = Infinity, maxX: number = -Infinity, maxY: number = -Infinity; - var trans = this.getAbsoluteTransform(top); + const trans = this.getAbsoluteTransform(top); points.forEach(function (point) { - var transformed = trans.point(point); + const transformed = trans.point(point); if (minX === undefined) { minX = maxX = transformed.x; minY = maxY = transformed.y; @@ -535,8 +535,8 @@ export abstract class Node { const canvasCache = this._getCanvasCache(); context.translate(canvasCache.x, canvasCache.y); - var cacheCanvas = this._getCachedSceneCanvas(); - var ratio = cacheCanvas.pixelRatio; + const cacheCanvas = this._getCachedSceneCanvas(); + const ratio = cacheCanvas.pixelRatio; context.drawImage( cacheCanvas._canvas, @@ -548,7 +548,7 @@ export abstract class Node { context.restore(); } _drawCachedHitCanvas(context: Context) { - var canvasCache = this._getCanvasCache(), + const canvasCache = this._getCanvasCache(), hitCanvas = canvasCache.hit; context.save(); context.translate(canvasCache.x, canvasCache.y); @@ -562,7 +562,7 @@ export abstract class Node { context.restore(); } _getCachedSceneCanvas() { - var filters = this.filters(), + let filters = this.filters(), cachedCanvas = this._getCanvasCache(), sceneCanvas = cachedCanvas.scene, filterCanvas = cachedCanvas.filter, @@ -574,7 +574,7 @@ export abstract class Node { if (filters) { if (!this._filterUpToDate) { - var ratio = sceneCanvas.pixelRatio; + const ratio = sceneCanvas.pixelRatio; filterCanvas.setSize( sceneCanvas.width / sceneCanvas.pixelRatio, sceneCanvas.height / sceneCanvas.pixelRatio @@ -697,7 +697,7 @@ export abstract class Node { if (arguments.length === 3) { return this._delegate.apply(this, arguments as any); } - var events = (evtStr as string).split(SPACE), + let events = (evtStr as string).split(SPACE), len = events.length, n, event, @@ -751,7 +751,7 @@ export abstract class Node { * node.off('click.foo'); */ off(evtStr?: string, callback?: Function) { - var events = (evtStr || '').split(SPACE), + let events = (evtStr || '').split(SPACE), len = events.length, n, t, @@ -788,7 +788,7 @@ export abstract class Node { } // some event aliases for third party integration like HammerJS dispatchEvent(evt: any) { - var e = { + const e = { target: this, type: evt.type, evt: evt, @@ -809,10 +809,10 @@ export abstract class Node { } // like node.on _delegate(event: string, selector: string, handler: (e: Event) => void) { - var stopNode = this; + const stopNode = this; this.on(event, function (evt) { - var targets = evt.target.findAncestors(selector, true, stopNode); - for (var i = 0; i < targets.length; i++) { + const targets = evt.target.findAncestors(selector, true, stopNode); + for (let i = 0; i < targets.length; i++) { evt = Util.cloneObject(evt); evt.currentTarget = targets[i] as any; handler.call(targets[i], evt as any); @@ -850,7 +850,7 @@ export abstract class Node { // traversal must be cleared when removing a node this._clearCaches(); - var parent = this.getParent(); + const parent = this.getParent(); if (parent && parent.children) { parent.children.splice(this.index, 1); @@ -881,7 +881,7 @@ export abstract class Node { * var x = node.getAttr('x'); */ getAttr(attr: string) { - var method = 'get' + Util._capitalize(attr); + const method = 'get' + Util._capitalize(attr); if (Util._isFunction((this as any)[method])) { return (this as any)[method](); } @@ -899,7 +899,7 @@ export abstract class Node { * }) */ getAncestors() { - var parent = this.getParent(), + let parent = this.getParent(), ancestors: Array = []; while (parent) { @@ -932,7 +932,7 @@ export abstract class Node { */ setAttrs(config: any) { this._batchTransformChanges(() => { - var key, method; + let key, method; if (!config) { return this; } @@ -1016,9 +1016,9 @@ export abstract class Node { if (top) { return this._isVisible(top) && this._isListening(top); } - var layer = this.getLayer(); + const layer = this.getLayer(); - var layerUnderDrag = false; + let layerUnderDrag = false; DD._dragElements.forEach((elem) => { if (elem.dragStatus !== 'dragging') { return; @@ -1029,7 +1029,7 @@ export abstract class Node { } }); - var dragSkip = + const dragSkip = !skipDragCheck && !Konva.hitOnDragEnabled && (layerUnderDrag || Konva.isTransforming()); @@ -1067,7 +1067,7 @@ export abstract class Node { * @returns {Integer} */ getAbsoluteZIndex() { - var depth = this.getDepth(), + let depth = this.getDepth(), that = this, index = 0, nodes, @@ -1111,7 +1111,7 @@ export abstract class Node { * @returns {Integer} */ getDepth() { - var depth = 0, + let depth = 0, parent = this.parent; while (parent) { @@ -1167,11 +1167,11 @@ export abstract class Node { return null; } // get pointer (say mouse or touch) position - var pos = stage.getPointerPosition(); + const pos = stage.getPointerPosition(); if (!pos) { return null; } - var transform = this.getAbsoluteTransform().copy(); + const transform = this.getAbsoluteTransform().copy(); // to detect relative position we need to invert transform transform.invert(); // now we can find relative point @@ -1207,7 +1207,7 @@ export abstract class Node { // "true" is not a node, but it will just allow skip all caching top = true as any; } - var absoluteMatrix = this.getAbsoluteTransform(top).getMatrix(), + const absoluteMatrix = this.getAbsoluteTransform(top).getMatrix(), absoluteTransform = new Transform(), offset = this.offset(); @@ -1226,7 +1226,7 @@ export abstract class Node { // important, use non cached value this._clearCache(TRANSFORM); - var it = this._getAbsoluteTransform().copy(); + const it = this._getAbsoluteTransform().copy(); it.invert(); it.translate(pos.x, pos.y); @@ -1242,7 +1242,7 @@ export abstract class Node { return this; } _setTransform(trans) { - var key; + let key; for (key in trans) { this.attrs[key] = trans[key]; @@ -1251,7 +1251,7 @@ export abstract class Node { // this._clearSelfAndDescendantCache(ABSOLUTE_TRANSFORM); } _clearTransform() { - var trans = { + const trans = { x: this.x(), y: this.y(), rotation: this.rotation(), @@ -1292,7 +1292,7 @@ export abstract class Node { * }); */ move(change: Vector2d) { - var changeX = change.x, + let changeX = change.x, changeY = change.y, x = this.x(), y = this.y(); @@ -1309,7 +1309,7 @@ export abstract class Node { return this; } _eachAncestorReverse(func, top) { - var family: Array = [], + let family: Array = [], parent = this.getParent(), len, n; @@ -1356,7 +1356,7 @@ export abstract class Node { Util.warn('Node has no parent. moveToTop function is ignored.'); return false; } - var index = this.index, + const index = this.index, len = this.parent.getChildren().length; if (index < len - 1) { this.parent.children.splice(index, 1); @@ -1377,7 +1377,7 @@ export abstract class Node { Util.warn('Node has no parent. moveUp function is ignored.'); return false; } - var index = this.index, + const index = this.index, len = this.parent.getChildren().length; if (index < len - 1) { this.parent.children.splice(index, 1); @@ -1398,7 +1398,7 @@ export abstract class Node { Util.warn('Node has no parent. moveDown function is ignored.'); return false; } - var index = this.index; + const index = this.index; if (index > 0) { this.parent.children.splice(index, 1); this.parent.children.splice(index - 1, 0, this); @@ -1418,7 +1418,7 @@ export abstract class Node { Util.warn('Node has no parent. moveToBottom function is ignored.'); return false; } - var index = this.index; + const index = this.index; if (index > 0) { this.parent.children.splice(index, 1); this.parent.children.unshift(this); @@ -1441,7 +1441,7 @@ export abstract class Node { '.' ); } - var index = this.index; + const index = this.index; this.parent.children.splice(index, 1); this.parent.children.splice(zIndex, 0, this); this.parent._setChildrenIndices(); @@ -1457,8 +1457,8 @@ export abstract class Node { return this._getCache(ABSOLUTE_OPACITY, this._getAbsoluteOpacity); } _getAbsoluteOpacity() { - var absOpacity = this.opacity(); - var parent = this.getParent(); + let absOpacity = this.opacity(); + const parent = this.getParent(); if (parent && !parent._isUnderCache) { absOpacity *= parent.getAbsoluteOpacity(); } @@ -1489,7 +1489,7 @@ export abstract class Node { * @returns {Object} */ toObject() { - var attrs = this.getAttrs() as any, + let attrs = this.getAttrs() as any, key, val, getter, @@ -1562,12 +1562,12 @@ export abstract class Node { includeSelf?: boolean, stopNode?: Node ) { - var res: Array = []; + const res: Array = []; if (includeSelf && this._isMatch(selector)) { res.push(this); } - var ancestor = this.parent; + let ancestor = this.parent; while (ancestor) { if (ancestor === stopNode) { return res; @@ -1609,7 +1609,7 @@ export abstract class Node { if (typeof selector === 'function') { return selector(this); } - var selectorArr = selector.replace(/ /g, '').split(','), + let selectorArr = selector.replace(/ /g, '').split(','), len = selectorArr.length, n, sel; @@ -1650,7 +1650,7 @@ export abstract class Node { * @returns {Konva.Layer} */ getLayer(): Layer | null { - var parent = this.getParent(); + const parent = this.getParent(); return parent ? parent.getLayer() : null; } /** @@ -1664,7 +1664,7 @@ export abstract class Node { } _getStage() { - var parent = this.getParent(); + const parent = this.getParent(); if (parent) { return parent.getStage(); } else { @@ -1726,13 +1726,13 @@ export abstract class Node { } } _getAbsoluteTransform(top?: Node) { - var at: Transform; + let at: Transform; // we we need position relative to an ancestor, we will iterate for all if (top) { at = new Transform(); // start with stage and traverse downwards to self this._eachAncestorReverse(function (node: Node) { - var transformsEnabled = node.transformsEnabled(); + const transformsEnabled = node.transformsEnabled(); if (transformsEnabled === 'all') { at.multiply(node.getTransform()); @@ -1750,7 +1750,7 @@ export abstract class Node { } else { at.reset(); } - var transformsEnabled = this.transformsEnabled(); + const transformsEnabled = this.transformsEnabled(); if (transformsEnabled === 'all') { at.multiply(this.getTransform()); } else if (transformsEnabled === 'position') { @@ -1780,7 +1780,7 @@ export abstract class Node { // do not cache this calculations, // because it use cache transform // this is special logic for caching with some shapes with shadow - var parent: Node | null = this; + let parent: Node | null = this; while (parent) { if (parent._isUnderCache) { top = parent; @@ -1827,13 +1827,13 @@ export abstract class Node { return this._getCache(TRANSFORM, this._getTransform) as Transform; } _getTransform(): Transform { - var m: Transform = this._cache.get(TRANSFORM) || new Transform(); + const m: Transform = this._cache.get(TRANSFORM) || new Transform(); m.reset(); // I was trying to use attributes directly here // but it doesn't work for Transformer well // because it overwrite x,y getters - var x = this.x(), + const x = this.x(), y = this.y(), rotation = Konva.getAngle(this.rotation()), scaleX = this.attrs.scaleX ?? 1, @@ -1882,7 +1882,7 @@ export abstract class Node { */ clone(obj?: any) { // instantiate new node - var attrs = Util.cloneObject(this.attrs), + let attrs = Util.cloneObject(this.attrs), key, allListeners, len, @@ -1893,7 +1893,7 @@ export abstract class Node { attrs[key] = obj[key]; } - var node = new (this.constructor)(attrs); + const node = new (this.constructor)(attrs); // copy over listeners for (key in this.eventListeners) { allListeners = this.eventListeners[key]; @@ -1918,9 +1918,9 @@ export abstract class Node { _toKonvaCanvas(config) { config = config || {}; - var box = this.getClientRect(); + const box = this.getClientRect(); - var stage = this.getStage(), + const stage = this.getStage(), x = config.x !== undefined ? config.x : Math.floor(box.x), y = config.y !== undefined ? config.y : Math.floor(box.y), pixelRatio = config.pixelRatio || 1, @@ -2013,9 +2013,9 @@ export abstract class Node { callback?: (str: string) => void; }) { config = config || {}; - var mimeType = config.mimeType || null, + const mimeType = config.mimeType || null, quality = config.quality || null; - var url = this._toKonvaCanvas(config).toDataURL(mimeType, quality); + const url = this._toKonvaCanvas(config).toDataURL(mimeType, quality); if (config.callback) { config.callback(url); } @@ -2163,7 +2163,7 @@ export abstract class Node { } } _off(type, name?, callback?) { - var evtListeners = this.eventListeners[type], + let evtListeners = this.eventListeners[type], i, evtName, handler; @@ -2209,8 +2209,8 @@ export abstract class Node { */ addName(name) { if (!this.hasName(name)) { - var oldName = this.name(); - var newName = oldName ? oldName + ' ' + name : name; + const oldName = this.name(); + const newName = oldName ? oldName + ' ' + name : name; this.name(newName); } return this; @@ -2236,7 +2236,7 @@ export abstract class Node { return false; } // if name is '' the "names" will be [''], so I added extra check above - var names = (fullName || '').split(/\s/g); + const names = (fullName || '').split(/\s/g); return names.indexOf(name) !== -1; } /** @@ -2252,8 +2252,8 @@ export abstract class Node { * node.name(); // return 'red' */ removeName(name) { - var names = (this.name() || '').split(/\s/g); - var index = names.indexOf(name); + const names = (this.name() || '').split(/\s/g); + const index = names.indexOf(name); if (index !== -1) { names.splice(index, 1); this.name(names.join(' ')); @@ -2271,7 +2271,7 @@ export abstract class Node { * node.setAttr('x', 5); */ setAttr(attr, val) { - var func = this[SET + Util._capitalize(attr)]; + const func = this[SET + Util._capitalize(attr)]; if (Util._isFunction(func)) { func.call(this, val); @@ -2288,7 +2288,7 @@ export abstract class Node { } } _setAttr(key, val) { - var oldVal = this.attrs[key]; + const oldVal = this.attrs[key]; if (oldVal === val && !Util.isObject(val)) { return; } @@ -2303,7 +2303,7 @@ export abstract class Node { this._requestDraw(); } _setComponentAttr(key, component, val) { - var oldVal; + let oldVal; if (val !== undefined) { oldVal = this.attrs[key]; @@ -2321,7 +2321,7 @@ export abstract class Node { evt.target = this; } - var shouldStop = + const shouldStop = (eventType === MOUSEENTER || eventType === MOUSELEAVE) && ((compareShape && (this === compareShape || @@ -2332,7 +2332,7 @@ export abstract class Node { this._fire(eventType, evt); // simulate event bubbling - var stopBubble = + const stopBubble = (eventType === MOUSEENTER || eventType === MOUSELEAVE) && compareShape && compareShape.isAncestorOf && @@ -2407,13 +2407,13 @@ export abstract class Node { // drag & drop _createDragElement(evt) { - var pointerId = evt ? evt.pointerId : undefined; - var stage = this.getStage(); - var ap = this.getAbsolutePosition(); + const pointerId = evt ? evt.pointerId : undefined; + const stage = this.getStage(); + const ap = this.getAbsolutePosition(); if (!stage) { return; } - var pos = + const pos = stage._getPointerById(pointerId) || stage._changedPointerPositions[0] || ap; @@ -2460,12 +2460,12 @@ export abstract class Node { if (!pos) { return; } - var newNodePos = { + let newNodePos = { x: pos.x - elem.offset.x, y: pos.y - elem.offset.y, }; - var dbf = this.dragBoundFunc(); + const dbf = this.dragBoundFunc(); if (dbf !== undefined) { const bounded = dbf.call(this, newNodePos, evt); if (!bounded) { @@ -2522,8 +2522,8 @@ export abstract class Node { this._dragCleanup(); this.on('mousedown.konva touchstart.konva', function (evt) { - var shouldCheckButton = evt.evt['button'] !== undefined; - var canDrag = + const shouldCheckButton = evt.evt['button'] !== undefined; + const canDrag = !shouldCheckButton || Konva.dragButtons.indexOf(evt.evt['button']) >= 0; if (!canDrag) { return; @@ -2532,7 +2532,7 @@ export abstract class Node { return; } - var hasDraggingChild = false; + let hasDraggingChild = false; DD._dragElements.forEach((elem) => { if (this.isAncestorOf(elem.node)) { hasDraggingChild = true; @@ -2558,7 +2558,7 @@ export abstract class Node { * if this node is currently in * drag and drop mode */ - var stage = this.getStage(); + const stage = this.getStage(); if (!stage) { return; } @@ -2700,7 +2700,7 @@ export abstract class Node { } static _createNode(obj, container?) { - var className = Node.prototype.getClassName.call(obj), + let className = Node.prototype.getClassName.call(obj), children = obj.children, no, len, diff --git a/src/Shape.ts b/src/Shape.ts index e34abbfd6..aec9d0643 100644 --- a/src/Shape.ts +++ b/src/Shape.ts @@ -94,11 +94,11 @@ export type FillFuncOutput = | [Path2D | CanvasFillRule] | [Path2D, CanvasFillRule]; -var HAS_SHADOW = 'hasShadow'; -var SHADOW_RGBA = 'shadowRGBA'; -var patternImage = 'patternImage'; -var linearGradient = 'linearGradient'; -var radialGradient = 'radialGradient'; +const HAS_SHADOW = 'hasShadow'; +const SHADOW_RGBA = 'shadowRGBA'; +const patternImage = 'patternImage'; +const linearGradient = 'linearGradient'; +const radialGradient = 'radialGradient'; let dummyContext: CanvasRenderingContext2D; function getDummyContext(): CanvasRenderingContext2D { @@ -255,7 +255,7 @@ export class Shape< } __getFillPattern() { if (this.fillPatternImage()) { - var ctx = getDummyContext(); + const ctx = getDummyContext(); const pattern = ctx.createPattern( this.fillPatternImage(), this.fillPatternRepeat() || 'repeat' @@ -294,16 +294,16 @@ export class Shape< return this._getCache(linearGradient, this.__getLinearGradient); } __getLinearGradient() { - var colorStops = this.fillLinearGradientColorStops(); + const colorStops = this.fillLinearGradientColorStops(); if (colorStops) { - var ctx = getDummyContext(); + const ctx = getDummyContext(); - var start = this.fillLinearGradientStartPoint(); - var end = this.fillLinearGradientEndPoint(); - var grd = ctx.createLinearGradient(start.x, start.y, end.x, end.y); + const start = this.fillLinearGradientStartPoint(); + const end = this.fillLinearGradientEndPoint(); + const grd = ctx.createLinearGradient(start.x, start.y, end.x, end.y); // build color stops - for (var n = 0; n < colorStops.length; n += 2) { + for (let n = 0; n < colorStops.length; n += 2) { grd.addColorStop(colorStops[n] as number, colorStops[n + 1] as string); } return grd; @@ -314,13 +314,13 @@ export class Shape< return this._getCache(radialGradient, this.__getRadialGradient); } __getRadialGradient() { - var colorStops = this.fillRadialGradientColorStops(); + const colorStops = this.fillRadialGradientColorStops(); if (colorStops) { - var ctx = getDummyContext(); + const ctx = getDummyContext(); - var start = this.fillRadialGradientStartPoint(); - var end = this.fillRadialGradientEndPoint(); - var grd = ctx.createRadialGradient( + const start = this.fillRadialGradientStartPoint(); + const end = this.fillRadialGradientEndPoint(); + const grd = ctx.createRadialGradient( start.x, start.y, this.fillRadialGradientStartRadius(), @@ -330,7 +330,7 @@ export class Shape< ); // build color stops - for (var n = 0; n < colorStops.length; n += 2) { + for (let n = 0; n < colorStops.length; n += 2) { grd.addColorStop(colorStops[n] as number, colorStops[n + 1] as string); } return grd; @@ -343,7 +343,7 @@ export class Shape< if (!this.hasShadow()) { return; } - var rgba = Util.colorToRGBA(this.shadowColor()); + const rgba = Util.colorToRGBA(this.shadowColor()); if (rgba) { return ( 'rgba(' + @@ -443,7 +443,7 @@ export class Shape< * @returns {Boolean} */ intersects(point) { - var stage = this.getStage(); + const stage = this.getStage(); if (!stage) { return false; } @@ -524,7 +524,7 @@ export class Shape< * */ getSelfRect() { - var size = this.size(); + const size = this.size(); return { x: this._centroid ? -size.width / 2 : 0, y: this._centroid ? -size.height / 2 : 0, @@ -593,8 +593,8 @@ export class Shape< // 2 - when we are caching current // 3 - when node is cached and we need to draw it into layer - var layer = this.getLayer(); - var canvas = can || layer!.getCanvas(), + const layer = this.getLayer(); + let canvas = can || layer!.getCanvas(), context = canvas.getContext() as SceneContext, cachedCanvas = this._getCanvasCache(), drawFunc = this.getSceneFunc(), @@ -602,8 +602,8 @@ export class Shape< stage, bufferContext; - var skipBuffer = canvas.isCache; - var cachingSelf = top === this; + const skipBuffer = canvas.isCache; + const cachingSelf = top === this; if (!this.isVisible() && !cachingSelf) { return this; @@ -612,7 +612,7 @@ export class Shape< if (cachedCanvas) { context.save(); - var m = this.getAbsoluteTransform(top).getMatrix(); + const m = this.getAbsoluteTransform(top).getMatrix(); context.transform(m[0], m[1], m[2], m[3], m[4], m[5]); this._drawCachedSceneCanvas(context); context.restore(); @@ -639,7 +639,7 @@ export class Shape< drawFunc.call(this, bufferContext, this); bufferContext.restore(); - var ratio = bc.pixelRatio; + const ratio = bc.pixelRatio; if (hasShadow) { context._applyShadow(this); @@ -671,7 +671,7 @@ export class Shape< return this; } - var layer = this.getLayer(), + const layer = this.getLayer(), canvas = can || layer!.hitCanvas, context = canvas && canvas.getContext(), drawFunc = this.hitFunc() || this.sceneFunc(), @@ -687,7 +687,7 @@ export class Shape< if (cachedHitCanvas) { context.save(); - var m = this.getAbsoluteTransform(top).getMatrix(); + const m = this.getAbsoluteTransform(top).getMatrix(); context.transform(m[0], m[1], m[2], m[3], m[4], m[5]); this._drawCachedHitCanvas(context); @@ -702,7 +702,7 @@ export class Shape< const selfCache = this === top; if (!selfCache) { - var o = this.getAbsoluteTransform(top).getMatrix(); + const o = this.getAbsoluteTransform(top).getMatrix(); context.transform(o[0], o[1], o[2], o[3], o[4], o[5]); } drawFunc.call(this, context, this); @@ -722,31 +722,25 @@ export class Shape< * shape.drawHitFromCache(); */ drawHitFromCache(alphaThreshold = 0) { - var cachedCanvas = this._getCanvasCache(), + const cachedCanvas = this._getCanvasCache(), sceneCanvas = this._getCachedSceneCanvas(), hitCanvas = cachedCanvas.hit, hitContext = hitCanvas.getContext(), hitWidth = hitCanvas.getWidth(), - hitHeight = hitCanvas.getHeight(), - hitImageData, - hitData, - len, - rgbColorKey, - i, - alpha; + hitHeight = hitCanvas.getHeight(); hitContext.clear(); hitContext.drawImage(sceneCanvas._canvas, 0, 0, hitWidth, hitHeight); try { - hitImageData = hitContext.getImageData(0, 0, hitWidth, hitHeight); - hitData = hitImageData.data; - len = hitData.length; - rgbColorKey = Util._hexToRgb(this.colorKey); + const hitImageData = hitContext.getImageData(0, 0, hitWidth, hitHeight); + const hitData = hitImageData.data; + const len = hitData.length; + const rgbColorKey = Util._hexToRgb(this.colorKey); // replace non transparent pixels with color key - for (i = 0; i < len; i += 4) { - alpha = hitData[i + 3]; + for (let i = 0; i < len; i += 4) { + const alpha = hitData[i + 3]; if (alpha > alphaThreshold) { hitData[i] = rgbColorKey.r; hitData[i + 1] = rgbColorKey.g; diff --git a/src/Stage.ts b/src/Stage.ts index a2eb87c3e..f2f56d1ab 100644 --- a/src/Stage.ts +++ b/src/Stage.ts @@ -15,7 +15,7 @@ export interface StageConfig extends ContainerConfig { } // CONSTANTS -var STAGE = 'Stage', +const STAGE = 'Stage', STRING = 'string', PX = 'px', MOUSEOUT = 'mouseout', @@ -215,7 +215,7 @@ export class Stage extends Container { setContainer(container) { if (typeof container === STRING) { if (container.charAt(0) === '.') { - var className = container.slice(1); + const className = container.slice(1); container = document.getElementsByClassName(className)[0]; } else { var id; @@ -249,7 +249,7 @@ export class Stage extends Container { * @name Konva.Stage#clear */ clear() { - var layers = this.children, + let layers = this.children, len = layers.length, n; @@ -270,11 +270,11 @@ export class Stage extends Container { destroy() { super.destroy(); - var content = this.content; + const content = this.content; if (content && Util._isInDocument(content)) { this.container().removeChild(content); } - var index = stages.indexOf(this); + const index = stages.indexOf(this); if (index > -1) { stages.splice(index, 1); } @@ -322,13 +322,13 @@ export class Stage extends Container { config.width = config.width || this.width(); config.height = config.height || this.height(); - var canvas = new SceneCanvas({ + const canvas = new SceneCanvas({ width: config.width, height: config.height, pixelRatio: config.pixelRatio || 1, }); - var _context = canvas.getContext()._context; - var layers = this.children; + const _context = canvas.getContext()._context; + const layers = this.children; if (config.x || config.y) { _context.translate(-1 * config.x, -1 * config.y); @@ -338,7 +338,7 @@ export class Stage extends Container { if (!layer.isVisible()) { return; } - var layerCanvas = layer._toKonvaCanvas(config); + const layerCanvas = layer._toKonvaCanvas(config); _context.drawImage( layerCanvas._canvas, config.x, @@ -367,7 +367,7 @@ export class Stage extends Container { if (!pos) { return null; } - var layers = this.children, + let layers = this.children, len = layers.length, end = len - 1, n; @@ -382,8 +382,8 @@ export class Stage extends Container { return null; } _resizeDOM() { - var width = this.width(); - var height = this.height(); + const width = this.width(); + const height = this.height(); if (this.content) { // set content dimensions this.content.style.width = width + PX; @@ -401,14 +401,14 @@ export class Stage extends Container { } add(layer: Layer, ...rest) { if (arguments.length > 1) { - for (var i = 0; i < arguments.length; i++) { + for (let i = 0; i < arguments.length; i++) { this.add(arguments[i]); } return this; } super.add(layer); - var length = this.children.length; + const length = this.children.length; if (length > MAX_LAYERS_NUMBER) { Util.warn( 'The stage has ' + @@ -507,8 +507,8 @@ export class Stage extends Container { } this.setPointersPositions(evt); - var targetShape = this._getTargetShape(eventType); - var eventsEnabled = + const targetShape = this._getTargetShape(eventType); + const eventsEnabled = !(Konva.isDragging() || Konva.isTransforming()) || Konva.hitOnDragEnabled; if (targetShape && eventsEnabled) { targetShape._fireAndBubble(events.pointerout, { evt: evt }); @@ -543,9 +543,9 @@ export class Stage extends Container { } this.setPointersPositions(evt); - var triggeredOnShape = false; + let triggeredOnShape = false; this._changedPointerPositions.forEach((pos) => { - var shape = this.getIntersection(pos); + const shape = this.getIntersection(pos); DD.justDragged = false; // probably we are staring a click Konva['_' + eventType + 'ListenClick'] = true; @@ -598,22 +598,22 @@ export class Stage extends Container { } this.setPointersPositions(evt); - var eventsEnabled = + const eventsEnabled = !(Konva.isDragging() || Konva.isTransforming()) || Konva.hitOnDragEnabled; if (!eventsEnabled) { return; } - var processedShapesIds = {}; + const processedShapesIds = {}; let triggeredOnShape = false; - var targetShape = this._getTargetShape(eventType); + const targetShape = this._getTargetShape(eventType); this._changedPointerPositions.forEach((pos) => { const shape = (PointerEvents.getCapturedShape(pos.id) || this.getIntersection(pos)) as Shape; const pointerId = pos.id; const event = { evt: evt, pointerId }; - var differentTarget = targetShape !== shape; + const differentTarget = targetShape !== shape; if (differentTarget && targetShape) { targetShape._fireAndBubble(events.pointerout, { ...event }, shape); @@ -667,7 +667,7 @@ export class Stage extends Container { this.setPointersPositions(evt); const clickStartShape = this[eventType + 'ClickStartShape']; const clickEndShape = this[eventType + 'ClickEndShape']; - var processedShapesIds = {}; + const processedShapesIds = {}; let triggeredOnShape = false; this._changedPointerPositions.forEach((pos) => { const shape = (PointerEvents.getCapturedShape(pos.id) || @@ -754,13 +754,13 @@ export class Stage extends Container { // TODO: are we sure we need to prevent default at all? // do not call this function on mobile because it prevent "click" event on all parent containers // but apps may listen to it. - if (evt.cancelable && eventType !== 'touch') { + if (evt.cancelable && eventType !== 'touch' && eventType !== 'pointer') { evt.preventDefault(); } } _contextmenu(evt) { this.setPointersPositions(evt); - var shape = this.getIntersection(this.getPointerPosition()!); + const shape = this.getIntersection(this.getPointerPosition()!); if (shape && shape.isListening()) { shape._fireAndBubble(CONTEXTMENU, { evt: evt }); @@ -775,7 +775,7 @@ export class Stage extends Container { _wheel(evt) { this.setPointersPositions(evt); - var shape = this.getIntersection(this.getPointerPosition()!); + const shape = this.getIntersection(this.getPointerPosition()!); if (shape && shape.isListening()) { shape._fireAndBubble(WHEEL, { evt: evt }); @@ -820,7 +820,7 @@ export class Stage extends Container { * }); */ setPointersPositions(evt) { - var contentPosition = this._getContentPosition(), + let contentPosition = this._getContentPosition(), x: number | null = null, y: number | null = null; evt = evt ? evt : window.event; @@ -879,7 +879,7 @@ export class Stage extends Container { }; } - var rect = this.content.getBoundingClientRect(); + const rect = this.content.getBoundingClientRect(); return { top: rect.top, @@ -904,7 +904,7 @@ export class Stage extends Container { if (!Konva.isBrowser) { return; } - var container = this.container(); + const container = this.container(); if (!container) { throw 'Stage has no container. A container is required.'; } diff --git a/src/Tween.ts b/src/Tween.ts index 45636d605..d29d6f152 100644 --- a/src/Tween.ts +++ b/src/Tween.ts @@ -4,7 +4,7 @@ import { Node, NodeConfig } from './Node'; import { Konva } from './Global'; import { Line } from './shapes/Line'; -var blacklist = { +let blacklist = { node: 1, duration: 1, easing: 1, @@ -58,7 +58,7 @@ class TweenEngine { this.pause(); } fire(str) { - var handler = this[str]; + const handler = this[str]; if (handler) { handler(); } @@ -133,7 +133,7 @@ class TweenEngine { this.fire('onUpdate'); } onEnterFrame() { - var t = this.getTimer() - this._startTime; + const t = this.getTimer() - this._startTime; if (this.state === PLAYING) { this.setTime(t); } else if (this.state === REVERSING) { @@ -195,7 +195,7 @@ export class Tween { onUpdate: Function | undefined; constructor(config: TweenConfig) { - var that = this, + let that = this, node = config.node as any, nodeId = node._id, duration, @@ -214,7 +214,7 @@ export class Tween { this.node = node; this._id = idCounter++; - var layers = + const layers = node.getLayer() || (node instanceof Konva['Stage'] ? node.getLayers() : null); if (!layers) { @@ -266,7 +266,7 @@ export class Tween { this.onUpdate = config.onUpdate; } _addAttr(key, end) { - var node = this.node, + let node = this.node, nodeId = node._id, start, diff, @@ -314,7 +314,7 @@ export class Tween { if (n % 2 === 0) { diff.push(end[n] - start[n]); } else { - var startRGBA = Util.colorToRGBA(start[n])!; + const startRGBA = Util.colorToRGBA(start[n])!; endRGBA = Util.colorToRGBA(end[n]); start[n] = startRGBA; diff.push({ @@ -353,7 +353,7 @@ export class Tween { Tween.tweens[nodeId][key] = this._id; } _tweenFunc(i) { - var node = this.node, + let node = this.node, attrs = Tween.attrs[node._id][this._id], key, attr, @@ -428,10 +428,10 @@ export class Tween { this.anim.stop(); }; this.tween.onFinish = () => { - var node = this.node as Node; + const node = this.node as Node; // after tweening points of line we need to set original end - var attrs = Tween.attrs[node._id][this._id]; + const attrs = Tween.attrs[node._id][this._id]; if (attrs.points && attrs.points.trueEnd) { node.setAttr('points', attrs.points.trueEnd); } @@ -441,9 +441,9 @@ export class Tween { } }; this.tween.onReset = () => { - var node = this.node as any; + const node = this.node as any; // after tweening points of line we need to set original start - var attrs = Tween.attrs[node._id][this._id]; + const attrs = Tween.attrs[node._id][this._id]; if (attrs.points && attrs.points.trueStart) { node.points(attrs.points.trueStart); } @@ -525,7 +525,7 @@ export class Tween { * @name Konva.Tween#destroy */ destroy() { - var nodeId = this.node._id, + let nodeId = this.node._id, thisId = this._id, attrs = Tween.tweens[nodeId], key; @@ -555,7 +555,7 @@ export class Tween { * }); */ Node.prototype.to = function (params) { - var onFinish = params.onFinish; + const onFinish = params.onFinish; params.node = this; params.onFinish = function () { this.destroy(); @@ -563,7 +563,7 @@ Node.prototype.to = function (params) { onFinish(); } }; - var tween = new Tween(params as any); + const tween = new Tween(params as any); tween.play(); }; @@ -583,7 +583,7 @@ export const Easings = { * @memberof Konva.Easings */ BackEaseIn(t, b, c, d) { - var s = 1.70158; + const s = 1.70158; return c * (t /= d) * t * ((s + 1) * t - s) + b; }, /** @@ -592,7 +592,7 @@ export const Easings = { * @memberof Konva.Easings */ BackEaseOut(t, b, c, d) { - var s = 1.70158; + const s = 1.70158; return c * ((t = t / d - 1) * t * ((s + 1) * t + s) + 1) + b; }, /** @@ -601,7 +601,7 @@ export const Easings = { * @memberof Konva.Easings */ BackEaseInOut(t, b, c, d) { - var s = 1.70158; + let s = 1.70158; if ((t /= d / 2) < 1) { return (c / 2) * (t * t * (((s *= 1.525) + 1) * t - s)) + b; } @@ -614,7 +614,7 @@ export const Easings = { */ ElasticEaseIn(t, b, c, d, a, p) { // added s = 0 - var s = 0; + let s = 0; if (t === 0) { return b; } @@ -645,7 +645,7 @@ export const Easings = { */ ElasticEaseOut(t, b, c, d, a, p) { // added s = 0 - var s = 0; + let s = 0; if (t === 0) { return b; } @@ -674,7 +674,7 @@ export const Easings = { */ ElasticEaseInOut(t, b, c, d, a, p) { // added s = 0 - var s = 0; + let s = 0; if (t === 0) { return b; } diff --git a/src/Util.ts b/src/Util.ts index 94102d642..8dff2d51b 100644 --- a/src/Util.ts +++ b/src/Util.ts @@ -1,6 +1,6 @@ import { Konva } from './Global'; import { Context } from './Context'; -import { IRect, RGB, RGBA, Vector2d } from './types'; +import { IRect, RGB, Vector2d } from './types'; /* * Last updated November 2011 @@ -67,7 +67,7 @@ export class Transform { * @returns {Object} 2D point(x, y) */ point(point: Vector2d) { - var m = this.m; + const m = this.m; return { x: m[0] * point.x + m[2] * point.y + m[4], y: m[1] * point.x + m[3] * point.y + m[5], @@ -109,12 +109,12 @@ export class Transform { * @returns {Konva.Transform} */ rotate(rad: number) { - var c = Math.cos(rad); - var s = Math.sin(rad); - var m11 = this.m[0] * c + this.m[2] * s; - var m12 = this.m[1] * c + this.m[3] * s; - var m21 = this.m[0] * -s + this.m[2] * c; - var m22 = this.m[1] * -s + this.m[3] * c; + const c = Math.cos(rad); + const s = Math.sin(rad); + const m11 = this.m[0] * c + this.m[2] * s; + const m12 = this.m[1] * c + this.m[3] * s; + const m21 = this.m[0] * -s + this.m[2] * c; + const m22 = this.m[1] * -s + this.m[3] * c; this.m[0] = m11; this.m[1] = m12; this.m[2] = m21; @@ -142,10 +142,10 @@ export class Transform { * @returns {Konva.Transform} */ skew(sx: number, sy: number) { - var m11 = this.m[0] + this.m[2] * sy; - var m12 = this.m[1] + this.m[3] * sy; - var m21 = this.m[2] + this.m[0] * sx; - var m22 = this.m[3] + this.m[1] * sx; + const m11 = this.m[0] + this.m[2] * sy; + const m12 = this.m[1] + this.m[3] * sy; + const m21 = this.m[2] + this.m[0] * sx; + const m22 = this.m[3] + this.m[1] * sx; this.m[0] = m11; this.m[1] = m12; this.m[2] = m21; @@ -160,14 +160,14 @@ export class Transform { * @returns {Konva.Transform} */ multiply(matrix: Transform) { - var m11 = this.m[0] * matrix.m[0] + this.m[2] * matrix.m[1]; - var m12 = this.m[1] * matrix.m[0] + this.m[3] * matrix.m[1]; + const m11 = this.m[0] * matrix.m[0] + this.m[2] * matrix.m[1]; + const m12 = this.m[1] * matrix.m[0] + this.m[3] * matrix.m[1]; - var m21 = this.m[0] * matrix.m[2] + this.m[2] * matrix.m[3]; - var m22 = this.m[1] * matrix.m[2] + this.m[3] * matrix.m[3]; + const m21 = this.m[0] * matrix.m[2] + this.m[2] * matrix.m[3]; + const m22 = this.m[1] * matrix.m[2] + this.m[3] * matrix.m[3]; - var dx = this.m[0] * matrix.m[4] + this.m[2] * matrix.m[5] + this.m[4]; - var dy = this.m[1] * matrix.m[4] + this.m[3] * matrix.m[5] + this.m[5]; + const dx = this.m[0] * matrix.m[4] + this.m[2] * matrix.m[5] + this.m[4]; + const dy = this.m[1] * matrix.m[4] + this.m[3] * matrix.m[5] + this.m[5]; this.m[0] = m11; this.m[1] = m12; @@ -184,13 +184,13 @@ export class Transform { * @returns {Konva.Transform} */ invert() { - var d = 1 / (this.m[0] * this.m[3] - this.m[1] * this.m[2]); - var m0 = this.m[3] * d; - var m1 = -this.m[1] * d; - var m2 = -this.m[2] * d; - var m3 = this.m[0] * d; - var m4 = d * (this.m[2] * this.m[5] - this.m[3] * this.m[4]); - var m5 = d * (this.m[1] * this.m[4] - this.m[0] * this.m[5]); + const d = 1 / (this.m[0] * this.m[3] - this.m[1] * this.m[2]); + const m0 = this.m[3] * d; + const m1 = -this.m[1] * d; + const m2 = -this.m[2] * d; + const m3 = this.m[0] * d; + const m4 = d * (this.m[2] * this.m[5] - this.m[3] * this.m[4]); + const m5 = d * (this.m[1] * this.m[4] - this.m[0] * this.m[5]); this.m[0] = m0; this.m[1] = m1; this.m[2] = m2; @@ -214,16 +214,16 @@ export class Transform { * @returns {Konva.Transform} */ decompose() { - var a = this.m[0]; - var b = this.m[1]; - var c = this.m[2]; - var d = this.m[3]; - var e = this.m[4]; - var f = this.m[5]; + const a = this.m[0]; + const b = this.m[1]; + const c = this.m[2]; + const d = this.m[3]; + const e = this.m[4]; + const f = this.m[5]; - var delta = a * d - b * c; + const delta = a * d - b * c; - let result = { + const result = { x: e, y: f, rotation: 0, @@ -235,14 +235,14 @@ export class Transform { // Apply the QR-like decomposition. if (a != 0 || b != 0) { - var r = Math.sqrt(a * a + b * b); + const r = Math.sqrt(a * a + b * b); result.rotation = b > 0 ? Math.acos(a / r) : -Math.acos(a / r); result.scaleX = r; result.scaleY = delta / r; result.skewX = (a * c + b * d) / delta; result.skewY = 0; } else if (c != 0 || d != 0) { - var s = Math.sqrt(c * c + d * d); + const s = Math.sqrt(c * c + d * d); result.rotation = Math.PI / 2 - (d > 0 ? Math.acos(-c / s) : -Math.acos(c / s)); result.scaleX = delta / s; @@ -260,7 +260,7 @@ export class Transform { } // CONSTANTS -var OBJECT_ARRAY = '[object Array]', +let OBJECT_ARRAY = '[object Array]', OBJECT_NUMBER = '[object Number]', OBJECT_STRING = '[object String]', OBJECT_BOOLEAN = '[object Boolean]', @@ -465,14 +465,14 @@ export const Util = { return Object.prototype.toString.call(obj) === OBJECT_BOOLEAN; }, // arrays are objects too - isObject(val: any): val is Object { + isObject(val: any): val is object { return val instanceof Object; }, isValidSelector(selector: any) { if (typeof selector !== 'string') { return false; } - var firstChar = selector[0]; + const firstChar = selector[0]; return ( firstChar === '#' || firstChar === '.' || @@ -505,7 +505,7 @@ export const Util = { } }, createCanvasElement() { - var canvas = document.createElement('canvas'); + const canvas = document.createElement('canvas'); // on some environments canvas.style is readonly try { (canvas).style = canvas.style || {}; @@ -529,7 +529,7 @@ export const Util = { */ _urlToImage(url: string, callback: Function) { // if arg is a string, then it's a data url - var imageObj = Util.createImageElement(); + const imageObj = Util.createImageElement(); imageObj.onload = function () { callback(imageObj); }; @@ -540,7 +540,7 @@ export const Util = { }, _hexToRgb(hex: string): RGB { hex = hex.replace(HASH, EMPTY_STRING); - var bigint = parseInt(hex, 16); + const bigint = parseInt(hex, 16); return { r: (bigint >> 16) & 255, g: (bigint >> 8) & 255, @@ -555,7 +555,7 @@ export const Util = { * shape.fill(Konva.Util.getRandomColor()); */ getRandomColor() { - var randColor = ((Math.random() * 0xffffff) << 0).toString(16); + let randColor = ((Math.random() * 0xffffff) << 0).toString(16); while (randColor.length < 6) { randColor = ZERO + randColor; } @@ -574,7 +574,7 @@ export const Util = { * var rgb = Konva.Util.getRGB('rgb(0,0,255)'); */ getRGB(color: string): RGB { - var rgb; + let rgb; // color string if (color in COLORS) { rgb = COLORS[color as keyof typeof COLORS]; @@ -620,7 +620,7 @@ export const Util = { }, // Parse named css color. Like "green" _namedColorToRBA(str: string) { - var c = COLORS[str.toLowerCase() as keyof typeof COLORS]; + const c = COLORS[str.toLowerCase() as keyof typeof COLORS]; if (!c) { return null; } @@ -635,7 +635,7 @@ export const Util = { _rgbColorToRGBA(str: string) { if (str.indexOf('rgb(') === 0) { str = str.match(/rgb\(([^)]+)\)/)![1]; - var parts = str.split(/ *, */).map(Number); + const parts = str.split(/ *, */).map(Number); return { r: parts[0], g: parts[1], @@ -648,7 +648,7 @@ export const Util = { _rgbaColorToRGBA(str: string) { if (str.indexOf('rgba(') === 0) { str = str.match(/rgba\(([^)]+)\)/)![1]!; - var parts = str.split(/ *, */).map((n, index) => { + const parts = str.split(/ *, */).map((n, index) => { if (n.slice(-1) === '%') { return index === 3 ? parseInt(n) / 100 : (parseInt(n) / 100) * 255; } @@ -789,8 +789,8 @@ export const Util = { ); }, cloneObject(obj: Any): Any { - var retObj: any = {}; - for (var key in obj) { + const retObj: any = {}; + for (const key in obj) { if (this._isPlainObject(obj[key])) { retObj[key] = this.cloneObject(obj[key]); } else if (this._isArray(obj[key])) { @@ -840,8 +840,8 @@ export const Util = { } console.warn(KONVA_WARNING + str); }, - each(obj: Object, func: Function) { - for (var key in obj) { + each(obj: object, func: Function) { + for (const key in obj) { func(key, obj[key as keyof typeof obj]); } }, @@ -849,15 +849,15 @@ export const Util = { return left <= val && val < right; }, _getProjectionToSegment(x1, y1, x2, y2, x3, y3) { - var x, y, dist; + let x, y, dist; - var pd2 = (x1 - x2) * (x1 - x2) + (y1 - y2) * (y1 - y2); + const pd2 = (x1 - x2) * (x1 - x2) + (y1 - y2) * (y1 - y2); if (pd2 == 0) { x = x1; y = y1; dist = (x3 - x2) * (x3 - x2) + (y3 - y2) * (y3 - y2); } else { - var u = ((x3 - x1) * (x2 - x1) + (y3 - y1) * (y2 - y1)) / pd2; + const u = ((x3 - x1) * (x2 - x1) + (y3 - y1) * (y2 - y1)) / pd2; if (u < 0) { x = x1; y = y1; @@ -877,14 +877,14 @@ export const Util = { // line as array of points. // line might be closed _getProjectionToLine(pt: Vector2d, line: Array, isClosed: boolean) { - var pc = Util.cloneObject(pt); - var dist = Number.MAX_VALUE; + const pc = Util.cloneObject(pt); + let dist = Number.MAX_VALUE; line.forEach(function (p1, i) { if (!isClosed && i === line.length - 1) { return; } - var p2 = line[(i + 1) % line.length]; - var proj = Util._getProjectionToSegment( + const p2 = line[(i + 1) % line.length]; + const proj = Util._getProjectionToSegment( p1.x, p1.y, p2.x, @@ -892,7 +892,7 @@ export const Util = { pt.x, pt.y ); - var px = proj[0], + const px = proj[0], py = proj[1], pdist = proj[2]; if (pdist < dist) { @@ -904,11 +904,11 @@ export const Util = { return pc; }, _prepareArrayForTween(startArray, endArray, isClosed) { - var n, + let n, start: Vector2d[] = [], end: Vector2d[] = []; if (startArray.length > endArray.length) { - var temp = endArray; + const temp = endArray; endArray = startArray; startArray = temp; } @@ -925,20 +925,20 @@ export const Util = { }); } - var newStart: number[] = []; + const newStart: number[] = []; end.forEach(function (point) { - var pr = Util._getProjectionToLine(point, start, isClosed); + const pr = Util._getProjectionToLine(point, start, isClosed); newStart.push(pr.x); newStart.push(pr.y); }); return newStart; }, _prepareToStringify(obj: any): T | null { - var desc; + let desc; obj.visitedByCircularReferenceRemoval = true; - for (var key in obj) { + for (const key in obj) { if ( !(obj.hasOwnProperty(key) && obj[key] && typeof obj[key] == 'object') ) { @@ -969,7 +969,7 @@ export const Util = { }, // very simplified version of Object.assign _assign(target: T, source: U) { - for (var key in source) { + for (const key in source) { (target)[key] = source[key]; } return target as T & U; diff --git a/src/Validators.ts b/src/Validators.ts index 175c320d3..023e0d900 100644 --- a/src/Validators.ts +++ b/src/Validators.ts @@ -52,8 +52,8 @@ export function getNumberValidator() { export function getNumberOrArrayOfNumbersValidator(noOfElements: number) { if (Konva.isUnminified) { return function (val: T, attr: string): T | void { - let isNumber = Util._isNumber(val); - let isValidArray = Util._isArray(val) && val.length == noOfElements; + const isNumber = Util._isNumber(val); + const isValidArray = Util._isArray(val) && val.length == noOfElements; if (!isNumber && !isValidArray) { Util.warn( _formatValue(val) + @@ -72,8 +72,8 @@ export function getNumberOrArrayOfNumbersValidator(noOfElements: number) { export function getNumberOrAutoValidator() { if (Konva.isUnminified) { return function (val: T, attr: string): T | void { - var isNumber = Util._isNumber(val); - var isAuto = val === 'auto'; + const isNumber = Util._isNumber(val); + const isAuto = val === 'auto'; if (!(isNumber || isAuto)) { Util.warn( @@ -175,7 +175,7 @@ export function getNumberArrayValidator() { export function getBooleanValidator() { if (Konva.isUnminified) { return function (val: any, attr: string) { - var isBool = val === true || val === false; + const isBool = val === true || val === false; if (!isBool) { Util.warn( _formatValue(val) + diff --git a/src/filters/Blur.ts b/src/filters/Blur.ts index 4cd12556e..4998e8e7e 100644 --- a/src/filters/Blur.ts +++ b/src/filters/Blur.ts @@ -54,7 +54,7 @@ function BlurStack(this: any) { this.next = null; } -var mul_table = [ +const mul_table = [ 512, 512, 456, 512, 328, 456, 335, 512, 405, 328, 271, 456, 388, 335, 292, 512, 454, 405, 364, 328, 298, 271, 496, 456, 420, 388, 360, 335, 312, 292, 273, 512, 482, 454, 428, 405, 383, 364, 345, 328, 312, 298, 284, 271, 259, @@ -74,7 +74,7 @@ var mul_table = [ 289, 287, 285, 282, 280, 278, 275, 273, 271, 269, 267, 265, 263, 261, 259, ]; -var shg_table = [ +const shg_table = [ 9, 11, 12, 13, 13, 14, 14, 15, 15, 15, 15, 16, 16, 16, 16, 17, 17, 17, 17, 17, 17, 17, 18, 18, 18, 18, 18, 18, 18, 18, 18, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, @@ -92,11 +92,11 @@ var shg_table = [ ]; function filterGaussBlurRGBA(imageData, radius) { - var pixels = imageData.data, + const pixels = imageData.data, width = imageData.width, height = imageData.height; - var x, + let x, y, i, p, @@ -121,19 +121,20 @@ function filterGaussBlurRGBA(imageData, radius) { pa, rbs; - var div = radius + radius + 1, + const div = radius + radius + 1, widthMinus1 = width - 1, heightMinus1 = height - 1, radiusPlus1 = radius + 1, sumFactor = (radiusPlus1 * (radiusPlus1 + 1)) / 2, stackStart = new BlurStack(), - stackEnd = null, - stack = stackStart, - stackIn: any = null, - stackOut: any = null, mul_sum = mul_table[radius], shg_sum = shg_table[radius]; + let stackEnd = null, + stack = stackStart, + stackIn: any = null, + stackOut: any = null; + for (i = 1; i < div; i++) { stack = stack.next = new BlurStack(); if (i === radiusPlus1) { @@ -365,7 +366,7 @@ function filterGaussBlurRGBA(imageData, radius) { * node.blurRadius(10); */ export const Blur: Filter = function Blur(imageData) { - var radius = Math.round(this.blurRadius()); + const radius = Math.round(this.blurRadius()); if (radius > 0) { filterGaussBlurRGBA(imageData, radius); diff --git a/src/filters/Brighten.ts b/src/filters/Brighten.ts index 2e11e823c..d7d981b7a 100644 --- a/src/filters/Brighten.ts +++ b/src/filters/Brighten.ts @@ -13,12 +13,11 @@ import { getNumberValidator } from '../Validators'; * node.brightness(0.8); */ export const Brighten: Filter = function (imageData) { - var brightness = this.brightness() * 255, + const brightness = this.brightness() * 255, data = imageData.data, - len = data.length, - i; + len = data.length; - for (i = 0; i < len; i += 4) { + for (let i = 0; i < len; i += 4) { // red data[i] += brightness; // green diff --git a/src/filters/Contrast.ts b/src/filters/Contrast.ts index 078048e48..80ec38b40 100644 --- a/src/filters/Contrast.ts +++ b/src/filters/Contrast.ts @@ -13,16 +13,15 @@ import { getNumberValidator } from '../Validators'; */ export const Contrast: Filter = function (imageData) { - var adjust = Math.pow((this.contrast() + 100) / 100, 2); + const adjust = Math.pow((this.contrast() + 100) / 100, 2); - var data = imageData.data, - nPixels = data.length, - red = 150, + const data = imageData.data, + nPixels = data.length; + let red = 150, green = 150, - blue = 150, - i; + blue = 150; - for (i = 0; i < nPixels; i += 4) { + for (let i = 0; i < nPixels; i += 4) { red = data[i]; green = data[i + 1]; blue = data[i + 2]; diff --git a/src/filters/Emboss.ts b/src/filters/Emboss.ts index 99bebca5c..cbeacd3cd 100644 --- a/src/filters/Emboss.ts +++ b/src/filters/Emboss.ts @@ -23,16 +23,16 @@ export const Emboss: Filter = function (imageData) { // pixastic greyLevel is between 0 and 255. I want it between 0 and 1. Also, // a max value of greyLevel yields a white emboss, and the min value yields a black // emboss. Therefore, I changed greyLevel to whiteLevel - var strength = this.embossStrength() * 10, + const strength = this.embossStrength() * 10, greyLevel = this.embossWhiteLevel() * 255, direction = this.embossDirection(), blend = this.embossBlend(), - dirY = 0, - dirX = 0, data = imageData.data, w = imageData.width, h = imageData.height, - w4 = w * 4, + w4 = w * 4; + let dirY = 0, + dirX = 0, y = h; switch (direction) { @@ -73,9 +73,9 @@ export const Emboss: Filter = function (imageData) { } do { - var offsetY = (y - 1) * w4; + const offsetY = (y - 1) * w4; - var otherY = dirY; + let otherY = dirY; if (y + otherY < 1) { otherY = 0; } @@ -83,13 +83,13 @@ export const Emboss: Filter = function (imageData) { otherY = 0; } - var offsetYOther = (y - 1 + otherY) * w * 4; + const offsetYOther = (y - 1 + otherY) * w * 4; - var x = w; + let x = w; do { - var offset = offsetY + (x - 1) * 4; + const offset = offsetY + (x - 1) * 4; - var otherX = dirX; + let otherX = dirX; if (x + otherX < 1) { otherX = 0; } @@ -97,17 +97,17 @@ export const Emboss: Filter = function (imageData) { otherX = 0; } - var offsetOther = offsetYOther + (x - 1 + otherX) * 4; + const offsetOther = offsetYOther + (x - 1 + otherX) * 4; - var dR = data[offset] - data[offsetOther]; - var dG = data[offset + 1] - data[offsetOther + 1]; - var dB = data[offset + 2] - data[offsetOther + 2]; + const dR = data[offset] - data[offsetOther]; + const dG = data[offset + 1] - data[offsetOther + 1]; + const dB = data[offset + 2] - data[offsetOther + 2]; - var dif = dR; - var absDif = dif > 0 ? dif : -dif; + let dif = dR; + const absDif = dif > 0 ? dif : -dif; - var absG = dG > 0 ? dG : -dG; - var absB = dB > 0 ? dB : -dB; + const absG = dG > 0 ? dG : -dG; + const absB = dB > 0 ? dB : -dB; if (absG > absDif) { dif = dG; @@ -119,15 +119,15 @@ export const Emboss: Filter = function (imageData) { dif *= strength; if (blend) { - var r = data[offset] + dif; - var g = data[offset + 1] + dif; - var b = data[offset + 2] + dif; + const r = data[offset] + dif; + const g = data[offset + 1] + dif; + const b = data[offset + 2] + dif; data[offset] = r > 255 ? 255 : r < 0 ? 0 : r; data[offset + 1] = g > 255 ? 255 : g < 0 ? 0 : g; data[offset + 2] = b > 255 ? 255 : b < 0 ? 0 : b; } else { - var grey = greyLevel - dif; + let grey = greyLevel - dif; if (grey < 0) { grey = 0; } else if (grey > 255) { diff --git a/src/filters/Enhance.ts b/src/filters/Enhance.ts index 2bc749430..d92d68344 100644 --- a/src/filters/Enhance.ts +++ b/src/filters/Enhance.ts @@ -2,11 +2,10 @@ import { Factory } from '../Factory'; import { Node, Filter } from '../Node'; import { getNumberValidator } from '../Validators'; -function remap(fromValue, fromMin, fromMax, toMin, toMax) { +function remap(fromValue: number, fromMin: number, fromMax: number, toMin: number, toMax: number) { // Compute the range of the data - var fromRange = fromMax - fromMin, - toRange = toMax - toMin, - toValue; + const fromRange = fromMax - fromMin, + toRange = toMax - toMin; // If either range is 0, then the value can only be mapped to 1 value if (fromRange === 0) { @@ -17,7 +16,7 @@ function remap(fromValue, fromMin, fromMax, toMin, toMax) { } // (1) untranslate, (2) unscale, (3) rescale, (4) retranslate - toValue = (fromValue - fromMin) / fromRange; + let toValue = (fromValue - fromMin) / fromRange; toValue = toRange * toValue + toMin; return toValue; @@ -38,9 +37,9 @@ function remap(fromValue, fromMin, fromMax, toMin, toMax) { * node.enhance(0.4); */ export const Enhance: Filter = function (imageData) { - var data = imageData.data, - nSubPixels = data.length, - rMin = data[0], + const data = imageData.data, + nSubPixels = data.length; + let rMin = data[0], rMax = rMin, r, gMin = data[1], @@ -48,17 +47,16 @@ export const Enhance: Filter = function (imageData) { g, bMin = data[2], bMax = bMin, - b, - i; + b; // If we are not enhancing anything - don't do any computation - var enhanceAmount = this.enhance(); + const enhanceAmount = this.enhance(); if (enhanceAmount === 0) { return; } // 1st Pass - find the min and max for each channel: - for (i = 0; i < nSubPixels; i += 4) { + for (let i = 0; i < nSubPixels; i += 4) { r = data[i + 0]; if (r < rMin) { rMin = r; @@ -96,7 +94,7 @@ export const Enhance: Filter = function (imageData) { bMin = 0; } - var rMid, + let rMid, rGoalMax, rGoalMin, gMid, @@ -128,7 +126,7 @@ export const Enhance: Filter = function (imageData) { } // Pass 2 - remap everything, except the alpha - for (i = 0; i < nSubPixels; i += 4) { + for (let i = 0; i < nSubPixels; i += 4) { data[i + 0] = remap(data[i + 0], rMin, rMax, rGoalMin, rGoalMax); data[i + 1] = remap(data[i + 1], gMin, gMax, gGoalMin, gGoalMax); data[i + 2] = remap(data[i + 2], bMin, bMax, bGoalMin, bGoalMax); diff --git a/src/filters/Grayscale.ts b/src/filters/Grayscale.ts index 980cd3adf..4457a95fb 100644 --- a/src/filters/Grayscale.ts +++ b/src/filters/Grayscale.ts @@ -10,13 +10,11 @@ import { Filter } from '../Node'; * node.filters([Konva.Filters.Grayscale]); */ export const Grayscale: Filter = function (imageData) { - var data = imageData.data, - len = data.length, - i, - brightness; + const data = imageData.data, + len = data.length; - for (i = 0; i < len; i += 4) { - brightness = 0.34 * data[i] + 0.5 * data[i + 1] + 0.16 * data[i + 2]; + for (let i = 0; i < len; i += 4) { + const brightness = 0.34 * data[i] + 0.5 * data[i + 1] + 0.16 * data[i + 2]; // red data[i] = brightness; // green diff --git a/src/filters/HSL.ts b/src/filters/HSL.ts index d91506c4c..1f1b4d9a8 100644 --- a/src/filters/HSL.ts +++ b/src/filters/HSL.ts @@ -59,7 +59,7 @@ Factory.addGetterSetter( */ export const HSL: Filter = function (imageData) { - var data = imageData.data, + let data = imageData.data, nPixels = data.length, v = 1, s = Math.pow(2, this.saturation()), @@ -79,20 +79,20 @@ export const HSL: Filter = function (imageData) { //[ .299V-.300vsu+1.25vsw .587V-.588vsu-1.05vsw .114V+.886vsu-.203vsw ] [B] // Precompute the values in the matrix: - var vsu = v * s * Math.cos((h * Math.PI) / 180), + const vsu = v * s * Math.cos((h * Math.PI) / 180), vsw = v * s * Math.sin((h * Math.PI) / 180); // (result spot)(source spot) - var rr = 0.299 * v + 0.701 * vsu + 0.167 * vsw, + const rr = 0.299 * v + 0.701 * vsu + 0.167 * vsw, rg = 0.587 * v - 0.587 * vsu + 0.33 * vsw, rb = 0.114 * v - 0.114 * vsu - 0.497 * vsw; - var gr = 0.299 * v - 0.299 * vsu - 0.328 * vsw, + const gr = 0.299 * v - 0.299 * vsu - 0.328 * vsw, gg = 0.587 * v + 0.413 * vsu + 0.035 * vsw, gb = 0.114 * v - 0.114 * vsu + 0.293 * vsw; - var br = 0.299 * v - 0.3 * vsu + 1.25 * vsw, + const br = 0.299 * v - 0.3 * vsu + 1.25 * vsw, bg = 0.587 * v - 0.586 * vsu - 1.05 * vsw, bb = 0.114 * v + 0.886 * vsu - 0.2 * vsw; - var r, g, b, a; + let r: number, g: number, b: number, a: number; for (i = 0; i < nPixels; i += 4) { r = data[i + 0]; diff --git a/src/filters/HSV.ts b/src/filters/HSV.ts index b3996b3de..855f66445 100644 --- a/src/filters/HSV.ts +++ b/src/filters/HSV.ts @@ -15,12 +15,11 @@ import { getNumberValidator } from '../Validators'; */ export const HSV: Filter = function (imageData) { - var data = imageData.data, + const data = imageData.data, nPixels = data.length, v = Math.pow(2, this.value()), s = Math.pow(2, this.saturation()), - h = Math.abs(this.hue() + 360) % 360, - i; + h = Math.abs(this.hue() + 360) % 360; // Basis for the technique used: // http://beesbuzz.biz/code/hsv_color_transforms.php @@ -34,22 +33,22 @@ export const HSV: Filter = function (imageData) { //[ .299V-.300vsu+1.25vsw .587V-.588vsu-1.05vsw .114V+.886vsu-.203vsw ] [B] // Precompute the values in the matrix: - var vsu = v * s * Math.cos((h * Math.PI) / 180), + const vsu = v * s * Math.cos((h * Math.PI) / 180), vsw = v * s * Math.sin((h * Math.PI) / 180); // (result spot)(source spot) - var rr = 0.299 * v + 0.701 * vsu + 0.167 * vsw, + const rr = 0.299 * v + 0.701 * vsu + 0.167 * vsw, rg = 0.587 * v - 0.587 * vsu + 0.33 * vsw, rb = 0.114 * v - 0.114 * vsu - 0.497 * vsw; - var gr = 0.299 * v - 0.299 * vsu - 0.328 * vsw, + const gr = 0.299 * v - 0.299 * vsu - 0.328 * vsw, gg = 0.587 * v + 0.413 * vsu + 0.035 * vsw, gb = 0.114 * v - 0.114 * vsu + 0.293 * vsw; - var br = 0.299 * v - 0.3 * vsu + 1.25 * vsw, + const br = 0.299 * v - 0.3 * vsu + 1.25 * vsw, bg = 0.587 * v - 0.586 * vsu - 1.05 * vsw, bb = 0.114 * v + 0.886 * vsu - 0.2 * vsw; - var r, g, b, a; + let r, g, b, a; - for (i = 0; i < nPixels; i += 4) { + for (let i = 0; i < nPixels; i += 4) { r = data[i + 0]; g = data[i + 1]; b = data[i + 2]; diff --git a/src/filters/Invert.ts b/src/filters/Invert.ts index 4b8668a75..a9bb259b6 100644 --- a/src/filters/Invert.ts +++ b/src/filters/Invert.ts @@ -9,7 +9,7 @@ import { Filter } from '../Node'; * node.filters([Konva.Filters.Invert]); */ export const Invert: Filter = function (imageData) { - var data = imageData.data, + let data = imageData.data, len = data.length, i; diff --git a/src/filters/Kaleidoscope.ts b/src/filters/Kaleidoscope.ts index dc13d86c4..70336fa80 100644 --- a/src/filters/Kaleidoscope.ts +++ b/src/filters/Kaleidoscope.ts @@ -19,8 +19,8 @@ import { getNumberValidator } from '../Validators'; * default is in the middle */ -var ToPolar = function (src, dst, opt) { - var srcPixels = src.data, +const ToPolar = function (src, dst, opt) { + let srcPixels = src.data, dstPixels = dst.data, xSize = src.width, ySize = src.height, @@ -35,7 +35,7 @@ var ToPolar = function (src, dst, opt) { a = 0; // Find the largest radius - var rad, + let rad, rMax = Math.sqrt(xMid * xMid + yMid * yMid); x = xSize - xMid; y = ySize - yMid; @@ -43,14 +43,14 @@ var ToPolar = function (src, dst, opt) { rMax = rad > rMax ? rad : rMax; // We'll be uisng y as the radius, and x as the angle (theta=t) - var rSize = ySize, + let rSize = ySize, tSize = xSize, radius, theta; // We want to cover all angles (0-360) and we need to convert to // radians (*PI/180) - var conversion = ((360 / tSize) * Math.PI) / 180, + let conversion = ((360 / tSize) * Math.PI) / 180, sin, cos; @@ -96,8 +96,8 @@ var ToPolar = function (src, dst, opt) { * 0 is no rotation, 360 degrees is a full rotation */ -var FromPolar = function (src, dst, opt) { - var srcPixels = src.data, +const FromPolar = function (src, dst, opt) { + let srcPixels = src.data, dstPixels = dst.data, xSize = src.width, ySize = src.height, @@ -114,7 +114,7 @@ var FromPolar = function (src, dst, opt) { a = 0; // Find the largest radius - var rad, + let rad, rMax = Math.sqrt(xMid * xMid + yMid * yMid); x = xSize - xMid; y = ySize - yMid; @@ -122,7 +122,7 @@ var FromPolar = function (src, dst, opt) { rMax = rad > rMax ? rad : rMax; // We'll be uisng x as the radius, and y as the angle (theta=t) - var rSize = ySize, + let rSize = ySize, tSize = xSize, radius, theta, @@ -133,7 +133,7 @@ var FromPolar = function (src, dst, opt) { // var conversion = tSize/360*180/Math.PI; //var conversion = tSize/360*180/Math.PI; - var x1, y1; + let x1, y1; for (x = 0; x < xSize; x += 1) { for (y = 0; y < ySize; y += 1) { @@ -178,23 +178,23 @@ var FromPolar = function (src, dst, opt) { * node.kaleidoscopeAngle(45); */ export const Kaleidoscope: Filter = function (imageData) { - var xSize = imageData.width, + const xSize = imageData.width, ySize = imageData.height; - var x, y, xoff, i, r, g, b, a, srcPos, dstPos; - var power = Math.round(this.kaleidoscopePower()); - var angle = Math.round(this.kaleidoscopeAngle()); - var offset = Math.floor((xSize * (angle % 360)) / 360); + let x, y, xoff, i, r, g, b, a, srcPos, dstPos; + let power = Math.round(this.kaleidoscopePower()); + const angle = Math.round(this.kaleidoscopeAngle()); + const offset = Math.floor((xSize * (angle % 360)) / 360); if (power < 1) { return; } // Work with our shared buffer canvas - var tempCanvas = Util.createCanvasElement(); + const tempCanvas = Util.createCanvasElement(); tempCanvas.width = xSize; tempCanvas.height = ySize; - var scratchData = tempCanvas + const scratchData = tempCanvas .getContext('2d')! .getImageData(0, 0, xSize, ySize); Util.releaseCanvas(tempCanvas); @@ -206,18 +206,18 @@ export const Kaleidoscope: Filter = function (imageData) { // Determine how big each section will be, if it's too small // make it bigger - var minSectionSize = xSize / Math.pow(2, power); + let minSectionSize = xSize / Math.pow(2, power); while (minSectionSize <= 8) { minSectionSize = minSectionSize * 2; power -= 1; } minSectionSize = Math.ceil(minSectionSize); - var sectionSize = minSectionSize; + let sectionSize = minSectionSize; // Copy the offset region to 0 // Depending on the size of filter and location of the offset we may need // to copy the section backwards to prevent it from rewriting itself - var xStart = 0, + let xStart = 0, xEnd = sectionSize, xDelta = 1; if (offset + minSectionSize > xSize) { diff --git a/src/filters/Mask.ts b/src/filters/Mask.ts index e2ff5a857..81a0bc44c 100644 --- a/src/filters/Mask.ts +++ b/src/filters/Mask.ts @@ -3,8 +3,8 @@ import { Node, Filter } from '../Node'; import { getNumberValidator } from '../Validators'; function pixelAt(idata, x, y) { - var idx = (y * idata.width + x) * 4; - var d: Array = []; + let idx = (y * idata.width + x) * 4; + const d: Array = []; d.push( idata.data[idx++], idata.data[idx++], @@ -23,9 +23,9 @@ function rgbDistance(p1, p2) { } function rgbMean(pTab) { - var m = [0, 0, 0]; + const m = [0, 0, 0]; - for (var i = 0; i < pTab.length; i++) { + for (let i = 0; i < pTab.length; i++) { m[0] += pTab[i][0]; m[1] += pTab[i][1]; m[2] += pTab[i][2]; @@ -39,12 +39,12 @@ function rgbMean(pTab) { } function backgroundMask(idata, threshold) { - var rgbv_no = pixelAt(idata, 0, 0); - var rgbv_ne = pixelAt(idata, idata.width - 1, 0); - var rgbv_so = pixelAt(idata, 0, idata.height - 1); - var rgbv_se = pixelAt(idata, idata.width - 1, idata.height - 1); + const rgbv_no = pixelAt(idata, 0, 0); + const rgbv_ne = pixelAt(idata, idata.width - 1, 0); + const rgbv_so = pixelAt(idata, 0, idata.height - 1); + const rgbv_se = pixelAt(idata, idata.width - 1, idata.height - 1); - var thres = threshold || 10; + const thres = threshold || 10; if ( rgbDistance(rgbv_no, rgbv_ne) < thres && rgbDistance(rgbv_ne, rgbv_se) < thres && @@ -52,12 +52,12 @@ function backgroundMask(idata, threshold) { rgbDistance(rgbv_so, rgbv_no) < thres ) { // Mean color - var mean = rgbMean([rgbv_ne, rgbv_no, rgbv_se, rgbv_so]); + const mean = rgbMean([rgbv_ne, rgbv_no, rgbv_se, rgbv_so]); // Mask based on color distance - var mask: Array = []; - for (var i = 0; i < idata.width * idata.height; i++) { - var d = rgbDistance(mean, [ + const mask: Array = []; + for (let i = 0; i < idata.width * idata.height; i++) { + const d = rgbDistance(mean, [ idata.data[i * 4], idata.data[i * 4 + 1], idata.data[i * 4 + 2], @@ -70,29 +70,29 @@ function backgroundMask(idata, threshold) { } function applyMask(idata, mask) { - for (var i = 0; i < idata.width * idata.height; i++) { + for (let i = 0; i < idata.width * idata.height; i++) { idata.data[4 * i + 3] = mask[i]; } } function erodeMask(mask, sw, sh) { - var weights = [1, 1, 1, 1, 0, 1, 1, 1, 1]; - var side = Math.round(Math.sqrt(weights.length)); - var halfSide = Math.floor(side / 2); - - var maskResult: Array = []; - for (var y = 0; y < sh; y++) { - for (var x = 0; x < sw; x++) { - var so = y * sw + x; - var a = 0; - for (var cy = 0; cy < side; cy++) { - for (var cx = 0; cx < side; cx++) { - var scy = y + cy - halfSide; - var scx = x + cx - halfSide; + const weights = [1, 1, 1, 1, 0, 1, 1, 1, 1]; + const side = Math.round(Math.sqrt(weights.length)); + const halfSide = Math.floor(side / 2); + + const maskResult: Array = []; + for (let y = 0; y < sh; y++) { + for (let x = 0; x < sw; x++) { + const so = y * sw + x; + let a = 0; + for (let cy = 0; cy < side; cy++) { + for (let cx = 0; cx < side; cx++) { + const scy = y + cy - halfSide; + const scx = x + cx - halfSide; if (scy >= 0 && scy < sh && scx >= 0 && scx < sw) { - var srcOff = scy * sw + scx; - var wt = weights[cy * side + cx]; + const srcOff = scy * sw + scx; + const wt = weights[cy * side + cx]; a += mask[srcOff] * wt; } @@ -107,23 +107,23 @@ function erodeMask(mask, sw, sh) { } function dilateMask(mask, sw, sh) { - var weights = [1, 1, 1, 1, 1, 1, 1, 1, 1]; - var side = Math.round(Math.sqrt(weights.length)); - var halfSide = Math.floor(side / 2); - - var maskResult: Array = []; - for (var y = 0; y < sh; y++) { - for (var x = 0; x < sw; x++) { - var so = y * sw + x; - var a = 0; - for (var cy = 0; cy < side; cy++) { - for (var cx = 0; cx < side; cx++) { - var scy = y + cy - halfSide; - var scx = x + cx - halfSide; + const weights = [1, 1, 1, 1, 1, 1, 1, 1, 1]; + const side = Math.round(Math.sqrt(weights.length)); + const halfSide = Math.floor(side / 2); + + const maskResult: Array = []; + for (let y = 0; y < sh; y++) { + for (let x = 0; x < sw; x++) { + const so = y * sw + x; + let a = 0; + for (let cy = 0; cy < side; cy++) { + for (let cx = 0; cx < side; cx++) { + const scy = y + cy - halfSide; + const scx = x + cx - halfSide; if (scy >= 0 && scy < sh && scx >= 0 && scx < sw) { - var srcOff = scy * sw + scx; - var wt = weights[cy * side + cx]; + const srcOff = scy * sw + scx; + const wt = weights[cy * side + cx]; a += mask[srcOff] * wt; } @@ -138,23 +138,23 @@ function dilateMask(mask, sw, sh) { } function smoothEdgeMask(mask, sw, sh) { - var weights = [1 / 9, 1 / 9, 1 / 9, 1 / 9, 1 / 9, 1 / 9, 1 / 9, 1 / 9, 1 / 9]; - var side = Math.round(Math.sqrt(weights.length)); - var halfSide = Math.floor(side / 2); - - var maskResult: Array = []; - for (var y = 0; y < sh; y++) { - for (var x = 0; x < sw; x++) { - var so = y * sw + x; - var a = 0; - for (var cy = 0; cy < side; cy++) { - for (var cx = 0; cx < side; cx++) { - var scy = y + cy - halfSide; - var scx = x + cx - halfSide; + const weights = [1 / 9, 1 / 9, 1 / 9, 1 / 9, 1 / 9, 1 / 9, 1 / 9, 1 / 9, 1 / 9]; + const side = Math.round(Math.sqrt(weights.length)); + const halfSide = Math.floor(side / 2); + + const maskResult: Array = []; + for (let y = 0; y < sh; y++) { + for (let x = 0; x < sw; x++) { + const so = y * sw + x; + let a = 0; + for (let cy = 0; cy < side; cy++) { + for (let cx = 0; cx < side; cx++) { + const scy = y + cy - halfSide; + const scx = x + cx - halfSide; if (scy >= 0 && scy < sh && scx >= 0 && scx < sw) { - var srcOff = scy * sw + scx; - var wt = weights[cy * side + cx]; + const srcOff = scy * sw + scx; + const wt = weights[cy * side + cx]; a += mask[srcOff] * wt; } @@ -181,7 +181,7 @@ function smoothEdgeMask(mask, sw, sh) { */ export const Mask: Filter = function (imageData) { // Detect pixels close to the background color - var threshold = this.threshold(), + let threshold = this.threshold(), mask = backgroundMask(imageData, threshold); if (mask) { // Erode diff --git a/src/filters/Noise.ts b/src/filters/Noise.ts index 0b741c1c9..39fd3ea12 100644 --- a/src/filters/Noise.ts +++ b/src/filters/Noise.ts @@ -15,13 +15,12 @@ import { getNumberValidator } from '../Validators'; * node.noise(0.8); */ export const Noise: Filter = function (imageData) { - var amount = this.noise() * 255, + const amount = this.noise() * 255, data = imageData.data, nPixels = data.length, - half = amount / 2, - i; + half = amount / 2; - for (i = 0; i < nPixels; i += 4) { + for (let i = 0; i < nPixels; i += 4) { data[i + 0] += half - 2 * half * Math.random(); data[i + 1] += half - 2 * half * Math.random(); data[i + 2] += half - 2 * half * Math.random(); diff --git a/src/filters/Pixelate.ts b/src/filters/Pixelate.ts index 35c3c630a..31dc27279 100644 --- a/src/filters/Pixelate.ts +++ b/src/filters/Pixelate.ts @@ -1,4 +1,4 @@ -/*eslint-disable max-depth */ + import { Factory } from '../Factory'; import { Util } from '../Util'; import { Node, Filter } from '../Node'; @@ -19,7 +19,7 @@ import { getNumberValidator } from '../Validators'; */ export const Pixelate: Filter = function (imageData) { - var pixelSize = Math.ceil(this.pixelSize()), + let pixelSize = Math.ceil(this.pixelSize()), width = imageData.width, height = imageData.height, x, diff --git a/src/filters/Posterize.ts b/src/filters/Posterize.ts index b27c0cf43..8c768e19f 100644 --- a/src/filters/Posterize.ts +++ b/src/filters/Posterize.ts @@ -18,7 +18,7 @@ import { getNumberValidator } from '../Validators'; export const Posterize: Filter = function (imageData) { // level must be between 1 and 255 - var levels = Math.round(this.levels() * 254) + 1, + let levels = Math.round(this.levels() * 254) + 1, data = imageData.data, len = data.length, scale = 255 / levels, diff --git a/src/filters/RGB.ts b/src/filters/RGB.ts index 3886f3ae7..8bdca6608 100644 --- a/src/filters/RGB.ts +++ b/src/filters/RGB.ts @@ -17,7 +17,7 @@ import { RGBComponent } from '../Validators'; */ export const RGB: Filter = function (imageData) { - var data = imageData.data, + let data = imageData.data, nPixels = data.length, red = this.red(), green = this.green(), diff --git a/src/filters/RGBA.ts b/src/filters/RGBA.ts index 793128c63..dcd140c07 100644 --- a/src/filters/RGBA.ts +++ b/src/filters/RGBA.ts @@ -18,17 +18,15 @@ import { RGBComponent } from '../Validators'; */ export const RGBA: Filter = function (imageData) { - var data = imageData.data, + const data = imageData.data, nPixels = data.length, red = this.red(), green = this.green(), blue = this.blue(), - alpha = this.alpha(), - i, - ia; + alpha = this.alpha(); - for (i = 0; i < nPixels; i += 4) { - ia = 1 - alpha; + for (let i = 0; i < nPixels; i += 4) { + const ia = 1 - alpha; data[i] = red * alpha + data[i] * ia; // r data[i + 1] = green * alpha + data[i + 1] * ia; // g diff --git a/src/filters/Sepia.ts b/src/filters/Sepia.ts index ee0c78702..2187bd0e6 100644 --- a/src/filters/Sepia.ts +++ b/src/filters/Sepia.ts @@ -12,7 +12,7 @@ import { Filter } from '../Node'; * node.filters([Konva.Filters.Sepia]); */ export const Sepia: Filter = function (imageData) { - var data = imageData.data, + let data = imageData.data, nPixels = data.length, i, r, diff --git a/src/filters/Solarize.ts b/src/filters/Solarize.ts index 472a68dab..c576b6f71 100644 --- a/src/filters/Solarize.ts +++ b/src/filters/Solarize.ts @@ -14,20 +14,21 @@ import { Filter } from '../Node'; */ export const Solarize: Filter = function (imageData) { - var data = imageData.data, + const data = imageData.data, w = imageData.width, h = imageData.height, - w4 = w * 4, - y = h; + w4 = w * 4; + + let y = h; do { - var offsetY = (y - 1) * w4; - var x = w; + const offsetY = (y - 1) * w4; + let x = w; do { - var offset = offsetY + (x - 1) * 4; - var r = data[offset]; - var g = data[offset + 1]; - var b = data[offset + 2]; + const offset = offsetY + (x - 1) * 4; + let r = data[offset]; + let g = data[offset + 1]; + let b = data[offset + 2]; if (r > 127) { r = 255 - r; diff --git a/src/filters/Threshold.ts b/src/filters/Threshold.ts index da8d55432..1cdb8bb02 100644 --- a/src/filters/Threshold.ts +++ b/src/filters/Threshold.ts @@ -17,12 +17,11 @@ import { getNumberValidator } from '../Validators'; */ export const Threshold: Filter = function (imageData) { - var level = this.threshold() * 255, + const level = this.threshold() * 255, data = imageData.data, - len = data.length, - i; + len = data.length; - for (i = 0; i < len; i += 1) { + for (let i = 0; i < len; i += 1) { data[i] = data[i] < level ? 0 : 255; } }; diff --git a/src/shapes/Arc.ts b/src/shapes/Arc.ts index b99a87117..63b97c5f7 100644 --- a/src/shapes/Arc.ts +++ b/src/shapes/Arc.ts @@ -39,7 +39,7 @@ export interface ArcConfig extends ShapeConfig { */ export class Arc extends Shape { _sceneFunc(context: Context) { - var angle = Konva.getAngle(this.angle()), + const angle = Konva.getAngle(this.angle()), clockwise = this.clockwise(); context.beginPath(); diff --git a/src/shapes/Arrow.ts b/src/shapes/Arrow.ts index 0b404c5de..72c735025 100644 --- a/src/shapes/Arrow.ts +++ b/src/shapes/Arrow.ts @@ -43,19 +43,19 @@ export interface ArrowConfig extends LineConfig { export class Arrow extends Line { _sceneFunc(ctx: Context) { super._sceneFunc(ctx); - var PI2 = Math.PI * 2; - var points = this.points(); + const PI2 = Math.PI * 2; + const points = this.points(); - var tp = points; - var fromTension = this.tension() !== 0 && points.length > 4; + let tp = points; + const fromTension = this.tension() !== 0 && points.length > 4; if (fromTension) { tp = this.getTensionPoints(); } - var length = this.pointerLength(); + const length = this.pointerLength(); - var n = points.length; + const n = points.length; - var dx, dy; + let dx, dy; if (fromTension) { const lp = [ tp[tp.length - 4], @@ -88,9 +88,9 @@ export class Arrow extends Line { dy = points[n - 1] - points[n - 3]; } - var radians = (Math.atan2(dy, dx) + PI2) % PI2; + const radians = (Math.atan2(dy, dx) + PI2) % PI2; - var width = this.pointerWidth(); + const width = this.pointerWidth(); if (this.pointerAtEnding()) { ctx.save(); @@ -130,7 +130,7 @@ export class Arrow extends Line { __fillStroke(ctx: Context) { // here is a tricky part // we need to disable dash for arrow pointers - var isDashEnabled = this.dashEnabled(); + const isDashEnabled = this.dashEnabled(); if (isDashEnabled) { // manually disable dash for head // it is better not to use setter here, diff --git a/src/shapes/Ellipse.ts b/src/shapes/Ellipse.ts index 83e6eaa13..2c115ae6c 100644 --- a/src/shapes/Ellipse.ts +++ b/src/shapes/Ellipse.ts @@ -31,7 +31,7 @@ export interface EllipseConfig extends ShapeConfig { */ export class Ellipse extends Shape { _sceneFunc(context: Context) { - var rx = this.radiusX(), + const rx = this.radiusX(), ry = this.radiusY(); context.beginPath(); diff --git a/src/shapes/Image.ts b/src/shapes/Image.ts index a17cc8787..ae5095308 100644 --- a/src/shapes/Image.ts +++ b/src/shapes/Image.ts @@ -117,7 +117,7 @@ export class Image extends Shape { // If you need to draw later, you need to execute save/restore } _hitFunc(context: Context) { - var width = this.width(), + const width = this.width(), height = this.height(), cornerRadius = this.cornerRadius(); @@ -156,9 +156,9 @@ export class Image extends Shape { callback: (img: Image) => void, onError: OnErrorEventHandler = null ) { - var img = Util.createImageElement(); + const img = Util.createImageElement(); img.onload = function () { - var image = new Image({ + const image = new Image({ image: img, }); callback(image); diff --git a/src/shapes/Label.ts b/src/shapes/Label.ts index 6ac09f5ff..a1e9888a7 100644 --- a/src/shapes/Label.ts +++ b/src/shapes/Label.ts @@ -15,7 +15,7 @@ import { Text } from './Text'; export interface LabelConfig extends ContainerConfig {} // constants -var ATTR_CHANGE_LIST = [ +const ATTR_CHANGE_LIST = [ 'fontFamily', 'fontSize', 'fontStyle', @@ -105,9 +105,9 @@ export class Label extends Group { return this.find('Tag')[0] as Tag; } _addListeners(text) { - var that = this, + let that = this, n; - var func = function () { + const func = function () { that._sync(); }; @@ -123,7 +123,7 @@ export class Label extends Group { return this.getText().height(); } _sync() { - var text = this.getText(), + let text = this.getText(), tag = this.getTag(), width, height, @@ -200,7 +200,7 @@ export interface TagConfig extends ShapeConfig { */ export class Tag extends Shape { _sceneFunc(context: Context) { - var width = this.width(), + const width = this.width(), height = this.height(), pointerDirection = this.pointerDirection(), pointerWidth = this.pointerWidth(), @@ -289,7 +289,7 @@ export class Tag extends Shape { context.fillStrokeShape(this); } getSelfRect() { - var x = 0, + let x = 0, y = 0, pointerWidth = this.pointerWidth(), pointerHeight = this.pointerHeight(), @@ -317,7 +317,7 @@ export class Tag extends Shape { }; } - pointerDirection: GetSet<'left' | 'top' | 'right' | 'bottom', this>; + pointerDirection: GetSet<'left' | 'top' | 'right' | 'bottom' | 'up' | 'down', this>; pointerWidth: GetSet; pointerHeight: GetSet; cornerRadius: GetSet; diff --git a/src/shapes/Line.ts b/src/shapes/Line.ts index 291a3de51..664fc3d50 100644 --- a/src/shapes/Line.ts +++ b/src/shapes/Line.ts @@ -1,14 +1,13 @@ -import { Util } from '../Util'; import { Factory } from '../Factory'; -import { Shape, ShapeConfig } from '../Shape'; -import { getNumberValidator, getNumberArrayValidator } from '../Validators'; import { _registerNode } from '../Global'; +import { Shape, ShapeConfig } from '../Shape'; +import { getNumberArrayValidator, getNumberValidator } from '../Validators'; -import { GetSet } from '../types'; import { Context } from '../Context'; +import { GetSet } from '../types'; function getControlPoints(x0, y0, x1, y1, x2, y2, t) { - var d01 = Math.sqrt(Math.pow(x1 - x0, 2) + Math.pow(y1 - y0, 2)), + const d01 = Math.sqrt(Math.pow(x1 - x0, 2) + Math.pow(y1 - y0, 2)), d12 = Math.sqrt(Math.pow(x2 - x1, 2) + Math.pow(y2 - y1, 2)), fa = (t * d01) / (d01 + d12), fb = (t * d12) / (d01 + d12), @@ -21,13 +20,11 @@ function getControlPoints(x0, y0, x1, y1, x2, y2, t) { } function expandPoints(p, tension) { - var len = p.length, - allPoints: Array = [], - n, - cp; + const len = p.length, + allPoints: Array = []; - for (n = 2; n < len - 2; n += 2) { - cp = getControlPoints( + for (let n = 2; n < len - 2; n += 2) { + const cp = getControlPoints( p[n - 2], p[n - 1], p[n], @@ -105,7 +102,7 @@ export class Line< } _sceneFunc(context: Context) { - var points = this.points(), + let points = this.points(), length = points.length, tension = this.tension(), closed = this.closed(), @@ -191,7 +188,7 @@ export class Line< } } _getTensionPointsClosed() { - var p = this.points(), + const p = this.points(), len = p.length, tension = this.tension(), firstControlPoints = getControlPoints( @@ -238,7 +235,7 @@ export class Line< } // overload size detection getSelfRect() { - var points = this.points(); + let points = this.points(); if (points.length < 4) { return { x: points[0] || 0, @@ -258,12 +255,12 @@ export class Line< } else { points = this.points(); } - var minX = points[0]; - var maxX = points[0]; - var minY = points[1]; - var maxY = points[1]; - var x, y; - for (var i = 0; i < points.length / 2; i++) { + let minX = points[0]; + let maxX = points[0]; + let minY = points[1]; + let maxY = points[1]; + let x, y; + for (let i = 0; i < points.length / 2; i++) { x = points[i * 2]; y = points[i * 2 + 1]; minX = Math.min(minX, x); diff --git a/src/shapes/Path.ts b/src/shapes/Path.ts index 67a905e25..e9e634932 100644 --- a/src/shapes/Path.ts +++ b/src/shapes/Path.ts @@ -51,14 +51,14 @@ export class Path extends Shape { } _sceneFunc(context) { - var ca = this.dataArray; + const ca = this.dataArray; // context position context.beginPath(); - var isClosed = false; - for (var n = 0; n < ca.length; n++) { - var c = ca[n].command; - var p = ca[n].points; + let isClosed = false; + for (let n = 0; n < ca.length; n++) { + const c = ca[n].command; + const p = ca[n].points; switch (c) { case 'L': context.lineTo(p[0], p[1]); @@ -109,16 +109,16 @@ export class Path extends Shape { } } getSelfRect() { - var points: Array = []; + let points: Array = []; this.dataArray.forEach(function (data) { if (data.command === 'A') { // Approximates by breaking curve into line segments - var start = data.points[4]; + const start = data.points[4]; // 4 = theta - var dTheta = data.points[5]; + const dTheta = data.points[5]; // 5 = dTheta - var end = data.points[4] + dTheta; - var inc = Math.PI / 180.0; + const end = data.points[4] + dTheta; + let inc = Math.PI / 180.0; // 1 degree resolution if (Math.abs(start - end) < inc) { inc = Math.abs(start - end); @@ -171,12 +171,12 @@ export class Path extends Shape { points = points.concat(data.points); } }); - var minX = points[0]; - var maxX = points[0]; - var minY = points[1]; - var maxY = points[1]; - var x, y; - for (var i = 0; i < points.length / 2; i++) { + let minX = points[0]; + let maxX = points[0]; + let minY = points[1]; + let maxY = points[1]; + let x, y; + for (let i = 0; i < points.length / 2; i++) { x = points[i * 2]; y = points[i * 2 + 1]; @@ -229,14 +229,14 @@ export class Path extends Shape { static getPathLength(dataArray: PathSegment[]) { let pathLength = 0; - for (var i = 0; i < dataArray.length; ++i) { + for (let i = 0; i < dataArray.length; ++i) { pathLength += dataArray[i].pathLength; } return pathLength; } static getPointAtLengthOfDataArray(length: number, dataArray: PathSegment[]) { - var points: number[], + let points: number[], i = 0, ii = dataArray.length; @@ -265,8 +265,8 @@ export class Path extends Shape { }; } - var cp = dataArray[i]; - var p = cp.points; + const cp = dataArray[i]; + const p = cp.points; switch (cp.command) { case 'L': return Path.getPointOnLine(length, cp.start.x, cp.start.y, p[0], p[1]); @@ -375,8 +375,8 @@ export class Path extends Shape { function CB4(t) { return (1 - t) * (1 - t) * (1 - t); } - var x = P4x * CB1(pct) + P3x * CB2(pct) + P2x * CB3(pct) + P1x * CB4(pct); - var y = P4y * CB1(pct) + P3y * CB2(pct) + P2y * CB3(pct) + P1y * CB4(pct); + const x = P4x * CB1(pct) + P3x * CB2(pct) + P2x * CB3(pct) + P1x * CB4(pct); + const y = P4y * CB1(pct) + P3y * CB2(pct) + P2y * CB3(pct) + P1y * CB4(pct); return { x: x, @@ -393,8 +393,8 @@ export class Path extends Shape { function QB3(t) { return (1 - t) * (1 - t); } - var x = P3x * QB1(pct) + P2x * QB2(pct) + P1x * QB3(pct); - var y = P3y * QB1(pct) + P2y * QB2(pct) + P1y * QB3(pct); + const x = P3x * QB1(pct) + P2x * QB2(pct) + P1x * QB3(pct); + const y = P3y * QB1(pct) + P2y * QB2(pct) + P1y * QB3(pct); return { x: x, @@ -409,9 +409,9 @@ export class Path extends Shape { theta: number, psi: number ) { - var cosPsi = Math.cos(psi), + const cosPsi = Math.cos(psi), sinPsi = Math.sin(psi); - var pt = { + const pt = { x: rx * Math.cos(theta), y: ry * Math.sin(theta), }; @@ -455,10 +455,10 @@ export class Path extends Shape { } // command string - var cs = data; + let cs = data; // command chars - var cc = [ + const cc = [ 'm', 'M', 'l', @@ -487,18 +487,18 @@ export class Path extends Shape { cs = cs.replace(new RegExp(cc[n], 'g'), '|' + cc[n]); } // create array - var arr = cs.split('|'); - var ca: PathSegment[] = []; - var coords: string[] = []; + const arr = cs.split('|'); + const ca: PathSegment[] = []; + const coords: string[] = []; // init context point - var cpx = 0; - var cpy = 0; + let cpx = 0; + let cpy = 0; - var re = /([-+]?((\d+\.\d+)|((\d+)|(\.\d+)))(?:e[-+]?\d+)?)/gi; - var match; + const re = /([-+]?((\d+\.\d+)|((\d+)|(\.\d+)))(?:e[-+]?\d+)?)/gi; + let match; for (n = 1; n < arr.length; n++) { - var str = arr[n]; - var c = str.charAt(0); + let str = arr[n]; + let c = str.charAt(0); str = str.slice(1); coords.length = 0; @@ -509,15 +509,15 @@ export class Path extends Shape { // while ((match = re.exec(str))) { // coords.push(match[0]); // } - var p: number[] = []; + const p: number[] = []; - for (var j = 0, jlen = coords.length; j < jlen; j++) { + for (let j = 0, jlen = coords.length; j < jlen; j++) { // extra case for merged flags if (coords[j] === '00') { p.push(0, 0); continue; } - var parsed = parseFloat(coords[j]); + const parsed = parseFloat(coords[j]); if (!isNaN(parsed)) { p.push(parsed); } else { @@ -531,9 +531,9 @@ export class Path extends Shape { break; } - var cmd: string = ''; - var points: number[] = []; - var startX = cpx, + let cmd: string = ''; + let points: number[] = []; + const startX = cpx, startY = cpy; // Move var from within the switch to up here (jshint) var prevCmd, ctlPtx, ctlPty; // Ss, Tt @@ -563,7 +563,7 @@ export class Path extends Shape { // After closing the path move the current position // to the the first point of the path (if any). if (ca.length > 2 && ca[ca.length - 1].command === 'z') { - for (var idx = ca.length - 2; idx >= 0; idx--) { + for (let idx = ca.length - 2; idx >= 0; idx--) { if (ca[idx].command === 'M') { cpx = ca[idx].points[0] + dx; cpy = ca[idx].points[1] + dy; @@ -761,8 +761,8 @@ export class Path extends Shape { return ca; } static calcLength(x, y, cmd, points) { - var len, p1, p2, t; - var path = Path; + let len, p1, p2, t; + const path = Path; switch (cmd) { case 'L': @@ -857,21 +857,21 @@ export class Path extends Shape { psiDeg ) { // Derived from: http://www.w3.org/TR/SVG/implnote.html#ArcImplementationNotes - var psi = psiDeg * (Math.PI / 180.0); - var xp = + const psi = psiDeg * (Math.PI / 180.0); + const xp = (Math.cos(psi) * (x1 - x2)) / 2.0 + (Math.sin(psi) * (y1 - y2)) / 2.0; - var yp = + const yp = (-1 * Math.sin(psi) * (x1 - x2)) / 2.0 + (Math.cos(psi) * (y1 - y2)) / 2.0; - var lambda = (xp * xp) / (rx * rx) + (yp * yp) / (ry * ry); + const lambda = (xp * xp) / (rx * rx) + (yp * yp) / (ry * ry); if (lambda > 1) { rx *= Math.sqrt(lambda); ry *= Math.sqrt(lambda); } - var f = Math.sqrt( + let f = Math.sqrt( (rx * rx * (ry * ry) - rx * rx * (yp * yp) - ry * ry * (xp * xp)) / (rx * rx * (yp * yp) + ry * ry * (xp * xp)) ); @@ -883,25 +883,25 @@ export class Path extends Shape { f = 0; } - var cxp = (f * rx * yp) / ry; - var cyp = (f * -ry * xp) / rx; + const cxp = (f * rx * yp) / ry; + const cyp = (f * -ry * xp) / rx; - var cx = (x1 + x2) / 2.0 + Math.cos(psi) * cxp - Math.sin(psi) * cyp; - var cy = (y1 + y2) / 2.0 + Math.sin(psi) * cxp + Math.cos(psi) * cyp; + const cx = (x1 + x2) / 2.0 + Math.cos(psi) * cxp - Math.sin(psi) * cyp; + const cy = (y1 + y2) / 2.0 + Math.sin(psi) * cxp + Math.cos(psi) * cyp; - var vMag = function (v) { + const vMag = function (v) { return Math.sqrt(v[0] * v[0] + v[1] * v[1]); }; - var vRatio = function (u, v) { + const vRatio = function (u, v) { return (u[0] * v[0] + u[1] * v[1]) / (vMag(u) * vMag(v)); }; - var vAngle = function (u, v) { + const vAngle = function (u, v) { return (u[0] * v[1] < u[1] * v[0] ? -1 : 1) * Math.acos(vRatio(u, v)); }; - var theta = vAngle([1, 0], [(xp - cxp) / rx, (yp - cyp) / ry]); - var u = [(xp - cxp) / rx, (yp - cyp) / ry]; - var v = [(-1 * xp - cxp) / rx, (-1 * yp - cyp) / ry]; - var dTheta = vAngle(u, v); + const theta = vAngle([1, 0], [(xp - cxp) / rx, (yp - cyp) / ry]); + const u = [(xp - cxp) / rx, (yp - cyp) / ry]; + const v = [(-1 * xp - cxp) / rx, (-1 * yp - cyp) / ry]; + let dTheta = vAngle(u, v); if (vRatio(u, v) <= -1) { dTheta = Math.PI; diff --git a/src/shapes/Rect.ts b/src/shapes/Rect.ts index 4b1dcddc4..ec8ad79de 100644 --- a/src/shapes/Rect.ts +++ b/src/shapes/Rect.ts @@ -31,7 +31,7 @@ export interface RectConfig extends ShapeConfig { */ export class Rect extends Shape { _sceneFunc(context: Context) { - var cornerRadius = this.cornerRadius(), + const cornerRadius = this.cornerRadius(), width = this.width(), height = this.height(); diff --git a/src/shapes/RegularPolygon.ts b/src/shapes/RegularPolygon.ts index e9ce01cc7..6ade36cfa 100644 --- a/src/shapes/RegularPolygon.ts +++ b/src/shapes/RegularPolygon.ts @@ -37,7 +37,7 @@ export class RegularPolygon extends Shape { context.beginPath(); context.moveTo(points[0].x, points[0].y); - for (var n = 1; n < points.length; n++) { + for (let n = 1; n < points.length; n++) { context.lineTo(points[n].x, points[n].y); } @@ -48,7 +48,7 @@ export class RegularPolygon extends Shape { const sides = this.attrs.sides as number; const radius = this.attrs.radius || 0; const points: Vector2d[] = []; - for (var n = 0; n < sides; n++) { + for (let n = 0; n < sides; n++) { points.push({ x: radius * Math.sin((n * 2 * Math.PI) / sides), y: -1 * radius * Math.cos((n * 2 * Math.PI) / sides), @@ -59,10 +59,10 @@ export class RegularPolygon extends Shape { getSelfRect() { const points = this._getPoints(); - var minX = points[0].x; - var maxX = points[0].y; - var minY = points[0].x; - var maxY = points[0].y; + let minX = points[0].x; + let maxX = points[0].y; + let minY = points[0].x; + let maxY = points[0].y; points.forEach((point) => { minX = Math.min(minX, point.x); maxX = Math.max(maxX, point.x); diff --git a/src/shapes/Ring.ts b/src/shapes/Ring.ts index 147338ae9..f22a47696 100644 --- a/src/shapes/Ring.ts +++ b/src/shapes/Ring.ts @@ -10,7 +10,7 @@ export interface RingConfig extends ShapeConfig { outerRadius: number; } -var PIx2 = Math.PI * 2; +const PIx2 = Math.PI * 2; /** * Ring constructor * @constructor diff --git a/src/shapes/Sprite.ts b/src/shapes/Sprite.ts index d1f2b7ef8..a4ac4918d 100644 --- a/src/shapes/Sprite.ts +++ b/src/shapes/Sprite.ts @@ -70,7 +70,7 @@ export class Sprite extends Shape { super(config); this.anim = new Animation(() => { // if we don't need to redraw layer we should return false - var updated = this._updated; + const updated = this._updated; this._updated = false; return updated; }); @@ -92,7 +92,7 @@ export class Sprite extends Shape { } _sceneFunc(context: Context) { - var anim = this.animation(), + const anim = this.animation(), index = this.frameIndex(), ix4 = index * 4, set = this.animations()[anim], @@ -112,7 +112,7 @@ export class Sprite extends Shape { if (image) { if (offsets) { - var offset = offsets[anim], + const offset = offsets[anim], ix2 = index * 2; context.drawImage( image, @@ -131,7 +131,7 @@ export class Sprite extends Shape { } } _hitFunc(context: Context) { - var anim = this.animation(), + const anim = this.animation(), index = this.frameIndex(), ix4 = index * 4, set = this.animations()[anim], @@ -141,8 +141,8 @@ export class Sprite extends Shape { context.beginPath(); if (offsets) { - var offset = offsets[anim]; - var ix2 = index * 2; + const offset = offsets[anim]; + const ix2 = index * 2; context.rect(offset[ix2 + 0], offset[ix2 + 1], width, height); } else { context.rect(0, 0, width, height); @@ -156,7 +156,7 @@ export class Sprite extends Shape { } _setInterval() { - var that = this; + const that = this; this.interval = setInterval(function () { that._updateIndex(); }, 1000 / this.frameRate()); @@ -170,7 +170,7 @@ export class Sprite extends Shape { if (this.isRunning()) { return; } - var layer = this.getLayer(); + const layer = this.getLayer(); /* * animation object has no executable function because @@ -201,7 +201,7 @@ export class Sprite extends Shape { return this.anim.isRunning(); } _updateIndex() { - var index = this.frameIndex(), + const index = this.frameIndex(), animation = this.animation(), animations = this.animations(), anim = animations[animation], diff --git a/src/shapes/Star.ts b/src/shapes/Star.ts index a98713f32..8dee6d542 100644 --- a/src/shapes/Star.ts +++ b/src/shapes/Star.ts @@ -37,17 +37,17 @@ export interface StarConfig extends ShapeConfig { */ export class Star extends Shape { _sceneFunc(context: Context) { - var innerRadius = this.innerRadius(), + const innerRadius = this.innerRadius(), outerRadius = this.outerRadius(), numPoints = this.numPoints(); context.beginPath(); context.moveTo(0, 0 - outerRadius); - for (var n = 1; n < numPoints * 2; n++) { - var radius = n % 2 === 0 ? outerRadius : innerRadius; - var x = radius * Math.sin((n * Math.PI) / numPoints); - var y = -1 * radius * Math.cos((n * Math.PI) / numPoints); + for (let n = 1; n < numPoints * 2; n++) { + const radius = n % 2 === 0 ? outerRadius : innerRadius; + const x = radius * Math.sin((n * Math.PI) / numPoints); + const y = -1 * radius * Math.cos((n * Math.PI) / numPoints); context.lineTo(x, y); } context.closePath(); diff --git a/src/shapes/Text.ts b/src/shapes/Text.ts index cd5b68df9..dbd3b9485 100644 --- a/src/shapes/Text.ts +++ b/src/shapes/Text.ts @@ -60,7 +60,7 @@ export interface TextConfig extends ShapeConfig { } // constants -var AUTO = 'auto', +const AUTO = 'auto', //CANVAS = 'canvas', CENTER = 'center', INHERIT = 'inherit', @@ -69,7 +69,6 @@ var AUTO = 'auto', CONTEXT_2D = '2d', DASH = '-', LEFT = 'left', - LTR = 'ltr', TEXT = 'text', TEXT_UPPER = 'Text', TOP = 'top', @@ -119,7 +118,7 @@ function normalizeFontFamily(fontFamily: string) { .join(', '); } -var dummyContext: CanvasRenderingContext2D; +let dummyContext: CanvasRenderingContext2D; function getDummyContext() { if (dummyContext) { return dummyContext; @@ -194,21 +193,21 @@ export class Text extends Shape { constructor(config?: TextConfig) { super(checkDefaultFill(config)); // update text data for certain attr changes - for (var n = 0; n < attrChangeListLen; n++) { + for (let n = 0; n < attrChangeListLen; n++) { this.on(ATTR_CHANGE_LIST[n] + CHANGE_KONVA, this._setTextData); } this._setTextData(); } _sceneFunc(context: Context) { - var textArr = this.textArr, + const textArr = this.textArr, textArrLen = textArr.length; if (!this.text()) { return; } - var padding = this.padding(), + let padding = this.padding(), fontSize = this.fontSize(), lineHeightPx = this.lineHeight() * fontSize, verticalAlign = this.verticalAlign(), @@ -225,10 +224,10 @@ export class Text extends Shape { direction = direction === INHERIT ? context.direction : direction; - var translateY = lineHeightPx / 2; - var baseline = MIDDLE; + let translateY = lineHeightPx / 2; + let baseline = MIDDLE; if (Konva._fixTextRendering) { - var metrics = this.measureSize('M'); // Use a sample character to get the ascent + const metrics = this.measureSize('M'); // Use a sample character to get the ascent baseline = 'alphabetic'; translateY = @@ -282,7 +281,7 @@ export class Text extends Shape { context.save(); context.beginPath(); - let yOffset = Konva._fixTextRendering + const yOffset = Konva._fixTextRendering ? Math.round(fontSize / 4) : Math.round(fontSize / 2); const x = lineTranslateX; @@ -306,14 +305,12 @@ export class Text extends Shape { if (shouldLineThrough) { context.save(); context.beginPath(); - let yOffset = Konva._fixTextRendering ? -Math.round(fontSize / 4) : 0; + const yOffset = Konva._fixTextRendering ? -Math.round(fontSize / 4) : 0; context.moveTo(lineTranslateX, translateY + lineTranslateY + yOffset); spacesNumber = text.split(' ').length - 1; oneWord = spacesNumber === 0; lineWidth = - align === JUSTIFY && lastLine && !oneWord - ? totalWidth - padding * 2 - : width; + align === JUSTIFY && !lastLine ? totalWidth - padding * 2 : width; context.lineTo( lineTranslateX + Math.round(lineWidth), translateY + lineTranslateY + yOffset @@ -330,9 +327,9 @@ export class Text extends Shape { if (direction !== RTL && (letterSpacing !== 0 || align === JUSTIFY)) { // var words = text.split(' '); spacesNumber = text.split(' ').length - 1; - var array = stringToArray(text); - for (var li = 0; li < array.length; li++) { - var letter = array[li]; + const array = stringToArray(text); + for (let li = 0; li < array.length; li++) { + const letter = array[li]; // skip justify for the last line if (letter === ' ' && !lastLine && align === JUSTIFY) { lineTranslateX += (totalWidth - padding * 2 - width) / spacesNumber; @@ -364,7 +361,7 @@ export class Text extends Shape { } } _hitFunc(context: Context) { - var width = this.getWidth(), + const width = this.getWidth(), height = this.getHeight(); context.beginPath(); @@ -373,7 +370,7 @@ export class Text extends Shape { context.fillStrokeShape(this); } setText(text: string) { - var str = Util._isString(text) + const str = Util._isString(text) ? text : text === null || text === undefined ? '' @@ -382,11 +379,11 @@ export class Text extends Shape { return this; } getWidth() { - var isAuto = this.attrs.width === AUTO || this.attrs.width === undefined; + const isAuto = this.attrs.width === AUTO || this.attrs.width === undefined; return isAuto ? this.getTextWidth() + this.padding() * 2 : this.attrs.width; } getHeight() { - var isAuto = this.attrs.height === AUTO || this.attrs.height === undefined; + const isAuto = this.attrs.height === AUTO || this.attrs.height === undefined; return isAuto ? this.fontSize() * this.textArr.length * this.lineHeight() + this.padding() * 2 @@ -417,7 +414,7 @@ export class Text extends Shape { * @returns {Object} { width , height } of measured text */ measureSize(text: string) { - var _context = getDummyContext(), + let _context = getDummyContext(), fontSize = this.fontSize(), metrics: TextMetrics; @@ -468,7 +465,7 @@ export class Text extends Shape { if (align === JUSTIFY) { line = line.trim(); } - var width = this._getTextWidth(line); + const width = this._getTextWidth(line); return this.textArr.push({ text: line, width: width, @@ -476,15 +473,15 @@ export class Text extends Shape { }); } _getTextWidth(text: string) { - var letterSpacing = this.letterSpacing(); - var length = text.length; + const letterSpacing = this.letterSpacing(); + const length = text.length; return ( getDummyContext().measureText(text).width + (length ? letterSpacing * (length - 1) : 0) ); } _setTextData() { - var lines = this.text().split('\n'), + let lines = this.text().split('\n'), fontSize = +this.fontSize(), textWidth = 0, lineHeightPx = this.lineHeight() * fontSize, @@ -504,11 +501,11 @@ export class Text extends Shape { this.textArr = []; getDummyContext().font = this._getContextFont(); - var additionalWidth = shouldAddEllipsis ? this._getTextWidth(ELLIPSIS) : 0; - for (var i = 0, max = lines.length; i < max; ++i) { - var line = lines[i]; + const additionalWidth = shouldAddEllipsis ? this._getTextWidth(ELLIPSIS) : 0; + for (let i = 0, max = lines.length; i < max; ++i) { + let line = lines[i]; - var lineWidth = this._getTextWidth(line); + let lineWidth = this._getTextWidth(line); if (fixedWidth && lineWidth > maxWidth) { /* * if width is fixed and line does not fit entirely @@ -519,12 +516,12 @@ export class Text extends Shape { * use binary search to find the longest substring that * that would fit in the specified width */ - var low = 0, + let low = 0, high = line.length, match = '', matchWidth = 0; while (low < high) { - var mid = (low + high) >>> 1, + const mid = (low + high) >>> 1, substr = line.slice(0, mid + 1), substrWidth = this._getTextWidth(substr) + additionalWidth; if (substrWidth <= maxWidth) { @@ -545,8 +542,8 @@ export class Text extends Shape { if (wrapAtWord) { // try to find a space or dash where wrapping could be done var wrapIndex; - var nextChar = line[match.length]; - var nextIsSpaceOrDash = nextChar === SPACE || nextChar === DASH; + const nextChar = line[match.length]; + const nextIsSpaceOrDash = nextChar === SPACE || nextChar === DASH; if (nextIsSpaceOrDash && matchWidth <= maxWidth) { wrapIndex = match.length; } else { @@ -568,7 +565,7 @@ export class Text extends Shape { textWidth = Math.max(textWidth, matchWidth); currentHeightPx += lineHeightPx; - var shouldHandleEllipsis = + const shouldHandleEllipsis = this._shouldHandleEllipsis(currentHeightPx); if (shouldHandleEllipsis) { this._tryToAddEllipsisToLastLine(); @@ -629,7 +626,7 @@ export class Text extends Shape { * @returns */ _shouldHandleEllipsis(currentHeightPx: number): boolean { - var fontSize = +this.fontSize(), + const fontSize = +this.fontSize(), lineHeightPx = this.lineHeight() * fontSize, height = this.attrs.height, fixedHeight = height !== AUTO && height !== undefined, @@ -645,19 +642,19 @@ export class Text extends Shape { } _tryToAddEllipsisToLastLine(): void { - var width = this.attrs.width, + const width = this.attrs.width, fixedWidth = width !== AUTO && width !== undefined, padding = this.padding(), maxWidth = width - padding * 2, shouldAddEllipsis = this.ellipsis(); - var lastLine = this.textArr[this.textArr.length - 1]; + const lastLine = this.textArr[this.textArr.length - 1]; if (!lastLine || !shouldAddEllipsis) { return; } if (fixedWidth) { - var haveSpace = this._getTextWidth(lastLine.text + ELLIPSIS) < maxWidth; + const haveSpace = this._getTextWidth(lastLine.text + ELLIPSIS) < maxWidth; if (!haveSpace) { lastLine.text = lastLine.text.slice(0, lastLine.text.length - 3); } diff --git a/src/shapes/TextPath.ts b/src/shapes/TextPath.ts index f329ef3a2..6912fe558 100644 --- a/src/shapes/TextPath.ts +++ b/src/shapes/TextPath.ts @@ -18,7 +18,7 @@ export interface TextPathConfig extends ShapeConfig { letterSpacing?: number; } -var EMPTY_STRING = '', +const EMPTY_STRING = '', NORMAL = 'normal'; function _fillFunc(this: TextPath, context) { @@ -137,18 +137,18 @@ export class TextPath extends Shape { context.setAttr('textAlign', 'left'); context.save(); - var textDecoration = this.textDecoration(); - var fill = this.fill(); - var fontSize = this.fontSize(); + const textDecoration = this.textDecoration(); + const fill = this.fill(); + const fontSize = this.fontSize(); - var glyphInfo = this.glyphInfo; + const glyphInfo = this.glyphInfo; if (textDecoration === 'underline') { context.beginPath(); } - for (var i = 0; i < glyphInfo.length; i++) { + for (let i = 0; i < glyphInfo.length; i++) { context.save(); - var p0 = glyphInfo[i].p0; + const p0 = glyphInfo[i].p0; context.translate(p0.x, p0.y); context.rotate(glyphInfo[i].rotation); @@ -184,13 +184,13 @@ export class TextPath extends Shape { _hitFunc(context: Context) { context.beginPath(); - var glyphInfo = this.glyphInfo; + const glyphInfo = this.glyphInfo; if (glyphInfo.length >= 1) { - var p0 = glyphInfo[0].p0; + const p0 = glyphInfo[0].p0; context.moveTo(p0.x, p0.y); } - for (var i = 0; i < glyphInfo.length; i++) { - var p1 = glyphInfo[i].p1; + for (let i = 0; i < glyphInfo.length; i++) { + const p1 = glyphInfo[i].p1; context.lineTo(p1.x, p1.y); } context.setAttr('lineWidth', this.fontSize()); @@ -220,13 +220,13 @@ export class TextPath extends Shape { } _getTextSize(text: string) { - var dummyCanvas = this.dummyCanvas; - var _context = dummyCanvas.getContext('2d')!; + const dummyCanvas = this.dummyCanvas; + const _context = dummyCanvas.getContext('2d')!; _context.save(); _context.font = this._getContextFont(); - var metrics = _context.measureText(text); + const metrics = _context.measureText(text); _context.restore(); @@ -271,7 +271,7 @@ export class TextPath extends Shape { // 3. Calculate the rotation, width, and midpoint of the glyph using the start and end points, // 4. Add glyph width to the offsetToGlyph and repeat let offsetToGlyph = offset; - for (var i = 0; i < charArr.length; i++) { + for (let i = 0; i < charArr.length; i++) { const charStartPoint = this._getPointAtLength(offsetToGlyph); if (!charStartPoint) return; @@ -338,7 +338,7 @@ export class TextPath extends Shape { height: 0, }; } - var points: number[] = []; + const points: number[] = []; this.glyphInfo.forEach(function (info) { points.push(info.p0.x); @@ -346,12 +346,12 @@ export class TextPath extends Shape { points.push(info.p1.x); points.push(info.p1.y); }); - var minX = points[0] || 0; - var maxX = points[0] || 0; - var minY = points[1] || 0; - var maxY = points[1] || 0; - var x, y; - for (var i = 0; i < points.length / 2; i++) { + let minX = points[0] || 0; + let maxX = points[0] || 0; + let minY = points[1] || 0; + let maxY = points[1] || 0; + let x, y; + for (let i = 0; i < points.length / 2; i++) { x = points[i * 2]; y = points[i * 2 + 1]; minX = Math.min(minX, x); @@ -359,7 +359,7 @@ export class TextPath extends Shape { minY = Math.min(minY, y); maxY = Math.max(maxY, y); } - var fontSize = this.fontSize(); + const fontSize = this.fontSize(); return { x: minX - fontSize / 2, y: minY - fontSize / 2, diff --git a/src/shapes/Transformer.ts b/src/shapes/Transformer.ts index 859608875..d5c6bd0e0 100644 --- a/src/shapes/Transformer.ts +++ b/src/shapes/Transformer.ts @@ -50,9 +50,9 @@ export interface TransformerConfig extends ContainerConfig { anchorStyleFunc?: (anchor: Rect) => void; } -var EVENTS_NAME = 'tr-konva'; +const EVENTS_NAME = 'tr-konva'; -var ATTR_CHANGE_LIST = [ +const ATTR_CHANGE_LIST = [ 'resizeEnabledChange', 'rotateAnchorOffsetChange', 'rotateEnabledChange', @@ -72,9 +72,9 @@ var ATTR_CHANGE_LIST = [ .map((e) => e + `.${EVENTS_NAME}`) .join(' '); -var NODES_RECT = 'nodesRect'; +const NODES_RECT = 'nodesRect'; -var TRANSFORM_CHANGE_STR = [ +const TRANSFORM_CHANGE_STR = [ 'widthChange', 'heightChange', 'scaleXChange', @@ -88,7 +88,7 @@ var TRANSFORM_CHANGE_STR = [ 'strokeWidthChange', ]; -var ANGLES = { +const ANGLES = { 'top-left': -45, 'top-center': 0, 'top-right': 45, @@ -107,7 +107,7 @@ function getCursor(anchorName, rad, rotateCursor) { } rad += Util.degToRad(ANGLES[anchorName] || 0); - var angle = ((Util.radToDeg(rad) % 360) + 360) % 360; + const angle = ((Util.radToDeg(rad) % 360) + 360) % 360; if (Util._inRange(angle, 315 + 22.5, 360) || Util._inRange(angle, 0, 22.5)) { // TOP @@ -140,7 +140,7 @@ function getCursor(anchorName, rad, rotateCursor) { } } -var ANCHORS_NAMES = [ +const ANCHORS_NAMES = [ 'top-left', 'top-center', 'top-right', @@ -151,7 +151,7 @@ var ANCHORS_NAMES = [ 'bottom-right', ]; -var MAX_SAFE_INTEGER = 100000000; +const MAX_SAFE_INTEGER = 100000000; function getCenter(shape: Box) { return { @@ -351,7 +351,7 @@ export class Transformer extends Group { this._resetTransformCache(); // we may need it if we set node in initial props // so elements are not defined yet - var elementsCreated = !!this.findOne('.top-left'); + const elementsCreated = !!this.findOne('.top-left'); if (elementsCreated) { this.update(); } @@ -449,17 +449,17 @@ export class Transformer extends Group { // return absolute rotated bounding rectangle __getNodeShape(node: Node, rot = this.rotation(), relative?: Node) { - var rect = node.getClientRect({ + const rect = node.getClientRect({ skipTransform: true, skipShadow: true, skipStroke: this.ignoreStroke(), }); - var absScale = node.getAbsoluteScale(relative); - var absPos = node.getAbsolutePosition(relative); + const absScale = node.getAbsoluteScale(relative); + const absPos = node.getAbsolutePosition(relative); - var dx = rect.x * absScale.x - node.offsetX() * absScale.x; - var dy = rect.y * absScale.y - node.offsetY() * absScale.y; + const dx = rect.x * absScale.x - node.offsetX() * absScale.x; + const dy = rect.y * absScale.y - node.offsetY() * absScale.y; const rotation = (Konva.getAngle(node.getAbsoluteRotation()) + Math.PI * 2) % @@ -479,7 +479,7 @@ export class Transformer extends Group { } // returns box + rotation of all shapes __getNodeRect() { - var node = this.getNode(); + const node = this.getNode(); if (!node) { return { x: -MAX_SAFE_INTEGER, @@ -497,15 +497,15 @@ export class Transformer extends Group { skipShadow: true, skipStroke: this.ignoreStroke(), }); - var points = [ + const points = [ { x: box.x, y: box.y }, { x: box.x + box.width, y: box.y }, { x: box.x + box.width, y: box.y + box.height }, { x: box.x, y: box.y + box.height }, ]; - var trans = node.getAbsoluteTransform(); + const trans = node.getAbsoluteTransform(); points.forEach(function (point) { - var transformed = trans.point(point); + const transformed = trans.point(point); totalPoints.push(transformed); }); }); @@ -513,12 +513,12 @@ export class Transformer extends Group { const tr = new Transform(); tr.rotate(-Konva.getAngle(this.rotation())); - var minX: number = Infinity, + let minX: number = Infinity, minY: number = Infinity, maxX: number = -Infinity, maxY: number = -Infinity; totalPoints.forEach(function (point) { - var transformed = tr.point(point); + const transformed = tr.point(point); if (minX === undefined) { minX = maxX = transformed.x; minY = maxY = transformed.y; @@ -570,7 +570,7 @@ export class Transformer extends Group { this._createAnchor('rotater'); } _createAnchor(name) { - var anchor = new Rect({ + const anchor = new Rect({ stroke: 'rgb(0, 161, 255)', fill: 'white', strokeWidth: 1, @@ -581,7 +581,7 @@ export class Transformer extends Group { draggable: true, hitStrokeWidth: TOUCH_DEVICE ? 10 : 'auto', }); - var self = this; + const self = this; anchor.on('mousedown touchstart', function (e) { self._handleMouseDown(e); }); @@ -595,9 +595,9 @@ export class Transformer extends Group { // add hover styling anchor.on('mouseenter', () => { - var rad = Konva.getAngle(this.rotation()); - var rotateCursor = this.rotateAnchorCursor(); - var cursor = getCursor(name, rad, rotateCursor); + const rad = Konva.getAngle(this.rotation()); + const rotateCursor = this.rotateAnchorCursor(); + const cursor = getCursor(name, rad, rotateCursor); anchor.getStage()!.content && (anchor.getStage()!.content.style.cursor = cursor); this._cursorChange = true; @@ -610,14 +610,14 @@ export class Transformer extends Group { this.add(anchor); } _createBack() { - var back = new Shape({ + const back = new Shape({ name: 'back', width: 0, height: 0, draggable: true, sceneFunc(ctx, shape) { - var tr = shape.getParent() as Transformer; - var padding = tr.padding(); + const tr = shape.getParent() as Transformer; + const padding = tr.padding(); ctx.beginPath(); ctx.rect( -padding, @@ -639,7 +639,7 @@ export class Transformer extends Group { if (!this.shouldOverdrawWholeArea()) { return; } - var padding = this.padding(); + const padding = this.padding(); ctx.beginPath(); ctx.rect( -padding, @@ -677,11 +677,11 @@ export class Transformer extends Group { } this._movingAnchorName = e.target.name().split(' ')[0]; - var attrs = this._getNodeRect(); - var width = attrs.width; - var height = attrs.height; + const attrs = this._getNodeRect(); + const width = attrs.width; + const height = attrs.height; - var hypotenuse = Math.sqrt(Math.pow(width, 2) + Math.pow(height, 2)); + const hypotenuse = Math.sqrt(Math.pow(width, 2) + Math.pow(height, 2)); this.sin = Math.abs(height / hypotenuse); this.cos = Math.abs(width / hypotenuse); @@ -693,8 +693,8 @@ export class Transformer extends Group { } this._transforming = true; - var ap = e.target.getAbsolutePosition(); - var pos = e.target.getStage().getPointerPosition(); + const ap = e.target.getAbsolutePosition(); + const pos = e.target.getStage().getPointerPosition(); this._anchorDragOffset = { x: pos.x - ap.x, y: pos.y - ap.y, @@ -706,9 +706,9 @@ export class Transformer extends Group { }); } _handleMouseMove(e) { - var x, y, newHypotenuse; - var anchorNode = this.findOne('.' + this._movingAnchorName)!; - var stage = anchorNode.getStage()!; + let x, y, newHypotenuse; + const anchorNode = this.findOne('.' + this._movingAnchorName)!; + const stage = anchorNode.getStage()!; stage.setPointersPositions(e); @@ -733,7 +733,7 @@ export class Transformer extends Group { // rotater is working very differently, so do it first if (this._movingAnchorName === 'rotater') { - var attrs = this._getNodeRect(); + const attrs = this._getNodeRect(); x = anchorNode.x() - attrs.width / 2; y = -anchorNode.y() + attrs.height / 2; @@ -744,7 +744,7 @@ export class Transformer extends Group { delta -= Math.PI; } - var oldRotation = Konva.getAngle(this.rotation()); + const oldRotation = Konva.getAngle(this.rotation()); const newRotation = oldRotation + delta; const tol = Konva.getAngle(this.rotationSnapTolerance()); @@ -757,9 +757,9 @@ export class Transformer extends Group { return; } - var shiftBehavior = this.shiftBehavior(); + const shiftBehavior = this.shiftBehavior(); - var keepProportion: boolean; + let keepProportion: boolean; if (shiftBehavior === 'inverted') { keepProportion = this.keepRatio() && !e.shiftKey; } else if (shiftBehavior === 'none') { @@ -908,13 +908,13 @@ export class Transformer extends Group { var centeredScaling = this.centeredScaling() || e.altKey; if (centeredScaling) { - var topLeft = this.findOne('.top-left')!; - var bottomRight = this.findOne('.bottom-right')!; - var topOffsetX = topLeft.x(); - var topOffsetY = topLeft.y(); + const topLeft = this.findOne('.top-left')!; + const bottomRight = this.findOne('.bottom-right')!; + const topOffsetX = topLeft.x(); + const topOffsetY = topLeft.y(); - var bottomOffsetX = this.getWidth() - bottomRight.x(); - var bottomOffsetY = this.getHeight() - bottomRight.y(); + const bottomOffsetX = this.getWidth() - bottomRight.x(); + const bottomOffsetY = this.getHeight() - bottomRight.y(); bottomRight.move({ x: -topOffsetX, @@ -927,15 +927,15 @@ export class Transformer extends Group { }); } - var absPos = this.findOne('.top-left')!.getAbsolutePosition(); + const absPos = this.findOne('.top-left')!.getAbsolutePosition(); x = absPos.x; y = absPos.y; - var width = + const width = this.findOne('.bottom-right')!.x() - this.findOne('.top-left')!.x(); - var height = + const height = this.findOne('.bottom-right')!.y() - this.findOne('.top-left')!.y(); this._fitNodesInto( @@ -964,7 +964,7 @@ export class Transformer extends Group { window.removeEventListener('mouseup', this._handleMouseUp, true); window.removeEventListener('touchend', this._handleMouseUp, true); } - var node = this.getNode(); + const node = this.getNode(); activeTransformersCount--; this._fire('transformend', { evt: e, target: node }); // redraw layer to restore hit graph @@ -981,7 +981,7 @@ export class Transformer extends Group { } } _fitNodesInto(newAttrs, evt?) { - var oldAttrs = this._getNodeRect(); + const oldAttrs = this._getNodeRect(); const minSize = 1; @@ -996,7 +996,7 @@ export class Transformer extends Group { return; } - var t = new Transform(); + const t = new Transform(); t.rotate(Konva.getAngle(this.rotation())); if ( this._movingAnchorName && @@ -1153,16 +1153,16 @@ export class Transformer extends Group { } update() { - var attrs = this._getNodeRect(); + const attrs = this._getNodeRect(); this.rotation(Util._getRotation(attrs.rotation)); - var width = attrs.width; - var height = attrs.height; + const width = attrs.width; + const height = attrs.height; - var enabledAnchors = this.enabledAnchors(); - var resizeEnabled = this.resizeEnabled(); - var padding = this.padding(); + const enabledAnchors = this.enabledAnchors(); + const resizeEnabled = this.resizeEnabled(); + const padding = this.padding(); - var anchorSize = this.anchorSize(); + const anchorSize = this.anchorSize(); const anchors = this.find('._anchor'); anchors.forEach((node) => { node.setAttrs({ @@ -1273,7 +1273,7 @@ export class Transformer extends Group { stopTransform() { if (this._transforming) { this._removeEvents(); - var anchorNode = this.findOne('.' + this._movingAnchorName); + const anchorNode = this.findOne('.' + this._movingAnchorName); if (anchorNode) { anchorNode.stopDrag(); } @@ -1296,7 +1296,7 @@ export class Transformer extends Group { // overwrite clone to NOT use method from Container clone(obj?: any) { - var node = Node.prototype.clone.call(this, obj); + const node = Node.prototype.clone.call(this, obj); return node as this; } getClientRect() { diff --git a/test/sandbox.html b/test/sandbox.html index a1d11e272..2b17ce672 100644 --- a/test/sandbox.html +++ b/test/sandbox.html @@ -44,28 +44,27 @@ var layer = new Konva.Layer(); stage.add(layer); - var text = new Konva.Text({ + var rect = new Konva.Rect({ x: 10, y: 10, - text: 'Simple Text', - fontSize: 100, - fontFamily: 'Calibri', + width: 100, + height: 100, fill: 'green', - textDecoration: 'underline line-through', draggable: true, }); - layer.add(text); + layer.add(rect); - var tr = new Konva.Transformer({ - nodes: [text], + window.addEventListener('touchend', () => { + console.log('touchend'); }); - layer.add(tr); - - tr.on('transformstart', () => { - console.log('transform start'); + window.addEventListener('touchcancel', () => { + console.log('touchcancel'); + }); + window.addEventListener('lostpointercapture', () => { + console.log('lostpointercapture'); }); - tr.on('transformend', () => { - console.log('transform end'); + window.addEventListener('focusout', () => { + console.log('focusout'); }); diff --git a/test/unit/Text-test.ts b/test/unit/Text-test.ts index 0c84ccd19..8d9bb850b 100644 --- a/test/unit/Text-test.ts +++ b/test/unit/Text-test.ts @@ -741,7 +741,7 @@ describe('Text', function () { }); // ====================================================== - it('text multi line with justify align and decoration', function () { + it.only('text multi line with justify align and decoration', function () { var stage = addStage(); var layer = new Konva.Layer(); @@ -764,7 +764,7 @@ describe('Text', function () { width: 380, align: 'justify', letterSpacing: 5, - textDecoration: 'underline', + textDecoration: 'underline line-through', padding: 20, draggable: true, }); @@ -780,7 +780,7 @@ describe('Text', function () { } var trace = - 'fillText(c,69.696,77);fillStyle=#555;fillText(e,81.696,77);fillStyle=#555;fillText(s,94.482,77);fillStyle=#555;fillText(;,106.482,77);fillStyle=#555;fillText( ,117.549,77);fillStyle=#555;fillText(A,126.438,77);fillStyle=#555;fillText(n,140.776,77);fillStyle=#555;fillText(d,153.563,77);fillStyle=#555;fillText( ,168.525,77);fillStyle=#555;fillText(o,177.415,77);fillStyle=#555;fillText(n,190.201,77);fillStyle=#555;fillText(e,202.987,77);fillStyle=#555;fillText( ,217.95,77);fillStyle=#555;fillText(m,226.84,77);fillStyle=#555;fillText(a,243.502,77);fillStyle=#555;fillText(n,256.288,77);fillStyle=#555;fillText( ,271.251,77);fillStyle=#555;fillText(i,280.141,77);fillStyle=#555;fillText(n,288.251,77);fillStyle=#555;fillText( ,303.214,77);fillStyle=#555;fillText(h,312.104,77);fillStyle=#555;fillText(i,324.89,77);fillStyle=#555;fillText(s,333,77);restore();save();save();beginPath();moveTo(0,98);lineTo(245,98);stroke();restore();fillStyle=#555;fillText(t,0,91);fillStyle=#555;fillText(i,8.89,91);fillStyle=#555;fillText(m,17,91);fillStyle=#555;fillText(e,33.662,91);fillStyle=#555;fillText( ,46.448,91);fillStyle=#555;fillText(p,55.338,91);fillStyle=#555;fillText(l,68.124,91);fillStyle=#555;fillText(a,76.234,91);fillStyle=#555;fillText(y,89.021,91);fillStyle=#555;fillText(s,101.021,91);fillStyle=#555;fillText( ,113.021,91);fillStyle=#555;fillText(m,121.91,91);fillStyle=#555;fillText(a,138.572,91);fillStyle=#555;fillText(n,151.358,91);fillStyle=#555;fillText(y,164.145,91);fillStyle=#555;fillText( ,176.145,91);fillStyle=#555;fillText(p,185.034,91);fillStyle=#555;fillText(a,197.82,91);fillStyle=#555;fillText(r,210.606,91);fillStyle=#555;fillText(t,220.269,91);fillStyle=#555;fillText(s,229.158,91);fillStyle=#555;fillText(.,241.158,91);restore();restore();'; + 'fillText(;,106.482,77);fillStyle=#555;fillText( ,117.549,77);fillStyle=#555;fillText(A,126.438,77);fillStyle=#555;fillText(n,140.776,77);fillStyle=#555;fillText(d,153.563,77);fillStyle=#555;fillText( ,168.525,77);fillStyle=#555;fillText(o,177.415,77);fillStyle=#555;fillText(n,190.201,77);fillStyle=#555;fillText(e,202.987,77);fillStyle=#555;fillText( ,217.95,77);fillStyle=#555;fillText(m,226.84,77);fillStyle=#555;fillText(a,243.502,77);fillStyle=#555;fillText(n,256.288,77);fillStyle=#555;fillText( ,271.251,77);fillStyle=#555;fillText(i,280.141,77);fillStyle=#555;fillText(n,288.251,77);fillStyle=#555;fillText( ,303.214,77);fillStyle=#555;fillText(h,312.104,77);fillStyle=#555;fillText(i,324.89,77);fillStyle=#555;fillText(s,333,77);restore();save();save();beginPath();moveTo(0,98);lineTo(245,98);stroke();restore();save();beginPath();moveTo(0,91);lineTo(245,91);stroke();restore();fillStyle=#555;fillText(t,0,91);fillStyle=#555;fillText(i,8.89,91);fillStyle=#555;fillText(m,17,91);fillStyle=#555;fillText(e,33.662,91);fillStyle=#555;fillText( ,46.448,91);fillStyle=#555;fillText(p,55.338,91);fillStyle=#555;fillText(l,68.124,91);fillStyle=#555;fillText(a,76.234,91);fillStyle=#555;fillText(y,89.021,91);fillStyle=#555;fillText(s,101.021,91);fillStyle=#555;fillText( ,113.021,91);fillStyle=#555;fillText(m,121.91,91);fillStyle=#555;fillText(a,138.572,91);fillStyle=#555;fillText(n,151.358,91);fillStyle=#555;fillText(y,164.145,91);fillStyle=#555;fillText( ,176.145,91);fillStyle=#555;fillText(p,185.034,91);fillStyle=#555;fillText(a,197.82,91);fillStyle=#555;fillText(r,210.606,91);fillStyle=#555;fillText(t,220.269,91);fillStyle=#555;fillText(s,229.158,91);fillStyle=#555;fillText(.,241.158,91);restore();restore();'; assert.equal(layer.getContext().getTrace(), trace); }); diff --git a/tsconfig.json b/tsconfig.json index da4622615..0312b5cc1 100644 --- a/tsconfig.json +++ b/tsconfig.json @@ -5,7 +5,7 @@ "target": "ES2018", // "sourceMap": true, "noEmitOnError": true, - "lib": ["ES2015", "dom"], + "lib": ["ES2019", "dom"], "moduleResolution": "node", "declaration": true, "removeComments": false,