diff --git a/ISSUE_TEMPLATE.md b/.github/ISSUE_TEMPLATE.md similarity index 100% rename from ISSUE_TEMPLATE.md rename to .github/ISSUE_TEMPLATE.md diff --git a/.gitignore b/.gitignore index 32da2d56..023152ef 100644 --- a/.gitignore +++ b/.gitignore @@ -1,4 +1,7 @@ dist +es +.parcel-cache +test-build documentation analysis node_modules diff --git a/CHANGELOG.md b/CHANGELOG.md index 56b73c3f..50e2bcfa 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -3,390 +3,390 @@ All notable changes to this project will be documented in this file. This project adheres to [Semantic Versioning](http://semver.org/). +- Fix `TextPath` recalculations on `fontSize` change + ## 7.2.5 -* Fix transform update on `letterSpacing` change of `Konva.Text` +- Fix transform update on `letterSpacing` change of `Konva.Text` ## 7.2.4 -* Fix wrong `mouseleave` trigger for `Konva.Stage` +- Fix wrong `mouseleave` trigger for `Konva.Stage` ## 7.2.3 -* Fix transformer rotation when parent of a node is rotated too. +- Fix transformer rotation when parent of a node is rotated too. ## 7.2.2 -* Fix wrong size calculations for `Konva.Line` with tension -* Fix `shape.intersects()` behavior when a node is dragged -* Fix ellipsis rendering for `Konva.Text` +- Fix wrong size calculations for `Konva.Line` with tension +- Fix `shape.intersects()` behavior when a node is dragged +- Fix ellipsis rendering for `Konva.Text` ## 7.2.1 -* Fix correct rendering of `Konva.Label` when heigh of text is changed -* Fix correct `transformstart` and `transformend` events when several nodes are attached with `Konva.Transformer` +- Fix correct rendering of `Konva.Label` when heigh of text is changed +- Fix correct `transformstart` and `transformend` events when several nodes are attached with `Konva.Transformer` ## 7.2.0 -* New property `fillAfterStrokeEnabled` for `Konva.Shape`. See API docs for more information. -* Fix for `Konva.Transformer` when it may fail to draw. -* Fix rendering of `TextPath` one more time. +- New property `fillAfterStrokeEnabled` for `Konva.Shape`. See API docs for more information. +- Fix for `Konva.Transformer` when it may fail to draw. +- Fix rendering of `TextPath` one more time. ## 7.1.9 -* Fix autodrawing for `Konva.Transformer` when it is on a different layer -* Fix `Konva.RegularPolygon` size calculations. +- Fix autodrawing for `Konva.Transformer` when it is on a different layer +- Fix `Konva.RegularPolygon` size calculations. ## 7.1.8 -* Fix incorrect rendering of `TextPath` in some cases. (again) +- Fix incorrect rendering of `TextPath` in some cases. (again) ## 7.1.7 -* Fix incorrect rendering of `TextPath` in some cases. +- Fix incorrect rendering of `TextPath` in some cases. ## 7.1.6 -* Fix for correct image/dataURL/canvas exports for `Konva.Stage`. +- Fix for correct image/dataURL/canvas exports for `Konva.Stage`. ## 7.1.5 -* Performance fixes for dragging many nodes with `Konva.Transformer`. -* Documentation updates +- Performance fixes for dragging many nodes with `Konva.Transformer`. +- Documentation updates ## 7.1.4 -* Perf fixes -* Change events trigger flow, so adding new events INSIDE event callback will work correctly. -* Fix double `dragend`, `dragstart`, `dragmove` triggers on `Konva.Transformer` +- Perf fixes +- Change events trigger flow, so adding new events INSIDE event callback will work correctly. +- Fix double `dragend`, `dragstart`, `dragmove` triggers on `Konva.Transformer` ## 7.1.3 -* Text rendering fixes +- Text rendering fixes ## 7.1.2 -* fix ellipses behavior for `Konva.Text`. -* fix scaled fill pattern for text. +- fix ellipses behavior for `Konva.Text`. +- fix scaled fill pattern for text. ## 7.1.1 -* fixes for `dragstart` event when `Konva.Transformer` is used. `dragstart` event will have correct native `evt` reference -* Better unicode support in `Konva.Text` and `Konva.TextPath`. Emoji should work better now 👍 +- fixes for `dragstart` event when `Konva.Transformer` is used. `dragstart` event will have correct native `evt` reference +- Better unicode support in `Konva.Text` and `Konva.TextPath`. Emoji should work better now 👍 ## 7.1.0 -* Multi row support for `ellipsis` config for `Konva.Text` -* Better `Konva.Transfomer` behavior when single attached node is programmatically rotated. +- Multi row support for `ellipsis` config for `Konva.Text` +- Better `Konva.Transfomer` behavior when single attached node is programmatically rotated. ## 7.0.7 -* fixes for `dragstart` event when `Konva.Transformer` is used. `dragstart` will not bubble from transformer. -* `string` and `fill` properties validation can accept `CanvasGradient` as valid value +- fixes for `dragstart` event when `Konva.Transformer` is used. `dragstart` will not bubble from transformer. +- `string` and `fill` properties validation can accept `CanvasGradient` as valid value ## 7.0.6 -* Better performance for stage dragging +- Better performance for stage dragging ## 7.0.5 -* Fixes for `node.cache()` function. +- Fixes for `node.cache()` function. ## 7.0.4 -* Add `onUpdate` callbacks to `Konva.Tween` configuration and `node.to()` method. -* Up to 6x faster initializations of objects, like `const shape = new Konva.Shape()`. +- Add `onUpdate` callbacks to `Konva.Tween` configuration and `node.to()` method. +- Up to 6x faster initializations of objects, like `const shape = new Konva.Shape()`. ## 7.0.3 - 2020-07-09 -* Fix wring `dragend` trigger on `draggable` property change inside `click` -* Fix incorrect text rendering with `letterSpacing !== 0` -* Typescript fixes +- Fix wring `dragend` trigger on `draggable` property change inside `click` +- Fix incorrect text rendering with `letterSpacing !== 0` +- Typescript fixes ## 7.0.2 - 2020-06-30 -* Fix wrong trigger `dbltap` and `click` on mobile +- Fix wrong trigger `dbltap` and `click` on mobile ## 7.0.1 - 2020-06-29 -* Fixes for different font families support. -* Fixes for `Konva.Transformer` positions -* Types fixes for better Typescript support - +- Fixes for different font families support. +- Fixes for `Konva.Transformer` positions +- Types fixes for better Typescript support ## 7.0.0 - 2020-06-23 -* **BREAKING** `inherit` option is removed from `visible` and `listening`. They now just have boolean values `true` or `false`. If you do `group.listening(false);` then whole group and all its children will be removed from the hitGraph (and they will not listen to events). Probably 99% `Konva` applications will be not affected by this *breaking change*. -* **Many performance fixes and code size optimizations. Up to 70% performance boost for many moving nodes.** -* `layer.hitGraphEnabled()` is deprecated. Just use `layer.listening(false)` instead -* Better support for font families with spaces inside (like `Font Awesome 5`). -* Fix wrong `dblclick` and `dbltap` triggers -* Deprecate `Konva.FastLayer`. Use `new Konva.Layer({ listening: false });` instead. -* `dragmove` event will be fired on `Konva.Transformer` too when you drag a node. -* `dragmove` triggers only after ALL positions of dragging nodes are changed - +- **BREAKING** `inherit` option is removed from `visible` and `listening`. They now just have boolean values `true` or `false`. If you do `group.listening(false);` then whole group and all its children will be removed from the hitGraph (and they will not listen to events). Probably 99% `Konva` applications will be not affected by this _breaking change_. +- **Many performance fixes and code size optimizations. Up to 70% performance boost for many moving nodes.** +- `layer.hitGraphEnabled()` is deprecated. Just use `layer.listening(false)` instead +- Better support for font families with spaces inside (like `Font Awesome 5`). +- Fix wrong `dblclick` and `dbltap` triggers +- Deprecate `Konva.FastLayer`. Use `new Konva.Layer({ listening: false });` instead. +- `dragmove` event will be fired on `Konva.Transformer` too when you drag a node. +- `dragmove` triggers only after ALL positions of dragging nodes are changed ## 6.0.0 - 2020-05-08 -* **BREAKING!** `boundBoxFunc` of `Konva.Transformer` works in absolute coordinates of whole transformer. Previously in was working in local coordinates of transforming node. -* Many `Konva.Transformer` fixes. Now it works correctly when you transform several rotated shapes. -* Fix for wrong `mouseleave` and `mouseout` fire on shape remove/destroy. +- **BREAKING!** `boundBoxFunc` of `Konva.Transformer` works in absolute coordinates of whole transformer. Previously in was working in local coordinates of transforming node. +- Many `Konva.Transformer` fixes. Now it works correctly when you transform several rotated shapes. +- Fix for wrong `mouseleave` and `mouseout` fire on shape remove/destroy. ## 5.0.3 - 2020-05-01 -* Fixes for `boundBoxFunc` of `Konva.Transformer`. +- Fixes for `boundBoxFunc` of `Konva.Transformer`. ## 5.0.2 - 2020-04-23 -* Deatach fixes for `Konva.Transformer` +- Deatach fixes for `Konva.Transformer` ## 5.0.1 - 2020-04-22 -* Fixes for `Konva.Transformer` when parent scale is changed -* Fixes for `Konva.Transformer` when parent is draggable -* Performance optimizations +- Fixes for `Konva.Transformer` when parent scale is changed +- Fixes for `Konva.Transformer` when parent is draggable +- Performance optimizations ## 5.0.0 - 2020-04-21 -* **New `Konva.Transformer` implementation!**. Old API should work. But I marked this release is `major` (breaking) just for smooth updates. Changes: - * Support of transforming multiple nodes at once: `tr.nodes([shape1, shape2])`. - * `tr.node()`, `tr.setNode()`, `tr.attachTo()` methods are deprecated. Use `tr.nodes(array)` instead - * Fixes for center scaling - * Fixes for better `padding` support - * `Transformer` can be placed anywhere in the tree of a stage tree (NOT just inside a parent of attached node). -* Fix `imageSmoothEnabled` resets when stage is resized -* Memory usage optimizations when a node is cached +- **New `Konva.Transformer` implementation!**. Old API should work. But I marked this release is `major` (breaking) just for smooth updates. Changes: + - Support of transforming multiple nodes at once: `tr.nodes([shape1, shape2])`. + - `tr.node()`, `tr.setNode()`, `tr.attachTo()` methods are deprecated. Use `tr.nodes(array)` instead + - Fixes for center scaling + - Fixes for better `padding` support + - `Transformer` can be placed anywhere in the tree of a stage tree (NOT just inside a parent of attached node). +- Fix `imageSmoothEnabled` resets when stage is resized +- Memory usage optimizations when a node is cached ## 4.2.2 - 2020-03-26 -* Fix hit stroke issues +- Fix hit stroke issues ## 4.2.1 - 2020-03-26 -* Fix some issues with `mouseenter` and `mouseleave` events. -* Deprecate `hitStrokeEnabled` property -* Fix rounding issues for `getClientRect()` for some shapes +- Fix some issues with `mouseenter` and `mouseleave` events. +- Deprecate `hitStrokeEnabled` property +- Fix rounding issues for `getClientRect()` for some shapes ## 4.2.0 - 2020-03-14 -* Add `rotationSnapTolerance` property to `Konva.Transformer`. -* Add `getActiveAnchor()` method to `Konva.Transformer` -* Fix hit for non-closed `Konva.Path` -* Some fixes for experimental Offscreen canvas support inside a worker +- Add `rotationSnapTolerance` property to `Konva.Transformer`. +- Add `getActiveAnchor()` method to `Konva.Transformer` +- Fix hit for non-closed `Konva.Path` +- Some fixes for experimental Offscreen canvas support inside a worker ## 4.1.6 - 2020-02-25 -* Events fixes for `Konva.Transformer` -* Now `Konva` will keep `id` in a cloned node -* Better error messages on tainted canvas issues +- Events fixes for `Konva.Transformer` +- Now `Konva` will keep `id` in a cloned node +- Better error messages on tainted canvas issues ## 4.1.5 - 2020-02-16 -* Fixes for `path.getClientRect()` function calculations +- Fixes for `path.getClientRect()` function calculations ## 4.1.4 - 2020-02-10 -* Fix wrong internal caching of absolute attributes -* Fix `Konva.Transformer` behavior on scaled with CSS stage +- Fix wrong internal caching of absolute attributes +- Fix `Konva.Transformer` behavior on scaled with CSS stage ## 4.1.3 - 2020-01-30 -* Fix line with tension calculations -* Add `node.getAbsoluteRotation()` method -* Fix cursor on anchors for rotated parent +- Fix line with tension calculations +- Add `node.getAbsoluteRotation()` method +- Fix cursor on anchors for rotated parent ## 4.1.2 - 2020-01-08 -* Fix possible `NaN` in content calculations +- Fix possible `NaN` in content calculations ## 4.1.1 - 2020-01-07 -* Add ability to use `width = 0` and `height = 0` for `Konva.Image`. -* Fix `cache()` method of `Konva.Arrow()` -* Add `Transform` to `Konva` default exports. So `Konva.Transform` is available now. +- Add ability to use `width = 0` and `height = 0` for `Konva.Image`. +- Fix `cache()` method of `Konva.Arrow()` +- Add `Transform` to `Konva` default exports. So `Konva.Transform` is available now. ## 4.1.0 - 2019-12-23 -* Make events work on some CSS transforms -* Fix caching on float dimensions -* Fix `mouseleave` event on stage. -* Increase default anchor size for `Konva.Transformer` on touch devices +- Make events work on some CSS transforms +- Fix caching on float dimensions +- Fix `mouseleave` event on stage. +- Increase default anchor size for `Konva.Transformer` on touch devices ## 4.0.18 - 2019-11-20 -* Fix `path.getClientRect()` calculations for `Konva.Path` -* Fix wrong fire of `click` and `tap` events on stopped drag events. +- Fix `path.getClientRect()` calculations for `Konva.Path` +- Fix wrong fire of `click` and `tap` events on stopped drag events. ## 4.0.17 - 2019-11-08 -* Allow hitStrokeWidth usage, even if a shape has not stroke visible -* Better IE11 support +- Allow hitStrokeWidth usage, even if a shape has not stroke visible +- Better IE11 support ## 4.0.16 - 2019-10-21 -* Warn on undefined return value of `dragBoundFunc`. -* Better calculations for `container.getClientRect()` +- Warn on undefined return value of `dragBoundFunc`. +- Better calculations for `container.getClientRect()` ## 4.0.15 - 2019-10-15 -* TS fixes -* Better calculations for `TextPath` with align = right -* Better `textPath.getClientRect()` +- TS fixes +- Better calculations for `TextPath` with align = right +- Better `textPath.getClientRect()` ## 4.0.14 - 2019-10-11 -* TS fixes -* Fix globalCompositeOperation + cached hit detections. -* Fix absolute position calculations for cached parent +- TS fixes +- Fix globalCompositeOperation + cached hit detections. +- Fix absolute position calculations for cached parent ## 4.0.13 - 2019-10-02 -* Fix `line.getClientRect()` calculations for line with a tension or low number of points +- Fix `line.getClientRect()` calculations for line with a tension or low number of points ## 4.0.12 - 2019-09-17 -* Fix some bugs when `Konva.Transformer` has `padding > 0` +- Fix some bugs when `Konva.Transformer` has `padding > 0` ## 4.0.10 - 2019-09-10 -* Fix drag position handling -* Fix multiple selector for find() method +- Fix drag position handling +- Fix multiple selector for find() method ## 4.0.9 - 2019-09-06 -* Fix `Konva.Transformer` behavior on mirrored nodes -* Fix `stage.getPointerPosition()` logic. +- Fix `Konva.Transformer` behavior on mirrored nodes +- Fix `stage.getPointerPosition()` logic. -## 4.0.8 - 2019-09-05 +## 4.0.8 - 2019-09-05 -* Fix `dragend` event on click -* Revert fillPatternScale for text fix. +- Fix `dragend` event on click +- Revert fillPatternScale for text fix. -## 4.0.7 - 2019-09-03 +## 4.0.7 - 2019-09-03 -* Fixed evt object on `dragstart` -* Fixed double tap trigger after dragging +- Fixed evt object on `dragstart` +- Fixed double tap trigger after dragging -## 4.0.6 - 2019-08-31 +## 4.0.6 - 2019-08-31 -* Fix fillPatternScale for text +- Fix fillPatternScale for text -## 4.0.5 - 2019-08-17 +## 4.0.5 - 2019-08-17 -* Fix `dragstart` flow when `node.startDrag()` is called. -* Fix `tap` and `dbltap` double trigger on stage +- Fix `dragstart` flow when `node.startDrag()` is called. +- Fix `tap` and `dbltap` double trigger on stage -## 4.0.4 - 2019-08-12 +## 4.0.4 - 2019-08-12 -* Add `node.isCached()` method -* Fix nested dragging bug +- Add `node.isCached()` method +- Fix nested dragging bug -## 4.0.3 - 2019-08-08 +## 4.0.3 - 2019-08-08 -* Slightly changed `mousemove` event flow. It triggers for first `mouseover` event too -* Better `Konva.hitOnDragEnabled` support for mouse inputs +- Slightly changed `mousemove` event flow. It triggers for first `mouseover` event too +- Better `Konva.hitOnDragEnabled` support for mouse inputs -## 4.0.2 - 2019-08-08 +## 4.0.2 - 2019-08-08 -* Fixed `node.startDrag()` behavior. We can call it at any time. +- Fixed `node.startDrag()` behavior. We can call it at any time. -## 4.0.1 - 2019-08-07 +## 4.0.1 - 2019-08-07 -* Better `Konva.Arrow` + tension drawing -* Typescript fixes +- Better `Konva.Arrow` + tension drawing +- Typescript fixes -## 4.0.0 - 2019-08-05 +## 4.0.0 - 2019-08-05 Basically the release doesn't have any breaking changes. You may only have issues if you are using something from `Konva.DD` object (which is private and never documented). Otherwise you should be fine. `Konva` has major upgrade about touch events system and drag&drop flow. The API is exactly the same. But the internal refactoring is huge so I decided to make a major version. Please upgrade carefully. Report about any issues you have. -* Better multi-touch support. Now we can trigger several `touch` events on one or many nodes. -* New drag&drop implementation. You can drag several shapes at once with several pointers. -* HSL colors support +- Better multi-touch support. Now we can trigger several `touch` events on one or many nodes. +- New drag&drop implementation. You can drag several shapes at once with several pointers. +- HSL colors support -## 3.4.1 - 2019-07-18 +## 3.4.1 - 2019-07-18 -* Fix wrong double tap trigger +- Fix wrong double tap trigger -## 3.4.0 - 2019-07-12 +## 3.4.0 - 2019-07-12 -* TS types fixes -* Added support for different values for `cornerRadius` of `Konva.Rect` +- TS types fixes +- Added support for different values for `cornerRadius` of `Konva.Rect` -## 3.3.3 - 2019-06-07 +## 3.3.3 - 2019-06-07 -* Some fixes for better support `konva-node` -* TS types fixes +- Some fixes for better support `konva-node` +- TS types fixes -## 3.3.2 - 2019-06-03 +## 3.3.2 - 2019-06-03 -* TS types fixes +- TS types fixes -## 3.3.1 - 2019-05-28 +## 3.3.1 - 2019-05-28 -* Add new property `imageSmoothingEnabled` to the node caching -* Even more ts fixes. Typescript need a lot of attention, you know... +- Add new property `imageSmoothingEnabled` to the node caching +- Even more ts fixes. Typescript need a lot of attention, you know... -## 3.3.0 - 2019-05-28 +## 3.3.0 - 2019-05-28 -* Enable strict mode for ts types -* Add new property `imageSmoothingEnabled` to the layer +- Enable strict mode for ts types +- Add new property `imageSmoothingEnabled` to the layer -## 3.2.7 - 2019-05-27 +## 3.2.7 - 2019-05-27 -* Typescript fixes -* Experimental pointer events support. Do `Konva._pointerEventsEnabled = true;` to enable -* Fix some `Konva.Transformer` bugs. +- Typescript fixes +- Experimental pointer events support. Do `Konva._pointerEventsEnabled = true;` to enable +- Fix some `Konva.Transformer` bugs. -## 3.2.6 - 2019-05-09 +## 3.2.6 - 2019-05-09 -* Typescript fixes again +- Typescript fixes again -## 3.2.5 - 2019-04-17 +## 3.2.5 - 2019-04-17 -* Show a warning when `Konva.Transformer` and attaching node have different parents. -* Typescript fixes +- Show a warning when `Konva.Transformer` and attaching node have different parents. +- Typescript fixes -## 3.2.4 - 2019-04-05 +## 3.2.4 - 2019-04-05 -* Fix some stage events. `mouseenter` and `mouseleave` should work correctly on empty spaces -* Fix some typescript types -* Better detection of production mode (no extra warnings) +- Fix some stage events. `mouseenter` and `mouseleave` should work correctly on empty spaces +- Fix some typescript types +- Better detection of production mode (no extra warnings) -## 3.2.3 - 2019-03-21 +## 3.2.3 - 2019-03-21 -* Fix `hasName` method for empty name cases +- Fix `hasName` method for empty name cases -## 3.2.2 - 2019-03-19 +## 3.2.2 - 2019-03-19 -* Remove `dependencies` from npm package +- Remove `dependencies` from npm package -## 3.2.1 - 2019-03-18 +## 3.2.1 - 2019-03-18 -* Better `find` and `findOne` lookup. Now we should not care about duplicate ids. -* Better typescript definitions +- Better `find` and `findOne` lookup. Now we should not care about duplicate ids. +- Better typescript definitions -## 3.2.0 - 2019-03-10 +## 3.2.0 - 2019-03-10 -* new property `shape.hitStrokeWidth(10)` -* Better typescript definitions -* Remove `Object.assign` usage (for IE11 support) +- new property `shape.hitStrokeWidth(10)` +- Better typescript definitions +- Remove `Object.assign` usage (for IE11 support) -## 3.1.7 - 2019-03-06 +## 3.1.7 - 2019-03-06 -* Better modules and TS types +- Better modules and TS types -## 3.1.6 - 2019-02-27 +## 3.1.6 - 2019-02-27 -* Fix commonjs exports -* Fix global injections +- Fix commonjs exports +- Fix global injections -## 3.1.0 - 2019-02-27 +## 3.1.0 - 2019-02-27 -* Make `Konva` modular: `import Konva from 'konva/lib/Core';`; -* Fix incorrect `Transformer` behavior -* Fix drag&drop for touch devices +- Make `Konva` modular: `import Konva from 'konva/lib/Core';`; +- Fix incorrect `Transformer` behavior +- Fix drag&drop for touch devices -## 3.0.0 - 2019-02-25 +## 3.0.0 - 2019-02-25 ## Breaking @@ -397,667 +397,667 @@ This feature will be added back later. That changes are private and internal specific. They should not break most of `Konva` apps. -* `Konva.Util.addMethods` is removed -* `Konva.Util._removeLastLetter` is removed -* `Konva.Util._getImage` is removed -* `Konv.Util._getRGBAString` is removed -* `Konv.Util._merge` is removed -* Removed polyfill for `requestAnimationFrame`. -* `id` and `name` properties defaults are empty strings, not `undefined` -* internal `_cache` property was updated to use es2015 `Map` instead of `{}`. -* `Konva.Validators` is removed. - - -### Added -* Show a warning when a stage has too many layers -* Show a warning on duplicate ids -* Show a warning on weird class in `Node.create` parsing from JSON -* Show a warning for incorrect value for component setters. -* Show a warning for incorrect value for `zIndex` property. -* Show a warning when user is trying to reuse destroyed shape. -* new publish method `measureSize(string)` for `Konva.Text` -* You can configure what mouse buttons can be used for drag&drop. To enable right button you can use `Konva.dragButtons = [0, 1]`. -* Now you can hide stage `stage.visible(false)`. It will set its container display style to "none". -* New method `stage.setPointersPositions(event)`. Usually you don't need to use it manually. -* New method `layer.toggleHitCanvas()` to show and debug hit areas - -### Changed -* Full rewrite to Typescript with tons of refactoring and small optimizations. The public API should be 100% the same -* Fixed `patternImage` and `radialGradient` for `Konva.Text` -* `Konva.Util._isObject` is renamed to `Konva.Util._isPlainObject`. -* A bit changed behavior of `removeId` (private method), now it doesn't clear node ref, if object is changed. -* simplified `batchDraw` method (it doesn't use `Konva.Animation`) now. -* Performance improvements for shapes will image patterns, linear and radial fills -* `text.getTextHeight()` is deprecated. Use `text.height()` or `text.fontSize()` instead. -* Private method `stage._setPointerPosition()` is deprecated. Use `stage.setPointersPositions(event)`; - -### Fixed - -* Better mouse support on mobile devices (yes, that is possible to connect mouse to mobile) -* Better implementation of `mouseover` event for stage -* Fixed underline drawing for text with `lineHeight !== 1` -* Fixed some caching behavior when a node has `globalCompositeOperation`. -* Fixed automatic updates for `Konva.Transformer` -* Fixed container change for a stage. -* Fixed warning for `width` and `height` attributes for `Konva.Text` -* Fixed gradient drawing for `Konva.Text` -* Fixed rendering with `strokeWidth = 0` - -## 2.6.0 - 2018-12-14 - -### Changed - -* Performance fixes when cached node has many children -* Better drawing for shape with `strokeScaleEnabled = false` on HDPI devices +- `Konva.Util.addMethods` is removed +- `Konva.Util._removeLastLetter` is removed +- `Konva.Util._getImage` is removed +- `Konv.Util._getRGBAString` is removed +- `Konv.Util._merge` is removed +- Removed polyfill for `requestAnimationFrame`. +- `id` and `name` properties defaults are empty strings, not `undefined` +- internal `_cache` property was updated to use es2015 `Map` instead of `{}`. +- `Konva.Validators` is removed. ### Added -* New `ignoreStroke` for `Konva.Transformer`. Good to use when a shape has `strokeScaleEnabled = false` +- Show a warning when a stage has too many layers +- Show a warning on duplicate ids +- Show a warning on weird class in `Node.create` parsing from JSON +- Show a warning for incorrect value for component setters. +- Show a warning for incorrect value for `zIndex` property. +- Show a warning when user is trying to reuse destroyed shape. +- new publish method `measureSize(string)` for `Konva.Text` +- You can configure what mouse buttons can be used for drag&drop. To enable right button you can use `Konva.dragButtons = [0, 1]`. +- Now you can hide stage `stage.visible(false)`. It will set its container display style to "none". +- New method `stage.setPointersPositions(event)`. Usually you don't need to use it manually. +- New method `layer.toggleHitCanvas()` to show and debug hit areas ### Changed -* `getKerning` TextPath API is deprecated. Use `kerningFunc` instead. +- Full rewrite to Typescript with tons of refactoring and small optimizations. The public API should be 100% the same +- Fixed `patternImage` and `radialGradient` for `Konva.Text` +- `Konva.Util._isObject` is renamed to `Konva.Util._isPlainObject`. +- A bit changed behavior of `removeId` (private method), now it doesn't clear node ref, if object is changed. +- simplified `batchDraw` method (it doesn't use `Konva.Animation`) now. +- Performance improvements for shapes will image patterns, linear and radial fills +- `text.getTextHeight()` is deprecated. Use `text.height()` or `text.fontSize()` instead. +- Private method `stage._setPointerPosition()` is deprecated. Use `stage.setPointersPositions(event)`; -## 2.5.1 - 2018-11-08 +### Fixed + +- Better mouse support on mobile devices (yes, that is possible to connect mouse to mobile) +- Better implementation of `mouseover` event for stage +- Fixed underline drawing for text with `lineHeight !== 1` +- Fixed some caching behavior when a node has `globalCompositeOperation`. +- Fixed automatic updates for `Konva.Transformer` +- Fixed container change for a stage. +- Fixed warning for `width` and `height` attributes for `Konva.Text` +- Fixed gradient drawing for `Konva.Text` +- Fixed rendering with `strokeWidth = 0` + +## 2.6.0 - 2018-12-14 ### Changed -* Use custom functions for `trimRight` and `trimLeft` (for better browsers support) - -## 2.5.0 - 2018-10-24 +- Performance fixes when cached node has many children +- Better drawing for shape with `strokeScaleEnabled = false` on HDPI devices ### Added -* New `anchorCornerRadius` for `Konva.Transformer` - -### Fixed - -* Performance fixes for caching +- New `ignoreStroke` for `Konva.Transformer`. Good to use when a shape has `strokeScaleEnabled = false` ### Changed -* `dragstart` event behavior is a bit changed. It will fire BEFORE actual position of a node is changed. +- `getKerning` TextPath API is deprecated. Use `kerningFunc` instead. -## 2.4.2 - 2018-10-12 - -### Fixed - -* Fixed a wrong cache when a shape inside group has `listening = false` - -## 2.4.1 - 2018-10-08 +## 2.5.1 - 2018-11-08 ### Changed -* Added some text trim logic to wrap in better +- Use custom functions for `trimRight` and `trimLeft` (for better browsers support) -### Fixed - -* `getClientRect` for complex paths fixes -* `getClientRect` calculation fix for groups -* Update `Konva.Transformer` on `rotateEnabled` change -* Fix click stage event on dragend -* Fix some Transformer cursor behavior - -## 2.4.0 - 2018-09-19 +## 2.5.0 - 2018-10-24 ### Added -* Centered resize with ALT key for `Konva.Transformer` -* New `centeredScaling` for `Konva.Transformer` +- New `anchorCornerRadius` for `Konva.Transformer` ### Fixed -* Tween support for gradient properties -* Add `user-select: none` to the stage container to fix some "selected contend around" issues - - -## 2.3.0 - 2018-08-30 - -### Added - -* new methods `path.getLength()` and `path.getPointAtLength(val)` -* `verticalAlign` for `Konva.Text` - -## 2.2.2 - 2018-08-21 +- Performance fixes for caching ### Changed -* Default duration for tweens and `node.to()` methods is now 300ms -* Typescript fixes -* Automatic validations for many attributes +- `dragstart` event behavior is a bit changed. It will fire BEFORE actual position of a node is changed. -## 2.2.1 - 2018-08-10 +## 2.4.2 - 2018-10-12 -### Added +### Fixed -* New properties for `Konva.Transformer`: `borderStroke`, `borderStrokeWidth`, `borderDash`, `anchorStroke`, `anchorStrokeWidth`, `anchorSize`. +- Fixed a wrong cache when a shape inside group has `listening = false` + +## 2.4.1 - 2018-10-08 ### Changed -* Some properties of `Konva.Transformer` are renamed. `lineEnabled` -> `borderEnabled`. `rotateHandlerOffset` -> `rotateAnchorOffset`, `enabledHandlers` -> `enabledAnchors`. - -## 2.1.8 - 2018-08-01 +- Added some text trim logic to wrap in better ### Fixed -* Some `Konva.Transformer` fixes -* Typescript fixes -* `stage.toDataURL()` fixes when it has hidden layers -* `shape.toDataURL()` automatically adjust position and size of resulted image +- `getClientRect` for complex paths fixes +- `getClientRect` calculation fix for groups +- Update `Konva.Transformer` on `rotateEnabled` change +- Fix click stage event on dragend +- Fix some Transformer cursor behavior -## 2.1.7 - 2018-07-03 - -### Fixed - -* `toObject` fixes - -## 2.1.7 - 2018-07-03 - -### Fixed - -* Some drag&drop fixes - -## 2.1.6 - 2018-06-16 - -### Fixed - -* Removed wrong dep -* Typescript fixes - -## 2.1.5 - 2018-06-15 - -### Fixed - -* Typescript fixes -* add shape as second argument for `sceneFunc` and `hitFunc` - -## 2.1.4 - 2018-06-15 - -### Fixed - -* Fixed `Konva.Text` justify drawing for a text with decoration -* Added methods `data()`,`setData()` and `getData()` methods to `Konva.TextPath` -* Correct cache reset for `Konva.Transformer` - -## 2.1.3 - 2018-05-17 - -### Fixed - -* `Konva.Transformer` automatically track shape changes -* `Konva.Transformer` works with shapes with offset too - -## 2.1.2 - 2018-05-16 - -### Fixed - -* Cursor fixes for `Konva.Transformer` -* Fixed lineHeight behavior for `Konva.Text` -* Some performance optimizations for `Konva.Text` -* Better wrap algorithm for `Konva.Text` -* fixed `Konva.Arrow` with tension != 0 -* Some fixes for `Konva.Transformer` - -## 2.0.3 - 2018-04-21 +## 2.4.0 - 2018-09-19 ### Added -* Typescript defs for `Konva.Transformer` -* Typescript defs for `globalCompositeOperation` +- Centered resize with ALT key for `Konva.Transformer` +- New `centeredScaling` for `Konva.Transformer` + +### Fixed + +- Tween support for gradient properties +- Add `user-select: none` to the stage container to fix some "selected contend around" issues + +## 2.3.0 - 2018-08-30 + +### Added + +- new methods `path.getLength()` and `path.getPointAtLength(val)` +- `verticalAlign` for `Konva.Text` + +## 2.2.2 - 2018-08-21 + +### Changed + +- Default duration for tweens and `node.to()` methods is now 300ms +- Typescript fixes +- Automatic validations for many attributes + +## 2.2.1 - 2018-08-10 + +### Added + +- New properties for `Konva.Transformer`: `borderStroke`, `borderStrokeWidth`, `borderDash`, `anchorStroke`, `anchorStrokeWidth`, `anchorSize`. + +### Changed + +- Some properties of `Konva.Transformer` are renamed. `lineEnabled` -> `borderEnabled`. `rotateHandlerOffset` -> `rotateAnchorOffset`, `enabledHandlers` -> `enabledAnchors`. + +## 2.1.8 - 2018-08-01 + +### Fixed + +- Some `Konva.Transformer` fixes +- Typescript fixes +- `stage.toDataURL()` fixes when it has hidden layers +- `shape.toDataURL()` automatically adjust position and size of resulted image + +## 2.1.7 - 2018-07-03 + +### Fixed + +- `toObject` fixes + +## 2.1.7 - 2018-07-03 + +### Fixed + +- Some drag&drop fixes + +## 2.1.6 - 2018-06-16 + +### Fixed + +- Removed wrong dep +- Typescript fixes + +## 2.1.5 - 2018-06-15 + +### Fixed + +- Typescript fixes +- add shape as second argument for `sceneFunc` and `hitFunc` + +## 2.1.4 - 2018-06-15 + +### Fixed + +- Fixed `Konva.Text` justify drawing for a text with decoration +- Added methods `data()`,`setData()` and `getData()` methods to `Konva.TextPath` +- Correct cache reset for `Konva.Transformer` + +## 2.1.3 - 2018-05-17 + +### Fixed + +- `Konva.Transformer` automatically track shape changes +- `Konva.Transformer` works with shapes with offset too + +## 2.1.2 - 2018-05-16 + +### Fixed + +- Cursor fixes for `Konva.Transformer` +- Fixed lineHeight behavior for `Konva.Text` +- Some performance optimizations for `Konva.Text` +- Better wrap algorithm for `Konva.Text` +- fixed `Konva.Arrow` with tension != 0 +- Some fixes for `Konva.Transformer` + +## 2.0.3 - 2018-04-21 + +### Added + +- Typescript defs for `Konva.Transformer` +- Typescript defs for `globalCompositeOperation` ## Changes -* Fixed flow for `contextmenu` event. Now it will be triggered on shapes too -* `find()` method for Containers can use a function as a parameter +- Fixed flow for `contextmenu` event. Now it will be triggered on shapes too +- `find()` method for Containers can use a function as a parameter ### Fixed -* some bugs fixes for `group.getClientRect()` -* `Konva.Arrow` will not draw dash for pointers -* setAttr will trigger change event if new value is the same Object -* better behavior of `dblclick` event when you click fast on different shapes -* `stage.toDataURL` will use `pixelRatio = 1` by default. +- some bugs fixes for `group.getClientRect()` +- `Konva.Arrow` will not draw dash for pointers +- setAttr will trigger change event if new value is the same Object +- better behavior of `dblclick` event when you click fast on different shapes +- `stage.toDataURL` will use `pixelRatio = 1` by default. -## 2.0.2 - 2018-03-15 +## 2.0.2 - 2018-03-15 ### Fixed -* Even more bugs fixes for `Konva.Transformer` +- Even more bugs fixes for `Konva.Transformer` -## 2.0.1 - 2018-03-15 +## 2.0.1 - 2018-03-15 ### Fixed -* Several bugs fixes for `Konva.Transformer` +- Several bugs fixes for `Konva.Transformer` -## 2.0.0 - 2018-03-15 +## 2.0.0 - 2018-03-15 ### Added -* new `Konva.Transformer`. It is a special group that allow simple resizing and rotation of a shape. -* Add ability to remove event by callback `node.off('event', callback)`. -* new `Konva.Filters.Contrast`. -* new `Konva.Util.haveIntersection()` to detect simple collusion -* add `Konva.Text.ellipsis` to add '…' to text string if width is fixed and wrap is set to 'none' -* add gradients for strokes +- new `Konva.Transformer`. It is a special group that allow simple resizing and rotation of a shape. +- Add ability to remove event by callback `node.off('event', callback)`. +- new `Konva.Filters.Contrast`. +- new `Konva.Util.haveIntersection()` to detect simple collusion +- add `Konva.Text.ellipsis` to add '…' to text string if width is fixed and wrap is set to 'none' +- add gradients for strokes ## Changed -* stage events are slightly changed. `mousedown`, `click`, `mouseup`, `dblclick`, `touchstart`, `touchend`, `tap`, `dbltap` will be triggered when clicked on empty areas too +- stage events are slightly changed. `mousedown`, `click`, `mouseup`, `dblclick`, `touchstart`, `touchend`, `tap`, `dbltap` will be triggered when clicked on empty areas too ### Fixed -* Some typescript fixes -* Pixelate filter fixes -* Fixes for path data parsing -* Fixed shadow size calculation +- Some typescript fixes +- Pixelate filter fixes +- Fixes for path data parsing +- Fixed shadow size calculation ## Removed -* Some deprecated methods are removed. If previous version was working without deprecation warnings for you, this one will work fine too. +- Some deprecated methods are removed. If previous version was working without deprecation warnings for you, this one will work fine too. -## 1.7.6 - 2017-11-01 +## 1.7.6 - 2017-11-01 ### Fixed -* Some typescript fixes +- Some typescript fixes -## 1.7.4 - 2017-10-30 +## 1.7.4 - 2017-10-30 ### Fixed -* `isBrowser` detection for electron +- `isBrowser` detection for electron -## 1.7.3 - 2017-10-19 +## 1.7.3 - 2017-10-19 ### Changed -* Changing size of a stage will redraw it in synchronous way +- Changing size of a stage will redraw it in synchronous way ### Fixed -* Some fixes special for nodejs +- Some fixes special for nodejs -## 1.7.2 - 2017-10-11 +## 1.7.2 - 2017-10-11 ### Fixed -* Fixed `Konva.document is undefined` +- Fixed `Konva.document is undefined` -## 1.7.1 - 2017-10-11 +## 1.7.1 - 2017-10-11 ### Changed -* Konva for browser env and Konva for nodejs env are separate packages now. You can use `konva-node` for NodeJS env. +- Konva for browser env and Konva for nodejs env are separate packages now. You can use `konva-node` for NodeJS env. -## 1.7.0 - 2017-10-08 +## 1.7.0 - 2017-10-08 ### Fixed -* Several typescript fixes +- Several typescript fixes ### Changed -* Default value for `dragDistance` is changed to 3px. -* Fix rare error throw on drag -* Caching with height = 0 or width = 0 with throw async error. Caching will be ignored. +- Default value for `dragDistance` is changed to 3px. +- Fix rare error throw on drag +- Caching with height = 0 or width = 0 with throw async error. Caching will be ignored. -## 1.6.8 - 2017-08-19 +## 1.6.8 - 2017-08-19 ### Changed -* The `node.getClientRect()` calculation is changed a bit. It is more powerfull and correct. Also it takes parent transform into account. See docs. -* Upgrade nodejs deps +- The `node.getClientRect()` calculation is changed a bit. It is more powerfull and correct. Also it takes parent transform into account. See docs. +- Upgrade nodejs deps -## 1.6.7 - 2017-07-28 +## 1.6.7 - 2017-07-28 ### Fixed -* Fix bug with double trigger wheel in Firefox -* Fix `node.getClientRect()` calculation in a case of Group + invisible child -* Fix dblclick issue https://github.com/konvajs/konva/issues/252 +- Fix bug with double trigger wheel in Firefox +- Fix `node.getClientRect()` calculation in a case of Group + invisible child +- Fix dblclick issue https://github.com/konvajs/konva/issues/252 -## 1.6.3 - 2017-05-24 +## 1.6.3 - 2017-05-24 ### Fixed -* Fixed bug with pointer detection. css 3d transformed stage will not work now. +- Fixed bug with pointer detection. css 3d transformed stage will not work now. -## 1.6.2 - 2017-05-08 +## 1.6.2 - 2017-05-08 ### Fixed -* Fixed bug with automatic shadow for negative scale values +- Fixed bug with automatic shadow for negative scale values -## 1.6.1 - 2017-04-25 +## 1.6.1 - 2017-04-25 ### Fixed -* Fix pointer position detection +- Fix pointer position detection ### Changed -* moved `globalCompositeOperation` property to `Konva.Node` +- moved `globalCompositeOperation` property to `Konva.Node` -## 1.6.0 - 2017-04-21 +## 1.6.0 - 2017-04-21 ### Added -* support of globalCompositeOperation for `Konva.Shape` +- support of globalCompositeOperation for `Konva.Shape` ### Fixed -* getAllIntersections now works ok for Text shapes (https://github.com/konvajs/konva/issues/224) +- getAllIntersections now works ok for Text shapes (https://github.com/konvajs/konva/issues/224) ### Changed -* Konva a bit changed a way to detect pointer position. Now it should be OK to apply css transform on Konva container. https://github.com/konvajs/konva/pull/215 +- Konva a bit changed a way to detect pointer position. Now it should be OK to apply css transform on Konva container. https://github.com/konvajs/konva/pull/215 -## 1.5.0 - 2017-03-20 +## 1.5.0 - 2017-03-20 ### Added -* support for `lineDashOffset` property for `Konva.Shape`. +- support for `lineDashOffset` property for `Konva.Shape`. -## 1.4.0 - 2017-02-07 +## 1.4.0 - 2017-02-07 ## Added -* `textDecoration` of `Konva.Text` now supports `line-through` +- `textDecoration` of `Konva.Text` now supports `line-through` -## 1.3.0 - 2017-01-10 +## 1.3.0 - 2017-01-10 ## Added -* new align value for `Konva.Text` and `Konva.TextPath`: `justify` -* new property for `Konva.Text` and `Konva.TextPath`: `textDecoration`. Right now it sports only '' (no decoration) and 'underline' values. -* new property for `Konva.Text`: `letterSpacing` -* new event `contentContextmenu` for `Konva.Stage` -* `align` support for `Konva.TextPath` -* new method `toCanvas()` for converting a node into canvas element +- new align value for `Konva.Text` and `Konva.TextPath`: `justify` +- new property for `Konva.Text` and `Konva.TextPath`: `textDecoration`. Right now it sports only '' (no decoration) and 'underline' values. +- new property for `Konva.Text`: `letterSpacing` +- new event `contentContextmenu` for `Konva.Stage` +- `align` support for `Konva.TextPath` +- new method `toCanvas()` for converting a node into canvas element ### Changed -* changing a size of `Konva.Stage` will update it in async way (via `batchDraw`). -* `shadowOffset` respect pixel ratio now +- changing a size of `Konva.Stage` will update it in async way (via `batchDraw`). +- `shadowOffset` respect pixel ratio now ### Fixed -* Fixed bug when `Konva.Tag` width was not changing its width dynamically -* Fixed "calling remove() for dragging shape will throw an error" -* Fixed wrong opacity level for cached group with opacity -* More consistent shadows on HDPI screens -* Fixed memory leak for nodes with several names +- Fixed bug when `Konva.Tag` width was not changing its width dynamically +- Fixed "calling remove() for dragging shape will throw an error" +- Fixed wrong opacity level for cached group with opacity +- More consistent shadows on HDPI screens +- Fixed memory leak for nodes with several names -## 1.2.2 - 2016-09-15 +## 1.2.2 - 2016-09-15 ### Fixed -* refresh stage hit and its `dragend` -* `getClientRect` calculations +- refresh stage hit and its `dragend` +- `getClientRect` calculations -## 1.2.0 - 2016-09-15 +## 1.2.0 - 2016-09-15 ## Added -* new properties for `Konva.TextPath`: `letterSpacing` and `textBaseline`. +- new properties for `Konva.TextPath`: `letterSpacing` and `textBaseline`. -## 1.1.4 - 2016-09-13 +## 1.1.4 - 2016-09-13 ### Fixed -* Prevent throwing an error when text property of `Konva.Text` = undefined or null +- Prevent throwing an error when text property of `Konva.Text` = undefined or null -## 1.1.3 - 2016-09-12 +## 1.1.3 - 2016-09-12 ### Changed -* Better hit function for `TextPath`. -* Validation of `Shape` filters. +- Better hit function for `TextPath`. +- Validation of `Shape` filters. -## 1.1.2 - 2016-09-10 +## 1.1.2 - 2016-09-10 ### Fixed -* Fixed "Dragging Group on mobile view throws "missing preventDefault" error" #169 +- Fixed "Dragging Group on mobile view throws "missing preventDefault" error" #169 -## 1.1.1 - 2016-08-30 +## 1.1.1 - 2016-08-30 ### Fixed -* Fixed #166 bug of drag&drop +- Fixed #166 bug of drag&drop -## 1.1.0 - 2016-08-21 +## 1.1.0 - 2016-08-21 ## Added -* new property of `Konva.Shape` - `preventDefault`. +- new property of `Konva.Shape` - `preventDefault`. -## 1.0.3 - 2016-08-14 +## 1.0.3 - 2016-08-14 ### Fixed -* Fixed some typescript definitions +- Fixed some typescript definitions -## 1.0.2 - 2016-07-08 +## 1.0.2 - 2016-07-08 ## Changed -* `Konva.Text` will interpret undefined `width` and `height` as `AUTO` +- `Konva.Text` will interpret undefined `width` and `height` as `AUTO` -## 1.0.1 - 2016-07-05 +## 1.0.1 - 2016-07-05 ### Changed -* you can now unset property by `node.x(undefined)` or `node.setAttr('x', null)` +- you can now unset property by `node.x(undefined)` or `node.setAttr('x', null)` ### Fixed -* Bug fix for case when `touchend` event throws error +- Bug fix for case when `touchend` event throws error -## 1.0.0 - 2016-07-05 +## 1.0.0 - 2016-07-05 ### Fixed -* Bug fix for case when `touchend` event throws error +- Bug fix for case when `touchend` event throws error -## 0.15.0 - 2016-06-18 +## 0.15.0 - 2016-06-18 ## Added -* Custom clip function +- Custom clip function -## 0.14.0 - 2016-06-17 +## 0.14.0 - 2016-06-17 ### Fixed -* fixes in typescript definitions -* fixes for bug with `mouseenter` event on deep nesting case +- fixes in typescript definitions +- fixes for bug with `mouseenter` event on deep nesting case -## 0.13.9 - 2016-05-14 +## 0.13.9 - 2016-05-14 ### Changed -* typescript definition in npm package -* node@5.10.1, canvas@1.3.14, jsdom@8.5.0 support -* `Konva.Path` will be filled when it is not closed -* `Animation.start()` will not not immediate sync draw. This should improve performance a little. -* Warning when node for `Tween` is not in layer yet. -* `removeChildren()` remove only first level children. So it will not remove grandchildren. +- typescript definition in npm package +- node@5.10.1, canvas@1.3.14, jsdom@8.5.0 support +- `Konva.Path` will be filled when it is not closed +- `Animation.start()` will not not immediate sync draw. This should improve performance a little. +- Warning when node for `Tween` is not in layer yet. +- `removeChildren()` remove only first level children. So it will not remove grandchildren. -## 0.12.4 - 2016-04-19 +## 0.12.4 - 2016-04-19 ### Changed -* `batchDraw` will do not immediate `draw()` +- `batchDraw` will do not immediate `draw()` ### Fixed -* fix incorrect shadow offset on rotation +- fix incorrect shadow offset on rotation -## 0.12.3 - 2016-04-07 +## 0.12.3 - 2016-04-07 ### Fixed -* `batchDraw` function works less time now -* lighter npm package +- `batchDraw` function works less time now +- lighter npm package -## 0.12.2 - 2016-03-31 +## 0.12.2 - 2016-03-31 ### Fixed -* repair `cancelBubble` event property behaviour -* fix wrong `Path` `getClientRect()` calculation -* better HDPI support -* better typescript definitions -* node 0.12 support +- repair `cancelBubble` event property behaviour +- fix wrong `Path` `getClientRect()` calculation +- better HDPI support +- better typescript definitions +- node 0.12 support ### Changed -* more universal stage container selector -* `mousewheel` event changed to `wheel` +- more universal stage container selector +- `mousewheel` event changed to `wheel` -## 0.11.1 - 2016-01-16 +## 0.11.1 - 2016-01-16 ### Fixed -* correct `Konva.Arrow` drawing. Now it works better. -* Better support for dragging when mouse out of stage -* Better corner radius for `Label` shape -* `contentTap` event for stage +- correct `Konva.Arrow` drawing. Now it works better. +- Better support for dragging when mouse out of stage +- Better corner radius for `Label` shape +- `contentTap` event for stage ### Added -* event delegation. You can use it in this way: `layer.on('click', 'Circle', handler);` -* new `node.findAncestors(selector)` and `node.findAncestor(selector)` functions -* optional selector parameter for `stage.getIntersection` and `layer.getIntersection` -* show warning message if several instances of Konva are added to page. +- event delegation. You can use it in this way: `layer.on('click', 'Circle', handler);` +- new `node.findAncestors(selector)` and `node.findAncestor(selector)` functions +- optional selector parameter for `stage.getIntersection` and `layer.getIntersection` +- show warning message if several instances of Konva are added to page. ### Changed -* `moveTo` and some other methods return `this` -* `getAbsolutePosition` support optional relative parent argument (useful to find absolute position inside of some of parent nodes) -* `change` event will be not fired if changed value is the same as old value +- `moveTo` and some other methods return `this` +- `getAbsolutePosition` support optional relative parent argument (useful to find absolute position inside of some of parent nodes) +- `change` event will be not fired if changed value is the same as old value -## 0.10.0 - 2015-10-27 +## 0.10.0 - 2015-10-27 ### Added -* RGBA filter. Thanks to [@codefo](https://github.com/codefo) -* `stroke` and `fill` support for `Konva.Sprite` +- RGBA filter. Thanks to [@codefo](https://github.com/codefo) +- `stroke` and `fill` support for `Konva.Sprite` ### Fixed -* Correct calculation in `getClientRect` method of `Konva.Line` and `Konva.Container`. -* Correct `toObject()` behaviour for node with attrs with extended native prototypes -* Fixed bug for caching where buffer canvas is required +- Correct calculation in `getClientRect` method of `Konva.Line` and `Konva.Container`. +- Correct `toObject()` behaviour for node with attrs with extended native prototypes +- Fixed bug for caching where buffer canvas is required ### Changed -* Dragging works much better. If your pointer is out of stage content dragging will still continue. -* `Konva.Node.create` now works with objects. -* `Konva.Tween` now supports tweening points to state with different length +- Dragging works much better. If your pointer is out of stage content dragging will still continue. +- `Konva.Node.create` now works with objects. +- `Konva.Tween` now supports tweening points to state with different length -## 0.9.5 - 2015-05-28 +## 0.9.5 - 2015-05-28 ### Fixed -* `to` will not throw error if no `onFinish` callback -* HDPI support for desktop -* Fix bug when filters are not correct for HDPI -* Fix bug when hit area is not correct for HDPI -* Fix bug for incorrect `getClientRect` calculation -* Repair fill gradient for text +- `to` will not throw error if no `onFinish` callback +- HDPI support for desktop +- Fix bug when filters are not correct for HDPI +- Fix bug when hit area is not correct for HDPI +- Fix bug for incorrect `getClientRect` calculation +- Repair fill gradient for text ### Changed -* context wrapper is more capable with native context. +- context wrapper is more capable with native context. So you can use `context.fillStyle` property in your `sceneFunc` without accessing native context. -* `toDataURL` now handles pixelRatio. you can pass `config.pixelRatio` argument -* Correct `clone()` for custom nodes -* `FastLayer` can now have transforms -* `stage.toDataURL()` method now works synchronously. So `callback` argument is not required. -* `container.find(selector)` method now has a validation step. So if you forgot to add `#` or `.` you will see a warning message in the console. +- `toDataURL` now handles pixelRatio. you can pass `config.pixelRatio` argument +- Correct `clone()` for custom nodes +- `FastLayer` can now have transforms +- `stage.toDataURL()` method now works synchronously. So `callback` argument is not required. +- `container.find(selector)` method now has a validation step. So if you forgot to add `#` or `.` you will see a warning message in the console. ### Added -* new `Konva.Image.fromURL` method +- new `Konva.Image.fromURL` method ### Deprecated -* `fillRed`, `fillGreen`, `fillBlue`, `fillAlpha` are deprecated. Use `fill` instead. -* `strokeRed`, `strokeGreen`, `strokeBlue`, `strokeAlpha` are deprecated. Use `stroke` instead. -* `shadowRed`, `shadowGreen`, `shadowBlue`, `shadowAlpha` are deprecated. Use `shadow` instead. -* `dashArray` is deprecated. Use `dash` instead. -* `drawFunc` is deprecated. Use `sceneFunc` instead. -* `drawHitFunc` is deprecated. Use `hitFunc` instead. -* `rotateDeg` is deprecated. Use `rotate` instead. +- `fillRed`, `fillGreen`, `fillBlue`, `fillAlpha` are deprecated. Use `fill` instead. +- `strokeRed`, `strokeGreen`, `strokeBlue`, `strokeAlpha` are deprecated. Use `stroke` instead. +- `shadowRed`, `shadowGreen`, `shadowBlue`, `shadowAlpha` are deprecated. Use `shadow` instead. +- `dashArray` is deprecated. Use `dash` instead. +- `drawFunc` is deprecated. Use `sceneFunc` instead. +- `drawHitFunc` is deprecated. Use `hitFunc` instead. +- `rotateDeg` is deprecated. Use `rotate` instead. -## 0.9.0 - 2015-02-27 +## 0.9.0 - 2015-02-27 ### Fixed -* cache algorithm has A LOT OF updates. +- cache algorithm has A LOT OF updates. ### Changed -* `scale` now affects `shadowOffset` -* performance optimization (remove some unnecessary draws) -* more expected drawing when shape has opacity, stroke and shadow -* HDPI for caching. -* Cache should work much better. Now you don't need to pass bounding box {x,y,width,height} to `cache` method for all buildin Konva shapes. (only for your custom `Konva.Shape` instance). -* `Tween` now supports color properties (`fill`, `stroke`, `shadowColor`) +- `scale` now affects `shadowOffset` +- performance optimization (remove some unnecessary draws) +- more expected drawing when shape has opacity, stroke and shadow +- HDPI for caching. +- Cache should work much better. Now you don't need to pass bounding box {x,y,width,height} to `cache` method for all buildin Konva shapes. (only for your custom `Konva.Shape` instance). +- `Tween` now supports color properties (`fill`, `stroke`, `shadowColor`) ### Added -* new methods for working with node's name: `addName`, `removeName`, `hasName`. -* new `perfectDrawEnabled` property for shape. See [http://konvajs.org/docs/performance/Disable_Perfect_Draw.html](http://konvajs.org/docs/performance/Disable_Perfect_Draw.html) -* new `shadowForStrokeEnabled` property for shape. See [http://konvajs.org/docs/performance/All_Performance_Tips.html](http://konvajs.org/docs/performance/All_Performance_Tips.html) -* new `getClientRect` method. -* new `to` method for every node for shorter tweening +- new methods for working with node's name: `addName`, `removeName`, `hasName`. +- new `perfectDrawEnabled` property for shape. See [http://konvajs.org/docs/performance/Disable_Perfect_Draw.html](http://konvajs.org/docs/performance/Disable_Perfect_Draw.html) +- new `shadowForStrokeEnabled` property for shape. See [http://konvajs.org/docs/performance/All_Performance_Tips.html](http://konvajs.org/docs/performance/All_Performance_Tips.html) +- new `getClientRect` method. +- new `to` method for every node for shorter tweening -## 0.8.0 - 2015-02-04 +## 0.8.0 - 2015-02-04 -* Bug Fixes - * browser crashing on pointer events fixed - * optimized `getIntersection` function -* Enhancements - * `container.findOne()` method - * new `strokeHitEnabled` property. Useful for performance optimizations - * typescript definitions. see `/resources/konva.d.ts` +- Bug Fixes + - browser crashing on pointer events fixed + - optimized `getIntersection` function +- Enhancements + - `container.findOne()` method + - new `strokeHitEnabled` property. Useful for performance optimizations + - typescript definitions. see `/resources/konva.d.ts` ## Rebranding release 2015-01-28 Differences from last official `KineticJS` release -* Bug Fixes +- Bug Fixes - * `strokeScaleEnabled = false` is disabled for text as I can not find a way to implement this - * `strokeScaleEnabled = false` for Line now creates a correct hit graph - * working "this-example" as name for nodes - * Konva.Text() with no config will not throw exception - * Konva.Line() with no config will not throw exception - * Correct stage resizing with `FastLayer` - * `batchDraw` method for `FastLayer` - * Correct mouseover/mouseout/mouseenter/mouseleave events for groups - * cache node before adding to layer - * `intersects` function now works for shapes with shadow + - `strokeScaleEnabled = false` is disabled for text as I can not find a way to implement this + - `strokeScaleEnabled = false` for Line now creates a correct hit graph + - working "this-example" as name for nodes + - Konva.Text() with no config will not throw exception + - Konva.Line() with no config will not throw exception + - Correct stage resizing with `FastLayer` + - `batchDraw` method for `FastLayer` + - Correct mouseover/mouseout/mouseenter/mouseleave events for groups + - cache node before adding to layer + - `intersects` function now works for shapes with shadow -* Enhancements - * `cornerRadius` of Rect is limited by `width/2` and `height/2` - * `black` is default fill for text - * true class extending. Now `rect instanceOf Konva.Shape` will return true - * while dragging you can redraw layer that is not under drag. hit graph will be updated in this case - * now you can move object that is dragging into another layer. - * new `frameOffsets` attribute for `Konva.Sprite` - * much better dragging performance - * `browserify` support - * applying opacity to cached node - * remove all events with `node.off()` - * mouse dragging only with left button - * opacity now affects cached shapes - * Label corner radius - * smart changing `width`, `height`, `radius` attrs for circle, start, ellipse, ring. - * `mousewheel` support. Thanks [@vmichnowicz](https://github.com/vmichnowicz) - * new Arrow plugin - * multiple names: `node.name('foo bar'); container.find('.foo');` (thanks [@mattslocum](https://github.com/mattslocum)) - * `Container.findOne()` +- Enhancements + - `cornerRadius` of Rect is limited by `width/2` and `height/2` + - `black` is default fill for text + - true class extending. Now `rect instanceOf Konva.Shape` will return true + - while dragging you can redraw layer that is not under drag. hit graph will be updated in this case + - now you can move object that is dragging into another layer. + - new `frameOffsets` attribute for `Konva.Sprite` + - much better dragging performance + - `browserify` support + - applying opacity to cached node + - remove all events with `node.off()` + - mouse dragging only with left button + - opacity now affects cached shapes + - Label corner radius + - smart changing `width`, `height`, `radius` attrs for circle, start, ellipse, ring. + - `mousewheel` support. Thanks [@vmichnowicz](https://github.com/vmichnowicz) + - new Arrow plugin + - multiple names: `node.name('foo bar'); container.find('.foo');` (thanks [@mattslocum](https://github.com/mattslocum)) + - `Container.findOne()` diff --git a/gulpfile.js b/gulpfile.js index c03e26d7..2d9dc947 100644 --- a/gulpfile.js +++ b/gulpfile.js @@ -1,14 +1,14 @@ -var gulp = require('gulp'); -var rename = require('gulp-rename'); -var uglify = require('gulp-uglify-es').default; -var replace = require('gulp-replace'); -var jsdoc = require('gulp-jsdoc3'); -var connect = require('gulp-connect'); -var jscpd = require('gulp-jscpd'); -var eslint = require('gulp-eslint'); -var gutil = require('gulp-util'); +import gulp from 'gulp'; +import rename from 'gulp-rename'; +import uglify from 'gulp-uglify-es'; +import replace from 'gulp-replace'; +import jsdoc from 'gulp-jsdoc3'; +import connect from 'gulp-connect'; +import jscpd from 'gulp-jscpd'; +import eslint from 'gulp-eslint'; +import gutil from 'gulp-util'; -var fs = require('fs'); +import fs from 'fs'; var NodeParams = fs .readFileSync('./resources/doc-includes/NodeParams.txt') .toString(); @@ -19,7 +19,7 @@ var ShapeParams = fs .readFileSync('./resources/doc-includes/ShapeParams.txt') .toString(); -var conf = require('./package.json'); +const conf = JSON.parse(fs.readFileSync('./package.json')); function build() { return gulp @@ -44,7 +44,9 @@ gulp.task('pre-build', function () { return build() .pipe(rename('konva.js')) .pipe(gulp.dest('./')) - .pipe(uglify({ output: { comments: /^!|@preserve|@license|@cc_on/i } })) + .pipe( + uglify.default({ output: { comments: /^!|@preserve|@license|@cc_on/i } }) + ) .on('error', function (err) { gutil.log(gutil.colors.red('[Error]'), err.toString()); }) diff --git a/konva.js b/konva.js index 22c60bda..7c95f76d 100644 --- a/konva.js +++ b/konva.js @@ -8,7 +8,7 @@ * Konva JavaScript Framework v7.2.5 * http://konvajs.org/ * Licensed under the MIT - * Date: Wed Mar 03 2021 + * Date: Thu Apr 29 2021 * * Original work Copyright (C) 2011 - 2013 by Eric Rowell (KineticJS) * Modified work Copyright (C) 2014 - present by Anton Lavrenov (Konva) @@ -26,7 +26,7 @@ // electron case {}.toString.call(window) === '[object global]')); } - var _detectIE = function (ua) { + const _detectIE = function (ua) { var msie = ua.indexOf('msie '); if (msie > 0) { // IE 10 or older => return version number @@ -46,7 +46,7 @@ // other browser return false; }; - var _parseUA = function (userAgent) { + const _parseUA = function (userAgent) { var ua = userAgent.toLowerCase(), // jQuery UA regex match = /(chrome)[ /]([\w.]+)/.exec(ua) || @@ -64,27 +64,28 @@ isIE: _detectIE(ua), // adding mobile flab mobile: mobile, - ieMobile: ieMobile // If this is true (i.e., WP8), then Konva touch events are executed instead of equivalent Konva mouse events + ieMobile: ieMobile, // If this is true (i.e., WP8), then Konva touch events are executed instead of equivalent Konva mouse events }; }; - var glob = typeof global !== 'undefined' + const glob = typeof global !== 'undefined' ? global : typeof window !== 'undefined' ? window : typeof WorkerGlobalScope !== 'undefined' ? self : {}; - var Konva = { + const Konva$2 = { _global: glob, version: '7.2.5', isBrowser: detectBrowser(), isUnminified: /param/.test(function (param) { }.toString()), dblClickWindow: 400, - getAngle: function (angle) { - return Konva.angleDeg ? angle * PI_OVER_180 : angle; + getAngle(angle) { + return Konva$2.angleDeg ? angle * PI_OVER_180 : angle; }, enableTrace: false, _pointerEventsEnabled: false, + autoDrawEnabled: false, /** * Should we enable hit detection while dragging? For performance reasons, by default it is false. * But on some rare cases you want to see hit graph and check intersections. Just set it to true. @@ -123,7 +124,7 @@ * // before any Konva code: * Konva.pixelRatio = 1; */ - pixelRatio: undefined, + pixelRatio: (typeof window !== 'undefined' && window.devicePixelRatio) || 1, /** * Drag distance property. If you start to drag a node you may want to wait until pointer is moved to some distance from start point, * only then start dragging. Default is 3px. @@ -170,8 +171,8 @@ * @method * @memberof Konva */ - isDragging: function () { - return Konva['DD'].isDragging; + isDragging() { + return Konva$2['DD'].isDragging; }, /** * returns whether or not a drag and drop operation is ready, but may @@ -179,102 +180,26 @@ * @method * @memberof Konva */ - isDragReady: function () { - return !!Konva['DD'].node; + isDragReady() { + return !!Konva$2['DD'].node; }, // user agent UA: _parseUA((glob.navigator && glob.navigator.userAgent) || ''), document: glob.document, // insert Konva into global namespace (window) // it is required for npm packages - _injectGlobal: function (Konva) { + _injectGlobal(Konva) { glob.Konva = Konva; }, - _parseUA: _parseUA + _parseUA, }; - var _NODES_REGISTRY = {}; - var _registerNode = function (NodeClass) { + const _NODES_REGISTRY = {}; + const _registerNode = (NodeClass) => { _NODES_REGISTRY[NodeClass.prototype.getClassName()] = NodeClass; - Konva[NodeClass.prototype.getClassName()] = NodeClass; - }; + Konva$2[NodeClass.prototype.getClassName()] = NodeClass; + }; + Konva$2._injectGlobal(Konva$2); - /** - * Collection constructor. Collection extends Array. - * This class is used in conjunction with {@link Konva.Container#find} - * The good thing about collection is that it has ALL methods of all Konva nodes. Take a look into examples. - * @constructor - * @memberof Konva - * @example - * - * // find all rectangles and return them as Collection - * const shapes = layer.find('Rect'); - * // fill all rectangles with a single function - * shapes.fill('red'); - */ - var Collection = /** @class */ (function () { - function Collection() { - } - /** - * convert array into a collection - * @method - * @memberof Konva.Collection - * @param {Array} arr - */ - Collection.toCollection = function (arr) { - var collection = new Collection(), len = arr.length, n; - for (n = 0; n < len; n++) { - collection.push(arr[n]); - } - return collection; - }; - Collection._mapMethod = function (methodName) { - Collection.prototype[methodName] = function () { - var len = this.length, i; - var args = [].slice.call(arguments); - for (i = 0; i < len; i++) { - this[i][methodName].apply(this[i], args); - } - return this; - }; - }; - Collection.mapMethods = function (constructor) { - var prot = constructor.prototype; - for (var methodName in prot) { - Collection._mapMethod(methodName); - } - }; - return Collection; - }()); - Collection.prototype = []; - /** - * iterate through node array and run a function for each node. - * The node and index is passed into the function - * @method - * @name Konva.Collection#each - * @param {Function} func - * @example - * // get all nodes with name foo inside layer, and set x to 10 for each - * layer.find('.foo').each(function(shape, n) { - * shape.setX(10); - * }); - */ - Collection.prototype.each = function (func) { - for (var n = 0; n < this.length; n++) { - func(this[n], n); - } - }; - /** - * convert collection into an array - * @method - * @name Konva.Collection#toArray - */ - Collection.prototype.toArray = function () { - var arr = [], len = this.length, n; - for (n = 0; n < len; n++) { - arr.push(this[n]); - } - return arr; - }; /* * Last updated November 2011 * By Simon Sarris @@ -298,20 +223,19 @@ * @param {Array} [m] Optional six-element matrix * @memberof Konva */ - var Transform = /** @class */ (function () { - function Transform(m) { - if (m === void 0) { m = [1, 0, 0, 1, 0, 0]; } + class Transform { + constructor(m = [1, 0, 0, 1, 0, 0]) { this.dirty = false; this.m = (m && m.slice()) || [1, 0, 0, 1, 0, 0]; } - Transform.prototype.reset = function () { + reset() { this.m[0] = 1; this.m[1] = 0; this.m[2] = 0; this.m[3] = 1; this.m[4] = 0; this.m[5] = 0; - }; + } /** * Copy Konva.Transform object * @method @@ -320,17 +244,17 @@ * @example * const tr = shape.getTransform().copy() */ - Transform.prototype.copy = function () { + copy() { return new Transform(this.m); - }; - Transform.prototype.copyInto = function (tr) { + } + copyInto(tr) { tr.m[0] = this.m[0]; tr.m[1] = this.m[1]; tr.m[2] = this.m[2]; tr.m[3] = this.m[3]; tr.m[4] = this.m[4]; tr.m[5] = this.m[5]; - }; + } /** * Transform point * @method @@ -338,13 +262,13 @@ * @param {Object} point 2D point(x, y) * @returns {Object} 2D point(x, y) */ - Transform.prototype.point = function (point) { + point(point) { var 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], }; - }; + } /** * Apply translation * @method @@ -353,11 +277,11 @@ * @param {Number} y * @returns {Konva.Transform} */ - Transform.prototype.translate = function (x, y) { + translate(x, y) { this.m[4] += this.m[0] * x + this.m[2] * y; this.m[5] += this.m[1] * x + this.m[3] * y; return this; - }; + } /** * Apply scale * @method @@ -366,13 +290,13 @@ * @param {Number} sy * @returns {Konva.Transform} */ - Transform.prototype.scale = function (sx, sy) { + scale(sx, sy) { this.m[0] *= sx; this.m[1] *= sx; this.m[2] *= sy; this.m[3] *= sy; return this; - }; + } /** * Apply rotation * @method @@ -380,7 +304,7 @@ * @param {Number} rad Angle in radians * @returns {Konva.Transform} */ - Transform.prototype.rotate = function (rad) { + rotate(rad) { var c = Math.cos(rad); var s = Math.sin(rad); var m11 = this.m[0] * c + this.m[2] * s; @@ -392,19 +316,19 @@ this.m[2] = m21; this.m[3] = m22; return this; - }; + } /** * Returns the translation * @method * @name Konva.Transform#getTranslation * @returns {Object} 2D point(x, y) */ - Transform.prototype.getTranslation = function () { + getTranslation() { return { x: this.m[4], y: this.m[5], }; - }; + } /** * Apply skew * @method @@ -413,7 +337,7 @@ * @param {Number} sy * @returns {Konva.Transform} */ - Transform.prototype.skew = function (sx, sy) { + skew(sx, sy) { 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; @@ -423,7 +347,7 @@ this.m[2] = m21; this.m[3] = m22; return this; - }; + } /** * Transform multiplication * @method @@ -431,7 +355,7 @@ * @param {Konva.Transform} matrix * @returns {Konva.Transform} */ - Transform.prototype.multiply = function (matrix) { + multiply(matrix) { 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]; var m21 = this.m[0] * matrix.m[2] + this.m[2] * matrix.m[3]; @@ -445,14 +369,14 @@ this.m[4] = dx; this.m[5] = dy; return this; - }; + } /** * Invert the matrix * @method * @name Konva.Transform#invert * @returns {Konva.Transform} */ - Transform.prototype.invert = function () { + 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; @@ -467,15 +391,15 @@ this.m[4] = m4; this.m[5] = m5; return this; - }; + } /** * return matrix * @method * @name Konva.Transform#getMatrix */ - Transform.prototype.getMatrix = function () { + getMatrix() { return this.m; - }; + } /** * set to absolute position via translation * @method @@ -483,17 +407,17 @@ * @returns {Konva.Transform} * @author ericdrowell */ - Transform.prototype.setAbsolutePosition = function (x, y) { + setAbsolutePosition(x, y) { var m0 = this.m[0], m1 = this.m[1], m2 = this.m[2], m3 = this.m[3], m4 = this.m[4], m5 = this.m[5], yt = (m0 * (y - m5) - m1 * (x - m4)) / (m0 * m3 - m1 * m2), xt = (x - m4 - m2 * yt) / m0; return this.translate(xt, yt); - }; + } /** * convert transformation matrix back into node's attributes * @method * @name Konva.Transform#decompose * @returns {Konva.Transform} */ - Transform.prototype.decompose = function () { + decompose() { var a = this.m[0]; var b = this.m[1]; var c = this.m[2]; @@ -501,7 +425,7 @@ var e = this.m[4]; var f = this.m[5]; var delta = a * d - b * c; - var result = { + let result = { x: e, y: f, rotation: 0, @@ -531,11 +455,10 @@ else ; result.rotation = Util._getRotation(result.rotation); return result; - }; - return Transform; - }()); + } + } // CONSTANTS - var OBJECT_ARRAY = '[object Array]', OBJECT_NUMBER = '[object Number]', OBJECT_STRING = '[object String]', OBJECT_BOOLEAN = '[object Boolean]', PI_OVER_DEG180 = Math.PI / 180, DEG180_OVER_PI = 180 / Math.PI, HASH = '#', EMPTY_STRING = '', ZERO = '0', KONVA_WARNING = 'Konva warning: ', KONVA_ERROR = 'Konva error: ', RGB_PAREN = 'rgb(', COLORS = { + var OBJECT_ARRAY = '[object Array]', OBJECT_NUMBER = '[object Number]', OBJECT_STRING = '[object String]', OBJECT_BOOLEAN = '[object Boolean]', PI_OVER_DEG180 = Math.PI / 180, DEG180_OVER_PI = 180 / Math.PI, HASH$1 = '#', EMPTY_STRING$2 = '', ZERO = '0', KONVA_WARNING = 'Konva warning: ', KONVA_ERROR = 'Konva error: ', RGB_PAREN = 'rgb(', COLORS = { aliceblue: [240, 248, 255], antiquewhite: [250, 235, 215], aqua: [0, 255, 255], @@ -690,38 +613,38 @@ * @namespace Util * @memberof Konva */ - var Util = { + const Util = { /* * cherry-picked utilities from underscore.js */ - _isElement: function (obj) { + _isElement(obj) { return !!(obj && obj.nodeType == 1); }, - _isFunction: function (obj) { + _isFunction(obj) { return !!(obj && obj.constructor && obj.call && obj.apply); }, - _isPlainObject: function (obj) { + _isPlainObject(obj) { return !!obj && obj.constructor === Object; }, - _isArray: function (obj) { + _isArray(obj) { return Object.prototype.toString.call(obj) === OBJECT_ARRAY; }, - _isNumber: function (obj) { + _isNumber(obj) { return (Object.prototype.toString.call(obj) === OBJECT_NUMBER && !isNaN(obj) && isFinite(obj)); }, - _isString: function (obj) { + _isString(obj) { return Object.prototype.toString.call(obj) === OBJECT_STRING; }, - _isBoolean: function (obj) { + _isBoolean(obj) { return Object.prototype.toString.call(obj) === OBJECT_BOOLEAN; }, // arrays are objects too - isObject: function (val) { + isObject(val) { return val instanceof Object; }, - isValidSelector: function (selector) { + isValidSelector(selector) { if (typeof selector !== 'string') { return false; } @@ -730,7 +653,7 @@ firstChar === '.' || firstChar === firstChar.toUpperCase()); }, - _sign: function (number) { + _sign(number) { if (number === 0) { // that is not what sign usually returns // but that is what we need @@ -743,11 +666,15 @@ return -1; } }, - requestAnimFrame: function (callback) { + requestAnimFrame(callback) { animQueue.push(callback); + const req = (typeof requestAnimationFrame !== 'undefined' && requestAnimationFrame) || + function (f) { + setTimeout(f, 60); + }; if (animQueue.length === 1) { - requestAnimationFrame(function () { - var queue = animQueue; + req(function () { + const queue = animQueue; animQueue = []; queue.forEach(function (cb) { cb(); @@ -755,7 +682,7 @@ }); } }, - createCanvasElement: function () { + createCanvasElement() { var canvas = document.createElement('canvas'); // on some environments canvas.style is readonly try { @@ -764,10 +691,10 @@ catch (e) { } return canvas; }, - createImageElement: function () { + createImageElement() { return document.createElement('img'); }, - _isInDocument: function (el) { + _isInDocument(el) { while ((el = el.parentNode)) { if (el == document) { return true; @@ -775,7 +702,7 @@ } return false; }, - _simplifyArray: function (arr) { + _simplifyArray(arr) { var retArr = [], len = arr.length, util = Util, n, val; for (n = 0; n < len; n++) { val = arr[n]; @@ -783,7 +710,7 @@ val = Math.round(val * 1000) / 1000; } else if (!util._isString(val)) { - val = val.toString(); + val = val + ''; } retArr.push(val); } @@ -792,19 +719,19 @@ /* * arg can be an image object or image data */ - _urlToImage: function (url, callback) { + _urlToImage(url, callback) { // if arg is a string, then it's a data url - var imageObj = new glob.Image(); + var imageObj = Util.createImageElement(); imageObj.onload = function () { callback(imageObj); }; imageObj.src = url; }, - _rgbToHex: function (r, g, b) { + _rgbToHex(r, g, b) { return ((1 << 24) + (r << 16) + (g << 8) + b).toString(16).slice(1); }, - _hexToRgb: function (hex) { - hex = hex.replace(HASH, EMPTY_STRING); + _hexToRgb(hex) { + hex = hex.replace(HASH$1, EMPTY_STRING$2); var bigint = parseInt(hex, 16); return { r: (bigint >> 16) & 255, @@ -819,14 +746,14 @@ * @example * shape.fill(Konva.Util.getRandomColor()); */ - getRandomColor: function () { + getRandomColor() { var randColor = ((Math.random() * 0xffffff) << 0).toString(16); while (randColor.length < 6) { randColor = ZERO + randColor; } - return HASH + randColor; + return HASH$1 + randColor; }, - get: function (val, def) { + get(val, def) { if (val === undefined) { return def; } @@ -845,7 +772,7 @@ * var rgb = Konva.Util.getRGB('#0000ff'); * var rgb = Konva.Util.getRGB('rgb(0,0,255)'); */ - getRGB: function (color) { + getRGB(color) { var rgb; // color string if (color in COLORS) { @@ -856,7 +783,7 @@ b: rgb[2], }; } - else if (color[0] === HASH) { + else if (color[0] === HASH$1) { // hex return this._hexToRgb(color.substring(1)); } @@ -880,7 +807,7 @@ }, // convert any color string to RGBA object // from https://github.com/component/color-parser - colorToRGBA: function (str) { + colorToRGBA(str) { str = str || 'black'; return (Util._namedColorToRBA(str) || Util._hex3ColorToRGBA(str) || @@ -890,7 +817,7 @@ Util._hslColorToRGBA(str)); }, // Parse named css color. Like "green" - _namedColorToRBA: function (str) { + _namedColorToRBA(str) { var c = COLORS[str.toLowerCase()]; if (!c) { return null; @@ -903,7 +830,7 @@ }; }, // Parse rgb(n, n, n) - _rgbColorToRGBA: function (str) { + _rgbColorToRGBA(str) { if (str.indexOf('rgb(') === 0) { str = str.match(/rgb\(([^)]+)\)/)[1]; var parts = str.split(/ *, */).map(Number); @@ -916,7 +843,7 @@ } }, // Parse rgba(n, n, n, n) - _rgbaColorToRGBA: function (str) { + _rgbaColorToRGBA(str) { if (str.indexOf('rgba(') === 0) { str = str.match(/rgba\(([^)]+)\)/)[1]; var parts = str.split(/ *, */).map(Number); @@ -929,7 +856,7 @@ } }, // Parse #nnnnnn - _hex6ColorToRGBA: function (str) { + _hex6ColorToRGBA(str) { if (str[0] === '#' && str.length === 7) { return { r: parseInt(str.slice(1, 3), 16), @@ -940,7 +867,7 @@ } }, // Parse #nnn - _hex3ColorToRGBA: function (str) { + _hex3ColorToRGBA(str) { if (str[0] === '#' && str.length === 4) { return { r: parseInt(str[1] + str[1], 16), @@ -951,17 +878,17 @@ } }, // Code adapted from https://github.com/Qix-/color-convert/blob/master/conversions.js#L244 - _hslColorToRGBA: function (str) { + _hslColorToRGBA(str) { // Check hsl() format if (/hsl\((\d+),\s*([\d.]+)%,\s*([\d.]+)%\)/g.test(str)) { // Extract h, s, l - var _a = /hsl\((\d+),\s*([\d.]+)%,\s*([\d.]+)%\)/g.exec(str); _a[0]; var hsl = _a.slice(1); - var h = Number(hsl[0]) / 360; - var s = Number(hsl[1]) / 100; - var l = Number(hsl[2]) / 100; - var t2 = void 0; - var t3 = void 0; - var val = void 0; + const [_, ...hsl] = /hsl\((\d+),\s*([\d.]+)%,\s*([\d.]+)%\)/g.exec(str); + const h = Number(hsl[0]) / 360; + const s = Number(hsl[1]) / 100; + const l = Number(hsl[2]) / 100; + let t2; + let t3; + let val; if (s === 0) { val = l * 255; return { @@ -977,9 +904,9 @@ else { t2 = l + s - l * s; } - var t1 = 2 * l - t2; - var rgb = [0, 0, 0]; - for (var i = 0; i < 3; i++) { + const t1 = 2 * l - t2; + const rgb = [0, 0, 0]; + for (let i = 0; i < 3; i++) { t3 = h + (1 / 3) * -(i - 1); if (t3 < 0) { t3++; @@ -1018,13 +945,13 @@ * @example * const overlapping = Konva.Util.haveIntersection(shape1.getClientRect(), shape2.getClientRect()); */ - haveIntersection: function (r1, r2) { + haveIntersection(r1, r2) { return !(r2.x > r1.x + r1.width || r2.x + r2.width < r1.x || r2.y > r1.y + r1.height || r2.y + r2.height < r1.y); }, - cloneObject: function (obj) { + cloneObject(obj) { var retObj = {}; for (var key in obj) { if (this._isPlainObject(obj[key])) { @@ -1039,34 +966,34 @@ } return retObj; }, - cloneArray: function (arr) { + cloneArray(arr) { return arr.slice(0); }, - _degToRad: function (deg) { + _degToRad(deg) { return deg * PI_OVER_DEG180; }, - _radToDeg: function (rad) { + _radToDeg(rad) { return rad * DEG180_OVER_PI; }, - _getRotation: function (radians) { - return Konva.angleDeg ? Util._radToDeg(radians) : radians; + _getRotation(radians) { + return Konva$2.angleDeg ? Util._radToDeg(radians) : radians; }, - _capitalize: function (str) { + _capitalize(str) { return str.charAt(0).toUpperCase() + str.slice(1); }, - throw: function (str) { + throw(str) { throw new Error(KONVA_ERROR + str); }, - error: function (str) { + error(str) { console.error(KONVA_ERROR + str); }, - warn: function (str) { - if (!Konva.showWarnings) { + warn(str) { + if (!Konva$2.showWarnings) { return; } console.warn(KONVA_WARNING + str); }, - extend: function (child, parent) { + extend(child, parent) { function Ctor() { this.constructor = child; } @@ -1082,11 +1009,11 @@ // create reference to parent child.super = parent; }, - _getControlPoints: function (x0, y0, x1, y1, x2, y2, t) { + _getControlPoints(x0, y0, x1, y1, x2, y2, t) { var 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), p1x = x1 - fa * (x2 - x0), p1y = y1 - fa * (y2 - y0), p2x = x1 + fb * (x2 - x0), p2y = y1 + fb * (y2 - y0); return [p1x, p1y, p2x, p2y]; }, - _expandPoints: function (p, tension) { + _expandPoints(p, tension) { var len = p.length, allPoints = [], n, cp; for (n = 2; n < len - 2; n += 2) { cp = Util._getControlPoints(p[n - 2], p[n - 1], p[n], p[n + 1], p[n + 2], p[n + 3], tension); @@ -1102,15 +1029,15 @@ } return allPoints; }, - each: function (obj, func) { + each(obj, func) { for (var key in obj) { func(key, obj[key]); } }, - _inRange: function (val, left, right) { + _inRange(val, left, right) { return left <= val && val < right; }, - _getProjectionToSegment: function (x1, y1, x2, y2, x3, y3) { + _getProjectionToSegment(x1, y1, x2, y2, x3, y3) { var x, y, dist; var pd2 = (x1 - x2) * (x1 - x2) + (y1 - y2) * (y1 - y2); if (pd2 == 0) { @@ -1140,7 +1067,7 @@ }, // line as array of points. // line might be closed - _getProjectionToLine: function (pt, line, isClosed) { + _getProjectionToLine(pt, line, isClosed) { var pc = Util.cloneObject(pt); var dist = Number.MAX_VALUE; line.forEach(function (p1, i) { @@ -1158,7 +1085,7 @@ }); return pc; }, - _prepareArrayForTween: function (startArray, endArray, isClosed) { + _prepareArrayForTween(startArray, endArray, isClosed) { var n, start = [], end = []; if (startArray.length > endArray.length) { var temp = endArray; @@ -1185,7 +1112,7 @@ }); return newStart; }, - _prepareToStringify: function (obj) { + _prepareToStringify(obj) { var desc; obj.visitedByCircularReferenceRemoval = true; for (var key in obj) { @@ -1215,13 +1142,13 @@ return obj; }, // very simplified version of Object.assign - _assign: function (target, source) { + _assign(target, source) { for (var key in source) { target[key] = source[key]; } return target; }, - _getFirstPointerId: function (evt) { + _getFirstPointerId(evt) { if (!evt.touches) { // fake id for mouse return 999; @@ -1254,7 +1181,7 @@ return Math.round(val); } function getNumberValidator() { - if (Konva.isUnminified) { + if (Konva$2.isUnminified) { return function (val, attr) { if (!Util._isNumber(val)) { Util.warn(_formatValue(val) + @@ -1267,10 +1194,10 @@ } } function getNumberOrArrayOfNumbersValidator(noOfElements) { - if (Konva.isUnminified) { + if (Konva$2.isUnminified) { return function (val, attr) { - var isNumber = Util._isNumber(val); - var isValidArray = Util._isArray(val) && val.length == noOfElements; + let isNumber = Util._isNumber(val); + let isValidArray = Util._isArray(val) && val.length == noOfElements; if (!isNumber && !isValidArray) { Util.warn(_formatValue(val) + ' is a not valid value for "' + @@ -1282,7 +1209,7 @@ } } function getNumberOrAutoValidator() { - if (Konva.isUnminified) { + if (Konva$2.isUnminified) { return function (val, attr) { var isNumber = Util._isNumber(val); var isAuto = val === 'auto'; @@ -1297,7 +1224,7 @@ } } function getStringValidator() { - if (Konva.isUnminified) { + if (Konva$2.isUnminified) { return function (val, attr) { if (!Util._isString(val)) { Util.warn(_formatValue(val) + @@ -1310,10 +1237,10 @@ } } function getStringOrGradientValidator() { - if (Konva.isUnminified) { + if (Konva$2.isUnminified) { return function (val, attr) { - var isString = Util._isString(val); - var isGradient = Object.prototype.toString.call(val) === '[object CanvasGradient]'; + const isString = Util._isString(val); + const isGradient = Object.prototype.toString.call(val) === '[object CanvasGradient]'; if (!(isString || isGradient)) { Util.warn(_formatValue(val) + ' is a not valid value for "' + @@ -1325,7 +1252,7 @@ } } function getNumberArrayValidator() { - if (Konva.isUnminified) { + if (Konva$2.isUnminified) { return function (val, attr) { if (!Util._isArray(val)) { Util.warn(_formatValue(val) + @@ -1349,7 +1276,7 @@ } } function getBooleanValidator() { - if (Konva.isUnminified) { + if (Konva$2.isUnminified) { return function (val, attr) { var isBool = val === true || val === false; if (!isBool) { @@ -1363,7 +1290,7 @@ } } function getComponentValidator(components) { - if (Konva.isUnminified) { + if (Konva$2.isUnminified) { return function (val, attr) { if (!Util.isObject(val)) { Util.warn(_formatValue(val) + @@ -1377,14 +1304,14 @@ } } - var GET = 'get', SET = 'set'; - var Factory = { - addGetterSetter: function (constructor, attr, def, validator, after) { + var GET = 'get', SET$1 = 'set'; + const Factory = { + addGetterSetter(constructor, attr, def, validator, after) { Factory.addGetter(constructor, attr, def); Factory.addSetter(constructor, attr, validator, after); Factory.addOverloadedGetterSetter(constructor, attr); }, - addGetter: function (constructor, attr, def) { + addGetter(constructor, attr, def) { var method = GET + Util._capitalize(attr); constructor.prototype[method] = constructor.prototype[method] || @@ -1393,14 +1320,14 @@ return val === undefined ? def : val; }; }, - addSetter: function (constructor, attr, validator, after) { - var method = SET + Util._capitalize(attr); + addSetter(constructor, attr, validator, after) { + var method = SET$1 + Util._capitalize(attr); if (!constructor.prototype[method]) { Factory.overWriteSetter(constructor, attr, validator, after); } }, - overWriteSetter: function (constructor, attr, validator, after) { - var method = SET + Util._capitalize(attr); + overWriteSetter(constructor, attr, validator, after) { + var method = SET$1 + Util._capitalize(attr); constructor.prototype[method] = function (val) { if (validator && val !== undefined && val !== null) { val = validator.call(this, val, attr); @@ -1412,8 +1339,8 @@ return this; }; }, - addComponentsGetterSetter: function (constructor, attr, components, validator, after) { - var len = components.length, capitalize = Util._capitalize, getter = GET + capitalize(attr), setter = SET + capitalize(attr), n, component; + addComponentsGetterSetter(constructor, attr, components, validator, after) { + var len = components.length, capitalize = Util._capitalize, getter = GET + capitalize(attr), setter = SET$1 + capitalize(attr), n, component; // getter constructor.prototype[getter] = function () { var ret = {}; @@ -1447,8 +1374,8 @@ }; Factory.addOverloadedGetterSetter(constructor, attr); }, - addOverloadedGetterSetter: function (constructor, attr) { - var capitalizedAttr = Util._capitalize(attr), setter = SET + capitalizedAttr, getter = GET + capitalizedAttr; + addOverloadedGetterSetter(constructor, attr) { + var capitalizedAttr = Util._capitalize(attr), setter = SET$1 + capitalizedAttr, getter = GET + capitalizedAttr; constructor.prototype[attr] = function () { // setting if (arguments.length) { @@ -1459,7 +1386,7 @@ return this[getter](); }; }, - addDeprecatedGetterSetter: function (constructor, attr, def, validator) { + addDeprecatedGetterSetter(constructor, attr, def, validator) { Util.error('Adding deprecated ' + attr); var method = GET + Util._capitalize(attr); var message = attr + @@ -1474,11 +1401,11 @@ }); Factory.addOverloadedGetterSetter(constructor, attr); }, - backCompat: function (constructor, methods) { + 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); + var oldSetter = SET$1 + Util._capitalize(oldMethodName); function deprecated() { method.apply(this, arguments); Util.error('"' + @@ -1492,59 +1419,11 @@ constructor.prototype[oldSetter] = deprecated; }); }, - afterSetFilter: function () { + afterSetFilter() { this._filterUpToDate = false; }, }; - /*! ***************************************************************************** - Copyright (c) Microsoft Corporation. - - Permission to use, copy, modify, and/or distribute this software for any - purpose with or without fee is hereby granted. - - THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH - REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY - AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, - INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM - LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR - OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR - PERFORMANCE OF THIS SOFTWARE. - ***************************************************************************** */ - /* global Reflect, Promise */ - - var extendStatics = function(d, b) { - extendStatics = Object.setPrototypeOf || - ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || - function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; }; - return extendStatics(d, b); - }; - - function __extends(d, b) { - extendStatics(d, b); - function __() { this.constructor = d; } - d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); - } - - var __assign = function() { - __assign = Object.assign || function __assign(t) { - for (var s, i = 1, n = arguments.length; i < n; i++) { - s = arguments[i]; - for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p]; - } - return t; - }; - return __assign.apply(this, arguments); - }; - - function __spreadArrays() { - for (var s = 0, i = 0, il = arguments.length; i < il; i++) s += arguments[i].length; - for (var r = Array(s), k = 0, i = 0; i < il; i++) - for (var a = arguments[i], j = 0, jl = a.length; j < jl; j++, k++) - r[k] = a[j]; - return r; - } - var COMMA = ',', OPEN_PAREN = '(', CLOSE_PAREN = ')', OPEN_PAREN_BRACKET = '([', CLOSE_BRACKET_PAREN = '])', SEMICOLON = ';', DOUBLE_PAREN = '()', // EMPTY_STRING = '', EQUALS = '=', @@ -1601,7 +1480,7 @@ 'globalCompositeOperation', 'imageSmoothingEnabled', ]; - var traceArrMax = 100; + const traceArrMax = 100; /** * Konva wrapper around native 2d canvas context. It has almost the same API of 2d context with some additional functions. * With core Konva shapes you don't need to use this object. But you will use it if you want to create @@ -1624,11 +1503,11 @@ * } * }) */ - var Context = /** @class */ (function () { - function Context(canvas) { + class Context { + constructor(canvas) { this.canvas = canvas; this._context = canvas._canvas.getContext('2d'); - if (Konva.enableTrace) { + if (Konva$2.enableTrace) { this.traceArr = []; this._enableTrace(); } @@ -1639,35 +1518,35 @@ * @name Konva.Context#fillShape * @param {Konva.Shape} shape */ - Context.prototype.fillShape = function (shape) { + fillShape(shape) { if (shape.fillEnabled()) { this._fill(shape); } - }; - Context.prototype._fill = function (shape) { + } + _fill(shape) { // abstract - }; + } /** * stroke shape * @method * @name Konva.Context#strokeShape * @param {Konva.Shape} shape */ - Context.prototype.strokeShape = function (shape) { + strokeShape(shape) { if (shape.hasStroke()) { this._stroke(shape); } - }; - Context.prototype._stroke = function (shape) { + } + _stroke(shape) { // abstract - }; + } /** * fill then stroke * @method * @name Konva.Context#fillStrokeShape * @param {Konva.Shape} shape */ - Context.prototype.fillStrokeShape = function (shape) { + fillStrokeShape(shape) { if (shape.attrs.fillAfterStrokeEnabled) { this.strokeShape(shape); this.fillShape(shape); @@ -1676,8 +1555,8 @@ this.fillShape(shape); this.strokeShape(shape); } - }; - Context.prototype.getTrace = function (relaxed) { + } + getTrace(relaxed) { var traceArr = this.traceArr, len = traceArr.length, str = '', n, trace, method, args; for (n = 0; n < len; n++) { trace = traceArr[n]; @@ -1708,36 +1587,36 @@ str += SEMICOLON; } return str; - }; - Context.prototype.clearTrace = function () { + } + clearTrace() { this.traceArr = []; - }; - Context.prototype._trace = function (str) { + } + _trace(str) { var traceArr = this.traceArr, len; traceArr.push(str); len = traceArr.length; if (len >= traceArrMax) { traceArr.shift(); } - }; + } /** * reset canvas context transform * @method * @name Konva.Context#reset */ - Context.prototype.reset = function () { + reset() { var pixelRatio = this.getCanvas().getPixelRatio(); this.setTransform(1 * pixelRatio, 0, 0, 1 * pixelRatio, 0, 0); - }; + } /** * get canvas wrapper * @method * @name Konva.Context#getCanvas * @returns {Konva.Canvas} */ - Context.prototype.getCanvas = function () { + getCanvas() { return this.canvas; - }; + } /** * clear canvas * @method @@ -1748,7 +1627,7 @@ * @param {Number} [bounds.width] * @param {Number} [bounds.height] */ - Context.prototype.clear = function (bounds) { + clear(bounds) { var canvas = this.getCanvas(); if (bounds) { this.clearRect(bounds.x || 0, bounds.y || 0, bounds.width || 0, bounds.height || 0); @@ -1756,90 +1635,90 @@ else { this.clearRect(0, 0, canvas.getWidth() / canvas.pixelRatio, canvas.getHeight() / canvas.pixelRatio); } - }; - Context.prototype._applyLineCap = function (shape) { + } + _applyLineCap(shape) { var lineCap = shape.getLineCap(); if (lineCap) { this.setAttr('lineCap', lineCap); } - }; - Context.prototype._applyOpacity = function (shape) { + } + _applyOpacity(shape) { var absOpacity = shape.getAbsoluteOpacity(); if (absOpacity !== 1) { this.setAttr('globalAlpha', absOpacity); } - }; - Context.prototype._applyLineJoin = function (shape) { + } + _applyLineJoin(shape) { var lineJoin = shape.attrs.lineJoin; if (lineJoin) { this.setAttr('lineJoin', lineJoin); } - }; - Context.prototype.setAttr = function (attr, val) { + } + setAttr(attr, val) { this._context[attr] = val; - }; + } /** * arc function. * @method * @name Konva.Context#arc */ - Context.prototype.arc = function (a0, a1, a2, a3, a4, a5) { + arc(a0, a1, a2, a3, a4, a5) { this._context.arc(a0, a1, a2, a3, a4, a5); - }; + } /** * arcTo function. * @method * @name Konva.Context#arcTo */ - Context.prototype.arcTo = function (a0, a1, a2, a3, a4) { + arcTo(a0, a1, a2, a3, a4) { this._context.arcTo(a0, a1, a2, a3, a4); - }; + } /** * beginPath function. * @method * @name Konva.Context#beginPath */ - Context.prototype.beginPath = function () { + beginPath() { this._context.beginPath(); - }; + } /** * bezierCurveTo function. * @method * @name Konva.Context#bezierCurveTo */ - Context.prototype.bezierCurveTo = function (a0, a1, a2, a3, a4, a5) { + bezierCurveTo(a0, a1, a2, a3, a4, a5) { this._context.bezierCurveTo(a0, a1, a2, a3, a4, a5); - }; + } /** * clearRect function. * @method * @name Konva.Context#clearRect */ - Context.prototype.clearRect = function (a0, a1, a2, a3) { + clearRect(a0, a1, a2, a3) { this._context.clearRect(a0, a1, a2, a3); - }; + } /** * clip function. * @method * @name Konva.Context#clip */ - Context.prototype.clip = function () { + clip() { this._context.clip(); - }; + } /** * closePath function. * @method * @name Konva.Context#closePath */ - Context.prototype.closePath = function () { + closePath() { this._context.closePath(); - }; + } /** * createImageData function. * @method * @name Konva.Context#createImageData */ - Context.prototype.createImageData = function (a0, a1) { + createImageData(a0, a1) { var a = arguments; if (a.length === 2) { return this._context.createImageData(a0, a1); @@ -1847,37 +1726,37 @@ else if (a.length === 1) { return this._context.createImageData(a0); } - }; + } /** * createLinearGradient function. * @method * @name Konva.Context#createLinearGradient */ - Context.prototype.createLinearGradient = function (a0, a1, a2, a3) { + createLinearGradient(a0, a1, a2, a3) { return this._context.createLinearGradient(a0, a1, a2, a3); - }; + } /** * createPattern function. * @method * @name Konva.Context#createPattern */ - Context.prototype.createPattern = function (a0, a1) { + createPattern(a0, a1) { return this._context.createPattern(a0, a1); - }; + } /** * createRadialGradient function. * @method * @name Konva.Context#createRadialGradient */ - Context.prototype.createRadialGradient = function (a0, a1, a2, a3, a4, a5) { + createRadialGradient(a0, a1, a2, a3, a4, a5) { return this._context.createRadialGradient(a0, a1, a2, a3, a4, a5); - }; + } /** * drawImage function. * @method * @name Konva.Context#drawImage */ - Context.prototype.drawImage = function (a0, a1, a2, a3, a4, a5, a6, a7, a8) { + drawImage(a0, a1, a2, a3, a4, a5, a6, a7, a8) { var a = arguments, _context = this._context; if (a.length === 3) { _context.drawImage(a0, a1, a2); @@ -1888,149 +1767,149 @@ else if (a.length === 9) { _context.drawImage(a0, a1, a2, a3, a4, a5, a6, a7, a8); } - }; + } /** * ellipse function. * @method * @name Konva.Context#ellipse */ - Context.prototype.ellipse = function (a0, a1, a2, a3, a4, a5, a6, a7) { + ellipse(a0, a1, a2, a3, a4, a5, a6, a7) { this._context.ellipse(a0, a1, a2, a3, a4, a5, a6, a7); - }; + } /** * isPointInPath function. * @method * @name Konva.Context#isPointInPath */ - Context.prototype.isPointInPath = function (x, y) { + isPointInPath(x, y) { return this._context.isPointInPath(x, y); - }; + } /** * fill function. * @method * @name Konva.Context#fill */ - Context.prototype.fill = function () { + fill() { this._context.fill(); - }; + } /** * fillRect function. * @method * @name Konva.Context#fillRect */ - Context.prototype.fillRect = function (x, y, width, height) { + fillRect(x, y, width, height) { this._context.fillRect(x, y, width, height); - }; + } /** * strokeRect function. * @method * @name Konva.Context#strokeRect */ - Context.prototype.strokeRect = function (x, y, width, height) { + strokeRect(x, y, width, height) { this._context.strokeRect(x, y, width, height); - }; + } /** * fillText function. * @method * @name Konva.Context#fillText */ - Context.prototype.fillText = function (a0, a1, a2) { + fillText(a0, a1, a2) { this._context.fillText(a0, a1, a2); - }; + } /** * measureText function. * @method * @name Konva.Context#measureText */ - Context.prototype.measureText = function (text) { + measureText(text) { return this._context.measureText(text); - }; + } /** * getImageData function. * @method * @name Konva.Context#getImageData */ - Context.prototype.getImageData = function (a0, a1, a2, a3) { + getImageData(a0, a1, a2, a3) { return this._context.getImageData(a0, a1, a2, a3); - }; + } /** * lineTo function. * @method * @name Konva.Context#lineTo */ - Context.prototype.lineTo = function (a0, a1) { + lineTo(a0, a1) { this._context.lineTo(a0, a1); - }; + } /** * moveTo function. * @method * @name Konva.Context#moveTo */ - Context.prototype.moveTo = function (a0, a1) { + moveTo(a0, a1) { this._context.moveTo(a0, a1); - }; + } /** * rect function. * @method * @name Konva.Context#rect */ - Context.prototype.rect = function (a0, a1, a2, a3) { + rect(a0, a1, a2, a3) { this._context.rect(a0, a1, a2, a3); - }; + } /** * putImageData function. * @method * @name Konva.Context#putImageData */ - Context.prototype.putImageData = function (a0, a1, a2) { + putImageData(a0, a1, a2) { this._context.putImageData(a0, a1, a2); - }; + } /** * quadraticCurveTo function. * @method * @name Konva.Context#quadraticCurveTo */ - Context.prototype.quadraticCurveTo = function (a0, a1, a2, a3) { + quadraticCurveTo(a0, a1, a2, a3) { this._context.quadraticCurveTo(a0, a1, a2, a3); - }; + } /** * restore function. * @method * @name Konva.Context#restore */ - Context.prototype.restore = function () { + restore() { this._context.restore(); - }; + } /** * rotate function. * @method * @name Konva.Context#rotate */ - Context.prototype.rotate = function (a0) { + rotate(a0) { this._context.rotate(a0); - }; + } /** * save function. * @method * @name Konva.Context#save */ - Context.prototype.save = function () { + save() { this._context.save(); - }; + } /** * scale function. * @method * @name Konva.Context#scale */ - Context.prototype.scale = function (a0, a1) { + scale(a0, a1) { this._context.scale(a0, a1); - }; + } /** * setLineDash function. * @method * @name Konva.Context#setLineDash */ - Context.prototype.setLineDash = function (a0) { + setLineDash(a0) { // works for Chrome and IE11 if (this._context.setLineDash) { this._context.setLineDash(a0); @@ -2044,62 +1923,62 @@ this._context['webkitLineDash'] = a0; } // no support for IE9 and IE10 - }; + } /** * getLineDash function. * @method * @name Konva.Context#getLineDash */ - Context.prototype.getLineDash = function () { + getLineDash() { return this._context.getLineDash(); - }; + } /** * setTransform function. * @method * @name Konva.Context#setTransform */ - Context.prototype.setTransform = function (a0, a1, a2, a3, a4, a5) { + setTransform(a0, a1, a2, a3, a4, a5) { this._context.setTransform(a0, a1, a2, a3, a4, a5); - }; + } /** * stroke function. * @method * @name Konva.Context#stroke */ - Context.prototype.stroke = function () { + stroke() { this._context.stroke(); - }; + } /** * strokeText function. * @method * @name Konva.Context#strokeText */ - Context.prototype.strokeText = function (a0, a1, a2, a3) { + strokeText(a0, a1, a2, a3) { this._context.strokeText(a0, a1, a2, a3); - }; + } /** * transform function. * @method * @name Konva.Context#transform */ - Context.prototype.transform = function (a0, a1, a2, a3, a4, a5) { + transform(a0, a1, a2, a3, a4, a5) { this._context.transform(a0, a1, a2, a3, a4, a5); - }; + } /** * translate function. * @method * @name Konva.Context#translate */ - Context.prototype.translate = function (a0, a1) { + translate(a0, a1) { this._context.translate(a0, a1); - }; - Context.prototype._enableTrace = function () { - var that = this, len = CONTEXT_METHODS.length, _simplifyArray = Util._simplifyArray, origSetter = this.setAttr, n, args; + } + _enableTrace() { + var 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], ret; that[methodName] = function () { - args = _simplifyArray(Array.prototype.slice.call(arguments, 0)); + args = Util._simplifyArray(Array.prototype.slice.call(arguments, 0)); ret = origMethod.apply(that, arguments); that._trace({ method: methodName, @@ -2127,37 +2006,32 @@ val: val, }); }; - }; - Context.prototype._applyGlobalCompositeOperation = function (node) { + } + _applyGlobalCompositeOperation(node) { var globalCompositeOperation = node.getGlobalCompositeOperation(); if (globalCompositeOperation !== 'source-over') { this.setAttr('globalCompositeOperation', globalCompositeOperation); } - }; - return Context; - }()); + } + } CONTEXT_PROPERTIES.forEach(function (prop) { Object.defineProperty(Context.prototype, prop, { - get: function () { + get() { return this._context[prop]; }, - set: function (val) { + set(val) { this._context[prop] = val; }, }); }); - var SceneContext = /** @class */ (function (_super) { - __extends(SceneContext, _super); - function SceneContext() { - return _super !== null && _super.apply(this, arguments) || this; - } - SceneContext.prototype._fillColor = function (shape) { + class SceneContext extends Context { + _fillColor(shape) { var fill = shape.fill(); this.setAttr('fillStyle', fill); shape._fillFunc(this); - }; - SceneContext.prototype._fillPattern = function (shape) { - var fillPatternX = shape.getFillPatternX(), fillPatternY = shape.getFillPatternY(), fillPatternRotation = Konva.getAngle(shape.getFillPatternRotation()), fillPatternOffsetX = shape.getFillPatternOffsetX(), fillPatternOffsetY = shape.getFillPatternOffsetY(); shape.getFillPatternScaleX(); shape.getFillPatternScaleY(); + } + _fillPattern(shape) { + var fillPatternX = shape.getFillPatternX(), fillPatternY = shape.getFillPatternY(), fillPatternRotation = Konva$2.getAngle(shape.getFillPatternRotation()), fillPatternOffsetX = shape.getFillPatternOffsetX(), fillPatternOffsetY = shape.getFillPatternOffsetY(); shape.getFillPatternScaleX(); shape.getFillPatternScaleY(); if (fillPatternX || fillPatternY) { this.translate(fillPatternX || 0, fillPatternY || 0); } @@ -2169,22 +2043,22 @@ } this.setAttr('fillStyle', shape._getFillPattern()); shape._fillFunc(this); - }; - SceneContext.prototype._fillLinearGradient = function (shape) { + } + _fillLinearGradient(shape) { var grd = shape._getLinearGradient(); if (grd) { this.setAttr('fillStyle', grd); shape._fillFunc(this); } - }; - SceneContext.prototype._fillRadialGradient = function (shape) { + } + _fillRadialGradient(shape) { var grd = shape._getRadialGradient(); if (grd) { this.setAttr('fillStyle', grd); shape._fillFunc(this); } - }; - SceneContext.prototype._fill = function (shape) { + } + _fill(shape) { var hasColor = shape.fill(), fillPriority = shape.getFillPriority(); // priority fills if (hasColor && fillPriority === 'color') { @@ -2219,8 +2093,8 @@ else if (hasRadialGradient) { this._fillRadialGradient(shape); } - }; - SceneContext.prototype._strokeLinearGradient = function (shape) { + } + _strokeLinearGradient(shape) { var start = shape.getStrokeLinearGradientStartPoint(), end = shape.getStrokeLinearGradientEndPoint(), colorStops = shape.getStrokeLinearGradientColorStops(), grd = this.createLinearGradient(start.x, start.y, end.x, end.y); if (colorStops) { // build color stops @@ -2229,8 +2103,8 @@ } this.setAttr('strokeStyle', grd); } - }; - SceneContext.prototype._stroke = function (shape) { + } + _stroke(shape) { var dash = shape.dash(), // ignore strokeScaleEnabled for Text strokeScaleEnabled = shape.getStrokeScaleEnabled(); @@ -2261,8 +2135,8 @@ this.restore(); } } - }; - SceneContext.prototype._applyShadow = function (shape) { + } + _applyShadow(shape) { var util = Util, color = util.get(shape.getShadowRGBA(), 'black'), blur = util.get(shape.getShadowBlur(), 5), offset = util.get(shape.getShadowOffset(), { x: 0, y: 0, @@ -2271,26 +2145,21 @@ this.setAttr('shadowBlur', blur * Math.min(Math.abs(scaleX), Math.abs(scaleY))); this.setAttr('shadowOffsetX', offset.x * scaleX); this.setAttr('shadowOffsetY', offset.y * scaleY); - }; - return SceneContext; - }(Context)); - var HitContext = /** @class */ (function (_super) { - __extends(HitContext, _super); - function HitContext() { - return _super !== null && _super.apply(this, arguments) || this; } - HitContext.prototype._fill = function (shape) { + } + class HitContext extends Context { + _fill(shape) { this.save(); this.setAttr('fillStyle', shape.colorKey); shape._fillFuncHit(this); this.restore(); - }; - HitContext.prototype.strokeShape = function (shape) { + } + strokeShape(shape) { if (shape.hasHitStroke()) { this._stroke(shape); } - }; - HitContext.prototype._stroke = function (shape) { + } + _stroke(shape) { if (shape.hasHitStroke()) { // ignore strokeScaleEnabled for Text var strokeScaleEnabled = shape.getStrokeScaleEnabled(); @@ -2309,9 +2178,8 @@ this.restore(); } } - }; - return HitContext; - }(Context)); + } + } // calculate pixel ratio var _pixelRatio; @@ -2322,7 +2190,7 @@ var canvas = Util.createCanvasElement(); var context = canvas.getContext('2d'); _pixelRatio = (function () { - var devicePixelRatio = Konva._global.devicePixelRatio || 1, backingStoreRatio = context.webkitBackingStorePixelRatio || + var devicePixelRatio = Konva$2._global.devicePixelRatio || 1, backingStoreRatio = context.webkitBackingStorePixelRatio || context.mozBackingStorePixelRatio || context.msBackingStorePixelRatio || context.oBackingStorePixelRatio || @@ -2343,14 +2211,14 @@ * @param {Number} config.height * @param {Number} config.pixelRatio */ - var Canvas = /** @class */ (function () { - function Canvas(config) { + class Canvas { + constructor(config) { this.pixelRatio = 1; this.width = 0; this.height = 0; this.isCache = false; var conf = config || {}; - var pixelRatio = conf.pixelRatio || Konva.pixelRatio || getDevicePixelRatio(); + var pixelRatio = conf.pixelRatio || Konva$2.pixelRatio || getDevicePixelRatio(); this.pixelRatio = pixelRatio; this._canvas = Util.createCanvasElement(); // set inline styles @@ -2368,41 +2236,41 @@ * @name Konva.Canvas#getContext * @returns {CanvasContext} context */ - Canvas.prototype.getContext = function () { + getContext() { return this.context; - }; - Canvas.prototype.getPixelRatio = function () { + } + getPixelRatio() { return this.pixelRatio; - }; - Canvas.prototype.setPixelRatio = function (pixelRatio) { + } + setPixelRatio(pixelRatio) { var previousRatio = this.pixelRatio; this.pixelRatio = pixelRatio; this.setSize(this.getWidth() / previousRatio, this.getHeight() / previousRatio); - }; - Canvas.prototype.setWidth = function (width) { + } + setWidth(width) { // take into account pixel ratio this.width = this._canvas.width = width * this.pixelRatio; this._canvas.style.width = width + 'px'; var pixelRatio = this.pixelRatio, _context = this.getContext()._context; _context.scale(pixelRatio, pixelRatio); - }; - Canvas.prototype.setHeight = function (height) { + } + setHeight(height) { // take into account pixel ratio this.height = this._canvas.height = height * this.pixelRatio; this._canvas.style.height = height + 'px'; var pixelRatio = this.pixelRatio, _context = this.getContext()._context; _context.scale(pixelRatio, pixelRatio); - }; - Canvas.prototype.getWidth = function () { + } + getWidth() { return this.width; - }; - Canvas.prototype.getHeight = function () { + } + getHeight() { return this.height; - }; - Canvas.prototype.setSize = function (width, height) { + } + setSize(width, height) { this.setWidth(width || 0); this.setHeight(height || 0); - }; + } /** * to data url * @method @@ -2411,7 +2279,7 @@ * @param {Number} quality between 0 and 1 for jpg mime types * @returns {String} data url string */ - Canvas.prototype.toDataURL = function (mimeType, quality) { + toDataURL(mimeType, quality) { try { // If this call fails (due to browser bug, like in Firefox 3.6), // then revert to previous no-parameter image/png behavior @@ -2428,9 +2296,8 @@ return ''; } } - }; - return Canvas; - }()); + } + } /** * get/set pixel ratio. * KonvaJS automatically handles pixel ratio adustments in order to render crisp drawings @@ -2452,34 +2319,26 @@ * layer.getCanvas().pixelRatio(3); */ Factory.addGetterSetter(Canvas, 'pixelRatio', undefined, getNumberValidator()); - var SceneCanvas = /** @class */ (function (_super) { - __extends(SceneCanvas, _super); - function SceneCanvas(config) { - if (config === void 0) { config = { width: 0, height: 0 }; } - var _this = _super.call(this, config) || this; - _this.context = new SceneContext(_this); - _this.setSize(config.width, config.height); - return _this; + class SceneCanvas extends Canvas { + constructor(config = { width: 0, height: 0 }) { + super(config); + this.context = new SceneContext(this); + this.setSize(config.width, config.height); } - return SceneCanvas; - }(Canvas)); - var HitCanvas = /** @class */ (function (_super) { - __extends(HitCanvas, _super); - function HitCanvas(config) { - if (config === void 0) { config = { width: 0, height: 0 }; } - var _this = _super.call(this, config) || this; - _this.hitCanvas = true; - _this.context = new HitContext(_this); - _this.setSize(config.width, config.height); - return _this; + } + class HitCanvas extends Canvas { + constructor(config = { width: 0, height: 0 }) { + super(config); + this.hitCanvas = true; + this.context = new HitContext(this); + this.setSize(config.width, config.height); } - return HitCanvas; - }(Canvas)); + } - var DD = { + const DD = { get isDragging() { var flag = false; - DD._dragElements.forEach(function (elem) { + DD._dragElements.forEach((elem) => { if (elem.dragStatus === 'dragging') { flag = true; } @@ -2490,26 +2349,26 @@ get node() { // return first dragging node var node; - DD._dragElements.forEach(function (elem) { + DD._dragElements.forEach((elem) => { node = elem.node; }); return node; }, _dragElements: new Map(), // methods - _drag: function (evt) { - var nodesToFireEvents = []; - DD._dragElements.forEach(function (elem, key) { - var node = elem.node; + _drag(evt) { + const nodesToFireEvents = []; + DD._dragElements.forEach((elem, key) => { + const { node } = elem; // we need to find pointer relative to that node - var stage = node.getStage(); + const stage = node.getStage(); stage.setPointersPositions(evt); // it is possible that user call startDrag without any event // it that case we need to detect first movable pointer and attach it into the node if (elem.pointerId === undefined) { elem.pointerId = Util._getFirstPointerId(evt); } - var pos = stage._changedPointerPositions.find(function (pos) { return pos.id === elem.pointerId; }); + const pos = stage._changedPointerPositions.find((pos) => pos.id === elem.pointerId); // not related pointer if (!pos) { return; @@ -2520,7 +2379,7 @@ if (distance < dragDistance) { return; } - node.startDrag({ evt: evt }); + node.startDrag({ evt }); // a user can stop dragging inside `dragstart` if (!node.isDragging()) { return; @@ -2530,7 +2389,7 @@ nodesToFireEvents.push(node); }); // call dragmove only after ALL positions are changed - nodesToFireEvents.forEach(function (node) { + nodesToFireEvents.forEach((node) => { node.fire('dragmove', { type: 'dragmove', target: node, @@ -2540,15 +2399,15 @@ }, // dragBefore and dragAfter allows us to set correct order of events // setup all in dragbefore, and stop dragging only after pointerup triggered. - _endDragBefore: function (evt) { - DD._dragElements.forEach(function (elem, key) { - var node = elem.node; + _endDragBefore(evt) { + DD._dragElements.forEach((elem, key) => { + const { node } = elem; // we need to find pointer relative to that node - var stage = node.getStage(); + const stage = node.getStage(); if (evt) { stage.setPointersPositions(evt); } - var pos = stage._changedPointerPositions.find(function (pos) { return pos.id === elem.pointerId; }); + const pos = stage._changedPointerPositions.find((pos) => pos.id === elem.pointerId); // that pointer is not related if (!pos) { return; @@ -2556,18 +2415,18 @@ if (elem.dragStatus === 'dragging' || elem.dragStatus === 'stopped') { // if a node is stopped manully we still need to reset events: DD.justDragged = true; - Konva.listenClickTap = false; + Konva$2.listenClickTap = false; elem.dragStatus = 'stopped'; } - var drawNode = elem.node.getLayer() || - (elem.node instanceof Konva['Stage'] && elem.node); + const drawNode = elem.node.getLayer() || + (elem.node instanceof Konva$2['Stage'] && elem.node); if (drawNode) { drawNode.batchDraw(); } }); }, - _endDragAfter: function (evt) { - DD._dragElements.forEach(function (elem, key) { + _endDragAfter(evt) { + DD._dragElements.forEach((elem, key) => { if (elem.dragStatus === 'stopped') { elem.node.fire('dragend', { type: 'dragend', @@ -2581,7 +2440,7 @@ }); }, }; - if (Konva.isBrowser) { + if (Konva$2.isBrowser) { window.addEventListener('mouseup', DD._endDragBefore, true); window.addEventListener('touchend', DD._endDragBefore, true); window.addEventListener('mousemove', DD._drag); @@ -2590,15 +2449,15 @@ window.addEventListener('touchend', DD._endDragAfter, false); } - var ids = {}; - var names = {}; - var _addId = function (node, id) { + const ids = {}; + const names = {}; + const _addId = function (node, id) { if (!id) { return; } ids[id] = node; }; - var _removeId = function (id, node) { + const _removeId = function (id, node) { // node has no id if (!id) { return; @@ -2609,7 +2468,7 @@ } delete ids[id]; }; - var _addName = function (node, name) { + const _addName = function (node, name) { if (name) { if (!names[name]) { names[name] = []; @@ -2617,7 +2476,7 @@ names[name].push(node); } }; - var _removeName = function (name, _id) { + const _removeName = function (name, _id) { if (!name) { return; } @@ -2636,7 +2495,7 @@ } }; // CONSTANTS - var ABSOLUTE_OPACITY = 'absoluteOpacity', ALL_LISTENERS = 'allEventListeners', ABSOLUTE_TRANSFORM = 'absoluteTransform', ABSOLUTE_SCALE = 'absoluteScale', CANVAS = 'canvas', CHANGE = 'Change', CHILDREN = 'children', KONVA = 'konva', LISTENING = 'listening', MOUSEENTER = 'mouseenter', MOUSELEAVE = 'mouseleave', NAME = 'name', SET$1 = 'set', SHAPE = 'Shape', SPACE = ' ', STAGE = 'stage', TRANSFORM = 'transform', UPPER_STAGE = 'Stage', VISIBLE = 'visible', TRANSFORM_CHANGE_STR = [ + var ABSOLUTE_OPACITY = 'absoluteOpacity', ALL_LISTENERS = 'allEventListeners', ABSOLUTE_TRANSFORM = 'absoluteTransform', ABSOLUTE_SCALE = 'absoluteScale', CANVAS = 'canvas', CHANGE = 'Change', CHILDREN = 'children', KONVA = 'konva', LISTENING = 'listening', MOUSEENTER$1 = 'mouseenter', MOUSELEAVE$1 = 'mouseleave', NAME = 'name', SET = 'set', SHAPE = 'Shape', SPACE$1 = ' ', STAGE$1 = 'stage', TRANSFORM = 'transform', UPPER_STAGE = 'Stage', VISIBLE = 'visible', TRANSFORM_CHANGE_STR$1 = [ 'xChange.konva', 'yChange.konva', 'scaleXChange.konva', @@ -2647,10 +2506,10 @@ 'offsetXChange.konva', 'offsetYChange.konva', 'transformsEnabledChange.konva', - ].join(SPACE); + ].join(SPACE$1); // TODO: can we remove children from node? - var emptyChildren = new Collection(); - var idCounter = 1; + const emptyChildren = []; + let idCounter$1 = 1; /** * Node constructor. Nodes are entities that can be transformed, layered, * and have bound events. The stage, layers, groups, and shapes all extend Node. @@ -2678,9 +2537,9 @@ * @param {Number} [config.dragDistance] * @param {Function} [config.dragBoundFunc] */ - var Node = /** @class */ (function () { - function Node(config) { - this._id = idCounter++; + class Node { + constructor(config) { + this._id = idCounter$1++; this.eventListeners = {}; this.attrs = {}; this.index = 0; @@ -2693,7 +2552,6 @@ this._needClearTransformCache = false; this._filterUpToDate = false; this._isUnderCache = false; - this.children = emptyChildren; this._dragEventId = null; this._shouldFireChangeEvents = false; // on initial set attrs wi don't need to fire change events @@ -2702,13 +2560,13 @@ this._shouldFireChangeEvents = true; // all change event listeners are attached to the prototype } - Node.prototype.hasChildren = function () { + hasChildren() { return false; - }; - Node.prototype.getChildren = function () { + } + getChildren() { return emptyChildren; - }; - Node.prototype._clearCache = function (attr) { + } + _clearCache(attr) { // if we want to clear transform cache // we don't really need to remove it from the cache // but instead mark as "dirty" @@ -2723,8 +2581,8 @@ else { this._cache.clear(); } - }; - Node.prototype._getCache = function (attr, privateGetter) { + } + _getCache(attr, privateGetter) { var cache = this._cache.get(attr); // for transform the cache can be NOT empty // but we still need to recalculate it if it is dirty @@ -2736,45 +2594,34 @@ this._cache.set(attr, cache); } return cache; - }; - Node.prototype._calculate = function (name, deps, getter) { - var _this = this; + } + _calculate(name, deps, getter) { // if we are trying to calculate function for the first time // we need to attach listeners for change events if (!this._attachedDepsListeners.get(name)) { - var depsString = deps.map(function (dep) { return dep + 'Change.konva'; }).join(SPACE); - this.on(depsString, function () { - _this._clearCache(name); + const depsString = deps.map((dep) => dep + 'Change.konva').join(SPACE$1); + this.on(depsString, () => { + this._clearCache(name); }); this._attachedDepsListeners.set(name, true); } // just use cache function return this._getCache(name, getter); - }; - Node.prototype._getCanvasCache = function () { + } + _getCanvasCache() { return this._cache.get(CANVAS); - }; + } /* * when the logic for a cached result depends on ancestor propagation, use this * method to clear self and children cache */ - Node.prototype._clearSelfAndDescendantCache = function (attr, forceEvent) { + _clearSelfAndDescendantCache(attr, forceEvent) { this._clearCache(attr); // trigger clear cache, so transformer can use it if (forceEvent && attr === ABSOLUTE_TRANSFORM) { this.fire('_clearTransformCache'); } - // skip clearing if node is cached with canvas - // for performance reasons !!! - if (this.isCached()) { - return; - } - if (this.children) { - this.children.each(function (node) { - node._clearSelfAndDescendantCache(attr, true); - }); - } - }; + } /** * clear cached canvas * @method @@ -2783,11 +2630,11 @@ * @example * node.clearCache(); */ - Node.prototype.clearCache = function () { + clearCache() { this._cache.delete(CANVAS); this._clearSelfAndDescendantCache(); return this; - }; + } /** * cache node to improve drawing performance, apply filters, or create more accurate * hit regions. For all basic shapes size of cache canvas will be automatically detected. @@ -2831,7 +2678,7 @@ * drawBorder: true * }); */ - Node.prototype.cache = function (config) { + cache(config) { var conf = config || {}; var rect = {}; // don't call getClientRect if we have all attributes @@ -2908,16 +2755,16 @@ y: y, }); return this; - }; + } /** * determine if node is currently cached * @method * @name Konva.Node#isCached * @returns {Boolean} */ - Node.prototype.isCached = function () { + isCached() { return this._cache.has('canvas'); - }; + } /** * Return client rectangle {x, y, width, height} of node. This rectangle also include all styling (strokes, shadows, etc). * The purpose of the method is similar to getBoundingClientRect API of the DOM. @@ -2954,12 +2801,12 @@ * rect.getClientRect(); * // returns Object {x: -2, y: 46, width: 104, height: 208} */ - Node.prototype.getClientRect = function (config) { + getClientRect(config) { // abstract method // redefine in Container and Shape throw new Error('abstract "getClientRect" method call'); - }; - Node.prototype._transformedRect = function (rect, top) { + } + _transformedRect(rect, top) { var points = [ { x: rect.x, y: rect.y }, { x: rect.x + rect.width, y: rect.y }, @@ -2985,26 +2832,26 @@ width: maxX - minX, height: maxY - minY, }; - }; - Node.prototype._drawCachedSceneCanvas = function (context) { + } + _drawCachedSceneCanvas(context) { context.save(); context._applyOpacity(this); context._applyGlobalCompositeOperation(this); - var canvasCache = this._getCanvasCache(); + const canvasCache = this._getCanvasCache(); context.translate(canvasCache.x, canvasCache.y); var cacheCanvas = this._getCachedSceneCanvas(); var ratio = cacheCanvas.pixelRatio; context.drawImage(cacheCanvas._canvas, 0, 0, cacheCanvas.width / ratio, cacheCanvas.height / ratio); context.restore(); - }; - Node.prototype._drawCachedHitCanvas = function (context) { + } + _drawCachedHitCanvas(context) { var canvasCache = this._getCanvasCache(), hitCanvas = canvasCache.hit; context.save(); context.translate(canvasCache.x, canvasCache.y); context.drawImage(hitCanvas._canvas, 0, 0); context.restore(); - }; - Node.prototype._getCachedSceneCanvas = function () { + } + _getCachedSceneCanvas() { var filters = this.filters(), cachedCanvas = this._getCanvasCache(), sceneCanvas = cachedCanvas.scene, filterCanvas = cachedCanvas.filter, filterContext = filterCanvas.getContext(), len, imageData, n, filter; if (filters) { if (!this._filterUpToDate) { @@ -3039,7 +2886,7 @@ return filterCanvas; } return sceneCanvas; - }; + } /** * bind events to the node. KonvaJS supports mouseover, mousemove, * mouseout, mouseenter, mouseleave, mousedown, mouseup, wheel, contextmenu, click, dblclick, touchstart, touchmove, @@ -3101,12 +2948,12 @@ * var group = evt.currentTarget; * }); */ - Node.prototype.on = function (evtStr, handler) { + on(evtStr, handler) { this._cache && this._cache.delete(ALL_LISTENERS); if (arguments.length === 3) { return this._delegate.apply(this, arguments); } - var events = evtStr.split(SPACE), len = events.length, n, event, parts, baseEvent, name; + var events = evtStr.split(SPACE$1), len = events.length, n, event, parts, baseEvent, name; /* * loop through types and attach event listeners to * each one. eg. 'click mouseover.namespace mouseout' @@ -3127,7 +2974,7 @@ }); } return this; - }; + } /** * remove event bindings from the node. Pass in a string of * event types delimmited by a space to remove multiple event @@ -3149,8 +2996,8 @@ * // remove listener by name * node.off('click.foo'); */ - Node.prototype.off = function (evtStr, callback) { - var events = (evtStr || '').split(SPACE), len = events.length, n, t, event, parts, baseEvent, name; + off(evtStr, callback) { + var events = (evtStr || '').split(SPACE$1), len = events.length, n, t, event, parts, baseEvent, name; this._cache && this._cache.delete(ALL_LISTENERS); if (!evtStr) { // remove all events @@ -3175,9 +3022,9 @@ } } return this; - }; + } // some event aliases for third party integration like HammerJS - Node.prototype.dispatchEvent = function (evt) { + dispatchEvent(evt) { var e = { target: this, type: evt.type, @@ -3185,20 +3032,20 @@ }; this.fire(evt.type, e); return this; - }; - Node.prototype.addEventListener = function (type, handler) { + } + addEventListener(type, handler) { // we have to pass native event to handler this.on(type, function (evt) { handler.call(this, evt.evt); }); return this; - }; - Node.prototype.removeEventListener = function (type) { + } + removeEventListener(type) { this.off(type); return this; - }; + } // like node.on - Node.prototype._delegate = function (event, selector, handler) { + _delegate(event, selector, handler) { var stopNode = this; this.on(event, function (evt) { var targets = evt.target.findAncestors(selector, true, stopNode); @@ -3208,7 +3055,7 @@ handler.call(targets[i], evt); } }); - }; + } /** * remove a node from parent, but don't destroy. You can reuse the node later. * @method @@ -3217,7 +3064,7 @@ * @example * node.remove(); */ - Node.prototype.remove = function () { + remove() { if (this.isDragging()) { this.stopDrag(); } @@ -3226,16 +3073,16 @@ DD._dragElements.delete(this._id); this._remove(); return this; - }; - Node.prototype._clearCaches = function () { + } + _clearCaches() { this._clearSelfAndDescendantCache(ABSOLUTE_TRANSFORM); this._clearSelfAndDescendantCache(ABSOLUTE_OPACITY); this._clearSelfAndDescendantCache(ABSOLUTE_SCALE); - this._clearSelfAndDescendantCache(STAGE); + this._clearSelfAndDescendantCache(STAGE$1); this._clearSelfAndDescendantCache(VISIBLE); this._clearSelfAndDescendantCache(LISTENING); - }; - Node.prototype._remove = function () { + } + _remove() { // every cached attr that is calculated via node tree // traversal must be cleared when removing a node this._clearCaches(); @@ -3245,7 +3092,7 @@ parent._setChildrenIndices(); this.parent = null; } - }; + } /** * remove and destroy a node. Kill it and delete forever! You should not reuse node after destroy(). * If the node is a container (Group, Stage or Layer) it will destroy all children too. @@ -3254,7 +3101,7 @@ * @example * node.destroy(); */ - Node.prototype.destroy = function () { + destroy() { // remove from ids and names hashes _removeId(this.id(), this); // remove all names @@ -3265,7 +3112,7 @@ } this.remove(); return this; - }; + } /** * get attr * @method @@ -3275,41 +3122,41 @@ * @example * var x = node.getAttr('x'); */ - Node.prototype.getAttr = function (attr) { + getAttr(attr) { var method = 'get' + Util._capitalize(attr); if (Util._isFunction(this[method])) { return this[method](); } // otherwise get directly return this.attrs[attr]; - }; + } /** * get ancestors * @method * @name Konva.Node#getAncestors - * @returns {Konva.Collection} + * @returns {Array} * @example - * shape.getAncestors().each(function(node) { + * shape.getAncestors().forEach(function(node) { * console.log(node.getId()); * }) */ - Node.prototype.getAncestors = function () { - var parent = this.getParent(), ancestors = new Collection(); + getAncestors() { + var parent = this.getParent(), ancestors = []; while (parent) { ancestors.push(parent); parent = parent.getParent(); } return ancestors; - }; + } /** * get attrs object literal * @method * @name Konva.Node#getAttrs * @returns {Object} */ - Node.prototype.getAttrs = function () { + getAttrs() { return this.attrs || {}; - }; + } /** * set multiple attrs at once using an object literal * @method @@ -3322,30 +3169,29 @@ * fill: 'red' * }); */ - Node.prototype.setAttrs = function (config) { - var _this = this; - this._batchTransformChanges(function () { + setAttrs(config) { + this._batchTransformChanges(() => { var key, method; if (!config) { - return _this; + return this; } for (key in config) { if (key === CHILDREN) { continue; } - method = SET$1 + Util._capitalize(key); + method = SET + Util._capitalize(key); // use setter if available - if (Util._isFunction(_this[method])) { - _this[method](config[key]); + if (Util._isFunction(this[method])) { + this[method](config[key]); } else { // otherwise set directly - _this._setAttr(key, config[key]); + this._setAttr(key, config[key]); } } }); return this; - }; + } /** * determine if node is listening for events by taking into account ancestors. * @@ -3361,22 +3207,22 @@ * @name Konva.Node#isListening * @returns {Boolean} */ - Node.prototype.isListening = function () { + isListening() { return this._getCache(LISTENING, this._isListening); - }; - Node.prototype._isListening = function (relativeTo) { - var listening = this.listening(); + } + _isListening(relativeTo) { + const listening = this.listening(); if (!listening) { return false; } - var parent = this.getParent(); + const parent = this.getParent(); if (parent && parent !== relativeTo && this !== relativeTo) { return parent._isListening(relativeTo); } else { return true; } - }; + } /** * determine if node is visible by taking into account ancestors. * @@ -3391,30 +3237,29 @@ * @name Konva.Node#isVisible * @returns {Boolean} */ - Node.prototype.isVisible = function () { + isVisible() { return this._getCache(VISIBLE, this._isVisible); - }; - Node.prototype._isVisible = function (relativeTo) { - var visible = this.visible(); + } + _isVisible(relativeTo) { + const visible = this.visible(); if (!visible) { return false; } - var parent = this.getParent(); + const parent = this.getParent(); if (parent && parent !== relativeTo && this !== relativeTo) { return parent._isVisible(relativeTo); } else { return true; } - }; - Node.prototype.shouldDrawHit = function (top, skipDragCheck) { - if (skipDragCheck === void 0) { skipDragCheck = false; } + } + shouldDrawHit(top, skipDragCheck = false) { if (top) { return this._isVisible(top) && this._isListening(top); } var layer = this.getLayer(); var layerUnderDrag = false; - DD._dragElements.forEach(function (elem) { + DD._dragElements.forEach((elem) => { if (elem.dragStatus !== 'dragging') { return; } @@ -3425,32 +3270,32 @@ layerUnderDrag = true; } }); - var dragSkip = !skipDragCheck && !Konva.hitOnDragEnabled && layerUnderDrag; + var dragSkip = !skipDragCheck && !Konva$2.hitOnDragEnabled && layerUnderDrag; return this.isListening() && this.isVisible() && !dragSkip; - }; + } /** * show node. set visible = true * @method * @name Konva.Node#show * @returns {Konva.Node} */ - Node.prototype.show = function () { + show() { this.visible(true); return this; - }; + } /** * hide node. Hidden nodes are no longer detectable * @method * @name Konva.Node#hide * @returns {Konva.Node} */ - Node.prototype.hide = function () { + hide() { this.visible(false); return this; - }; - Node.prototype.getZIndex = function () { + } + getZIndex() { return this.index || 0; - }; + } /** * get absolute z-index which takes into account sibling * and ancestor indices @@ -3458,7 +3303,7 @@ * @name Konva.Node#getAbsoluteZIndex * @returns {Integer} */ - Node.prototype.getAbsoluteZIndex = function () { + getAbsoluteZIndex() { var depth = this.getDepth(), that = this, index = 0, nodes, len, n, child; function addChildren(children) { nodes = []; @@ -3467,7 +3312,7 @@ child = children[n]; index++; if (child.nodeType !== SHAPE) { - nodes = nodes.concat(child.getChildren().toArray()); + nodes = nodes.concat(child.getChildren().slice()); } if (child._id === that._id) { n = len; @@ -3481,7 +3326,7 @@ addChildren(that.getStage().getChildren()); } return index; - }; + } /** * get node depth in node tree. Returns an integer. * e.g. Stage depth will always be 0. Layers will always be 1. Groups and Shapes will always @@ -3490,19 +3335,19 @@ * @name Konva.Node#getDepth * @returns {Integer} */ - Node.prototype.getDepth = function () { + getDepth() { var depth = 0, parent = this.parent; while (parent) { depth++; parent = parent.parent; } return depth; - }; + } // sometimes we do several attributes changes // like node.position(pos) // for performance reasons, lets batch transform reset // so it work faster - Node.prototype._batchTransformChanges = function (func) { + _batchTransformChanges(func) { this._batchingTransformChange = true; func(); this._batchingTransformChange = false; @@ -3511,21 +3356,20 @@ this._clearSelfAndDescendantCache(ABSOLUTE_TRANSFORM, true); } this._needClearTransformCache = false; - }; - Node.prototype.setPosition = function (pos) { - var _this = this; - this._batchTransformChanges(function () { - _this.x(pos.x); - _this.y(pos.y); + } + setPosition(pos) { + this._batchTransformChanges(() => { + this.x(pos.x); + this.y(pos.y); }); return this; - }; - Node.prototype.getPosition = function () { + } + getPosition() { return { x: this.x(), y: this.y(), }; - }; + } /** * get absolute position of a node. That function can be used to calculate absolute position, but relative to any ancestor * @method @@ -3541,9 +3385,9 @@ * // so stage transforms are ignored * node.getAbsolutePosition(stage) */ - Node.prototype.getAbsolutePosition = function (top) { - var haveCachedParent = false; - var parent = this.parent; + getAbsolutePosition(top) { + let haveCachedParent = false; + let parent = this.parent; while (parent) { if (parent.isCached()) { haveCachedParent = true; @@ -3561,8 +3405,8 @@ absoluteTransform.m = absoluteMatrix.slice(); absoluteTransform.translate(offset.x, offset.y); return absoluteTransform.getTranslation(); - }; - Node.prototype.setAbsolutePosition = function (pos) { + } + setAbsolutePosition(pos) { var origTrans = this._clearTransform(); // don't clear translation this.attrs.x = origTrans.x; @@ -3583,16 +3427,16 @@ this._clearCache(TRANSFORM); this._clearSelfAndDescendantCache(ABSOLUTE_TRANSFORM); return this; - }; - Node.prototype._setTransform = function (trans) { + } + _setTransform(trans) { var key; for (key in trans) { this.attrs[key] = trans[key]; } // this._clearCache(TRANSFORM); // this._clearSelfAndDescendantCache(ABSOLUTE_TRANSFORM); - }; - Node.prototype._clearTransform = function () { + } + _clearTransform() { var trans = { x: this.x(), y: this.y(), @@ -3615,7 +3459,7 @@ this.attrs.skewY = 0; // return original transform return trans; - }; + } /** * move node by an amount relative to its current position * @method @@ -3631,7 +3475,7 @@ * y: 2 * }); */ - Node.prototype.move = function (change) { + move(change) { var changeX = change.x, changeY = change.y, x = this.x(), y = this.y(); if (changeX !== undefined) { x += changeX; @@ -3641,8 +3485,8 @@ } this.setPosition({ x: x, y: y }); return this; - }; - Node.prototype._eachAncestorReverse = function (func, top) { + } + _eachAncestorReverse(func, top) { var family = [], parent = this.getParent(), len, n; // if top node is defined, and this node is top node, // there's no need to build a family tree. just execute @@ -3660,7 +3504,7 @@ for (n = 0; n < len; n++) { func(family[n]); } - }; + } /** * rotate node by an amount in degrees relative to its current rotation * @method @@ -3668,17 +3512,17 @@ * @param {Number} theta * @returns {Konva.Node} */ - Node.prototype.rotate = function (theta) { + rotate(theta) { this.rotation(this.rotation() + theta); return this; - }; + } /** * move node to the top of its siblings * @method * @name Konva.Node#moveToTop * @returns {Boolean} */ - Node.prototype.moveToTop = function () { + moveToTop() { if (!this.parent) { Util.warn('Node has no parent. moveToTop function is ignored.'); return false; @@ -3688,14 +3532,14 @@ this.parent.children.push(this); this.parent._setChildrenIndices(); return true; - }; + } /** * move node up * @method * @name Konva.Node#moveUp * @returns {Boolean} flag is moved or not */ - Node.prototype.moveUp = function () { + moveUp() { if (!this.parent) { Util.warn('Node has no parent. moveUp function is ignored.'); return false; @@ -3708,14 +3552,14 @@ return true; } return false; - }; + } /** * move node down * @method * @name Konva.Node#moveDown * @returns {Boolean} */ - Node.prototype.moveDown = function () { + moveDown() { if (!this.parent) { Util.warn('Node has no parent. moveDown function is ignored.'); return false; @@ -3728,14 +3572,14 @@ return true; } return false; - }; + } /** * move node to the bottom of its siblings * @method * @name Konva.Node#moveToBottom * @returns {Boolean} */ - Node.prototype.moveToBottom = function () { + moveToBottom() { if (!this.parent) { Util.warn('Node has no parent. moveToBottom function is ignored.'); return false; @@ -3748,8 +3592,8 @@ return true; } return false; - }; - Node.prototype.setZIndex = function (zIndex) { + } + setZIndex(zIndex) { if (!this.parent) { Util.warn('Node has no parent. zIndex parameter is ignored.'); return this; @@ -3766,24 +3610,24 @@ this.parent.children.splice(zIndex, 0, this); this.parent._setChildrenIndices(); return this; - }; + } /** * get absolute opacity * @method * @name Konva.Node#getAbsoluteOpacity * @returns {Number} */ - Node.prototype.getAbsoluteOpacity = function () { + getAbsoluteOpacity() { return this._getCache(ABSOLUTE_OPACITY, this._getAbsoluteOpacity); - }; - Node.prototype._getAbsoluteOpacity = function () { + } + _getAbsoluteOpacity() { var absOpacity = this.opacity(); var parent = this.getParent(); if (parent && !parent._isUnderCache) { absOpacity *= parent.getAbsoluteOpacity(); } return absOpacity; - }; + } /** * move node to another container * @method @@ -3794,21 +3638,21 @@ * // move node from current layer into layer2 * node.moveTo(layer2); */ - Node.prototype.moveTo = function (newContainer) { + moveTo(newContainer) { // do nothing if new container is already parent if (this.getParent() !== newContainer) { this._remove(); newContainer.add(this); } return this; - }; + } /** * convert Node into an object for serialization. Returns an object. * @method * @name Konva.Node#toObject * @returns {Object} */ - Node.prototype.toObject = function () { + toObject() { var obj = {}, attrs = this.getAttrs(), key, val, getter, defaultValue, nonPlainObject; obj.attrs = {}; for (key in attrs) { @@ -3832,25 +3676,25 @@ } obj.className = this.getClassName(); return Util._prepareToStringify(obj); - }; + } /** * convert Node into a JSON string. Returns a JSON string. * @method * @name Konva.Node#toJSON * @returns {String} */ - Node.prototype.toJSON = function () { + toJSON() { return JSON.stringify(this.toObject()); - }; + } /** * get parent container * @method * @name Konva.Node#getParent * @returns {Konva.Node} */ - Node.prototype.getParent = function () { + getParent() { return this.parent; - }; + } /** * get all ancestors (parent then parent of the parent, etc) of the node * @method @@ -3863,7 +3707,7 @@ * // get one of the parent group * var parentGroups = node.findAncestors('Group'); */ - Node.prototype.findAncestors = function (selector, includeSelf, stopNode) { + findAncestors(selector, includeSelf, stopNode) { var res = []; if (includeSelf && this._isMatch(selector)) { res.push(this); @@ -3879,10 +3723,10 @@ ancestor = ancestor.parent; } return res; - }; - Node.prototype.isAncestorOf = function (node) { + } + isAncestorOf(node) { return false; - }; + } /** * get ancestor (parent or parent of the parent, etc) of the node that match passed selector * @method @@ -3895,11 +3739,11 @@ * // get one of the parent group * var group = node.findAncestors('.mygroup'); */ - Node.prototype.findAncestor = function (selector, includeSelf, stopNode) { + findAncestor(selector, includeSelf, stopNode) { return this.findAncestors(selector, includeSelf, stopNode)[0]; - }; + } // is current node match passed selector? - Node.prototype._isMatch = function (selector) { + _isMatch(selector) { if (!selector) { return false; } @@ -3933,27 +3777,27 @@ } } return false; - }; + } /** * get layer ancestor * @method * @name Konva.Node#getLayer * @returns {Konva.Layer} */ - Node.prototype.getLayer = function () { + getLayer() { var parent = this.getParent(); return parent ? parent.getLayer() : null; - }; + } /** * get stage ancestor * @method * @name Konva.Node#getStage * @returns {Konva.Stage} */ - Node.prototype.getStage = function () { - return this._getCache(STAGE, this._getStage); - }; - Node.prototype._getStage = function () { + getStage() { + return this._getCache(STAGE$1, this._getStage); + } + _getStage() { var parent = this.getParent(); if (parent) { return parent.getStage(); @@ -3961,7 +3805,7 @@ else { return undefined; } - }; + } /** * fire event * @method @@ -3986,8 +3830,7 @@ * // fire click event that bubbles * node.fire('click', null, true); */ - Node.prototype.fire = function (eventType, evt, bubble) { - if (evt === void 0) { evt = {}; } + fire(eventType, evt = {}, bubble) { evt.target = evt.target || this; // bubble if (bubble) { @@ -3998,7 +3841,7 @@ this._fire(eventType, evt); } return this; - }; + } /** * get absolute transform of the node which takes into * account its ancestor transforms @@ -4006,7 +3849,7 @@ * @name Konva.Node#getAbsoluteTransform * @returns {Konva.Transform} */ - Node.prototype.getAbsoluteTransform = function (top) { + getAbsoluteTransform(top) { // if using an argument, we can't cache the result. if (top) { return this._getAbsoluteTransform(top); @@ -4015,8 +3858,8 @@ // if no argument, we can cache the result return this._getCache(ABSOLUTE_TRANSFORM, this._getAbsoluteTransform); } - }; - Node.prototype._getAbsoluteTransform = function (top) { + } + _getAbsoluteTransform(top) { var at; // we we need position relative to an ancestor, we will iterate for all if (top) { @@ -4049,16 +3892,16 @@ } else if (transformsEnabled === 'position') { // use "attrs" directly, because it is a bit faster - var x = this.attrs.x || 0; - var y = this.attrs.y || 0; - var offsetX = this.attrs.offsetX || 0; - var offsetY = this.attrs.offsetY || 0; + const x = this.attrs.x || 0; + const y = this.attrs.y || 0; + const offsetX = this.attrs.offsetX || 0; + const offsetY = this.attrs.offsetY || 0; at.translate(x - offsetX, y - offsetY); } at.dirty = false; return at; } - }; + } /** * get absolute scale of the node which takes into * account its ancestor scales @@ -4069,7 +3912,7 @@ * // get absolute scale x * var scaleX = node.getAbsoluteScale().x; */ - Node.prototype.getAbsoluteScale = function (top) { + getAbsoluteScale(top) { // do not cache this calculations, // because it use cache transform // this is special logic for caching with some shapes with shadow @@ -4080,13 +3923,13 @@ } parent = parent.getParent(); } - var transform = this.getAbsoluteTransform(top); - var attrs = transform.decompose(); + const transform = this.getAbsoluteTransform(top); + const attrs = transform.decompose(); return { x: attrs.scaleX, y: attrs.scaleY, }; - }; + } /** * get absolute rotation of the node which takes into * account its ancestor rotations @@ -4097,7 +3940,7 @@ * // get absolute rotation * var rotation = node.getAbsoluteRotation(); */ - Node.prototype.getAbsoluteRotation = function () { + getAbsoluteRotation() { // var parent: Node = this; // var rotation = 0; // while (parent) { @@ -4106,24 +3949,24 @@ // } // return rotation; return this.getAbsoluteTransform().decompose().rotation; - }; + } /** * get transform of the node * @method * @name Konva.Node#getTransform * @returns {Konva.Transform} */ - Node.prototype.getTransform = function () { + getTransform() { return this._getCache(TRANSFORM, this._getTransform); - }; - Node.prototype._getTransform = function () { + } + _getTransform() { var _a, _b; var m = 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(), y = this.y(), rotation = Konva.getAngle(this.rotation()), scaleX = (_a = this.attrs.scaleX) !== null && _a !== void 0 ? _a : 1, scaleY = (_b = this.attrs.scaleY) !== null && _b !== void 0 ? _b : 1, skewX = this.attrs.skewX || 0, skewY = this.attrs.skewY || 0, offsetX = this.attrs.offsetX || 0, offsetY = this.attrs.offsetY || 0; + var x = this.x(), y = this.y(), rotation = Konva$2.getAngle(this.rotation()), scaleX = (_a = this.attrs.scaleX) !== null && _a !== void 0 ? _a : 1, scaleY = (_b = this.attrs.scaleY) !== null && _b !== void 0 ? _b : 1, skewX = this.attrs.skewX || 0, skewY = this.attrs.skewY || 0, offsetX = this.attrs.offsetX || 0, offsetY = this.attrs.offsetY || 0; if (x !== 0 || y !== 0) { m.translate(x, y); } @@ -4141,7 +3984,7 @@ } m.dirty = false; return m; - }; + } /** * clone node. Returns a new Node instance with identical attributes. You can also override * the node properties with an object literal, enabling you to use an existing node as a template @@ -4159,7 +4002,7 @@ * x: 5 * }); */ - Node.prototype.clone = function (obj) { + clone(obj) { // instantiate new node var attrs = Util.cloneObject(this.attrs), key, allListeners, len, n, listener; // apply attr overrides @@ -4187,8 +4030,8 @@ } } return node; - }; - Node.prototype._toKonvaCanvas = function (config) { + } + _toKonvaCanvas(config) { config = config || {}; var box = this.getClientRect(); var stage = this.getStage(), x = config.x !== undefined ? config.x : box.x, y = config.y !== undefined ? config.y : box.y, pixelRatio = config.pixelRatio || 1, canvas = new SceneCanvas({ @@ -4203,7 +4046,7 @@ this.drawScene(canvas); context.restore(); return canvas; - }; + } /** * converts node into an canvas element. * @method @@ -4221,9 +4064,9 @@ * @example * var canvas = node.toCanvas(); */ - Node.prototype.toCanvas = function (config) { + toCanvas(config) { return this._toKonvaCanvas(config)._canvas; - }; + } /** * Creates a composite data URL (base64 string). If MIME type is not * specified, then "image/png" will result. For "image/jpeg", specify a quality @@ -4246,7 +4089,7 @@ * If you export to 500x500 size with pixelRatio = 2, then produced image will have size 1000x1000. * @returns {String} */ - Node.prototype.toDataURL = function (config) { + toDataURL(config) { config = config || {}; var mimeType = config.mimeType || null, quality = config.quality || null; var url = this._toKonvaCanvas(config).toDataURL(mimeType, quality); @@ -4254,7 +4097,7 @@ config.callback(url); } return url; - }; + } /** * converts node into an image. Since the toImage * method is asynchronous, a callback is required. toImage is most commonly used @@ -4283,7 +4126,7 @@ * } * }); */ - Node.prototype.toImage = function (config) { + toImage(config) { if (!config || !config.callback) { throw 'callback required for toImage method config argument'; } @@ -4292,37 +4135,37 @@ Util._urlToImage(this.toDataURL(config), function (img) { callback(img); }); - }; - Node.prototype.setSize = function (size) { + } + setSize(size) { this.width(size.width); this.height(size.height); return this; - }; - Node.prototype.getSize = function () { + } + getSize() { return { width: this.width(), height: this.height(), }; - }; + } /** * get class name, which may return Stage, Layer, Group, or shape class names like Rect, Circle, Text, etc. * @method * @name Konva.Node#getClassName * @returns {String} */ - Node.prototype.getClassName = function () { + getClassName() { return this.className || this.nodeType; - }; + } /** * get the node type, which may return Stage, Layer, Group, or Shape * @method * @name Konva.Node#getType * @returns {String} */ - Node.prototype.getType = function () { + getType() { return this.nodeType; - }; - Node.prototype.getDragDistance = function () { + } + getDragDistance() { // compare with undefined because we need to track 0 value if (this.attrs.dragDistance !== undefined) { return this.attrs.dragDistance; @@ -4331,10 +4174,10 @@ return this.parent.getDragDistance(); } else { - return Konva.dragDistance; + return Konva$2.dragDistance; } - }; - Node.prototype._off = function (type, name, callback) { + } + _off(type, name, callback) { var evtListeners = this.eventListeners[type], i, evtName, handler; for (i = 0; i < evtListeners.length; i++) { evtName = evtListeners[i].name; @@ -4354,21 +4197,21 @@ i--; } } - }; - Node.prototype._fireChangeEvent = function (attr, oldVal, newVal) { + } + _fireChangeEvent(attr, oldVal, newVal) { this._fire(attr + CHANGE, { oldVal: oldVal, newVal: newVal, }); - }; - Node.prototype.setId = function (id) { + } + setId(id) { var oldId = this.id(); _removeId(oldId, this); _addId(this, id); this._setAttr('id', id); return this; - }; - Node.prototype.setName = function (name) { + } + setName(name) { var oldNames = (this.name() || '').split(/\s/g); var newNames = (name || '').split(/\s/g); var subname, i; @@ -4388,7 +4231,7 @@ } this._setAttr(NAME, name); return this; - }; + } /** * add name to node * @method @@ -4400,14 +4243,14 @@ * node.addName('selected'); * node.name(); // return 'red selected' */ - Node.prototype.addName = function (name) { + addName(name) { if (!this.hasName(name)) { var oldName = this.name(); var newName = oldName ? oldName + ' ' + name : name; this.setName(newName); } return this; - }; + } /** * check is node has name * @method @@ -4420,18 +4263,18 @@ * node.hasName('selected'); // return false * node.hasName(''); // return false */ - Node.prototype.hasName = function (name) { + hasName(name) { if (!name) { return false; } - var fullName = this.name(); + const fullName = this.name(); if (!fullName) { return false; } // if name is '' the "names" will be [''], so I added extra check above var names = (fullName || '').split(/\s/g); return names.indexOf(name) !== -1; - }; + } /** * remove name from node * @method @@ -4444,7 +4287,7 @@ * node.hasName('selected'); // return false * node.name(); // return 'red' */ - Node.prototype.removeName = function (name) { + removeName(name) { var names = (this.name() || '').split(/\s/g); var index = names.indexOf(name); if (index !== -1) { @@ -4452,7 +4295,7 @@ this.setName(names.join(' ')); } return this; - }; + } /** * set attr * @method @@ -4463,8 +4306,8 @@ * @example * node.setAttr('x', 5); */ - Node.prototype.setAttr = function (attr, val) { - var func = this[SET$1 + Util._capitalize(attr)]; + setAttr(attr, val) { + var func = this[SET + Util._capitalize(attr)]; if (Util._isFunction(func)) { func.call(this, val); } @@ -4473,8 +4316,8 @@ this._setAttr(attr, val); } return this; - }; - Node.prototype._setAttr = function (key, val, skipFire) { + } + _setAttr(key, val, skipFire = false) { var oldVal = this.attrs[key]; if (oldVal === val && !Util.isObject(val)) { return; @@ -4488,8 +4331,12 @@ if (this._shouldFireChangeEvents) { this._fireChangeEvent(key, oldVal, val); } - }; - Node.prototype._setComponentAttr = function (key, component, val) { + if (Konva$2.autoDrawEnabled) { + const drawNode = this.getLayer() || this.getStage(); + drawNode === null || drawNode === void 0 ? void 0 : drawNode.batchDraw(); + } + } + _setComponentAttr(key, component, val) { var oldVal; if (val !== undefined) { oldVal = this.attrs[key]; @@ -4500,12 +4347,12 @@ this.attrs[key][component] = val; this._fireChangeEvent(key, oldVal, val); } - }; - Node.prototype._fireAndBubble = function (eventType, evt, compareShape) { + } + _fireAndBubble(eventType, evt, compareShape) { if (evt && this.nodeType === SHAPE) { evt.target = this; } - var shouldStop = (eventType === MOUSEENTER || eventType === MOUSELEAVE) && + var shouldStop = (eventType === MOUSEENTER$1 || eventType === MOUSELEAVE$1) && ((compareShape && (this === compareShape || (this.isAncestorOf && this.isAncestorOf(compareShape)))) || @@ -4513,7 +4360,7 @@ if (!shouldStop) { this._fire(eventType, evt); // simulate event bubbling - var stopBubble = (eventType === MOUSEENTER || eventType === MOUSELEAVE) && + var stopBubble = (eventType === MOUSEENTER$1 || eventType === MOUSELEAVE$1) && compareShape && compareShape.isAncestorOf && compareShape.isAncestorOf(this) && @@ -4530,21 +4377,21 @@ } } } - }; - Node.prototype._getProtoListeners = function (eventType) { - var listeners = this._cache.get(ALL_LISTENERS); + } + _getProtoListeners(eventType) { + let listeners = this._cache.get(ALL_LISTENERS); // if no cache for listeners, we need to pre calculate it if (!listeners) { listeners = {}; - var obj = Object.getPrototypeOf(this); + let obj = Object.getPrototypeOf(this); while (obj) { if (!obj.eventListeners) { obj = Object.getPrototypeOf(obj); continue; } for (var event in obj.eventListeners) { - var newEvents = obj.eventListeners[event]; - var oldEvents = listeners[event] || []; + const newEvents = obj.eventListeners[event]; + const oldEvents = listeners[event] || []; listeners[event] = newEvents.concat(oldEvents); } obj = Object.getPrototypeOf(obj); @@ -4552,12 +4399,12 @@ this._cache.set(ALL_LISTENERS, listeners); } return listeners[eventType]; - }; - Node.prototype._fire = function (eventType, evt) { + } + _fire(eventType, evt) { evt = evt || {}; evt.currentTarget = this; evt.type = eventType; - var topListeners = this._getProtoListeners(eventType); + const topListeners = this._getProtoListeners(eventType); if (topListeners) { for (var i = 0; i < topListeners.length; i++) { topListeners[i].handler.call(this, evt); @@ -4565,26 +4412,26 @@ } // it is important to iterate over self listeners without cache // because events can be added/removed while firing - var selfListeners = this.eventListeners[eventType]; + const selfListeners = this.eventListeners[eventType]; if (selfListeners) { for (var i = 0; i < selfListeners.length; i++) { selfListeners[i].handler.call(this, evt); } } - }; + } /** * draw both scene and hit graphs. If the node being drawn is the stage, all of the layers will be cleared and redrawn * @method * @name Konva.Node#draw * @returns {Konva.Node} */ - Node.prototype.draw = function () { + draw() { this.drawScene(); this.drawHit(); return this; - }; + } // drag & drop - Node.prototype._createDragElement = function (evt) { + _createDragElement(evt) { var pointerId = evt ? evt.pointerId : undefined; var stage = this.getStage(); var ap = this.getAbsolutePosition(); @@ -4599,31 +4446,30 @@ y: pos.y - ap.y, }, dragStatus: 'ready', - pointerId: pointerId, + pointerId, }); - }; + } /** * initiate drag and drop. * @method * @name Konva.Node#startDrag */ - Node.prototype.startDrag = function (evt, bubbleEvent) { - if (bubbleEvent === void 0) { bubbleEvent = true; } + startDrag(evt, bubbleEvent = true) { if (!DD._dragElements.has(this._id)) { this._createDragElement(evt); } - var elem = DD._dragElements.get(this._id); + const elem = DD._dragElements.get(this._id); elem.dragStatus = 'dragging'; this.fire('dragstart', { type: 'dragstart', target: this, evt: evt && evt.evt, }, bubbleEvent); - }; - Node.prototype._setDragPosition = function (evt, elem) { + } + _setDragPosition(evt, elem) { // const pointers = this.getStage().getPointersPositions(); // const pos = pointers.find(p => p.id === this._dragEventId); - var pos = this.getStage()._getPointerById(elem.pointerId); + const pos = this.getStage()._getPointerById(elem.pointerId); if (!pos) { return; } @@ -4633,7 +4479,7 @@ }; var dbf = this.dragBoundFunc(); if (dbf !== undefined) { - var bounded = dbf.call(this, newNodePos, evt); + const bounded = dbf.call(this, newNodePos, evt); if (!bounded) { Util.warn('dragBoundFunc did not return any value. That is unexpected behavior. You must return new absolute position from dragBoundFunc.'); } @@ -4653,39 +4499,38 @@ } } this._lastPos = newNodePos; - }; + } /** * stop drag and drop * @method * @name Konva.Node#stopDrag */ - Node.prototype.stopDrag = function (evt) { - var elem = DD._dragElements.get(this._id); + stopDrag(evt) { + const elem = DD._dragElements.get(this._id); if (elem) { elem.dragStatus = 'stopped'; } DD._endDragBefore(evt); DD._endDragAfter(evt); - }; - Node.prototype.setDraggable = function (draggable) { + } + setDraggable(draggable) { this._setAttr('draggable', draggable); this._dragChange(); - }; + } /** * determine if node is currently in drag and drop mode * @method * @name Konva.Node#isDragging */ - Node.prototype.isDragging = function () { - var elem = DD._dragElements.get(this._id); + isDragging() { + const elem = DD._dragElements.get(this._id); return elem ? elem.dragStatus === 'dragging' : false; - }; - Node.prototype._listenDrag = function () { + } + _listenDrag() { this._dragCleanup(); this.on('mousedown.konva touchstart.konva', function (evt) { - var _this = this; var shouldCheckButton = evt.evt['button'] !== undefined; - var canDrag = !shouldCheckButton || Konva.dragButtons.indexOf(evt.evt['button']) >= 0; + var canDrag = !shouldCheckButton || Konva$2.dragButtons.indexOf(evt.evt['button']) >= 0; if (!canDrag) { return; } @@ -4693,8 +4538,8 @@ return; } var hasDraggingChild = false; - DD._dragElements.forEach(function (elem) { - if (_this.isAncestorOf(elem.node)) { + DD._dragElements.forEach((elem) => { + if (this.isAncestorOf(elem.node)) { hasDraggingChild = true; } }); @@ -4704,8 +4549,8 @@ this._createDragElement(evt); } }); - }; - Node.prototype._dragChange = function () { + } + _dragChange() { if (this.attrs.draggable) { this._listenDrag(); } @@ -4721,9 +4566,9 @@ if (!stage) { return; } - var dragElement = DD._dragElements.get(this._id); - var isDragging = dragElement && dragElement.dragStatus === 'dragging'; - var isReady = dragElement && dragElement.dragStatus === 'ready'; + const dragElement = DD._dragElements.get(this._id); + const isDragging = dragElement && dragElement.dragStatus === 'dragging'; + const isReady = dragElement && dragElement.dragStatus === 'ready'; if (isDragging) { this.stopDrag(); } @@ -4731,11 +4576,11 @@ DD._dragElements.delete(this._id); } } - }; - Node.prototype._dragCleanup = function () { + } + _dragCleanup() { this.off('mousedown.konva'); this.off('touchstart.konva'); - }; + } /** * create node with JSON string or an Object. De-serializtion does not generate custom * shape drawing functions, images, or event handlers (this would make the @@ -4749,13 +4594,13 @@ * @param {Element} [container] optional container dom element used only if you're * creating a stage node */ - Node.create = function (data, container) { + static create(data, container) { if (Util._isString(data)) { data = JSON.parse(data); } return this._createNode(data, container); - }; - Node._createNode = function (obj, container) { + } + static _createNode(obj, container) { var className = Node.prototype.getClassName.call(obj), children = obj.children, no, len, n; // if container was passed in, add it to attrs if (container) { @@ -4767,7 +4612,7 @@ '". Fallback to "Shape".'); className = 'Shape'; } - var Class = _NODES_REGISTRY[className]; + const Class = _NODES_REGISTRY[className]; no = new Class(obj.attrs); if (children) { len = children.length; @@ -4776,15 +4621,14 @@ } } return no; - }; - return Node; - }()); + } + } Node.prototype.nodeType = 'Node'; Node.prototype._attrsAffectingSize = []; // attache events listeners once into prototype // that way we don't spend too much time on making an new instance Node.prototype.eventListeners = {}; - Node.prototype.on.call(Node.prototype, TRANSFORM_CHANGE_STR, function () { + Node.prototype.on.call(Node.prototype, TRANSFORM_CHANGE_STR$1, function () { if (this._batchingTransformChange) { this._needClearTransformCache = true; return; @@ -4801,7 +4645,7 @@ Node.prototype.on.call(Node.prototype, 'opacityChange.konva', function () { this._clearSelfAndDescendantCache(ABSOLUTE_OPACITY); }); - var addGetterSetter = Factory.addGetterSetter; + const addGetterSetter = Factory.addGetterSetter; /** * get/set zIndex relative to the node's siblings who share the same parent. * Please remember that zIndex is not absolute (like in CSS). It is relative to parent element only. @@ -5305,8 +5149,7 @@ rotateDeg: 'rotate', setRotationDeg: 'setRotation', getRotationDeg: 'getRotation', - }); - Collection.mapMethods(Node); + }); /** * Container constructor.  Containers are used to contain nodes or other containers @@ -5343,19 +5186,17 @@ * @param {Function} [config.clipFunc] set clip func */ - var Container = /** @class */ (function (_super) { - __extends(Container, _super); - function Container() { - var _this = _super !== null && _super.apply(this, arguments) || this; - _this.children = new Collection(); - return _this; + class Container extends Node { + constructor() { + super(...arguments); + this.children = []; } /** - * returns a {@link Konva.Collection} of direct descendant nodes + * returns an array of direct descendant nodes * @method * @name Konva.Container#getChildren * @param {Function} [filterFunc] filter function - * @returns {Konva.Collection} + * @returns {Array} * @example * // get all children * var children = layer.getChildren(); @@ -5365,62 +5206,59 @@ * return node.getClassName() === 'Circle'; * }); */ - Container.prototype.getChildren = function (filterFunc) { + getChildren(filterFunc) { if (!filterFunc) { - return this.children; + return this.children || []; } - var results = new Collection(); - this.children.each(function (child) { + const children = this.children || []; + var results = []; + children.forEach(function (child) { if (filterFunc(child)) { results.push(child); } }); return results; - }; + } /** * determine if node has children * @method * @name Konva.Container#hasChildren * @returns {Boolean} */ - Container.prototype.hasChildren = function () { + hasChildren() { return this.getChildren().length > 0; - }; + } /** * remove all children. Children will be still in memory. * If you want to completely destroy all children please use "destroyChildren" method instead * @method * @name Konva.Container#removeChildren */ - Container.prototype.removeChildren = function () { - var child; - for (var i = 0; i < this.children.length; i++) { - child = this.children[i]; + removeChildren() { + this.getChildren().forEach((child) => { // reset parent to prevent many _setChildrenIndices calls child.parent = null; child.index = 0; child.remove(); - } - this.children = new Collection(); + }); + this.children = []; return this; - }; + } /** * destroy all children nodes. * @method * @name Konva.Container#destroyChildren */ - Container.prototype.destroyChildren = function () { - var child; - for (var i = 0; i < this.children.length; i++) { - child = this.children[i]; + destroyChildren() { + this.getChildren().forEach((child) => { // reset parent to prevent many _setChildrenIndices calls child.parent = null; child.index = 0; child.destroy(); - } - this.children = new Collection(); + }); + this.children = []; return this; - }; + } /** * add a child and children into container * @name Konva.Container#add @@ -5433,11 +5271,7 @@ * // remember to redraw layer if you changed something * layer.draw(); */ - Container.prototype.add = function () { - var children = []; - for (var _i = 0; _i < arguments.length; _i++) { - children[_i] = arguments[_i]; - } + add(...children) { if (arguments.length > 1) { for (var i = 0; i < arguments.length; i++) { this.add(arguments[i]); @@ -5449,27 +5283,26 @@ child.moveTo(this); return this; } - var _children = this.children; this._validateAdd(child); child._clearCaches(); - child.index = _children.length; + child.index = this.getChildren().length; child.parent = this; - _children.push(child); + this.getChildren().push(child); this._fire('add', { child: child, }); // chainable return this; - }; - Container.prototype.destroy = function () { + } + destroy() { if (this.hasChildren()) { this.destroyChildren(); } - _super.prototype.destroy.call(this); + super.destroy(); return this; - }; + } /** - * return a {@link Konva.Collection} of nodes that match the selector. + * return an array of nodes that match the selector. * You can provide a string with '#' for id selections and '.' for name selections. * Or a function that will return true/false when a node is passed through. See example below. * With strings you can also select by type or class name. Pass multiple selectors @@ -5477,7 +5310,7 @@ * @method * @name Konva.Container#find * @param {String | Function} selector - * @returns {Collection} + * @returns {Array} * @example * * Passing a string as a selector @@ -5508,15 +5341,11 @@ * return node.getType() === 'Node' && node.getAbsoluteOpacity() < 1; * }); */ - Container.prototype.find = function (selector) { + find(selector) { // protecting _generalFind to prevent user from accidentally adding // second argument and getting unexpected `findOne` result return this._generalFind(selector, false); - }; - Container.prototype.get = function (selector) { - Util.warn('collection.get() method is deprecated. Please use collection.find() instead.'); - return this.find(selector); - }; + } /** * return a first node from `find` method * @method @@ -5535,14 +5364,14 @@ * return node.getType() === 'Shape' * }) */ - Container.prototype.findOne = function (selector) { + findOne(selector) { var result = this._generalFind(selector, true); return result.length > 0 ? result[0] : undefined; - }; - Container.prototype._generalFind = function (selector, findOne) { + } + _generalFind(selector, findOne) { var retArr = []; - this._descendants(function (node) { - var valid = node._isMatch(selector); + this._descendants((node) => { + const valid = node._isMatch(selector); if (valid) { retArr.push(node); } @@ -5551,12 +5380,12 @@ } return false; }); - return Collection.toCollection(retArr); - }; - Container.prototype._descendants = function (fn) { - var shouldStop = false; - for (var i = 0; i < this.children.length; i++) { - var child = this.children[i]; + return retArr; + } + _descendants(fn) { + let shouldStop = false; + const children = this.getChildren(); + for (const child of children) { shouldStop = fn(child); if (shouldStop) { return true; @@ -5570,19 +5399,16 @@ } } return false; - }; + } // extenders - Container.prototype.toObject = function () { + toObject() { var obj = Node.prototype.toObject.call(this); obj.children = []; - var children = this.getChildren(); - var len = children.length; - for (var n = 0; n < len; n++) { - var child = children[n]; + this.getChildren().forEach((child) => { obj.children.push(child.toObject()); - } + }); return obj; - }; + } /** * determine if node is an ancestor * of descendant @@ -5590,7 +5416,7 @@ * @name Konva.Container#isAncestorOf * @param {Konva.Node} node */ - Container.prototype.isAncestorOf = function (node) { + isAncestorOf(node) { var parent = node.getParent(); while (parent) { if (parent._id === this._id) { @@ -5599,15 +5425,15 @@ parent = parent.getParent(); } return false; - }; - Container.prototype.clone = function (obj) { + } + clone(obj) { // call super method var node = Node.prototype.clone.call(this, obj); - this.getChildren().each(function (no) { + this.getChildren().forEach(function (no) { node.add(no.clone()); }); return node; - }; + } /** * get all shapes that intersect a point. Note: because this method must clear a temporary * canvas and redraw every shape inside the container, it should only be used for special situations @@ -5620,21 +5446,34 @@ * @param {Number} pos.y * @returns {Array} array of shapes */ - Container.prototype.getAllIntersections = function (pos) { + getAllIntersections(pos) { var arr = []; - this.find('Shape').each(function (shape) { + this.find('Shape').forEach(function (shape) { if (shape.isVisible() && shape.intersects(pos)) { arr.push(shape); } }); return arr; - }; - Container.prototype._setChildrenIndices = function () { - this.children.each(function (child, n) { + } + _clearSelfAndDescendantCache(attr, forceEvent) { + var _a; + super._clearSelfAndDescendantCache(attr, forceEvent); + // skip clearing if node is cached with canvas + // for performance reasons !!! + if (this.isCached()) { + return; + } + (_a = this.children) === null || _a === void 0 ? void 0 : _a.forEach(function (node) { + node._clearSelfAndDescendantCache(attr, forceEvent); + }); + } + _setChildrenIndices() { + var _a; + (_a = this.children) === null || _a === void 0 ? void 0 : _a.forEach(function (child, n) { child.index = n; }); - }; - Container.prototype.drawScene = function (can, top) { + } + drawScene(can, top) { var layer = this.getLayer(), canvas = can || (layer && layer.getCanvas()), context = canvas && canvas.getContext(), cachedCanvas = this._getCanvasCache(), cachedSceneCanvas = cachedCanvas && cachedCanvas.scene; var caching = canvas && canvas.isCache; if (!this.isVisible() && !caching) { @@ -5651,8 +5490,8 @@ this._drawChildren('drawScene', canvas, top); } return this; - }; - Container.prototype.drawHit = function (can, top) { + } + drawHit(can, top) { if (!this.shouldDrawHit(top)) { return this; } @@ -5668,10 +5507,11 @@ this._drawChildren('drawHit', canvas, top); } return this; - }; - Container.prototype._drawChildren = function (drawMethod, canvas, top) { + } + _drawChildren(drawMethod, canvas, top) { + var _a; var context = canvas && canvas.getContext(), clipWidth = this.clipWidth(), clipHeight = this.clipHeight(), clipFunc = this.clipFunc(), hasClip = (clipWidth && clipHeight) || clipFunc; - var selfCache = top === this; + const selfCache = top === this; if (hasClip) { context.save(); var transform = this.getAbsoluteTransform(top); @@ -5697,7 +5537,7 @@ context.save(); context._applyGlobalCompositeOperation(this); } - this.children.each(function (child) { + (_a = this.children) === null || _a === void 0 ? void 0 : _a.forEach(function (child) { child[drawMethod](canvas, top); }); if (hasComposition) { @@ -5706,8 +5546,9 @@ if (hasClip) { context.restore(); } - }; - Container.prototype.getClientRect = function (config) { + } + getClientRect(config) { + var _a; config = config || {}; var skipTransform = config.skipTransform; var relativeTo = config.relativeTo; @@ -5719,7 +5560,7 @@ height: 0, }; var that = this; - this.children.each(function (child) { + (_a = this.children) === null || _a === void 0 ? void 0 : _a.forEach(function (child) { // skip invisible children if (!child.visible()) { return; @@ -5777,9 +5618,8 @@ return this._transformedRect(selfRect, relativeTo); } return selfRect; - }; - return Container; - }(Node)); + } + } // add getters setters Factory.addComponentsGetterSetter(Container, 'clip', [ 'x', @@ -5880,19 +5720,18 @@ * container.clipFunc(function(ctx) { * ctx.rect(0, 0, 100, 100); * }); - */ - Collection.mapMethods(Container); + */ - var Captures = new Map(); + const Captures = new Map(); // we may use this module for capturing touch events too // so make sure we don't do something super specific to pointer - var SUPPORT_POINTER_EVENTS = Konva._global['PointerEvent'] !== undefined; + const SUPPORT_POINTER_EVENTS = Konva$2._global['PointerEvent'] !== undefined; function getCapturedShape(pointerId) { return Captures.get(pointerId); } function createEvent(evt) { return { - evt: evt, + evt, pointerId: evt.pointerId }; } @@ -5901,7 +5740,7 @@ } function setPointerCapture(pointerId, shape) { releaseCapture(pointerId); - var stage = shape.getStage(); + const stage = shape.getStage(); if (!stage) return; Captures.set(pointerId, shape); @@ -5910,10 +5749,10 @@ } } function releaseCapture(pointerId, target) { - var shape = Captures.get(pointerId); + const shape = Captures.get(pointerId); if (!shape) return; - var stage = shape.getStage(); + const stage = shape.getStage(); if (stage && stage.content) ; Captures.delete(pointerId); if (SUPPORT_POINTER_EVENTS) { @@ -5922,14 +5761,14 @@ } // CONSTANTS - var STAGE$1 = 'Stage', STRING = 'string', PX = 'px', MOUSEOUT = 'mouseout', MOUSELEAVE$1 = 'mouseleave', MOUSEOVER = 'mouseover', MOUSEENTER$1 = 'mouseenter', MOUSEMOVE = 'mousemove', MOUSEDOWN = 'mousedown', MOUSEUP = 'mouseup', + var STAGE = 'Stage', STRING = 'string', PX = 'px', MOUSEOUT = 'mouseout', MOUSELEAVE = 'mouseleave', MOUSEOVER = 'mouseover', MOUSEENTER = 'mouseenter', MOUSEMOVE = 'mousemove', MOUSEDOWN = 'mousedown', MOUSEUP = 'mouseup', // TODO: add them into "on" method docs and into site docs POINTERMOVE = 'pointermove', POINTERDOWN = 'pointerdown', POINTERUP = 'pointerup', POINTERCANCEL = 'pointercancel', LOSTPOINTERCAPTURE = 'lostpointercapture', CONTEXTMENU = 'contextmenu', CLICK = 'click', DBL_CLICK = 'dblclick', TOUCHSTART = 'touchstart', TOUCHEND = 'touchend', TAP = 'tap', DBL_TAP = 'dbltap', TOUCHMOVE = 'touchmove', WHEEL = 'wheel', CONTENT_MOUSEOUT = 'contentMouseout', CONTENT_MOUSEOVER = 'contentMouseover', CONTENT_MOUSEMOVE = 'contentMousemove', CONTENT_MOUSEDOWN = 'contentMousedown', CONTENT_MOUSEUP = 'contentMouseup', CONTENT_CONTEXTMENU = 'contentContextmenu', CONTENT_CLICK = 'contentClick', CONTENT_DBL_CLICK = 'contentDblclick', CONTENT_TOUCHSTART = 'contentTouchstart', CONTENT_TOUCHEND = 'contentTouchend', CONTENT_DBL_TAP = 'contentDbltap', CONTENT_TAP = 'contentTap', CONTENT_TOUCHMOVE = 'contentTouchmove', CONTENT_WHEEL = 'contentWheel', RELATIVE = 'relative', KONVA_CONTENT = 'konvajs-content', UNDERSCORE = '_', CONTAINER = 'container', MAX_LAYERS_NUMBER = 5, EMPTY_STRING$1 = '', EVENTS = [ - MOUSEENTER$1, + MOUSEENTER, MOUSEDOWN, MOUSEMOVE, MOUSEUP, - MOUSELEAVE$1, + MOUSELEAVE, TOUCHSTART, TOUCHMOVE, TOUCHEND, @@ -5949,10 +5788,9 @@ ctx[UNDERSCORE + eventName](evt); }, false); } - var NO_POINTERS_MESSAGE = "Pointer position is missing and not registered by the stage. Looks like it is outside of the stage container. You can set it manually from event: stage.setPointersPositions(event);"; - var stages = []; - function checkNoClip(attrs) { - if (attrs === void 0) { attrs = {}; } + const NO_POINTERS_MESSAGE = `Pointer position is missing and not registered by the stage. Looks like it is outside of the stage container. You can set it manually from event: stage.setPointersPositions(event);`; + const stages = []; + function checkNoClip(attrs = {}) { if (attrs.clipFunc || attrs.clipWidth || attrs.clipHeight) { Util.warn('Stage does not support clipping. Please use clip for Layers or Groups.'); } @@ -5992,45 +5830,43 @@ * container: 'containerId' // or "#containerId" or ".containerClass" * }); */ - var Stage = /** @class */ (function (_super) { - __extends(Stage, _super); - function Stage(config) { - var _this = _super.call(this, checkNoClip(config)) || this; - _this._pointerPositions = []; - _this._changedPointerPositions = []; - _this._buildDOM(); - _this._bindContentEvents(); - stages.push(_this); - _this.on('widthChange.konva heightChange.konva', _this._resizeDOM); - _this.on('visibleChange.konva', _this._checkVisibility); - _this.on('clipWidthChange.konva clipHeightChange.konva clipFuncChange.konva', function () { - checkNoClip(_this.attrs); + class Stage extends Container { + constructor(config) { + super(checkNoClip(config)); + this._pointerPositions = []; + this._changedPointerPositions = []; + this._buildDOM(); + this._bindContentEvents(); + stages.push(this); + this.on('widthChange.konva heightChange.konva', this._resizeDOM); + this.on('visibleChange.konva', this._checkVisibility); + this.on('clipWidthChange.konva clipHeightChange.konva clipFuncChange.konva', () => { + checkNoClip(this.attrs); }); - _this._checkVisibility(); - return _this; + this._checkVisibility(); } - Stage.prototype._validateAdd = function (child) { - var isLayer = child.getType() === 'Layer'; - var isFastLayer = child.getType() === 'FastLayer'; - var valid = isLayer || isFastLayer; + _validateAdd(child) { + const isLayer = child.getType() === 'Layer'; + const isFastLayer = child.getType() === 'FastLayer'; + const valid = isLayer || isFastLayer; if (!valid) { Util.throw('You may only add layers to the stage.'); } - }; - Stage.prototype._checkVisibility = function () { + } + _checkVisibility() { if (!this.content) { return; } - var style = this.visible() ? '' : 'none'; + const style = this.visible() ? '' : 'none'; this.content.style.display = style; - }; + } /** * set container dom element which contains the stage wrapper div element * @method * @name Konva.Stage#setContainer * @param {DomElement} container can pass in a dom element or id string */ - Stage.prototype.setContainer = function (container) { + setContainer(container) { if (typeof container === STRING) { if (container.charAt(0) === '.') { var className = container.slice(1); @@ -6058,31 +5894,32 @@ container.appendChild(this.content); } return this; - }; - Stage.prototype.shouldDrawHit = function () { + } + shouldDrawHit() { return true; - }; + } /** * clear all layers * @method * @name Konva.Stage#clear */ - Stage.prototype.clear = function () { + clear() { var layers = this.children, len = layers.length, n; for (n = 0; n < len; n++) { layers[n].clear(); } return this; - }; - Stage.prototype.clone = function (obj) { + } + clone(obj) { if (!obj) { obj = {}; } - obj.container = document.createElement('div'); + obj.container = + typeof document !== 'undefined' && document.createElement('div'); return Container.prototype.clone.call(this, obj); - }; - Stage.prototype.destroy = function () { - _super.prototype.destroy.call(this); + } + destroy() { + super.destroy(); var content = this.content; if (content && Util._isInDocument(content)) { this.container().removeChild(content); @@ -6092,7 +5929,7 @@ stages.splice(index, 1); } return this; - }; + } /** * returns absolute pointer position which can be a touch position or mouse position * pointer position doesn't include any transforms (such as scale) of the stage @@ -6101,8 +5938,8 @@ * @name Konva.Stage#getPointerPosition * @returns {Vector2d|null} */ - Stage.prototype.getPointerPosition = function () { - var pos = this._pointerPositions[0] || this._changedPointerPositions[0]; + getPointerPosition() { + const pos = this._pointerPositions[0] || this._changedPointerPositions[0]; if (!pos) { Util.warn(NO_POINTERS_MESSAGE); return null; @@ -6111,20 +5948,20 @@ x: pos.x, y: pos.y, }; - }; - Stage.prototype._getPointerById = function (id) { - return this._pointerPositions.find(function (p) { return p.id === id; }); - }; - Stage.prototype.getPointersPositions = function () { + } + _getPointerById(id) { + return this._pointerPositions.find((p) => p.id === id); + } + getPointersPositions() { return this._pointerPositions; - }; - Stage.prototype.getStage = function () { + } + getStage() { return this; - }; - Stage.prototype.getContent = function () { + } + getContent() { return this.content; - }; - Stage.prototype._toKonvaCanvas = function (config) { + } + _toKonvaCanvas(config) { config = config || {}; config.x = config.x || 0; config.y = config.y || 0; @@ -6140,7 +5977,7 @@ if (config.x || config.y) { _context.translate(-1 * config.x, -1 * config.y); } - layers.each(function (layer) { + layers.forEach(function (layer) { if (!layer.isVisible()) { return; } @@ -6148,7 +5985,7 @@ _context.drawImage(layerCanvas._canvas, config.x, config.y, layerCanvas.getWidth() / layerCanvas.getPixelRatio(), layerCanvas.getHeight() / layerCanvas.getPixelRatio()); }); return canvas; - }; + } /** * get visible intersection shape. This is the preferred * method for determining if a point intersects a shape or not @@ -6164,20 +6001,20 @@ * // or if you interested in shape parent: * var group = stage.getIntersection({x: 50, y: 50}, 'Group'); */ - Stage.prototype.getIntersection = function (pos, selector) { + getIntersection(pos, selector) { if (!pos) { return null; } - var layers = this.children, len = layers.length, end = len - 1, n, shape; + var layers = this.children, len = layers.length, end = len - 1, n; for (n = end; n >= 0; n--) { - shape = layers[n].getIntersection(pos, selector); + const shape = layers[n].getIntersection(pos, selector); if (shape) { return shape; } } return null; - }; - Stage.prototype._resizeDOM = function () { + } + _resizeDOM() { var width = this.width(); var height = this.height(); if (this.content) { @@ -6188,19 +6025,19 @@ this.bufferCanvas.setSize(width, height); this.bufferHitCanvas.setSize(width, height); // set layer dimensions - this.children.each(function (layer) { - layer.setSize({ width: width, height: height }); + this.children.forEach((layer) => { + layer.setSize({ width, height }); layer.draw(); }); - }; - Stage.prototype.add = function (layer) { + } + add(layer, ...rest) { if (arguments.length > 1) { for (var i = 0; i < arguments.length; i++) { this.add(arguments[i]); } return this; } - _super.prototype.add.call(this, layer); + super.add(layer); var length = this.children.length; if (length > MAX_LAYERS_NUMBER) { Util.warn('The stage has ' + @@ -6210,65 +6047,65 @@ layer.setSize({ width: this.width(), height: this.height() }); // draw layer and append canvas to container layer.draw(); - if (Konva.isBrowser) { + if (Konva$2.isBrowser) { this.content.appendChild(layer.canvas._canvas); } // chainable return this; - }; - Stage.prototype.getParent = function () { + } + getParent() { return null; - }; - Stage.prototype.getLayer = function () { + } + getLayer() { return null; - }; - Stage.prototype.hasPointerCapture = function (pointerId) { + } + hasPointerCapture(pointerId) { return hasPointerCapture(pointerId, this); - }; - Stage.prototype.setPointerCapture = function (pointerId) { + } + setPointerCapture(pointerId) { setPointerCapture(pointerId, this); - }; - Stage.prototype.releaseCapture = function (pointerId) { + } + releaseCapture(pointerId) { releaseCapture(pointerId); - }; + } /** - * returns a {@link Konva.Collection} of layers + * returns an array of layers * @method * @name Konva.Stage#getLayers */ - Stage.prototype.getLayers = function () { - return this.getChildren(); - }; - Stage.prototype._bindContentEvents = function () { - if (!Konva.isBrowser) { + getLayers() { + return this.children; + } + _bindContentEvents() { + if (!Konva$2.isBrowser) { return; } for (var n = 0; n < eventsLength; n++) { addEvent(this, EVENTS[n]); } - }; - Stage.prototype._mouseenter = function (evt) { + } + _mouseenter(evt) { this.setPointersPositions(evt); - this._fire(MOUSEENTER$1, { evt: evt, target: this, currentTarget: this }); - }; - Stage.prototype._mouseover = function (evt) { + this._fire(MOUSEENTER, { evt: evt, target: this, currentTarget: this }); + } + _mouseover(evt) { this.setPointersPositions(evt); this._fire(CONTENT_MOUSEOVER, { evt: evt }); this._fire(MOUSEOVER, { evt: evt, target: this, currentTarget: this }); - }; - Stage.prototype._mouseleave = function (evt) { + } + _mouseleave(evt) { var _a; this.setPointersPositions(evt); var targetShape = ((_a = this.targetShape) === null || _a === void 0 ? void 0 : _a.getStage()) ? this.targetShape : null; - var eventsEnabled = !DD.isDragging || Konva.hitOnDragEnabled; + var eventsEnabled = !DD.isDragging || Konva$2.hitOnDragEnabled; if (targetShape && eventsEnabled) { targetShape._fireAndBubble(MOUSEOUT, { evt: evt }); - targetShape._fireAndBubble(MOUSELEAVE$1, { evt: evt }); - this._fire(MOUSELEAVE$1, { evt: evt, target: this, currentTarget: this }); + targetShape._fireAndBubble(MOUSELEAVE, { evt: evt }); + this._fire(MOUSELEAVE, { evt: evt, target: this, currentTarget: this }); this.targetShape = null; } else if (eventsEnabled) { - this._fire(MOUSELEAVE$1, { + this._fire(MOUSELEAVE, { evt: evt, target: this, currentTarget: this, @@ -6282,34 +6119,33 @@ this.pointerPos = undefined; this._pointerPositions = []; this._fire(CONTENT_MOUSEOUT, { evt: evt }); - }; - Stage.prototype._mousemove = function (evt) { + } + _mousemove(evt) { var _a; // workaround for mobile IE to force touch event when unhandled pointer event elevates into a mouse event - if (Konva.UA.ieMobile) { + if (Konva$2.UA.ieMobile) { return this._touchmove(evt); } this.setPointersPositions(evt); var pointerId = Util._getFirstPointerId(evt); - var shape; var targetShape = ((_a = this.targetShape) === null || _a === void 0 ? void 0 : _a.getStage()) ? this.targetShape : null; - var eventsEnabled = !DD.isDragging || Konva.hitOnDragEnabled; + var eventsEnabled = !DD.isDragging || Konva$2.hitOnDragEnabled; if (eventsEnabled) { - shape = this.getIntersection(this.getPointerPosition()); + const shape = this.getIntersection(this.getPointerPosition()); if (shape && shape.isListening()) { var differentTarget = targetShape !== shape; if (eventsEnabled && differentTarget) { if (targetShape) { - targetShape._fireAndBubble(MOUSEOUT, { evt: evt, pointerId: pointerId }, shape); - targetShape._fireAndBubble(MOUSELEAVE$1, { evt: evt, pointerId: pointerId }, shape); + targetShape._fireAndBubble(MOUSEOUT, { evt: evt, pointerId }, shape); + targetShape._fireAndBubble(MOUSELEAVE, { evt: evt, pointerId }, shape); } - shape._fireAndBubble(MOUSEOVER, { evt: evt, pointerId: pointerId }, targetShape); - shape._fireAndBubble(MOUSEENTER$1, { evt: evt, pointerId: pointerId }, targetShape); - shape._fireAndBubble(MOUSEMOVE, { evt: evt, pointerId: pointerId }); + shape._fireAndBubble(MOUSEOVER, { evt: evt, pointerId }, targetShape); + shape._fireAndBubble(MOUSEENTER, { evt: evt, pointerId }, targetShape); + shape._fireAndBubble(MOUSEMOVE, { evt: evt, pointerId }); this.targetShape = shape; } else { - shape._fireAndBubble(MOUSEMOVE, { evt: evt, pointerId: pointerId }); + shape._fireAndBubble(MOUSEMOVE, { evt: evt, pointerId }); } } else { @@ -6318,13 +6154,13 @@ * to run mouseout from previous target shape */ if (targetShape && eventsEnabled) { - targetShape._fireAndBubble(MOUSEOUT, { evt: evt, pointerId: pointerId }); - targetShape._fireAndBubble(MOUSELEAVE$1, { evt: evt, pointerId: pointerId }); + targetShape._fireAndBubble(MOUSEOUT, { evt: evt, pointerId }); + targetShape._fireAndBubble(MOUSELEAVE, { evt: evt, pointerId }); this._fire(MOUSEOVER, { evt: evt, target: this, currentTarget: this, - pointerId: pointerId, + pointerId, }); this.targetShape = null; } @@ -6332,7 +6168,7 @@ evt: evt, target: this, currentTarget: this, - pointerId: pointerId, + pointerId, }); } // content event @@ -6343,27 +6179,27 @@ if (evt.cancelable) { evt.preventDefault(); } - }; - Stage.prototype._mousedown = function (evt) { + } + _mousedown(evt) { // workaround for mobile IE to force touch event when unhandled pointer event elevates into a mouse event - if (Konva.UA.ieMobile) { + if (Konva$2.UA.ieMobile) { return this._touchstart(evt); } this.setPointersPositions(evt); var pointerId = Util._getFirstPointerId(evt); var shape = this.getIntersection(this.getPointerPosition()); DD.justDragged = false; - Konva.listenClickTap = true; + Konva$2.listenClickTap = true; if (shape && shape.isListening()) { this.clickStartShape = shape; - shape._fireAndBubble(MOUSEDOWN, { evt: evt, pointerId: pointerId }); + shape._fireAndBubble(MOUSEDOWN, { evt: evt, pointerId }); } else { this._fire(MOUSEDOWN, { evt: evt, target: this, currentTarget: this, - pointerId: pointerId, + pointerId, }); } // content event @@ -6374,38 +6210,38 @@ // if (evt.cancelable) { // evt.preventDefault(); // } - }; - Stage.prototype._mouseup = function (evt) { + } + _mouseup(evt) { // workaround for mobile IE to force touch event when unhandled pointer event elevates into a mouse event - if (Konva.UA.ieMobile) { + if (Konva$2.UA.ieMobile) { return this._touchend(evt); } this.setPointersPositions(evt); var pointerId = Util._getFirstPointerId(evt); var shape = this.getIntersection(this.getPointerPosition()), clickStartShape = this.clickStartShape, clickEndShape = this.clickEndShape, fireDblClick = false; - if (Konva.inDblClickWindow) { + if (Konva$2.inDblClickWindow) { fireDblClick = true; clearTimeout(this.dblTimeout); // Konva.inDblClickWindow = false; } else if (!DD.justDragged) { // don't set inDblClickWindow after dragging - Konva.inDblClickWindow = true; + Konva$2.inDblClickWindow = true; clearTimeout(this.dblTimeout); } this.dblTimeout = setTimeout(function () { - Konva.inDblClickWindow = false; - }, Konva.dblClickWindow); + Konva$2.inDblClickWindow = false; + }, Konva$2.dblClickWindow); if (shape && shape.isListening()) { this.clickEndShape = shape; - shape._fireAndBubble(MOUSEUP, { evt: evt, pointerId: pointerId }); + shape._fireAndBubble(MOUSEUP, { evt: evt, pointerId }); // detect if click or double click occurred - if (Konva.listenClickTap && + if (Konva$2.listenClickTap && clickStartShape && clickStartShape._id === shape._id) { - shape._fireAndBubble(CLICK, { evt: evt, pointerId: pointerId }); + shape._fireAndBubble(CLICK, { evt: evt, pointerId }); if (fireDblClick && clickEndShape && clickEndShape === shape) { - shape._fireAndBubble(DBL_CLICK, { evt: evt, pointerId: pointerId }); + shape._fireAndBubble(DBL_CLICK, { evt: evt, pointerId }); } } } @@ -6415,14 +6251,14 @@ evt: evt, target: this, currentTarget: this, - pointerId: pointerId, + pointerId, }); - if (Konva.listenClickTap) { + if (Konva$2.listenClickTap) { this._fire(CLICK, { evt: evt, target: this, currentTarget: this, - pointerId: pointerId, + pointerId, }); } if (fireDblClick) { @@ -6430,26 +6266,26 @@ evt: evt, target: this, currentTarget: this, - pointerId: pointerId, + pointerId, }); } } // content events this._fire(CONTENT_MOUSEUP, { evt: evt }); - if (Konva.listenClickTap) { + if (Konva$2.listenClickTap) { this._fire(CONTENT_CLICK, { evt: evt }); if (fireDblClick) { this._fire(CONTENT_DBL_CLICK, { evt: evt }); } } - Konva.listenClickTap = false; + Konva$2.listenClickTap = false; // always call preventDefault for desktop events because some browsers // try to drag and drop the canvas element if (evt.cancelable) { evt.preventDefault(); } - }; - Stage.prototype._contextmenu = function (evt) { + } + _contextmenu(evt) { this.setPointersPositions(evt); var shape = this.getIntersection(this.getPointerPosition()); if (shape && shape.isListening()) { @@ -6463,24 +6299,23 @@ }); } this._fire(CONTENT_CONTEXTMENU, { evt: evt }); - }; - Stage.prototype._touchstart = function (evt) { - var _this = this; + } + _touchstart(evt) { this.setPointersPositions(evt); var triggeredOnShape = false; - this._changedPointerPositions.forEach(function (pos) { - var shape = _this.getIntersection(pos); - Konva.listenClickTap = true; + this._changedPointerPositions.forEach((pos) => { + var shape = this.getIntersection(pos); + Konva$2.listenClickTap = true; DD.justDragged = false; - var hasShape = shape && shape.isListening(); + const hasShape = shape && shape.isListening(); if (!hasShape) { return; } - if (Konva.captureTouchEventsEnabled) { + if (Konva$2.captureTouchEventsEnabled) { shape.setPointerCapture(pos.id); } - _this.tapStartShape = shape; - shape._fireAndBubble(TOUCHSTART, { evt: evt, pointerId: pos.id }, _this); + this.tapStartShape = shape; + shape._fireAndBubble(TOUCHSTART, { evt: evt, pointerId: pos.id }, this); triggeredOnShape = true; // only call preventDefault if the shape is listening for events if (shape.isListening() && shape.preventDefault() && evt.cancelable) { @@ -6497,17 +6332,16 @@ } // content event this._fire(CONTENT_TOUCHSTART, { evt: evt }); - }; - Stage.prototype._touchmove = function (evt) { - var _this = this; + } + _touchmove(evt) { this.setPointersPositions(evt); - var eventsEnabled = !DD.isDragging || Konva.hitOnDragEnabled; + var eventsEnabled = !DD.isDragging || Konva$2.hitOnDragEnabled; if (eventsEnabled) { var triggeredOnShape = false; var processedShapesIds = {}; - this._changedPointerPositions.forEach(function (pos) { - var shape = getCapturedShape(pos.id) || _this.getIntersection(pos); - var hasShape = shape && shape.isListening(); + this._changedPointerPositions.forEach((pos) => { + const shape = getCapturedShape(pos.id) || this.getIntersection(pos); + const hasShape = shape && shape.isListening(); if (!hasShape) { return; } @@ -6535,34 +6369,33 @@ if (DD.isDragging && DD.node.preventDefault() && evt.cancelable) { evt.preventDefault(); } - }; - Stage.prototype._touchend = function (evt) { - var _this = this; + } + _touchend(evt) { this.setPointersPositions(evt); var tapEndShape = this.tapEndShape, fireDblClick = false; - if (Konva.inDblClickWindow) { + if (Konva$2.inDblClickWindow) { fireDblClick = true; clearTimeout(this.dblTimeout); // Konva.inDblClickWindow = false; } else if (!DD.justDragged) { - Konva.inDblClickWindow = true; + Konva$2.inDblClickWindow = true; clearTimeout(this.dblTimeout); } this.dblTimeout = setTimeout(function () { - Konva.inDblClickWindow = false; - }, Konva.dblClickWindow); + Konva$2.inDblClickWindow = false; + }, Konva$2.dblClickWindow); var triggeredOnShape = false; var processedShapesIds = {}; var tapTriggered = false; var dblTapTriggered = false; - this._changedPointerPositions.forEach(function (pos) { + this._changedPointerPositions.forEach((pos) => { var shape = getCapturedShape(pos.id) || - _this.getIntersection(pos); + this.getIntersection(pos); if (shape) { shape.releaseCapture(pos.id); } - var hasShape = shape && shape.isListening(); + const hasShape = shape && shape.isListening(); if (!hasShape) { return; } @@ -6570,11 +6403,11 @@ return; } processedShapesIds[shape._id] = true; - _this.tapEndShape = shape; + this.tapEndShape = shape; shape._fireAndBubble(TOUCHEND, { evt: evt, pointerId: pos.id }); triggeredOnShape = true; // detect if tap or double tap occurred - if (Konva.listenClickTap && shape === _this.tapStartShape) { + if (Konva$2.listenClickTap && shape === this.tapStartShape) { tapTriggered = true; shape._fireAndBubble(TAP, { evt: evt, pointerId: pos.id }); if (fireDblClick && tapEndShape && tapEndShape === shape) { @@ -6595,7 +6428,7 @@ pointerId: this._changedPointerPositions[0].id, }); } - if (Konva.listenClickTap && !tapTriggered) { + if (Konva$2.listenClickTap && !tapTriggered) { this.tapEndShape = null; this._fire(TAP, { evt: evt, @@ -6614,7 +6447,7 @@ } // content events this._fire(CONTENT_TOUCHEND, { evt: evt }); - if (Konva.listenClickTap) { + if (Konva$2.listenClickTap) { this._fire(CONTENT_TAP, { evt: evt }); if (fireDblClick) { this._fire(CONTENT_DBL_TAP, { evt: evt }); @@ -6623,9 +6456,9 @@ if (this.preventDefault() && evt.cancelable) { evt.preventDefault(); } - Konva.listenClickTap = false; - }; - Stage.prototype._wheel = function (evt) { + Konva$2.listenClickTap = false; + } + _wheel(evt) { this.setPointersPositions(evt); var shape = this.getIntersection(this.getPointerPosition()); if (shape && shape.isListening()) { @@ -6639,56 +6472,56 @@ }); } this._fire(CONTENT_WHEEL, { evt: evt }); - }; - Stage.prototype._pointerdown = function (evt) { - if (!Konva._pointerEventsEnabled) { + } + _pointerdown(evt) { + if (!Konva$2._pointerEventsEnabled) { return; } this.setPointersPositions(evt); - var shape = getCapturedShape(evt.pointerId) || + const shape = getCapturedShape(evt.pointerId) || this.getIntersection(this.getPointerPosition()); if (shape) { shape._fireAndBubble(POINTERDOWN, createEvent(evt)); } - }; - Stage.prototype._pointermove = function (evt) { - if (!Konva._pointerEventsEnabled) { + } + _pointermove(evt) { + if (!Konva$2._pointerEventsEnabled) { return; } this.setPointersPositions(evt); - var shape = getCapturedShape(evt.pointerId) || + const shape = getCapturedShape(evt.pointerId) || this.getIntersection(this.getPointerPosition()); if (shape) { shape._fireAndBubble(POINTERMOVE, createEvent(evt)); } - }; - Stage.prototype._pointerup = function (evt) { - if (!Konva._pointerEventsEnabled) { + } + _pointerup(evt) { + if (!Konva$2._pointerEventsEnabled) { return; } this.setPointersPositions(evt); - var shape = getCapturedShape(evt.pointerId) || + const shape = getCapturedShape(evt.pointerId) || this.getIntersection(this.getPointerPosition()); if (shape) { shape._fireAndBubble(POINTERUP, createEvent(evt)); } releaseCapture(evt.pointerId); - }; - Stage.prototype._pointercancel = function (evt) { - if (!Konva._pointerEventsEnabled) { + } + _pointercancel(evt) { + if (!Konva$2._pointerEventsEnabled) { return; } this.setPointersPositions(evt); - var shape = getCapturedShape(evt.pointerId) || + const shape = getCapturedShape(evt.pointerId) || this.getIntersection(this.getPointerPosition()); if (shape) { shape._fireAndBubble(POINTERUP, createEvent(evt)); } releaseCapture(evt.pointerId); - }; - Stage.prototype._lostpointercapture = function (evt) { + } + _lostpointercapture(evt) { releaseCapture(evt.pointerId); - }; + } /** * manually register pointers positions (mouse/touch) in the stage. * So you can use stage.getPointerPosition(). Usually you don't need to use that method @@ -6703,8 +6536,7 @@ * stage.setPointersPositions(e); * }); */ - Stage.prototype.setPointersPositions = function (evt) { - var _this = this; + setPointersPositions(evt) { var contentPosition = this._getContentPosition(), x = null, y = null; evt = evt ? evt : window.event; // touch events @@ -6713,15 +6545,15 @@ // so we have to iterate this._pointerPositions = []; this._changedPointerPositions = []; - Collection.prototype.each.call(evt.touches, function (touch) { - _this._pointerPositions.push({ + Array.prototype.forEach.call(evt.touches, (touch) => { + this._pointerPositions.push({ id: touch.identifier, x: (touch.clientX - contentPosition.left) / contentPosition.scaleX, y: (touch.clientY - contentPosition.top) / contentPosition.scaleY, }); }); - Collection.prototype.each.call(evt.changedTouches || evt.touches, function (touch) { - _this._changedPointerPositions.push({ + Array.prototype.forEach.call(evt.changedTouches || evt.touches, (touch) => { + this._changedPointerPositions.push({ id: touch.identifier, x: (touch.clientX - contentPosition.left) / contentPosition.scaleX, y: (touch.clientY - contentPosition.top) / contentPosition.scaleY, @@ -6736,17 +6568,17 @@ x: x, y: y, }; - this._pointerPositions = [{ x: x, y: y, id: Util._getFirstPointerId(evt) }]; + this._pointerPositions = [{ x, y, id: Util._getFirstPointerId(evt) }]; this._changedPointerPositions = [ - { x: x, y: y, id: Util._getFirstPointerId(evt) }, + { x, y, id: Util._getFirstPointerId(evt) }, ]; } - }; - Stage.prototype._setPointerPosition = function (evt) { + } + _setPointerPosition(evt) { Util.warn('Method _setPointerPosition is deprecated. Use "stage.setPointersPositions(event)" instead.'); this.setPointersPositions(evt); - }; - Stage.prototype._getContentPosition = function () { + } + _getContentPosition() { if (!this.content || !this.content.getBoundingClientRect) { return { top: 0, @@ -6764,8 +6596,8 @@ scaleX: rect.width / this.content.clientWidth || 1, scaleY: rect.height / this.content.clientHeight || 1, }; - }; - Stage.prototype._buildDOM = function () { + } + _buildDOM() { this.bufferCanvas = new SceneCanvas({ width: this.width(), height: this.height(), @@ -6775,7 +6607,7 @@ width: this.width(), height: this.height(), }); - if (!Konva.isBrowser) { + if (!Konva$2.isBrowser) { return; } var container = this.container(); @@ -6792,30 +6624,29 @@ this.content.setAttribute('role', 'presentation'); container.appendChild(this.content); this._resizeDOM(); - }; + } // currently cache function is now working for stage, because stage has no its own canvas element - Stage.prototype.cache = function () { + cache() { Util.warn('Cache function is not allowed for stage. You may use cache only for layers, groups and shapes.'); return this; - }; - Stage.prototype.clearCache = function () { + } + clearCache() { return this; - }; + } /** * batch draw * @method * @name Konva.Stage#batchDraw * @return {Konva.Stage} this */ - Stage.prototype.batchDraw = function () { - this.children.each(function (layer) { + batchDraw() { + this.children.forEach(function (layer) { layer.batchDraw(); }); return this; - }; - return Stage; - }(Container)); - Stage.prototype.nodeType = STAGE$1; + } + } + Stage.prototype.nodeType = STAGE; _registerNode(Stage); /** * get/set container DOM element @@ -6837,24 +6668,24 @@ var patternImage = 'patternImage'; var linearGradient = 'linearGradient'; var radialGradient = 'radialGradient'; - var dummyContext; - function getDummyContext() { - if (dummyContext) { - return dummyContext; + let dummyContext$1; + function getDummyContext$1() { + if (dummyContext$1) { + return dummyContext$1; } - dummyContext = Util.createCanvasElement().getContext('2d'); - return dummyContext; + dummyContext$1 = Util.createCanvasElement().getContext('2d'); + return dummyContext$1; } - var shapes = {}; + const shapes = {}; // TODO: idea - use only "remove" (or destroy method) // how? on add, check that every inner shape has reference in konva store with color // on remove - clear that reference // the approach is good. But what if we want to cache the shape before we add it into the stage // what color to use for hit test? - function _fillFunc(context) { + function _fillFunc$2(context) { context.fill(); } - function _strokeFunc(context) { + function _strokeFunc$2(context) { context.stroke(); } function _fillFuncHit(context) { @@ -6976,21 +6807,19 @@ * } *}); */ - var Shape = /** @class */ (function (_super) { - __extends(Shape, _super); - function Shape(config) { - var _this = _super.call(this, config) || this; + class Shape extends Node { + constructor(config) { + super(config); // set colorKey - var key; + let key; while (true) { key = Util.getRandomColor(); if (key && !(key in shapes)) { break; } } - _this.colorKey = key; - shapes[key] = _this; - return _this; + this.colorKey = key; + shapes[key] = this; } /** * get canvas context tied to the layer @@ -6998,48 +6827,48 @@ * @name Konva.Shape#getContext * @returns {Konva.Context} */ - Shape.prototype.getContext = function () { + getContext() { return this.getLayer().getContext(); - }; + } /** * get canvas renderer tied to the layer. Note that this returns a canvas renderer, not a canvas element * @method * @name Konva.Shape#getCanvas * @returns {Konva.Canvas} */ - Shape.prototype.getCanvas = function () { + getCanvas() { return this.getLayer().getCanvas(); - }; - Shape.prototype.getSceneFunc = function () { + } + getSceneFunc() { return this.attrs.sceneFunc || this['_sceneFunc']; - }; - Shape.prototype.getHitFunc = function () { + } + getHitFunc() { return this.attrs.hitFunc || this['_hitFunc']; - }; + } /** * returns whether or not a shadow will be rendered * @method * @name Konva.Shape#hasShadow * @returns {Boolean} */ - Shape.prototype.hasShadow = function () { + hasShadow() { return this._getCache(HAS_SHADOW, this._hasShadow); - }; - Shape.prototype._hasShadow = function () { + } + _hasShadow() { return (this.shadowEnabled() && this.shadowOpacity() !== 0 && !!(this.shadowColor() || this.shadowBlur() || this.shadowOffsetX() || this.shadowOffsetY())); - }; - Shape.prototype._getFillPattern = function () { + } + _getFillPattern() { return this._getCache(patternImage, this.__getFillPattern); - }; - Shape.prototype.__getFillPattern = function () { + } + __getFillPattern() { if (this.fillPatternImage()) { - var ctx = getDummyContext(); - var pattern = ctx.createPattern(this.fillPatternImage(), this.fillPatternRepeat() || 'repeat'); + var ctx = getDummyContext$1(); + const pattern = ctx.createPattern(this.fillPatternImage(), this.fillPatternRepeat() || 'repeat'); if (pattern && pattern.setTransform) { pattern.setTransform({ a: this.fillPatternScaleX(), @@ -7047,19 +6876,19 @@ c: 0, d: this.fillPatternScaleY(), e: 0, - f: 0, + f: 0, // Vertical translation (moving). }); } return pattern; } - }; - Shape.prototype._getLinearGradient = function () { + } + _getLinearGradient() { return this._getCache(linearGradient, this.__getLinearGradient); - }; - Shape.prototype.__getLinearGradient = function () { + } + __getLinearGradient() { var colorStops = this.fillLinearGradientColorStops(); if (colorStops) { - var ctx = getDummyContext(); + var ctx = getDummyContext$1(); var start = this.fillLinearGradientStartPoint(); var end = this.fillLinearGradientEndPoint(); var grd = ctx.createLinearGradient(start.x, start.y, end.x, end.y); @@ -7069,14 +6898,14 @@ } return grd; } - }; - Shape.prototype._getRadialGradient = function () { + } + _getRadialGradient() { return this._getCache(radialGradient, this.__getRadialGradient); - }; - Shape.prototype.__getRadialGradient = function () { + } + __getRadialGradient() { var colorStops = this.fillRadialGradientColorStops(); if (colorStops) { - var ctx = getDummyContext(); + var ctx = getDummyContext$1(); var start = this.fillRadialGradientStartPoint(); var end = this.fillRadialGradientEndPoint(); var grd = ctx.createRadialGradient(start.x, start.y, this.fillRadialGradientStartRadius(), end.x, end.y, this.fillRadialGradientEndRadius()); @@ -7086,11 +6915,11 @@ } return grd; } - }; - Shape.prototype.getShadowRGBA = function () { + } + getShadowRGBA() { return this._getCache(SHADOW_RGBA, this._getShadowRGBA); - }; - Shape.prototype._getShadowRGBA = function () { + } + _getShadowRGBA() { if (this.hasShadow()) { var rgba = Util.colorToRGBA(this.shadowColor()); return ('rgba(' + @@ -7103,46 +6932,44 @@ rgba.a * (this.shadowOpacity() || 1) + ')'); } - }; + } /** * returns whether or not the shape will be filled * @method * @name Konva.Shape#hasFill * @returns {Boolean} */ - Shape.prototype.hasFill = function () { - var _this = this; + hasFill() { return this._calculate('hasFill', [ 'fillEnabled', 'fill', 'fillPatternImage', 'fillLinearGradientColorStops', 'fillRadialGradientColorStops', - ], function () { - return (_this.fillEnabled() && - !!(_this.fill() || - _this.fillPatternImage() || - _this.fillLinearGradientColorStops() || - _this.fillRadialGradientColorStops())); + ], () => { + return (this.fillEnabled() && + !!(this.fill() || + this.fillPatternImage() || + this.fillLinearGradientColorStops() || + this.fillRadialGradientColorStops())); }); - }; + } /** * returns whether or not the shape will be stroked * @method * @name Konva.Shape#hasStroke * @returns {Boolean} */ - Shape.prototype.hasStroke = function () { - var _this = this; + hasStroke() { return this._calculate('hasStroke', [ 'strokeEnabled', 'strokeWidth', 'stroke', 'strokeLinearGradientColorStops', - ], function () { - return (_this.strokeEnabled() && - _this.strokeWidth() && - !!(_this.stroke() || _this.strokeLinearGradientColorStops()) + ], () => { + return (this.strokeEnabled() && + this.strokeWidth() && + !!(this.stroke() || this.strokeLinearGradientColorStops()) // this.getStrokeRadialGradientColorStops() ); }); @@ -7152,9 +6979,9 @@ // !!(this.stroke() || this.strokeLinearGradientColorStops()) // // this.getStrokeRadialGradientColorStops() // ); - }; - Shape.prototype.hasHitStroke = function () { - var width = this.hitStrokeWidth(); + } + hasHitStroke() { + const width = this.hitStrokeWidth(); // on auto just check by stroke if (width === 'auto') { return this.hasStroke(); @@ -7162,7 +6989,7 @@ // we should enable hit stroke if stroke is enabled // and we have some value from width return this.strokeEnabled() && !!width; - }; + } /** * determines if point is in the shape, regardless if other shapes are on top of it. Note: because * this method clears a temporary canvas and then redraws the shape, it performs very poorly if executed many times @@ -7175,23 +7002,23 @@ * @param {Number} point.y * @returns {Boolean} */ - Shape.prototype.intersects = function (point) { + intersects(point) { var stage = this.getStage(), bufferHitCanvas = stage.bufferHitCanvas, p; bufferHitCanvas.getContext().clear(); this.drawHit(bufferHitCanvas, null, true); p = bufferHitCanvas.context.getImageData(Math.round(point.x), Math.round(point.y), 1, 1).data; return p[3] > 0; - }; - Shape.prototype.destroy = function () { + } + destroy() { Node.prototype.destroy.call(this); delete shapes[this.colorKey]; delete this.colorKey; return this; - }; + } // why do we need buffer canvas? // it give better result when a shape has // stroke with fill and with some opacity - Shape.prototype._useBufferCanvas = function (forceFill) { + _useBufferCanvas(forceFill) { // image and sprite still has "fill" as image // so they use that method with forced fill // it probably will be simpler, then copy/paste the code @@ -7201,24 +7028,24 @@ return false; } // force skip buffer canvas - var perfectDrawEnabled = (_a = this.attrs.perfectDrawEnabled) !== null && _a !== void 0 ? _a : true; + const perfectDrawEnabled = (_a = this.attrs.perfectDrawEnabled) !== null && _a !== void 0 ? _a : true; if (!perfectDrawEnabled) { return false; } - var hasFill = forceFill || this.hasFill(); - var hasStroke = this.hasStroke(); - var isTransparent = this.getAbsoluteOpacity() !== 1; + const hasFill = forceFill || this.hasFill(); + const hasStroke = this.hasStroke(); + const isTransparent = this.getAbsoluteOpacity() !== 1; if (hasFill && hasStroke && isTransparent) { return true; } - var hasShadow = this.hasShadow(); - var strokeForShadow = this.shadowForStrokeEnabled(); + const hasShadow = this.hasShadow(); + const strokeForShadow = this.shadowForStrokeEnabled(); if (hasFill && hasStroke && hasShadow && strokeForShadow) { return true; } return false; - }; - Shape.prototype.setStrokeHitEnabled = function (val) { + } + setStrokeHitEnabled(val) { Util.warn('strokeHitEnabled property is deprecated. Please use hitStrokeWidth instead.'); if (val) { this.hitStrokeWidth('auto'); @@ -7226,15 +7053,15 @@ else { this.hitStrokeWidth(0); } - }; - Shape.prototype.getStrokeHitEnabled = function () { + } + getStrokeHitEnabled() { if (this.hitStrokeWidth() === 0) { return false; } else { return true; } - }; + } /** * return self rectangle (x, y, width, height) of shape. * This method are not taken into account transformation and styles. @@ -7247,7 +7074,7 @@ * circle.getSelfRect(); // return {x: - circle.width() / 2, y: - circle.height() / 2, width:circle.width(), height:circle.height()} * */ - Shape.prototype.getSelfRect = function () { + getSelfRect() { var size = this.size(); return { x: this._centroid ? -size.width / 2 : 0, @@ -7255,32 +7082,31 @@ width: size.width, height: size.height, }; - }; - Shape.prototype.getClientRect = function (config) { - if (config === void 0) { config = {}; } - var skipTransform = config.skipTransform; - var relativeTo = config.relativeTo; - var fillRect = this.getSelfRect(); - var applyStroke = !config.skipStroke && this.hasStroke(); - var strokeWidth = (applyStroke && this.strokeWidth()) || 0; - var fillAndStrokeWidth = fillRect.width + strokeWidth; - var fillAndStrokeHeight = fillRect.height + strokeWidth; - var applyShadow = !config.skipShadow && this.hasShadow(); - var shadowOffsetX = applyShadow ? this.shadowOffsetX() : 0; - var shadowOffsetY = applyShadow ? this.shadowOffsetY() : 0; - var preWidth = fillAndStrokeWidth + Math.abs(shadowOffsetX); - var preHeight = fillAndStrokeHeight + Math.abs(shadowOffsetY); - var blurRadius = (applyShadow && this.shadowBlur()) || 0; - var width = preWidth + blurRadius * 2; - var height = preHeight + blurRadius * 2; + } + getClientRect(config = {}) { + const skipTransform = config.skipTransform; + const relativeTo = config.relativeTo; + const fillRect = this.getSelfRect(); + const applyStroke = !config.skipStroke && this.hasStroke(); + const strokeWidth = (applyStroke && this.strokeWidth()) || 0; + const fillAndStrokeWidth = fillRect.width + strokeWidth; + const fillAndStrokeHeight = fillRect.height + strokeWidth; + const applyShadow = !config.skipShadow && this.hasShadow(); + const shadowOffsetX = applyShadow ? this.shadowOffsetX() : 0; + const shadowOffsetY = applyShadow ? this.shadowOffsetY() : 0; + const preWidth = fillAndStrokeWidth + Math.abs(shadowOffsetX); + const preHeight = fillAndStrokeHeight + Math.abs(shadowOffsetY); + const blurRadius = (applyShadow && this.shadowBlur()) || 0; + const width = preWidth + blurRadius * 2; + const height = preHeight + blurRadius * 2; // if stroke, for example = 3 // we need to set x to 1.5, but after Math.round it will be 2 // as we have additional offset we need to increase width and height by 1 pixel - var roundingOffset = 0; + let roundingOffset = 0; if (Math.round(strokeWidth / 2) !== strokeWidth / 2) { roundingOffset = 1; } - var rect = { + const rect = { width: width + roundingOffset, height: height + roundingOffset, x: -Math.round(strokeWidth / 2 + blurRadius) + @@ -7294,8 +7120,8 @@ return this._transformedRect(rect, relativeTo); } return rect; - }; - Shape.prototype.drawScene = function (can, top) { + } + drawScene(can, top) { // basically there are 3 drawing modes // 1 - simple drawing when nothing is cached. // 2 - when we are caching current @@ -7356,16 +7182,14 @@ } context.restore(); return this; - }; - Shape.prototype.drawHit = function (can, top, skipDragCheck) { - if (skipDragCheck === void 0) { skipDragCheck = false; } + } + drawHit(can, top, skipDragCheck = false) { if (!this.shouldDrawHit(top, skipDragCheck)) { return this; } var layer = this.getLayer(), canvas = can || layer.hitCanvas, context = canvas && canvas.getContext(), drawFunc = this.hitFunc() || this.sceneFunc(), cachedCanvas = this._getCanvasCache(), cachedHitCanvas = cachedCanvas && cachedCanvas.hit; if (!this.colorKey) { - console.log(this); - Util.warn('Looks like your canvas has a destroyed shape in it. Do not reuse shape after you destroyed it. See the shape in logs above. If you want to reuse shape you should call remove() instead of destroy()'); + Util.warn('Looks like your canvas has a destroyed shape in it. Do not reuse shape after you destroyed it. If you want to reuse shape you should call remove() instead of destroy()'); } if (cachedHitCanvas) { context.save(); @@ -7380,7 +7204,7 @@ } context.save(); context._applyLineJoin(this); - var selfCache = this === top; + const selfCache = this === top; if (!selfCache) { var o = this.getAbsoluteTransform(top).getMatrix(); context.transform(o[0], o[1], o[2], o[3], o[4], o[5]); @@ -7388,7 +7212,7 @@ drawFunc.call(this, context, this); context.restore(); return this; - }; + } /** * draw hit graph using the cached scene canvas * @method @@ -7401,8 +7225,7 @@ * shape.cache(); * shape.drawHitFromCache(); */ - Shape.prototype.drawHitFromCache = function (alphaThreshold) { - if (alphaThreshold === void 0) { alphaThreshold = 0; } + drawHitFromCache(alphaThreshold = 0) { var cachedCanvas = this._getCanvasCache(), sceneCanvas = this._getCachedSceneCanvas(), hitCanvas = cachedCanvas.hit, hitContext = hitCanvas.getContext(), hitWidth = hitCanvas.getWidth(), hitHeight = hitCanvas.getHeight(), hitImageData, hitData, len, rgbColorKey, i, alpha; hitContext.clear(); hitContext.drawImage(sceneCanvas._canvas, 0, 0, hitWidth, hitHeight); @@ -7430,20 +7253,19 @@ Util.error('Unable to draw hit graph from cached scene canvas. ' + e.message); } return this; - }; - Shape.prototype.hasPointerCapture = function (pointerId) { + } + hasPointerCapture(pointerId) { return hasPointerCapture(pointerId, this); - }; - Shape.prototype.setPointerCapture = function (pointerId) { + } + setPointerCapture(pointerId) { setPointerCapture(pointerId, this); - }; - Shape.prototype.releaseCapture = function (pointerId) { + } + releaseCapture(pointerId) { releaseCapture(pointerId); - }; - return Shape; - }(Node)); - Shape.prototype._fillFunc = _fillFunc; - Shape.prototype._strokeFunc = _strokeFunc; + } + } + Shape.prototype._fillFunc = _fillFunc$2; + Shape.prototype._strokeFunc = _strokeFunc$2; Shape.prototype._fillFuncHit = _fillFuncHit; Shape.prototype._strokeFuncHit = _strokeFuncHit; Shape.prototype._centroid = false; @@ -8451,11 +8273,10 @@ drawHitFunc: 'hitFunc', getDrawHitFunc: 'getHitFunc', setDrawHitFunc: 'setHitFunc', - }); - Collection.mapMethods(Shape); + }); // constants - var HASH$1 = '#', BEFORE_DRAW = 'beforeDraw', DRAW = 'draw', + var HASH = '#', BEFORE_DRAW = 'beforeDraw', DRAW = 'draw', /* * 2 - 3 - 4 * | | @@ -8468,7 +8289,7 @@ { x: -1, y: -1 }, { x: 1, y: -1 }, { x: 1, y: 1 }, - { x: -1, y: 1 }, + { x: -1, y: 1 }, // 8 ], INTERSECTION_OFFSETS_LEN = INTERSECTION_OFFSETS.length; /** * Layer constructor. Layers are tied to their own canvas element and are used @@ -8511,50 +8332,56 @@ * stage.add(layer); * // now you can add shapes, groups into the layer */ - var Layer = /** @class */ (function (_super) { - __extends(Layer, _super); - function Layer(config) { - var _this = _super.call(this, config) || this; - _this.canvas = new SceneCanvas(); - _this.hitCanvas = new HitCanvas({ + class Layer extends Container { + constructor(config) { + super(config); + this.canvas = new SceneCanvas(); + this.hitCanvas = new HitCanvas({ pixelRatio: 1, }); - _this._waitingForDraw = false; - _this.on('visibleChange.konva', _this._checkVisibility); - _this._checkVisibility(); - _this.on('imageSmoothingEnabledChange.konva', _this._setSmoothEnabled); - _this._setSmoothEnabled(); - return _this; + this._waitingForDraw = false; + this.on('visibleChange.konva', this._checkVisibility); + this._checkVisibility(); + this.on('imageSmoothingEnabledChange.konva', this._setSmoothEnabled); + this._setSmoothEnabled(); } // for nodejs? - Layer.prototype.createPNGStream = function () { - var c = this.canvas._canvas; + createPNGStream() { + const c = this.canvas._canvas; return c.createPNGStream(); - }; + } /** * get layer canvas wrapper * @method * @name Konva.Layer#getCanvas */ - Layer.prototype.getCanvas = function () { + getCanvas() { return this.canvas; - }; + } + /** + * get native canvas element + * @method + * @name Konva.Layer#getCanvas + */ + getCanvasElement() { + return this.canvas._canvas; + } /** * get layer hit canvas * @method * @name Konva.Layer#getHitCanvas */ - Layer.prototype.getHitCanvas = function () { + getHitCanvas() { return this.hitCanvas; - }; + } /** * get layer canvas context * @method * @name Konva.Layer#getContext */ - Layer.prototype.getContext = function () { + getContext() { return this.getCanvas().getContext(); - }; + } /** * clear scene and hit canvas contexts tied to the layer. * This function doesn't remove any nodes. It just clear canvas element. @@ -8574,14 +8401,14 @@ * height : 100 * }); */ - Layer.prototype.clear = function (bounds) { + clear(bounds) { this.getContext().clear(bounds); this.getHitCanvas().getContext().clear(bounds); return this; - }; + } // extend Node.prototype.setZIndex - Layer.prototype.setZIndex = function (index) { - _super.prototype.setZIndex.call(this, index); + setZIndex(index) { + super.setZIndex(index); var stage = this.getStage(); if (stage) { stage.content.removeChild(this.getCanvas()._canvas); @@ -8593,8 +8420,8 @@ } } return this; - }; - Layer.prototype.moveToTop = function () { + } + moveToTop() { Node.prototype.moveToTop.call(this); var stage = this.getStage(); if (stage) { @@ -8602,8 +8429,8 @@ stage.content.appendChild(this.getCanvas()._canvas); } return true; - }; - Layer.prototype.moveUp = function () { + } + moveUp() { var moved = Node.prototype.moveUp.call(this); if (!moved) { return false; @@ -8620,9 +8447,9 @@ stage.content.appendChild(this.getCanvas()._canvas); } return true; - }; + } // extend Node.prototype.moveDown - Layer.prototype.moveDown = function () { + moveDown() { if (Node.prototype.moveDown.call(this)) { var stage = this.getStage(); if (stage) { @@ -8633,9 +8460,9 @@ return true; } return false; - }; + } // extend Node.prototype.moveToBottom - Layer.prototype.moveToBottom = function () { + moveToBottom() { if (Node.prototype.moveToBottom.call(this)) { var stage = this.getStage(); if (stage) { @@ -8646,54 +8473,53 @@ return true; } return false; - }; - Layer.prototype.getLayer = function () { + } + getLayer() { return this; - }; - Layer.prototype.remove = function () { + } + remove() { var _canvas = this.getCanvas()._canvas; Node.prototype.remove.call(this); if (_canvas && _canvas.parentNode && Util._isInDocument(_canvas)) { _canvas.parentNode.removeChild(_canvas); } return this; - }; - Layer.prototype.getStage = function () { + } + getStage() { return this.parent; - }; - Layer.prototype.setSize = function (_a) { - var width = _a.width, height = _a.height; + } + setSize({ width, height }) { this.canvas.setSize(width, height); this.hitCanvas.setSize(width, height); this._setSmoothEnabled(); return this; - }; - Layer.prototype._validateAdd = function (child) { + } + _validateAdd(child) { var type = child.getType(); if (type !== 'Group' && type !== 'Shape') { Util.throw('You may only add groups and shapes to a layer.'); } - }; - Layer.prototype._toKonvaCanvas = function (config) { + } + _toKonvaCanvas(config) { config = config || {}; config.width = config.width || this.getWidth(); config.height = config.height || this.getHeight(); config.x = config.x !== undefined ? config.x : this.x(); config.y = config.y !== undefined ? config.y : this.y(); return Node.prototype._toKonvaCanvas.call(this, config); - }; - Layer.prototype._checkVisibility = function () { - var visible = this.visible(); + } + _checkVisibility() { + const visible = this.visible(); if (visible) { this.canvas._canvas.style.display = 'block'; } else { this.canvas._canvas.style.display = 'none'; } - }; - Layer.prototype._setSmoothEnabled = function () { + } + _setSmoothEnabled() { this.getContext()._context.imageSmoothingEnabled = this.imageSmoothingEnabled(); - }; + } /** * get/set width of layer. getter return width of stage. setter doing nothing. * if you want change width use `stage.width(value);` @@ -8703,14 +8529,14 @@ * @example * var width = layer.width(); */ - Layer.prototype.getWidth = function () { + getWidth() { if (this.parent) { return this.parent.width(); } - }; - Layer.prototype.setWidth = function () { + } + setWidth() { Util.warn('Can not change width of layer. Use "stage.width(value)" function instead.'); - }; + } /** * get/set height of layer.getter return height of stage. setter doing nothing. * if you want change height use `stage.height(value);` @@ -8720,14 +8546,14 @@ * @example * var height = layer.height(); */ - Layer.prototype.getHeight = function () { + getHeight() { if (this.parent) { return this.parent.height(); } - }; - Layer.prototype.setHeight = function () { + } + setHeight() { Util.warn('Can not change height of layer. Use "stage.height(value)" function instead.'); - }; + } /** * batch draw. this function will not do immediate draw * but it will schedule drawing to next tick (requestAnimFrame) @@ -8735,17 +8561,16 @@ * @name Konva.Layer#batchDraw * @return {Konva.Layer} this */ - Layer.prototype.batchDraw = function () { - var _this = this; + batchDraw() { if (!this._waitingForDraw) { this._waitingForDraw = true; - Util.requestAnimFrame(function () { - _this.draw(); - _this._waitingForDraw = false; + Util.requestAnimFrame(() => { + this.draw(); + this._waitingForDraw = false; }); } return this; - }; + } /** * get visible intersection shape. This is the preferred * method for determining if a point intersects a shape or not @@ -8762,7 +8587,7 @@ * // or if you interested in shape parent: * var group = layer.getIntersection({x: 50, y: 50}, 'Group'); */ - Layer.prototype.getIntersection = function (pos, selector) { + getIntersection(pos, selector) { if (!this.isListening() || !this.isVisible()) { return null; } @@ -8771,13 +8596,13 @@ var spiralSearchDistance = 1; var continueSearch = false; while (true) { - for (var i = 0; i < INTERSECTION_OFFSETS_LEN; i++) { - var intersectionOffset = INTERSECTION_OFFSETS[i]; - var obj = this._getIntersection({ + for (let i = 0; i < INTERSECTION_OFFSETS_LEN; i++) { + const intersectionOffset = INTERSECTION_OFFSETS[i]; + const obj = this._getIntersection({ x: pos.x + intersectionOffset.x * spiralSearchDistance, y: pos.y + intersectionOffset.y * spiralSearchDistance, }); - var shape = obj.shape; + const shape = obj.shape; if (shape && selector) { return shape.findAncestor(selector, true); } @@ -8800,15 +8625,15 @@ return null; } } - }; - Layer.prototype._getIntersection = function (pos) { - var ratio = this.hitCanvas.pixelRatio; - var p = this.hitCanvas.context.getImageData(Math.round(pos.x * ratio), Math.round(pos.y * ratio), 1, 1).data; - var p3 = p[3]; + } + _getIntersection(pos) { + const ratio = this.hitCanvas.pixelRatio; + const p = this.hitCanvas.context.getImageData(Math.round(pos.x * ratio), Math.round(pos.y * ratio), 1, 1).data; + const p3 = p[3]; // fully opaque pixel if (p3 === 255) { - var colorKey = Util._rgbToHex(p[0], p[1], p[2]); - var shape = shapes[HASH$1 + colorKey]; + const colorKey = Util._rgbToHex(p[0], p[1], p[2]); + const shape = shapes[HASH + colorKey]; if (shape) { return { shape: shape, @@ -8826,8 +8651,8 @@ } // empty pixel return {}; - }; - Layer.prototype.drawScene = function (can, top) { + } + drawScene(can, top) { var layer = this.getLayer(), canvas = can || (layer && layer.getCanvas()); this._fire(BEFORE_DRAW, { node: this, @@ -8840,49 +8665,49 @@ node: this, }); return this; - }; - Layer.prototype.drawHit = function (can, top) { + } + drawHit(can, top) { var layer = this.getLayer(), canvas = can || (layer && layer.hitCanvas); if (layer && layer.clearBeforeDraw()) { layer.getHitCanvas().getContext().clear(); } Container.prototype.drawHit.call(this, canvas, top); return this; - }; + } /** * enable hit graph. **DEPRECATED!** Use `layer.listening(true)` instead. * @name Konva.Layer#enableHitGraph * @method * @returns {Layer} */ - Layer.prototype.enableHitGraph = function () { + enableHitGraph() { this.hitGraphEnabled(true); return this; - }; + } /** * disable hit graph. **DEPRECATED!** Use `layer.listening(false)` instead. * @name Konva.Layer#disableHitGraph * @method * @returns {Layer} */ - Layer.prototype.disableHitGraph = function () { + disableHitGraph() { this.hitGraphEnabled(false); return this; - }; - Layer.prototype.setHitGraphEnabled = function (val) { + } + setHitGraphEnabled(val) { Util.warn('hitGraphEnabled method is deprecated. Please use layer.listening() instead.'); this.listening(val); - }; - Layer.prototype.getHitGraphEnabled = function (val) { + } + getHitGraphEnabled(val) { Util.warn('hitGraphEnabled method is deprecated. Please use layer.listening() instead.'); return this.listening(); - }; + } /** * Show or hide hit canvas over the stage. May be useful for debugging custom hitFunc * @name Konva.Layer#toggleHitCanvas * @method */ - Layer.prototype.toggleHitCanvas = function () { + toggleHitCanvas() { if (!this.parent) { return; } @@ -8894,9 +8719,8 @@ else { parent.content.appendChild(this.hitCanvas._canvas); } - }; - return Layer; - }(Container)); + } + } Layer.prototype.nodeType = 'Layer'; _registerNode(Layer); /** @@ -8952,8 +8776,7 @@ * * // enable hit graph * layer.hitGraphEnabled(true); - */ - Collection.mapMethods(Layer); + */ /** * FastLayer constructor. **DEPRECATED!** Please use `Konva.Layer({ listening: false})` instead. Layers are tied to their own canvas element and are used @@ -8974,19 +8797,15 @@ * @example * var layer = new Konva.FastLayer(); */ - var FastLayer = /** @class */ (function (_super) { - __extends(FastLayer, _super); - function FastLayer(attrs) { - var _this = _super.call(this, attrs) || this; - _this.listening(false); + class FastLayer extends Layer { + constructor(attrs) { + super(attrs); + this.listening(false); Util.warn('Konva.Fast layer is deprecated. Please use "new Konva.Layer({ listening: false })" instead.'); - return _this; } - return FastLayer; - }(Layer)); + } FastLayer.prototype.nodeType = 'FastLayer'; - _registerNode(FastLayer); - Collection.mapMethods(FastLayer); + _registerNode(FastLayer); /** * Group constructor. Groups are used to contain shapes or other groups. @@ -9024,22 +8843,16 @@ * @example * var group = new Konva.Group(); */ - var Group = /** @class */ (function (_super) { - __extends(Group, _super); - function Group() { - return _super !== null && _super.apply(this, arguments) || this; - } - Group.prototype._validateAdd = function (child) { + class Group extends Container { + _validateAdd(child) { var type = child.getType(); if (type !== 'Group' && type !== 'Shape') { Util.throw('You may only add groups and shapes to groups.'); } - }; - return Group; - }(Container)); + } + } Group.prototype.nodeType = 'Group'; - _registerNode(Group); - Collection.mapMethods(Group); + _registerNode(Group); var now = (function () { if (glob.performance && glob.performance.now) { @@ -9073,14 +8886,14 @@ * * anim.start(); */ - var Animation = /** @class */ (function () { - function Animation(func, layers) { + class Animation { + constructor(func, layers) { this.id = Animation.animIdCounter++; this.frame = { time: 0, timeDiff: 0, lastTime: now(), - frameRate: 0 + frameRate: 0, }; this.func = func; this.setLayers(layers); @@ -9092,7 +8905,7 @@ * @param {Konva.Layer|Array} [layers] layer(s) to be redrawn. Can be a layer, an array of layers, or null. Not specifying a node will result in no redraw. * @return {Konva.Animation} this */ - Animation.prototype.setLayers = function (layers) { + setLayers(layers) { var lays = []; // if passing in no layers if (!layers) { @@ -9100,7 +8913,7 @@ } else if (layers.length > 0) { // if passing in an array of Layers - // NOTE: layers could be an array or Konva.Collection. for simplicity, I'm just inspecting + // NOTE: layers could be an array. for simplicity, I'm just inspecting // the length property to check for both cases lays = layers; } @@ -9110,16 +8923,16 @@ } this.layers = lays; return this; - }; + } /** * get layers * @method * @name Konva.Animation#getLayers * @return {Array} Array of Konva.Layer */ - Animation.prototype.getLayers = function () { + getLayers() { return this.layers; - }; + } /** * add layer. Returns true if the layer was added, and false if it was not * @method @@ -9127,7 +8940,7 @@ * @param {Konva.Layer} layer to add * @return {Bool} true if layer is added to animation, otherwise false */ - Animation.prototype.addLayer = function (layer) { + addLayer(layer) { var layers = this.layers, len = layers.length, n; // don't add the layer if it already exists for (n = 0; n < len; n++) { @@ -9137,14 +8950,14 @@ } this.layers.push(layer); return true; - }; + } /** * determine if animation is running or not. returns true or false * @method * @name Konva.Animation#isRunning * @return {Bool} is animation running? */ - Animation.prototype.isRunning = function () { + isRunning() { var a = Animation, animations = a.animations, len = animations.length, n; for (n = 0; n < len; n++) { if (animations[n].id === this.id) { @@ -9152,41 +8965,41 @@ } } return false; - }; + } /** * start animation * @method * @name Konva.Animation#start * @return {Konva.Animation} this */ - Animation.prototype.start = function () { + start() { this.stop(); this.frame.timeDiff = 0; this.frame.lastTime = now(); Animation._addAnimation(this); return this; - }; + } /** * stop animation * @method * @name Konva.Animation#stop * @return {Konva.Animation} this */ - Animation.prototype.stop = function () { + stop() { Animation._removeAnimation(this); return this; - }; - Animation.prototype._updateFrameObject = function (time) { + } + _updateFrameObject(time) { this.frame.timeDiff = time - this.frame.lastTime; this.frame.lastTime = time; this.frame.time += this.frame.timeDiff; this.frame.frameRate = 1000 / this.frame.timeDiff; - }; - Animation._addAnimation = function (anim) { + } + static _addAnimation(anim) { this.animations.push(anim); this._handleAnimation(); - }; - Animation._removeAnimation = function (anim) { + } + static _removeAnimation(anim) { var id = anim.id, animations = this.animations, len = animations.length, n; for (n = 0; n < len; n++) { if (animations[n].id === id) { @@ -9194,8 +9007,8 @@ break; } } - }; - Animation._runFrames = function () { + } + static _runFrames() { var layerHash = {}, animations = this.animations, anim, layers, func, n, i, layersLen, layer, key, needRedraw; /* * loop through all animations and execute animation @@ -9238,28 +9051,27 @@ } layerHash[key].draw(); } - }; - Animation._animationLoop = function () { + } + static _animationLoop() { var Anim = Animation; if (Anim.animations.length) { Anim._runFrames(); - requestAnimationFrame(Anim._animationLoop); + Util.requestAnimFrame(Anim._animationLoop); } else { Anim.animRunning = false; } - }; - Animation._handleAnimation = function () { + } + static _handleAnimation() { if (!this.animRunning) { this.animRunning = true; - requestAnimationFrame(this._animationLoop); + Util.requestAnimFrame(this._animationLoop); } - }; - Animation.animations = []; - Animation.animIdCounter = 0; - Animation.animRunning = false; - return Animation; - }()); + } + } + Animation.animations = []; + Animation.animIdCounter = 0; + Animation.animRunning = false; var blacklist = { node: 1, @@ -9267,9 +9079,9 @@ easing: 1, onFinish: 1, yoyo: 1, - }, PAUSED = 1, PLAYING = 2, REVERSING = 3, idCounter$1 = 0, colorAttrs = ['fill', 'stroke', 'shadowColor']; - var TweenEngine = /** @class */ (function () { - function TweenEngine(prop, propFunc, func, begin, finish, duration, yoyo) { + }, PAUSED = 1, PLAYING = 2, REVERSING = 3, idCounter = 0, colorAttrs = ['fill', 'stroke', 'shadowColor']; + class TweenEngine { + constructor(prop, propFunc, func, begin, finish, duration, yoyo) { this.prop = prop; this.propFunc = propFunc; this.begin = begin; @@ -9286,13 +9098,13 @@ this._change = finish - this.begin; this.pause(); } - TweenEngine.prototype.fire = function (str) { + fire(str) { var handler = this[str]; if (handler) { handler(); } - }; - TweenEngine.prototype.setTime = function (t) { + } + setTime(t) { if (t > this.duration) { if (this.yoyo) { this._time = this.duration; @@ -9315,57 +9127,57 @@ this._time = t; this.update(); } - }; - TweenEngine.prototype.getTime = function () { + } + getTime() { return this._time; - }; - TweenEngine.prototype.setPosition = function (p) { + } + setPosition(p) { this.prevPos = this._pos; this.propFunc(p); this._pos = p; - }; - TweenEngine.prototype.getPosition = function (t) { + } + getPosition(t) { if (t === undefined) { t = this._time; } return this.func(t, this.begin, this._change, this.duration); - }; - TweenEngine.prototype.play = function () { + } + play() { this.state = PLAYING; this._startTime = this.getTimer() - this._time; this.onEnterFrame(); this.fire('onPlay'); - }; - TweenEngine.prototype.reverse = function () { + } + reverse() { this.state = REVERSING; this._time = this.duration - this._time; this._startTime = this.getTimer() - this._time; this.onEnterFrame(); this.fire('onReverse'); - }; - TweenEngine.prototype.seek = function (t) { + } + seek(t) { this.pause(); this._time = t; this.update(); this.fire('onSeek'); - }; - TweenEngine.prototype.reset = function () { + } + reset() { this.pause(); this._time = 0; this.update(); this.fire('onReset'); - }; - TweenEngine.prototype.finish = function () { + } + finish() { this.pause(); this._time = this.duration; this.update(); this.fire('onFinish'); - }; - TweenEngine.prototype.update = function () { + } + update() { this.setPosition(this.getPosition(this._time)); this.fire('onUpdate'); - }; - TweenEngine.prototype.onEnterFrame = function () { + } + onEnterFrame() { var t = this.getTimer() - this._startTime; if (this.state === PLAYING) { this.setTime(t); @@ -9373,16 +9185,15 @@ else if (this.state === REVERSING) { this.setTime(this.duration - t); } - }; - TweenEngine.prototype.pause = function () { + } + pause() { this.state = PAUSED; this.fire('onPause'); - }; - TweenEngine.prototype.getTimer = function () { + } + getTimer() { return new Date().getTime(); - }; - return TweenEngine; - }()); + } + } /** * Tween constructor. Tweens enable you to animate a node between the current state and a new state. * You can play, pause, reverse, seek, reset, and finish tweens. By default, tweens are animated using @@ -9409,8 +9220,8 @@ * // pause tween * tween.pause(); */ - var Tween = /** @class */ (function () { - function Tween(config) { + class Tween { + constructor(config) { var that = this, node = config.node, nodeId = node._id, duration, easing = config.easing || Easings.Linear, yoyo = !!config.yoyo, key; if (typeof config.duration === 'undefined') { duration = 0.3; @@ -9423,9 +9234,9 @@ duration = config.duration; } this.node = node; - this._id = idCounter$1++; + this._id = idCounter++; var layers = node.getLayer() || - (node instanceof Konva['Stage'] ? node.getLayers() : null); + (node instanceof Konva$2['Stage'] ? node.getLayers() : null); if (!layers) { Util.error('Tween constructor have `node` that is not in a layer. Please add node into layer first.'); } @@ -9458,7 +9269,7 @@ this.onReset = config.onReset; this.onUpdate = config.onUpdate; } - Tween.prototype._addAttr = function (key, end) { + _addAttr(key, end) { var node = this.node, nodeId = node._id, start, diff, tweenId, n, len, trueEnd, trueStart, endRGBA; // remove conflict from tween map if it exists tweenId = Tween.tweens[nodeId][key]; @@ -9529,8 +9340,8 @@ trueStart: trueStart, }; Tween.tweens[nodeId][key] = this._id; - }; - Tween.prototype._tweenFunc = function (i) { + } + _tweenFunc(i) { var node = this.node, attrs = Tween.attrs[node._id][this._id], key, attr, start, diff, newVal, n, len, end; for (key in attrs) { attr = attrs[key]; @@ -9581,78 +9392,77 @@ } node.setAttr(key, newVal); } - }; - Tween.prototype._addListeners = function () { - var _this = this; + } + _addListeners() { // start listeners - this.tween.onPlay = function () { - _this.anim.start(); + this.tween.onPlay = () => { + this.anim.start(); }; - this.tween.onReverse = function () { - _this.anim.start(); + this.tween.onReverse = () => { + this.anim.start(); }; // stop listeners - this.tween.onPause = function () { - _this.anim.stop(); + this.tween.onPause = () => { + this.anim.stop(); }; - this.tween.onFinish = function () { - var node = _this.node; + this.tween.onFinish = () => { + var node = this.node; // after tweening points of line we need to set original end - var attrs = Tween.attrs[node._id][_this._id]; + var attrs = Tween.attrs[node._id][this._id]; if (attrs.points && attrs.points.trueEnd) { node.setAttr('points', attrs.points.trueEnd); } - if (_this.onFinish) { - _this.onFinish.call(_this); + if (this.onFinish) { + this.onFinish.call(this); } }; - this.tween.onReset = function () { - var node = _this.node; + this.tween.onReset = () => { + var node = this.node; // after tweening points of line we need to set original start - var attrs = Tween.attrs[node._id][_this._id]; + var attrs = Tween.attrs[node._id][this._id]; if (attrs.points && attrs.points.trueStart) { node.points(attrs.points.trueStart); } - if (_this.onReset) { - _this.onReset(); + if (this.onReset) { + this.onReset(); } }; - this.tween.onUpdate = function () { - if (_this.onUpdate) { - _this.onUpdate.call(_this); + this.tween.onUpdate = () => { + if (this.onUpdate) { + this.onUpdate.call(this); } }; - }; + } /** * play * @method * @name Konva.Tween#play * @returns {Tween} */ - Tween.prototype.play = function () { + play() { this.tween.play(); return this; - }; + } /** * reverse * @method * @name Konva.Tween#reverse * @returns {Tween} */ - Tween.prototype.reverse = function () { + reverse() { this.tween.reverse(); return this; - }; + } /** * reset * @method * @name Konva.Tween#reset * @returns {Tween} */ - Tween.prototype.reset = function () { + reset() { this.tween.reset(); return this; - }; + } /** * seek * @method @@ -9660,47 +9470,46 @@ * @param {Integer} t time in seconds between 0 and the duration * @returns {Tween} */ - Tween.prototype.seek = function (t) { + seek(t) { this.tween.seek(t * 1000); return this; - }; + } /** * pause * @method * @name Konva.Tween#pause * @returns {Tween} */ - Tween.prototype.pause = function () { + pause() { this.tween.pause(); return this; - }; + } /** * finish * @method * @name Konva.Tween#finish * @returns {Tween} */ - Tween.prototype.finish = function () { + finish() { this.tween.finish(); return this; - }; + } /** * destroy * @method * @name Konva.Tween#destroy */ - Tween.prototype.destroy = function () { + destroy() { var nodeId = this.node._id, thisId = this._id, attrs = Tween.tweens[nodeId], key; this.pause(); for (key in attrs) { delete Tween.tweens[nodeId][key]; } delete Tween.attrs[nodeId][thisId]; - }; - Tween.attrs = {}; - Tween.tweens = {}; - return Tween; - }()); + } + } + Tween.attrs = {}; + Tween.tweens = {}; /** * Tween node properties. Shorter usage of {@link Konva.Tween} object. * @@ -9735,13 +9544,13 @@ * @namespace Easings * @memberof Konva */ - var Easings = { + const Easings = { /** * back ease in * @function * @memberof Konva.Easings */ - BackEaseIn: function (t, b, c, d) { + BackEaseIn(t, b, c, d) { var s = 1.70158; return c * (t /= d) * t * ((s + 1) * t - s) + b; }, @@ -9750,7 +9559,7 @@ * @function * @memberof Konva.Easings */ - BackEaseOut: function (t, b, c, d) { + BackEaseOut(t, b, c, d) { var s = 1.70158; return c * ((t = t / d - 1) * t * ((s + 1) * t + s) + 1) + b; }, @@ -9759,7 +9568,7 @@ * @function * @memberof Konva.Easings */ - BackEaseInOut: function (t, b, c, d) { + BackEaseInOut(t, b, c, d) { var s = 1.70158; if ((t /= d / 2) < 1) { return (c / 2) * (t * t * (((s *= 1.525) + 1) * t - s)) + b; @@ -9771,7 +9580,7 @@ * @function * @memberof Konva.Easings */ - ElasticEaseIn: function (t, b, c, d, a, p) { + ElasticEaseIn(t, b, c, d, a, p) { // added s = 0 var s = 0; if (t === 0) { @@ -9799,7 +9608,7 @@ * @function * @memberof Konva.Easings */ - ElasticEaseOut: function (t, b, c, d, a, p) { + ElasticEaseOut(t, b, c, d, a, p) { // added s = 0 var s = 0; if (t === 0) { @@ -9827,7 +9636,7 @@ * @function * @memberof Konva.Easings */ - ElasticEaseInOut: function (t, b, c, d, a, p) { + ElasticEaseInOut(t, b, c, d, a, p) { // added s = 0 var s = 0; if (t === 0) { @@ -9865,7 +9674,7 @@ * @function * @memberof Konva.Easings */ - BounceEaseOut: function (t, b, c, d) { + BounceEaseOut(t, b, c, d) { if ((t /= d) < 1 / 2.75) { return c * (7.5625 * t * t) + b; } @@ -9884,7 +9693,7 @@ * @function * @memberof Konva.Easings */ - BounceEaseIn: function (t, b, c, d) { + BounceEaseIn(t, b, c, d) { return c - Easings.BounceEaseOut(d - t, 0, c, d) + b; }, /** @@ -9892,7 +9701,7 @@ * @function * @memberof Konva.Easings */ - BounceEaseInOut: function (t, b, c, d) { + BounceEaseInOut(t, b, c, d) { if (t < d / 2) { return Easings.BounceEaseIn(t * 2, 0, c, d) * 0.5 + b; } @@ -9905,7 +9714,7 @@ * @function * @memberof Konva.Easings */ - EaseIn: function (t, b, c, d) { + EaseIn(t, b, c, d) { return c * (t /= d) * t + b; }, /** @@ -9913,7 +9722,7 @@ * @function * @memberof Konva.Easings */ - EaseOut: function (t, b, c, d) { + EaseOut(t, b, c, d) { return -c * (t /= d) * (t - 2) + b; }, /** @@ -9921,7 +9730,7 @@ * @function * @memberof Konva.Easings */ - EaseInOut: function (t, b, c, d) { + EaseInOut(t, b, c, d) { if ((t /= d / 2) < 1) { return (c / 2) * t * t + b; } @@ -9932,7 +9741,7 @@ * @function * @memberof Konva.Easings */ - StrongEaseIn: function (t, b, c, d) { + StrongEaseIn(t, b, c, d) { return c * (t /= d) * t * t * t * t + b; }, /** @@ -9940,7 +9749,7 @@ * @function * @memberof Konva.Easings */ - StrongEaseOut: function (t, b, c, d) { + StrongEaseOut(t, b, c, d) { return c * ((t = t / d - 1) * t * t * t * t + 1) + b; }, /** @@ -9948,7 +9757,7 @@ * @function * @memberof Konva.Easings */ - StrongEaseInOut: function (t, b, c, d) { + StrongEaseInOut(t, b, c, d) { if ((t /= d / 2) < 1) { return (c / 2) * t * t * t * t * t + b; } @@ -9959,33 +9768,32 @@ * @function * @memberof Konva.Easings */ - Linear: function (t, b, c, d) { + Linear(t, b, c, d) { return (c * t) / d + b; }, }; // what is core parts of Konva? - var Konva$1 = Util._assign(Konva, { - Collection: Collection, - Util: Util, - Transform: Transform, - Node: Node, - ids: ids, - names: names, - Container: Container, - Stage: Stage, - stages: stages, - Layer: Layer, - FastLayer: FastLayer, - Group: Group, - DD: DD, - Shape: Shape, - shapes: shapes, - Animation: Animation, - Tween: Tween, - Easings: Easings, - Context: Context, - Canvas: Canvas + const Konva$1 = Util._assign(Konva$2, { + Util, + Transform, + Node, + ids, + names, + Container, + Stage, + stages, + Layer, + FastLayer, + Group, + DD, + Shape, + shapes, + Animation, + Tween, + Easings, + Context, + Canvas, }); /** @@ -10084,33 +9892,28 @@ * rotationDeg: -120 * }); */ - var Arc = /** @class */ (function (_super) { - __extends(Arc, _super); - function Arc() { - return _super !== null && _super.apply(this, arguments) || this; - } - Arc.prototype._sceneFunc = function (context) { - var angle = Konva.getAngle(this.angle()), clockwise = this.clockwise(); + class Arc extends Shape { + _sceneFunc(context) { + var angle = Konva$2.getAngle(this.angle()), clockwise = this.clockwise(); context.beginPath(); context.arc(0, 0, this.outerRadius(), 0, angle, clockwise); context.arc(0, 0, this.innerRadius(), angle, 0, !clockwise); context.closePath(); context.fillStrokeShape(this); - }; - Arc.prototype.getWidth = function () { + } + getWidth() { return this.outerRadius() * 2; - }; - Arc.prototype.getHeight = function () { + } + getHeight() { return this.outerRadius() * 2; - }; - Arc.prototype.setWidth = function (width) { + } + setWidth(width) { this.outerRadius(width / 2); - }; - Arc.prototype.setHeight = function (height) { + } + setHeight(height) { this.outerRadius(height / 2); - }; - return Arc; - }(Shape)); + } + } Arc.prototype._centroid = true; Arc.prototype.className = 'Arc'; Arc.prototype._attrsAffectingSize = ['innerRadius', 'outerRadius']; @@ -10174,8 +9977,7 @@ * * // draw arc clockwise * arc.clockwise(true); - */ - Collection.mapMethods(Arc); + */ /** * Line constructor.  Lines are defined by an array of points and @@ -10272,16 +10074,14 @@ * tension: 1 * }); */ - var Line = /** @class */ (function (_super) { - __extends(Line, _super); - function Line(config) { - var _this = _super.call(this, config) || this; - _this.on('pointsChange.konva tensionChange.konva closedChange.konva bezierChange.konva', function () { + class Line extends Shape { + constructor(config) { + super(config); + this.on('pointsChange.konva tensionChange.konva closedChange.konva bezierChange.konva', function () { this._clearCache('tensionPoints'); }); - return _this; } - Line.prototype._sceneFunc = function (context) { + _sceneFunc(context) { var points = this.points(), length = points.length, tension = this.tension(), closed = this.closed(), bezier = this.bezier(), tp, len, n; if (!length) { return; @@ -10325,19 +10125,19 @@ // open e.g. lines and splines context.strokeShape(this); } - }; - Line.prototype.getTensionPoints = function () { + } + getTensionPoints() { return this._getCache('tensionPoints', this._getTensionPoints); - }; - Line.prototype._getTensionPoints = function () { + } + _getTensionPoints() { if (this.closed()) { return this._getTensionPointsClosed(); } else { return Util._expandPoints(this.points(), this.tension()); } - }; - Line.prototype._getTensionPointsClosed = function () { + } + _getTensionPointsClosed() { var p = this.points(), len = p.length, tension = this.tension(), firstControlPoints = Util._getControlPoints(p[len - 2], p[len - 1], p[0], p[1], p[2], p[3], tension), lastControlPoints = Util._getControlPoints(p[len - 4], p[len - 3], p[len - 2], p[len - 1], p[0], p[1], tension), middle = Util._expandPoints(p, tension), tp = [firstControlPoints[2], firstControlPoints[3]] .concat(middle) .concat([ @@ -10350,35 +10150,35 @@ firstControlPoints[0], firstControlPoints[1], p[0], - p[1] + p[1], ]); return tp; - }; - Line.prototype.getWidth = function () { + } + getWidth() { return this.getSelfRect().width; - }; - Line.prototype.getHeight = function () { + } + getHeight() { return this.getSelfRect().height; - }; + } // overload size detection - Line.prototype.getSelfRect = function () { + getSelfRect() { var points = this.points(); if (points.length < 4) { return { x: points[0] || 0, y: points[1] || 0, width: 0, - height: 0 + height: 0, }; } if (this.tension() !== 0) { - points = __spreadArrays([ + points = [ points[0], - points[1] - ], this._getTensionPoints(), [ + points[1], + ...this._getTensionPoints(), points[points.length - 2], - points[points.length - 1] - ]); + points[points.length - 1], + ]; } else { points = this.points(); @@ -10400,11 +10200,10 @@ x: minX, y: minY, width: maxX - minX, - height: maxY - minY + height: maxY - minY, }; - }; - return Line; - }(Shape)); + } + } Line.prototype.className = 'Line'; Line.prototype._attrsAffectingSize = ['points', 'bezier', 'tension']; _registerNode(Line); @@ -10470,8 +10269,7 @@ * * // push a new point * line.points(line.points().concat([70, 80])); - */ - Collection.mapMethods(Line); + */ /** * Arrow constructor @@ -10568,13 +10366,9 @@ * pointerWidth : 12 * }); */ - var Arrow = /** @class */ (function (_super) { - __extends(Arrow, _super); - function Arrow() { - return _super !== null && _super.apply(this, arguments) || this; - } - Arrow.prototype._sceneFunc = function (ctx) { - _super.prototype._sceneFunc.call(this, ctx); + class Arrow extends Line { + _sceneFunc(ctx) { + super._sceneFunc(ctx); var PI2 = Math.PI * 2; var points = this.points(); var tp = points; @@ -10637,19 +10431,18 @@ if (isDashEnabled) { this.attrs.dashEnabled = true; } - }; - Arrow.prototype.getSelfRect = function () { - var lineRect = _super.prototype.getSelfRect.call(this); - var offset = this.pointerWidth() / 2; + } + getSelfRect() { + const lineRect = super.getSelfRect(); + const offset = this.pointerWidth() / 2; return { x: lineRect.x - offset, y: lineRect.y - offset, width: lineRect.width + offset * 2, - height: lineRect.height + offset * 2 + height: lineRect.height + offset * 2, }; - }; - return Arrow; - }(Line)); + } + } Arrow.prototype.className = 'Arrow'; _registerNode(Arrow); /** @@ -10694,8 +10487,7 @@ * // set value * line.pointerAtBeginning(true); */ - Factory.addGetterSetter(Arrow, 'pointerAtBeginning', false); - Collection.mapMethods(Arrow); + Factory.addGetterSetter(Arrow, 'pointerAtBeginning', false); /** * Circle constructor @@ -10787,35 +10579,30 @@ * strokeWidth: 5 * }); */ - var Circle = /** @class */ (function (_super) { - __extends(Circle, _super); - function Circle() { - return _super !== null && _super.apply(this, arguments) || this; - } - Circle.prototype._sceneFunc = function (context) { + class Circle extends Shape { + _sceneFunc(context) { context.beginPath(); context.arc(0, 0, this.attrs.radius || 0, 0, Math.PI * 2, false); context.closePath(); context.fillStrokeShape(this); - }; - Circle.prototype.getWidth = function () { + } + getWidth() { return this.radius() * 2; - }; - Circle.prototype.getHeight = function () { + } + getHeight() { return this.radius() * 2; - }; - Circle.prototype.setWidth = function (width) { + } + setWidth(width) { if (this.radius() !== width / 2) { this.radius(width / 2); } - }; - Circle.prototype.setHeight = function (height) { + } + setHeight(height) { if (this.radius() !== height / 2) { this.radius(height / 2); } - }; - return Circle; - }(Shape)); + } + } Circle.prototype._centroid = true; Circle.prototype.className = 'Circle'; Circle.prototype._attrsAffectingSize = ['radius']; @@ -10833,8 +10620,7 @@ * // set radius * circle.radius(10); */ - Factory.addGetterSetter(Circle, 'radius', 0, getNumberValidator()); - Collection.mapMethods(Circle); + Factory.addGetterSetter(Circle, 'radius', 0, getNumberValidator()); /** * Ellipse constructor @@ -10926,12 +10712,8 @@ * fill: 'red' * }); */ - var Ellipse = /** @class */ (function (_super) { - __extends(Ellipse, _super); - function Ellipse() { - return _super !== null && _super.apply(this, arguments) || this; - } - Ellipse.prototype._sceneFunc = function (context) { + class Ellipse extends Shape { + _sceneFunc(context) { var rx = this.radiusX(), ry = this.radiusY(); context.beginPath(); context.save(); @@ -10942,21 +10724,20 @@ context.restore(); context.closePath(); context.fillStrokeShape(this); - }; - Ellipse.prototype.getWidth = function () { + } + getWidth() { return this.radiusX() * 2; - }; - Ellipse.prototype.getHeight = function () { + } + getHeight() { return this.radiusY() * 2; - }; - Ellipse.prototype.setWidth = function (width) { + } + setWidth(width) { this.radiusX(width / 2); - }; - Ellipse.prototype.setHeight = function (height) { + } + setHeight(height) { this.radiusY(height / 2); - }; - return Ellipse; - }(Shape)); + } + } Ellipse.prototype.className = 'Ellipse'; Ellipse.prototype._centroid = true; Ellipse.prototype._attrsAffectingSize = ['radiusX', 'radiusY']; @@ -11008,8 +10789,7 @@ * * // set radius y * ellipse.radiusY(200); - */ - Collection.mapMethods(Ellipse); + */ /** * Image constructor @@ -11106,22 +10886,18 @@ * }; * imageObj.src = '/path/to/image.jpg' */ - var Image = /** @class */ (function (_super) { - __extends(Image, _super); - function Image() { - return _super !== null && _super.apply(this, arguments) || this; + class Image extends Shape { + _useBufferCanvas() { + return super._useBufferCanvas(true); } - Image.prototype._useBufferCanvas = function () { - return _super.prototype._useBufferCanvas.call(this, true); - }; - Image.prototype._sceneFunc = function (context) { - var width = this.getWidth(); - var height = this.getHeight(); - var image = this.attrs.image; - var params; + _sceneFunc(context) { + const width = this.getWidth(); + const height = this.getHeight(); + const image = this.attrs.image; + let params; if (image) { - var cropWidth = this.attrs.cropWidth; - var cropHeight = this.attrs.cropHeight; + const cropWidth = this.attrs.cropWidth; + const cropHeight = this.attrs.cropHeight; if (cropWidth && cropHeight) { params = [ image, @@ -11148,22 +10924,22 @@ if (image) { context.drawImage.apply(context, params); } - }; - Image.prototype._hitFunc = function (context) { + } + _hitFunc(context) { var width = this.width(), height = this.height(); context.beginPath(); context.rect(0, 0, width, height); context.closePath(); context.fillStrokeShape(this); - }; - Image.prototype.getWidth = function () { + } + getWidth() { var _a, _b; - return (_a = this.attrs.width) !== null && _a !== void 0 ? _a : (((_b = this.image()) === null || _b === void 0 ? void 0 : _b.width) || 0); - }; - Image.prototype.getHeight = function () { + return (_a = this.attrs.width) !== null && _a !== void 0 ? _a : (_b = this.image()) === null || _b === void 0 ? void 0 : _b.width; + } + getHeight() { var _a, _b; - return (_a = this.attrs.height) !== null && _a !== void 0 ? _a : (((_b = this.image()) === null || _b === void 0 ? void 0 : _b.height) || 0); - }; + return (_a = this.attrs.height) !== null && _a !== void 0 ? _a : (_b = this.image()) === null || _b === void 0 ? void 0 : _b.height; + } /** * load image from given url and create `Konva.Image` instance * @method @@ -11177,7 +10953,7 @@ * layer.draw(); * }); */ - Image.fromURL = function (url, callback) { + static fromURL(url, callback) { var img = Util.createImageElement(); img.onload = function () { var image = new Image({ @@ -11187,9 +10963,8 @@ }; img.crossOrigin = 'Anonymous'; img.src = url; - }; - return Image; - }(Shape)); + } + } Image.prototype.className = 'Image'; _registerNode(Image); /** @@ -11284,11 +11059,10 @@ * * // set crop height * image.cropHeight(20); - */ - Collection.mapMethods(Image); + */ // constants - var ATTR_CHANGE_LIST = [ + var ATTR_CHANGE_LIST$2 = [ 'fontFamily', 'fontSize', 'fontStyle', @@ -11297,9 +11071,9 @@ 'text', 'width', 'height', - ], CHANGE_KONVA = 'Change.konva', NONE = 'none', UP = 'up', RIGHT = 'right', DOWN = 'down', LEFT = 'left', + ], CHANGE_KONVA$1 = 'Change.konva', NONE$1 = 'none', UP = 'up', RIGHT$1 = 'right', DOWN = 'down', LEFT$1 = 'left', // cached variables - attrChangeListLen = ATTR_CHANGE_LIST.length; + attrChangeListLen$1 = ATTR_CHANGE_LIST$2.length; /** * Label constructor.  Labels are groups that contain a Text and Tag shape * @constructor @@ -11357,15 +11131,13 @@ * fill: 'green' * })); */ - var Label = /** @class */ (function (_super) { - __extends(Label, _super); - function Label(config) { - var _this = _super.call(this, config) || this; - _this.on('add.konva', function (evt) { + class Label extends Group { + constructor(config) { + super(config); + this.on('add.konva', function (evt) { this._addListeners(evt.child); this._sync(); }); - return _this; } /** * get Text shape for the label. You need to access the Text shape in order to update @@ -11375,35 +11147,35 @@ * @example * label.getText().fill('red') */ - Label.prototype.getText = function () { + getText() { return this.find('Text')[0]; - }; + } /** * get Tag shape for the label. You need to access the Tag shape in order to update * the pointer properties and the corner radius * @name Konva.Label#getTag * @method */ - Label.prototype.getTag = function () { + getTag() { return this.find('Tag')[0]; - }; - Label.prototype._addListeners = function (text) { + } + _addListeners(text) { var that = this, n; var func = function () { that._sync(); }; // update text data for certain attr changes - for (n = 0; n < attrChangeListLen; n++) { - text.on(ATTR_CHANGE_LIST[n] + CHANGE_KONVA, func); + for (n = 0; n < attrChangeListLen$1; n++) { + text.on(ATTR_CHANGE_LIST$2[n] + CHANGE_KONVA$1, func); } - }; - Label.prototype.getWidth = function () { + } + getWidth() { return this.getText().width(); - }; - Label.prototype.getHeight = function () { + } + getHeight() { return this.getText().height(); - }; - Label.prototype._sync = function () { + } + _sync() { var text = this.getText(), tag = this.getTag(), width, height, pointerDirection, pointerWidth, x, y, pointerHeight; if (text && tag) { width = text.width(); @@ -11418,7 +11190,7 @@ x = width / 2; y = -1 * pointerHeight; break; - case RIGHT: + case RIGHT$1: x = width + pointerWidth; y = height / 2; break; @@ -11426,7 +11198,7 @@ x = width / 2; y = height + pointerHeight; break; - case LEFT: + case LEFT$1: x = -1 * pointerWidth; y = height / 2; break; @@ -11442,12 +11214,10 @@ y: -1 * y, }); } - }; - return Label; - }(Group)); + } + } Label.prototype.className = 'Label'; _registerNode(Label); - Collection.mapMethods(Label); /** * Tag constructor.  A Tag can be configured * to have a pointer element that points up, right, down, or left @@ -11460,17 +11230,13 @@ * @param {Number} [config.pointerHeight] * @param {Number} [config.cornerRadius] */ - var Tag = /** @class */ (function (_super) { - __extends(Tag, _super); - function Tag() { - return _super !== null && _super.apply(this, arguments) || this; - } - Tag.prototype._sceneFunc = function (context) { + class Tag extends Shape { + _sceneFunc(context) { var width = this.width(), height = this.height(), pointerDirection = this.pointerDirection(), pointerWidth = this.pointerWidth(), pointerHeight = this.pointerHeight(), cornerRadius = this.cornerRadius(); - var topLeft = 0; - var topRight = 0; - var bottomLeft = 0; - var bottomRight = 0; + let topLeft = 0; + let topRight = 0; + let bottomLeft = 0; + let bottomRight = 0; if (typeof cornerRadius === 'number') { topLeft = topRight = bottomLeft = bottomRight = Math.min(cornerRadius, width / 2, height / 2); } @@ -11489,7 +11255,7 @@ } context.lineTo(width - topRight, 0); context.arc(width - topRight, topRight, topRight, (Math.PI * 3) / 2, 0, false); - if (pointerDirection === RIGHT) { + if (pointerDirection === RIGHT$1) { context.lineTo(width, (height - pointerHeight) / 2); context.lineTo(width + pointerWidth, height / 2); context.lineTo(width, (height + pointerHeight) / 2); @@ -11503,7 +11269,7 @@ } context.lineTo(bottomLeft, height); context.arc(bottomLeft, height - bottomLeft, bottomLeft, Math.PI / 2, Math.PI, false); - if (pointerDirection === LEFT) { + if (pointerDirection === LEFT$1) { context.lineTo(0, (height + pointerHeight) / 2); context.lineTo(-1 * pointerWidth, height / 2); context.lineTo(0, (height - pointerHeight) / 2); @@ -11512,8 +11278,8 @@ context.arc(topLeft, topLeft, topLeft, Math.PI, (Math.PI * 3) / 2, false); context.closePath(); context.fillStrokeShape(this); - }; - Tag.prototype.getSelfRect = function () { + } + getSelfRect() { var x = 0, y = 0, pointerWidth = this.pointerWidth(), pointerHeight = this.pointerHeight(), direction = this.pointerDirection(), width = this.width(), height = this.height(); if (direction === UP) { y -= pointerHeight; @@ -11522,12 +11288,12 @@ else if (direction === DOWN) { height += pointerHeight; } - else if (direction === LEFT) { + else if (direction === LEFT$1) { // ARGH!!! I have no idea why should I used magic 1.5!!!!!!!!! x -= pointerWidth * 1.5; width += pointerWidth; } - else if (direction === RIGHT) { + else if (direction === RIGHT$1) { width += pointerWidth * 1.5; } return { @@ -11536,9 +11302,8 @@ width: width, height: height, }; - }; - return Tag; - }(Shape)); + } + } Tag.prototype.className = 'Tag'; _registerNode(Tag); /** @@ -11550,7 +11315,7 @@ * @example * tag.pointerDirection('right'); */ - Factory.addGetterSetter(Tag, 'pointerDirection', NONE); + Factory.addGetterSetter(Tag, 'pointerDirection', NONE$1); /** * get/set pointer width * @name Konva.Tag#pointerWidth @@ -11584,8 +11349,7 @@ * // top-left, top-right, bottom-right, bottom-left * tag.cornerRadius([0, 10, 20, 30]); */ - Factory.addGetterSetter(Tag, 'cornerRadius', 0, getNumberOrArrayOfNumbersValidator(4)); - Collection.mapMethods(Tag); + Factory.addGetterSetter(Tag, 'cornerRadius', 0, getNumberOrArrayOfNumbersValidator(4)); /** * Path constructor. @@ -11679,27 +11443,25 @@ * scaleY: 2 * }); */ - var Path = /** @class */ (function (_super) { - __extends(Path, _super); - function Path(config) { - var _this = _super.call(this, config) || this; - _this.dataArray = []; - _this.pathLength = 0; - _this.dataArray = Path.parsePathData(_this.data()); - _this.pathLength = 0; - for (var i = 0; i < _this.dataArray.length; ++i) { - _this.pathLength += _this.dataArray[i].pathLength; + class Path extends Shape { + constructor(config) { + super(config); + this.dataArray = []; + this.pathLength = 0; + this.dataArray = Path.parsePathData(this.data()); + this.pathLength = 0; + for (var i = 0; i < this.dataArray.length; ++i) { + this.pathLength += this.dataArray[i].pathLength; } - _this.on('dataChange.konva', function () { + this.on('dataChange.konva', function () { this.dataArray = Path.parsePathData(this.data()); this.pathLength = 0; for (var i = 0; i < this.dataArray.length; ++i) { this.pathLength += this.dataArray[i].pathLength; } }); - return _this; } - Path.prototype._sceneFunc = function (context) { + _sceneFunc(context) { var ca = this.dataArray; // context position context.beginPath(); @@ -11745,8 +11507,8 @@ else { context.fillStrokeShape(this); } - }; - Path.prototype.getSelfRect = function () { + } + getSelfRect() { var points = []; this.dataArray.forEach(function (data) { if (data.command === 'A') { @@ -11763,23 +11525,23 @@ } if (dTheta < 0) { // clockwise - for (var t = start - inc; t > end; t -= inc) { - var point = Path.getPointOnEllipticalArc(data.points[0], data.points[1], data.points[2], data.points[3], t, 0); + for (let t = start - inc; t > end; t -= inc) { + const point = Path.getPointOnEllipticalArc(data.points[0], data.points[1], data.points[2], data.points[3], t, 0); points.push(point.x, point.y); } } else { // counter-clockwise - for (var t = start + inc; t < end; t += inc) { - var point = Path.getPointOnEllipticalArc(data.points[0], data.points[1], data.points[2], data.points[3], t, 0); + for (let t = start + inc; t < end; t += inc) { + const point = Path.getPointOnEllipticalArc(data.points[0], data.points[1], data.points[2], data.points[3], t, 0); points.push(point.x, point.y); } } } else if (data.command === 'C') { // Approximates by breaking curve into 100 line segments - for (var t = 0.0; t <= 1; t += 0.01) { - var point = Path.getPointOnCubicBezier(t, data.start.x, data.start.y, data.points[0], data.points[1], data.points[2], data.points[3], data.points[4], data.points[5]); + for (let t = 0.0; t <= 1; t += 0.01) { + const point = Path.getPointOnCubicBezier(t, data.start.x, data.start.y, data.points[0], data.points[1], data.points[2], data.points[3], data.points[4], data.points[5]); points.push(point.x, point.y); } } @@ -11812,7 +11574,7 @@ width: Math.round(maxX - minX), height: Math.round(maxY - minY), }; - }; + } /** * Return length of the path. * @method @@ -11821,9 +11583,9 @@ * @example * var length = path.getLength(); */ - Path.prototype.getLength = function () { + getLength() { return this.pathLength; - }; + } /** * Get point on path at specific length of the path * @method @@ -11833,7 +11595,7 @@ * @example * var point = path.getPointAtLength(10); */ - Path.prototype.getPointAtLength = function (length) { + getPointAtLength(length) { var point, i = 0, ii = this.dataArray.length; if (!ii) { return null; @@ -11871,11 +11633,11 @@ return Path.getPointOnEllipticalArc(cx, cy, rx, ry, theta, psi); } return null; - }; - Path.getLineLength = function (x1, y1, x2, y2) { + } + static getLineLength(x1, y1, x2, y2) { return Math.sqrt((x2 - x1) * (x2 - x1) + (y2 - y1) * (y2 - y1)); - }; - Path.getPointOnLine = function (dist, P1x, P1y, P2x, P2y, fromX, fromY) { + } + static getPointOnLine(dist, P1x, P1y, P2x, P2y, fromX, fromY) { if (fromX === undefined) { fromX = P1x; } @@ -11928,8 +11690,8 @@ }; } return pt; - }; - Path.getPointOnCubicBezier = function (pct, P1x, P1y, P2x, P2y, P3x, P3y, P4x, P4y) { + } + static getPointOnCubicBezier(pct, P1x, P1y, P2x, P2y, P3x, P3y, P4x, P4y) { function CB1(t) { return t * t * t; } @@ -11948,8 +11710,8 @@ x: x, y: y, }; - }; - Path.getPointOnQuadraticBezier = function (pct, P1x, P1y, P2x, P2y, P3x, P3y) { + } + static getPointOnQuadraticBezier(pct, P1x, P1y, P2x, P2y, P3x, P3y) { function QB1(t) { return t * t; } @@ -11965,8 +11727,8 @@ x: x, y: y, }; - }; - Path.getPointOnEllipticalArc = function (cx, cy, rx, ry, theta, psi) { + } + static getPointOnEllipticalArc(cx, cy, rx, ry, theta, psi) { var cosPsi = Math.cos(psi), sinPsi = Math.sin(psi); var pt = { x: rx * Math.cos(theta), @@ -11976,14 +11738,14 @@ x: cx + (pt.x * cosPsi - pt.y * sinPsi), y: cy + (pt.x * sinPsi + pt.y * cosPsi), }; - }; + } /* * get parsed data array from the data * string. V, v, H, h, and l data are converted to * L data for the purpose of high performance Path * rendering */ - Path.parsePathData = function (data) { + static parsePathData(data) { // Path Data Segment must begin with a moveTo //m (x y)+ Relative moveTo (subsequent points are treated as lineTo) //M (x y)+ Absolute moveTo (subsequent points are treated as lineTo) @@ -12272,8 +12034,8 @@ } } return ca; - }; - Path.calcLength = function (x, y, cmd, points) { + } + static calcLength(x, y, cmd, points) { var len, p1, p2, t; var path = Path; switch (cmd) { @@ -12335,8 +12097,8 @@ return len; } return 0; - }; - Path.convertEndpointToCenterParameterization = function (x1, y1, x2, y2, fa, fs, rx, ry, psiDeg) { + } + static convertEndpointToCenterParameterization(x1, y1, x2, y2, fa, fs, rx, ry, psiDeg) { // Derived from: http://www.w3.org/TR/SVG/implnote.html#ArcImplementationNotes var psi = psiDeg * (Math.PI / 180.0); var xp = (Math.cos(psi) * (x1 - x2)) / 2.0 + (Math.sin(psi) * (y1 - y2)) / 2.0; @@ -12385,9 +12147,8 @@ dTheta = dTheta + 2 * Math.PI; } return [cx, cy, rx, ry, theta, dTheta, psi, fs]; - }; - return Path; - }(Shape)); + } + } Path.prototype.className = 'Path'; Path.prototype._attrsAffectingSize = ['data']; _registerNode(Path); @@ -12407,8 +12168,7 @@ * // set data * path.data('M200,100h100v50z'); */ - Factory.addGetterSetter(Path, 'data'); - Collection.mapMethods(Path); + Factory.addGetterSetter(Path, 'data'); /** * Rect constructor @@ -12500,12 +12260,8 @@ * strokeWidth: 5 * }); */ - var Rect = /** @class */ (function (_super) { - __extends(Rect, _super); - function Rect() { - return _super !== null && _super.apply(this, arguments) || this; - } - Rect.prototype._sceneFunc = function (context) { + class Rect extends Shape { + _sceneFunc(context) { var cornerRadius = this.cornerRadius(), width = this.width(), height = this.height(); context.beginPath(); if (!cornerRadius) { @@ -12513,10 +12269,10 @@ context.rect(0, 0, width, height); } else { - var topLeft = 0; - var topRight = 0; - var bottomLeft = 0; - var bottomRight = 0; + let topLeft = 0; + let topRight = 0; + let bottomLeft = 0; + let bottomRight = 0; if (typeof cornerRadius === 'number') { topLeft = topRight = bottomLeft = bottomRight = Math.min(cornerRadius, width / 2, height / 2); } @@ -12538,9 +12294,8 @@ } context.closePath(); context.fillStrokeShape(this); - }; - return Rect; - }(Shape)); + } + } Rect.prototype.className = 'Rect'; _registerNode(Rect); /** @@ -12560,8 +12315,7 @@ * // top-left, top-right, bottom-right, bottom-left * rect.cornerRadius([0, 10, 20, 30]); */ - Factory.addGetterSetter(Rect, 'cornerRadius', 0, getNumberOrArrayOfNumbersValidator(4)); - Collection.mapMethods(Rect); + Factory.addGetterSetter(Rect, 'cornerRadius', 0, getNumberOrArrayOfNumbersValidator(4)); /** * RegularPolygon constructor. Examples include triangles, squares, pentagons, hexagons, etc. @@ -12656,13 +12410,9 @@ * strokeWidth: 4 * }); */ - var RegularPolygon = /** @class */ (function (_super) { - __extends(RegularPolygon, _super); - function RegularPolygon() { - return _super !== null && _super.apply(this, arguments) || this; - } - RegularPolygon.prototype._sceneFunc = function (context) { - var points = this._getPoints(); + class RegularPolygon extends Shape { + _sceneFunc(context) { + const points = this._getPoints(); context.beginPath(); context.moveTo(points[0].x, points[0].y); for (var n = 1; n < points.length; n++) { @@ -12670,11 +12420,11 @@ } context.closePath(); context.fillStrokeShape(this); - }; - RegularPolygon.prototype._getPoints = function () { - var sides = this.attrs.sides; - var radius = this.attrs.radius || 0; - var points = []; + } + _getPoints() { + const sides = this.attrs.sides; + const radius = this.attrs.radius || 0; + const points = []; for (var n = 0; n < sides; n++) { points.push({ x: radius * Math.sin((n * 2 * Math.PI) / sides), @@ -12682,14 +12432,14 @@ }); } return points; - }; - RegularPolygon.prototype.getSelfRect = function () { - var points = this._getPoints(); + } + 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; - points.forEach(function (point) { + points.forEach((point) => { minX = Math.min(minX, point.x); maxX = Math.max(maxX, point.x); minY = Math.min(minY, point.y); @@ -12701,21 +12451,20 @@ width: maxX - minX, height: maxY - minY, }; - }; - RegularPolygon.prototype.getWidth = function () { + } + getWidth() { return this.radius() * 2; - }; - RegularPolygon.prototype.getHeight = function () { + } + getHeight() { return this.radius() * 2; - }; - RegularPolygon.prototype.setWidth = function (width) { + } + setWidth(width) { this.radius(width / 2); - }; - RegularPolygon.prototype.setHeight = function (height) { + } + setHeight(height) { this.radius(height / 2); - }; - return RegularPolygon; - }(Shape)); + } + } RegularPolygon.prototype.className = 'RegularPolygon'; RegularPolygon.prototype._centroid = true; RegularPolygon.prototype._attrsAffectingSize = ['radius']; @@ -12747,8 +12496,7 @@ * // set sides * shape.sides(10); */ - Factory.addGetterSetter(RegularPolygon, 'sides', 0, getNumberValidator()); - Collection.mapMethods(RegularPolygon); + Factory.addGetterSetter(RegularPolygon, 'sides', 0, getNumberValidator()); var PIx2 = Math.PI * 2; /** @@ -12843,33 +12591,28 @@ * strokeWidth: 5 * }); */ - var Ring = /** @class */ (function (_super) { - __extends(Ring, _super); - function Ring() { - return _super !== null && _super.apply(this, arguments) || this; - } - Ring.prototype._sceneFunc = function (context) { + class Ring extends Shape { + _sceneFunc(context) { context.beginPath(); context.arc(0, 0, this.innerRadius(), 0, PIx2, false); context.moveTo(this.outerRadius(), 0); context.arc(0, 0, this.outerRadius(), PIx2, 0, true); context.closePath(); context.fillStrokeShape(this); - }; - Ring.prototype.getWidth = function () { + } + getWidth() { return this.outerRadius() * 2; - }; - Ring.prototype.getHeight = function () { + } + getHeight() { return this.outerRadius() * 2; - }; - Ring.prototype.setWidth = function (width) { + } + setWidth(width) { this.outerRadius(width / 2); - }; - Ring.prototype.setHeight = function (height) { + } + setHeight(height) { this.outerRadius(height / 2); - }; - return Ring; - }(Shape)); + } + } Ring.prototype.className = 'Ring'; Ring.prototype._centroid = true; Ring.prototype._attrsAffectingSize = ['innerRadius', 'outerRadius']; @@ -12901,8 +12644,7 @@ * // set outer radius * ring.outerRadius(20); */ - Factory.addGetterSetter(Ring, 'outerRadius', 0, getNumberValidator()); - Collection.mapMethods(Ring); + Factory.addGetterSetter(Ring, 'outerRadius', 0, getNumberValidator()); /** * Sprite constructor @@ -13023,35 +12765,33 @@ * }; * imageObj.src = '/path/to/image.jpg' */ - var Sprite = /** @class */ (function (_super) { - __extends(Sprite, _super); - function Sprite(config) { - var _this = _super.call(this, config) || this; - _this._updated = true; - _this.anim = new Animation(function () { + class Sprite extends Shape { + constructor(config) { + super(config); + this._updated = true; + this.anim = new Animation(() => { // if we don't need to redraw layer we should return false - var updated = _this._updated; - _this._updated = false; + var updated = this._updated; + this._updated = false; return updated; }); - _this.on('animationChange.konva', function () { + this.on('animationChange.konva', function () { // reset index when animation changes this.frameIndex(0); }); - _this.on('frameIndexChange.konva', function () { + this.on('frameIndexChange.konva', function () { this._updated = true; }); // smooth change for frameRate - _this.on('frameRateChange.konva', function () { + this.on('frameRateChange.konva', function () { if (!this.anim.isRunning()) { return; } clearInterval(this.interval); this._setInterval(); }); - return _this; } - Sprite.prototype._sceneFunc = function (context) { + _sceneFunc(context) { var anim = this.animation(), index = this.frameIndex(), ix4 = index * 4, set = this.animations()[anim], offsets = this.frameOffsets(), x = set[ix4 + 0], y = set[ix4 + 1], width = set[ix4 + 2], height = set[ix4 + 3], image = this.image(); if (this.hasFill() || this.hasStroke()) { context.beginPath(); @@ -13068,8 +12808,8 @@ context.drawImage(image, x, y, width, height, 0, 0, width, height); } } - }; - Sprite.prototype._hitFunc = function (context) { + } + _hitFunc(context) { var anim = this.animation(), index = this.frameIndex(), ix4 = index * 4, set = this.animations()[anim], offsets = this.frameOffsets(), width = set[ix4 + 2], height = set[ix4 + 3]; context.beginPath(); if (offsets) { @@ -13082,22 +12822,22 @@ } context.closePath(); context.fillShape(this); - }; - Sprite.prototype._useBufferCanvas = function () { - return _super.prototype._useBufferCanvas.call(this, true); - }; - Sprite.prototype._setInterval = function () { + } + _useBufferCanvas() { + return super._useBufferCanvas(true); + } + _setInterval() { var that = this; this.interval = setInterval(function () { that._updateIndex(); }, 1000 / this.frameRate()); - }; + } /** * start sprite animation * @method * @name Konva.Sprite#start */ - Sprite.prototype.start = function () { + start() { if (this.isRunning()) { return; } @@ -13111,26 +12851,26 @@ this.anim.setLayers(layer); this._setInterval(); this.anim.start(); - }; + } /** * stop sprite animation * @method * @name Konva.Sprite#stop */ - Sprite.prototype.stop = function () { + stop() { this.anim.stop(); clearInterval(this.interval); - }; + } /** * determine if animation of sprite is running or not. returns true or false * @method * @name Konva.Sprite#isRunning * @returns {Boolean} */ - Sprite.prototype.isRunning = function () { + isRunning() { return this.anim.isRunning(); - }; - Sprite.prototype._updateIndex = function () { + } + _updateIndex() { var index = this.frameIndex(), animation = this.animation(), animations = this.animations(), anim = animations[animation], len = anim.length / 4; if (index < len - 1) { this.frameIndex(index + 1); @@ -13138,9 +12878,8 @@ else { this.frameIndex(0); } - }; - return Sprite; - }(Shape)); + } + } Sprite.prototype.className = 'Sprite'; _registerNode(Sprite); // add getters setters @@ -13272,8 +13011,7 @@ index: 'frameIndex', getIndex: 'getFrameIndex', setIndex: 'setFrameIndex', - }); - Collection.mapMethods(Sprite); + }); /** * Star constructor @@ -13370,12 +13108,8 @@ * strokeWidth: 4 * }); */ - var Star = /** @class */ (function (_super) { - __extends(Star, _super); - function Star() { - return _super !== null && _super.apply(this, arguments) || this; - } - Star.prototype._sceneFunc = function (context) { + class Star extends Shape { + _sceneFunc(context) { var innerRadius = this.innerRadius(), outerRadius = this.outerRadius(), numPoints = this.numPoints(); context.beginPath(); context.moveTo(0, 0 - outerRadius); @@ -13387,21 +13121,20 @@ } context.closePath(); context.fillStrokeShape(this); - }; - Star.prototype.getWidth = function () { + } + getWidth() { return this.outerRadius() * 2; - }; - Star.prototype.getHeight = function () { + } + getHeight() { return this.outerRadius() * 2; - }; - Star.prototype.setWidth = function (width) { + } + setWidth(width) { this.outerRadius(width / 2); - }; - Star.prototype.setHeight = function (height) { + } + setHeight(height) { this.outerRadius(height / 2); - }; - return Star; - }(Shape)); + } + } Star.prototype.className = 'Star'; Star.prototype._centroid = true; Star.prototype._attrsAffectingSize = ['innerRadius', 'outerRadius']; @@ -13447,8 +13180,7 @@ * // set inner radius * star.outerRadius(20); */ - Factory.addGetterSetter(Star, 'outerRadius', 0, getNumberValidator()); - Collection.mapMethods(Star); + Factory.addGetterSetter(Star, 'outerRadius', 0, getNumberValidator()); function stringToArray(string) { // we need to use `Array.from` because it can split unicode string correctly @@ -13460,7 +13192,7 @@ // constants var AUTO = 'auto', //CANVAS = 'canvas', - CENTER = 'center', JUSTIFY = 'justify', CHANGE_KONVA$1 = 'Change.konva', CONTEXT_2D = '2d', DASH = '-', LEFT$1 = 'left', TEXT = 'text', TEXT_UPPER = 'Text', TOP = 'top', BOTTOM = 'bottom', MIDDLE = 'middle', NORMAL = 'normal', PX_SPACE = 'px ', SPACE$1 = ' ', RIGHT$1 = 'right', WORD = 'word', CHAR = 'char', NONE$1 = 'none', ELLIPSIS = '…', ATTR_CHANGE_LIST$1 = [ + CENTER = 'center', JUSTIFY = 'justify', CHANGE_KONVA = 'Change.konva', CONTEXT_2D = '2d', DASH = '-', LEFT = 'left', TEXT = 'text', TEXT_UPPER = 'Text', TOP = 'top', BOTTOM = 'bottom', MIDDLE = 'middle', NORMAL$1 = 'normal', PX_SPACE = 'px ', SPACE = ' ', RIGHT = 'right', WORD = 'word', CHAR = 'char', NONE = 'none', ELLIPSIS = '…', ATTR_CHANGE_LIST$1 = [ 'fontFamily', 'fontSize', 'fontStyle', @@ -13477,28 +13209,28 @@ 'letterSpacing', ], // cached variables - attrChangeListLen$1 = ATTR_CHANGE_LIST$1.length; + attrChangeListLen = ATTR_CHANGE_LIST$1.length; function normalizeFontFamily(fontFamily) { return fontFamily .split(',') - .map(function (family) { + .map((family) => { family = family.trim(); - var hasSpace = family.indexOf(' ') >= 0; - var hasQuotes = family.indexOf('"') >= 0 || family.indexOf("'") >= 0; + const hasSpace = family.indexOf(' ') >= 0; + const hasQuotes = family.indexOf('"') >= 0 || family.indexOf("'") >= 0; if (hasSpace && !hasQuotes) { - family = "\"" + family + "\""; + family = `"${family}"`; } return family; }) .join(', '); } - var dummyContext$1; - function getDummyContext$1() { - if (dummyContext$1) { - return dummyContext$1; + var dummyContext; + function getDummyContext() { + if (dummyContext) { + return dummyContext; } - dummyContext$1 = Util.createCanvasElement().getContext(CONTEXT_2D); - return dummyContext$1; + dummyContext = Util.createCanvasElement().getContext(CONTEXT_2D); + return dummyContext; } function _fillFunc$1(context) { context.fillText(this._partialText, this._partialTextX, this._partialTextY); @@ -13524,7 +13256,7 @@ * @param {Object} config * @param {String} [config.fontFamily] default is Arial * @param {Number} [config.fontSize] in pixels. Default is 12 - * @param {String} [config.fontStyle] can be normal, bold, or italic. Default is normal + * @param {String} [config.fontStyle] can be 'normal', 'bold', 'italic' or even 'italic bold'. Default is 'normal' * @param {String} [config.fontVariant] can be normal or small-caps. Default is normal * @param {String} [config.textDecoration] can be line-through, underline or empty string. Default is empty string. * @param {String} config.text @@ -13618,20 +13350,18 @@ * fill: 'green' * }); */ - var Text = /** @class */ (function (_super) { - __extends(Text, _super); - function Text(config) { - var _this = _super.call(this, checkDefaultFill(config)) || this; - _this._partialTextX = 0; - _this._partialTextY = 0; + class Text extends Shape { + constructor(config) { + super(checkDefaultFill(config)); + this._partialTextX = 0; + this._partialTextY = 0; // update text data for certain attr changes - for (var n = 0; n < attrChangeListLen$1; n++) { - _this.on(ATTR_CHANGE_LIST$1[n] + CHANGE_KONVA$1, _this._setTextData); + for (var n = 0; n < attrChangeListLen; n++) { + this.on(ATTR_CHANGE_LIST$1[n] + CHANGE_KONVA, this._setTextData); } - _this._setTextData(); - return _this; + this._setTextData(); } - Text.prototype._sceneFunc = function (context) { + _sceneFunc(context) { var textArr = this.textArr, textArrLen = textArr.length; if (!this.text()) { return; @@ -13643,7 +13373,7 @@ var lineTranslateY = 0; context.setAttr('font', this._getContextFont()); context.setAttr('textBaseline', MIDDLE); - context.setAttr('textAlign', LEFT$1); + context.setAttr('textAlign', LEFT); // handle vertical alignment if (verticalAlign === MIDDLE) { alignY = (this.getHeight() - textArrLen * lineHeightPx - padding * 2) / 2; @@ -13659,7 +13389,7 @@ var obj = textArr[n], text = obj.text, width = obj.width, lastLine = n !== textArrLen - 1, spacesNumber, oneWord, lineWidth; // horizontal alignment context.save(); - if (align === RIGHT$1) { + if (align === RIGHT) { lineTranslateX += totalWidth - width - padding * 2; } else if (align === CENTER) { @@ -13731,15 +13461,15 @@ translateY += lineHeightPx; } } - }; - Text.prototype._hitFunc = function (context) { + } + _hitFunc(context) { var width = this.getWidth(), height = this.getHeight(); context.beginPath(); context.rect(0, 0, width, height); context.closePath(); context.fillStrokeShape(this); - }; - Text.prototype.setText = function (text) { + } + setText(text) { var str = Util._isString(text) ? text : text === null || text === undefined @@ -13747,31 +13477,31 @@ : text + ''; this._setAttr(TEXT, str); return this; - }; - Text.prototype.getWidth = function () { + } + getWidth() { var isAuto = this.attrs.width === AUTO || this.attrs.width === undefined; return isAuto ? this.getTextWidth() + this.padding() * 2 : this.attrs.width; - }; - Text.prototype.getHeight = function () { + } + getHeight() { var isAuto = this.attrs.height === AUTO || this.attrs.height === undefined; return isAuto ? this.fontSize() * this.textArr.length * this.lineHeight() + this.padding() * 2 : this.attrs.height; - }; + } /** * get pure text width without padding * @method * @name Konva.Text#getTextWidth * @returns {Number} */ - Text.prototype.getTextWidth = function () { + getTextWidth() { return this.textWidth; - }; - Text.prototype.getTextHeight = function () { + } + getTextHeight() { Util.warn('text.getTextHeight() method is deprecated. Use text.height() - for full height and text.fontSize() - for one line height.'); return this.textHeight; - }; + } /** * measure string with the font of current text shape. * That method can't handle multiline text. @@ -13780,8 +13510,8 @@ * @param {String} [text] text to measure * @returns {Object} { width , height} of measured text */ - Text.prototype.measureSize = function (text) { - var _context = getDummyContext$1(), fontSize = this.fontSize(), metrics; + measureSize(text) { + var _context = getDummyContext(), fontSize = this.fontSize(), metrics; _context.save(); _context.font = this._getContextFont(); metrics = _context.measureText(text); @@ -13790,46 +13520,46 @@ width: metrics.width, height: fontSize, }; - }; - Text.prototype._getContextFont = function () { + } + _getContextFont() { // IE don't want to work with usual font style // bold was not working // removing font variant will solve // fix for: https://github.com/konvajs/konva/issues/94 - if (Konva.UA.isIE) { + if (Konva$2.UA.isIE) { return (this.fontStyle() + - SPACE$1 + + SPACE + this.fontSize() + PX_SPACE + this.fontFamily()); } return (this.fontStyle() + - SPACE$1 + + SPACE + this.fontVariant() + - SPACE$1 + + SPACE + (this.fontSize() + PX_SPACE) + // wrap font family into " so font families with spaces works ok normalizeFontFamily(this.fontFamily())); - }; - Text.prototype._addTextLine = function (line) { + } + _addTextLine(line) { if (this.align() === JUSTIFY) { line = line.trim(); } var width = this._getTextWidth(line); return this.textArr.push({ text: line, width: width }); - }; - Text.prototype._getTextWidth = function (text) { + } + _getTextWidth(text) { var letterSpacing = this.letterSpacing(); var length = text.length; - return (getDummyContext$1().measureText(text).width + + return (getDummyContext().measureText(text).width + (length ? letterSpacing * (length - 1) : 0)); - }; - Text.prototype._setTextData = function () { + } + _setTextData() { var lines = this.text().split('\n'), fontSize = +this.fontSize(), textWidth = 0, lineHeightPx = this.lineHeight() * fontSize, width = this.attrs.width, height = this.attrs.height, fixedWidth = width !== AUTO && width !== undefined, fixedHeight = height !== AUTO && height !== undefined, padding = this.padding(), maxWidth = width - padding * 2, maxHeightPx = height - padding * 2, currentHeightPx = 0, wrap = this.wrap(), // align = this.align(), - shouldWrap = wrap !== NONE$1, wrapAtWord = wrap !== CHAR && shouldWrap, shouldAddEllipsis = this.ellipsis(); + shouldWrap = wrap !== NONE, wrapAtWord = wrap !== CHAR && shouldWrap, shouldAddEllipsis = this.ellipsis(); this.textArr = []; - getDummyContext$1().font = this._getContextFont(); + 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]; @@ -13867,13 +13597,13 @@ // try to find a space or dash where wrapping could be done var wrapIndex; var nextChar = line[match.length]; - var nextIsSpaceOrDash = nextChar === SPACE$1 || nextChar === DASH; + var nextIsSpaceOrDash = nextChar === SPACE || nextChar === DASH; if (nextIsSpaceOrDash && matchWidth <= maxWidth) { wrapIndex = match.length; } else { wrapIndex = - Math.max(match.lastIndexOf(SPACE$1), match.lastIndexOf(DASH)) + + Math.max(match.lastIndexOf(SPACE), match.lastIndexOf(DASH)) + 1; } if (wrapIndex > 0) { @@ -13945,14 +13675,13 @@ // maxTextWidth = Math.max(maxTextWidth, this.textArr[j].width); // } this.textWidth = textWidth; - }; + } // for text we can't disable stroke scaling // if we do, the result will be unexpected - Text.prototype.getStrokeScaleEnabled = function () { + getStrokeScaleEnabled() { return true; - }; - return Text; - }(Shape)); + } + } Text.prototype._fillFunc = _fillFunc$1; Text.prototype._strokeFunc = _strokeFunc$1; Text.prototype.className = TEXT_UPPER; @@ -14030,7 +13759,7 @@ */ Factory.addGetterSetter(Text, 'fontSize', 12, getNumberValidator()); /** - * get/set font style. Can be 'normal', 'italic', or 'bold'. 'normal' is the default. + * get/set font style. Can be 'normal', 'italic', or 'bold' or even 'italic bold'. 'normal' is the default. * @name Konva.Text#fontStyle * @method * @param {String} fontStyle @@ -14042,7 +13771,7 @@ * // set font style * text.fontStyle('bold'); */ - Factory.addGetterSetter(Text, 'fontStyle', NORMAL); + Factory.addGetterSetter(Text, 'fontStyle', NORMAL$1); /** * get/set font variant. Can be 'normal' or 'small-caps'. 'normal' is the default. * @name Konva.Text#fontVariant @@ -14056,7 +13785,7 @@ * // set font variant * text.fontVariant('small-caps'); */ - Factory.addGetterSetter(Text, 'fontVariant', NORMAL); + Factory.addGetterSetter(Text, 'fontVariant', NORMAL$1); /** * get/set padding * @name Konva.Text#padding @@ -14087,7 +13816,7 @@ * // align text to right * text.align('right'); */ - Factory.addGetterSetter(Text, 'align', LEFT$1); + Factory.addGetterSetter(Text, 'align', LEFT); /** * get/set vertical align of text. Can be 'top', 'middle', 'bottom'. * @name Konva.Text#verticalAlign @@ -14188,14 +13917,13 @@ * // underline and strike text * text.textDecoration('underline line-through'); */ - Factory.addGetterSetter(Text, 'textDecoration', ''); - Collection.mapMethods(Text); + Factory.addGetterSetter(Text, 'textDecoration', ''); - var EMPTY_STRING$2 = '', NORMAL$1 = 'normal'; - function _fillFunc$2(context) { + var EMPTY_STRING = '', NORMAL = 'normal'; + function _fillFunc(context) { context.fillText(this.partialText, 0, 0); } - function _strokeFunc$2(context) { + function _strokeFunc(context) { context.strokeText(this.partialText, 0, 0); } /** @@ -14315,29 +14043,26 @@ * } * }); */ - var TextPath = /** @class */ (function (_super) { - __extends(TextPath, _super); - function TextPath(config) { - var _this = + class TextPath extends Shape { + constructor(config) { // call super constructor - _super.call(this, config) || this; - _this.dummyCanvas = Util.createCanvasElement(); - _this.dataArray = []; - _this.dataArray = Path.parsePathData(_this.attrs.data); - _this.on('dataChange.konva', function () { + super(config); + this.dummyCanvas = Util.createCanvasElement(); + this.dataArray = []; + this.dataArray = Path.parsePathData(this.attrs.data); + this.on('dataChange.konva', function () { this.dataArray = Path.parsePathData(this.attrs.data); this._setTextData(); }); // update text data for certain attr changes - _this.on('textChange.konva alignChange.konva letterSpacingChange.konva kerningFuncChange.konva', _this._setTextData); + this.on('textChange.konva alignChange.konva letterSpacingChange.konva kerningFuncChange.konva fontSizeChange.konva', this._setTextData); if (config && config['getKerning']) { Util.warn('getKerning TextPath API is deprecated. Please use "kerningFunc" instead.'); - _this.kerningFunc(config['getKerning']); + this.kerningFunc(config['getKerning']); } - _this._setTextData(); - return _this; + this._setTextData(); } - TextPath.prototype._sceneFunc = function (context) { + _sceneFunc(context) { context.setAttr('font', this._getContextFont()); context.setAttr('textBaseline', this.textBaseline()); context.setAttr('textAlign', 'left'); @@ -14378,8 +14103,8 @@ context.stroke(); } context.restore(); - }; - TextPath.prototype._hitFunc = function (context) { + } + _hitFunc(context) { context.beginPath(); var glyphInfo = this.glyphInfo; if (glyphInfo.length >= 1) { @@ -14393,26 +14118,26 @@ context.setAttr('lineWidth', this.fontSize()); context.setAttr('strokeStyle', this.colorKey); context.stroke(); - }; + } /** * get text width in pixels * @method * @name Konva.TextPath#getTextWidth */ - TextPath.prototype.getTextWidth = function () { + getTextWidth() { return this.textWidth; - }; - TextPath.prototype.getTextHeight = function () { + } + getTextHeight() { Util.warn('text.getTextHeight() method is deprecated. Use text.height() - for full height and text.fontSize() - for one line height.'); return this.textHeight; - }; - TextPath.prototype.setText = function (text) { + } + setText(text) { return Text.prototype.setText.call(this, text); - }; - TextPath.prototype._getContextFont = function () { + } + _getContextFont() { return Text.prototype._getContextFont.call(this); - }; - TextPath.prototype._getTextSize = function (text) { + } + _getTextSize(text) { var dummyCanvas = this.dummyCanvas; var _context = dummyCanvas.getContext('2d'); _context.save(); @@ -14423,8 +14148,8 @@ width: metrics.width, height: parseInt(this.attrs.fontSize, 10), }; - }; - TextPath.prototype._setTextData = function () { + } + _setTextData() { var that = this; var size = this._getTextSize(this.attrs.text); var letterSpacing = this.letterSpacing(); @@ -14627,8 +14352,8 @@ }); p0 = p1; } - }; - TextPath.prototype.getSelfRect = function () { + } + getSelfRect() { if (!this.glyphInfo.length) { return { x: 0, @@ -14664,13 +14389,12 @@ width: maxX - minX + fontSize, height: maxY - minY + fontSize, }; - }; - return TextPath; - }(Shape)); - TextPath.prototype._fillFunc = _fillFunc$2; - TextPath.prototype._strokeFunc = _strokeFunc$2; - TextPath.prototype._fillFuncHit = _fillFunc$2; - TextPath.prototype._strokeFuncHit = _strokeFunc$2; + } + } + TextPath.prototype._fillFunc = _fillFunc; + TextPath.prototype._strokeFunc = _strokeFunc; + TextPath.prototype._fillFuncHit = _fillFunc; + TextPath.prototype._strokeFuncHit = _strokeFunc; TextPath.prototype.className = 'TextPath'; TextPath.prototype._attrsAffectingSize = ['text', 'fontSize', 'data']; _registerNode(TextPath); @@ -14732,7 +14456,7 @@ * // set font style * shape.fontStyle('bold'); */ - Factory.addGetterSetter(TextPath, 'fontStyle', NORMAL$1); + Factory.addGetterSetter(TextPath, 'fontStyle', NORMAL); /** * get/set horizontal align of text. Can be 'left', 'center', 'right' or 'justify' * @name Konva.TextPath#align @@ -14791,7 +14515,7 @@ * // set font variant * shape.fontVariant('small-caps'); */ - Factory.addGetterSetter(TextPath, 'fontVariant', NORMAL$1); + Factory.addGetterSetter(TextPath, 'fontVariant', NORMAL); /** * get/set text * @name Konva.TextPath#getText @@ -14805,7 +14529,7 @@ * // set text * text.text('Hello world!'); */ - Factory.addGetterSetter(TextPath, 'text', EMPTY_STRING$2); + Factory.addGetterSetter(TextPath, 'text', EMPTY_STRING); /** * get/set text decoration of a text. Can be '' or 'underline'. * @name Konva.TextPath#textDecoration @@ -14835,11 +14559,10 @@ * return 1; * }); */ - Factory.addGetterSetter(TextPath, 'kerningFunc', null); - Collection.mapMethods(TextPath); + Factory.addGetterSetter(TextPath, 'kerningFunc', null); var EVENTS_NAME = 'tr-konva'; - var ATTR_CHANGE_LIST$2 = [ + var ATTR_CHANGE_LIST = [ 'resizeEnabledChange', 'rotateAnchorOffsetChange', 'rotateEnabledChange', @@ -14855,10 +14578,10 @@ 'anchorCornerRadiusChange', 'ignoreStrokeChange', ] - .map(function (e) { return e + ("." + EVENTS_NAME); }) + .map((e) => e + `.${EVENTS_NAME}`) .join(' '); var NODES_RECT = 'nodesRect'; - var TRANSFORM_CHANGE_STR$1 = [ + var TRANSFORM_CHANGE_STR = [ 'widthChange', 'heightChange', 'scaleXChange', @@ -14871,7 +14594,7 @@ 'transformsEnabledChange', 'strokeWidthChange', ] - .map(function (e) { return e + ("." + EVENTS_NAME); }) + .map((e) => e + `.${EVENTS_NAME}`) .join(' '); var ANGLES = { 'top-left': -45, @@ -14883,7 +14606,7 @@ 'bottom-center': 180, 'bottom-right': 135, }; - var TOUCH_DEVICE = 'ontouchstart' in Konva._global; + const TOUCH_DEVICE = 'ontouchstart' in Konva$2._global; function getCursor(anchorName, rad) { if (anchorName === 'rotater') { return 'crosshair'; @@ -14950,25 +14673,25 @@ }; } function rotateAroundPoint(shape, angleRad, point) { - var x = point.x + + const x = point.x + (shape.x - point.x) * Math.cos(angleRad) - (shape.y - point.y) * Math.sin(angleRad); - var y = point.y + + const y = point.y + (shape.x - point.x) * Math.sin(angleRad) + (shape.y - point.y) * Math.cos(angleRad); - return __assign(__assign({}, shape), { rotation: shape.rotation + angleRad, x: x, - y: y }); + return Object.assign(Object.assign({}, shape), { rotation: shape.rotation + angleRad, x, + y }); } function rotateAroundCenter(shape, deltaRad) { - var center = getCenter(shape); + const center = getCenter(shape); return rotateAroundPoint(shape, deltaRad, center); } function getSnap(snaps, newRotationRad, tol) { - var snapped = newRotationRad; - for (var i = 0; i < snaps.length; i++) { - var angle = Konva.getAngle(snaps[i]); - var absDiff = Math.abs(angle - newRotationRad) % (Math.PI * 2); - var dif = Math.min(absDiff, Math.PI * 2 - absDiff); + let snapped = newRotationRad; + for (let i = 0; i < snaps.length; i++) { + const angle = Konva$2.getAngle(snaps[i]); + const absDiff = Math.abs(angle - newRotationRad) % (Math.PI * 2); + const dif = Math.min(absDiff, Math.PI * 2 - absDiff); if (dif < tol) { snapped = angle; } @@ -15011,24 +14734,21 @@ * }); * layer.add(transformer); */ - var Transformer = /** @class */ (function (_super) { - __extends(Transformer, _super); - function Transformer(config) { - var _this = + class Transformer extends Group { + constructor(config) { // call super constructor - _super.call(this, config) || this; - _this._transforming = false; - _this._createElements(); + super(config); + this._transforming = false; + this._createElements(); // bindings - _this._handleMouseMove = _this._handleMouseMove.bind(_this); - _this._handleMouseUp = _this._handleMouseUp.bind(_this); - _this.update = _this.update.bind(_this); + this._handleMouseMove = this._handleMouseMove.bind(this); + this._handleMouseUp = this._handleMouseUp.bind(this); + this.update = this.update.bind(this); // update transformer data for certain attr changes - _this.on(ATTR_CHANGE_LIST$2, _this.update); - if (_this.getNode()) { - _this.update(); + this.on(ATTR_CHANGE_LIST, this.update); + if (this.getNode()) { + this.update(); } - return _this; } /** * alias to `tr.nodes([shape])`/ This method is deprecated and will be removed soon. @@ -15038,20 +14758,18 @@ * @example * transformer.attachTo(shape); */ - Transformer.prototype.attachTo = function (node) { + attachTo(node) { this.setNode(node); return this; - }; - Transformer.prototype.setNode = function (node) { + } + setNode(node) { Util.warn('tr.setNode(shape), tr.node(shape) and tr.attachTo(shape) methods are deprecated. Please use tr.nodes(nodesArray) instead.'); return this.setNodes([node]); - }; - Transformer.prototype.getNode = function () { + } + getNode() { return this._nodes && this._nodes[0]; - }; - Transformer.prototype.setNodes = function (nodes) { - var _this = this; - if (nodes === void 0) { nodes = []; } + } + setNodes(nodes = []) { if (this._nodes && this._nodes.length) { this.detach(); } @@ -15062,25 +14780,25 @@ else { this.rotation(0); } - this._nodes.forEach(function (node) { - var additionalEvents = node._attrsAffectingSize - .map(function (prop) { return prop + 'Change.' + EVENTS_NAME; }) + this._nodes.forEach((node) => { + const additionalEvents = node._attrsAffectingSize + .map((prop) => prop + 'Change.' + EVENTS_NAME) .join(' '); - var onChange = function () { + const onChange = () => { // - if (_this.nodes().length === 1) { - _this.rotation(_this.nodes()[0].getAbsoluteRotation()); + if (this.nodes().length === 1) { + this.rotation(this.nodes()[0].getAbsoluteRotation()); } - _this._resetTransformCache(); - if (!_this._transforming && !_this.isDragging()) { - _this.update(); + this._resetTransformCache(); + if (!this._transforming && !this.isDragging()) { + this.update(); } }; node.on(additionalEvents, onChange); - node.on(TRANSFORM_CHANGE_STR$1, onChange); - node.on("_clearTransformCache." + EVENTS_NAME, onChange); - node.on("xChange." + EVENTS_NAME + " yChange." + EVENTS_NAME, onChange); - _this._proxyDrag(node); + node.on(TRANSFORM_CHANGE_STR, onChange); + node.on(`_clearTransformCache.${EVENTS_NAME}`, onChange); + node.on(`xChange.${EVENTS_NAME} yChange.${EVENTS_NAME}`, onChange); + this._proxyDrag(node); }); this._resetTransformCache(); // we may need it if we set node in initial props @@ -15090,33 +14808,32 @@ this.update(); } return this; - }; - Transformer.prototype._proxyDrag = function (node) { - var _this = this; - var lastPos; - node.on("dragstart." + EVENTS_NAME, function (e) { + } + _proxyDrag(node) { + let lastPos; + node.on(`dragstart.${EVENTS_NAME}`, (e) => { lastPos = node.getAbsolutePosition(); // actual dragging of Transformer doesn't make sense // but we need to proxy drag events - if (!_this.isDragging() && node !== _this.findOne('.back')) { - _this.startDrag(e, false); + if (!this.isDragging() && node !== this.findOne('.back')) { + this.startDrag(e, false); } }); - node.on("dragmove." + EVENTS_NAME, function (e) { + node.on(`dragmove.${EVENTS_NAME}`, (e) => { if (!lastPos) { return; } - var abs = node.getAbsolutePosition(); - var dx = abs.x - lastPos.x; - var dy = abs.y - lastPos.y; - _this.nodes().forEach(function (otherNode) { + const abs = node.getAbsolutePosition(); + const dx = abs.x - lastPos.x; + const dy = abs.y - lastPos.y; + this.nodes().forEach((otherNode) => { if (otherNode === node) { return; } if (otherNode.isDragging()) { return; } - var otherAbs = otherNode.getAbsolutePosition(); + const otherAbs = otherNode.getAbsolutePosition(); otherNode.setAbsolutePosition({ x: otherAbs.x + dx, y: otherAbs.y + dy, @@ -15125,10 +14842,10 @@ }); lastPos = null; }); - }; - Transformer.prototype.getNodes = function () { + } + getNodes() { return this._nodes || []; - }; + } /** * return the name of current active anchor * @method @@ -15137,9 +14854,9 @@ * @example * transformer.getActiveAnchor(); */ - Transformer.prototype.getActiveAnchor = function () { + getActiveAnchor() { return this._movingAnchorName; - }; + } /** * detach transformer from an attached node * @method @@ -15148,27 +14865,26 @@ * @example * transformer.detach(); */ - Transformer.prototype.detach = function () { + detach() { // remove events if (this._nodes) { - this._nodes.forEach(function (node) { + this._nodes.forEach((node) => { node.off('.' + EVENTS_NAME); }); } this._nodes = []; this._resetTransformCache(); - }; - Transformer.prototype._resetTransformCache = function () { + } + _resetTransformCache() { this._clearCache(NODES_RECT); this._clearCache('transform'); this._clearSelfAndDescendantCache('absoluteTransform'); - }; - Transformer.prototype._getNodeRect = function () { + } + _getNodeRect() { return this._getCache(NODES_RECT, this.__getNodeRect); - }; + } // return absolute rotated bounding rectangle - Transformer.prototype.__getNodeShape = function (node, rot, relative) { - if (rot === void 0) { rot = this.rotation(); } + __getNodeShape(node, rot = this.rotation(), relative) { var rect = node.getClientRect({ skipTransform: true, skipShadow: true, @@ -15178,23 +14894,22 @@ var absPos = node.getAbsolutePosition(relative); var dx = rect.x * absScale.x - node.offsetX() * absScale.x; var dy = rect.y * absScale.y - node.offsetY() * absScale.y; - var rotation = (Konva.getAngle(node.getAbsoluteRotation()) + Math.PI * 2) % + const rotation = (Konva$2.getAngle(node.getAbsoluteRotation()) + Math.PI * 2) % (Math.PI * 2); - var box = { + const box = { x: absPos.x + dx * Math.cos(rotation) + dy * Math.sin(-rotation), y: absPos.y + dy * Math.cos(rotation) + dx * Math.sin(rotation), width: rect.width * absScale.x, height: rect.height * absScale.y, rotation: rotation, }; - return rotateAroundPoint(box, -Konva.getAngle(rot), { + return rotateAroundPoint(box, -Konva$2.getAngle(rot), { x: 0, y: 0, }); - }; + } // returns box + rotation of all shapes - Transformer.prototype.__getNodeRect = function () { - var _this = this; + __getNodeRect() { var node = this.getNode(); if (!node) { return { @@ -15205,12 +14920,12 @@ rotation: 0, }; } - var totalPoints = []; - this.nodes().map(function (node) { - var box = node.getClientRect({ + const totalPoints = []; + this.nodes().map((node) => { + const box = node.getClientRect({ skipTransform: true, skipShadow: true, - skipStroke: _this.ignoreStroke(), + skipStroke: this.ignoreStroke(), }); var points = [ { x: box.x, y: box.y }, @@ -15224,8 +14939,8 @@ totalPoints.push(transformed); }); }); - var tr = new Transform(); - tr.rotate(-Konva.getAngle(this.rotation())); + const tr = new Transform(); + tr.rotate(-Konva$2.getAngle(this.rotation())); var minX, minY, maxX, maxY; totalPoints.forEach(function (point) { var transformed = tr.point(point); @@ -15239,13 +14954,13 @@ maxY = Math.max(maxY, transformed.y); }); tr.invert(); - var p = tr.point({ x: minX, y: minY }); + const p = tr.point({ x: minX, y: minY }); return { x: p.x, y: p.y, width: maxX - minX, height: maxY - minY, - rotation: Konva.getAngle(this.rotation()), + rotation: Konva$2.getAngle(this.rotation()), }; // const shapes = this.nodes().map(node => { // return this.__getNodeShape(node); @@ -15255,28 +14970,27 @@ // x: 0, // y: 0 // }); - }; - Transformer.prototype.getX = function () { + } + getX() { return this._getNodeRect().x; - }; - Transformer.prototype.getY = function () { + } + getY() { return this._getNodeRect().y; - }; - Transformer.prototype.getWidth = function () { + } + getWidth() { return this._getNodeRect().width; - }; - Transformer.prototype.getHeight = function () { + } + getHeight() { return this._getNodeRect().height; - }; - Transformer.prototype._createElements = function () { + } + _createElements() { this._createBack(); ANCHORS_NAMES.forEach(function (name) { this._createAnchor(name); }.bind(this)); this._createAnchor('rotater'); - }; - Transformer.prototype._createAnchor = function (name) { - var _this = this; + } + _createAnchor(name) { var anchor = new Rect({ stroke: 'rgb(0, 161, 255)', fill: 'white', @@ -15292,34 +15006,33 @@ anchor.on('mousedown touchstart', function (e) { self._handleMouseDown(e); }); - anchor.on('dragstart', function (e) { + anchor.on('dragstart', (e) => { anchor.stopDrag(); e.cancelBubble = true; }); - anchor.on('dragend', function (e) { + anchor.on('dragend', (e) => { e.cancelBubble = true; }); // add hover styling - anchor.on('mouseenter', function () { - var rad = Konva.getAngle(_this.rotation()); + anchor.on('mouseenter', () => { + var rad = Konva$2.getAngle(this.rotation()); var cursor = getCursor(name, rad); anchor.getStage().content.style.cursor = cursor; - _this._cursorChange = true; + this._cursorChange = true; }); - anchor.on('mouseout', function () { + anchor.on('mouseout', () => { anchor.getStage().content.style.cursor = ''; - _this._cursorChange = false; + this._cursorChange = false; }); this.add(anchor); - }; - Transformer.prototype._createBack = function () { - var _this = this; + } + _createBack() { var back = new Shape({ name: 'back', width: 0, height: 0, draggable: true, - sceneFunc: function (ctx) { + sceneFunc(ctx) { var tr = this.getParent(); var padding = tr.padding(); ctx.beginPath(); @@ -15330,11 +15043,11 @@ } ctx.fillStrokeShape(this); }, - hitFunc: function (ctx, shape) { - if (!_this.shouldOverdrawWholeArea()) { + hitFunc: (ctx, shape) => { + if (!this.shouldOverdrawWholeArea()) { return; } - var padding = _this.padding(); + var padding = this.padding(); ctx.beginPath(); ctx.rect(-padding, -padding, shape.width() + padding * 2, shape.height() + padding * 2); ctx.fillStrokeShape(shape); @@ -15345,17 +15058,17 @@ // do not bubble drag from the back shape // because we already "drag" whole transformer // so we don't want to trigger drag twice on transformer - back.on('dragstart', function (e) { + back.on('dragstart', (e) => { e.cancelBubble = true; }); - back.on('dragmove', function (e) { + back.on('dragmove', (e) => { e.cancelBubble = true; }); - back.on('dragend', function (e) { + back.on('dragend', (e) => { e.cancelBubble = true; }); - }; - Transformer.prototype._handleMouseDown = function (e) { + } + _handleMouseDown(e) { this._movingAnchorName = e.target.name().split(' ')[0]; var attrs = this._getNodeRect(); var width = attrs.width; @@ -15375,23 +15088,23 @@ y: pos.y - ap.y, }; this._fire('transformstart', { evt: e, target: this.getNode() }); - this._nodes.forEach(function (target) { - target._fire('transformstart', { evt: e, target: target }); + this._nodes.forEach((target) => { + target._fire('transformstart', { evt: e, target }); }); - }; - Transformer.prototype._handleMouseMove = function (e) { + } + _handleMouseMove(e) { var x, y, newHypotenuse; var anchorNode = this.findOne('.' + this._movingAnchorName); var stage = anchorNode.getStage(); stage.setPointersPositions(e); - var pp = stage.getPointerPosition(); + const pp = stage.getPointerPosition(); var newNodePos = { x: pp.x - this._anchorDragOffset.x, y: pp.y - this._anchorDragOffset.y, }; - var oldAbs = anchorNode.getAbsolutePosition(); + const oldAbs = anchorNode.getAbsolutePosition(); anchorNode.setAbsolutePosition(newNodePos); - var newAbs = anchorNode.getAbsolutePosition(); + const newAbs = anchorNode.getAbsolutePosition(); if (oldAbs.x === newAbs.x && oldAbs.y === newAbs.y) { return; } @@ -15401,16 +15114,16 @@ x = anchorNode.x() - attrs.width / 2; y = -anchorNode.y() + attrs.height / 2; // hor angle is changed? - var delta = Math.atan2(-y, x) + Math.PI / 2; + let delta = Math.atan2(-y, x) + Math.PI / 2; if (attrs.height < 0) { delta -= Math.PI; } - var oldRotation = Konva.getAngle(this.rotation()); - var newRotation = oldRotation + delta; - var tol = Konva.getAngle(this.rotationSnapTolerance()); - var snappedRot = getSnap(this.rotationSnaps(), newRotation, tol); - var diff = snappedRot - attrs.rotation; - var shape = rotateAroundCenter(attrs, diff); + var oldRotation = Konva$2.getAngle(this.rotation()); + const newRotation = oldRotation + delta; + const tol = Konva$2.getAngle(this.rotationSnapTolerance()); + const snappedRot = getSnap(this.rotationSnaps(), newRotation, tol); + const diff = snappedRot - attrs.rotation; + const shape = rotateAroundCenter(attrs, diff); this._fitNodesInto(shape, e); return; } @@ -15549,16 +15262,16 @@ y: y, width: width, height: height, - rotation: Konva.getAngle(this.rotation()), + rotation: Konva$2.getAngle(this.rotation()), }, e); - }; - Transformer.prototype._handleMouseUp = function (e) { + } + _handleMouseUp(e) { this._removeEvents(e); - }; - Transformer.prototype.getAbsoluteTransform = function () { + } + getAbsoluteTransform() { return this.getTransform(); - }; - Transformer.prototype._removeEvents = function (e) { + } + _removeEvents(e) { if (this._transforming) { this._transforming = false; window.removeEventListener('mousemove', this._handleMouseMove); @@ -15568,17 +15281,16 @@ var node = this.getNode(); this._fire('transformend', { evt: e, target: node }); if (node) { - this._nodes.forEach(function (target) { - target._fire('transformend', { evt: e, target: target }); + this._nodes.forEach((target) => { + target._fire('transformend', { evt: e, target }); }); } this._movingAnchorName = null; } - }; - Transformer.prototype._fitNodesInto = function (newAttrs, evt) { - var _this = this; + } + _fitNodesInto(newAttrs, evt) { var oldAttrs = this._getNodeRect(); - var minSize = 1; + const minSize = 1; if (Util._inRange(newAttrs.width, -this.padding() * 2 - minSize, minSize)) { this.update(); return; @@ -15588,11 +15300,11 @@ return; } var t = new Transform(); - t.rotate(Konva.getAngle(this.rotation())); + t.rotate(Konva$2.getAngle(this.rotation())); if (this._movingAnchorName && newAttrs.width < 0 && this._movingAnchorName.indexOf('left') >= 0) { - var offset = t.point({ + const offset = t.point({ x: -this.padding() * 2, y: 0, }); @@ -15606,7 +15318,7 @@ else if (this._movingAnchorName && newAttrs.width < 0 && this._movingAnchorName.indexOf('right') >= 0) { - var offset = t.point({ + const offset = t.point({ x: this.padding() * 2, y: 0, }); @@ -15618,7 +15330,7 @@ if (this._movingAnchorName && newAttrs.height < 0 && this._movingAnchorName.indexOf('top') >= 0) { - var offset = t.point({ + const offset = t.point({ x: 0, y: -this.padding() * 2, }); @@ -15632,7 +15344,7 @@ else if (this._movingAnchorName && newAttrs.height < 0 && this._movingAnchorName.indexOf('bottom') >= 0) { - var offset = t.point({ + const offset = t.point({ x: 0, y: this.padding() * 2, }); @@ -15642,7 +15354,7 @@ newAttrs.height += this.padding() * 2; } if (this.boundBoxFunc()) { - var bounded = this.boundBoxFunc()(oldAttrs, newAttrs); + const bounded = this.boundBoxFunc()(oldAttrs, newAttrs); if (bounded) { newAttrs = bounded; } @@ -15654,12 +15366,12 @@ // we just need to think about bounding boxes as transforms // but how? // the idea is that we have a transformed rectangle with the size of "baseSize" - var baseSize = 10000000; - var oldTr = new Transform(); + const baseSize = 10000000; + const oldTr = new Transform(); oldTr.translate(oldAttrs.x, oldAttrs.y); oldTr.rotate(oldAttrs.rotation); oldTr.scale(oldAttrs.width / baseSize, oldAttrs.height / baseSize); - var newTr = new Transform(); + const newTr = new Transform(); newTr.translate(newAttrs.x, newAttrs.y); newTr.rotate(newAttrs.rotation); newTr.scale(newAttrs.width / baseSize, newAttrs.height / baseSize); @@ -15669,27 +15381,27 @@ // [delta transform] * [old transform] = [new transform] // that means that // [delta transform] = [new transform] * [old transform inverted] - var delta = newTr.multiply(oldTr.invert()); - this._nodes.forEach(function (node) { + const delta = newTr.multiply(oldTr.invert()); + this._nodes.forEach((node) => { var _a; // for each node we have the same [delta transform] // the equations is // [delta transform] * [parent transform] * [old local transform] = [parent transform] * [new local transform] // and we need to find [new local transform] // [new local] = [parent inverted] * [delta] * [parent] * [old local] - var parentTransform = node.getParent().getAbsoluteTransform(); - var localTransform = node.getTransform().copy(); + const parentTransform = node.getParent().getAbsoluteTransform(); + const localTransform = node.getTransform().copy(); // skip offset: localTransform.translate(node.offsetX(), node.offsetY()); - var newLocalTransform = new Transform(); + const newLocalTransform = new Transform(); newLocalTransform .multiply(parentTransform.copy().invert()) .multiply(delta) .multiply(parentTransform) .multiply(localTransform); - var attrs = newLocalTransform.decompose(); + const attrs = newLocalTransform.decompose(); node.setAttrs(attrs); - _this._fire('transform', { evt: evt, target: node }); + this._fire('transform', { evt: evt, target: node }); node._fire('transform', { evt: evt, target: node }); (_a = node.getLayer()) === null || _a === void 0 ? void 0 : _a.batchDraw(); }); @@ -15697,23 +15409,22 @@ this._resetTransformCache(); this.update(); this.getLayer().batchDraw(); - }; + } /** * force update of Konva.Transformer. * Use it when you updated attached Konva.Group and now you need to reset transformer size * @method * @name Konva.Transformer#forceUpdate */ - Transformer.prototype.forceUpdate = function () { + forceUpdate() { this._resetTransformCache(); this.update(); - }; - Transformer.prototype._batchChangeChild = function (selector, attrs) { - var anchor = this.findOne(selector); + } + _batchChangeChild(selector, attrs) { + const anchor = this.findOne(selector); anchor.setAttrs(attrs); - }; - Transformer.prototype.update = function () { - var _this = this; + } + update() { var _a; var attrs = this._getNodeRect(); this.rotation(Util._getRotation(attrs.rotation)); @@ -15723,16 +15434,16 @@ var resizeEnabled = this.resizeEnabled(); var padding = this.padding(); var anchorSize = this.anchorSize(); - this.find('._anchor').each(function (node) { + this.find('._anchor').forEach((node) => { node.setAttrs({ width: anchorSize, height: anchorSize, offsetX: anchorSize / 2, offsetY: anchorSize / 2, - stroke: _this.anchorStroke(), - strokeWidth: _this.anchorStrokeWidth(), - fill: _this.anchorFill(), - cornerRadius: _this.anchorCornerRadius(), + stroke: this.anchorStroke(), + strokeWidth: this.anchorStrokeWidth(), + fill: this.anchorFill(), + cornerRadius: this.anchorCornerRadius(), }); }); this._batchChangeChild('.top-left', { @@ -15803,23 +15514,23 @@ y: 0, }); (_a = this.getLayer()) === null || _a === void 0 ? void 0 : _a.batchDraw(); - }; + } /** * determine if transformer is in active transform * @method * @name Konva.Transformer#isTransforming * @returns {Boolean} */ - Transformer.prototype.isTransforming = function () { + isTransforming() { return this._transforming; - }; + } /** * Stop active transform action * @method * @name Konva.Transformer#stopTransform * @returns {Boolean} */ - Transformer.prototype.stopTransform = function () { + stopTransform() { if (this._transforming) { this._removeEvents(); var anchorNode = this.findOne('.' + this._movingAnchorName); @@ -15827,8 +15538,8 @@ anchorNode.stopDrag(); } } - }; - Transformer.prototype.destroy = function () { + } + destroy() { if (this.getStage() && this._cursorChange) { this.getStage().content.style.cursor = ''; } @@ -15836,14 +15547,13 @@ this.detach(); this._removeEvents(); return this; - }; + } // do not work as a container // we will recreate inner nodes manually - Transformer.prototype.toObject = function () { + toObject() { return Node.prototype.toObject.call(this); - }; - return Transformer; - }(Group)); + } + } function validateAnchors(val) { if (!(val instanceof Array)) { Util.warn('enabledAnchors value should be an array'); @@ -16175,8 +15885,7 @@ lineEnabled: 'borderEnabled', rotateHandlerOffset: 'rotateAnchorOffset', enabledHandlers: 'enabledAnchors', - }); - Collection.mapMethods(Transformer); + }); /** * Wedge constructor @@ -16272,32 +15981,27 @@ * rotationDeg: -120 * }); */ - var Wedge = /** @class */ (function (_super) { - __extends(Wedge, _super); - function Wedge() { - return _super !== null && _super.apply(this, arguments) || this; - } - Wedge.prototype._sceneFunc = function (context) { + class Wedge extends Shape { + _sceneFunc(context) { context.beginPath(); - context.arc(0, 0, this.radius(), 0, Konva.getAngle(this.angle()), this.clockwise()); + context.arc(0, 0, this.radius(), 0, Konva$2.getAngle(this.angle()), this.clockwise()); context.lineTo(0, 0); context.closePath(); context.fillStrokeShape(this); - }; - Wedge.prototype.getWidth = function () { + } + getWidth() { return this.radius() * 2; - }; - Wedge.prototype.getHeight = function () { + } + getHeight() { return this.radius() * 2; - }; - Wedge.prototype.setWidth = function (width) { + } + setWidth(width) { this.radius(width / 2); - }; - Wedge.prototype.setHeight = function (height) { + } + setHeight(height) { this.radius(height / 2); - }; - return Wedge; - }(Shape)); + } + } Wedge.prototype.className = 'Wedge'; Wedge.prototype._centroid = true; Wedge.prototype._attrsAffectingSize = ['radius']; @@ -16350,9 +16054,8 @@ Factory.backCompat(Wedge, { angleDeg: 'angle', getAngleDeg: 'getAngle', - setAngleDeg: 'setAngle' - }); - Collection.mapMethods(Wedge); + setAngleDeg: 'setAngle', + }); /* the Gauss filter @@ -17096,7 +16799,7 @@ * node.filters([Konva.Filters.Blur]); * node.blurRadius(10); */ - var Blur = function Blur(imageData) { + const Blur = function Blur(imageData) { var radius = Math.round(this.blurRadius()); if (radius > 0) { filterGaussBlurRGBA(imageData, radius); @@ -17121,7 +16824,7 @@ * node.filters([Konva.Filters.Brighten]); * node.brightness(0.8); */ - var Brighten = function (imageData) { + const Brighten = function (imageData) { var brightness = this.brightness() * 255, data = imageData.data, len = data.length, i; for (i = 0; i < len; i += 4) { // red @@ -17153,7 +16856,7 @@ * node.filters([Konva.Filters.Contrast]); * node.contrast(10); */ - var Contrast = function (imageData) { + const Contrast = function (imageData) { var adjust = Math.pow((this.contrast() + 100) / 100, 2); var data = imageData.data, nPixels = data.length, red = 150, green = 150, blue = 150, i; for (i = 0; i < nPixels; i += 4) { @@ -17212,7 +16915,7 @@ * node.embossDirection('right'); * node.embossBlend(true); */ - var Emboss = function (imageData) { + const Emboss = function (imageData) { // pixastic strength is between 0 and 10. I want it between 0 and 1 // 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 @@ -17373,7 +17076,7 @@ * node.filters([Konva.Filters.Enhance]); * node.enhance(0.4); */ - var Enhance = function (imageData) { + const Enhance = function (imageData) { var data = imageData.data, nSubPixels = data.length, rMin = data[0], rMax = rMin, r, gMin = data[1], gMax = gMin, g, bMin = data[2], bMax = bMin, b, i; // If we are not enhancing anything - don't do any computation var enhanceAmount = this.enhance(); @@ -17468,7 +17171,7 @@ * node.cache(); * node.filters([Konva.Filters.Grayscale]); */ - var Grayscale = function (imageData) { + const Grayscale = function (imageData) { var data = imageData.data, len = data.length, i, brightness; for (i = 0; i < len; i += 4) { brightness = 0.34 * data[i] + 0.5 * data[i + 1] + 0.16 * data[i + 2]; @@ -17515,7 +17218,7 @@ * image.filters([Konva.Filters.HSL]); * image.luminance(0.2); */ - var HSL = function (imageData) { + const HSL = function (imageData) { var data = imageData.data, nPixels = data.length, v = 1, s = Math.pow(2, this.saturation()), h = Math.abs(this.hue() + 360) % 360, l = this.luminance() * 127, i; // Basis for the technique used: // http://beesbuzz.biz/code/hsv_color_transforms.php @@ -17557,7 +17260,7 @@ * image.filters([Konva.Filters.HSV]); * image.value(200); */ - var HSV = function (imageData) { + const HSV = function (imageData) { var 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; // Basis for the technique used: // http://beesbuzz.biz/code/hsv_color_transforms.php @@ -17621,7 +17324,7 @@ * node.cache(); * node.filters([Konva.Filters.Invert]); */ - var Invert = function (imageData) { + const Invert = function (imageData) { var data = imageData.data, len = data.length, i; for (i = 0; i < len; i += 4) { // red @@ -17752,7 +17455,7 @@ * node.kaleidoscopePower(3); * node.kaleidoscopeAngle(45); */ - var Kaleidoscope = function (imageData) { + const Kaleidoscope = function (imageData) { var xSize = imageData.width, ySize = imageData.height; var x, y, xoff, i, r, g, b, a, srcPos, dstPos; var power = Math.round(this.kaleidoscopePower()); @@ -17984,7 +17687,7 @@ * node.filters([Konva.Filters.Mask]); * node.threshold(200); */ - var Mask = function (imageData) { + const Mask = function (imageData) { // Detect pixels close to the background color var threshold = this.threshold(), mask = backgroundMask(imageData, threshold); if (mask) { @@ -18013,7 +17716,7 @@ * node.filters([Konva.Filters.Noise]); * node.noise(0.8); */ - var Noise = function (imageData) { + const Noise = function (imageData) { var amount = this.noise() * 255, data = imageData.data, nPixels = data.length, half = amount / 2, i; for (i = 0; i < nPixels; i += 4) { data[i + 0] += half - 2 * half * Math.random(); @@ -18044,7 +17747,7 @@ * node.filters([Konva.Filters.Pixelate]); * node.pixelSize(10); */ - var Pixelate = function (imageData) { + const Pixelate = function (imageData) { var pixelSize = Math.ceil(this.pixelSize()), width = imageData.width, height = imageData.height, x, y, i, //pixelsPerBin = pixelSize * pixelSize, red, green, blue, alpha, nBinsX = Math.ceil(width / pixelSize), nBinsY = Math.ceil(height / pixelSize), xBinStart, xBinEnd, yBinStart, yBinEnd, xBin, yBin, pixelsInBin, data = imageData.data; @@ -18129,7 +17832,7 @@ * node.filters([Konva.Filters.Posterize]); * node.levels(0.8); // between 0 and 1 */ - var Posterize = function (imageData) { + const Posterize = function (imageData) { // level must be between 1 and 255 var levels = Math.round(this.levels() * 254) + 1, data = imageData.data, len = data.length, scale = 255 / levels, i; for (i = 0; i < len; i += 1) { @@ -18158,7 +17861,7 @@ * node.blue(120); * node.green(200); */ - var RGB = function (imageData) { + const RGB = function (imageData) { var data = imageData.data, nPixels = data.length, red = this.red(), green = this.green(), blue = this.blue(), i, brightness; for (i = 0; i < nPixels; i += 4) { brightness = @@ -18233,7 +17936,7 @@ * node.green(200); * node.alpha(0.3); */ - var RGBA = function (imageData) { + const RGBA = function (imageData) { var data = imageData.data, nPixels = data.length, red = this.red(), green = this.green(), blue = this.blue(), alpha = this.alpha(), i, ia; for (i = 0; i < nPixels; i += 4) { ia = 1 - alpha; @@ -18322,7 +18025,7 @@ * node.cache(); * node.filters([Konva.Filters.Sepia]); */ - var Sepia = function (imageData) { + const Sepia = function (imageData) { var data = imageData.data, nPixels = data.length, i, r, g, b; for (i = 0; i < nPixels; i += 4) { r = data[i + 0]; @@ -18347,7 +18050,7 @@ * node.cache(); * node.filters([Konva.Filters.Solarize]); */ - var Solarize = function (imageData) { + const Solarize = function (imageData) { var data = imageData.data, w = imageData.width, h = imageData.height, w4 = w * 4, y = h; do { var offsetY = (y - 1) * w4; @@ -18387,7 +18090,7 @@ * node.filters([Konva.Filters.Threshold]); * node.threshold(0.1); */ - var Threshold = function (imageData) { + const Threshold = function (imageData) { var level = this.threshold() * 255, data = imageData.data, len = data.length, i; for (i = 0; i < len; i += 1) { data[i] = data[i] < level ? 0 : 255; @@ -18404,54 +18107,52 @@ */ // we need to import core of the Konva and then extend it with all additional objects - var Konva$2 = Konva$1.Util._assign(Konva$1, { - Arc: Arc, - Arrow: Arrow, - Circle: Circle, - Ellipse: Ellipse, - Image: Image, - Label: Label, - Tag: Tag, - Line: Line, - Path: Path, - Rect: Rect, - RegularPolygon: RegularPolygon, - Ring: Ring, - Sprite: Sprite, - Star: Star, - Text: Text, - TextPath: TextPath, - Transformer: Transformer, - Wedge: Wedge, + const Konva = Konva$1.Util._assign(Konva$1, { + Arc, + Arrow, + Circle, + Ellipse, + Image, + Label, + Tag, + Line, + Path, + Rect, + RegularPolygon, + Ring, + Sprite, + Star, + Text, + TextPath, + Transformer, + Wedge, /** * @namespace Filters * @memberof Konva */ Filters: { - Blur: Blur, - Brighten: Brighten, - Contrast: Contrast, - Emboss: Emboss, - Enhance: Enhance, - Grayscale: Grayscale, - HSL: HSL, - HSV: HSV, - Invert: Invert, - Kaleidoscope: Kaleidoscope, - Mask: Mask, - Noise: Noise, - Pixelate: Pixelate, - Posterize: Posterize, - RGB: RGB, - RGBA: RGBA, - Sepia: Sepia, - Solarize: Solarize, - Threshold: Threshold, + Blur, + Brighten, + Contrast, + Emboss, + Enhance, + Grayscale, + HSL, + HSV, + Invert, + Kaleidoscope, + Mask, + Noise, + Pixelate, + Posterize, + RGB, + RGBA, + Sepia, + Solarize, + Threshold, }, }); - // main entry for umd build for rollup - - return Konva$2; + return Konva; }))); diff --git a/konva.min.js b/konva.min.js index 96bbb89c..cf8a0e6f 100644 --- a/konva.min.js +++ b/konva.min.js @@ -3,10 +3,10 @@ * Konva JavaScript Framework v7.2.5 * http://konvajs.org/ * Licensed under the MIT - * Date: Wed Mar 03 2021 + * Date: Thu Apr 29 2021 * * Original work Copyright (C) 2011 - 2013 by Eric Rowell (KineticJS) * Modified work Copyright (C) 2014 - present by Anton Lavrenov (Konva) * * @license - */var t=Math.PI/180;var e=function(t){var e=t.indexOf("msie ");if(e>0)return parseInt(t.substring(e+5,t.indexOf(".",e)),10);if(t.indexOf("trident/")>0){var i=t.indexOf("rv:");return parseInt(t.substring(i+3,t.indexOf(".",i)),10)}var n=t.indexOf("edge/");return n>0&&parseInt(t.substring(n+5,t.indexOf(".",n)),10)},i=function(t){var i=t.toLowerCase(),n=/(chrome)[ /]([\w.]+)/.exec(i)||/(webkit)[ /]([\w.]+)/.exec(i)||/(opera)(?:.*version|)[ /]([\w.]+)/.exec(i)||/(msie) ([\w.]+)/.exec(i)||i.indexOf("compatible")<0&&/(mozilla)(?:.*? rv:([\w.]+)|)/.exec(i)||[],r=!!t.match(/Android|BlackBerry|iPhone|iPad|iPod|Opera Mini|IEMobile/i),o=!!t.match(/IEMobile/i);return{browser:n[1]||"",version:n[2]||"0",isIE:e(i),mobile:r,ieMobile:o}},n="undefined"!=typeof global?global:"undefined"!=typeof window?window:"undefined"!=typeof WorkerGlobalScope?self:{},r={_global:n,version:"7.2.5",isBrowser:"undefined"!=typeof window&&("[object Window]"==={}.toString.call(window)||"[object global]"==={}.toString.call(window)),isUnminified:/param/.test(function(t){}.toString()),dblClickWindow:400,getAngle:function(e){return r.angleDeg?e*t:e},enableTrace:!1,_pointerEventsEnabled:!1,hitOnDragEnabled:!1,captureTouchEventsEnabled:!1,listenClickTap:!1,inDblClickWindow:!1,pixelRatio:void 0,dragDistance:3,angleDeg:!0,showWarnings:!0,dragButtons:[0,1],isDragging:function(){return r.DD.isDragging},isDragReady:function(){return!!r.DD.node},UA:i(n.navigator&&n.navigator.userAgent||""),document:n.document,_injectGlobal:function(t){n.Konva=t},_parseUA:i},o={},a=function(t){o[t.prototype.getClassName()]=t,r[t.prototype.getClassName()]=t},s=function(){function t(){}return t.toCollection=function(e){var i,n=new t,r=e.length;for(i=0;i0?Math.acos(t/a):-Math.acos(t/a),o.scaleX=a,o.scaleY=r/a,o.skewX=(t*i+e*n)/r,o.skewY=0}else if(0!=i||0!=n){var s=Math.sqrt(i*i+n*n);o.rotation=Math.PI/2-(n>0?Math.acos(-i/s):-Math.acos(i/s)),o.scaleX=r/s,o.scaleY=s,o.skewX=0,o.skewY=(t*i+e*n)/r}return o.rotation=f._getRotation(o.rotation),o},t}(),l=Math.PI/180,c=180/Math.PI,d={aliceblue:[240,248,255],antiquewhite:[250,235,215],aqua:[0,255,255],aquamarine:[127,255,212],azure:[240,255,255],beige:[245,245,220],bisque:[255,228,196],black:[0,0,0],blanchedalmond:[255,235,205],blue:[0,0,255],blueviolet:[138,43,226],brown:[165,42,42],burlywood:[222,184,135],cadetblue:[95,158,160],chartreuse:[127,255,0],chocolate:[210,105,30],coral:[255,127,80],cornflowerblue:[100,149,237],cornsilk:[255,248,220],crimson:[220,20,60],cyan:[0,255,255],darkblue:[0,0,139],darkcyan:[0,139,139],darkgoldenrod:[184,132,11],darkgray:[169,169,169],darkgreen:[0,100,0],darkgrey:[169,169,169],darkkhaki:[189,183,107],darkmagenta:[139,0,139],darkolivegreen:[85,107,47],darkorange:[255,140,0],darkorchid:[153,50,204],darkred:[139,0,0],darksalmon:[233,150,122],darkseagreen:[143,188,143],darkslateblue:[72,61,139],darkslategray:[47,79,79],darkslategrey:[47,79,79],darkturquoise:[0,206,209],darkviolet:[148,0,211],deeppink:[255,20,147],deepskyblue:[0,191,255],dimgray:[105,105,105],dimgrey:[105,105,105],dodgerblue:[30,144,255],firebrick:[178,34,34],floralwhite:[255,255,240],forestgreen:[34,139,34],fuchsia:[255,0,255],gainsboro:[220,220,220],ghostwhite:[248,248,255],gold:[255,215,0],goldenrod:[218,165,32],gray:[128,128,128],green:[0,128,0],greenyellow:[173,255,47],grey:[128,128,128],honeydew:[240,255,240],hotpink:[255,105,180],indianred:[205,92,92],indigo:[75,0,130],ivory:[255,255,240],khaki:[240,230,140],lavender:[230,230,250],lavenderblush:[255,240,245],lawngreen:[124,252,0],lemonchiffon:[255,250,205],lightblue:[173,216,230],lightcoral:[240,128,128],lightcyan:[224,255,255],lightgoldenrodyellow:[250,250,210],lightgray:[211,211,211],lightgreen:[144,238,144],lightgrey:[211,211,211],lightpink:[255,182,193],lightsalmon:[255,160,122],lightseagreen:[32,178,170],lightskyblue:[135,206,250],lightslategray:[119,136,153],lightslategrey:[119,136,153],lightsteelblue:[176,196,222],lightyellow:[255,255,224],lime:[0,255,0],limegreen:[50,205,50],linen:[250,240,230],magenta:[255,0,255],maroon:[128,0,0],mediumaquamarine:[102,205,170],mediumblue:[0,0,205],mediumorchid:[186,85,211],mediumpurple:[147,112,219],mediumseagreen:[60,179,113],mediumslateblue:[123,104,238],mediumspringgreen:[0,250,154],mediumturquoise:[72,209,204],mediumvioletred:[199,21,133],midnightblue:[25,25,112],mintcream:[245,255,250],mistyrose:[255,228,225],moccasin:[255,228,181],navajowhite:[255,222,173],navy:[0,0,128],oldlace:[253,245,230],olive:[128,128,0],olivedrab:[107,142,35],orange:[255,165,0],orangered:[255,69,0],orchid:[218,112,214],palegoldenrod:[238,232,170],palegreen:[152,251,152],paleturquoise:[175,238,238],palevioletred:[219,112,147],papayawhip:[255,239,213],peachpuff:[255,218,185],peru:[205,133,63],pink:[255,192,203],plum:[221,160,203],powderblue:[176,224,230],purple:[128,0,128],rebeccapurple:[102,51,153],red:[255,0,0],rosybrown:[188,143,143],royalblue:[65,105,225],saddlebrown:[139,69,19],salmon:[250,128,114],sandybrown:[244,164,96],seagreen:[46,139,87],seashell:[255,245,238],sienna:[160,82,45],silver:[192,192,192],skyblue:[135,206,235],slateblue:[106,90,205],slategray:[119,128,144],slategrey:[119,128,144],snow:[255,255,250],springgreen:[0,255,127],steelblue:[70,130,180],tan:[210,180,140],teal:[0,128,128],thistle:[216,191,216],transparent:[255,255,255,0],tomato:[255,99,71],turquoise:[64,224,208],violet:[238,130,238],wheat:[245,222,179],white:[255,255,255],whitesmoke:[245,245,245],yellow:[255,255,0],yellowgreen:[154,205,5]},u=/rgb\((\d{1,3}),(\d{1,3}),(\d{1,3})\)/,p=[],f={_isElement:function(t){return!(!t||1!=t.nodeType)},_isFunction:function(t){return!!(t&&t.constructor&&t.call&&t.apply)},_isPlainObject:function(t){return!!t&&t.constructor===Object},_isArray:function(t){return"[object Array]"===Object.prototype.toString.call(t)},_isNumber:function(t){return"[object Number]"===Object.prototype.toString.call(t)&&!isNaN(t)&&isFinite(t)},_isString:function(t){return"[object String]"===Object.prototype.toString.call(t)},_isBoolean:function(t){return"[object Boolean]"===Object.prototype.toString.call(t)},isObject:function(t){return t instanceof Object},isValidSelector:function(t){if("string"!=typeof t)return!1;var e=t[0];return"#"===e||"."===e||e===e.toUpperCase()},_sign:function(t){return 0===t||t>0?1:-1},requestAnimFrame:function(t){p.push(t),1===p.length&&requestAnimationFrame((function(){var t=p;p=[],t.forEach((function(t){t()}))}))},createCanvasElement:function(){var t=document.createElement("canvas");try{t.style=t.style||{}}catch(t){}return t},createImageElement:function(){return document.createElement("img")},_isInDocument:function(t){for(;t=t.parentNode;)if(t==document)return!0;return!1},_simplifyArray:function(t){var e,i,n=[],r=t.length,o=f;for(e=0;e>16&255,g:e>>8&255,b:255&e}},getRandomColor:function(){for(var t=(16777215*Math.random()<<0).toString(16);t.length<6;)t="0"+t;return"#"+t},get:function(t,e){return void 0===t?e:t},getRGB:function(t){var e;return t in d?{r:(e=d[t])[0],g:e[1],b:e[2]}:"#"===t[0]?this._hexToRgb(t.substring(1)):"rgb("===t.substr(0,4)?(e=u.exec(t.replace(/ /g,"")),{r:parseInt(e[1],10),g:parseInt(e[2],10),b:parseInt(e[3],10)}):{r:0,g:0,b:0}},colorToRGBA:function(t){return t=t||"black",f._namedColorToRBA(t)||f._hex3ColorToRGBA(t)||f._hex6ColorToRGBA(t)||f._rgbColorToRGBA(t)||f._rgbaColorToRGBA(t)||f._hslColorToRGBA(t)},_namedColorToRBA:function(t){var e=d[t.toLowerCase()];return e?{r:e[0],g:e[1],b:e[2],a:1}:null},_rgbColorToRGBA:function(t){if(0===t.indexOf("rgb(")){var e=(t=t.match(/rgb\(([^)]+)\)/)[1]).split(/ *, */).map(Number);return{r:e[0],g:e[1],b:e[2],a:1}}},_rgbaColorToRGBA:function(t){if(0===t.indexOf("rgba(")){var e=(t=t.match(/rgba\(([^)]+)\)/)[1]).split(/ *, */).map(Number);return{r:e[0],g:e[1],b:e[2],a:e[3]}}},_hex6ColorToRGBA:function(t){if("#"===t[0]&&7===t.length)return{r:parseInt(t.slice(1,3),16),g:parseInt(t.slice(3,5),16),b:parseInt(t.slice(5,7),16),a:1}},_hex3ColorToRGBA:function(t){if("#"===t[0]&&4===t.length)return{r:parseInt(t[1]+t[1],16),g:parseInt(t[2]+t[2],16),b:parseInt(t[3]+t[3],16),a:1}},_hslColorToRGBA:function(t){if(/hsl\((\d+),\s*([\d.]+)%,\s*([\d.]+)%\)/g.test(t)){var e=/hsl\((\d+),\s*([\d.]+)%,\s*([\d.]+)%\)/g.exec(t);e[0];var i=e.slice(1),n=Number(i[0])/360,r=Number(i[1])/100,o=Number(i[2])/100,a=void 0,s=void 0,h=void 0;if(0===r)return h=255*o,{r:Math.round(h),g:Math.round(h),b:Math.round(h),a:1};for(var l=2*o-(a=o<.5?o*(1+r):o+r-o*r),c=[0,0,0],d=0;d<3;d++)(s=n+1/3*-(d-1))<0&&s++,s>1&&s--,h=6*s<1?l+6*(a-l)*s:2*s<1?a:3*s<2?l+(a-l)*(2/3-s)*6:l,c[d]=255*h;return{r:Math.round(c[0]),g:Math.round(c[1]),b:Math.round(c[2]),a:1}}},haveIntersection:function(t,e){return!(e.x>t.x+t.width||e.x+e.widtht.y+t.height||e.y+e.height1?(a=i,s=n,h=(i-r)*(i-r)+(n-o)*(n-o)):h=((a=t+c*(i-t))-r)*(a-r)+((s=e+c*(n-e))-o)*(s-o)}return[a,s,h]},_getProjectionToLine:function(t,e,i){var n=f.cloneObject(t),r=Number.MAX_VALUE;return e.forEach((function(o,a){if(i||a!==e.length-1){var s=e[(a+1)%e.length],h=f._getProjectionToSegment(o.x,o.y,s.x,s.y,t.x,t.y),l=h[0],c=h[1],d=h[2];de.length){var a=e;e=t,t=a}for(n=0;n255?255:t<0?0:Math.round(t)}function y(){if(r.isUnminified)return function(t,e){return f._isNumber(t)||f.warn(g(t)+' is a not valid value for "'+e+'" attribute. The value should be a number.'),t}}function m(t){if(r.isUnminified)return function(e,i){var n=f._isNumber(e),r=f._isArray(e)&&e.length==t;return n||r||f.warn(g(e)+' is a not valid value for "'+i+'" attribute. The value should be a number or Array('+t+")"),e}}function _(){if(r.isUnminified)return function(t,e){return f._isNumber(t)||"auto"===t||f.warn(g(t)+' is a not valid value for "'+e+'" attribute. The value should be a number or "auto".'),t}}function b(){if(r.isUnminified)return function(t,e){return f._isString(t)||f.warn(g(t)+' is a not valid value for "'+e+'" attribute. The value should be a string.'),t}}function x(){if(r.isUnminified)return function(t,e){var i=f._isString(t),n="[object CanvasGradient]"===Object.prototype.toString.call(t);return i||n||f.warn(g(t)+' is a not valid value for "'+e+'" attribute. The value should be a string or a native gradient.'),t}}function S(){if(r.isUnminified)return function(t,e){return!0===t||!1===t||f.warn(g(t)+' is a not valid value for "'+e+'" attribute. The value should be a boolean.'),t}}var w={addGetterSetter:function(t,e,i,n,r){w.addGetter(t,e,i),w.addSetter(t,e,n,r),w.addOverloadedGetterSetter(t,e)},addGetter:function(t,e,i){var n="get"+f._capitalize(e);t.prototype[n]=t.prototype[n]||function(){var t=this.attrs[e];return void 0===t?i:t}},addSetter:function(t,e,i,n){var r="set"+f._capitalize(e);t.prototype[r]||w.overWriteSetter(t,e,i,n)},overWriteSetter:function(t,e,i,n){var r="set"+f._capitalize(e);t.prototype[r]=function(t){return i&&null!=t&&(t=i.call(this,t,e)),this._setAttr(e,t),n&&n.call(this),this}},addComponentsGetterSetter:function(t,e,i,n,o){var a,s,h=i.length,l=f._capitalize,c="get"+l(e),d="set"+l(e);t.prototype[c]=function(){var t={};for(a=0;a=100&&e.shift()},t.prototype.reset=function(){var t=this.getCanvas().getPixelRatio();this.setTransform(1*t,0,0,1*t,0,0)},t.prototype.getCanvas=function(){return this.canvas},t.prototype.clear=function(t){var e=this.getCanvas();t?this.clearRect(t.x||0,t.y||0,t.width||0,t.height||0):this.clearRect(0,0,e.getWidth()/e.pixelRatio,e.getHeight()/e.pixelRatio)},t.prototype._applyLineCap=function(t){var e=t.getLineCap();e&&this.setAttr("lineCap",e)},t.prototype._applyOpacity=function(t){var e=t.getAbsoluteOpacity();1!==e&&this.setAttr("globalAlpha",e)},t.prototype._applyLineJoin=function(t){var e=t.attrs.lineJoin;e&&this.setAttr("lineJoin",e)},t.prototype.setAttr=function(t,e){this._context[t]=e},t.prototype.arc=function(t,e,i,n,r,o){this._context.arc(t,e,i,n,r,o)},t.prototype.arcTo=function(t,e,i,n,r){this._context.arcTo(t,e,i,n,r)},t.prototype.beginPath=function(){this._context.beginPath()},t.prototype.bezierCurveTo=function(t,e,i,n,r,o){this._context.bezierCurveTo(t,e,i,n,r,o)},t.prototype.clearRect=function(t,e,i,n){this._context.clearRect(t,e,i,n)},t.prototype.clip=function(){this._context.clip()},t.prototype.closePath=function(){this._context.closePath()},t.prototype.createImageData=function(t,e){var i=arguments;return 2===i.length?this._context.createImageData(t,e):1===i.length?this._context.createImageData(t):void 0},t.prototype.createLinearGradient=function(t,e,i,n){return this._context.createLinearGradient(t,e,i,n)},t.prototype.createPattern=function(t,e){return this._context.createPattern(t,e)},t.prototype.createRadialGradient=function(t,e,i,n,r,o){return this._context.createRadialGradient(t,e,i,n,r,o)},t.prototype.drawImage=function(t,e,i,n,r,o,a,s,h){var l=arguments,c=this._context;3===l.length?c.drawImage(t,e,i):5===l.length?c.drawImage(t,e,i,n,r):9===l.length&&c.drawImage(t,e,i,n,r,o,a,s,h)},t.prototype.ellipse=function(t,e,i,n,r,o,a,s){this._context.ellipse(t,e,i,n,r,o,a,s)},t.prototype.isPointInPath=function(t,e){return this._context.isPointInPath(t,e)},t.prototype.fill=function(){this._context.fill()},t.prototype.fillRect=function(t,e,i,n){this._context.fillRect(t,e,i,n)},t.prototype.strokeRect=function(t,e,i,n){this._context.strokeRect(t,e,i,n)},t.prototype.fillText=function(t,e,i){this._context.fillText(t,e,i)},t.prototype.measureText=function(t){return this._context.measureText(t)},t.prototype.getImageData=function(t,e,i,n){return this._context.getImageData(t,e,i,n)},t.prototype.lineTo=function(t,e){this._context.lineTo(t,e)},t.prototype.moveTo=function(t,e){this._context.moveTo(t,e)},t.prototype.rect=function(t,e,i,n){this._context.rect(t,e,i,n)},t.prototype.putImageData=function(t,e,i){this._context.putImageData(t,e,i)},t.prototype.quadraticCurveTo=function(t,e,i,n){this._context.quadraticCurveTo(t,e,i,n)},t.prototype.restore=function(){this._context.restore()},t.prototype.rotate=function(t){this._context.rotate(t)},t.prototype.save=function(){this._context.save()},t.prototype.scale=function(t,e){this._context.scale(t,e)},t.prototype.setLineDash=function(t){this._context.setLineDash?this._context.setLineDash(t):"mozDash"in this._context?this._context.mozDash=t:"webkitLineDash"in this._context&&(this._context.webkitLineDash=t)},t.prototype.getLineDash=function(){return this._context.getLineDash()},t.prototype.setTransform=function(t,e,i,n,r,o){this._context.setTransform(t,e,i,n,r,o)},t.prototype.stroke=function(){this._context.stroke()},t.prototype.strokeText=function(t,e,i,n){this._context.strokeText(t,e,i,n)},t.prototype.transform=function(t,e,i,n,r,o){this._context.transform(t,e,i,n,r,o)},t.prototype.translate=function(t,e){this._context.translate(t,e)},t.prototype._enableTrace=function(){var t,e,i=this,n=T.length,r=f._simplifyArray,o=this.setAttr,a=function(t){var n,o=i[t];i[t]=function(){return e=r(Array.prototype.slice.call(arguments,0)),n=o.apply(i,arguments),i._trace({method:t,args:e}),n}};for(t=0;t0&&t[0].getDepth()<=r&&s(t)}(o.getStage().getChildren()),a},t.prototype.getDepth=function(){for(var t=0,e=this.parent;e;)t++,e=e.parent;return t},t.prototype._batchTransformChanges=function(t){this._batchingTransformChange=!0,t(),this._batchingTransformChange=!1,this._needClearTransformCache&&(this._clearCache("transform"),this._clearSelfAndDescendantCache("absoluteTransform",!0)),this._needClearTransformCache=!1},t.prototype.setPosition=function(t){var e=this;return this._batchTransformChanges((function(){e.x(t.x),e.y(t.y)})),this},t.prototype.getPosition=function(){return{x:this.x(),y:this.y()}},t.prototype.getAbsolutePosition=function(t){for(var e=!1,i=this.parent;i;){if(i.isCached()){e=!0;break}i=i.parent}e&&!t&&(t=!0);var n=this.getAbsoluteTransform(t).getMatrix(),r=new h,o=this.offset();return r.m=n.slice(),r.translate(o.x,o.y),r.getTranslation()},t.prototype.setAbsolutePosition=function(t){var e=this._clearTransform();this.attrs.x=e.x,this.attrs.y=e.y,delete e.x,delete e.y,this._clearCache("transform");var i=this._getAbsoluteTransform().copy();return i.invert(),i.translate(t.x,t.y),t={x:this.attrs.x+i.getTranslation().x,y:this.attrs.y+i.getTranslation().y},this._setTransform(e),this.setPosition({x:t.x,y:t.y}),this._clearCache("transform"),this._clearSelfAndDescendantCache("absoluteTransform"),this},t.prototype._setTransform=function(t){var e;for(e in t)this.attrs[e]=t[e]},t.prototype._clearTransform=function(){var t={x:this.x(),y:this.y(),rotation:this.rotation(),scaleX:this.scaleX(),scaleY:this.scaleY(),offsetX:this.offsetX(),offsetY:this.offsetY(),skewX:this.skewX(),skewY:this.skewY()};return this.attrs.x=0,this.attrs.y=0,this.attrs.rotation=0,this.attrs.scaleX=1,this.attrs.scaleY=1,this.attrs.offsetX=0,this.attrs.offsetY=0,this.attrs.skewX=0,this.attrs.skewY=0,t},t.prototype.move=function(t){var e=t.x,i=t.y,n=this.x(),r=this.y();return void 0!==e&&(n+=e),void 0!==i&&(r+=i),this.setPosition({x:n,y:r}),this},t.prototype._eachAncestorReverse=function(t,e){var i,n,r=[],o=this.getParent();if(!e||e._id!==this._id){for(r.unshift(this);o&&(!e||o._id!==e._id);)r.unshift(o),o=o.parent;for(i=r.length,n=0;n0&&(this.parent.children.splice(t,1),this.parent.children.splice(t-1,0,this),this.parent._setChildrenIndices(),!0)},t.prototype.moveToBottom=function(){if(!this.parent)return f.warn("Node has no parent. moveToBottom function is ignored."),!1;var t=this.index;return t>0&&(this.parent.children.splice(t,1),this.parent.children.unshift(this),this.parent._setChildrenIndices(),!0)},t.prototype.setZIndex=function(t){if(!this.parent)return f.warn("Node has no parent. zIndex parameter is ignored."),this;(t<0||t>=this.parent.children.length)&&f.warn("Unexpected value "+t+" for zIndex property. zIndex is just index of a node in children of its parent. Expected value is from 0 to "+(this.parent.children.length-1)+".");var e=this.index;return this.parent.children.splice(e,1),this.parent.children.splice(t,0,this),this.parent._setChildrenIndices(),this},t.prototype.getAbsoluteOpacity=function(){return this._getCache("absoluteOpacity",this._getAbsoluteOpacity)},t.prototype._getAbsoluteOpacity=function(){var t=this.opacity(),e=this.getParent();return e&&!e._isUnderCache&&(t*=e.getAbsoluteOpacity()),t},t.prototype.moveTo=function(t){return this.getParent()!==t&&(this._remove(),t.add(this)),this},t.prototype.toObject=function(){var t,e,i,n,r={},o=this.getAttrs();for(t in r.attrs={},o)e=o[t],f.isObject(e)&&!f._isPlainObject(e)&&!f._isArray(e)||(i="function"==typeof this[t]&&this[t],delete o[t],n=i?i.call(this):null,o[t]=e,n!==e&&(r.attrs[t]=e));return r.className=this.getClassName(),f._prepareToStringify(r)},t.prototype.toJSON=function(){return JSON.stringify(this.toObject())},t.prototype.getParent=function(){return this.parent},t.prototype.findAncestors=function(t,e,i){var n=[];e&&this._isMatch(t)&&n.push(this);for(var r=this.parent;r;){if(r===i)return n;r._isMatch(t)&&n.push(r),r=r.parent}return n},t.prototype.isAncestorOf=function(t){return!1},t.prototype.findAncestor=function(t,e,i){return this.findAncestors(t,e,i)[0]},t.prototype._isMatch=function(t){if(!t)return!1;if("function"==typeof t)return t(this);var e,i,n=t.replace(/ /g,"").split(","),r=n.length;for(e=0;e=0)&&!this.isDragging()){var i=!1;D._dragElements.forEach((function(t){e.isAncestorOf(t.node)&&(i=!0)})),i||this._createDragElement(t)}}))},t.prototype._dragChange=function(){if(this.attrs.draggable)this._listenDrag();else{if(this._dragCleanup(),!this.getStage())return;var t=D._dragElements.get(this._id),e=t&&"dragging"===t.dragStatus,i=t&&"ready"===t.dragStatus;e?this.stopDrag():i&&D._dragElements.delete(this._id)}},t.prototype._dragCleanup=function(){this.off("mousedown.konva"),this.off("touchstart.konva")},t.create=function(t,e){return f._isString(t)&&(t=JSON.parse(t)),this._createNode(t,e)},t._createNode=function(e,i){var n,r,a,s=t.prototype.getClassName.call(e),h=e.children;if(i&&(e.attrs.container=i),o[s]||(f.warn('Can not find a node with class name "'+s+'". Fallback to "Shape".'),s="Shape"),n=new(0,o[s])(e.attrs),h)for(r=h.length,a=0;a0},e.prototype.removeChildren=function(){for(var t,e=0;e1){for(var i=0;i0?e[0]:void 0},e.prototype._generalFind=function(t,e){var i=[];return this._descendants((function(n){var r=n._isMatch(t);return r&&i.push(n),!(!r||!e)})),s.toCollection(i)},e.prototype._descendants=function(t){for(var e=0;e-1&&nt.splice(i,1),this},e.prototype.getPointerPosition=function(){var t=this._pointerPositions[0]||this._changedPointerPositions[0];return t?{x:t.x,y:t.y}:(f.warn("Pointer position is missing and not registered by the stage. Looks like it is outside of the stage container. You can set it manually from event: stage.setPointersPositions(event);"),null)},e.prototype._getPointerById=function(t){return this._pointerPositions.find((function(e){return e.id===t}))},e.prototype.getPointersPositions=function(){return this._pointerPositions},e.prototype.getStage=function(){return this},e.prototype.getContent=function(){return this.content},e.prototype._toKonvaCanvas=function(t){(t=t||{}).x=t.x||0,t.y=t.y||0,t.width=t.width||this.width(),t.height=t.height||this.height();var e=new E({width:t.width,height:t.height,pixelRatio:t.pixelRatio||1}),i=e.getContext()._context,n=this.children;return(t.x||t.y)&&i.translate(-1*t.x,-1*t.y),n.each((function(e){if(e.isVisible()){var n=e._toKonvaCanvas(t);i.drawImage(n._canvas,t.x,t.y,n.getWidth()/n.getPixelRatio(),n.getHeight()/n.getPixelRatio())}})),e},e.prototype.getIntersection=function(t,e){if(!t)return null;var i,n,r=this.children;for(i=r.length-1;i>=0;i--)if(n=r[i].getIntersection(t,e))return n;return null},e.prototype._resizeDOM=function(){var t=this.width(),e=this.height();this.content&&(this.content.style.width=t+"px",this.content.style.height=e+"px"),this.bufferCanvas.setSize(t,e),this.bufferHitCanvas.setSize(t,e),this.children.each((function(i){i.setSize({width:t,height:e}),i.draw()}))},e.prototype.add=function(e){if(arguments.length>1){for(var i=0;i5&&f.warn("The stage has "+n+" layers. Recommended maximum number of layers is 3-5. Adding more layers into the stage may drop the performance. Rethink your tree structure, you can use Konva.Group."),e.setSize({width:this.width(),height:this.height()}),e.draw(),r.isBrowser&&this.content.appendChild(e.canvas._canvas),this},e.prototype.getParent=function(){return null},e.prototype.getLayer=function(){return null},e.prototype.hasPointerCapture=function(t){return J(t,this)},e.prototype.setPointerCapture=function(t){Z(t,this)},e.prototype.releaseCapture=function(t){$(t)},e.prototype.getLayers=function(){return this.getChildren()},e.prototype._bindContentEvents=function(){if(r.isBrowser)for(var t=0;t0},e.prototype.destroy=function(){return X.prototype.destroy.call(this),delete ht[this.colorKey],delete this.colorKey,this},e.prototype._useBufferCanvas=function(t){var e;if(!this.getStage())return!1;if(!(null===(e=this.attrs.perfectDrawEnabled)||void 0===e||e))return!1;var i=t||this.hasFill(),n=this.hasStroke(),r=1!==this.getAbsoluteOpacity();if(i&&n&&r)return!0;var o=this.hasShadow(),a=this.shadowForStrokeEnabled();return!!(i&&n&&o&&a)},e.prototype.setStrokeHitEnabled=function(t){f.warn("strokeHitEnabled property is deprecated. Please use hitStrokeWidth instead."),t?this.hitStrokeWidth("auto"):this.hitStrokeWidth(0)},e.prototype.getStrokeHitEnabled=function(){return 0!==this.hitStrokeWidth()},e.prototype.getSelfRect=function(){var t=this.size();return{x:this._centroid?-t.width/2:0,y:this._centroid?-t.height/2:0,width:t.width,height:t.height}},e.prototype.getClientRect=function(t){void 0===t&&(t={});var e=t.skipTransform,i=t.relativeTo,n=this.getSelfRect(),r=!t.skipStroke&&this.hasStroke()&&this.strokeWidth()||0,o=n.width+r,a=n.height+r,s=!t.skipShadow&&this.hasShadow(),h=s?this.shadowOffsetX():0,l=s?this.shadowOffsetY():0,c=o+Math.abs(h),d=a+Math.abs(l),u=s&&this.shadowBlur()||0,p=c+2*u,f=d+2*u,g=0;Math.round(r/2)!==r/2&&(g=1);var v={width:p+g,height:f+g,x:-Math.round(r/2+u)+Math.min(h,0)+n.x,y:-Math.round(r/2+u)+Math.min(l,0)+n.y};return e?v:this._transformedRect(v,i)},e.prototype.drawScene=function(t,e){var i,n,r=this.getLayer(),o=t||r.getCanvas(),a=o.getContext(),s=this._getCanvasCache(),h=this.getSceneFunc(),l=this.hasShadow(),c=o.isCache,d=o.isCache,u=e===this;if(!this.isVisible()&&!c)return this;if(s){a.save();var p=this.getAbsoluteTransform(e).getMatrix();return a.transform(p[0],p[1],p[2],p[3],p[4],p[5]),this._drawCachedSceneCanvas(a),a.restore(),this}if(!h)return this;if(a.save(),this._useBufferCanvas()&&!d){(n=(i=this.getStage().bufferCanvas).getContext()).clear(),n.save(),n._applyLineJoin(this);var f=this.getAbsoluteTransform(e).getMatrix();n.transform(f[0],f[1],f[2],f[3],f[4],f[5]),h.call(this,n,this),n.restore();var g=i.pixelRatio;l&&a._applyShadow(this),a._applyOpacity(this),a._applyGlobalCompositeOperation(this),a.drawImage(i._canvas,0,0,i.width/g,i.height/g)}else{if(a._applyLineJoin(this),!u){f=this.getAbsoluteTransform(e).getMatrix();a.transform(f[0],f[1],f[2],f[3],f[4],f[5]),a._applyOpacity(this),a._applyGlobalCompositeOperation(this)}l&&a._applyShadow(this),h.call(this,a,this)}return a.restore(),this},e.prototype.drawHit=function(t,e,i){if(void 0===i&&(i=!1),!this.shouldDrawHit(e,i))return this;var n=this.getLayer(),r=t||n.hitCanvas,o=r&&r.getContext(),a=this.hitFunc()||this.sceneFunc(),s=this._getCanvasCache(),h=s&&s.hit;if(this.colorKey||(console.log(this),f.warn("Looks like your canvas has a destroyed shape in it. Do not reuse shape after you destroyed it. See the shape in logs above. If you want to reuse shape you should call remove() instead of destroy()")),h){o.save();var l=this.getAbsoluteTransform(e).getMatrix();return o.transform(l[0],l[1],l[2],l[3],l[4],l[5]),this._drawCachedHitCanvas(o),o.restore(),this}if(!a)return this;if(o.save(),o._applyLineJoin(this),!(this===e)){var c=this.getAbsoluteTransform(e).getMatrix();o.transform(c[0],c[1],c[2],c[3],c[4],c[5])}return a.call(this,o,this),o.restore(),this},e.prototype.drawHitFromCache=function(t){void 0===t&&(t=0);var e,i,n,r,o,a=this._getCanvasCache(),s=this._getCachedSceneCanvas(),h=a.hit,l=h.getContext(),c=h.getWidth(),d=h.getHeight();l.clear(),l.drawImage(s._canvas,0,0,c,d);try{for(n=(i=(e=l.getImageData(0,0,c,d)).data).length,r=f._hexToRgb(this.colorKey),o=0;ot?(i[o]=r.r,i[o+1]=r.g,i[o+2]=r.b,i[o+3]=255):i[o+3]=0;l.putImageData(e,0,0)}catch(t){f.error("Unable to draw hit graph from cached scene canvas. "+t.message)}return this},e.prototype.hasPointerCapture=function(t){return J(t,this)},e.prototype.setPointerCapture=function(t){Z(t,this)},e.prototype.releaseCapture=function(t){$(t)},e}(X);lt.prototype._fillFunc=function(t){t.fill()},lt.prototype._strokeFunc=function(t){t.stroke()},lt.prototype._fillFuncHit=function(t){t.fill()},lt.prototype._strokeFuncHit=function(t){t.stroke()},lt.prototype._centroid=!1,lt.prototype.nodeType="Shape",a(lt),lt.prototype.eventListeners={},lt.prototype.on.call(lt.prototype,"shadowColorChange.konva shadowBlurChange.konva shadowOffsetChange.konva shadowOpacityChange.konva shadowEnabledChange.konva",(function(){this._clearCache("hasShadow")})),lt.prototype.on.call(lt.prototype,"shadowColorChange.konva shadowOpacityChange.konva shadowEnabledChange.konva",(function(){this._clearCache("shadowRGBA")})),lt.prototype.on.call(lt.prototype,"fillPriorityChange.konva fillPatternImageChange.konva fillPatternRepeatChange.konva fillPatternScaleXChange.konva fillPatternScaleYChange.konva",(function(){this._clearCache("patternImage")})),lt.prototype.on.call(lt.prototype,"fillPriorityChange.konva fillLinearGradientColorStopsChange.konva fillLinearGradientStartPointXChange.konva fillLinearGradientStartPointYChange.konva fillLinearGradientEndPointXChange.konva fillLinearGradientEndPointYChange.konva",(function(){this._clearCache("linearGradient")})),lt.prototype.on.call(lt.prototype,"fillPriorityChange.konva fillRadialGradientColorStopsChange.konva fillRadialGradientStartPointXChange.konva fillRadialGradientStartPointYChange.konva fillRadialGradientEndPointXChange.konva fillRadialGradientEndPointYChange.konva fillRadialGradientStartRadiusChange.konva fillRadialGradientEndRadiusChange.konva",(function(){this._clearCache("radialGradient")})),w.addGetterSetter(lt,"stroke",void 0,x()),w.addGetterSetter(lt,"strokeWidth",2,y()),w.addGetterSetter(lt,"fillAfterStrokeEnabled",!1),w.addGetterSetter(lt,"hitStrokeWidth","auto",_()),w.addGetterSetter(lt,"strokeHitEnabled",!0,S()),w.addGetterSetter(lt,"perfectDrawEnabled",!0,S()),w.addGetterSetter(lt,"shadowForStrokeEnabled",!0,S()),w.addGetterSetter(lt,"lineJoin"),w.addGetterSetter(lt,"lineCap"),w.addGetterSetter(lt,"sceneFunc"),w.addGetterSetter(lt,"hitFunc"),w.addGetterSetter(lt,"dash"),w.addGetterSetter(lt,"dashOffset",0,y()),w.addGetterSetter(lt,"shadowColor",void 0,b()),w.addGetterSetter(lt,"shadowBlur",0,y()),w.addGetterSetter(lt,"shadowOpacity",1,y()),w.addComponentsGetterSetter(lt,"shadowOffset",["x","y"]),w.addGetterSetter(lt,"shadowOffsetX",0,y()),w.addGetterSetter(lt,"shadowOffsetY",0,y()),w.addGetterSetter(lt,"fillPatternImage"),w.addGetterSetter(lt,"fill",void 0,x()),w.addGetterSetter(lt,"fillPatternX",0,y()),w.addGetterSetter(lt,"fillPatternY",0,y()),w.addGetterSetter(lt,"fillLinearGradientColorStops"),w.addGetterSetter(lt,"strokeLinearGradientColorStops"),w.addGetterSetter(lt,"fillRadialGradientStartRadius",0),w.addGetterSetter(lt,"fillRadialGradientEndRadius",0),w.addGetterSetter(lt,"fillRadialGradientColorStops"),w.addGetterSetter(lt,"fillPatternRepeat","repeat"),w.addGetterSetter(lt,"fillEnabled",!0),w.addGetterSetter(lt,"strokeEnabled",!0),w.addGetterSetter(lt,"shadowEnabled",!0),w.addGetterSetter(lt,"dashEnabled",!0),w.addGetterSetter(lt,"strokeScaleEnabled",!0),w.addGetterSetter(lt,"fillPriority","color"),w.addComponentsGetterSetter(lt,"fillPatternOffset",["x","y"]),w.addGetterSetter(lt,"fillPatternOffsetX",0,y()),w.addGetterSetter(lt,"fillPatternOffsetY",0,y()),w.addComponentsGetterSetter(lt,"fillPatternScale",["x","y"]),w.addGetterSetter(lt,"fillPatternScaleX",1,y()),w.addGetterSetter(lt,"fillPatternScaleY",1,y()),w.addComponentsGetterSetter(lt,"fillLinearGradientStartPoint",["x","y"]),w.addComponentsGetterSetter(lt,"strokeLinearGradientStartPoint",["x","y"]),w.addGetterSetter(lt,"fillLinearGradientStartPointX",0),w.addGetterSetter(lt,"strokeLinearGradientStartPointX",0),w.addGetterSetter(lt,"fillLinearGradientStartPointY",0),w.addGetterSetter(lt,"strokeLinearGradientStartPointY",0),w.addComponentsGetterSetter(lt,"fillLinearGradientEndPoint",["x","y"]),w.addComponentsGetterSetter(lt,"strokeLinearGradientEndPoint",["x","y"]),w.addGetterSetter(lt,"fillLinearGradientEndPointX",0),w.addGetterSetter(lt,"strokeLinearGradientEndPointX",0),w.addGetterSetter(lt,"fillLinearGradientEndPointY",0),w.addGetterSetter(lt,"strokeLinearGradientEndPointY",0),w.addComponentsGetterSetter(lt,"fillRadialGradientStartPoint",["x","y"]),w.addGetterSetter(lt,"fillRadialGradientStartPointX",0),w.addGetterSetter(lt,"fillRadialGradientStartPointY",0),w.addComponentsGetterSetter(lt,"fillRadialGradientEndPoint",["x","y"]),w.addGetterSetter(lt,"fillRadialGradientEndPointX",0),w.addGetterSetter(lt,"fillRadialGradientEndPointY",0),w.addGetterSetter(lt,"fillPatternRotation",0),w.backCompat(lt,{dashArray:"dash",getDashArray:"getDash",setDashArray:"getDash",drawFunc:"sceneFunc",getDrawFunc:"getSceneFunc",setDrawFunc:"setSceneFunc",drawHitFunc:"hitFunc",getDrawHitFunc:"getHitFunc",setDrawHitFunc:"setHitFunc"}),s.mapMethods(lt);var ct=[{x:0,y:0},{x:-1,y:-1},{x:1,y:-1},{x:1,y:1},{x:-1,y:1}],dt=ct.length,ut=function(t){function e(e){var i=t.call(this,e)||this;return i.canvas=new E,i.hitCanvas=new O({pixelRatio:1}),i._waitingForDraw=!1,i.on("visibleChange.konva",i._checkVisibility),i._checkVisibility(),i.on("imageSmoothingEnabledChange.konva",i._setSmoothEnabled),i._setSmoothEnabled(),i}return P(e,t),e.prototype.createPNGStream=function(){return this.canvas._canvas.createPNGStream()},e.prototype.getCanvas=function(){return this.canvas},e.prototype.getHitCanvas=function(){return this.hitCanvas},e.prototype.getContext=function(){return this.getCanvas().getContext()},e.prototype.clear=function(t){return this.getContext().clear(t),this.getHitCanvas().getContext().clear(t),this},e.prototype.setZIndex=function(e){t.prototype.setZIndex.call(this,e);var i=this.getStage();return i&&(i.content.removeChild(this.getCanvas()._canvas),e0?{antialiased:!0}:{}},e.prototype.drawScene=function(t,e){var i=this.getLayer(),n=t||i&&i.getCanvas();return this._fire("beforeDraw",{node:this}),this.clearBeforeDraw()&&n.getContext().clear(),U.prototype.drawScene.call(this,n,e),this._fire("draw",{node:this}),this},e.prototype.drawHit=function(t,e){var i=this.getLayer(),n=t||i&&i.hitCanvas;return i&&i.clearBeforeDraw()&&i.getHitCanvas().getContext().clear(),U.prototype.drawHit.call(this,n,e),this},e.prototype.enableHitGraph=function(){return this.hitGraphEnabled(!0),this},e.prototype.disableHitGraph=function(){return this.hitGraphEnabled(!1),this},e.prototype.setHitGraphEnabled=function(t){f.warn("hitGraphEnabled method is deprecated. Please use layer.listening() instead."),this.listening(t)},e.prototype.getHitGraphEnabled=function(t){return f.warn("hitGraphEnabled method is deprecated. Please use layer.listening() instead."),this.listening()},e.prototype.toggleHitCanvas=function(){if(this.parent){var t=this.parent;!!this.hitCanvas._canvas.parentNode?t.content.removeChild(this.hitCanvas._canvas):t.content.appendChild(this.hitCanvas._canvas)}},e}(U);ut.prototype.nodeType="Layer",a(ut),w.addGetterSetter(ut,"imageSmoothingEnabled",!0),w.addGetterSetter(ut,"clearBeforeDraw",!0),w.addGetterSetter(ut,"hitGraphEnabled",!0,S()),s.mapMethods(ut);var pt=function(t){function e(e){var i=t.call(this,e)||this;return i.listening(!1),f.warn('Konva.Fast layer is deprecated. Please use "new Konva.Layer({ listening: false })" instead.'),i}return P(e,t),e}(ut);pt.prototype.nodeType="FastLayer",a(pt),s.mapMethods(pt);var ft=function(t){function e(){return null!==t&&t.apply(this,arguments)||this}return P(e,t),e.prototype._validateAdd=function(t){var e=t.getType();"Group"!==e&&"Shape"!==e&&f.throw("You may only add groups and shapes to groups.")},e}(U);ft.prototype.nodeType="Group",a(ft),s.mapMethods(ft);var gt=n.performance&&n.performance.now?function(){return n.performance.now()}:function(){return(new Date).getTime()},vt=function(){function t(e,i){this.id=t.animIdCounter++,this.frame={time:0,timeDiff:0,lastTime:gt(),frameRate:0},this.func=e,this.setLayers(i)}return t.prototype.setLayers=function(t){var e=[];return e=t?t.length>0?t:[t]:[],this.layers=e,this},t.prototype.getLayers=function(){return this.layers},t.prototype.addLayer=function(t){var e,i=this.layers,n=i.length;for(e=0;ethis.duration?this.yoyo?(this._time=this.duration,this.reverse()):this.finish():t<0?this.yoyo?(this._time=0,this.play()):this.reset():(this._time=t,this.update())},t.prototype.getTime=function(){return this._time},t.prototype.setPosition=function(t){this.prevPos=this._pos,this.propFunc(t),this._pos=t},t.prototype.getPosition=function(t){return void 0===t&&(t=this._time),this.func(t,this.begin,this._change,this.duration)},t.prototype.play=function(){this.state=2,this._startTime=this.getTimer()-this._time,this.onEnterFrame(),this.fire("onPlay")},t.prototype.reverse=function(){this.state=3,this._time=this.duration-this._time,this._startTime=this.getTimer()-this._time,this.onEnterFrame(),this.fire("onReverse")},t.prototype.seek=function(t){this.pause(),this._time=t,this.update(),this.fire("onSeek")},t.prototype.reset=function(){this.pause(),this._time=0,this.update(),this.fire("onReset")},t.prototype.finish=function(){this.pause(),this._time=this.duration,this.update(),this.fire("onFinish")},t.prototype.update=function(){this.setPosition(this.getPosition(this._time)),this.fire("onUpdate")},t.prototype.onEnterFrame=function(){var t=this.getTimer()-this._startTime;2===this.state?this.setTime(t):3===this.state&&this.setTime(this.duration-t)},t.prototype.pause=function(){this.state=1,this.fire("onPause")},t.prototype.getTimer=function(){return(new Date).getTime()},t}(),xt=function(){function t(e){var i,n,o=this,a=e.node,s=a._id,h=e.easing||St.Linear,l=!!e.yoyo;i=void 0===e.duration?.3:0===e.duration?.001:e.duration,this.node=a,this._id=mt++;var c=a.getLayer()||(a instanceof r.Stage?a.getLayers():null);for(n in c||f.error("Tween constructor have `node` that is not in a layer. Please add node into layer first."),this.anim=new vt((function(){o.tween.onEnterFrame()}),c),this.tween=new bt(n,(function(t){o._tweenFunc(t)}),h,0,1,1e3*i,l),this._addListeners(),t.attrs[s]||(t.attrs[s]={}),t.attrs[s][this._id]||(t.attrs[s][this._id]={}),t.tweens[s]||(t.tweens[s]={}),e)void 0===yt[n]&&this._addAttr(n,e[n]);this.reset(),this.onFinish=e.onFinish,this.onReset=e.onReset,this.onUpdate=e.onUpdate}return t.prototype._addAttr=function(e,i){var n,r,o,a,s,h,l,c,d=this.node,u=d._id;if((o=t.tweens[u][e])&&delete t.attrs[u][o][e],n=d.getAttr(e),f._isArray(i))if(r=[],s=Math.max(i.length,n.length),"points"===e&&i.length!==n.length&&(i.length>n.length?(l=n,n=f._prepareArrayForTween(n,i,d.closed())):(h=i,i=f._prepareArrayForTween(i,n,d.closed()))),0===e.indexOf("fill"))for(a=0;a4){for(i=(e=this.getTensionPoints()).length,n=s?0:4,s||t.quadraticCurveTo(e[0],e[1],e[2],e[3]);n4;o&&(r=this.getTensionPoints());var a,s,h=n.length;o?(a=n[h-2]-(r[r.length-2]+r[r.length-4])/2,s=n[h-1]-(r[r.length-1]+r[r.length-3])/2):(a=n[h-2]-n[h-4],s=n[h-1]-n[h-3]);var l=(Math.atan2(s,a)+i)%i,c=this.pointerLength(),d=this.pointerWidth();e.save(),e.beginPath(),e.translate(n[h-2],n[h-1]),e.rotate(l),e.moveTo(0,0),e.lineTo(-c,d/2),e.lineTo(-c,-d/2),e.closePath(),e.restore(),this.pointerAtBeginning()&&(e.save(),e.translate(n[0],n[1]),o?(a=(r[0]+r[2])/2-n[0],s=(r[1]+r[3])/2-n[1]):(a=n[2]-n[0],s=n[3]-n[1]),e.rotate((Math.atan2(-s,-a)+i)%i),e.moveTo(0,0),e.lineTo(-c,d/2),e.lineTo(-c,-d/2),e.closePath(),e.restore());var u=this.dashEnabled();u&&(this.attrs.dashEnabled=!1,e.setLineDash([])),e.fillStrokeShape(this),u&&(this.attrs.dashEnabled=!0)},e.prototype.getSelfRect=function(){var e=t.prototype.getSelfRect.call(this),i=this.pointerWidth()/2;return{x:e.x-i,y:e.y-i,width:e.width+2*i,height:e.height+2*i}},e}(Pt);kt.prototype.className="Arrow",a(kt),w.addGetterSetter(kt,"pointerLength",10,y()),w.addGetterSetter(kt,"pointerWidth",10,y()),w.addGetterSetter(kt,"pointerAtBeginning",!1),s.mapMethods(kt);var Tt=function(t){function e(){return null!==t&&t.apply(this,arguments)||this}return P(e,t),e.prototype._sceneFunc=function(t){t.beginPath(),t.arc(0,0,this.attrs.radius||0,0,2*Math.PI,!1),t.closePath(),t.fillStrokeShape(this)},e.prototype.getWidth=function(){return 2*this.radius()},e.prototype.getHeight=function(){return 2*this.radius()},e.prototype.setWidth=function(t){this.radius()!==t/2&&this.radius(t/2)},e.prototype.setHeight=function(t){this.radius()!==t/2&&this.radius(t/2)},e}(lt);Tt.prototype._centroid=!0,Tt.prototype.className="Circle",Tt.prototype._attrsAffectingSize=["radius"],a(Tt),w.addGetterSetter(Tt,"radius",0,y()),s.mapMethods(Tt);var At=function(t){function e(){return null!==t&&t.apply(this,arguments)||this}return P(e,t),e.prototype._sceneFunc=function(t){var e=this.radiusX(),i=this.radiusY();t.beginPath(),t.save(),e!==i&&t.scale(1,i/e),t.arc(0,0,e,0,2*Math.PI,!1),t.restore(),t.closePath(),t.fillStrokeShape(this)},e.prototype.getWidth=function(){return 2*this.radiusX()},e.prototype.getHeight=function(){return 2*this.radiusY()},e.prototype.setWidth=function(t){this.radiusX(t/2)},e.prototype.setHeight=function(t){this.radiusY(t/2)},e}(lt);At.prototype.className="Ellipse",At.prototype._centroid=!0,At.prototype._attrsAffectingSize=["radiusX","radiusY"],a(At),w.addComponentsGetterSetter(At,"radius",["x","y"]),w.addGetterSetter(At,"radiusX",0,y()),w.addGetterSetter(At,"radiusY",0,y()),s.mapMethods(At);var Mt=function(t){function e(){return null!==t&&t.apply(this,arguments)||this}return P(e,t),e.prototype._useBufferCanvas=function(){return t.prototype._useBufferCanvas.call(this,!0)},e.prototype._sceneFunc=function(t){var e,i=this.getWidth(),n=this.getHeight(),r=this.attrs.image;if(r){var o=this.attrs.cropWidth,a=this.attrs.cropHeight;e=o&&a?[r,this.cropX(),this.cropY(),o,a,0,0,i,n]:[r,0,0,i,n]}(this.hasFill()||this.hasStroke())&&(t.beginPath(),t.rect(0,0,i,n),t.closePath(),t.fillStrokeShape(this)),r&&t.drawImage.apply(t,e)},e.prototype._hitFunc=function(t){var e=this.width(),i=this.height();t.beginPath(),t.rect(0,0,e,i),t.closePath(),t.fillStrokeShape(this)},e.prototype.getWidth=function(){var t,e;return null!==(t=this.attrs.width)&&void 0!==t?t:(null===(e=this.image())||void 0===e?void 0:e.width)||0},e.prototype.getHeight=function(){var t,e;return null!==(t=this.attrs.height)&&void 0!==t?t:(null===(e=this.image())||void 0===e?void 0:e.height)||0},e.fromURL=function(t,i){var n=f.createImageElement();n.onload=function(){var t=new e({image:n});i(t)},n.crossOrigin="Anonymous",n.src=t},e}(lt);Mt.prototype.className="Image",a(Mt),w.addGetterSetter(Mt,"image"),w.addComponentsGetterSetter(Mt,"crop",["x","y","width","height"]),w.addGetterSetter(Mt,"cropX",0,y()),w.addGetterSetter(Mt,"cropY",0,y()),w.addGetterSetter(Mt,"cropWidth",0,y()),w.addGetterSetter(Mt,"cropHeight",0,y()),s.mapMethods(Mt);var Gt=["fontFamily","fontSize","fontStyle","padding","lineHeight","text","width","height"],Rt=Gt.length,Lt=function(t){function e(e){var i=t.call(this,e)||this;return i.on("add.konva",(function(t){this._addListeners(t.child),this._sync()})),i}return P(e,t),e.prototype.getText=function(){return this.find("Text")[0]},e.prototype.getTag=function(){return this.find("Tag")[0]},e.prototype._addListeners=function(t){var e,i=this,n=function(){i._sync()};for(e=0;el?h:l,g=h>l?1:h/l,v=h>l?l/h:1;t.translate(a,s),t.rotate(u),t.scale(g,v),t.arc(0,0,f,c,c+d,1-p),t.scale(1/g,1/v),t.rotate(-u),t.translate(-a,-s);break;case"z":i=!0,t.closePath()}}i||this.hasFill()?t.fillStrokeShape(this):t.strokeShape(this)},e.prototype.getSelfRect=function(){var t=[];this.dataArray.forEach((function(i){if("A"===i.command){var n=i.points[4],r=i.points[5],o=i.points[4]+r,a=Math.PI/180;if(Math.abs(n-o)o;s-=a){var h=e.getPointOnEllipticalArc(i.points[0],i.points[1],i.points[2],i.points[3],s,0);t.push(h.x,h.y)}else for(s=n+a;sthis.dataArray[n].pathLength;)t-=this.dataArray[n].pathLength,++n;if(n===r)return{x:(i=this.dataArray[n-1].points.slice(-2))[0],y:i[1]};if(t<.01)return{x:(i=this.dataArray[n].points.slice(0,2))[0],y:i[1]};var o=this.dataArray[n],a=o.points;switch(o.command){case"L":return e.getPointOnLine(t,o.start.x,o.start.y,a[0],a[1]);case"C":return e.getPointOnCubicBezier(t/o.pathLength,o.start.x,o.start.y,a[0],a[1],a[2],a[3],a[4],a[5]);case"Q":return e.getPointOnQuadraticBezier(t/o.pathLength,o.start.x,o.start.y,a[0],a[1],a[2],a[3]);case"A":var s=a[0],h=a[1],l=a[2],c=a[3],d=a[4],u=a[5],p=a[6];return d+=u*t/o.pathLength,e.getPointOnEllipticalArc(s,h,l,c,d,p)}return null},e.getLineLength=function(t,e,i,n){return Math.sqrt((i-t)*(i-t)+(n-e)*(n-e))},e.getPointOnLine=function(t,e,i,n,r,o,a){void 0===o&&(o=e),void 0===a&&(a=i);var s=(r-i)/(n-e+1e-8),h=Math.sqrt(t*t/(1+s*s));n0&&!isNaN(p[0]);){var y,m,_,b,x,S,w,C,P,k,T=null,A=[],M=h,G=l;switch(u){case"l":h+=p.shift(),l+=p.shift(),T="L",A.push(h,l);break;case"L":h=p.shift(),l=p.shift(),A.push(h,l);break;case"m":var R=p.shift(),L=p.shift();if(h+=R,l+=L,T="M",a.length>2&&"z"===a[a.length-1].command)for(var E=a.length-2;E>=0;E--)if("M"===a[E].command){h=a[E].points[0]+R,l=a[E].points[1]+L;break}A.push(h,l),u="l";break;case"M":h=p.shift(),l=p.shift(),T="M",A.push(h,l),u="L";break;case"h":h+=p.shift(),T="L",A.push(h,l);break;case"H":h=p.shift(),T="L",A.push(h,l);break;case"v":l+=p.shift(),T="L",A.push(h,l);break;case"V":l=p.shift(),T="L",A.push(h,l);break;case"C":A.push(p.shift(),p.shift(),p.shift(),p.shift()),h=p.shift(),l=p.shift(),A.push(h,l);break;case"c":A.push(h+p.shift(),l+p.shift(),h+p.shift(),l+p.shift()),h+=p.shift(),l+=p.shift(),T="C",A.push(h,l);break;case"S":m=h,_=l,"C"===(y=a[a.length-1]).command&&(m=h+(h-y.points[2]),_=l+(l-y.points[3])),A.push(m,_,p.shift(),p.shift()),h=p.shift(),l=p.shift(),T="C",A.push(h,l);break;case"s":m=h,_=l,"C"===(y=a[a.length-1]).command&&(m=h+(h-y.points[2]),_=l+(l-y.points[3])),A.push(m,_,h+p.shift(),l+p.shift()),h+=p.shift(),l+=p.shift(),T="C",A.push(h,l);break;case"Q":A.push(p.shift(),p.shift()),h=p.shift(),l=p.shift(),A.push(h,l);break;case"q":A.push(h+p.shift(),l+p.shift()),h+=p.shift(),l+=p.shift(),T="Q",A.push(h,l);break;case"T":m=h,_=l,"Q"===(y=a[a.length-1]).command&&(m=h+(h-y.points[0]),_=l+(l-y.points[1])),h=p.shift(),l=p.shift(),T="Q",A.push(m,_,h,l);break;case"t":m=h,_=l,"Q"===(y=a[a.length-1]).command&&(m=h+(h-y.points[0]),_=l+(l-y.points[1])),h+=p.shift(),l+=p.shift(),T="Q",A.push(m,_,h,l);break;case"A":b=p.shift(),x=p.shift(),S=p.shift(),w=p.shift(),C=p.shift(),P=h,k=l,h=p.shift(),l=p.shift(),T="A",A=this.convertEndpointToCenterParameterization(P,k,h,l,w,C,b,x,S);break;case"a":b=p.shift(),x=p.shift(),S=p.shift(),w=p.shift(),C=p.shift(),P=h,k=l,h+=p.shift(),l+=p.shift(),T="A",A=this.convertEndpointToCenterParameterization(P,k,h,l,w,C,b,x,S)}a.push({command:T||u,points:A,start:{x:M,y:G},pathLength:this.calcLength(M,G,T||u,A)})}"z"!==u&&"Z"!==u||a.push({command:"z",points:[],start:void 0,pathLength:0})}return a},e.calcLength=function(t,i,n,r){var o,a,s,h,l=e;switch(n){case"L":return l.getLineLength(t,i,r[0],r[1]);case"C":for(o=0,a=l.getPointOnCubicBezier(0,t,i,r[0],r[1],r[2],r[3],r[4],r[5]),h=.01;h<=1;h+=.01)s=l.getPointOnCubicBezier(h,t,i,r[0],r[1],r[2],r[3],r[4],r[5]),o+=l.getLineLength(a.x,a.y,s.x,s.y),a=s;return o;case"Q":for(o=0,a=l.getPointOnQuadraticBezier(0,t,i,r[0],r[1],r[2],r[3]),h=.01;h<=1;h+=.01)s=l.getPointOnQuadraticBezier(h,t,i,r[0],r[1],r[2],r[3]),o+=l.getLineLength(a.x,a.y,s.x,s.y),a=s;return o;case"A":o=0;var c=r[4],d=r[5],u=r[4]+d,p=Math.PI/180;if(Math.abs(c-u)u;h-=p)s=l.getPointOnEllipticalArc(r[0],r[1],r[2],r[3],h,0),o+=l.getLineLength(a.x,a.y,s.x,s.y),a=s;else for(h=c+p;h1&&(a*=Math.sqrt(u),s*=Math.sqrt(u));var p=Math.sqrt((a*a*(s*s)-a*a*(d*d)-s*s*(c*c))/(a*a*(d*d)+s*s*(c*c)));r===o&&(p*=-1),isNaN(p)&&(p=0);var f=p*a*d/s,g=p*-s*c/a,v=(t+i)/2+Math.cos(l)*f-Math.sin(l)*g,y=(e+n)/2+Math.sin(l)*f+Math.cos(l)*g,m=function(t){return Math.sqrt(t[0]*t[0]+t[1]*t[1])},_=function(t,e){return(t[0]*e[0]+t[1]*e[1])/(m(t)*m(e))},b=function(t,e){return(t[0]*e[1]=1&&(C=0),0===o&&C>0&&(C-=2*Math.PI),1===o&&C<0&&(C+=2*Math.PI),[v,y,a,s,x,C,l,o]},e}(lt);Ot.prototype.className="Path",Ot.prototype._attrsAffectingSize=["data"],a(Ot),w.addGetterSetter(Ot,"data"),s.mapMethods(Ot);var Dt=function(t){function e(){return null!==t&&t.apply(this,arguments)||this}return P(e,t),e.prototype._sceneFunc=function(t){var e=this.cornerRadius(),i=this.width(),n=this.height();if(t.beginPath(),e){var r=0,o=0,a=0,s=0;"number"==typeof e?r=o=a=s=Math.min(e,i/2,n/2):(r=Math.min(e[0]||0,i/2,n/2),o=Math.min(e[1]||0,i/2,n/2),s=Math.min(e[2]||0,i/2,n/2),a=Math.min(e[3]||0,i/2,n/2)),t.moveTo(r,0),t.lineTo(i-o,0),t.arc(i-o,o,o,3*Math.PI/2,0,!1),t.lineTo(i,n-s),t.arc(i-s,n-s,s,0,Math.PI/2,!1),t.lineTo(a,n),t.arc(a,n-a,a,Math.PI/2,Math.PI,!1),t.lineTo(0,r),t.arc(r,r,r,Math.PI,3*Math.PI/2,!1)}else t.rect(0,0,i,n);t.closePath(),t.fillStrokeShape(this)},e}(lt);Dt.prototype.className="Rect",a(Dt),w.addGetterSetter(Dt,"cornerRadius",0,m(4)),s.mapMethods(Dt);var It=function(t){function e(){return null!==t&&t.apply(this,arguments)||this}return P(e,t),e.prototype._sceneFunc=function(t){var e=this._getPoints();t.beginPath(),t.moveTo(e[0].x,e[0].y);for(var i=1;i1&&(v+=a)}}},e.prototype._hitFunc=function(t){var e=this.getWidth(),i=this.getHeight();t.beginPath(),t.rect(0,0,e,i),t.closePath(),t.fillStrokeShape(this)},e.prototype.setText=function(t){var e=f._isString(t)?t:null==t?"":t+"";return this._setAttr("text",e),this},e.prototype.getWidth=function(){return"auto"===this.attrs.width||void 0===this.attrs.width?this.getTextWidth()+2*this.padding():this.attrs.width},e.prototype.getHeight=function(){return"auto"===this.attrs.height||void 0===this.attrs.height?this.fontSize()*this.textArr.length*this.lineHeight()+2*this.padding():this.attrs.height},e.prototype.getTextWidth=function(){return this.textWidth},e.prototype.getTextHeight=function(){return f.warn("text.getTextHeight() method is deprecated. Use text.height() - for full height and text.fontSize() - for one line height."),this.textHeight},e.prototype.measureSize=function(t){var e,i=jt(),n=this.fontSize();return i.save(),i.font=this._getContextFont(),e=i.measureText(t),i.restore(),{width:e.width,height:n}},e.prototype._getContextFont=function(){return r.UA.isIE?this.fontStyle()+" "+this.fontSize()+"px "+this.fontFamily():this.fontStyle()+" "+this.fontVariant()+" "+this.fontSize()+"px "+this.fontFamily().split(",").map((function(t){var e=(t=t.trim()).indexOf(" ")>=0,i=t.indexOf('"')>=0||t.indexOf("'")>=0;return e&&!i&&(t='"'+t+'"'),t})).join(", ")},e.prototype._addTextLine=function(t){"justify"===this.align()&&(t=t.trim());var e=this._getTextWidth(t);return this.textArr.push({text:t,width:e})},e.prototype._getTextWidth=function(t){var e=this.letterSpacing(),i=t.length;return jt().measureText(t).width+(i?e*(i-1):0)},e.prototype._setTextData=function(){var t=this.text().split("\n"),e=+this.fontSize(),i=0,n=this.lineHeight()*e,r=this.attrs.width,o=this.attrs.height,a="auto"!==r&&void 0!==r,s="auto"!==o&&void 0!==o,h=this.padding(),l=r-2*h,c=o-2*h,d=0,u=this.wrap(),p="none"!==u,f="char"!==u&&p,g=this.ellipsis();this.textArr=[],jt().font=this._getContextFont();for(var v=g?this._getTextWidth("…"):0,y=0,m=t.length;yl)for(;_.length>0;){for(var x=0,S=_.length,w="",C=0;x>>1,k=_.slice(0,P+1),T=this._getTextWidth(k)+v;T<=l?(x=P+1,w=k,C=T):S=P}if(!w)break;if(f){var A,M=_[w.length];(A=(" "===M||"-"===M)&&C<=l?w.length:Math.max(w.lastIndexOf(" "),w.lastIndexOf("-"))+1)>0&&(x=A,w=w.slice(0,x),C=this._getTextWidth(w))}if(w=w.trimRight(),this._addTextLine(w),i=Math.max(i,C),d+=n,!p||s&&d+n>c){var G=this.textArr[this.textArr.length-1];if(G)if(g)this._getTextWidth(G.text+"…")0&&(b=this._getTextWidth(_))<=l){this._addTextLine(_),d+=n,i=Math.max(i,b);break}}else this._addTextLine(_),d+=n,i=Math.max(i,b);if(s&&d+n>c)break}this.textHeight=e,this.textWidth=i},e.prototype.getStrokeScaleEnabled=function(){return!0},e}(lt);Ut.prototype._fillFunc=function(t){t.fillText(this._partialText,this._partialTextX,this._partialTextY)},Ut.prototype._strokeFunc=function(t){t.strokeText(this._partialText,this._partialTextX,this._partialTextY)},Ut.prototype.className="Text",Ut.prototype._attrsAffectingSize=["text","fontSize","padding","wrap","lineHeight","letterSpacing"],a(Ut),w.overWriteSetter(Ut,"width",_()),w.overWriteSetter(Ut,"height",_()),w.addGetterSetter(Ut,"fontFamily","Arial"),w.addGetterSetter(Ut,"fontSize",12,y()),w.addGetterSetter(Ut,"fontStyle","normal"),w.addGetterSetter(Ut,"fontVariant","normal"),w.addGetterSetter(Ut,"padding",0,y()),w.addGetterSetter(Ut,"align","left"),w.addGetterSetter(Ut,"verticalAlign","top"),w.addGetterSetter(Ut,"lineHeight",1,y()),w.addGetterSetter(Ut,"wrap","word"),w.addGetterSetter(Ut,"ellipsis",!1,S()),w.addGetterSetter(Ut,"letterSpacing",0,y()),w.addGetterSetter(Ut,"text","",b()),w.addGetterSetter(Ut,"textDecoration",""),s.mapMethods(Ut);function qt(t){t.fillText(this.partialText,0,0)}function Kt(t){t.strokeText(this.partialText,0,0)}var Vt=function(t){function e(e){var i=t.call(this,e)||this;return i.dummyCanvas=f.createCanvasElement(),i.dataArray=[],i.dataArray=Ot.parsePathData(i.attrs.data),i.on("dataChange.konva",(function(){this.dataArray=Ot.parsePathData(this.attrs.data),this._setTextData()})),i.on("textChange.konva alignChange.konva letterSpacingChange.konva kerningFuncChange.konva",i._setTextData),e&&e.getKerning&&(f.warn('getKerning TextPath API is deprecated. Please use "kerningFunc" instead.'),i.kerningFunc(e.getKerning)),i._setTextData(),i}return P(e,t),e.prototype._sceneFunc=function(t){t.setAttr("font",this._getContextFont()),t.setAttr("textBaseline",this.textBaseline()),t.setAttr("textAlign","left"),t.save();var e=this.textDecoration(),i=this.fill(),n=this.fontSize(),r=this.glyphInfo;"underline"===e&&t.beginPath();for(var o=0;o=1){var i=e[0].p0;t.moveTo(i.x,i.y)}for(var n=0;n0&&(a+=t.dataArray[s].pathLength);var h=0;"center"===n&&(h=Math.max(0,a/2-o/2)),"right"===n&&(h=Math.max(0,a-o));for(var l,c,d,u=Wt(this.text()),p=this.text().split(" ").length-1,f=-1,g=0,v=function(){g=0;for(var e=t.dataArray,i=f+1;i0)return f=i,e[i];"M"===e[i].command&&(l={x:e[i].points[0],y:e[i].points[1]})}return{}},y=function(e){var r=t._getTextSize(e).width+i;" "===e&&"justify"===n&&(r+=(a-o)/p);var s=0,h=0;for(c=void 0;Math.abs(r-s)/r>.01&&h<20;){h++;for(var u=s;void 0===d;)(d=v())&&u+d.pathLengthr?c=Ot.getPointOnLine(r,l.x,l.y,d.points[0],d.points[1],l.x,l.y):d=void 0;break;case"A":var y=d.points[4],m=d.points[5],_=d.points[4]+m;0===g?g=y+1e-8:r>s?g+=Math.PI/180*m/Math.abs(m):g-=Math.PI/360*m/Math.abs(m),(m<0&&g<_||m>=0&&g>_)&&(g=_,f=!0),c=Ot.getPointOnEllipticalArc(d.points[0],d.points[1],d.points[2],d.points[3],g,d.points[6]);break;case"C":0===g?g=r>d.pathLength?1e-8:r/d.pathLength:r>s?g+=(r-s)/d.pathLength/2:g=Math.max(g-(s-r)/d.pathLength/2,0),g>1&&(g=1,f=!0),c=Ot.getPointOnCubicBezier(g,d.start.x,d.start.y,d.points[0],d.points[1],d.points[2],d.points[3],d.points[4],d.points[5]);break;case"Q":0===g?g=r/d.pathLength:r>s?g+=(r-s)/d.pathLength:g-=(s-r)/d.pathLength,g>1&&(g=1,f=!0),c=Ot.getPointOnQuadraticBezier(g,d.start.x,d.start.y,d.points[0],d.points[1],d.points[2],d.points[3])}void 0!==c&&(s=Ot.getLineLength(l.x,l.y,c.x,c.y)),f&&(f=!1,d=void 0)}},m=h/(t._getTextSize("C").width+i)-1,_=0;_p.x?-1:1,g=this.findOne(".top-left").y()>p.y?-1:1;e=n*this.cos*f,i=n*this.sin*g,this.findOne(".top-left").x(p.x-e),this.findOne(".top-left").y(p.y-i)}}else if("top-center"===this._movingAnchorName)this.findOne(".top-left").y(o.y());else if("top-right"===this._movingAnchorName){if(d){p=u?{x:this.width()/2,y:this.height()/2}:{x:this.findOne(".bottom-left").x(),y:this.findOne(".bottom-left").y()};n=Math.sqrt(Math.pow(o.x()-p.x,2)+Math.pow(p.y-o.y(),2));f=this.findOne(".top-right").x()p.y?-1:1;e=n*this.cos*f,i=n*this.sin*g,this.findOne(".top-right").x(p.x+e),this.findOne(".top-right").y(p.y-i)}var v=o.position();this.findOne(".top-left").y(v.y),this.findOne(".bottom-right").x(v.x)}else if("middle-left"===this._movingAnchorName)this.findOne(".top-left").x(o.x());else if("middle-right"===this._movingAnchorName)this.findOne(".bottom-right").x(o.x());else if("bottom-left"===this._movingAnchorName){if(d){p=u?{x:this.width()/2,y:this.height()/2}:{x:this.findOne(".top-right").x(),y:this.findOne(".top-right").y()};n=Math.sqrt(Math.pow(p.x-o.x(),2)+Math.pow(o.y()-p.y,2));f=p.x=0){var a=o.point({x:2*-this.padding(),y:0});t.x+=a.x,t.y+=a.y,t.width+=2*this.padding(),this._movingAnchorName=this._movingAnchorName.replace("left","right"),this._anchorDragOffset.x-=a.x,this._anchorDragOffset.y-=a.y}else if(this._movingAnchorName&&t.width<0&&this._movingAnchorName.indexOf("right")>=0){a=o.point({x:2*this.padding(),y:0});this._movingAnchorName=this._movingAnchorName.replace("right","left"),this._anchorDragOffset.x-=a.x,this._anchorDragOffset.y-=a.y,t.width+=2*this.padding()}if(this._movingAnchorName&&t.height<0&&this._movingAnchorName.indexOf("top")>=0){a=o.point({x:0,y:2*-this.padding()});t.x+=a.x,t.y+=a.y,this._movingAnchorName=this._movingAnchorName.replace("top","bottom"),this._anchorDragOffset.x-=a.x,this._anchorDragOffset.y-=a.y,t.height+=2*this.padding()}else if(this._movingAnchorName&&t.height<0&&this._movingAnchorName.indexOf("bottom")>=0){a=o.point({x:0,y:2*this.padding()});this._movingAnchorName=this._movingAnchorName.replace("bottom","top"),this._anchorDragOffset.x-=a.x,this._anchorDragOffset.y-=a.y,t.height+=2*this.padding()}if(this.boundBoxFunc()){var s=this.boundBoxFunc()(n,t);s?t=s:f.warn("boundBoxFunc returned falsy. You should return new bound rect from it!")}var l=new h;l.translate(n.x,n.y),l.rotate(n.rotation),l.scale(n.width/1e7,n.height/1e7);var c=new h;c.translate(t.x,t.y),c.rotate(t.rotation),c.scale(t.width/1e7,t.height/1e7);var d=c.multiply(l.invert());this._nodes.forEach((function(t){var n,r=t.getParent().getAbsoluteTransform(),o=t.getTransform().copy();o.translate(t.offsetX(),t.offsetY());var a=new h;a.multiply(r.copy().invert()).multiply(d).multiply(r).multiply(o);var s=a.decompose();t.setAttrs(s),i._fire("transform",{evt:e,target:t}),t._fire("transform",{evt:e,target:t}),null===(n=t.getLayer())||void 0===n||n.batchDraw()})),this.rotation(f._getRotation(t.rotation)),this._resetTransformCache(),this.update(),this.getLayer().batchDraw()}},e.prototype.forceUpdate=function(){this._resetTransformCache(),this.update()},e.prototype._batchChangeChild=function(t,e){this.findOne(t).setAttrs(e)},e.prototype.update=function(){var t,e=this,i=this._getNodeRect();this.rotation(f._getRotation(i.rotation));var n=i.width,r=i.height,o=this.enabledAnchors(),a=this.resizeEnabled(),s=this.padding(),h=this.anchorSize();this.find("._anchor").each((function(t){t.setAttrs({width:h,height:h,offsetX:h/2,offsetY:h/2,stroke:e.anchorStroke(),strokeWidth:e.anchorStrokeWidth(),fill:e.anchorFill(),cornerRadius:e.anchorCornerRadius()})})),this._batchChangeChild(".top-left",{x:0,y:0,offsetX:h/2+s,offsetY:h/2+s,visible:a&&o.indexOf("top-left")>=0}),this._batchChangeChild(".top-center",{x:n/2,y:0,offsetY:h/2+s,visible:a&&o.indexOf("top-center")>=0}),this._batchChangeChild(".top-right",{x:n,y:0,offsetX:h/2-s,offsetY:h/2+s,visible:a&&o.indexOf("top-right")>=0}),this._batchChangeChild(".middle-left",{x:0,y:r/2,offsetX:h/2+s,visible:a&&o.indexOf("middle-left")>=0}),this._batchChangeChild(".middle-right",{x:n,y:r/2,offsetX:h/2-s,visible:a&&o.indexOf("middle-right")>=0}),this._batchChangeChild(".bottom-left",{x:0,y:r,offsetX:h/2+s,offsetY:h/2-s,visible:a&&o.indexOf("bottom-left")>=0}),this._batchChangeChild(".bottom-center",{x:n/2,y:r,offsetY:h/2-s,visible:a&&o.indexOf("bottom-center")>=0}),this._batchChangeChild(".bottom-right",{x:n,y:r,offsetX:h/2-s,offsetY:h/2-s,visible:a&&o.indexOf("bottom-right")>=0}),this._batchChangeChild(".rotater",{x:n/2,y:-this.rotateAnchorOffset()*f._sign(r)-s,visible:this.rotateEnabled()}),this._batchChangeChild(".back",{width:n,height:r,visible:this.borderEnabled(),stroke:this.borderStroke(),strokeWidth:this.borderStrokeWidth(),dash:this.borderDash(),x:0,y:0}),null===(t=this.getLayer())||void 0===t||t.batchDraw()},e.prototype.isTransforming=function(){return this._transforming},e.prototype.stopTransform=function(){if(this._transforming){this._removeEvents();var t=this.findOne("."+this._movingAnchorName);t&&t.stopDrag()}},e.prototype.destroy=function(){return this.getStage()&&this._cursorChange&&(this.getStage().content.style.cursor=""),ft.prototype.destroy.call(this),this.detach(),this._removeEvents(),this},e.prototype.toObject=function(){return X.prototype.toObject.call(this)},e}(ft);ne.prototype.className="Transformer",a(ne),w.addGetterSetter(ne,"enabledAnchors",te,(function(t){return t instanceof Array||f.warn("enabledAnchors value should be an array"),t instanceof Array&&t.forEach((function(t){-1===te.indexOf(t)&&f.warn("Unknown anchor name: "+t+". Available names are: "+te.join(", "))})),t||[]})),w.addGetterSetter(ne,"resizeEnabled",!0),w.addGetterSetter(ne,"anchorSize",10,y()),w.addGetterSetter(ne,"rotateEnabled",!0),w.addGetterSetter(ne,"rotationSnaps",[]),w.addGetterSetter(ne,"rotateAnchorOffset",50,y()),w.addGetterSetter(ne,"rotationSnapTolerance",5,y()),w.addGetterSetter(ne,"borderEnabled",!0),w.addGetterSetter(ne,"anchorStroke","rgb(0, 161, 255)"),w.addGetterSetter(ne,"anchorStrokeWidth",1,y()),w.addGetterSetter(ne,"anchorFill","white"),w.addGetterSetter(ne,"anchorCornerRadius",0,y()),w.addGetterSetter(ne,"borderStroke","rgb(0, 161, 255)"),w.addGetterSetter(ne,"borderStrokeWidth",1,y()),w.addGetterSetter(ne,"borderDash"),w.addGetterSetter(ne,"keepRatio",!0),w.addGetterSetter(ne,"centeredScaling",!1),w.addGetterSetter(ne,"ignoreStroke",!1),w.addGetterSetter(ne,"padding",0,y()),w.addGetterSetter(ne,"node"),w.addGetterSetter(ne,"nodes"),w.addGetterSetter(ne,"boundBoxFunc"),w.addGetterSetter(ne,"shouldOverdrawWholeArea",!1),w.backCompat(ne,{lineEnabled:"borderEnabled",rotateHandlerOffset:"rotateAnchorOffset",enabledHandlers:"enabledAnchors"}),s.mapMethods(ne);var re=function(t){function e(){return null!==t&&t.apply(this,arguments)||this}return P(e,t),e.prototype._sceneFunc=function(t){t.beginPath(),t.arc(0,0,this.radius(),0,r.getAngle(this.angle()),this.clockwise()),t.lineTo(0,0),t.closePath(),t.fillStrokeShape(this)},e.prototype.getWidth=function(){return 2*this.radius()},e.prototype.getHeight=function(){return 2*this.radius()},e.prototype.setWidth=function(t){this.radius(t/2)},e.prototype.setHeight=function(t){this.radius(t/2)},e}(lt);function oe(){this.r=0,this.g=0,this.b=0,this.a=0,this.next=null}re.prototype.className="Wedge",re.prototype._centroid=!0,re.prototype._attrsAffectingSize=["radius"],a(re),w.addGetterSetter(re,"radius",0,y()),w.addGetterSetter(re,"angle",0,y()),w.addGetterSetter(re,"clockwise",!1),w.backCompat(re,{angleDeg:"angle",getAngleDeg:"getAngle",setAngleDeg:"setAngle"}),s.mapMethods(re);var ae=[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,496,475,456,437,420,404,388,374,360,347,335,323,312,302,292,282,273,265,512,497,482,468,454,441,428,417,405,394,383,373,364,354,345,337,328,320,312,305,298,291,284,278,271,265,259,507,496,485,475,465,456,446,437,428,420,412,404,396,388,381,374,367,360,354,347,341,335,329,323,318,312,307,302,297,292,287,282,278,273,269,265,261,512,505,497,489,482,475,468,461,454,447,441,435,428,422,417,411,405,399,394,389,383,378,373,368,364,359,354,350,345,341,337,332,328,324,320,316,312,309,305,301,298,294,291,287,284,281,278,274,271,268,265,262,259,257,507,501,496,491,485,480,475,470,465,460,456,451,446,442,437,433,428,424,420,416,412,408,404,400,396,392,388,385,381,377,374,370,367,363,360,357,354,350,347,344,341,338,335,332,329,326,323,320,318,315,312,310,307,304,302,299,297,294,292,289,287,285,282,280,278,275,273,271,269,267,265,263,261,259],se=[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,20,20,20,20,20,21,21,21,21,21,21,21,21,21,21,21,21,21,21,21,21,21,21,21,21,21,21,21,21,21,21,21,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24];w.addGetterSetter(X,"blurRadius",0,y(),w.afterSetFilter);w.addGetterSetter(X,"brightness",0,y(),w.afterSetFilter);w.addGetterSetter(X,"contrast",0,y(),w.afterSetFilter);function he(t,e,i,n,r){var o=i-e,a=r-n;return 0===o?n+a/2:0===a?n:a*((t-e)/o)+n}w.addGetterSetter(X,"embossStrength",.5,y(),w.afterSetFilter),w.addGetterSetter(X,"embossWhiteLevel",.5,y(),w.afterSetFilter),w.addGetterSetter(X,"embossDirection","top-left",null,w.afterSetFilter),w.addGetterSetter(X,"embossBlend",!1,null,w.afterSetFilter);w.addGetterSetter(X,"enhance",0,y(),w.afterSetFilter);w.addGetterSetter(X,"hue",0,y(),w.afterSetFilter),w.addGetterSetter(X,"saturation",0,y(),w.afterSetFilter),w.addGetterSetter(X,"luminance",0,y(),w.afterSetFilter);w.addGetterSetter(X,"hue",0,y(),w.afterSetFilter),w.addGetterSetter(X,"saturation",0,y(),w.afterSetFilter),w.addGetterSetter(X,"value",0,y(),w.afterSetFilter);function le(t,e,i){var n=4*(i*t.width+e),r=[];return r.push(t.data[n++],t.data[n++],t.data[n++],t.data[n++]),r}function ce(t,e){return Math.sqrt(Math.pow(t[0]-e[0],2)+Math.pow(t[1]-e[1],2)+Math.pow(t[2]-e[2],2))}w.addGetterSetter(X,"kaleidoscopePower",2,y(),w.afterSetFilter),w.addGetterSetter(X,"kaleidoscopeAngle",0,y(),w.afterSetFilter);w.addGetterSetter(X,"threshold",0,y(),w.afterSetFilter);w.addGetterSetter(X,"noise",.2,y(),w.afterSetFilter);w.addGetterSetter(X,"pixelSize",8,y(),w.afterSetFilter);w.addGetterSetter(X,"levels",.5,y(),w.afterSetFilter);w.addGetterSetter(X,"red",0,(function(t){return this._filterUpToDate=!1,t>255?255:t<0?0:Math.round(t)})),w.addGetterSetter(X,"green",0,(function(t){return this._filterUpToDate=!1,t>255?255:t<0?0:Math.round(t)})),w.addGetterSetter(X,"blue",0,v,w.afterSetFilter);w.addGetterSetter(X,"red",0,(function(t){return this._filterUpToDate=!1,t>255?255:t<0?0:Math.round(t)})),w.addGetterSetter(X,"green",0,(function(t){return this._filterUpToDate=!1,t>255?255:t<0?0:Math.round(t)})),w.addGetterSetter(X,"blue",0,v,w.afterSetFilter),w.addGetterSetter(X,"alpha",1,(function(t){return this._filterUpToDate=!1,t>1?1:t<0?0:t}));return w.addGetterSetter(X,"threshold",.5,y(),w.afterSetFilter),wt.Util._assign(wt,{Arc:Ct,Arrow:kt,Circle:Tt,Ellipse:At,Image:Mt,Label:Lt,Tag:Et,Line:Pt,Path:Ot,Rect:Dt,RegularPolygon:It,Ring:Bt,Sprite:Nt,Star:zt,Text:Ut,TextPath:Vt,Transformer:ne,Wedge:re,Filters:{Blur:function(t){var e=Math.round(this.blurRadius());e>0&&function(t,e){var i,n,r,o,a,s,h,l,c,d,u,p,f,g,v,y,m,_,b,x,S,w,C,P,k=t.data,T=t.width,A=t.height,M=e+e+1,G=T-1,R=A-1,L=e+1,E=L*(L+1)/2,O=new oe,D=null,I=O,F=null,B=null,N=ae[e],z=se[e];for(r=1;r>z,0!==C?(C=255/C,k[s]=(l*N>>z)*C,k[s+1]=(c*N>>z)*C,k[s+2]=(d*N>>z)*C):k[s]=k[s+1]=k[s+2]=0,l-=p,c-=f,d-=g,u-=v,p-=F.r,f-=F.g,g-=F.b,v-=F.a,o=h+((o=i+e+1)>z,C>0?(C=255/C,k[o]=(l*N>>z)*C,k[o+1]=(c*N>>z)*C,k[o+2]=(d*N>>z)*C):k[o]=k[o+1]=k[o+2]=0,l-=p,c-=f,d-=g,u-=v,p-=F.r,f-=F.g,g-=F.b,v-=F.a,o=i+((o=n+L)255?255:o,a=(a*=255)<0?0:a>255?255:a,s=(s*=255)<0?0:s>255?255:s,n[e]=o,n[e+1]=a,n[e+2]=s},Emboss:function(t){var e=10*this.embossStrength(),i=255*this.embossWhiteLevel(),n=this.embossDirection(),r=this.embossBlend(),o=0,a=0,s=t.data,h=t.width,l=t.height,c=4*h,d=l;switch(n){case"top-left":o=-1,a=-1;break;case"top":o=-1,a=0;break;case"top-right":o=-1,a=1;break;case"right":o=0,a=1;break;case"bottom-right":o=1,a=1;break;case"bottom":o=1,a=0;break;case"bottom-left":o=1,a=-1;break;case"left":o=0,a=-1;break;default:f.error("Unknown emboss direction: "+n)}do{var u=(d-1)*c,p=o;d+p<1&&(p=0),d+p>l&&(p=0);var g=(d-1+p)*h*4,v=h;do{var y=u+4*(v-1),m=a;v+m<1&&(m=0),v+m>h&&(m=0);var _=g+4*(v-1+m),b=s[y]-s[_],x=s[y+1]-s[_+1],S=s[y+2]-s[_+2],w=b,C=w>0?w:-w;if((x>0?x:-x)>C&&(w=x),(S>0?S:-S)>C&&(w=S),w*=e,r){var P=s[y]+w,k=s[y+1]+w,T=s[y+2]+w;s[y]=P>255?255:P<0?0:P,s[y+1]=k>255?255:k<0?0:k,s[y+2]=T>255?255:T<0?0:T}else{var A=i-w;A<0?A=0:A>255&&(A=255),s[y]=s[y+1]=s[y+2]=A}}while(--v)}while(--d)},Enhance:function(t){var e,i,n,r,o=t.data,a=o.length,s=o[0],h=s,l=o[1],c=l,d=o[2],u=d,p=this.enhance();if(0!==p){for(r=0;rh&&(h=e),(i=o[r+1])c&&(c=i),(n=o[r+2])u&&(u=n);var f,g,v,y,m,_,b,x,S;for(h===s&&(h=255,s=0),c===l&&(c=255,l=0),u===d&&(u=255,d=0),p>0?(g=h+p*(255-h),v=s-p*(s-0),m=c+p*(255-c),_=l-p*(l-0),x=u+p*(255-u),S=d-p*(d-0)):(g=h+p*(h-(f=.5*(h+s))),v=s+p*(s-f),m=c+p*(c-(y=.5*(c+l))),_=l+p*(l-y),x=u+p*(u-(b=.5*(u+d))),S=d+p*(d-b)),r=0;ry?a:y;var m,_,b,x,S=c,w=l,C=360/w*Math.PI/180;for(_=0;_c&&(b=_,x=0,S=-1),i=0;i_?h:_;var b,x,S,w=u,C=d,P=i.polarRotation||0;for(r=0;r=0&&p=0&&f=0&&p=0&&f=1020?255:0}return a}(e=function(t,e,i){for(var n=[1,1,1,1,0,1,1,1,1],r=Math.round(Math.sqrt(n.length)),o=Math.floor(r/2),a=[],s=0;s=0&&p=0&&f=y))for(i=c;i=m||(r+=x[(n=4*(y*i+e))+0],o+=x[n+1],a+=x[n+2],s+=x[n+3],g+=1);for(r/=g,o/=g,a/=g,s/=g,e=h;e=y))for(i=c;i=m||(x[(n=4*(y*i+e))+0]=r,x[n+1]=o,x[n+2]=a,x[n+3]=s)}},Posterize:function(t){var e,i=Math.round(254*this.levels())+1,n=t.data,r=n.length,o=255/i;for(e=0;e127&&(h=255-h),l>127&&(l=255-l),c>127&&(c=255-c),e[s]=h,e[s+1]=l,e[s+2]=c}while(--a)}while(--r)},Threshold:function(t){var e,i=255*this.threshold(),n=t.data,r=n.length;for(e=0;e0)return parseInt(t.substring(e+5,t.indexOf(".",e)),10);if(t.indexOf("trident/")>0){var i=t.indexOf("rv:");return parseInt(t.substring(i+3,t.indexOf(".",i)),10)}var r=t.indexOf("edge/");return r>0&&parseInt(t.substring(r+5,t.indexOf(".",r)),10)},i=function(t){var i=t.toLowerCase(),r=/(chrome)[ /]([\w.]+)/.exec(i)||/(webkit)[ /]([\w.]+)/.exec(i)||/(opera)(?:.*version|)[ /]([\w.]+)/.exec(i)||/(msie) ([\w.]+)/.exec(i)||i.indexOf("compatible")<0&&/(mozilla)(?:.*? rv:([\w.]+)|)/.exec(i)||[],a=!!t.match(/Android|BlackBerry|iPhone|iPad|iPod|Opera Mini|IEMobile/i),n=!!t.match(/IEMobile/i);return{browser:r[1]||"",version:r[2]||"0",isIE:e(i),mobile:a,ieMobile:n}},r="undefined"!=typeof global?global:"undefined"!=typeof window?window:"undefined"!=typeof WorkerGlobalScope?self:{},a={_global:r,version:"7.2.5",isBrowser:"undefined"!=typeof window&&("[object Window]"==={}.toString.call(window)||"[object global]"==={}.toString.call(window)),isUnminified:/param/.test(function(t){}.toString()),dblClickWindow:400,getAngle:e=>a.angleDeg?e*t:e,enableTrace:!1,_pointerEventsEnabled:!1,autoDrawEnabled:!1,hitOnDragEnabled:!1,captureTouchEventsEnabled:!1,listenClickTap:!1,inDblClickWindow:!1,pixelRatio:"undefined"!=typeof window&&window.devicePixelRatio||1,dragDistance:3,angleDeg:!0,showWarnings:!0,dragButtons:[0,1],isDragging:()=>a.DD.isDragging,isDragReady:()=>!!a.DD.node,UA:i(r.navigator&&r.navigator.userAgent||""),document:r.document,_injectGlobal(t){r.Konva=t},_parseUA:i},n={},s=t=>{n[t.prototype.getClassName()]=t,a[t.prototype.getClassName()]=t};a._injectGlobal(a);class o{constructor(t=[1,0,0,1,0,0]){this.dirty=!1,this.m=t&&t.slice()||[1,0,0,1,0,0]}reset(){this.m[0]=1,this.m[1]=0,this.m[2]=0,this.m[3]=1,this.m[4]=0,this.m[5]=0}copy(){return new o(this.m)}copyInto(t){t.m[0]=this.m[0],t.m[1]=this.m[1],t.m[2]=this.m[2],t.m[3]=this.m[3],t.m[4]=this.m[4],t.m[5]=this.m[5]}point(t){var e=this.m;return{x:e[0]*t.x+e[2]*t.y+e[4],y:e[1]*t.x+e[3]*t.y+e[5]}}translate(t,e){return this.m[4]+=this.m[0]*t+this.m[2]*e,this.m[5]+=this.m[1]*t+this.m[3]*e,this}scale(t,e){return this.m[0]*=t,this.m[1]*=t,this.m[2]*=e,this.m[3]*=e,this}rotate(t){var e=Math.cos(t),i=Math.sin(t),r=this.m[0]*e+this.m[2]*i,a=this.m[1]*e+this.m[3]*i,n=this.m[0]*-i+this.m[2]*e,s=this.m[1]*-i+this.m[3]*e;return this.m[0]=r,this.m[1]=a,this.m[2]=n,this.m[3]=s,this}getTranslation(){return{x:this.m[4],y:this.m[5]}}skew(t,e){var i=this.m[0]+this.m[2]*e,r=this.m[1]+this.m[3]*e,a=this.m[2]+this.m[0]*t,n=this.m[3]+this.m[1]*t;return this.m[0]=i,this.m[1]=r,this.m[2]=a,this.m[3]=n,this}multiply(t){var e=this.m[0]*t.m[0]+this.m[2]*t.m[1],i=this.m[1]*t.m[0]+this.m[3]*t.m[1],r=this.m[0]*t.m[2]+this.m[2]*t.m[3],a=this.m[1]*t.m[2]+this.m[3]*t.m[3],n=this.m[0]*t.m[4]+this.m[2]*t.m[5]+this.m[4],s=this.m[1]*t.m[4]+this.m[3]*t.m[5]+this.m[5];return this.m[0]=e,this.m[1]=i,this.m[2]=r,this.m[3]=a,this.m[4]=n,this.m[5]=s,this}invert(){var t=1/(this.m[0]*this.m[3]-this.m[1]*this.m[2]),e=this.m[3]*t,i=-this.m[1]*t,r=-this.m[2]*t,a=this.m[0]*t,n=t*(this.m[2]*this.m[5]-this.m[3]*this.m[4]),s=t*(this.m[1]*this.m[4]-this.m[0]*this.m[5]);return this.m[0]=e,this.m[1]=i,this.m[2]=r,this.m[3]=a,this.m[4]=n,this.m[5]=s,this}getMatrix(){return this.m}setAbsolutePosition(t,e){var i=this.m[0],r=this.m[1],a=this.m[2],n=this.m[3],s=this.m[4],o=(i*(e-this.m[5])-r*(t-s))/(i*n-r*a),h=(t-s-a*o)/i;return this.translate(h,o)}decompose(){var t=this.m[0],e=this.m[1],i=this.m[2],r=this.m[3],a=t*r-e*i;let n={x:this.m[4],y:this.m[5],rotation:0,scaleX:0,scaleY:0,skewX:0,skewY:0};if(0!=t||0!=e){var s=Math.sqrt(t*t+e*e);n.rotation=e>0?Math.acos(t/s):-Math.acos(t/s),n.scaleX=s,n.scaleY=a/s,n.skewX=(t*i+e*r)/a,n.skewY=0}else if(0!=i||0!=r){var o=Math.sqrt(i*i+r*r);n.rotation=Math.PI/2-(r>0?Math.acos(-i/o):-Math.acos(i/o)),n.scaleX=a/o,n.scaleY=o,n.skewX=0,n.skewY=(t*i+e*r)/a}return n.rotation=u._getRotation(n.rotation),n}}var h=Math.PI/180,l=180/Math.PI,d={aliceblue:[240,248,255],antiquewhite:[250,235,215],aqua:[0,255,255],aquamarine:[127,255,212],azure:[240,255,255],beige:[245,245,220],bisque:[255,228,196],black:[0,0,0],blanchedalmond:[255,235,205],blue:[0,0,255],blueviolet:[138,43,226],brown:[165,42,42],burlywood:[222,184,135],cadetblue:[95,158,160],chartreuse:[127,255,0],chocolate:[210,105,30],coral:[255,127,80],cornflowerblue:[100,149,237],cornsilk:[255,248,220],crimson:[220,20,60],cyan:[0,255,255],darkblue:[0,0,139],darkcyan:[0,139,139],darkgoldenrod:[184,132,11],darkgray:[169,169,169],darkgreen:[0,100,0],darkgrey:[169,169,169],darkkhaki:[189,183,107],darkmagenta:[139,0,139],darkolivegreen:[85,107,47],darkorange:[255,140,0],darkorchid:[153,50,204],darkred:[139,0,0],darksalmon:[233,150,122],darkseagreen:[143,188,143],darkslateblue:[72,61,139],darkslategray:[47,79,79],darkslategrey:[47,79,79],darkturquoise:[0,206,209],darkviolet:[148,0,211],deeppink:[255,20,147],deepskyblue:[0,191,255],dimgray:[105,105,105],dimgrey:[105,105,105],dodgerblue:[30,144,255],firebrick:[178,34,34],floralwhite:[255,255,240],forestgreen:[34,139,34],fuchsia:[255,0,255],gainsboro:[220,220,220],ghostwhite:[248,248,255],gold:[255,215,0],goldenrod:[218,165,32],gray:[128,128,128],green:[0,128,0],greenyellow:[173,255,47],grey:[128,128,128],honeydew:[240,255,240],hotpink:[255,105,180],indianred:[205,92,92],indigo:[75,0,130],ivory:[255,255,240],khaki:[240,230,140],lavender:[230,230,250],lavenderblush:[255,240,245],lawngreen:[124,252,0],lemonchiffon:[255,250,205],lightblue:[173,216,230],lightcoral:[240,128,128],lightcyan:[224,255,255],lightgoldenrodyellow:[250,250,210],lightgray:[211,211,211],lightgreen:[144,238,144],lightgrey:[211,211,211],lightpink:[255,182,193],lightsalmon:[255,160,122],lightseagreen:[32,178,170],lightskyblue:[135,206,250],lightslategray:[119,136,153],lightslategrey:[119,136,153],lightsteelblue:[176,196,222],lightyellow:[255,255,224],lime:[0,255,0],limegreen:[50,205,50],linen:[250,240,230],magenta:[255,0,255],maroon:[128,0,0],mediumaquamarine:[102,205,170],mediumblue:[0,0,205],mediumorchid:[186,85,211],mediumpurple:[147,112,219],mediumseagreen:[60,179,113],mediumslateblue:[123,104,238],mediumspringgreen:[0,250,154],mediumturquoise:[72,209,204],mediumvioletred:[199,21,133],midnightblue:[25,25,112],mintcream:[245,255,250],mistyrose:[255,228,225],moccasin:[255,228,181],navajowhite:[255,222,173],navy:[0,0,128],oldlace:[253,245,230],olive:[128,128,0],olivedrab:[107,142,35],orange:[255,165,0],orangered:[255,69,0],orchid:[218,112,214],palegoldenrod:[238,232,170],palegreen:[152,251,152],paleturquoise:[175,238,238],palevioletred:[219,112,147],papayawhip:[255,239,213],peachpuff:[255,218,185],peru:[205,133,63],pink:[255,192,203],plum:[221,160,203],powderblue:[176,224,230],purple:[128,0,128],rebeccapurple:[102,51,153],red:[255,0,0],rosybrown:[188,143,143],royalblue:[65,105,225],saddlebrown:[139,69,19],salmon:[250,128,114],sandybrown:[244,164,96],seagreen:[46,139,87],seashell:[255,245,238],sienna:[160,82,45],silver:[192,192,192],skyblue:[135,206,235],slateblue:[106,90,205],slategray:[119,128,144],slategrey:[119,128,144],snow:[255,255,250],springgreen:[0,255,127],steelblue:[70,130,180],tan:[210,180,140],teal:[0,128,128],thistle:[216,191,216],transparent:[255,255,255,0],tomato:[255,99,71],turquoise:[64,224,208],violet:[238,130,238],wheat:[245,222,179],white:[255,255,255],whitesmoke:[245,245,245],yellow:[255,255,0],yellowgreen:[154,205,5]},c=/rgb\((\d{1,3}),(\d{1,3}),(\d{1,3})\)/,g=[];const u={_isElement:t=>!(!t||1!=t.nodeType),_isFunction:t=>!!(t&&t.constructor&&t.call&&t.apply),_isPlainObject:t=>!!t&&t.constructor===Object,_isArray:t=>"[object Array]"===Object.prototype.toString.call(t),_isNumber:t=>"[object Number]"===Object.prototype.toString.call(t)&&!isNaN(t)&&isFinite(t),_isString:t=>"[object String]"===Object.prototype.toString.call(t),_isBoolean:t=>"[object Boolean]"===Object.prototype.toString.call(t),isObject:t=>t instanceof Object,isValidSelector(t){if("string"!=typeof t)return!1;var e=t[0];return"#"===e||"."===e||e===e.toUpperCase()},_sign:t=>0===t||t>0?1:-1,requestAnimFrame(t){g.push(t);const e="undefined"!=typeof requestAnimationFrame&&requestAnimationFrame||function(t){setTimeout(t,60)};1===g.length&&e((function(){const t=g;g=[],t.forEach((function(t){t()}))}))},createCanvasElement(){var t=document.createElement("canvas");try{t.style=t.style||{}}catch(t){}return t},createImageElement:()=>document.createElement("img"),_isInDocument(t){for(;t=t.parentNode;)if(t==document)return!0;return!1},_simplifyArray(t){var e,i,r=[],a=t.length,n=u;for(e=0;e((1<<24)+(t<<16)+(e<<8)+i).toString(16).slice(1),_hexToRgb(t){t=t.replace("#","");var e=parseInt(t,16);return{r:e>>16&255,g:e>>8&255,b:255&e}},getRandomColor(){for(var t=(16777215*Math.random()<<0).toString(16);t.length<6;)t="0"+t;return"#"+t},get:(t,e)=>void 0===t?e:t,getRGB(t){var e;return t in d?{r:(e=d[t])[0],g:e[1],b:e[2]}:"#"===t[0]?this._hexToRgb(t.substring(1)):"rgb("===t.substr(0,4)?(e=c.exec(t.replace(/ /g,"")),{r:parseInt(e[1],10),g:parseInt(e[2],10),b:parseInt(e[3],10)}):{r:0,g:0,b:0}},colorToRGBA:t=>(t=t||"black",u._namedColorToRBA(t)||u._hex3ColorToRGBA(t)||u._hex6ColorToRGBA(t)||u._rgbColorToRGBA(t)||u._rgbaColorToRGBA(t)||u._hslColorToRGBA(t)),_namedColorToRBA(t){var e=d[t.toLowerCase()];return e?{r:e[0],g:e[1],b:e[2],a:1}:null},_rgbColorToRGBA(t){if(0===t.indexOf("rgb(")){var e=(t=t.match(/rgb\(([^)]+)\)/)[1]).split(/ *, */).map(Number);return{r:e[0],g:e[1],b:e[2],a:1}}},_rgbaColorToRGBA(t){if(0===t.indexOf("rgba(")){var e=(t=t.match(/rgba\(([^)]+)\)/)[1]).split(/ *, */).map(Number);return{r:e[0],g:e[1],b:e[2],a:e[3]}}},_hex6ColorToRGBA(t){if("#"===t[0]&&7===t.length)return{r:parseInt(t.slice(1,3),16),g:parseInt(t.slice(3,5),16),b:parseInt(t.slice(5,7),16),a:1}},_hex3ColorToRGBA(t){if("#"===t[0]&&4===t.length)return{r:parseInt(t[1]+t[1],16),g:parseInt(t[2]+t[2],16),b:parseInt(t[3]+t[3],16),a:1}},_hslColorToRGBA(t){if(/hsl\((\d+),\s*([\d.]+)%,\s*([\d.]+)%\)/g.test(t)){const[e,...i]=/hsl\((\d+),\s*([\d.]+)%,\s*([\d.]+)%\)/g.exec(t),r=Number(i[0])/360,a=Number(i[1])/100,n=Number(i[2])/100;let s,o,h;if(0===a)return h=255*n,{r:Math.round(h),g:Math.round(h),b:Math.round(h),a:1};s=n<.5?n*(1+a):n+a-n*a;const l=2*n-s,d=[0,0,0];for(let t=0;t<3;t++)o=r+1/3*-(t-1),o<0&&o++,o>1&&o--,h=6*o<1?l+6*(s-l)*o:2*o<1?s:3*o<2?l+(s-l)*(2/3-o)*6:l,d[t]=255*h;return{r:Math.round(d[0]),g:Math.round(d[1]),b:Math.round(d[2]),a:1}}},haveIntersection:(t,e)=>!(e.x>t.x+t.width||e.x+e.widtht.y+t.height||e.y+e.heightt.slice(0),_degToRad:t=>t*h,_radToDeg:t=>t*l,_getRotation:t=>a.angleDeg?u._radToDeg(t):t,_capitalize:t=>t.charAt(0).toUpperCase()+t.slice(1),throw(t){throw new Error("Konva error: "+t)},error(t){console.error("Konva error: "+t)},warn(t){a.showWarnings&&console.warn("Konva warning: "+t)},extend(t,e){function i(){this.constructor=t}i.prototype=e.prototype;var r=t.prototype;for(var a in t.prototype=new i,r)r.hasOwnProperty(a)&&(t.prototype[a]=r[a]);t.__super__=e.prototype,t.super=e},_getControlPoints(t,e,i,r,a,n,s){var o=Math.sqrt(Math.pow(i-t,2)+Math.pow(r-e,2)),h=Math.sqrt(Math.pow(a-i,2)+Math.pow(n-r,2)),l=s*o/(o+h),d=s*h/(o+h);return[i-l*(a-t),r-l*(n-e),i+d*(a-t),r+d*(n-e)]},_expandPoints(t,e){var i,r,a=t.length,n=[];for(i=2;ie<=t&&t1?(s=i,o=r,h=(i-a)*(i-a)+(r-n)*(r-n)):h=((s=t+d*(i-t))-a)*(s-a)+((o=e+d*(r-e))-n)*(o-n)}return[s,o,h]},_getProjectionToLine(t,e,i){var r=u.cloneObject(t),a=Number.MAX_VALUE;return e.forEach((function(n,s){if(i||s!==e.length-1){var o=e[(s+1)%e.length],h=u._getProjectionToSegment(n.x,n.y,o.x,o.y,t.x,t.y),l=h[0],d=h[1],c=h[2];ce.length){var s=e;e=t,t=s}for(r=0;rt.touches?t.changedTouches[0].identifier:999};function f(t){return u._isString(t)?'"'+t+'"':"[object Number]"===Object.prototype.toString.call(t)||u._isBoolean(t)?t:Object.prototype.toString.call(t)}function p(t){return t>255?255:t<0?0:Math.round(t)}function v(){if(a.isUnminified)return function(t,e){return u._isNumber(t)||u.warn(f(t)+' is a not valid value for "'+e+'" attribute. The value should be a number.'),t}}function m(t){if(a.isUnminified)return function(e,i){let r=u._isNumber(e),a=u._isArray(e)&&e.length==t;return r||a||u.warn(f(e)+' is a not valid value for "'+i+'" attribute. The value should be a number or Array('+t+")"),e}}function _(){if(a.isUnminified)return function(t,e){return u._isNumber(t)||"auto"===t||u.warn(f(t)+' is a not valid value for "'+e+'" attribute. The value should be a number or "auto".'),t}}function y(){if(a.isUnminified)return function(t,e){return u._isString(t)||u.warn(f(t)+' is a not valid value for "'+e+'" attribute. The value should be a string.'),t}}function x(){if(a.isUnminified)return function(t,e){const i=u._isString(t),r="[object CanvasGradient]"===Object.prototype.toString.call(t);return i||r||u.warn(f(t)+' is a not valid value for "'+e+'" attribute. The value should be a string or a native gradient.'),t}}function b(){if(a.isUnminified)return function(t,e){return!0===t||!1===t||u.warn(f(t)+' is a not valid value for "'+e+'" attribute. The value should be a boolean.'),t}}const S={addGetterSetter(t,e,i,r,a){S.addGetter(t,e,i),S.addSetter(t,e,r,a),S.addOverloadedGetterSetter(t,e)},addGetter(t,e,i){var r="get"+u._capitalize(e);t.prototype[r]=t.prototype[r]||function(){var t=this.attrs[e];return void 0===t?i:t}},addSetter(t,e,i,r){var a="set"+u._capitalize(e);t.prototype[a]||S.overWriteSetter(t,e,i,r)},overWriteSetter(t,e,i,r){var a="set"+u._capitalize(e);t.prototype[a]=function(t){return i&&null!=t&&(t=i.call(this,t,e)),this._setAttr(e,t),r&&r.call(this),this}},addComponentsGetterSetter(t,e,i,r,n){var s,o,h=i.length,l=u._capitalize,d="get"+l(e),c="set"+l(e);t.prototype[d]=function(){var t={};for(s=0;s=100&&e.shift()}reset(){var t=this.getCanvas().getPixelRatio();this.setTransform(1*t,0,0,1*t,0,0)}getCanvas(){return this.canvas}clear(t){var e=this.getCanvas();t?this.clearRect(t.x||0,t.y||0,t.width||0,t.height||0):this.clearRect(0,0,e.getWidth()/e.pixelRatio,e.getHeight()/e.pixelRatio)}_applyLineCap(t){var e=t.getLineCap();e&&this.setAttr("lineCap",e)}_applyOpacity(t){var e=t.getAbsoluteOpacity();1!==e&&this.setAttr("globalAlpha",e)}_applyLineJoin(t){var e=t.attrs.lineJoin;e&&this.setAttr("lineJoin",e)}setAttr(t,e){this._context[t]=e}arc(t,e,i,r,a,n){this._context.arc(t,e,i,r,a,n)}arcTo(t,e,i,r,a){this._context.arcTo(t,e,i,r,a)}beginPath(){this._context.beginPath()}bezierCurveTo(t,e,i,r,a,n){this._context.bezierCurveTo(t,e,i,r,a,n)}clearRect(t,e,i,r){this._context.clearRect(t,e,i,r)}clip(){this._context.clip()}closePath(){this._context.closePath()}createImageData(t,e){var i=arguments;return 2===i.length?this._context.createImageData(t,e):1===i.length?this._context.createImageData(t):void 0}createLinearGradient(t,e,i,r){return this._context.createLinearGradient(t,e,i,r)}createPattern(t,e){return this._context.createPattern(t,e)}createRadialGradient(t,e,i,r,a,n){return this._context.createRadialGradient(t,e,i,r,a,n)}drawImage(t,e,i,r,a,n,s,o,h){var l=arguments,d=this._context;3===l.length?d.drawImage(t,e,i):5===l.length?d.drawImage(t,e,i,r,a):9===l.length&&d.drawImage(t,e,i,r,a,n,s,o,h)}ellipse(t,e,i,r,a,n,s,o){this._context.ellipse(t,e,i,r,a,n,s,o)}isPointInPath(t,e){return this._context.isPointInPath(t,e)}fill(){this._context.fill()}fillRect(t,e,i,r){this._context.fillRect(t,e,i,r)}strokeRect(t,e,i,r){this._context.strokeRect(t,e,i,r)}fillText(t,e,i){this._context.fillText(t,e,i)}measureText(t){return this._context.measureText(t)}getImageData(t,e,i,r){return this._context.getImageData(t,e,i,r)}lineTo(t,e){this._context.lineTo(t,e)}moveTo(t,e){this._context.moveTo(t,e)}rect(t,e,i,r){this._context.rect(t,e,i,r)}putImageData(t,e,i){this._context.putImageData(t,e,i)}quadraticCurveTo(t,e,i,r){this._context.quadraticCurveTo(t,e,i,r)}restore(){this._context.restore()}rotate(t){this._context.rotate(t)}save(){this._context.save()}scale(t,e){this._context.scale(t,e)}setLineDash(t){this._context.setLineDash?this._context.setLineDash(t):"mozDash"in this._context?this._context.mozDash=t:"webkitLineDash"in this._context&&(this._context.webkitLineDash=t)}getLineDash(){return this._context.getLineDash()}setTransform(t,e,i,r,a,n){this._context.setTransform(t,e,i,r,a,n)}stroke(){this._context.stroke()}strokeText(t,e,i,r){this._context.strokeText(t,e,i,r)}transform(t,e,i,r,a,n){this._context.transform(t,e,i,r,a,n)}translate(t,e){this._context.translate(t,e)}_enableTrace(){var t,e,i=this,r=w.length,a=this.setAttr,n=function(t){var r,a=i[t];i[t]=function(){return e=u._simplifyArray(Array.prototype.slice.call(arguments,0)),r=a.apply(i,arguments),i._trace({method:t,args:e}),r}};for(t=0;t{"dragging"===e.dragStatus&&(t=!0)}),t},justDragged:!1,get node(){var t;return E._dragElements.forEach(e=>{t=e.node}),t},_dragElements:new Map,_drag(t){const e=[];E._dragElements.forEach((i,r)=>{const{node:a}=i,n=a.getStage();n.setPointersPositions(t),void 0===i.pointerId&&(i.pointerId=u._getFirstPointerId(t));const s=n._changedPointerPositions.find(t=>t.id===i.pointerId);if(s){if("dragging"!==i.dragStatus){var o=a.dragDistance();if(Math.max(Math.abs(s.x-i.startPointerPos.x),Math.abs(s.y-i.startPointerPos.y)){e.fire("dragmove",{type:"dragmove",target:e,evt:t},!0)})},_endDragBefore(t){E._dragElements.forEach((e,i)=>{const{node:r}=e,n=r.getStage();t&&n.setPointersPositions(t);if(!n._changedPointerPositions.find(t=>t.id===e.pointerId))return;"dragging"!==e.dragStatus&&"stopped"!==e.dragStatus||(E.justDragged=!0,a.listenClickTap=!1,e.dragStatus="stopped");const s=e.node.getLayer()||e.node instanceof a.Stage&&e.node;s&&s.batchDraw()})},_endDragAfter(t){E._dragElements.forEach((e,i)=>{"stopped"===e.dragStatus&&e.node.fire("dragend",{type:"dragend",target:e.node,evt:t},!0),"dragging"!==e.dragStatus&&E._dragElements.delete(i)})}};a.isBrowser&&(window.addEventListener("mouseup",E._endDragBefore,!0),window.addEventListener("touchend",E._endDragBefore,!0),window.addEventListener("mousemove",E._drag),window.addEventListener("touchmove",E._drag),window.addEventListener("mouseup",E._endDragAfter,!1),window.addEventListener("touchend",E._endDragAfter,!1));const R={},L={},D=function(t,e){t&&R[t]===e&&delete R[t]},I=function(t,e){e&&(L[e]||(L[e]=[]),L[e].push(t))},O=function(t,e){if(t){var i=L[t];if(i){for(var r=0;rt+"Change.konva").join(" ");this.on(i,()=>{this._clearCache(t)}),this._attachedDepsListeners.set(t,!0)}return this._getCache(t,i)}_getCanvasCache(){return this._cache.get("canvas")}_clearSelfAndDescendantCache(t,e){this._clearCache(t),e&&"absoluteTransform"===t&&this.fire("_clearTransformCache")}clearCache(){return this._cache.delete("canvas"),this._clearSelfAndDescendantCache(),this}cache(t){var e=t||{},i={};void 0!==e.x&&void 0!==e.y&&void 0!==e.width&&void 0!==e.height||(i=this.getClientRect({skipTransform:!0,relativeTo:this.getParent()}));var r=Math.ceil(e.width||i.width),a=Math.ceil(e.height||i.height),n=e.pixelRatio,s=void 0===e.x?i.x:e.x,o=void 0===e.y?i.y:e.y,h=e.offset||0,l=e.drawBorder||!1;if(r&&a){s-=h,o-=h;var d=new M({pixelRatio:n,width:r+=2*h,height:a+=2*h}),c=new M({pixelRatio:n,width:0,height:0}),g=new G({pixelRatio:1,width:r,height:a}),f=d.getContext(),p=g.getContext();return g.isCache=!0,d.isCache=!0,this._cache.delete("canvas"),this._filterUpToDate=!1,!1===e.imageSmoothingEnabled&&(d.getContext()._context.imageSmoothingEnabled=!1,c.getContext()._context.imageSmoothingEnabled=!1),f.save(),p.save(),f.translate(-s,-o),p.translate(-s,-o),this._isUnderCache=!0,this._clearSelfAndDescendantCache("absoluteOpacity"),this._clearSelfAndDescendantCache("absoluteScale"),this.drawScene(d,this),this.drawHit(g,this),this._isUnderCache=!1,f.restore(),p.restore(),l&&(f.save(),f.beginPath(),f.rect(0,0,r,a),f.closePath(),f.setAttr("strokeStyle","red"),f.setAttr("lineWidth",5),f.stroke(),f.restore()),this._cache.set("canvas",{scene:d,filter:c,hit:g,x:s,y:o}),this}u.error("Can not cache the node. Width or height of the node equals 0. Caching is skipped.")}isCached(){return this._cache.has("canvas")}getClientRect(t){throw new Error('abstract "getClientRect" method call')}_transformedRect(t,e){var i,r,a,n,s=[{x:t.x,y:t.y},{x:t.x+t.width,y:t.y},{x:t.x+t.width,y:t.y+t.height},{x:t.x,y:t.y+t.height}],o=this.getAbsoluteTransform(e);return s.forEach((function(t){var e=o.point(t);void 0===i&&(i=a=e.x,r=n=e.y),i=Math.min(i,e.x),r=Math.min(r,e.y),a=Math.max(a,e.x),n=Math.max(n,e.y)})),{x:i,y:r,width:a-i,height:n-r}}_drawCachedSceneCanvas(t){t.save(),t._applyOpacity(this),t._applyGlobalCompositeOperation(this);const e=this._getCanvasCache();t.translate(e.x,e.y);var i=this._getCachedSceneCanvas(),r=i.pixelRatio;t.drawImage(i._canvas,0,0,i.width/r,i.height/r),t.restore()}_drawCachedHitCanvas(t){var e=this._getCanvasCache(),i=e.hit;t.save(),t.translate(e.x,e.y),t.drawImage(i._canvas,0,0),t.restore()}_getCachedSceneCanvas(){var t,e,i,r,a=this.filters(),n=this._getCanvasCache(),s=n.scene,o=n.filter,h=o.getContext();if(a){if(!this._filterUpToDate){var l=s.pixelRatio;o.setSize(s.width/s.pixelRatio,s.height/s.pixelRatio);try{for(t=a.length,h.clear(),h.drawImage(s._canvas,0,0,s.getWidth()/l,s.getHeight()/l),e=h.getImageData(0,0,o.getWidth(),o.getHeight()),i=0;i{var e,i;if(!t)return this;for(e in t)"children"!==e&&(i="set"+u._capitalize(e),u._isFunction(this[i])?this[i](t[e]):this._setAttr(e,t[e]))}),this}isListening(){return this._getCache("listening",this._isListening)}_isListening(t){if(!this.listening())return!1;const e=this.getParent();return!e||e===t||this===t||e._isListening(t)}isVisible(){return this._getCache("visible",this._isVisible)}_isVisible(t){if(!this.visible())return!1;const e=this.getParent();return!e||e===t||this===t||e._isVisible(t)}shouldDrawHit(t,e=!1){if(t)return this._isVisible(t)&&this._isListening(t);var i=this.getLayer(),r=!1;E._dragElements.forEach(t=>{"dragging"===t.dragStatus&&("Stage"===t.node.nodeType||t.node.getLayer()===i)&&(r=!0)});var n=!e&&!a.hitOnDragEnabled&&r;return this.isListening()&&this.isVisible()&&!n}show(){return this.visible(!0),this}hide(){return this.visible(!1),this}getZIndex(){return this.index||0}getAbsoluteZIndex(){var t,e,i,r,a=this.getDepth(),n=this,s=0;return"Stage"!==n.nodeType&&function o(h){for(t=[],e=h.length,i=0;i0&&t[0].getDepth()<=a&&o(t)}(n.getStage().getChildren()),s}getDepth(){for(var t=0,e=this.parent;e;)t++,e=e.parent;return t}_batchTransformChanges(t){this._batchingTransformChange=!0,t(),this._batchingTransformChange=!1,this._needClearTransformCache&&(this._clearCache("transform"),this._clearSelfAndDescendantCache("absoluteTransform",!0)),this._needClearTransformCache=!1}setPosition(t){return this._batchTransformChanges(()=>{this.x(t.x),this.y(t.y)}),this}getPosition(){return{x:this.x(),y:this.y()}}getAbsolutePosition(t){let e=!1,i=this.parent;for(;i;){if(i.isCached()){e=!0;break}i=i.parent}e&&!t&&(t=!0);var r=this.getAbsoluteTransform(t).getMatrix(),a=new o,n=this.offset();return a.m=r.slice(),a.translate(n.x,n.y),a.getTranslation()}setAbsolutePosition(t){var e=this._clearTransform();this.attrs.x=e.x,this.attrs.y=e.y,delete e.x,delete e.y,this._clearCache("transform");var i=this._getAbsoluteTransform().copy();return i.invert(),i.translate(t.x,t.y),t={x:this.attrs.x+i.getTranslation().x,y:this.attrs.y+i.getTranslation().y},this._setTransform(e),this.setPosition({x:t.x,y:t.y}),this._clearCache("transform"),this._clearSelfAndDescendantCache("absoluteTransform"),this}_setTransform(t){var e;for(e in t)this.attrs[e]=t[e]}_clearTransform(){var t={x:this.x(),y:this.y(),rotation:this.rotation(),scaleX:this.scaleX(),scaleY:this.scaleY(),offsetX:this.offsetX(),offsetY:this.offsetY(),skewX:this.skewX(),skewY:this.skewY()};return this.attrs.x=0,this.attrs.y=0,this.attrs.rotation=0,this.attrs.scaleX=1,this.attrs.scaleY=1,this.attrs.offsetX=0,this.attrs.offsetY=0,this.attrs.skewX=0,this.attrs.skewY=0,t}move(t){var e=t.x,i=t.y,r=this.x(),a=this.y();return void 0!==e&&(r+=e),void 0!==i&&(a+=i),this.setPosition({x:r,y:a}),this}_eachAncestorReverse(t,e){var i,r,a=[],n=this.getParent();if(!e||e._id!==this._id){for(a.unshift(this);n&&(!e||n._id!==e._id);)a.unshift(n),n=n.parent;for(i=a.length,r=0;r0&&(this.parent.children.splice(t,1),this.parent.children.splice(t-1,0,this),this.parent._setChildrenIndices(),!0)}moveToBottom(){if(!this.parent)return u.warn("Node has no parent. moveToBottom function is ignored."),!1;var t=this.index;return t>0&&(this.parent.children.splice(t,1),this.parent.children.unshift(this),this.parent._setChildrenIndices(),!0)}setZIndex(t){if(!this.parent)return u.warn("Node has no parent. zIndex parameter is ignored."),this;(t<0||t>=this.parent.children.length)&&u.warn("Unexpected value "+t+" for zIndex property. zIndex is just index of a node in children of its parent. Expected value is from 0 to "+(this.parent.children.length-1)+".");var e=this.index;return this.parent.children.splice(e,1),this.parent.children.splice(t,0,this),this.parent._setChildrenIndices(),this}getAbsoluteOpacity(){return this._getCache("absoluteOpacity",this._getAbsoluteOpacity)}_getAbsoluteOpacity(){var t=this.opacity(),e=this.getParent();return e&&!e._isUnderCache&&(t*=e.getAbsoluteOpacity()),t}moveTo(t){return this.getParent()!==t&&(this._remove(),t.add(this)),this}toObject(){var t,e,i,r,a={},n=this.getAttrs();for(t in a.attrs={},n)e=n[t],u.isObject(e)&&!u._isPlainObject(e)&&!u._isArray(e)||(i="function"==typeof this[t]&&this[t],delete n[t],r=i?i.call(this):null,n[t]=e,r!==e&&(a.attrs[t]=e));return a.className=this.getClassName(),u._prepareToStringify(a)}toJSON(){return JSON.stringify(this.toObject())}getParent(){return this.parent}findAncestors(t,e,i){var r=[];e&&this._isMatch(t)&&r.push(this);for(var a=this.parent;a;){if(a===i)return r;a._isMatch(t)&&r.push(a),a=a.parent}return r}isAncestorOf(t){return!1}findAncestor(t,e,i){return this.findAncestors(t,e,i)[0]}_isMatch(t){if(!t)return!1;if("function"==typeof t)return t(this);var e,i,r=t.replace(/ /g,"").split(","),a=r.length;for(e=0;e=0)&&!this.isDragging()){var e=!1;E._dragElements.forEach(t=>{this.isAncestorOf(t.node)&&(e=!0)}),e||this._createDragElement(t)}}))}_dragChange(){if(this.attrs.draggable)this._listenDrag();else{if(this._dragCleanup(),!this.getStage())return;const t=E._dragElements.get(this._id),e=t&&"dragging"===t.dragStatus,i=t&&"ready"===t.dragStatus;e?this.stopDrag():i&&E._dragElements.delete(this._id)}}_dragCleanup(){this.off("mousedown.konva"),this.off("touchstart.konva")}static create(t,e){return u._isString(t)&&(t=JSON.parse(t)),this._createNode(t,e)}static _createNode(t,e){var i,r,a,s=z.prototype.getClassName.call(t),o=t.children;e&&(t.attrs.container=e),n[s]||(u.warn('Can not find a node with class name "'+s+'". Fallback to "Shape".'),s="Shape");if(i=new(0,n[s])(t.attrs),o)for(r=o.length,a=0;a0}removeChildren(){return this.getChildren().forEach(t=>{t.parent=null,t.index=0,t.remove()}),this.children=[],this}destroyChildren(){return this.getChildren().forEach(t=>{t.parent=null,t.index=0,t.destroy()}),this.children=[],this}add(...t){if(arguments.length>1){for(var e=0;e0?e[0]:void 0}_generalFind(t,e){var i=[];return this._descendants(r=>{const a=r._isMatch(t);return a&&i.push(r),!(!a||!e)}),i}_descendants(t){let e=!1;const i=this.getChildren();for(const r of i){if(e=t(r),e)return!0;if(r.hasChildren()&&(e=r._descendants(t),e))return!0}return!1}toObject(){var t=z.prototype.toObject.call(this);return t.children=[],this.getChildren().forEach(e=>{t.children.push(e.toObject())}),t}isAncestorOf(t){for(var e=t.getParent();e;){if(e._id===this._id)return!0;e=e.getParent()}return!1}clone(t){var e=z.prototype.clone.call(this,t);return this.getChildren().forEach((function(t){e.add(t.clone())})),e}getAllIntersections(t){var e=[];return this.find("Shape").forEach((function(i){i.isVisible()&&i.intersects(t)&&e.push(i)})),e}_clearSelfAndDescendantCache(t,e){var i;super._clearSelfAndDescendantCache(t,e),this.isCached()||null===(i=this.children)||void 0===i||i.forEach((function(i){i._clearSelfAndDescendantCache(t,e)}))}_setChildrenIndices(){var t;null===(t=this.children)||void 0===t||t.forEach((function(t,e){t.index=e}))}drawScene(t,e){var i=this.getLayer(),r=t||i&&i.getCanvas(),a=r&&r.getContext(),n=this._getCanvasCache(),s=n&&n.scene,o=r&&r.isCache;if(!this.isVisible()&&!o)return this;if(s){a.save();var h=this.getAbsoluteTransform(e).getMatrix();a.transform(h[0],h[1],h[2],h[3],h[4],h[5]),this._drawCachedSceneCanvas(a),a.restore()}else this._drawChildren("drawScene",r,e);return this}drawHit(t,e){if(!this.shouldDrawHit(e))return this;var i=this.getLayer(),r=t||i&&i.hitCanvas,a=r&&r.getContext(),n=this._getCanvasCache();if(n&&n.hit){a.save();var s=this.getAbsoluteTransform(e).getMatrix();a.transform(s[0],s[1],s[2],s[3],s[4],s[5]),this._drawCachedHitCanvas(a),a.restore()}else this._drawChildren("drawHit",r,e);return this}_drawChildren(t,e,i){var r,a=e&&e.getContext(),n=this.clipWidth(),s=this.clipHeight(),o=this.clipFunc(),h=n&&s||o;const l=i===this;if(h){a.save();var d=this.getAbsoluteTransform(i),c=d.getMatrix();if(a.transform(c[0],c[1],c[2],c[3],c[4],c[5]),a.beginPath(),o)o.call(this,a,this);else{var g=this.clipX(),u=this.clipY();a.rect(g,u,n,s)}a.clip(),c=d.copy().invert().getMatrix(),a.transform(c[0],c[1],c[2],c[3],c[4],c[5])}var f=!l&&"source-over"!==this.globalCompositeOperation()&&"drawScene"===t;f&&(a.save(),a._applyGlobalCompositeOperation(this)),null===(r=this.children)||void 0===r||r.forEach((function(r){r[t](e,i)})),f&&a.restore(),h&&a.restore()}getClientRect(t){var e,i,r,a,n,s=(t=t||{}).skipTransform,o=t.relativeTo,h={x:1/0,y:1/0,width:0,height:0},l=this;null===(e=this.children)||void 0===e||e.forEach((function(e){if(e.visible()){var s=e.getClientRect({relativeTo:l,skipShadow:t.skipShadow,skipStroke:t.skipStroke});0===s.width&&0===s.height||(void 0===i?(i=s.x,r=s.y,a=s.x+s.width,n=s.y+s.height):(i=Math.min(i,s.x),r=Math.min(r,s.y),a=Math.max(a,s.x+s.width),n=Math.max(n,s.y+s.height)))}}));for(var d=this.find("Shape"),c=!1,g=0;g{tt(this.attrs)}),this._checkVisibility()}_validateAdd(t){const e="Layer"===t.getType(),i="FastLayer"===t.getType();e||i||u.throw("You may only add layers to the stage.")}_checkVisibility(){if(!this.content)return;const t=this.visible()?"":"none";this.content.style.display=t}setContainer(t){if("string"==typeof t){if("."===t.charAt(0)){var e=t.slice(1);t=document.getElementsByClassName(e)[0]}else{var i;i="#"!==t.charAt(0)?t:t.slice(1),t=document.getElementById(i)}if(!t)throw"Can not find container in document with id "+i}return this._setAttr("container",t),this.content&&(this.content.parentElement&&this.content.parentElement.removeChild(this.content),t.appendChild(this.content)),this}shouldDrawHit(){return!0}clear(){var t,e=this.children,i=e.length;for(t=0;t-1&&$.splice(e,1),this}getPointerPosition(){const t=this._pointerPositions[0]||this._changedPointerPositions[0];return t?{x:t.x,y:t.y}:(u.warn("Pointer position is missing and not registered by the stage. Looks like it is outside of the stage container. You can set it manually from event: stage.setPointersPositions(event);"),null)}_getPointerById(t){return this._pointerPositions.find(e=>e.id===t)}getPointersPositions(){return this._pointerPositions}getStage(){return this}getContent(){return this.content}_toKonvaCanvas(t){(t=t||{}).x=t.x||0,t.y=t.y||0,t.width=t.width||this.width(),t.height=t.height||this.height();var e=new M({width:t.width,height:t.height,pixelRatio:t.pixelRatio||1}),i=e.getContext()._context,r=this.children;return(t.x||t.y)&&i.translate(-1*t.x,-1*t.y),r.forEach((function(e){if(e.isVisible()){var r=e._toKonvaCanvas(t);i.drawImage(r._canvas,t.x,t.y,r.getWidth()/r.getPixelRatio(),r.getHeight()/r.getPixelRatio())}})),e}getIntersection(t,e){if(!t)return null;var i,r=this.children;for(i=r.length-1;i>=0;i--){const a=r[i].getIntersection(t,e);if(a)return a}return null}_resizeDOM(){var t=this.width(),e=this.height();this.content&&(this.content.style.width=t+"px",this.content.style.height=e+"px"),this.bufferCanvas.setSize(t,e),this.bufferHitCanvas.setSize(t,e),this.children.forEach(i=>{i.setSize({width:t,height:e}),i.draw()})}add(t,...e){if(arguments.length>1){for(var i=0;i5&&u.warn("The stage has "+r+" layers. Recommended maximum number of layers is 3-5. Adding more layers into the stage may drop the performance. Rethink your tree structure, you can use Konva.Group."),t.setSize({width:this.width(),height:this.height()}),t.draw(),a.isBrowser&&this.content.appendChild(t.canvas._canvas),this}getParent(){return null}getLayer(){return null}hasPointerCapture(t){return q(t,this)}setPointerCapture(t){K(t,this)}releaseCapture(t){V(t)}getLayers(){return this.children}_bindContentEvents(){if(a.isBrowser)for(var t=0;t{var r=this.getIntersection(i);a.listenClickTap=!0,E.justDragged=!1;r&&r.isListening()&&(a.captureTouchEventsEnabled&&r.setPointerCapture(i.id),this.tapStartShape=r,r._fireAndBubble("touchstart",{evt:t,pointerId:i.id},this),e=!0,r.isListening()&&r.preventDefault()&&t.cancelable&&t.preventDefault())}),e||this._fire("touchstart",{evt:t,target:this,currentTarget:this,pointerId:this._changedPointerPositions[0].id}),this._fire("contentTouchstart",{evt:t})}_touchmove(t){if(this.setPointersPositions(t),!E.isDragging||a.hitOnDragEnabled){var e=!1,i={};this._changedPointerPositions.forEach(r=>{const a=j(r.id)||this.getIntersection(r);a&&a.isListening()&&(i[a._id]||(i[a._id]=!0,a._fireAndBubble("touchmove",{evt:t,pointerId:r.id}),e=!0,a.isListening()&&a.preventDefault()&&t.cancelable&&t.preventDefault()))}),e||this._fire("touchmove",{evt:t,target:this,currentTarget:this,pointerId:this._changedPointerPositions[0].id}),this._fire("contentTouchmove",{evt:t})}E.isDragging&&E.node.preventDefault()&&t.cancelable&&t.preventDefault()}_touchend(t){this.setPointersPositions(t);var e=this.tapEndShape,i=!1;a.inDblClickWindow?(i=!0,clearTimeout(this.dblTimeout)):E.justDragged||(a.inDblClickWindow=!0,clearTimeout(this.dblTimeout)),this.dblTimeout=setTimeout((function(){a.inDblClickWindow=!1}),a.dblClickWindow);var r=!1,n={},s=!1,o=!1;this._changedPointerPositions.forEach(h=>{var l=j(h.id)||this.getIntersection(h);l&&l.releaseCapture(h.id);l&&l.isListening()&&(n[l._id]||(n[l._id]=!0,this.tapEndShape=l,l._fireAndBubble("touchend",{evt:t,pointerId:h.id}),r=!0,a.listenClickTap&&l===this.tapStartShape&&(s=!0,l._fireAndBubble("tap",{evt:t,pointerId:h.id}),i&&e&&e===l&&(o=!0,l._fireAndBubble("dbltap",{evt:t,pointerId:h.id}))),l.isListening()&&l.preventDefault()&&t.cancelable&&t.preventDefault()))}),r||this._fire("touchend",{evt:t,target:this,currentTarget:this,pointerId:this._changedPointerPositions[0].id}),a.listenClickTap&&!s&&(this.tapEndShape=null,this._fire("tap",{evt:t,target:this,currentTarget:this,pointerId:this._changedPointerPositions[0].id})),i&&!o&&this._fire("dbltap",{evt:t,target:this,currentTarget:this,pointerId:this._changedPointerPositions[0].id}),this._fire("contentTouchend",{evt:t}),a.listenClickTap&&(this._fire("contentTap",{evt:t}),i&&this._fire("contentDbltap",{evt:t})),this.preventDefault()&&t.cancelable&&t.preventDefault(),a.listenClickTap=!1}_wheel(t){this.setPointersPositions(t);var e=this.getIntersection(this.getPointerPosition());e&&e.isListening()?e._fireAndBubble("wheel",{evt:t}):this._fire("wheel",{evt:t,target:this,currentTarget:this}),this._fire("contentWheel",{evt:t})}_pointerdown(t){if(!a._pointerEventsEnabled)return;this.setPointersPositions(t);const e=j(t.pointerId)||this.getIntersection(this.getPointerPosition());e&&e._fireAndBubble("pointerdown",U(t))}_pointermove(t){if(!a._pointerEventsEnabled)return;this.setPointersPositions(t);const e=j(t.pointerId)||this.getIntersection(this.getPointerPosition());e&&e._fireAndBubble("pointermove",U(t))}_pointerup(t){if(!a._pointerEventsEnabled)return;this.setPointersPositions(t);const e=j(t.pointerId)||this.getIntersection(this.getPointerPosition());e&&e._fireAndBubble("pointerup",U(t)),V(t.pointerId)}_pointercancel(t){if(!a._pointerEventsEnabled)return;this.setPointersPositions(t);const e=j(t.pointerId)||this.getIntersection(this.getPointerPosition());e&&e._fireAndBubble("pointerup",U(t)),V(t.pointerId)}_lostpointercapture(t){V(t.pointerId)}setPointersPositions(t){var e=this._getContentPosition(),i=null,r=null;void 0!==(t=t||window.event).touches?(this._pointerPositions=[],this._changedPointerPositions=[],Array.prototype.forEach.call(t.touches,t=>{this._pointerPositions.push({id:t.identifier,x:(t.clientX-e.left)/e.scaleX,y:(t.clientY-e.top)/e.scaleY})}),Array.prototype.forEach.call(t.changedTouches||t.touches,t=>{this._changedPointerPositions.push({id:t.identifier,x:(t.clientX-e.left)/e.scaleX,y:(t.clientY-e.top)/e.scaleY})})):(i=(t.clientX-e.left)/e.scaleX,r=(t.clientY-e.top)/e.scaleY,this.pointerPos={x:i,y:r},this._pointerPositions=[{x:i,y:r,id:u._getFirstPointerId(t)}],this._changedPointerPositions=[{x:i,y:r,id:u._getFirstPointerId(t)}])}_setPointerPosition(t){u.warn('Method _setPointerPosition is deprecated. Use "stage.setPointersPositions(event)" instead.'),this.setPointersPositions(t)}_getContentPosition(){if(!this.content||!this.content.getBoundingClientRect)return{top:0,left:0,scaleX:1,scaleY:1};var t=this.content.getBoundingClientRect();return{top:t.top,left:t.left,scaleX:t.width/this.content.clientWidth||1,scaleY:t.height/this.content.clientHeight||1}}_buildDOM(){if(this.bufferCanvas=new M({width:this.width(),height:this.height()}),this.bufferHitCanvas=new G({pixelRatio:1,width:this.width(),height:this.height()}),a.isBrowser){var t=this.container();if(!t)throw"Stage has no container. A container is required.";t.innerHTML="",this.content=document.createElement("div"),this.content.style.position="relative",this.content.style.userSelect="none",this.content.className="konvajs-content",this.content.setAttribute("role","presentation"),t.appendChild(this.content),this._resizeDOM()}}cache(){return u.warn("Cache function is not allowed for stage. You may use cache only for layers, groups and shapes."),this}clearCache(){return this}batchDraw(){return this.children.forEach((function(t){t.batchDraw()})),this}}et.prototype.nodeType="Stage",s(et),S.addGetterSetter(et,"container");let it;function rt(){return it||(it=u.createCanvasElement().getContext("2d"),it)}const at={};class nt extends z{constructor(t){let e;for(super(t);e=u.getRandomColor(),!e||e in at;);this.colorKey=e,at[e]=this}getContext(){return this.getLayer().getContext()}getCanvas(){return this.getLayer().getCanvas()}getSceneFunc(){return this.attrs.sceneFunc||this._sceneFunc}getHitFunc(){return this.attrs.hitFunc||this._hitFunc}hasShadow(){return this._getCache("hasShadow",this._hasShadow)}_hasShadow(){return this.shadowEnabled()&&0!==this.shadowOpacity()&&!!(this.shadowColor()||this.shadowBlur()||this.shadowOffsetX()||this.shadowOffsetY())}_getFillPattern(){return this._getCache("patternImage",this.__getFillPattern)}__getFillPattern(){if(this.fillPatternImage()){const t=rt().createPattern(this.fillPatternImage(),this.fillPatternRepeat()||"repeat");return t&&t.setTransform&&t.setTransform({a:this.fillPatternScaleX(),b:0,c:0,d:this.fillPatternScaleY(),e:0,f:0}),t}}_getLinearGradient(){return this._getCache("linearGradient",this.__getLinearGradient)}__getLinearGradient(){var t=this.fillLinearGradientColorStops();if(t){for(var e=rt(),i=this.fillLinearGradientStartPoint(),r=this.fillLinearGradientEndPoint(),a=e.createLinearGradient(i.x,i.y,r.x,r.y),n=0;nthis.fillEnabled()&&!!(this.fill()||this.fillPatternImage()||this.fillLinearGradientColorStops()||this.fillRadialGradientColorStops()))}hasStroke(){return this._calculate("hasStroke",["strokeEnabled","strokeWidth","stroke","strokeLinearGradientColorStops"],()=>this.strokeEnabled()&&this.strokeWidth()&&!(!this.stroke()&&!this.strokeLinearGradientColorStops()))}hasHitStroke(){const t=this.hitStrokeWidth();return"auto"===t?this.hasStroke():this.strokeEnabled()&&!!t}intersects(t){var e=this.getStage().bufferHitCanvas;return e.getContext().clear(),this.drawHit(e,null,!0),e.context.getImageData(Math.round(t.x),Math.round(t.y),1,1).data[3]>0}destroy(){return z.prototype.destroy.call(this),delete at[this.colorKey],delete this.colorKey,this}_useBufferCanvas(t){var e;if(!this.getStage())return!1;if(!(null===(e=this.attrs.perfectDrawEnabled)||void 0===e||e))return!1;const i=t||this.hasFill(),r=this.hasStroke(),a=1!==this.getAbsoluteOpacity();if(i&&r&&a)return!0;const n=this.hasShadow(),s=this.shadowForStrokeEnabled();return!!(i&&r&&n&&s)}setStrokeHitEnabled(t){u.warn("strokeHitEnabled property is deprecated. Please use hitStrokeWidth instead."),t?this.hitStrokeWidth("auto"):this.hitStrokeWidth(0)}getStrokeHitEnabled(){return 0!==this.hitStrokeWidth()}getSelfRect(){var t=this.size();return{x:this._centroid?-t.width/2:0,y:this._centroid?-t.height/2:0,width:t.width,height:t.height}}getClientRect(t={}){const e=t.skipTransform,i=t.relativeTo,r=this.getSelfRect(),a=!t.skipStroke&&this.hasStroke()&&this.strokeWidth()||0,n=r.width+a,s=r.height+a,o=!t.skipShadow&&this.hasShadow(),h=o?this.shadowOffsetX():0,l=o?this.shadowOffsetY():0,d=n+Math.abs(h),c=s+Math.abs(l),g=o&&this.shadowBlur()||0,u=d+2*g,f=c+2*g;let p=0;Math.round(a/2)!==a/2&&(p=1);const v={width:u+p,height:f+p,x:-Math.round(a/2+g)+Math.min(h,0)+r.x,y:-Math.round(a/2+g)+Math.min(l,0)+r.y};return e?v:this._transformedRect(v,i)}drawScene(t,e){var i,r,a=this.getLayer(),n=t||a.getCanvas(),s=n.getContext(),o=this._getCanvasCache(),h=this.getSceneFunc(),l=this.hasShadow(),d=n.isCache,c=n.isCache,g=e===this;if(!this.isVisible()&&!d)return this;if(o){s.save();var u=this.getAbsoluteTransform(e).getMatrix();return s.transform(u[0],u[1],u[2],u[3],u[4],u[5]),this._drawCachedSceneCanvas(s),s.restore(),this}if(!h)return this;if(s.save(),this._useBufferCanvas()&&!c){(r=(i=this.getStage().bufferCanvas).getContext()).clear(),r.save(),r._applyLineJoin(this);var f=this.getAbsoluteTransform(e).getMatrix();r.transform(f[0],f[1],f[2],f[3],f[4],f[5]),h.call(this,r,this),r.restore();var p=i.pixelRatio;l&&s._applyShadow(this),s._applyOpacity(this),s._applyGlobalCompositeOperation(this),s.drawImage(i._canvas,0,0,i.width/p,i.height/p)}else{if(s._applyLineJoin(this),!g){f=this.getAbsoluteTransform(e).getMatrix();s.transform(f[0],f[1],f[2],f[3],f[4],f[5]),s._applyOpacity(this),s._applyGlobalCompositeOperation(this)}l&&s._applyShadow(this),h.call(this,s,this)}return s.restore(),this}drawHit(t,e,i=!1){if(!this.shouldDrawHit(e,i))return this;var r=this.getLayer(),a=t||r.hitCanvas,n=a&&a.getContext(),s=this.hitFunc()||this.sceneFunc(),o=this._getCanvasCache(),h=o&&o.hit;if(this.colorKey||u.warn("Looks like your canvas has a destroyed shape in it. Do not reuse shape after you destroyed it. If you want to reuse shape you should call remove() instead of destroy()"),h){n.save();var l=this.getAbsoluteTransform(e).getMatrix();return n.transform(l[0],l[1],l[2],l[3],l[4],l[5]),this._drawCachedHitCanvas(n),n.restore(),this}if(!s)return this;n.save(),n._applyLineJoin(this);if(!(this===e)){var d=this.getAbsoluteTransform(e).getMatrix();n.transform(d[0],d[1],d[2],d[3],d[4],d[5])}return s.call(this,n,this),n.restore(),this}drawHitFromCache(t=0){var e,i,r,a,n,s=this._getCanvasCache(),o=this._getCachedSceneCanvas(),h=s.hit,l=h.getContext(),d=h.getWidth(),c=h.getHeight();l.clear(),l.drawImage(o._canvas,0,0,d,c);try{for(r=(i=(e=l.getImageData(0,0,d,c)).data).length,a=u._hexToRgb(this.colorKey),n=0;nt?(i[n]=a.r,i[n+1]=a.g,i[n+2]=a.b,i[n+3]=255):i[n+3]=0;l.putImageData(e,0,0)}catch(t){u.error("Unable to draw hit graph from cached scene canvas. "+t.message)}return this}hasPointerCapture(t){return q(t,this)}setPointerCapture(t){K(t,this)}releaseCapture(t){V(t)}}nt.prototype._fillFunc=function(t){t.fill()},nt.prototype._strokeFunc=function(t){t.stroke()},nt.prototype._fillFuncHit=function(t){t.fill()},nt.prototype._strokeFuncHit=function(t){t.stroke()},nt.prototype._centroid=!1,nt.prototype.nodeType="Shape",s(nt),nt.prototype.eventListeners={},nt.prototype.on.call(nt.prototype,"shadowColorChange.konva shadowBlurChange.konva shadowOffsetChange.konva shadowOpacityChange.konva shadowEnabledChange.konva",(function(){this._clearCache("hasShadow")})),nt.prototype.on.call(nt.prototype,"shadowColorChange.konva shadowOpacityChange.konva shadowEnabledChange.konva",(function(){this._clearCache("shadowRGBA")})),nt.prototype.on.call(nt.prototype,"fillPriorityChange.konva fillPatternImageChange.konva fillPatternRepeatChange.konva fillPatternScaleXChange.konva fillPatternScaleYChange.konva",(function(){this._clearCache("patternImage")})),nt.prototype.on.call(nt.prototype,"fillPriorityChange.konva fillLinearGradientColorStopsChange.konva fillLinearGradientStartPointXChange.konva fillLinearGradientStartPointYChange.konva fillLinearGradientEndPointXChange.konva fillLinearGradientEndPointYChange.konva",(function(){this._clearCache("linearGradient")})),nt.prototype.on.call(nt.prototype,"fillPriorityChange.konva fillRadialGradientColorStopsChange.konva fillRadialGradientStartPointXChange.konva fillRadialGradientStartPointYChange.konva fillRadialGradientEndPointXChange.konva fillRadialGradientEndPointYChange.konva fillRadialGradientStartRadiusChange.konva fillRadialGradientEndRadiusChange.konva",(function(){this._clearCache("radialGradient")})),S.addGetterSetter(nt,"stroke",void 0,x()),S.addGetterSetter(nt,"strokeWidth",2,v()),S.addGetterSetter(nt,"fillAfterStrokeEnabled",!1),S.addGetterSetter(nt,"hitStrokeWidth","auto",_()),S.addGetterSetter(nt,"strokeHitEnabled",!0,b()),S.addGetterSetter(nt,"perfectDrawEnabled",!0,b()),S.addGetterSetter(nt,"shadowForStrokeEnabled",!0,b()),S.addGetterSetter(nt,"lineJoin"),S.addGetterSetter(nt,"lineCap"),S.addGetterSetter(nt,"sceneFunc"),S.addGetterSetter(nt,"hitFunc"),S.addGetterSetter(nt,"dash"),S.addGetterSetter(nt,"dashOffset",0,v()),S.addGetterSetter(nt,"shadowColor",void 0,y()),S.addGetterSetter(nt,"shadowBlur",0,v()),S.addGetterSetter(nt,"shadowOpacity",1,v()),S.addComponentsGetterSetter(nt,"shadowOffset",["x","y"]),S.addGetterSetter(nt,"shadowOffsetX",0,v()),S.addGetterSetter(nt,"shadowOffsetY",0,v()),S.addGetterSetter(nt,"fillPatternImage"),S.addGetterSetter(nt,"fill",void 0,x()),S.addGetterSetter(nt,"fillPatternX",0,v()),S.addGetterSetter(nt,"fillPatternY",0,v()),S.addGetterSetter(nt,"fillLinearGradientColorStops"),S.addGetterSetter(nt,"strokeLinearGradientColorStops"),S.addGetterSetter(nt,"fillRadialGradientStartRadius",0),S.addGetterSetter(nt,"fillRadialGradientEndRadius",0),S.addGetterSetter(nt,"fillRadialGradientColorStops"),S.addGetterSetter(nt,"fillPatternRepeat","repeat"),S.addGetterSetter(nt,"fillEnabled",!0),S.addGetterSetter(nt,"strokeEnabled",!0),S.addGetterSetter(nt,"shadowEnabled",!0),S.addGetterSetter(nt,"dashEnabled",!0),S.addGetterSetter(nt,"strokeScaleEnabled",!0),S.addGetterSetter(nt,"fillPriority","color"),S.addComponentsGetterSetter(nt,"fillPatternOffset",["x","y"]),S.addGetterSetter(nt,"fillPatternOffsetX",0,v()),S.addGetterSetter(nt,"fillPatternOffsetY",0,v()),S.addComponentsGetterSetter(nt,"fillPatternScale",["x","y"]),S.addGetterSetter(nt,"fillPatternScaleX",1,v()),S.addGetterSetter(nt,"fillPatternScaleY",1,v()),S.addComponentsGetterSetter(nt,"fillLinearGradientStartPoint",["x","y"]),S.addComponentsGetterSetter(nt,"strokeLinearGradientStartPoint",["x","y"]),S.addGetterSetter(nt,"fillLinearGradientStartPointX",0),S.addGetterSetter(nt,"strokeLinearGradientStartPointX",0),S.addGetterSetter(nt,"fillLinearGradientStartPointY",0),S.addGetterSetter(nt,"strokeLinearGradientStartPointY",0),S.addComponentsGetterSetter(nt,"fillLinearGradientEndPoint",["x","y"]),S.addComponentsGetterSetter(nt,"strokeLinearGradientEndPoint",["x","y"]),S.addGetterSetter(nt,"fillLinearGradientEndPointX",0),S.addGetterSetter(nt,"strokeLinearGradientEndPointX",0),S.addGetterSetter(nt,"fillLinearGradientEndPointY",0),S.addGetterSetter(nt,"strokeLinearGradientEndPointY",0),S.addComponentsGetterSetter(nt,"fillRadialGradientStartPoint",["x","y"]),S.addGetterSetter(nt,"fillRadialGradientStartPointX",0),S.addGetterSetter(nt,"fillRadialGradientStartPointY",0),S.addComponentsGetterSetter(nt,"fillRadialGradientEndPoint",["x","y"]),S.addGetterSetter(nt,"fillRadialGradientEndPointX",0),S.addGetterSetter(nt,"fillRadialGradientEndPointY",0),S.addGetterSetter(nt,"fillPatternRotation",0),S.backCompat(nt,{dashArray:"dash",getDashArray:"getDash",setDashArray:"getDash",drawFunc:"sceneFunc",getDrawFunc:"getSceneFunc",setDrawFunc:"setSceneFunc",drawHitFunc:"hitFunc",getDrawHitFunc:"getHitFunc",setDrawHitFunc:"setHitFunc"});var st=[{x:0,y:0},{x:-1,y:-1},{x:1,y:-1},{x:1,y:1},{x:-1,y:1}],ot=st.length;class ht extends H{constructor(t){super(t),this.canvas=new M,this.hitCanvas=new G({pixelRatio:1}),this._waitingForDraw=!1,this.on("visibleChange.konva",this._checkVisibility),this._checkVisibility(),this.on("imageSmoothingEnabledChange.konva",this._setSmoothEnabled),this._setSmoothEnabled()}createPNGStream(){return this.canvas._canvas.createPNGStream()}getCanvas(){return this.canvas}getCanvasElement(){return this.canvas._canvas}getHitCanvas(){return this.hitCanvas}getContext(){return this.getCanvas().getContext()}clear(t){return this.getContext().clear(t),this.getHitCanvas().getContext().clear(t),this}setZIndex(t){super.setZIndex(t);var e=this.getStage();return e&&(e.content.removeChild(this.getCanvas()._canvas),t{this.draw(),this._waitingForDraw=!1})),this}getIntersection(t,e){if(!this.isListening()||!this.isVisible())return null;for(var i=1,r=!1;;){for(let a=0;a0?{antialiased:!0}:{}}drawScene(t,e){var i=this.getLayer(),r=t||i&&i.getCanvas();return this._fire("beforeDraw",{node:this}),this.clearBeforeDraw()&&r.getContext().clear(),H.prototype.drawScene.call(this,r,e),this._fire("draw",{node:this}),this}drawHit(t,e){var i=this.getLayer(),r=t||i&&i.hitCanvas;return i&&i.clearBeforeDraw()&&i.getHitCanvas().getContext().clear(),H.prototype.drawHit.call(this,r,e),this}enableHitGraph(){return this.hitGraphEnabled(!0),this}disableHitGraph(){return this.hitGraphEnabled(!1),this}setHitGraphEnabled(t){u.warn("hitGraphEnabled method is deprecated. Please use layer.listening() instead."),this.listening(t)}getHitGraphEnabled(t){return u.warn("hitGraphEnabled method is deprecated. Please use layer.listening() instead."),this.listening()}toggleHitCanvas(){if(this.parent){var t=this.parent;!!this.hitCanvas._canvas.parentNode?t.content.removeChild(this.hitCanvas._canvas):t.content.appendChild(this.hitCanvas._canvas)}}}ht.prototype.nodeType="Layer",s(ht),S.addGetterSetter(ht,"imageSmoothingEnabled",!0),S.addGetterSetter(ht,"clearBeforeDraw",!0),S.addGetterSetter(ht,"hitGraphEnabled",!0,b());class lt extends ht{constructor(t){super(t),this.listening(!1),u.warn('Konva.Fast layer is deprecated. Please use "new Konva.Layer({ listening: false })" instead.')}}lt.prototype.nodeType="FastLayer",s(lt);class dt extends H{_validateAdd(t){var e=t.getType();"Group"!==e&&"Shape"!==e&&u.throw("You may only add groups and shapes to groups.")}}dt.prototype.nodeType="Group",s(dt);var ct=r.performance&&r.performance.now?function(){return r.performance.now()}:function(){return(new Date).getTime()};class gt{constructor(t,e){this.id=gt.animIdCounter++,this.frame={time:0,timeDiff:0,lastTime:ct(),frameRate:0},this.func=t,this.setLayers(e)}setLayers(t){var e=[];return e=t?t.length>0?t:[t]:[],this.layers=e,this}getLayers(){return this.layers}addLayer(t){var e,i=this.layers,r=i.length;for(e=0;ethis.duration?this.yoyo?(this._time=this.duration,this.reverse()):this.finish():t<0?this.yoyo?(this._time=0,this.play()):this.reset():(this._time=t,this.update())}getTime(){return this._time}setPosition(t){this.prevPos=this._pos,this.propFunc(t),this._pos=t}getPosition(t){return void 0===t&&(t=this._time),this.func(t,this.begin,this._change,this.duration)}play(){this.state=2,this._startTime=this.getTimer()-this._time,this.onEnterFrame(),this.fire("onPlay")}reverse(){this.state=3,this._time=this.duration-this._time,this._startTime=this.getTimer()-this._time,this.onEnterFrame(),this.fire("onReverse")}seek(t){this.pause(),this._time=t,this.update(),this.fire("onSeek")}reset(){this.pause(),this._time=0,this.update(),this.fire("onReset")}finish(){this.pause(),this._time=this.duration,this.update(),this.fire("onFinish")}update(){this.setPosition(this.getPosition(this._time)),this.fire("onUpdate")}onEnterFrame(){var t=this.getTimer()-this._startTime;2===this.state?this.setTime(t):3===this.state&&this.setTime(this.duration-t)}pause(){this.state=1,this.fire("onPause")}getTimer(){return(new Date).getTime()}}class mt{constructor(t){var e,i,r=this,n=t.node,s=n._id,o=t.easing||_t.Linear,h=!!t.yoyo;e=void 0===t.duration?.3:0===t.duration?.001:t.duration,this.node=n,this._id=ft++;var l=n.getLayer()||(n instanceof a.Stage?n.getLayers():null);for(i in l||u.error("Tween constructor have `node` that is not in a layer. Please add node into layer first."),this.anim=new gt((function(){r.tween.onEnterFrame()}),l),this.tween=new vt(i,(function(t){r._tweenFunc(t)}),o,0,1,1e3*e,h),this._addListeners(),mt.attrs[s]||(mt.attrs[s]={}),mt.attrs[s][this._id]||(mt.attrs[s][this._id]={}),mt.tweens[s]||(mt.tweens[s]={}),t)void 0===ut[i]&&this._addAttr(i,t[i]);this.reset(),this.onFinish=t.onFinish,this.onReset=t.onReset,this.onUpdate=t.onUpdate}_addAttr(t,e){var i,r,a,n,s,o,h,l,d=this.node,c=d._id;if((a=mt.tweens[c][t])&&delete mt.attrs[c][a][t],i=d.getAttr(t),u._isArray(e))if(r=[],s=Math.max(e.length,i.length),"points"===t&&e.length!==i.length&&(e.length>i.length?(h=i,i=u._prepareArrayForTween(i,e,d.closed())):(o=e,e=u._prepareArrayForTween(e,i,d.closed()))),0===t.indexOf("fill"))for(n=0;n{this.anim.start()},this.tween.onReverse=()=>{this.anim.start()},this.tween.onPause=()=>{this.anim.stop()},this.tween.onFinish=()=>{var t=this.node,e=mt.attrs[t._id][this._id];e.points&&e.points.trueEnd&&t.setAttr("points",e.points.trueEnd),this.onFinish&&this.onFinish.call(this)},this.tween.onReset=()=>{var t=this.node,e=mt.attrs[t._id][this._id];e.points&&e.points.trueStart&&t.points(e.points.trueStart),this.onReset&&this.onReset()},this.tween.onUpdate=()=>{this.onUpdate&&this.onUpdate.call(this)}}play(){return this.tween.play(),this}reverse(){return this.tween.reverse(),this}reset(){return this.tween.reset(),this}seek(t){return this.tween.seek(1e3*t),this}pause(){return this.tween.pause(),this}finish(){return this.tween.finish(),this}destroy(){var t,e=this.node._id,i=this._id,r=mt.tweens[e];for(t in this.pause(),r)delete mt.tweens[e][t];delete mt.attrs[e][i]}}mt.attrs={},mt.tweens={},z.prototype.to=function(t){var e=t.onFinish;t.node=this,t.onFinish=function(){this.destroy(),e&&e()},new mt(t).play()};const _t={BackEaseIn(t,e,i,r){var a=1.70158;return i*(t/=r)*t*((a+1)*t-a)+e},BackEaseOut(t,e,i,r){var a=1.70158;return i*((t=t/r-1)*t*((a+1)*t+a)+1)+e},BackEaseInOut(t,e,i,r){var a=1.70158;return(t/=r/2)<1?i/2*(t*t*((1+(a*=1.525))*t-a))+e:i/2*((t-=2)*t*((1+(a*=1.525))*t+a)+2)+e},ElasticEaseIn(t,e,i,r,a,n){var s=0;return 0===t?e:1==(t/=r)?e+i:(n||(n=.3*r),!a||a(t/=r)<1/2.75?i*(7.5625*t*t)+e:t<2/2.75?i*(7.5625*(t-=1.5/2.75)*t+.75)+e:t<2.5/2.75?i*(7.5625*(t-=2.25/2.75)*t+.9375)+e:i*(7.5625*(t-=2.625/2.75)*t+.984375)+e,BounceEaseIn:(t,e,i,r)=>i-_t.BounceEaseOut(r-t,0,i,r)+e,BounceEaseInOut:(t,e,i,r)=>ti*(t/=r)*t+e,EaseOut:(t,e,i,r)=>-i*(t/=r)*(t-2)+e,EaseInOut:(t,e,i,r)=>(t/=r/2)<1?i/2*t*t+e:-i/2*(--t*(t-2)-1)+e,StrongEaseIn:(t,e,i,r)=>i*(t/=r)*t*t*t*t+e,StrongEaseOut:(t,e,i,r)=>i*((t=t/r-1)*t*t*t*t+1)+e,StrongEaseInOut:(t,e,i,r)=>(t/=r/2)<1?i/2*t*t*t*t*t+e:i/2*((t-=2)*t*t*t*t+2)+e,Linear:(t,e,i,r)=>i*t/r+e},yt=u._assign(a,{Util:u,Transform:o,Node:z,ids:R,names:L,Container:H,Stage:et,stages:$,Layer:ht,FastLayer:lt,Group:dt,DD:E,Shape:nt,shapes:at,Animation:gt,Tween:mt,Easings:_t,Context:C,Canvas:A});class xt extends nt{_sceneFunc(t){var e=a.getAngle(this.angle()),i=this.clockwise();t.beginPath(),t.arc(0,0,this.outerRadius(),0,e,i),t.arc(0,0,this.innerRadius(),e,0,!i),t.closePath(),t.fillStrokeShape(this)}getWidth(){return 2*this.outerRadius()}getHeight(){return 2*this.outerRadius()}setWidth(t){this.outerRadius(t/2)}setHeight(t){this.outerRadius(t/2)}}xt.prototype._centroid=!0,xt.prototype.className="Arc",xt.prototype._attrsAffectingSize=["innerRadius","outerRadius"],s(xt),S.addGetterSetter(xt,"innerRadius",0,v()),S.addGetterSetter(xt,"outerRadius",0,v()),S.addGetterSetter(xt,"angle",0,v()),S.addGetterSetter(xt,"clockwise",!1,b());class bt extends nt{constructor(t){super(t),this.on("pointsChange.konva tensionChange.konva closedChange.konva bezierChange.konva",(function(){this._clearCache("tensionPoints")}))}_sceneFunc(t){var e,i,r,a=this.points(),n=a.length,s=this.tension(),o=this.closed(),h=this.bezier();if(n){if(t.beginPath(),t.moveTo(a[0],a[1]),0!==s&&n>4){for(i=(e=this.getTensionPoints()).length,r=o?0:4,o||t.quadraticCurveTo(e[0],e[1],e[2],e[3]);r4;a&&(r=this.getTensionPoints());var n,s,o=i.length;a?(n=i[o-2]-(r[r.length-2]+r[r.length-4])/2,s=i[o-1]-(r[r.length-1]+r[r.length-3])/2):(n=i[o-2]-i[o-4],s=i[o-1]-i[o-3]);var h=(Math.atan2(s,n)+e)%e,l=this.pointerLength(),d=this.pointerWidth();t.save(),t.beginPath(),t.translate(i[o-2],i[o-1]),t.rotate(h),t.moveTo(0,0),t.lineTo(-l,d/2),t.lineTo(-l,-d/2),t.closePath(),t.restore(),this.pointerAtBeginning()&&(t.save(),t.translate(i[0],i[1]),a?(n=(r[0]+r[2])/2-i[0],s=(r[1]+r[3])/2-i[1]):(n=i[2]-i[0],s=i[3]-i[1]),t.rotate((Math.atan2(-s,-n)+e)%e),t.moveTo(0,0),t.lineTo(-l,d/2),t.lineTo(-l,-d/2),t.closePath(),t.restore());var c=this.dashEnabled();c&&(this.attrs.dashEnabled=!1,t.setLineDash([])),t.fillStrokeShape(this),c&&(this.attrs.dashEnabled=!0)}getSelfRect(){const t=super.getSelfRect(),e=this.pointerWidth()/2;return{x:t.x-e,y:t.y-e,width:t.width+2*e,height:t.height+2*e}}}St.prototype.className="Arrow",s(St),S.addGetterSetter(St,"pointerLength",10,v()),S.addGetterSetter(St,"pointerWidth",10,v()),S.addGetterSetter(St,"pointerAtBeginning",!1);class wt extends nt{_sceneFunc(t){t.beginPath(),t.arc(0,0,this.attrs.radius||0,0,2*Math.PI,!1),t.closePath(),t.fillStrokeShape(this)}getWidth(){return 2*this.radius()}getHeight(){return 2*this.radius()}setWidth(t){this.radius()!==t/2&&this.radius(t/2)}setHeight(t){this.radius()!==t/2&&this.radius(t/2)}}wt.prototype._centroid=!0,wt.prototype.className="Circle",wt.prototype._attrsAffectingSize=["radius"],s(wt),S.addGetterSetter(wt,"radius",0,v());class Ct extends nt{_sceneFunc(t){var e=this.radiusX(),i=this.radiusY();t.beginPath(),t.save(),e!==i&&t.scale(1,i/e),t.arc(0,0,e,0,2*Math.PI,!1),t.restore(),t.closePath(),t.fillStrokeShape(this)}getWidth(){return 2*this.radiusX()}getHeight(){return 2*this.radiusY()}setWidth(t){this.radiusX(t/2)}setHeight(t){this.radiusY(t/2)}}Ct.prototype.className="Ellipse",Ct.prototype._centroid=!0,Ct.prototype._attrsAffectingSize=["radiusX","radiusY"],s(Ct),S.addComponentsGetterSetter(Ct,"radius",["x","y"]),S.addGetterSetter(Ct,"radiusX",0,v()),S.addGetterSetter(Ct,"radiusY",0,v());class Pt extends nt{_useBufferCanvas(){return super._useBufferCanvas(!0)}_sceneFunc(t){const e=this.getWidth(),i=this.getHeight(),r=this.attrs.image;let a;if(r){const t=this.attrs.cropWidth,n=this.attrs.cropHeight;a=t&&n?[r,this.cropX(),this.cropY(),t,n,0,0,e,i]:[r,0,0,e,i]}(this.hasFill()||this.hasStroke())&&(t.beginPath(),t.rect(0,0,e,i),t.closePath(),t.fillStrokeShape(this)),r&&t.drawImage.apply(t,a)}_hitFunc(t){var e=this.width(),i=this.height();t.beginPath(),t.rect(0,0,e,i),t.closePath(),t.fillStrokeShape(this)}getWidth(){var t,e;return null!==(t=this.attrs.width)&&void 0!==t?t:null===(e=this.image())||void 0===e?void 0:e.width}getHeight(){var t,e;return null!==(t=this.attrs.height)&&void 0!==t?t:null===(e=this.image())||void 0===e?void 0:e.height}static fromURL(t,e){var i=u.createImageElement();i.onload=function(){var t=new Pt({image:i});e(t)},i.crossOrigin="Anonymous",i.src=t}}Pt.prototype.className="Image",s(Pt),S.addGetterSetter(Pt,"image"),S.addComponentsGetterSetter(Pt,"crop",["x","y","width","height"]),S.addGetterSetter(Pt,"cropX",0,v()),S.addGetterSetter(Pt,"cropY",0,v()),S.addGetterSetter(Pt,"cropWidth",0,v()),S.addGetterSetter(Pt,"cropHeight",0,v());var kt=["fontFamily","fontSize","fontStyle","padding","lineHeight","text","width","height"],Tt=kt.length;class At extends dt{constructor(t){super(t),this.on("add.konva",(function(t){this._addListeners(t.child),this._sync()}))}getText(){return this.find("Text")[0]}getTag(){return this.find("Tag")[0]}_addListeners(t){var e,i=this,r=function(){i._sync()};for(e=0;el?h:l,p=h>l?1:h/l,v=h>l?l/h:1;t.translate(s,o),t.rotate(g),t.scale(p,v),t.arc(0,0,f,d,d+c,1-u),t.scale(1/p,1/v),t.rotate(-g),t.translate(-s,-o);break;case"z":i=!0,t.closePath()}}i||this.hasFill()?t.fillStrokeShape(this):t.strokeShape(this)}getSelfRect(){var t=[];this.dataArray.forEach((function(e){if("A"===e.command){var i=e.points[4],r=e.points[5],a=e.points[4]+r,n=Math.PI/180;if(Math.abs(i-a)a;r-=n){const i=Gt.getPointOnEllipticalArc(e.points[0],e.points[1],e.points[2],e.points[3],r,0);t.push(i.x,i.y)}else for(let r=i+n;rthis.dataArray[i].pathLength;)t-=this.dataArray[i].pathLength,++i;if(i===r)return{x:(e=this.dataArray[i-1].points.slice(-2))[0],y:e[1]};if(t<.01)return{x:(e=this.dataArray[i].points.slice(0,2))[0],y:e[1]};var a=this.dataArray[i],n=a.points;switch(a.command){case"L":return Gt.getPointOnLine(t,a.start.x,a.start.y,n[0],n[1]);case"C":return Gt.getPointOnCubicBezier(t/a.pathLength,a.start.x,a.start.y,n[0],n[1],n[2],n[3],n[4],n[5]);case"Q":return Gt.getPointOnQuadraticBezier(t/a.pathLength,a.start.x,a.start.y,n[0],n[1],n[2],n[3]);case"A":var s=n[0],o=n[1],h=n[2],l=n[3],d=n[4],c=n[5],g=n[6];return d+=c*t/a.pathLength,Gt.getPointOnEllipticalArc(s,o,h,l,d,g)}return null}static getLineLength(t,e,i,r){return Math.sqrt((i-t)*(i-t)+(r-e)*(r-e))}static getPointOnLine(t,e,i,r,a,n,s){void 0===n&&(n=e),void 0===s&&(s=i);var o=(a-i)/(r-e+1e-8),h=Math.sqrt(t*t/(1+o*o));r0&&!isNaN(u[0]);){var m,_,y,x,b,S,w,C,P,k,T=null,A=[],M=h,G=l;switch(g){case"l":h+=u.shift(),l+=u.shift(),T="L",A.push(h,l);break;case"L":h=u.shift(),l=u.shift(),A.push(h,l);break;case"m":var E=u.shift(),R=u.shift();if(h+=E,l+=R,T="M",s.length>2&&"z"===s[s.length-1].command)for(var L=s.length-2;L>=0;L--)if("M"===s[L].command){h=s[L].points[0]+E,l=s[L].points[1]+R;break}A.push(h,l),g="l";break;case"M":h=u.shift(),l=u.shift(),T="M",A.push(h,l),g="L";break;case"h":h+=u.shift(),T="L",A.push(h,l);break;case"H":h=u.shift(),T="L",A.push(h,l);break;case"v":l+=u.shift(),T="L",A.push(h,l);break;case"V":l=u.shift(),T="L",A.push(h,l);break;case"C":A.push(u.shift(),u.shift(),u.shift(),u.shift()),h=u.shift(),l=u.shift(),A.push(h,l);break;case"c":A.push(h+u.shift(),l+u.shift(),h+u.shift(),l+u.shift()),h+=u.shift(),l+=u.shift(),T="C",A.push(h,l);break;case"S":_=h,y=l,"C"===(m=s[s.length-1]).command&&(_=h+(h-m.points[2]),y=l+(l-m.points[3])),A.push(_,y,u.shift(),u.shift()),h=u.shift(),l=u.shift(),T="C",A.push(h,l);break;case"s":_=h,y=l,"C"===(m=s[s.length-1]).command&&(_=h+(h-m.points[2]),y=l+(l-m.points[3])),A.push(_,y,h+u.shift(),l+u.shift()),h+=u.shift(),l+=u.shift(),T="C",A.push(h,l);break;case"Q":A.push(u.shift(),u.shift()),h=u.shift(),l=u.shift(),A.push(h,l);break;case"q":A.push(h+u.shift(),l+u.shift()),h+=u.shift(),l+=u.shift(),T="Q",A.push(h,l);break;case"T":_=h,y=l,"Q"===(m=s[s.length-1]).command&&(_=h+(h-m.points[0]),y=l+(l-m.points[1])),h=u.shift(),l=u.shift(),T="Q",A.push(_,y,h,l);break;case"t":_=h,y=l,"Q"===(m=s[s.length-1]).command&&(_=h+(h-m.points[0]),y=l+(l-m.points[1])),h+=u.shift(),l+=u.shift(),T="Q",A.push(_,y,h,l);break;case"A":x=u.shift(),b=u.shift(),S=u.shift(),w=u.shift(),C=u.shift(),P=h,k=l,h=u.shift(),l=u.shift(),T="A",A=this.convertEndpointToCenterParameterization(P,k,h,l,w,C,x,b,S);break;case"a":x=u.shift(),b=u.shift(),S=u.shift(),w=u.shift(),C=u.shift(),P=h,k=l,h+=u.shift(),l+=u.shift(),T="A",A=this.convertEndpointToCenterParameterization(P,k,h,l,w,C,x,b,S)}s.push({command:T||g,points:A,start:{x:M,y:G},pathLength:this.calcLength(M,G,T||g,A)})}"z"!==g&&"Z"!==g||s.push({command:"z",points:[],start:void 0,pathLength:0})}return s}static calcLength(t,e,i,r){var a,n,s,o,h=Gt;switch(i){case"L":return h.getLineLength(t,e,r[0],r[1]);case"C":for(a=0,n=h.getPointOnCubicBezier(0,t,e,r[0],r[1],r[2],r[3],r[4],r[5]),o=.01;o<=1;o+=.01)s=h.getPointOnCubicBezier(o,t,e,r[0],r[1],r[2],r[3],r[4],r[5]),a+=h.getLineLength(n.x,n.y,s.x,s.y),n=s;return a;case"Q":for(a=0,n=h.getPointOnQuadraticBezier(0,t,e,r[0],r[1],r[2],r[3]),o=.01;o<=1;o+=.01)s=h.getPointOnQuadraticBezier(o,t,e,r[0],r[1],r[2],r[3]),a+=h.getLineLength(n.x,n.y,s.x,s.y),n=s;return a;case"A":a=0;var l=r[4],d=r[5],c=r[4]+d,g=Math.PI/180;if(Math.abs(l-c)c;o-=g)s=h.getPointOnEllipticalArc(r[0],r[1],r[2],r[3],o,0),a+=h.getLineLength(n.x,n.y,s.x,s.y),n=s;else for(o=l+g;o1&&(s*=Math.sqrt(g),o*=Math.sqrt(g));var u=Math.sqrt((s*s*(o*o)-s*s*(c*c)-o*o*(d*d))/(s*s*(c*c)+o*o*(d*d)));a===n&&(u*=-1),isNaN(u)&&(u=0);var f=u*s*c/o,p=u*-o*d/s,v=(t+i)/2+Math.cos(l)*f-Math.sin(l)*p,m=(e+r)/2+Math.sin(l)*f+Math.cos(l)*p,_=function(t){return Math.sqrt(t[0]*t[0]+t[1]*t[1])},y=function(t,e){return(t[0]*e[0]+t[1]*e[1])/(_(t)*_(e))},x=function(t,e){return(t[0]*e[1]=1&&(C=0),0===n&&C>0&&(C-=2*Math.PI),1===n&&C<0&&(C+=2*Math.PI),[v,m,s,o,b,C,l,n]}}Gt.prototype.className="Path",Gt.prototype._attrsAffectingSize=["data"],s(Gt),S.addGetterSetter(Gt,"data");class Et extends nt{_sceneFunc(t){var e=this.cornerRadius(),i=this.width(),r=this.height();if(t.beginPath(),e){let a=0,n=0,s=0,o=0;"number"==typeof e?a=n=s=o=Math.min(e,i/2,r/2):(a=Math.min(e[0]||0,i/2,r/2),n=Math.min(e[1]||0,i/2,r/2),o=Math.min(e[2]||0,i/2,r/2),s=Math.min(e[3]||0,i/2,r/2)),t.moveTo(a,0),t.lineTo(i-n,0),t.arc(i-n,n,n,3*Math.PI/2,0,!1),t.lineTo(i,r-o),t.arc(i-o,r-o,o,0,Math.PI/2,!1),t.lineTo(s,r),t.arc(s,r-s,s,Math.PI/2,Math.PI,!1),t.lineTo(0,a),t.arc(a,a,a,Math.PI,3*Math.PI/2,!1)}else t.rect(0,0,i,r);t.closePath(),t.fillStrokeShape(this)}}Et.prototype.className="Rect",s(Et),S.addGetterSetter(Et,"cornerRadius",0,m(4));class Rt extends nt{_sceneFunc(t){const e=this._getPoints();t.beginPath(),t.moveTo(e[0].x,e[0].y);for(var i=1;i{e=Math.min(e,t.x),i=Math.max(i,t.x),r=Math.min(r,t.y),a=Math.max(a,t.y)}),{x:e,y:r,width:i-e,height:a-r}}getWidth(){return 2*this.radius()}getHeight(){return 2*this.radius()}setWidth(t){this.radius(t/2)}setHeight(t){this.radius(t/2)}}Rt.prototype.className="RegularPolygon",Rt.prototype._centroid=!0,Rt.prototype._attrsAffectingSize=["radius"],s(Rt),S.addGetterSetter(Rt,"radius",0,v()),S.addGetterSetter(Rt,"sides",0,v());var Lt=2*Math.PI;class Dt extends nt{_sceneFunc(t){t.beginPath(),t.arc(0,0,this.innerRadius(),0,Lt,!1),t.moveTo(this.outerRadius(),0),t.arc(0,0,this.outerRadius(),Lt,0,!0),t.closePath(),t.fillStrokeShape(this)}getWidth(){return 2*this.outerRadius()}getHeight(){return 2*this.outerRadius()}setWidth(t){this.outerRadius(t/2)}setHeight(t){this.outerRadius(t/2)}}Dt.prototype.className="Ring",Dt.prototype._centroid=!0,Dt.prototype._attrsAffectingSize=["innerRadius","outerRadius"],s(Dt),S.addGetterSetter(Dt,"innerRadius",0,v()),S.addGetterSetter(Dt,"outerRadius",0,v());class It extends nt{constructor(t){super(t),this._updated=!0,this.anim=new gt(()=>{var t=this._updated;return this._updated=!1,t}),this.on("animationChange.konva",(function(){this.frameIndex(0)})),this.on("frameIndexChange.konva",(function(){this._updated=!0})),this.on("frameRateChange.konva",(function(){this.anim.isRunning()&&(clearInterval(this.interval),this._setInterval())}))}_sceneFunc(t){var e=this.animation(),i=this.frameIndex(),r=4*i,a=this.animations()[e],n=this.frameOffsets(),s=a[r+0],o=a[r+1],h=a[r+2],l=a[r+3],d=this.image();if((this.hasFill()||this.hasStroke())&&(t.beginPath(),t.rect(0,0,h,l),t.closePath(),t.fillStrokeShape(this)),d)if(n){var c=n[e],g=2*i;t.drawImage(d,s,o,h,l,c[g+0],c[g+1],h,l)}else t.drawImage(d,s,o,h,l,0,0,h,l)}_hitFunc(t){var e=this.animation(),i=this.frameIndex(),r=4*i,a=this.animations()[e],n=this.frameOffsets(),s=a[r+2],o=a[r+3];if(t.beginPath(),n){var h=n[e],l=2*i;t.rect(h[l+0],h[l+1],s,o)}else t.rect(0,0,s,o);t.closePath(),t.fillShape(this)}_useBufferCanvas(){return super._useBufferCanvas(!0)}_setInterval(){var t=this;this.interval=setInterval((function(){t._updateIndex()}),1e3/this.frameRate())}start(){if(!this.isRunning()){var t=this.getLayer();this.anim.setLayers(t),this._setInterval(),this.anim.start()}}stop(){this.anim.stop(),clearInterval(this.interval)}isRunning(){return this.anim.isRunning()}_updateIndex(){var t=this.frameIndex(),e=this.animation();t1&&(v+=s)}}}_hitFunc(t){var e=this.getWidth(),i=this.getHeight();t.beginPath(),t.rect(0,0,e,i),t.closePath(),t.fillStrokeShape(this)}setText(t){var e=u._isString(t)?t:null==t?"":t+"";return this._setAttr("text",e),this}getWidth(){return"auto"===this.attrs.width||void 0===this.attrs.width?this.getTextWidth()+2*this.padding():this.attrs.width}getHeight(){return"auto"===this.attrs.height||void 0===this.attrs.height?this.fontSize()*this.textArr.length*this.lineHeight()+2*this.padding():this.attrs.height}getTextWidth(){return this.textWidth}getTextHeight(){return u.warn("text.getTextHeight() method is deprecated. Use text.height() - for full height and text.fontSize() - for one line height."),this.textHeight}measureSize(t){var e,i=Wt(),r=this.fontSize();return i.save(),i.font=this._getContextFont(),e=i.measureText(t),i.restore(),{width:e.width,height:r}}_getContextFont(){return a.UA.isIE?this.fontStyle()+" "+this.fontSize()+"px "+this.fontFamily():this.fontStyle()+" "+this.fontVariant()+" "+this.fontSize()+"px "+this.fontFamily().split(",").map(t=>{const e=(t=t.trim()).indexOf(" ")>=0,i=t.indexOf('"')>=0||t.indexOf("'")>=0;return e&&!i&&(t=`"${t}"`),t}).join(", ")}_addTextLine(t){"justify"===this.align()&&(t=t.trim());var e=this._getTextWidth(t);return this.textArr.push({text:t,width:e})}_getTextWidth(t){var e=this.letterSpacing(),i=t.length;return Wt().measureText(t).width+(i?e*(i-1):0)}_setTextData(){var t=this.text().split("\n"),e=+this.fontSize(),i=0,r=this.lineHeight()*e,a=this.attrs.width,n=this.attrs.height,s="auto"!==a&&void 0!==a,o="auto"!==n&&void 0!==n,h=this.padding(),l=a-2*h,d=n-2*h,c=0,g=this.wrap(),u="none"!==g,f="char"!==g&&u,p=this.ellipsis();this.textArr=[],Wt().font=this._getContextFont();for(var v=p?this._getTextWidth("…"):0,m=0,_=t.length;m<_;++m){var y=t[m],x=this._getTextWidth(y);if(s&&x>l)for(;y.length>0;){for(var b=0,S=y.length,w="",C=0;b>>1,k=y.slice(0,P+1),T=this._getTextWidth(k)+v;T<=l?(b=P+1,w=k,C=T):S=P}if(!w)break;if(f){var A,M=y[w.length];(A=(" "===M||"-"===M)&&C<=l?w.length:Math.max(w.lastIndexOf(" "),w.lastIndexOf("-"))+1)>0&&(b=A,w=w.slice(0,b),C=this._getTextWidth(w))}if(w=w.trimRight(),this._addTextLine(w),i=Math.max(i,C),c+=r,!u||o&&c+r>d){var G=this.textArr[this.textArr.length-1];if(G)if(p)this._getTextWidth(G.text+"…")0&&(x=this._getTextWidth(y))<=l){this._addTextLine(y),c+=r,i=Math.max(i,x);break}}else this._addTextLine(y),c+=r,i=Math.max(i,x);if(o&&c+r>d)break}this.textHeight=e,this.textWidth=i}getStrokeScaleEnabled(){return!0}}Ht.prototype._fillFunc=function(t){t.fillText(this._partialText,this._partialTextX,this._partialTextY)},Ht.prototype._strokeFunc=function(t){t.strokeText(this._partialText,this._partialTextX,this._partialTextY)},Ht.prototype.className="Text",Ht.prototype._attrsAffectingSize=["text","fontSize","padding","wrap","lineHeight","letterSpacing"],s(Ht),S.overWriteSetter(Ht,"width",_()),S.overWriteSetter(Ht,"height",_()),S.addGetterSetter(Ht,"fontFamily","Arial"),S.addGetterSetter(Ht,"fontSize",12,v()),S.addGetterSetter(Ht,"fontStyle","normal"),S.addGetterSetter(Ht,"fontVariant","normal"),S.addGetterSetter(Ht,"padding",0,v()),S.addGetterSetter(Ht,"align","left"),S.addGetterSetter(Ht,"verticalAlign","top"),S.addGetterSetter(Ht,"lineHeight",1,v()),S.addGetterSetter(Ht,"wrap","word"),S.addGetterSetter(Ht,"ellipsis",!1,b()),S.addGetterSetter(Ht,"letterSpacing",0,v()),S.addGetterSetter(Ht,"text","",y()),S.addGetterSetter(Ht,"textDecoration","");function Yt(t){t.fillText(this.partialText,0,0)}function Xt(t){t.strokeText(this.partialText,0,0)}class jt extends nt{constructor(t){super(t),this.dummyCanvas=u.createCanvasElement(),this.dataArray=[],this.dataArray=Gt.parsePathData(this.attrs.data),this.on("dataChange.konva",(function(){this.dataArray=Gt.parsePathData(this.attrs.data),this._setTextData()})),this.on("textChange.konva alignChange.konva letterSpacingChange.konva kerningFuncChange.konva fontSizeChange.konva",this._setTextData),t&&t.getKerning&&(u.warn('getKerning TextPath API is deprecated. Please use "kerningFunc" instead.'),this.kerningFunc(t.getKerning)),this._setTextData()}_sceneFunc(t){t.setAttr("font",this._getContextFont()),t.setAttr("textBaseline",this.textBaseline()),t.setAttr("textAlign","left"),t.save();var e=this.textDecoration(),i=this.fill(),r=this.fontSize(),a=this.glyphInfo;"underline"===e&&t.beginPath();for(var n=0;n=1){var i=e[0].p0;t.moveTo(i.x,i.y)}for(var r=0;r0&&(s+=t.dataArray[o].pathLength);var h=0;"center"===r&&(h=Math.max(0,s/2-n/2)),"right"===r&&(h=Math.max(0,s-n));for(var l,d,c,g=Ft(this.text()),u=this.text().split(" ").length-1,f=-1,p=0,v=function(){p=0;for(var e=t.dataArray,i=f+1;i0)return f=i,e[i];"M"===e[i].command&&(l={x:e[i].points[0],y:e[i].points[1]})}return{}},m=function(e){var a=t._getTextSize(e).width+i;" "===e&&"justify"===r&&(a+=(s-n)/u);var o=0,h=0;for(d=void 0;Math.abs(a-o)/a>.01&&h<20;){h++;for(var g=o;void 0===c;)(c=v())&&g+c.pathLengtha?d=Gt.getPointOnLine(a,l.x,l.y,c.points[0],c.points[1],l.x,l.y):c=void 0;break;case"A":var m=c.points[4],_=c.points[5],y=c.points[4]+_;0===p?p=m+1e-8:a>o?p+=Math.PI/180*_/Math.abs(_):p-=Math.PI/360*_/Math.abs(_),(_<0&&p=0&&p>y)&&(p=y,f=!0),d=Gt.getPointOnEllipticalArc(c.points[0],c.points[1],c.points[2],c.points[3],p,c.points[6]);break;case"C":0===p?p=a>c.pathLength?1e-8:a/c.pathLength:a>o?p+=(a-o)/c.pathLength/2:p=Math.max(p-(o-a)/c.pathLength/2,0),p>1&&(p=1,f=!0),d=Gt.getPointOnCubicBezier(p,c.start.x,c.start.y,c.points[0],c.points[1],c.points[2],c.points[3],c.points[4],c.points[5]);break;case"Q":0===p?p=a/c.pathLength:a>o?p+=(a-o)/c.pathLength:p-=(o-a)/c.pathLength,p>1&&(p=1,f=!0),d=Gt.getPointOnQuadraticBezier(p,c.start.x,c.start.y,c.points[0],c.points[1],c.points[2],c.points[3])}void 0!==d&&(o=Gt.getLineLength(l.x,l.y,d.x,d.y)),f&&(f=!1,c=void 0)}},_=h/(t._getTextSize("C").width+i)-1,y=0;y<_&&(m("C"),void 0!==l&&void 0!==d);y++)l=d;for(var x=0;xt+".tr-konva").join(" "),qt=["widthChange","heightChange","scaleXChange","scaleYChange","skewXChange","skewYChange","rotationChange","offsetXChange","offsetYChange","transformsEnabledChange","strokeWidthChange"].map(t=>t+".tr-konva").join(" "),Kt={"top-left":-45,"top-center":0,"top-right":45,"middle-right":-90,"middle-left":90,"bottom-left":-135,"bottom-center":180,"bottom-right":135};const Vt="ontouchstart"in a._global;var Qt=["top-left","top-center","top-right","middle-right","middle-left","bottom-left","bottom-center","bottom-right"];function Jt(t,e,i){const r=i.x+(t.x-i.x)*Math.cos(e)-(t.y-i.y)*Math.sin(e),a=i.y+(t.x-i.x)*Math.sin(e)+(t.y-i.y)*Math.cos(e);return Object.assign(Object.assign({},t),{rotation:t.rotation+e,x:r,y:a})}function Zt(t,e){return Jt(t,e,function(t){return{x:t.x+t.width/2*Math.cos(t.rotation)+t.height/2*Math.sin(-t.rotation),y:t.y+t.height/2*Math.cos(t.rotation)+t.width/2*Math.sin(t.rotation)}}(t))}class $t extends dt{constructor(t){super(t),this._transforming=!1,this._createElements(),this._handleMouseMove=this._handleMouseMove.bind(this),this._handleMouseUp=this._handleMouseUp.bind(this),this.update=this.update.bind(this),this.on(Ut,this.update),this.getNode()&&this.update()}attachTo(t){return this.setNode(t),this}setNode(t){return u.warn("tr.setNode(shape), tr.node(shape) and tr.attachTo(shape) methods are deprecated. Please use tr.nodes(nodesArray) instead."),this.setNodes([t])}getNode(){return this._nodes&&this._nodes[0]}setNodes(t=[]){return this._nodes&&this._nodes.length&&this.detach(),this._nodes=t,1===t.length?this.rotation(t[0].getAbsoluteRotation()):this.rotation(0),this._nodes.forEach(t=>{const e=t._attrsAffectingSize.map(t=>t+"Change.tr-konva").join(" "),i=()=>{1===this.nodes().length&&this.rotation(this.nodes()[0].getAbsoluteRotation()),this._resetTransformCache(),this._transforming||this.isDragging()||this.update()};t.on(e,i),t.on(qt,i),t.on("_clearTransformCache.tr-konva",i),t.on("xChange.tr-konva yChange.tr-konva",i),this._proxyDrag(t)}),this._resetTransformCache(),!!this.findOne(".top-left")&&this.update(),this}_proxyDrag(t){let e;t.on("dragstart.tr-konva",i=>{e=t.getAbsolutePosition(),this.isDragging()||t===this.findOne(".back")||this.startDrag(i,!1)}),t.on("dragmove.tr-konva",i=>{if(!e)return;const r=t.getAbsolutePosition(),a=r.x-e.x,n=r.y-e.y;this.nodes().forEach(e=>{if(e===t)return;if(e.isDragging())return;const r=e.getAbsolutePosition();e.setAbsolutePosition({x:r.x+a,y:r.y+n}),e.startDrag(i)}),e=null})}getNodes(){return this._nodes||[]}getActiveAnchor(){return this._movingAnchorName}detach(){this._nodes&&this._nodes.forEach(t=>{t.off(".tr-konva")}),this._nodes=[],this._resetTransformCache()}_resetTransformCache(){this._clearCache("nodesRect"),this._clearCache("transform"),this._clearSelfAndDescendantCache("absoluteTransform")}_getNodeRect(){return this._getCache("nodesRect",this.__getNodeRect)}__getNodeShape(t,e=this.rotation(),i){var r=t.getClientRect({skipTransform:!0,skipShadow:!0,skipStroke:this.ignoreStroke()}),n=t.getAbsoluteScale(i),s=t.getAbsolutePosition(i),o=r.x*n.x-t.offsetX()*n.x,h=r.y*n.y-t.offsetY()*n.y;const l=(a.getAngle(t.getAbsoluteRotation())+2*Math.PI)%(2*Math.PI);return Jt({x:s.x+o*Math.cos(l)+h*Math.sin(-l),y:s.y+h*Math.cos(l)+o*Math.sin(l),width:r.width*n.x,height:r.height*n.y,rotation:l},-a.getAngle(e),{x:0,y:0})}__getNodeRect(){if(!this.getNode())return{x:-1e8,y:-1e8,width:0,height:0,rotation:0};const t=[];this.nodes().map(e=>{const i=e.getClientRect({skipTransform:!0,skipShadow:!0,skipStroke:this.ignoreStroke()});var r=[{x:i.x,y:i.y},{x:i.x+i.width,y:i.y},{x:i.x+i.width,y:i.y+i.height},{x:i.x,y:i.y+i.height}],a=e.getAbsoluteTransform();r.forEach((function(e){var i=a.point(e);t.push(i)}))});const e=new o;var i,r,n,s;e.rotate(-a.getAngle(this.rotation())),t.forEach((function(t){var a=e.point(t);void 0===i&&(i=n=a.x,r=s=a.y),i=Math.min(i,a.x),r=Math.min(r,a.y),n=Math.max(n,a.x),s=Math.max(s,a.y)})),e.invert();const h=e.point({x:i,y:r});return{x:h.x,y:h.y,width:n-i,height:s-r,rotation:a.getAngle(this.rotation())}}getX(){return this._getNodeRect().x}getY(){return this._getNodeRect().y}getWidth(){return this._getNodeRect().width}getHeight(){return this._getNodeRect().height}_createElements(){this._createBack(),Qt.forEach(function(t){this._createAnchor(t)}.bind(this)),this._createAnchor("rotater")}_createAnchor(t){var e=new Et({stroke:"rgb(0, 161, 255)",fill:"white",strokeWidth:1,name:t+" _anchor",dragDistance:0,draggable:!0,hitStrokeWidth:Vt?10:"auto"}),i=this;e.on("mousedown touchstart",(function(t){i._handleMouseDown(t)})),e.on("dragstart",t=>{e.stopDrag(),t.cancelBubble=!0}),e.on("dragend",t=>{t.cancelBubble=!0}),e.on("mouseenter",()=>{var i=a.getAngle(this.rotation()),r=function(t,e){if("rotater"===t)return"crosshair";e+=u._degToRad(Kt[t]||0);var i=(u._radToDeg(e)%360+360)%360;return u._inRange(i,337.5,360)||u._inRange(i,0,22.5)?"ns-resize":u._inRange(i,22.5,67.5)?"nesw-resize":u._inRange(i,67.5,112.5)?"ew-resize":u._inRange(i,112.5,157.5)?"nwse-resize":u._inRange(i,157.5,202.5)?"ns-resize":u._inRange(i,202.5,247.5)?"nesw-resize":u._inRange(i,247.5,292.5)?"ew-resize":u._inRange(i,292.5,337.5)?"nwse-resize":(u.error("Transformer has unknown angle for cursor detection: "+i),"pointer")}(t,i);e.getStage().content.style.cursor=r,this._cursorChange=!0}),e.on("mouseout",()=>{e.getStage().content.style.cursor="",this._cursorChange=!1}),this.add(e)}_createBack(){var t=new nt({name:"back",width:0,height:0,draggable:!0,sceneFunc(t){var e=this.getParent(),i=e.padding();t.beginPath(),t.rect(-i,-i,this.width()+2*i,this.height()+2*i),t.moveTo(this.width()/2,-i),e.rotateEnabled()&&t.lineTo(this.width()/2,-e.rotateAnchorOffset()*u._sign(this.height())-i),t.fillStrokeShape(this)},hitFunc:(t,e)=>{if(this.shouldOverdrawWholeArea()){var i=this.padding();t.beginPath(),t.rect(-i,-i,e.width()+2*i,e.height()+2*i),t.fillStrokeShape(e)}}});this.add(t),this._proxyDrag(t),t.on("dragstart",t=>{t.cancelBubble=!0}),t.on("dragmove",t=>{t.cancelBubble=!0}),t.on("dragend",t=>{t.cancelBubble=!0})}_handleMouseDown(t){this._movingAnchorName=t.target.name().split(" ")[0];var e=this._getNodeRect(),i=e.width,r=e.height,a=Math.sqrt(Math.pow(i,2)+Math.pow(r,2));this.sin=Math.abs(r/a),this.cos=Math.abs(i/a),window.addEventListener("mousemove",this._handleMouseMove),window.addEventListener("touchmove",this._handleMouseMove),window.addEventListener("mouseup",this._handleMouseUp,!0),window.addEventListener("touchend",this._handleMouseUp,!0),this._transforming=!0;var n=t.target.getAbsolutePosition(),s=t.target.getStage().getPointerPosition();this._anchorDragOffset={x:s.x-n.x,y:s.y-n.y},this._fire("transformstart",{evt:t,target:this.getNode()}),this._nodes.forEach(e=>{e._fire("transformstart",{evt:t,target:e})})}_handleMouseMove(t){var e,i,r,n=this.findOne("."+this._movingAnchorName),s=n.getStage();s.setPointersPositions(t);const o=s.getPointerPosition();var h={x:o.x-this._anchorDragOffset.x,y:o.y-this._anchorDragOffset.y};const l=n.getAbsolutePosition();n.setAbsolutePosition(h);const d=n.getAbsolutePosition();if(l.x!==d.x||l.y!==d.y)if("rotater"!==this._movingAnchorName){var c=this.keepRatio()||t.shiftKey,g=this.centeredScaling()||t.altKey;if("top-left"===this._movingAnchorName){if(c){var u=g?{x:this.width()/2,y:this.height()/2}:{x:this.findOne(".bottom-right").x(),y:this.findOne(".bottom-right").y()};r=Math.sqrt(Math.pow(u.x-n.x(),2)+Math.pow(u.y-n.y(),2));var f=this.findOne(".top-left").x()>u.x?-1:1,p=this.findOne(".top-left").y()>u.y?-1:1;e=r*this.cos*f,i=r*this.sin*p,this.findOne(".top-left").x(u.x-e),this.findOne(".top-left").y(u.y-i)}}else if("top-center"===this._movingAnchorName)this.findOne(".top-left").y(n.y());else if("top-right"===this._movingAnchorName){if(c){u=g?{x:this.width()/2,y:this.height()/2}:{x:this.findOne(".bottom-left").x(),y:this.findOne(".bottom-left").y()};r=Math.sqrt(Math.pow(n.x()-u.x,2)+Math.pow(u.y-n.y(),2));f=this.findOne(".top-right").x()u.y?-1:1;e=r*this.cos*f,i=r*this.sin*p,this.findOne(".top-right").x(u.x+e),this.findOne(".top-right").y(u.y-i)}var v=n.position();this.findOne(".top-left").y(v.y),this.findOne(".bottom-right").x(v.x)}else if("middle-left"===this._movingAnchorName)this.findOne(".top-left").x(n.x());else if("middle-right"===this._movingAnchorName)this.findOne(".bottom-right").x(n.x());else if("bottom-left"===this._movingAnchorName){if(c){u=g?{x:this.width()/2,y:this.height()/2}:{x:this.findOne(".top-right").x(),y:this.findOne(".top-right").y()};r=Math.sqrt(Math.pow(u.x-n.x(),2)+Math.pow(n.y()-u.y,2));f=u.x{e._fire("transformend",{evt:t,target:e})}),this._movingAnchorName=null}}_fitNodesInto(t,e){var i=this._getNodeRect();if(u._inRange(t.width,2*-this.padding()-1,1))return void this.update();if(u._inRange(t.height,2*-this.padding()-1,1))return void this.update();var r=new o;if(r.rotate(a.getAngle(this.rotation())),this._movingAnchorName&&t.width<0&&this._movingAnchorName.indexOf("left")>=0){const e=r.point({x:2*-this.padding(),y:0});t.x+=e.x,t.y+=e.y,t.width+=2*this.padding(),this._movingAnchorName=this._movingAnchorName.replace("left","right"),this._anchorDragOffset.x-=e.x,this._anchorDragOffset.y-=e.y}else if(this._movingAnchorName&&t.width<0&&this._movingAnchorName.indexOf("right")>=0){const e=r.point({x:2*this.padding(),y:0});this._movingAnchorName=this._movingAnchorName.replace("right","left"),this._anchorDragOffset.x-=e.x,this._anchorDragOffset.y-=e.y,t.width+=2*this.padding()}if(this._movingAnchorName&&t.height<0&&this._movingAnchorName.indexOf("top")>=0){const e=r.point({x:0,y:2*-this.padding()});t.x+=e.x,t.y+=e.y,this._movingAnchorName=this._movingAnchorName.replace("top","bottom"),this._anchorDragOffset.x-=e.x,this._anchorDragOffset.y-=e.y,t.height+=2*this.padding()}else if(this._movingAnchorName&&t.height<0&&this._movingAnchorName.indexOf("bottom")>=0){const e=r.point({x:0,y:2*this.padding()});this._movingAnchorName=this._movingAnchorName.replace("bottom","top"),this._anchorDragOffset.x-=e.x,this._anchorDragOffset.y-=e.y,t.height+=2*this.padding()}if(this.boundBoxFunc()){const e=this.boundBoxFunc()(i,t);e?t=e:u.warn("boundBoxFunc returned falsy. You should return new bound rect from it!")}const n=new o;n.translate(i.x,i.y),n.rotate(i.rotation),n.scale(i.width/1e7,i.height/1e7);const s=new o;s.translate(t.x,t.y),s.rotate(t.rotation),s.scale(t.width/1e7,t.height/1e7);const h=s.multiply(n.invert());this._nodes.forEach(t=>{var i;const r=t.getParent().getAbsoluteTransform(),a=t.getTransform().copy();a.translate(t.offsetX(),t.offsetY());const n=new o;n.multiply(r.copy().invert()).multiply(h).multiply(r).multiply(a);const s=n.decompose();t.setAttrs(s),this._fire("transform",{evt:e,target:t}),t._fire("transform",{evt:e,target:t}),null===(i=t.getLayer())||void 0===i||i.batchDraw()}),this.rotation(u._getRotation(t.rotation)),this._resetTransformCache(),this.update(),this.getLayer().batchDraw()}forceUpdate(){this._resetTransformCache(),this.update()}_batchChangeChild(t,e){this.findOne(t).setAttrs(e)}update(){var t,e=this._getNodeRect();this.rotation(u._getRotation(e.rotation));var i=e.width,r=e.height,a=this.enabledAnchors(),n=this.resizeEnabled(),s=this.padding(),o=this.anchorSize();this.find("._anchor").forEach(t=>{t.setAttrs({width:o,height:o,offsetX:o/2,offsetY:o/2,stroke:this.anchorStroke(),strokeWidth:this.anchorStrokeWidth(),fill:this.anchorFill(),cornerRadius:this.anchorCornerRadius()})}),this._batchChangeChild(".top-left",{x:0,y:0,offsetX:o/2+s,offsetY:o/2+s,visible:n&&a.indexOf("top-left")>=0}),this._batchChangeChild(".top-center",{x:i/2,y:0,offsetY:o/2+s,visible:n&&a.indexOf("top-center")>=0}),this._batchChangeChild(".top-right",{x:i,y:0,offsetX:o/2-s,offsetY:o/2+s,visible:n&&a.indexOf("top-right")>=0}),this._batchChangeChild(".middle-left",{x:0,y:r/2,offsetX:o/2+s,visible:n&&a.indexOf("middle-left")>=0}),this._batchChangeChild(".middle-right",{x:i,y:r/2,offsetX:o/2-s,visible:n&&a.indexOf("middle-right")>=0}),this._batchChangeChild(".bottom-left",{x:0,y:r,offsetX:o/2+s,offsetY:o/2-s,visible:n&&a.indexOf("bottom-left")>=0}),this._batchChangeChild(".bottom-center",{x:i/2,y:r,offsetY:o/2-s,visible:n&&a.indexOf("bottom-center")>=0}),this._batchChangeChild(".bottom-right",{x:i,y:r,offsetX:o/2-s,offsetY:o/2-s,visible:n&&a.indexOf("bottom-right")>=0}),this._batchChangeChild(".rotater",{x:i/2,y:-this.rotateAnchorOffset()*u._sign(r)-s,visible:this.rotateEnabled()}),this._batchChangeChild(".back",{width:i,height:r,visible:this.borderEnabled(),stroke:this.borderStroke(),strokeWidth:this.borderStrokeWidth(),dash:this.borderDash(),x:0,y:0}),null===(t=this.getLayer())||void 0===t||t.batchDraw()}isTransforming(){return this._transforming}stopTransform(){if(this._transforming){this._removeEvents();var t=this.findOne("."+this._movingAnchorName);t&&t.stopDrag()}}destroy(){return this.getStage()&&this._cursorChange&&(this.getStage().content.style.cursor=""),dt.prototype.destroy.call(this),this.detach(),this._removeEvents(),this}toObject(){return z.prototype.toObject.call(this)}}$t.prototype.className="Transformer",s($t),S.addGetterSetter($t,"enabledAnchors",Qt,(function(t){return t instanceof Array||u.warn("enabledAnchors value should be an array"),t instanceof Array&&t.forEach((function(t){-1===Qt.indexOf(t)&&u.warn("Unknown anchor name: "+t+". Available names are: "+Qt.join(", "))})),t||[]})),S.addGetterSetter($t,"resizeEnabled",!0),S.addGetterSetter($t,"anchorSize",10,v()),S.addGetterSetter($t,"rotateEnabled",!0),S.addGetterSetter($t,"rotationSnaps",[]),S.addGetterSetter($t,"rotateAnchorOffset",50,v()),S.addGetterSetter($t,"rotationSnapTolerance",5,v()),S.addGetterSetter($t,"borderEnabled",!0),S.addGetterSetter($t,"anchorStroke","rgb(0, 161, 255)"),S.addGetterSetter($t,"anchorStrokeWidth",1,v()),S.addGetterSetter($t,"anchorFill","white"),S.addGetterSetter($t,"anchorCornerRadius",0,v()),S.addGetterSetter($t,"borderStroke","rgb(0, 161, 255)"),S.addGetterSetter($t,"borderStrokeWidth",1,v()),S.addGetterSetter($t,"borderDash"),S.addGetterSetter($t,"keepRatio",!0),S.addGetterSetter($t,"centeredScaling",!1),S.addGetterSetter($t,"ignoreStroke",!1),S.addGetterSetter($t,"padding",0,v()),S.addGetterSetter($t,"node"),S.addGetterSetter($t,"nodes"),S.addGetterSetter($t,"boundBoxFunc"),S.addGetterSetter($t,"shouldOverdrawWholeArea",!1),S.backCompat($t,{lineEnabled:"borderEnabled",rotateHandlerOffset:"rotateAnchorOffset",enabledHandlers:"enabledAnchors"});class te extends nt{_sceneFunc(t){t.beginPath(),t.arc(0,0,this.radius(),0,a.getAngle(this.angle()),this.clockwise()),t.lineTo(0,0),t.closePath(),t.fillStrokeShape(this)}getWidth(){return 2*this.radius()}getHeight(){return 2*this.radius()}setWidth(t){this.radius(t/2)}setHeight(t){this.radius(t/2)}}function ee(){this.r=0,this.g=0,this.b=0,this.a=0,this.next=null}te.prototype.className="Wedge",te.prototype._centroid=!0,te.prototype._attrsAffectingSize=["radius"],s(te),S.addGetterSetter(te,"radius",0,v()),S.addGetterSetter(te,"angle",0,v()),S.addGetterSetter(te,"clockwise",!1),S.backCompat(te,{angleDeg:"angle",getAngleDeg:"getAngle",setAngleDeg:"setAngle"});var ie=[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,496,475,456,437,420,404,388,374,360,347,335,323,312,302,292,282,273,265,512,497,482,468,454,441,428,417,405,394,383,373,364,354,345,337,328,320,312,305,298,291,284,278,271,265,259,507,496,485,475,465,456,446,437,428,420,412,404,396,388,381,374,367,360,354,347,341,335,329,323,318,312,307,302,297,292,287,282,278,273,269,265,261,512,505,497,489,482,475,468,461,454,447,441,435,428,422,417,411,405,399,394,389,383,378,373,368,364,359,354,350,345,341,337,332,328,324,320,316,312,309,305,301,298,294,291,287,284,281,278,274,271,268,265,262,259,257,507,501,496,491,485,480,475,470,465,460,456,451,446,442,437,433,428,424,420,416,412,408,404,400,396,392,388,385,381,377,374,370,367,363,360,357,354,350,347,344,341,338,335,332,329,326,323,320,318,315,312,310,307,304,302,299,297,294,292,289,287,285,282,280,278,275,273,271,269,267,265,263,261,259],re=[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,20,20,20,20,20,21,21,21,21,21,21,21,21,21,21,21,21,21,21,21,21,21,21,21,21,21,21,21,21,21,21,21,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24];S.addGetterSetter(z,"blurRadius",0,v(),S.afterSetFilter);S.addGetterSetter(z,"brightness",0,v(),S.afterSetFilter);S.addGetterSetter(z,"contrast",0,v(),S.afterSetFilter);function ae(t,e,i,r,a){var n=i-e,s=a-r;return 0===n?r+s/2:0===s?r:s*((t-e)/n)+r}S.addGetterSetter(z,"embossStrength",.5,v(),S.afterSetFilter),S.addGetterSetter(z,"embossWhiteLevel",.5,v(),S.afterSetFilter),S.addGetterSetter(z,"embossDirection","top-left",null,S.afterSetFilter),S.addGetterSetter(z,"embossBlend",!1,null,S.afterSetFilter);S.addGetterSetter(z,"enhance",0,v(),S.afterSetFilter);S.addGetterSetter(z,"hue",0,v(),S.afterSetFilter),S.addGetterSetter(z,"saturation",0,v(),S.afterSetFilter),S.addGetterSetter(z,"luminance",0,v(),S.afterSetFilter);S.addGetterSetter(z,"hue",0,v(),S.afterSetFilter),S.addGetterSetter(z,"saturation",0,v(),S.afterSetFilter),S.addGetterSetter(z,"value",0,v(),S.afterSetFilter);function ne(t,e,i){var r=4*(i*t.width+e),a=[];return a.push(t.data[r++],t.data[r++],t.data[r++],t.data[r++]),a}function se(t,e){return Math.sqrt(Math.pow(t[0]-e[0],2)+Math.pow(t[1]-e[1],2)+Math.pow(t[2]-e[2],2))}S.addGetterSetter(z,"kaleidoscopePower",2,v(),S.afterSetFilter),S.addGetterSetter(z,"kaleidoscopeAngle",0,v(),S.afterSetFilter);S.addGetterSetter(z,"threshold",0,v(),S.afterSetFilter);S.addGetterSetter(z,"noise",.2,v(),S.afterSetFilter);S.addGetterSetter(z,"pixelSize",8,v(),S.afterSetFilter);S.addGetterSetter(z,"levels",.5,v(),S.afterSetFilter);S.addGetterSetter(z,"red",0,(function(t){return this._filterUpToDate=!1,t>255?255:t<0?0:Math.round(t)})),S.addGetterSetter(z,"green",0,(function(t){return this._filterUpToDate=!1,t>255?255:t<0?0:Math.round(t)})),S.addGetterSetter(z,"blue",0,p,S.afterSetFilter);S.addGetterSetter(z,"red",0,(function(t){return this._filterUpToDate=!1,t>255?255:t<0?0:Math.round(t)})),S.addGetterSetter(z,"green",0,(function(t){return this._filterUpToDate=!1,t>255?255:t<0?0:Math.round(t)})),S.addGetterSetter(z,"blue",0,p,S.afterSetFilter),S.addGetterSetter(z,"alpha",1,(function(t){return this._filterUpToDate=!1,t>1?1:t<0?0:t}));S.addGetterSetter(z,"threshold",.5,v(),S.afterSetFilter);return yt.Util._assign(yt,{Arc:xt,Arrow:St,Circle:wt,Ellipse:Ct,Image:Pt,Label:At,Tag:Mt,Line:bt,Path:Gt,Rect:Et,RegularPolygon:Rt,Ring:Dt,Sprite:It,Star:Ot,Text:Ht,TextPath:jt,Transformer:$t,Wedge:te,Filters:{Blur:function(t){var e=Math.round(this.blurRadius());e>0&&function(t,e){var i,r,a,n,s,o,h,l,d,c,g,u,f,p,v,m,_,y,x,b,S,w,C,P,k=t.data,T=t.width,A=t.height,M=e+e+1,G=T-1,E=A-1,R=e+1,L=R*(R+1)/2,D=new ee,I=null,O=D,F=null,B=null,N=ie[e],z=re[e];for(a=1;a>z,0!==C?(C=255/C,k[o]=(l*N>>z)*C,k[o+1]=(d*N>>z)*C,k[o+2]=(c*N>>z)*C):k[o]=k[o+1]=k[o+2]=0,l-=u,d-=f,c-=p,g-=v,u-=F.r,f-=F.g,p-=F.b,v-=F.a,n=h+((n=i+e+1)>z,C>0?(C=255/C,k[n]=(l*N>>z)*C,k[n+1]=(d*N>>z)*C,k[n+2]=(c*N>>z)*C):k[n]=k[n+1]=k[n+2]=0,l-=u,d-=f,c-=p,g-=v,u-=F.r,f-=F.g,p-=F.b,v-=F.a,n=i+((n=r+R)255?255:n,s=(s*=255)<0?0:s>255?255:s,o=(o*=255)<0?0:o>255?255:o,r[e]=n,r[e+1]=s,r[e+2]=o},Emboss:function(t){var e=10*this.embossStrength(),i=255*this.embossWhiteLevel(),r=this.embossDirection(),a=this.embossBlend(),n=0,s=0,o=t.data,h=t.width,l=t.height,d=4*h,c=l;switch(r){case"top-left":n=-1,s=-1;break;case"top":n=-1,s=0;break;case"top-right":n=-1,s=1;break;case"right":n=0,s=1;break;case"bottom-right":n=1,s=1;break;case"bottom":n=1,s=0;break;case"bottom-left":n=1,s=-1;break;case"left":n=0,s=-1;break;default:u.error("Unknown emboss direction: "+r)}do{var g=(c-1)*d,f=n;c+f<1&&(f=0),c+f>l&&(f=0);var p=(c-1+f)*h*4,v=h;do{var m=g+4*(v-1),_=s;v+_<1&&(_=0),v+_>h&&(_=0);var y=p+4*(v-1+_),x=o[m]-o[y],b=o[m+1]-o[y+1],S=o[m+2]-o[y+2],w=x,C=w>0?w:-w;if((b>0?b:-b)>C&&(w=b),(S>0?S:-S)>C&&(w=S),w*=e,a){var P=o[m]+w,k=o[m+1]+w,T=o[m+2]+w;o[m]=P>255?255:P<0?0:P,o[m+1]=k>255?255:k<0?0:k,o[m+2]=T>255?255:T<0?0:T}else{var A=i-w;A<0?A=0:A>255&&(A=255),o[m]=o[m+1]=o[m+2]=A}}while(--v)}while(--c)},Enhance:function(t){var e,i,r,a,n=t.data,s=n.length,o=n[0],h=o,l=n[1],d=l,c=n[2],g=c,u=this.enhance();if(0!==u){for(a=0;ah&&(h=e),(i=n[a+1])d&&(d=i),(r=n[a+2])g&&(g=r);var f,p,v,m,_,y,x,b,S;for(h===o&&(h=255,o=0),d===l&&(d=255,l=0),g===c&&(g=255,c=0),u>0?(p=h+u*(255-h),v=o-u*(o-0),_=d+u*(255-d),y=l-u*(l-0),b=g+u*(255-g),S=c-u*(c-0)):(p=h+u*(h-(f=.5*(h+o))),v=o+u*(o-f),_=d+u*(d-(m=.5*(d+l))),y=l+u*(l-m),b=g+u*(g-(x=.5*(g+c))),S=c+u*(c-x)),a=0;am?s:m;var _,y,x,b,S=d,w=l,C=360/w*Math.PI/180;for(y=0;yd&&(x=y,b=0,S=-1),i=0;iy?h:y;var x,b,S,w=g,C=c,P=i.polarRotation||0;for(a=0;a=0&&u=0&&f=0&&u=0&&f=1020?255:0}return s}(e=function(t,e,i){for(var r=[1,1,1,1,0,1,1,1,1],a=Math.round(Math.sqrt(r.length)),n=Math.floor(a/2),s=[],o=0;o=0&&u=0&&f=m))for(i=d;i=_||(a+=b[(r=4*(m*i+e))+0],n+=b[r+1],s+=b[r+2],o+=b[r+3],p+=1);for(a/=p,n/=p,s/=p,o/=p,e=h;e=m))for(i=d;i=_||(b[(r=4*(m*i+e))+0]=a,b[r+1]=n,b[r+2]=s,b[r+3]=o)}},Posterize:function(t){var e,i=Math.round(254*this.levels())+1,r=t.data,a=r.length,n=255/i;for(e=0;e127&&(h=255-h),l>127&&(l=255-l),d>127&&(d=255-d),e[o]=h,e[o+1]=l,e[o+2]=d}while(--s)}while(--a)},Threshold:function(t){var e,i=255*this.threshold(),r=t.data,a=r.length;for(e=0;e number { +var now = (function (): () => number { if (glob.performance && glob.performance.now) { - return function() { + return function () { return glob.performance.now(); }; } - return function() { + return function () { return new Date().getTime(); }; })(); @@ -42,11 +43,11 @@ export class Animation { layers: Layer[]; - frame : IFrame = { + frame: IFrame = { time: 0, timeDiff: 0, lastTime: now(), - frameRate: 0 + frameRate: 0, }; constructor(func: AnimationFn, layers?) { @@ -67,7 +68,7 @@ export class Animation { lays = []; } else if (layers.length > 0) { // if passing in an array of Layers - // NOTE: layers could be an array or Konva.Collection. for simplicity, I'm just inspecting + // NOTE: layers could be an array. for simplicity, I'm just inspecting // the length property to check for both cases lays = layers; } else { @@ -242,7 +243,7 @@ export class Animation { var Anim = Animation; if (Anim.animations.length) { Anim._runFrames(); - requestAnimationFrame(Anim._animationLoop); + Util.requestAnimFrame(Anim._animationLoop); } else { Anim.animRunning = false; } @@ -250,7 +251,7 @@ export class Animation { static _handleAnimation() { if (!this.animRunning) { this.animRunning = true; - requestAnimationFrame(this._animationLoop); + Util.requestAnimFrame(this._animationLoop); } } } diff --git a/src/Container.ts b/src/Container.ts index 517a58cf..450d6a93 100644 --- a/src/Container.ts +++ b/src/Container.ts @@ -1,9 +1,7 @@ -import { Util, Collection } from './Util'; +import { Util } from './Util'; import { Factory } from './Factory'; import { Node, NodeConfig } from './Node'; -import { DD } from './DragAndDrop'; import { getNumberValidator } from './Validators'; -import { Konva } from './Global'; import { GetSet, IRect } from './types'; import { Shape } from './Shape'; @@ -31,14 +29,14 @@ export interface ContainerConfig extends NodeConfig { export abstract class Container< ChildType extends Node > extends Node { - children = new Collection(); + children: Array | undefined = []; /** - * returns a {@link Konva.Collection} of direct descendant nodes + * returns an array of direct descendant nodes * @method * @name Konva.Container#getChildren * @param {Function} [filterFunc] filter function - * @returns {Konva.Collection} + * @returns {Array} * @example * // get all children * var children = layer.getChildren(); @@ -50,11 +48,12 @@ export abstract class Container< */ getChildren(filterFunc?: (item: Node) => boolean) { if (!filterFunc) { - return this.children; + return this.children || []; } - var results = new Collection(); - this.children.each(function (child) { + const children = this.children || []; + var results: Array = []; + children.forEach(function (child) { if (filterFunc(child)) { results.push(child); } @@ -77,15 +76,13 @@ export abstract class Container< * @name Konva.Container#removeChildren */ removeChildren() { - var child; - for (var i = 0; i < this.children.length; i++) { - child = this.children[i]; + this.getChildren().forEach((child) => { // reset parent to prevent many _setChildrenIndices calls child.parent = null; child.index = 0; child.remove(); - } - this.children = new Collection(); + }); + this.children = []; return this; } /** @@ -94,15 +91,13 @@ export abstract class Container< * @name Konva.Container#destroyChildren */ destroyChildren() { - var child; - for (var i = 0; i < this.children.length; i++) { - child = this.children[i]; + this.getChildren().forEach((child) => { // reset parent to prevent many _setChildrenIndices calls child.parent = null; child.index = 0; child.destroy(); - } - this.children = new Collection(); + }); + this.children = []; return this; } abstract _validateAdd(node: Node): void; @@ -130,12 +125,11 @@ export abstract class Container< child.moveTo(this); return this; } - var _children = this.children; this._validateAdd(child); child._clearCaches(); - child.index = _children.length; + child.index = this.getChildren().length; child.parent = this; - _children.push(child); + this.getChildren().push(child); this._fire('add', { child: child, }); @@ -150,7 +144,7 @@ export abstract class Container< return this; } /** - * return a {@link Konva.Collection} of nodes that match the selector. + * return an array of nodes that match the selector. * You can provide a string with '#' for id selections and '.' for name selections. * Or a function that will return true/false when a node is passed through. See example below. * With strings you can also select by type or class name. Pass multiple selectors @@ -158,7 +152,7 @@ export abstract class Container< * @method * @name Konva.Container#find * @param {String | Function} selector - * @returns {Collection} + * @returns {Array} * @example * * Passing a string as a selector @@ -189,18 +183,11 @@ export abstract class Container< * return node.getType() === 'Node' && node.getAbsoluteOpacity() < 1; * }); */ - find(selector): Collection { + find(selector): Array { // protecting _generalFind to prevent user from accidentally adding // second argument and getting unexpected `findOne` result return this._generalFind(selector, false); } - - get(selector) { - Util.warn( - 'collection.get() method is deprecated. Please use collection.find() instead.' - ); - return this.find(selector); - } /** * return a first node from `find` method * @method @@ -240,12 +227,12 @@ export abstract class Container< return false; }); - return Collection.toCollection(retArr); + return retArr; } private _descendants(fn: (n: Node) => boolean) { let shouldStop = false; - for (var i = 0; i < this.children.length; i++) { - const child = this.children[i]; + const children = this.getChildren(); + for (const child of children) { shouldStop = fn(child); if (shouldStop) { return true; @@ -266,12 +253,9 @@ export abstract class Container< obj.children = []; - var children = this.getChildren(); - var len = children.length; - for (var n = 0; n < len; n++) { - var child = children[n]; + this.getChildren().forEach((child) => { obj.children.push(child.toObject()); - } + }); return obj; } @@ -297,10 +281,10 @@ export abstract class Container< // call super method var node = Node.prototype.clone.call(this, obj); - this.getChildren().each(function (no) { + this.getChildren().forEach(function (no) { node.add(no.clone()); }); - return node; + return node as this; } /** * get all shapes that intersect a point. Note: because this method must clear a temporary @@ -317,7 +301,7 @@ export abstract class Container< getAllIntersections(pos) { var arr = []; - this.find('Shape').each(function (shape: Shape) { + this.find('Shape').forEach(function (shape: Shape) { if (shape.isVisible() && shape.intersects(pos)) { arr.push(shape); } @@ -325,8 +309,19 @@ export abstract class Container< return arr; } + _clearSelfAndDescendantCache(attr?: string, forceEvent?: boolean) { + super._clearSelfAndDescendantCache(attr, forceEvent); + // skip clearing if node is cached with canvas + // for performance reasons !!! + if (this.isCached()) { + return; + } + this.children?.forEach(function (node) { + node._clearSelfAndDescendantCache(attr, forceEvent); + }); + } _setChildrenIndices() { - this.children.each(function (child, n) { + this.children?.forEach(function (child, n) { child.index = n; }); } @@ -412,7 +407,7 @@ export abstract class Container< context._applyGlobalCompositeOperation(this); } - this.children.each(function (child) { + this.children?.forEach(function (child) { child[drawMethod](canvas, top); }); if (hasComposition) { @@ -442,7 +437,7 @@ export abstract class Container< height: 0, }; var that = this; - this.children.each(function (child) { + this.children?.forEach(function (child) { // skip invisible children if (!child.visible()) { return; @@ -634,5 +629,3 @@ Factory.addGetterSetter(Container, 'clipFunc'); * ctx.rect(0, 0, 100, 100); * }); */ - -Collection.mapMethods(Container); diff --git a/src/Context.ts b/src/Context.ts index d7e7142b..b15a33ba 100644 --- a/src/Context.ts +++ b/src/Context.ts @@ -152,7 +152,7 @@ export class Context { } } - getTrace(relaxed) { + getTrace(relaxed?, rounded?) { var traceArr = this.traceArr, len = traceArr.length, str = '', @@ -175,6 +175,11 @@ export class Context { if (Util._isArray(args[0])) { str += OPEN_PAREN_BRACKET + args.join(COMMA) + CLOSE_BRACKET_PAREN; } else { + if (rounded) { + args = args.map((a) => + typeof a === 'number' ? Math.floor(a) : a + ); + } str += OPEN_PAREN + args.join(COMMA) + CLOSE_PAREN; } } @@ -611,7 +616,6 @@ export class Context { _enableTrace() { var that = this, len = CONTEXT_METHODS.length, - _simplifyArray = Util._simplifyArray, origSetter = this.setAttr, n, args; @@ -622,7 +626,7 @@ export class Context { ret; that[methodName] = function () { - args = _simplifyArray(Array.prototype.slice.call(arguments, 0)); + args = Util._simplifyArray(Array.prototype.slice.call(arguments, 0)); ret = origMethod.apply(that, arguments); that._trace({ diff --git a/src/Core.ts b/src/Core.ts index 9e054f5e..e6eecb92 100644 --- a/src/Core.ts +++ b/src/Core.ts @@ -1,8 +1,5 @@ // enter file of limited Konva version with only core functions +export { Konva } from './_CoreInternals'; +import { Konva } from './_CoreInternals'; -var Konva = require('./_CoreInternals').Konva; -// add Konva to global variable -Konva._injectGlobal(Konva); -exports['default'] = Konva; -Konva.default = Konva; -module.exports = exports['default']; +export default Konva; diff --git a/src/FastLayer.ts b/src/FastLayer.ts index 49cd745b..a7f59931 100644 --- a/src/FastLayer.ts +++ b/src/FastLayer.ts @@ -1,5 +1,4 @@ -import { Util, Collection } from './Util'; -import { Container } from './Container'; +import { Util } from './Util'; import { Layer } from './Layer'; import { _registerNode } from './Global'; @@ -28,5 +27,3 @@ export class FastLayer extends Layer { FastLayer.prototype.nodeType = 'FastLayer'; _registerNode(FastLayer); - -Collection.mapMethods(FastLayer); diff --git a/src/Global.ts b/src/Global.ts index 8c90eca5..d6c2c459 100644 --- a/src/Global.ts +++ b/src/Global.ts @@ -24,7 +24,7 @@ function detectBrowser() { ); } -const _detectIE = function(ua) { +const _detectIE = function (ua) { var msie = ua.indexOf('msie '); if (msie > 0) { // IE 10 or older => return version number @@ -48,7 +48,7 @@ const _detectIE = function(ua) { return false; }; -export const _parseUA = function(userAgent) { +export const _parseUA = function (userAgent) { var ua = userAgent.toLowerCase(), // jQuery UA regex match = @@ -71,7 +71,7 @@ export const _parseUA = function(userAgent) { isIE: _detectIE(ua), // adding mobile flab mobile: mobile, - ieMobile: ieMobile // If this is true (i.e., WP8), then Konva touch events are executed instead of equivalent Konva mouse events + ieMobile: ieMobile, // If this is true (i.e., WP8), then Konva touch events are executed instead of equivalent Konva mouse events }; }; @@ -90,13 +90,14 @@ export const Konva = { _global: glob, version: '@@version', isBrowser: detectBrowser(), - isUnminified: /param/.test(function(param) {}.toString()), + isUnminified: /param/.test(function (param) {}.toString()), dblClickWindow: 400, getAngle(angle) { return Konva.angleDeg ? angle * PI_OVER_180 : angle; }, enableTrace: false, _pointerEventsEnabled: false, + autoDrawEnabled: false, /** * Should we enable hit detection while dragging? For performance reasons, by default it is false. * But on some rare cases you want to see hit graph and check intersections. Just set it to true. @@ -137,7 +138,7 @@ export const Konva = { * // before any Konva code: * Konva.pixelRatio = 1; */ - pixelRatio: undefined, + pixelRatio: (typeof window !== 'undefined' && window.devicePixelRatio) || 1, /** * Drag distance property. If you start to drag a node you may want to wait until pointer is moved to some distance from start point, @@ -207,12 +208,14 @@ export const Konva = { _injectGlobal(Konva) { glob.Konva = Konva; }, - _parseUA + _parseUA, }; export const _NODES_REGISTRY = {}; -export const _registerNode = NodeClass => { +export const _registerNode = (NodeClass) => { _NODES_REGISTRY[NodeClass.prototype.getClassName()] = NodeClass; Konva[NodeClass.prototype.getClassName()] = NodeClass; }; + +Konva._injectGlobal(Konva); diff --git a/src/Group.ts b/src/Group.ts index 8020815a..4ebb0bd5 100644 --- a/src/Group.ts +++ b/src/Group.ts @@ -1,4 +1,4 @@ -import { Util, Collection } from './Util'; +import { Util } from './Util'; import { Container } from './Container'; import { _registerNode } from './Global'; import { Node } from './Node'; @@ -26,5 +26,3 @@ export class Group extends Container { Group.prototype.nodeType = 'Group'; _registerNode(Group); - -Collection.mapMethods(Group); diff --git a/src/Layer.ts b/src/Layer.ts index 86a3d3e7..92015449 100644 --- a/src/Layer.ts +++ b/src/Layer.ts @@ -1,4 +1,4 @@ -import { Util, Collection } from './Util'; +import { Util } from './Util'; import { Container, ContainerConfig } from './Container'; import { Node } from './Node'; import { Factory } from './Factory'; @@ -83,6 +83,14 @@ export class Layer extends Container { getCanvas() { return this.canvas; } + /** + * get native canvas element + * @method + * @name Konva.Layer#getCanvas + */ + getCanvasElement() { + return this.canvas._canvas; + } /** * get layer hit canvas * @method @@ -127,16 +135,16 @@ export class Layer extends Container { setZIndex(index) { super.setZIndex(index); var stage = this.getStage(); - if (stage) { - stage.content.removeChild(this.getCanvas()._canvas); + if (stage && stage.content) { + stage.content.removeChild(this.getCanvasElement()); if (index < stage.children.length - 1) { stage.content.insertBefore( - this.getCanvas()._canvas, + this.getCanvasElement(), stage.children[index + 1].getCanvas()._canvas ); } else { - stage.content.appendChild(this.getCanvas()._canvas); + stage.content.appendChild(this.getCanvasElement()); } } return this; @@ -144,9 +152,9 @@ export class Layer extends Container { moveToTop() { Node.prototype.moveToTop.call(this); var stage = this.getStage(); - if (stage) { - stage.content.removeChild(this.getCanvas()._canvas); - stage.content.appendChild(this.getCanvas()._canvas); + if (stage && stage.content) { + stage.content.removeChild(this.getCanvasElement()); + stage.content.appendChild(this.getCanvasElement()); } return true; } @@ -156,18 +164,18 @@ export class Layer extends Container { return false; } var stage = this.getStage(); - if (!stage) { + if (!stage || !stage.content) { return false; } - stage.content.removeChild(this.getCanvas()._canvas); + stage.content.removeChild(this.getCanvasElement()); if (this.index < stage.children.length - 1) { stage.content.insertBefore( - this.getCanvas()._canvas, + this.getCanvasElement(), stage.children[this.index + 1].getCanvas()._canvas ); } else { - stage.content.appendChild(this.getCanvas()._canvas); + stage.content.appendChild(this.getCanvasElement()); } return true; } @@ -177,11 +185,13 @@ export class Layer extends Container { var stage = this.getStage(); if (stage) { var children = stage.children; - stage.content.removeChild(this.getCanvas()._canvas); - stage.content.insertBefore( - this.getCanvas()._canvas, - children[this.index + 1].getCanvas()._canvas - ); + if (stage.content) { + stage.content.removeChild(this.getCanvasElement()); + stage.content.insertBefore( + this.getCanvasElement(), + children[this.index + 1].getCanvas()._canvas + ); + } } return true; } @@ -193,11 +203,13 @@ export class Layer extends Container { var stage = this.getStage(); if (stage) { var children = stage.children; - stage.content.removeChild(this.getCanvas()._canvas); - stage.content.insertBefore( - this.getCanvas()._canvas, - children[1].getCanvas()._canvas - ); + if (stage.content) { + stage.content.removeChild(this.getCanvasElement()); + stage.content.insertBefore( + this.getCanvasElement(), + children[1].getCanvas()._canvas + ); + } } return true; } @@ -207,7 +219,7 @@ export class Layer extends Container { return this; } remove() { - var _canvas = this.getCanvas()._canvas; + var _canvas = this.getCanvasElement(); Node.prototype.remove.call(this); @@ -394,7 +406,7 @@ export class Layer extends Container { // empty pixel return {}; } - drawScene(can, top) { + drawScene(can?: SceneCanvas, top?: Node) { var layer = this.getLayer(), canvas = can || (layer && layer.getCanvas()); @@ -414,7 +426,7 @@ export class Layer extends Container { return this; } - drawHit(can, top) { + drawHit(can?: HitCanvas, top?: Node) { var layer = this.getLayer(), canvas = can || (layer && layer.hitCanvas); @@ -466,7 +478,7 @@ export class Layer extends Container { * @method */ toggleHitCanvas() { - if (!this.parent) { + if (!this.parent || !this.parent['content']) { return; } var parent = this.parent as any; @@ -543,5 +555,3 @@ Factory.addGetterSetter(Layer, 'hitGraphEnabled', true, getBooleanValidator()); * // enable hit graph * layer.hitGraphEnabled(true); */ - -Collection.mapMethods(Layer); diff --git a/src/Node.ts b/src/Node.ts index 9ab0b0a0..3f03e365 100644 --- a/src/Node.ts +++ b/src/Node.ts @@ -1,4 +1,4 @@ -import { Util, Collection, Transform } from './Util'; +import { Util, Transform } from './Util'; import { Factory } from './Factory'; import { SceneCanvas, HitCanvas, Canvas } from './Canvas'; import { Konva, _NODES_REGISTRY } from './Global'; @@ -159,7 +159,7 @@ var ABSOLUTE_OPACITY = 'absoluteOpacity', SCALE_CHANGE_STR = ['scaleXChange.konva', 'scaleYChange.konva'].join(SPACE); // TODO: can we remove children from node? -const emptyChildren: Collection = new Collection(); +const emptyChildren = []; let idCounter = 1; @@ -207,7 +207,6 @@ export abstract class Node { _filterUpToDate = false; _isUnderCache = false; - children = emptyChildren; nodeType!: string; className!: string; @@ -288,19 +287,8 @@ export abstract class Node { _clearSelfAndDescendantCache(attr?: string, forceEvent?: boolean) { this._clearCache(attr); // trigger clear cache, so transformer can use it - if (forceEvent && attr === ABSOLUTE_TRANSFORM) { - this.fire('_clearTransformCache'); - } - - // skip clearing if node is cached with canvas - // for performance reasons !!! - if (this.isCached()) { - return; - } - if (this.children) { - this.children.each(function (node) { - node._clearSelfAndDescendantCache(attr, true); - }); + if (attr === ABSOLUTE_TRANSFORM) { + this.fire('absoluteTransformChange'); } } /** @@ -779,7 +767,7 @@ export abstract class Node { * // remove listener by name * node.off('click.foo'); */ - off(evtStr: string, callback?: Function) { + off(evtStr?: string, callback?: Function) { var events = (evtStr || '').split(SPACE), len = events.length, n, @@ -930,15 +918,15 @@ export abstract class Node { * get ancestors * @method * @name Konva.Node#getAncestors - * @returns {Konva.Collection} + * @returns {Array} * @example - * shape.getAncestors().each(function(node) { + * shape.getAncestors().forEach(function(node) { * console.log(node.getId()); * }) */ getAncestors() { var parent = this.getParent(), - ancestors = new Collection(); + ancestors: Array = []; while (parent) { ancestors.push(parent); @@ -1118,7 +1106,7 @@ export abstract class Node { index++; if (child.nodeType !== SHAPE) { - nodes = nodes.concat(child.getChildren().toArray()); + nodes = nodes.concat(child.getChildren().slice()); } if (child._id === that._id) { @@ -1589,7 +1577,7 @@ export abstract class Node { * // get one of the parent group * var group = node.findAncestors('.mygroup'); */ - findAncestor(selector, includeSelf?, stopNode?) { + findAncestor(selector?: string, includeSelf?: boolean, stopNode?: Node) { return this.findAncestors(selector, includeSelf, stopNode)[0]; } // is current node match passed selector? @@ -1950,7 +1938,7 @@ export abstract class Node { * @example * var canvas = node.toCanvas(); */ - toCanvas(config) { + toCanvas(config?) { return this._toKonvaCanvas(config)._canvas; } /** @@ -2243,6 +2231,10 @@ export abstract class Node { if (this._shouldFireChangeEvents) { this._fireChangeEvent(key, oldVal, val); } + if (Konva.autoDrawEnabled) { + const drawNode = this.getLayer() || this.getStage(); + drawNode?.batchDraw(); + } } _setComponentAttr(key, component, val) { var oldVal; @@ -3237,5 +3229,3 @@ Factory.backCompat(Node, { setRotationDeg: 'setRotation', getRotationDeg: 'getRotation', }); - -Collection.mapMethods(Node); diff --git a/src/Shape.ts b/src/Shape.ts index c5551aa1..120bd0f0 100644 --- a/src/Shape.ts +++ b/src/Shape.ts @@ -1,4 +1,4 @@ -import { Util, Collection } from './Util'; +import { Util } from './Util'; import { Factory } from './Factory'; import { Node, NodeConfig } from './Node'; import { @@ -55,7 +55,7 @@ export interface ShapeConfig extends NodeConfig { fillRadialGradientColorStops?: Array; fillEnabled?: boolean; fillPriority?: string; - stroke?: string; + stroke?: string | CanvasGradient; strokeWidth?: number; fillAfterStrokeEnabled?: boolean; hitStrokeWidth?: number | string; @@ -169,9 +169,9 @@ function _clearRadialGradientCache() { * } *}); */ -export class Shape extends Node< - Config -> { +export class Shape< + Config extends ShapeConfig = ShapeConfig +> extends Node { _centroid: boolean; colorKey: string; @@ -656,9 +656,8 @@ export class Shape extends Node< cachedHitCanvas = cachedCanvas && cachedCanvas.hit; if (!this.colorKey) { - console.log(this); Util.warn( - 'Looks like your canvas has a destroyed shape in it. Do not reuse shape after you destroyed it. See the shape in logs above. If you want to reuse shape you should call remove() instead of destroy()' + 'Looks like your canvas has a destroyed shape in it. Do not reuse shape after you destroyed it. If you want to reuse shape you should call remove() instead of destroy()' ); } @@ -777,7 +776,7 @@ export class Shape extends Node< fillLinearRadialEndPoint: GetSet; fillLinearRadialEndPointX: GetSet; fillLinearRadialEndPointY: GetSet; - fillPatternImage: GetSet; + fillPatternImage: GetSet; fillRadialGradientStartRadius: GetSet; fillRadialGradientEndRadius: GetSet; fillRadialGradientColorStops: GetSet, this>; @@ -1996,5 +1995,3 @@ Factory.backCompat(Shape, { getDrawHitFunc: 'getHitFunc', setDrawHitFunc: 'setHitFunc', }); - -Collection.mapMethods(Shape); diff --git a/src/Stage.ts b/src/Stage.ts index a8759f78..4f30d34b 100644 --- a/src/Stage.ts +++ b/src/Stage.ts @@ -1,4 +1,4 @@ -import { Util, Collection } from './Util'; +import { Util } from './Util'; import { Factory } from './Factory'; import { Container, ContainerConfig } from './Container'; import { Konva } from './Global'; @@ -223,11 +223,12 @@ export class Stage extends Container { } return this; } - clone(obj) { + clone(obj?) { if (!obj) { obj = {}; } - obj.container = document.createElement('div'); + obj.container = + typeof document !== 'undefined' && document.createElement('div'); return Container.prototype.clone.call(this, obj); } @@ -295,7 +296,7 @@ export class Stage extends Container { _context.translate(-1 * config.x, -1 * config.y); } - layers.each(function (layer) { + layers.forEach(function (layer) { if (!layer.isVisible()) { return; } @@ -326,18 +327,17 @@ export class Stage extends Container { * // or if you interested in shape parent: * var group = stage.getIntersection({x: 50, y: 50}, 'Group'); */ - getIntersection(pos: Vector2d | null, selector?: string): Shape | null { + getIntersection(pos: Vector2d | null, selector?: string) { if (!pos) { return null; } var layers = this.children, len = layers.length, end = len - 1, - n, - shape; + n; for (n = end; n >= 0; n--) { - shape = layers[n].getIntersection(pos, selector); + const shape = layers[n].getIntersection(pos, selector); if (shape) { return shape; } @@ -358,12 +358,12 @@ export class Stage extends Container { this.bufferHitCanvas.setSize(width, height); // set layer dimensions - this.children.each((layer) => { + this.children.forEach((layer) => { layer.setSize({ width, height }); layer.draw(); }); } - add(layer: Layer) { + add(layer: Layer, ...rest) { if (arguments.length > 1) { for (var i = 0; i < arguments.length; i++) { this.add(arguments[i]); @@ -412,12 +412,12 @@ export class Stage extends Container { } /** - * returns a {@link Konva.Collection} of layers + * returns an array of layers * @method * @name Konva.Stage#getLayers */ getLayers() { - return this.getChildren(); + return this.children; } _bindContentEvents() { if (!Konva.isBrowser) { @@ -470,11 +470,10 @@ export class Stage extends Container { } this.setPointersPositions(evt); var pointerId = Util._getFirstPointerId(evt); - var shape: Shape; var targetShape = this.targetShape?.getStage() ? this.targetShape : null; var eventsEnabled = !DD.isDragging || Konva.hitOnDragEnabled; if (eventsEnabled) { - shape = this.getIntersection(this.getPointerPosition()); + const shape = this.getIntersection(this.getPointerPosition()) as Shape; if (shape && shape.isListening()) { var differentTarget = targetShape !== shape; if (eventsEnabled && differentTarget) { @@ -542,7 +541,7 @@ export class Stage extends Container { } this.setPointersPositions(evt); var pointerId = Util._getFirstPointerId(evt); - var shape = this.getIntersection(this.getPointerPosition()); + var shape = this.getIntersection(this.getPointerPosition()) as Shape; DD.justDragged = false; Konva.listenClickTap = true; @@ -576,7 +575,7 @@ export class Stage extends Container { } this.setPointersPositions(evt); var pointerId = Util._getFirstPointerId(evt); - var shape = this.getIntersection(this.getPointerPosition()), + var shape = this.getIntersection(this.getPointerPosition()) as Shape, clickStartShape = this.clickStartShape, clickEndShape = this.clickEndShape, fireDblClick = false; @@ -673,7 +672,7 @@ export class Stage extends Container { this.setPointersPositions(evt); var triggeredOnShape = false; this._changedPointerPositions.forEach((pos) => { - var shape = this.getIntersection(pos); + var shape = this.getIntersection(pos) as Shape; Konva.listenClickTap = true; DD.justDragged = false; const hasShape = shape && shape.isListening(); @@ -775,7 +774,7 @@ export class Stage extends Container { this._changedPointerPositions.forEach((pos) => { var shape = (PointerEvents.getCapturedShape(pos.id) as Shape) || - this.getIntersection(pos); + (this.getIntersection(pos) as Shape); if (shape) { shape.releaseCapture(pos.id); @@ -961,7 +960,7 @@ export class Stage extends Container { // so we have to iterate this._pointerPositions = []; this._changedPointerPositions = []; - Collection.prototype.each.call(evt.touches, (touch: any) => { + Array.prototype.forEach.call(evt.touches, (touch: any) => { this._pointerPositions.push({ id: touch.identifier, x: (touch.clientX - contentPosition.left) / contentPosition.scaleX, @@ -969,7 +968,7 @@ export class Stage extends Container { }); }); - Collection.prototype.each.call( + Array.prototype.forEach.call( evt.changedTouches || evt.touches, (touch: any) => { this._changedPointerPositions.push({ @@ -1070,7 +1069,7 @@ export class Stage extends Container { * @return {Konva.Stage} this */ batchDraw() { - this.children.each(function (layer) { + this.children.forEach(function (layer) { layer.batchDraw(); }); return this; diff --git a/src/Util.ts b/src/Util.ts index 2978fcba..d562f4dc 100644 --- a/src/Util.ts +++ b/src/Util.ts @@ -1,111 +1,6 @@ -import { glob, Konva } from './Global'; -import { Node } from './Node'; +import { Konva } from './Global'; import { IRect, RGB, RGBA, Vector2d } from './types'; -/** - * Collection constructor. Collection extends Array. - * This class is used in conjunction with {@link Konva.Container#find} - * The good thing about collection is that it has ALL methods of all Konva nodes. Take a look into examples. - * @constructor - * @memberof Konva - * @example - * - * // find all rectangles and return them as Collection - * const shapes = layer.find('Rect'); - * // fill all rectangles with a single function - * shapes.fill('red'); - */ -export class Collection { - [index: number]: Child; - - // @ts-ignore - [Symbol.iterator](): Iterator; - // @ts-ignore - length: number; - // @ts-ignore - each: (f: (child: Child, index: number) => void) => void; - // @ts-ignore - toArray: () => Array; - // @ts-ignore - push: (item: Child) => void; - // @ts-ignore - unshift: (item: Child) => void; - // @ts-ignore - splice: (start: number, length: number, replace?: any) => void; - - /** - * convert array into a collection - * @method - * @memberof Konva.Collection - * @param {Array} arr - */ - static toCollection(arr: Array) { - var collection = new Collection(), - len = arr.length, - n; - - for (n = 0; n < len; n++) { - collection.push(arr[n]); - } - return collection; - } - - static _mapMethod(methodName: any) { - Collection.prototype[methodName] = function () { - var len = this.length, - i; - - var args = [].slice.call(arguments); - for (i = 0; i < len; i++) { - this[i][methodName].apply(this[i], args); - } - - return this; - }; - } - - static mapMethods = function (constructor: Function) { - var prot = constructor.prototype; - for (var methodName in prot) { - Collection._mapMethod(methodName); - } - }; -} - -Collection.prototype = [] as any; -/** - * iterate through node array and run a function for each node. - * The node and index is passed into the function - * @method - * @name Konva.Collection#each - * @param {Function} func - * @example - * // get all nodes with name foo inside layer, and set x to 10 for each - * layer.find('.foo').each(function(shape, n) { - * shape.setX(10); - * }); - */ -Collection.prototype.each = function (func) { - for (var n = 0; n < this.length; n++) { - func(this[n], n); - } -}; -/** - * convert collection into an array - * @method - * @name Konva.Collection#toArray - */ -Collection.prototype.toArray = function () { - var arr = [], - len = this.length, - n; - - for (n = 0; n < len; n++) { - arr.push(this[n]); - } - return arr; -}; - /* * Last updated November 2011 * By Simon Sarris @@ -612,8 +507,13 @@ export const Util = { requestAnimFrame(callback: Function) { animQueue.push(callback); + const req = + (typeof requestAnimationFrame !== 'undefined' && requestAnimationFrame) || + function (f) { + setTimeout(f, 60); + }; if (animQueue.length === 1) { - requestAnimationFrame(function () { + req(function () { const queue = animQueue; animQueue = []; queue.forEach(function (cb) { @@ -653,7 +553,7 @@ export const Util = { if (util._isNumber(val)) { val = Math.round(val * 1000) / 1000; } else if (!util._isString(val)) { - val = val.toString(); + val = val + ''; } retArr.push(val); diff --git a/src/Validators.ts b/src/Validators.ts index c6f77768..a41e6537 100644 --- a/src/Validators.ts +++ b/src/Validators.ts @@ -56,10 +56,12 @@ export function getNumberOrArrayOfNumbersValidator(noOfElements: number) { let isValidArray = Util._isArray(val) && val.length == noOfElements; if (!isNumber && !isValidArray) { Util.warn( - _formatValue(val) + + _formatValue(val) + ' is a not valid value for "' + attr + - '" attribute. The value should be a number or Array(' + noOfElements + ')' + '" attribute. The value should be a number or Array(' + + noOfElements + + ')' ); } return val; @@ -107,7 +109,8 @@ export function getStringOrGradientValidator() { return function (val: any, attr: string) { const isString = Util._isString(val); const isGradient = - Object.prototype.toString.call(val) === '[object CanvasGradient]'; + Object.prototype.toString.call(val) === '[object CanvasGradient]' || + (val && val.addColorStop); if (!(isString || isGradient)) { Util.warn( _formatValue(val) + diff --git a/src/_CoreInternals.ts b/src/_CoreInternals.ts index 300f2281..4a539eda 100644 --- a/src/_CoreInternals.ts +++ b/src/_CoreInternals.ts @@ -1,7 +1,7 @@ // what is core parts of Konva? import { Konva as Global } from './Global'; -import { Collection, Util, Transform } from './Util'; +import { Util, Transform } from './Util'; import { Node, ids, names } from './Node'; import { Container } from './Container'; @@ -23,7 +23,6 @@ import { Context } from './Context'; import { Canvas } from './Canvas'; export const Konva = Util._assign(Global, { - Collection, Util, Transform, Node, @@ -42,5 +41,7 @@ export const Konva = Util._assign(Global, { Tween, Easings, Context, - Canvas + Canvas, }); + +export default Konva; diff --git a/src/index-node.ts b/src/index-node.ts new file mode 100644 index 00000000..e5dfc134 --- /dev/null +++ b/src/index-node.ts @@ -0,0 +1,23 @@ +// main entry for umd build for rollup +import { Konva } from './_FullInternals'; +import * as canvas from 'canvas'; + +const isNode = typeof global.document === 'undefined'; + +if (isNode) { + Konva.Util['createCanvasElement'] = () => { + const node = canvas.createCanvas(300, 300) as any; + if (!node['style']) { + node['style'] = {}; + } + return node; + }; + + // create image in Node env + Konva.Util.createImageElement = () => { + const node = new canvas.Image() as any; + return node; + }; +} + +export default Konva; diff --git a/src/index-types.d.ts b/src/index-types.d.ts index 932d7d28..f432984a 100644 --- a/src/index-types.d.ts +++ b/src/index-types.d.ts @@ -28,6 +28,7 @@ import { Solarize } from './filters/Solarize'; import { Threshold } from './filters/Threshold'; declare namespace Konva { + export let enableTrace: number; export let pixelRatio: number; export let dragDistance: number; export let angleDeg: boolean; @@ -43,9 +44,9 @@ declare namespace Konva { export type Node = import('./Node').Node; export type NodeConfig = import('./Node').NodeConfig; - export type KonvaEventObject = import('./Node').KonvaEventObject< + export type KonvaEventObject< EventType - >; + > = import('./Node').KonvaEventObject; export type KonvaPointerEvent = import('./PointerEvents').KonvaPointerEvent; @@ -58,8 +59,6 @@ declare namespace Konva { export type Container = import('./Container').Container; export type ContainerConfig = import('./Container').ContainerConfig; - export const Collection: typeof import('./Util').Collection; - export type Collection = import('./Util').Collection; export const Transform: typeof import('./Util').Transform; export type Transform = import('./Util').Transform; diff --git a/src/index-umd.ts b/src/index-umd.ts deleted file mode 100644 index 38140997..00000000 --- a/src/index-umd.ts +++ /dev/null @@ -1,4 +0,0 @@ -// main entry for umd build for rollup -import { Konva } from './_FullInternals'; - -export default Konva; diff --git a/src/index.ts b/src/index.ts index 08cfb979..75ffb064 100644 --- a/src/index.ts +++ b/src/index.ts @@ -1,7 +1,3 @@ -// main enter file of full Konva version +import { Konva } from './_FullInternals'; -var Konva = require('./_FullInternals').Konva; -// add Konva to global variable -Konva._injectGlobal(Konva); -exports['default'] = Konva; -module.exports = exports['default']; +export default Konva; diff --git a/src/shapes/Arc.ts b/src/shapes/Arc.ts index e26e7b77..ff65bfb2 100644 --- a/src/shapes/Arc.ts +++ b/src/shapes/Arc.ts @@ -1,4 +1,3 @@ -import { Collection } from '../Util'; import { Factory } from '../Factory'; import { Shape, ShapeConfig } from '../Shape'; import { Konva } from '../Global'; @@ -139,5 +138,3 @@ Factory.addGetterSetter(Arc, 'clockwise', false, getBooleanValidator()); * // draw arc clockwise * arc.clockwise(true); */ - -Collection.mapMethods(Arc); diff --git a/src/shapes/Arrow.ts b/src/shapes/Arrow.ts index 44831a4e..7e822e01 100644 --- a/src/shapes/Arrow.ts +++ b/src/shapes/Arrow.ts @@ -1,4 +1,3 @@ -import { Collection } from '../Util'; import { Factory } from '../Factory'; import { Line, LineConfig } from './Line'; import { GetSet } from '../types'; @@ -119,7 +118,7 @@ export class Arrow extends Line { x: lineRect.x - offset, y: lineRect.y - offset, width: lineRect.width + offset * 2, - height: lineRect.height + offset * 2 + height: lineRect.height + offset * 2, }; } @@ -177,4 +176,3 @@ Factory.addGetterSetter(Arrow, 'pointerWidth', 10, getNumberValidator()); */ Factory.addGetterSetter(Arrow, 'pointerAtBeginning', false); -Collection.mapMethods(Arrow); diff --git a/src/shapes/Circle.ts b/src/shapes/Circle.ts index b1dedd08..538b7b91 100644 --- a/src/shapes/Circle.ts +++ b/src/shapes/Circle.ts @@ -1,4 +1,3 @@ -import { Collection } from '../Util'; import { Factory } from '../Factory'; import { Shape, ShapeConfig } from '../Shape'; import { GetSet } from '../types'; @@ -73,5 +72,3 @@ _registerNode(Circle); * circle.radius(10); */ Factory.addGetterSetter(Circle, 'radius', 0, getNumberValidator()); - -Collection.mapMethods(Circle); diff --git a/src/shapes/Ellipse.ts b/src/shapes/Ellipse.ts index 383bd213..c410bbfa 100644 --- a/src/shapes/Ellipse.ts +++ b/src/shapes/Ellipse.ts @@ -1,4 +1,3 @@ -import { Collection } from '../Util'; import { Factory } from '../Factory'; import { Shape, ShapeConfig } from '../Shape'; import { getNumberValidator } from '../Validators'; @@ -118,5 +117,3 @@ Factory.addGetterSetter(Ellipse, 'radiusY', 0, getNumberValidator()); * // set radius y * ellipse.radiusY(200); */ - -Collection.mapMethods(Ellipse); diff --git a/src/shapes/Image.ts b/src/shapes/Image.ts index cc5cffae..0000af1d 100644 --- a/src/shapes/Image.ts +++ b/src/shapes/Image.ts @@ -1,4 +1,4 @@ -import { Util, Collection } from '../Util'; +import { Util } from '../Util'; import { Factory } from '../Factory'; import { Shape, ShapeConfig } from '../Shape'; import { getNumberValidator } from '../Validators'; @@ -86,10 +86,10 @@ export class Image extends Shape { context.fillStrokeShape(this); } getWidth() { - return this.attrs.width ?? (this.image()?.width || 0); + return this.attrs.width ?? this.image()?.width; } getHeight() { - return this.attrs.height ?? (this.image()?.height || 0); + return this.attrs.height ?? this.image()?.height; } /** @@ -225,5 +225,3 @@ Factory.addGetterSetter(Image, 'cropHeight', 0, getNumberValidator()); * // set crop height * image.cropHeight(20); */ - -Collection.mapMethods(Image); diff --git a/src/shapes/Label.ts b/src/shapes/Label.ts index cc9c2908..d4c3128c 100644 --- a/src/shapes/Label.ts +++ b/src/shapes/Label.ts @@ -1,4 +1,3 @@ -import { Collection } from '../Util'; import { Factory } from '../Factory'; import { Shape, ShapeConfig } from '../Shape'; import { Group } from '../Group'; @@ -10,6 +9,7 @@ import { import { _registerNode } from '../Global'; import { GetSet } from '../types'; +import { Text } from './Text'; export interface LabelConfig extends ContainerConfig {} @@ -72,7 +72,7 @@ var ATTR_CHANGE_LIST = [ * })); */ export class Label extends Group { - constructor(config) { + constructor(config?) { super(config); this.on('add.konva', function (evt) { this._addListeners(evt.child); @@ -89,7 +89,7 @@ export class Label extends Group { * label.getText().fill('red') */ getText() { - return this.find('Text')[0]; + return this.find('Text')[0]; } /** * get Tag shape for the label. You need to access the Tag shape in order to update @@ -175,13 +175,11 @@ export class Label extends Group { Label.prototype.className = 'Label'; _registerNode(Label); -Collection.mapMethods(Label); - export interface TagConfig extends ShapeConfig { pointerDirection?: string; pointerWidth?: number; pointerHeight?: number; - cornerRadius?: number; + cornerRadius?: number | Array; } /** @@ -378,5 +376,3 @@ Factory.addGetterSetter( 0, getNumberOrArrayOfNumbersValidator(4) ); - -Collection.mapMethods(Tag); diff --git a/src/shapes/Line.ts b/src/shapes/Line.ts index cdacdee2..e686bcaa 100644 --- a/src/shapes/Line.ts +++ b/src/shapes/Line.ts @@ -1,4 +1,4 @@ -import { Util, Collection } from '../Util'; +import { Util } from '../Util'; import { Factory } from '../Factory'; import { Shape, ShapeConfig } from '../Shape'; import { getNumberValidator, getNumberArrayValidator } from '../Validators'; @@ -8,7 +8,7 @@ import { GetSet } from '../types'; import { Context } from '../Context'; export interface LineConfig extends ShapeConfig { - points: number[]; + points?: number[]; tension?: number; closed?: boolean; bezier?: boolean; @@ -38,14 +38,14 @@ export interface LineConfig extends ShapeConfig { * }); */ -export class Line extends Shape< - Config -> { +export class Line< + Config extends LineConfig = LineConfig +> extends Shape { constructor(config?: Config) { super(config); this.on( 'pointsChange.konva tensionChange.konva closedChange.konva bezierChange.konva', - function() { + function () { this._clearCache('tensionPoints'); } ); @@ -172,7 +172,7 @@ export class Line extends Shape< firstControlPoints[0], firstControlPoints[1], p[0], - p[1] + p[1], ]); return tp; @@ -191,7 +191,7 @@ export class Line extends Shape< x: points[0] || 0, y: points[1] || 0, width: 0, - height: 0 + height: 0, }; } if (this.tension() !== 0) { @@ -200,7 +200,7 @@ export class Line extends Shape< points[1], ...this._getTensionPoints(), points[points.length - 2], - points[points.length - 1] + points[points.length - 1], ]; } else { points = this.points(); @@ -222,7 +222,7 @@ export class Line extends Shape< x: minX, y: minY, width: maxX - minX, - height: maxY - minY + height: maxY - minY, }; } @@ -305,5 +305,3 @@ Factory.addGetterSetter(Line, 'points', [], getNumberArrayValidator()); * // push a new point * line.points(line.points().concat([70, 80])); */ - -Collection.mapMethods(Line); diff --git a/src/shapes/Path.ts b/src/shapes/Path.ts index eed400e6..ecb2b507 100644 --- a/src/shapes/Path.ts +++ b/src/shapes/Path.ts @@ -1,4 +1,3 @@ -import { Collection } from '../Util'; import { Factory } from '../Factory'; import { Shape, ShapeConfig } from '../Shape'; import { _registerNode } from '../Global'; @@ -6,7 +5,7 @@ import { _registerNode } from '../Global'; import { GetSet } from '../types'; export interface PathConfig extends ShapeConfig { - data: string; + data?: string; } /** * Path constructor. @@ -960,5 +959,3 @@ _registerNode(Path); * path.data('M200,100h100v50z'); */ Factory.addGetterSetter(Path, 'data'); - -Collection.mapMethods(Path); diff --git a/src/shapes/Rect.ts b/src/shapes/Rect.ts index 1717f552..27549e7f 100644 --- a/src/shapes/Rect.ts +++ b/src/shapes/Rect.ts @@ -1,4 +1,3 @@ -import { Collection } from '../Util'; import { Factory } from '../Factory'; import { Shape, ShapeConfig } from '../Shape'; import { _registerNode } from '../Global'; @@ -119,5 +118,3 @@ Factory.addGetterSetter( 0, getNumberOrArrayOfNumbersValidator(4) ); - -Collection.mapMethods(Rect); diff --git a/src/shapes/RegularPolygon.ts b/src/shapes/RegularPolygon.ts index ab935932..580a156f 100644 --- a/src/shapes/RegularPolygon.ts +++ b/src/shapes/RegularPolygon.ts @@ -1,4 +1,3 @@ -import { Collection } from '../Util'; import { Factory } from '../Factory'; import { Shape, ShapeConfig } from '../Shape'; import { GetSet } from '../types'; @@ -127,5 +126,3 @@ Factory.addGetterSetter(RegularPolygon, 'radius', 0, getNumberValidator()); * shape.sides(10); */ Factory.addGetterSetter(RegularPolygon, 'sides', 0, getNumberValidator()); - -Collection.mapMethods(RegularPolygon); diff --git a/src/shapes/Ring.ts b/src/shapes/Ring.ts index 79133e06..bf547f10 100644 --- a/src/shapes/Ring.ts +++ b/src/shapes/Ring.ts @@ -1,4 +1,3 @@ -import { Collection } from '../Util'; import { Factory } from '../Factory'; import { Shape, ShapeConfig } from '../Shape'; import { GetSet } from '../types'; @@ -93,5 +92,3 @@ Factory.addGetterSetter(Ring, 'innerRadius', 0, getNumberValidator()); * ring.outerRadius(20); */ Factory.addGetterSetter(Ring, 'outerRadius', 0, getNumberValidator()); - -Collection.mapMethods(Ring); diff --git a/src/shapes/Sprite.ts b/src/shapes/Sprite.ts index accf3c20..832615c6 100644 --- a/src/shapes/Sprite.ts +++ b/src/shapes/Sprite.ts @@ -1,4 +1,3 @@ -import { Collection } from '../Util'; import { Factory } from '../Factory'; import { Shape, ShapeConfig } from '../Shape'; import { Animation } from '../Animation'; @@ -367,5 +366,3 @@ Factory.backCompat(Sprite, { getIndex: 'getFrameIndex', setIndex: 'setFrameIndex', }); - -Collection.mapMethods(Sprite); diff --git a/src/shapes/Star.ts b/src/shapes/Star.ts index 6c33d34e..4df5d97c 100644 --- a/src/shapes/Star.ts +++ b/src/shapes/Star.ts @@ -1,4 +1,3 @@ -import { Collection } from '../Util'; import { Factory } from '../Factory'; import { Shape, ShapeConfig } from '../Shape'; import { getNumberValidator } from '../Validators'; @@ -122,5 +121,3 @@ Factory.addGetterSetter(Star, 'innerRadius', 0, getNumberValidator()); */ Factory.addGetterSetter(Star, 'outerRadius', 0, getNumberValidator()); - -Collection.mapMethods(Star); diff --git a/src/shapes/Text.ts b/src/shapes/Text.ts index b1e814f5..959afa8d 100644 --- a/src/shapes/Text.ts +++ b/src/shapes/Text.ts @@ -1,4 +1,4 @@ -import { Util, Collection } from '../Util'; +import { Util } from '../Util'; import { Factory } from '../Factory'; import { Shape, ShapeConfig } from '../Shape'; import { Konva } from '../Global'; @@ -850,5 +850,3 @@ Factory.addGetterSetter(Text, 'text', '', getStringValidator()); */ Factory.addGetterSetter(Text, 'textDecoration', ''); - -Collection.mapMethods(Text); diff --git a/src/shapes/TextPath.ts b/src/shapes/TextPath.ts index de3c2371..50818f4c 100644 --- a/src/shapes/TextPath.ts +++ b/src/shapes/TextPath.ts @@ -1,4 +1,4 @@ -import { Util, Collection } from '../Util'; +import { Util } from '../Util'; import { Factory } from '../Factory'; import { Shape, ShapeConfig } from '../Shape'; import { Path } from './Path'; @@ -98,7 +98,7 @@ export class TextPath extends Shape { // update text data for certain attr changes this.on( - 'textChange.konva alignChange.konva letterSpacingChange.konva kerningFuncChange.konva', + 'textChange.konva alignChange.konva letterSpacingChange.konva kerningFuncChange.konva fontSizeChange.konva', this._setTextData ); @@ -738,5 +738,3 @@ Factory.addGetterSetter(TextPath, 'textDecoration', null); * }); */ Factory.addGetterSetter(TextPath, 'kerningFunc', null); - -Collection.mapMethods(TextPath); diff --git a/src/shapes/Transformer.ts b/src/shapes/Transformer.ts index 3e8bbd73..a882b567 100644 --- a/src/shapes/Transformer.ts +++ b/src/shapes/Transformer.ts @@ -1,4 +1,4 @@ -import { Util, Collection, Transform } from '../Util'; +import { Util, Transform } from '../Util'; import { Factory } from '../Factory'; import { Node } from '../Node'; import { Shape } from '../Shape'; @@ -305,7 +305,7 @@ export class Transformer extends Group { }; node.on(additionalEvents, onChange); node.on(TRANSFORM_CHANGE_STR, onChange); - node.on(`_clearTransformCache.${EVENTS_NAME}`, onChange); + node.on(`absoluteTransformChange.${EVENTS_NAME}`, onChange); node.on(`xChange.${EVENTS_NAME} yChange.${EVENTS_NAME}`, onChange); this._proxyDrag(node); }); @@ -544,11 +544,13 @@ export class Transformer extends Group { anchor.on('mouseenter', () => { var rad = Konva.getAngle(this.rotation()); var cursor = getCursor(name, rad); - anchor.getStage().content.style.cursor = cursor; + anchor.getStage().content && + (anchor.getStage().content.style.cursor = cursor); this._cursorChange = true; }); anchor.on('mouseout', () => { - anchor.getStage().content.style.cursor = ''; + anchor.getStage().content && + (anchor.getStage().content.style.cursor = ''); this._cursorChange = false; }); this.add(anchor); @@ -620,10 +622,12 @@ export class Transformer extends Group { this.sin = Math.abs(height / hypotenuse); this.cos = Math.abs(width / hypotenuse); - window.addEventListener('mousemove', this._handleMouseMove); - window.addEventListener('touchmove', this._handleMouseMove); - window.addEventListener('mouseup', this._handleMouseUp, true); - window.addEventListener('touchend', this._handleMouseUp, true); + if (typeof window !== 'undefined') { + window.addEventListener('mousemove', this._handleMouseMove); + window.addEventListener('touchmove', this._handleMouseMove); + window.addEventListener('mouseup', this._handleMouseUp, true); + window.addEventListener('touchend', this._handleMouseUp, true); + } this._transforming = true; var ap = e.target.getAbsolutePosition(); @@ -872,10 +876,12 @@ export class Transformer extends Group { _removeEvents(e?) { if (this._transforming) { this._transforming = false; - window.removeEventListener('mousemove', this._handleMouseMove); - window.removeEventListener('touchmove', this._handleMouseMove); - window.removeEventListener('mouseup', this._handleMouseUp, true); - window.removeEventListener('touchend', this._handleMouseUp, true); + if (typeof window !== 'undefined') { + window.removeEventListener('mousemove', this._handleMouseMove); + window.removeEventListener('touchmove', this._handleMouseMove); + window.removeEventListener('mouseup', this._handleMouseUp, true); + window.removeEventListener('touchend', this._handleMouseUp, true); + } var node = this.getNode(); this._fire('transformend', { evt: e, target: node }); @@ -887,7 +893,7 @@ export class Transformer extends Group { this._movingAnchorName = null; } } - _fitNodesInto(newAttrs, evt) { + _fitNodesInto(newAttrs, evt?) { var oldAttrs = this._getNodeRect(); const minSize = 1; @@ -1071,7 +1077,7 @@ export class Transformer extends Group { var padding = this.padding(); var anchorSize = this.anchorSize(); - this.find('._anchor').each((node) => { + this.find('._anchor').forEach((node) => { node.setAttrs({ width: anchorSize, height: anchorSize, @@ -1181,7 +1187,7 @@ export class Transformer extends Group { } destroy() { if (this.getStage() && this._cursorChange) { - this.getStage().content.style.cursor = ''; + this.getStage().content && (this.getStage().content.style.cursor = ''); } Group.prototype.destroy.call(this); this.detach(); @@ -1607,5 +1613,3 @@ Factory.backCompat(Transformer, { rotateHandlerOffset: 'rotateAnchorOffset', enabledHandlers: 'enabledAnchors', }); - -Collection.mapMethods(Transformer); diff --git a/src/shapes/Wedge.ts b/src/shapes/Wedge.ts index 4e20fc14..28b11792 100644 --- a/src/shapes/Wedge.ts +++ b/src/shapes/Wedge.ts @@ -1,4 +1,3 @@ -import { Collection } from '../Util'; import { Factory } from '../Factory'; import { Shape, ShapeConfig } from '../Shape'; import { Konva } from '../Global'; @@ -124,7 +123,5 @@ Factory.addGetterSetter(Wedge, 'clockwise', false); Factory.backCompat(Wedge, { angleDeg: 'angle', getAngleDeg: 'getAngle', - setAngleDeg: 'setAngle' + setAngleDeg: 'setAngle', }); - -Collection.mapMethods(Wedge); diff --git a/test.ts b/test.ts new file mode 100644 index 00000000..e69de29b diff --git a/test/assets/tiger.js b/test/assets/tiger.ts similarity index 99% rename from test/assets/tiger.js rename to test/assets/tiger.ts index 6a784620..754f7078 100644 --- a/test/assets/tiger.js +++ b/test/assets/tiger.ts @@ -1,4 +1,4 @@ -var tiger = [ +export default [ { fill: '#ffffff', stroke: '#000000', diff --git a/test/assets/worldMap.js b/test/assets/worldMap.ts similarity index 99% rename from test/assets/worldMap.js rename to test/assets/worldMap.ts index 5749ae80..2efc4ce8 100644 --- a/test/assets/worldMap.js +++ b/test/assets/worldMap.ts @@ -1,4 +1,4 @@ -var worldMap = { +export default { shapes: { AE: 'M604.196,161.643l0.514-0.129l0,0.772l2.188-0.386l2.189,0l1.672,0.129l1.803-1.802l2.058-1.802l1.674-1.673l0.518,0.900l0.385,2.189l-1.417,0l-0.258,1.802l0.517,0.386l-1.159,0.515l-0.129,1.029l-0.773,1.159l0,1.030l-0.514,0.644l-8.110-1.416l-1.031-2.704l0.127,0.643z', diff --git a/test/import-test.js b/test/import-test.js index 2a5d6b51..1aaf56cd 100644 --- a/test/import-test.js +++ b/test/import-test.js @@ -1,26 +1,29 @@ -function equal(val1, val2, message) { - if (val1 !== val2) { - throw new Error('Not passed: ' + message); - } -} +// TODO: restore +// function equal(val1, val2, message) { +// if (val1 !== val2) { +// throw new Error('Not passed: ' + message); +// } +// } -// try to import only core -let Konva = require('../lib/Core'); +// // try to import only core +// let { Konva } = require('../lib/Core'); -// no external shapes -equal(Konva.Rect, undefined, 'no external shapes'); +// // no external shapes +// equal(Konva.Rect, undefined, 'no external shapes'); -let Rect = require('../lib/shapes/Rect').Rect; +// let Rect = require('../lib/shapes/Rect').Rect; -equal(Rect !== undefined, true, 'Rect is defined'); -equal(Konva.Rect, Rect, 'Rect is injected'); +// equal(Rect !== undefined, true, 'Rect is defined'); -// now import from package.json -let NewKonva = require('../'); +// equal(Konva.Rect, Rect, 'Rect is injected'); -equal(NewKonva.Rect, Rect, 'Same rects'); +// // now import from package.json +// const oldKonva = Konva; +// Konva = require('../'); -// check global injection -equal(global.Konva, NewKonva, 'injected'); +// equal(Konva.Rect, Rect, 'Same rects'); -equal(NewKonva, Konva, 'Full package is the same as core.'); +// // check global injection +// equal(global.Konva, Konva, 'injected'); + +// equal(Konva, oldKonva, 'Full package is the same as core.'); diff --git a/test/manual/manual-test.js b/test/manual/manual-test.js index 39465017..3b599a6d 100644 --- a/test/manual/manual-test.js +++ b/test/manual/manual-test.js @@ -67,7 +67,9 @@ suite('Manual', function () { var velocity = 360; // 1 rev per second var anim = new Konva.Animation(function (frame) { - layer.find('Rect').rotate((velocity * frame.timeDiff) / 1000); + layer + .find('Rect') + .forEach((rect) => rect.rotate((velocity * frame.timeDiff) / 1000)); }, layer); anim.start(); diff --git a/test/parcel-runner.html b/test/parcel-runner.html index b4c7bac6..1fbd14d1 100644 --- a/test/parcel-runner.html +++ b/test/parcel-runner.html @@ -1,6 +1,37 @@
+ + + + + + + + +
+ + + diff --git a/test/parcel-runner.ts b/test/parcel-runner.ts index f42f9a3a..bfa96d9c 100644 --- a/test/parcel-runner.ts +++ b/test/parcel-runner.ts @@ -1,16 +1,34 @@ -// import 'mocha'; -// import chai from 'chai'; +import './unit-new/Animation-test.ts'; +import './unit-new/Canvas-test.ts'; +import './unit-new/Container-test.ts'; +import './unit-new/Context-test.ts'; +import './unit-new/DragAndDrop-test.ts'; +import './unit-new/Global-test.ts'; +import './unit-new/Group-test.ts'; +import './unit-new/Layer-test.ts'; +import './unit-new/Util-test.ts'; +import './unit-new/Stage-test.ts'; +import './unit-new/Shape-test.ts'; +import './unit-new/Node-test.ts'; +import './unit-new/Node-cache-test.ts'; -// mocha.ui('tdd'); -// mocha.setup('bdd'); -// mocha.run(); - -// import './unit-new/Shape-test'; - - - -import Konva from '../'; - -var shape = new Konva.Rect({ - filters: [Konva.Filters.Blur] -}) +import './unit-new/shapes/Rect-test.ts'; +import './unit-new/shapes/Circle-test.ts'; +import './unit-new/shapes/Image-test.ts'; +import './unit-new/shapes/Line-test.ts'; +import './unit-new/shapes/Text-test.ts'; +import './unit-new/shapes/Blob-test.ts'; +import './unit-new/shapes/Ellipse-test.ts'; +import './unit-new/shapes/Polygon-test.ts'; +import './unit-new/shapes/Spline-test.ts'; +import './unit-new/shapes/Sprite-test.ts'; +import './unit-new/shapes/Wedge-test.ts'; +import './unit-new/shapes/Arc-test.ts'; +import './unit-new/shapes/Ring-test.ts'; +import './unit-new/shapes/Label-test.ts'; +import './unit-new/shapes/Star-test.ts'; +import './unit-new/shapes/RegularPolygon-test.ts'; +import './unit-new/shapes/Path-test.ts'; +import './unit-new/shapes/TextPath-test.ts'; +import './unit-new/shapes/Arrow-test.ts'; +import './unit-new/shapes/Transformer-test.ts'; diff --git a/test/runner.html b/test/runner.html index 4359a780..eb7c8c1a 100644 --- a/test/runner.html +++ b/test/runner.html @@ -120,7 +120,7 @@ - + diff --git a/test/tsconfig.json b/test/tsconfig.json index c6135bfa..819141e6 100644 --- a/test/tsconfig.json +++ b/test/tsconfig.json @@ -3,4 +3,4 @@ "strict": true }, "files": ["../types/index-types.d.ts"] -} +} \ No newline at end of file diff --git a/test/unit/Animation-test.js b/test/unit-new/Animation-test.ts similarity index 88% rename from test/unit/Animation-test.js rename to test/unit-new/Animation-test.ts index f648ed10..6e4b1862 100644 --- a/test/unit/Animation-test.js +++ b/test/unit-new/Animation-test.ts @@ -1,6 +1,10 @@ -suite('Animation', function () { +import { assert } from 'chai'; + +import { addStage, Konva } from './utis'; + +describe('Animation', function () { // ====================================================== - test('test start and stop', function () { + it('test start and stop', function () { var stage = addStage(); var layer = new Konva.Layer(); var rect = new Konva.Rect({ @@ -19,10 +23,10 @@ suite('Animation', function () { var amplitude = 150; var period = 1000; // in ms - var centerX = stage.getWidth() / 2 - 100 / 2; + var centerX = stage.width() / 2 - 100 / 2; var anim = new Konva.Animation(function (frame) { - rect.setX( + rect.x( amplitude * Math.sin((frame.time * 2 * Math.PI) / period) + centerX ); }, layer); @@ -51,7 +55,7 @@ suite('Animation', function () { }); // ====================================================== - test('layer batch draw', function () { + it('layer batch draw', function () { var stage = addStage(); var layer = new Konva.Layer(); var rect = new Konva.Rect({ @@ -67,7 +71,7 @@ suite('Animation', function () { layer.add(rect); stage.add(layer); - draws = 0; + var draws = 0; layer.on('draw', function () { //console.log('draw') @@ -88,7 +92,7 @@ suite('Animation', function () { }); // ====================================================== - test('stage batch draw', function () { + it('stage batch draw', function () { var stage = addStage(); var layer = new Konva.Layer(); var rect = new Konva.Rect({ @@ -104,7 +108,7 @@ suite('Animation', function () { layer.add(rect); stage.add(layer); - draws = 0; + var draws = 0; layer.on('draw', function () { //console.log('draw') diff --git a/test/unit/Canvas-test.js b/test/unit-new/Canvas-test.ts similarity index 75% rename from test/unit/Canvas-test.js rename to test/unit-new/Canvas-test.ts index 21fea997..99009b33 100644 --- a/test/unit/Canvas-test.js +++ b/test/unit-new/Canvas-test.ts @@ -1,6 +1,9 @@ -suite('Canvas', function () { +import { assert } from 'chai'; +import { addStage, Konva } from './utis'; + +describe('Canvas', function () { // ====================================================== - test('pixel ratio', function () { + it('pixel ratio', function () { var stage = addStage(); var layer = new Konva.Layer(); @@ -18,14 +21,11 @@ suite('Canvas', function () { layer.add(circle); stage.add(layer); - stage.setWidth(578 / 2); - stage.setHeight(100); + stage.width(578 / 2); + stage.height(100); stage.draw(); - assert.equal( - layer.getCanvas().getPixelRatio(), - Konva.pixelRatio || window.devicePixelRatio || 1 - ); + assert.equal(layer.getCanvas().getPixelRatio(), Konva.pixelRatio); layer.getCanvas().setPixelRatio(1); assert.equal(layer.getCanvas().getPixelRatio(), 1); diff --git a/test/unit/Container-test.js b/test/unit-new/Container-test.ts similarity index 90% rename from test/unit/Container-test.js rename to test/unit-new/Container-test.ts index 26099da0..423f644f 100644 --- a/test/unit/Container-test.js +++ b/test/unit-new/Container-test.ts @@ -1,14 +1,18 @@ -suite('Container', function () { +import { assert } from 'chai'; +import { Shape } from '../../src/Shape'; +import { addStage, Konva, compareLayers } from './utis'; + +describe('Container', function () { // ====================================================== - test('clip', function () { + it('clip', function () { var stage = addStage(); var layer = new Konva.Layer({ - clip: { x: 0, y: 0, width: stage.getWidth() / 2, height: 100 }, + clip: { x: 0, y: 0, width: stage.width() / 2, height: 100 }, }); var group = new Konva.Group(); var circle = new Konva.Circle({ - x: stage.getWidth() / 2, - y: stage.getHeight() / 2, + x: stage.width() / 2, + y: stage.height() / 2, radius: 70, fill: 'green', stroke: 'black', @@ -30,7 +34,7 @@ suite('Container', function () { }); // ====================================================== - test('clip function', function () { + it('clip function', function () { var stage = addStage(); // cliped by circle is the same as draw circle @@ -66,13 +70,13 @@ suite('Container', function () { }); // ====================================================== - test('adder validation', function () { + it('adder validation', function () { var stage = addStage(); var layer = new Konva.Layer(); var group = new Konva.Group(); var circle = new Konva.Circle({ - x: stage.getWidth() / 2, - y: stage.getHeight() / 2, + x: stage.width() / 2, + y: stage.height() / 2, radius: 70, fill: 'green', stroke: 'black', @@ -93,7 +97,7 @@ suite('Container', function () { // =================================== var errorThrown = false; try { - stage.add(stage); + stage.add(stage as any); } catch (err) { errorThrown = true; } @@ -107,7 +111,7 @@ suite('Container', function () { // =================================== var errorThrown = false; try { - stage.add(group); + stage.add(group as any); } catch (err) { errorThrown = true; } @@ -121,7 +125,7 @@ suite('Container', function () { // =================================== var errorThrown = false; try { - stage.add(circle); + stage.add(circle as any); } catch (err) { errorThrown = true; } @@ -135,7 +139,7 @@ suite('Container', function () { // =================================== var errorThrown = false; try { - layer.add(stage); + layer.add(stage as any); } catch (err) { errorThrown = true; } @@ -163,7 +167,7 @@ suite('Container', function () { // =================================== var errorThrown = false; try { - group.add(stage); + group.add(stage as any); } catch (err) { errorThrown = true; } @@ -190,13 +194,13 @@ suite('Container', function () { }); // ====================================================== - test('add layer then group then shape', function () { + it('add layer then group then shape', function () { var stage = addStage(); var layer = new Konva.Layer(); var group = new Konva.Group(); var circle = new Konva.Circle({ - x: stage.getWidth() / 2, - y: stage.getHeight() / 2, + x: stage.width() / 2, + y: stage.height() / 2, radius: 70, fill: 'green', stroke: 'black', @@ -218,13 +222,13 @@ suite('Container', function () { }); // ====================================================== - test('add shape then stage then layer', function () { + it('add shape then stage then layer', function () { var stage = addStage(); var layer = new Konva.Layer(); var group = new Konva.Group(); var circle = new Konva.Circle({ - x: stage.getWidth() / 2, - y: stage.getHeight() / 2, + x: stage.width() / 2, + y: stage.height() / 2, radius: 70, fill: 'green', stroke: 'black', @@ -246,14 +250,14 @@ suite('Container', function () { }); // ====================================================== - test('select shape by id and name', function () { + it('select shape by id and name', function () { var stage = addStage(); var layer = new Konva.Layer({ id: 'myLayer', }); var circle = new Konva.Circle({ - x: stage.getWidth() / 2, - y: stage.getHeight() / 2, + x: stage.width() / 2, + y: stage.height() / 2, radius: 70, fill: 'green', stroke: 'black', @@ -288,7 +292,7 @@ suite('Container', function () { }); // ====================================================== - test('select shape by name with "-" char', function () { + it('select shape by name with "-" char', function () { var stage = addStage(); var layer = new Konva.Layer(); @@ -311,7 +315,7 @@ suite('Container', function () { }); // ====================================================== - test('select should return elements in their order', function () { + it('select should return elements in their order', function () { var stage = addStage(); var layer = new Konva.Layer(); stage.add(layer); @@ -355,14 +359,14 @@ suite('Container', function () { }); // ====================================================== - test('select shape with findOne', function () { + it('select shape with findOne', function () { var stage = addStage(); var layer = new Konva.Layer({ id: 'myLayer', }); var circle = new Konva.Circle({ - x: stage.getWidth() / 2, - y: stage.getHeight() / 2, + x: stage.width() / 2, + y: stage.height() / 2, radius: 70, fill: 'green', stroke: 'black', @@ -401,14 +405,14 @@ suite('Container', function () { }); // ====================================================== - test('select shapes with multiple selectors', function () { + it('select shapes with multiple selectors', function () { var stage = addStage(); var layer = new Konva.Layer({ id: 'myLayer', }); var circle = new Konva.Circle({ - x: stage.getWidth() / 2, - y: stage.getHeight() / 2, + x: stage.width() / 2, + y: stage.height() / 2, radius: 70, fill: 'green', stroke: 'black', @@ -465,7 +469,7 @@ suite('Container', function () { }); // ====================================================== - test('select shape by function', function () { + it('select shape by function', function () { var stage = addStage(); var layer = new Konva.Layer(); @@ -496,7 +500,7 @@ suite('Container', function () { }); // ====================================================== - test('select shape with duplicate id', function () { + it('select shape with duplicate id', function () { var stage = addStage(); var layer = new Konva.Layer(); stage.add(layer); @@ -532,12 +536,12 @@ suite('Container', function () { }); // ====================================================== - test('set x on an array of nodes', function () { + it('set x on an array of nodes', function () { var stage = addStage(); var layer = new Konva.Layer(); var circle = new Konva.Circle({ - x: stage.getWidth() / 2, - y: stage.getHeight() / 2, + x: stage.width() / 2, + y: stage.height() / 2, radius: 70, fill: 'green', stroke: 'black', @@ -564,24 +568,24 @@ suite('Container', function () { assert.equal(shapes.length, 2, 'shapes array should have 2 elements'); - shapes.each(function (node) { - node.setX(200); + shapes.forEach(function (node) { + node.x(200); }); layer.draw(); - shapes.each(function (node) { - assert.equal(node.getX(), 200, 'shape x should be 200'); + shapes.forEach(function (node) { + assert.equal(node.x(), 200, 'shape x should be 200'); }); }); // ====================================================== - test('set fill on array by Shape-selector', function () { + it('set fill on array by Shape-selector', function () { var stage = addStage(); var layer = new Konva.Layer(); var circle = new Konva.Circle({ - x: stage.getWidth() / 2, - y: stage.getHeight() / 2, + x: stage.width() / 2, + y: stage.height() / 2, radius: 70, fill: 'green', stroke: 'black', @@ -604,28 +608,28 @@ suite('Container', function () { layer.add(rect); stage.add(layer); - var shapes = layer.find('Shape'); + var shapes = layer.find('Shape'); assert.equal(shapes.length, 2, 'shapes array should have 2 elements'); - shapes.each(function (node) { - node.setFill('gray'); + shapes.forEach(function (node) { + node.fill('gray'); }); layer.draw(); - shapes.each(function (node) { - assert.equal(node.getFill(), 'gray', 'shape x should be 200'); + shapes.forEach(function (node) { + assert.equal(node.fill(), 'gray', 'shape x should be 200'); }); }); // ====================================================== - test('add listener to an array of nodes', function () { + it('add listener to an array of nodes', function () { var stage = addStage(); var layer = new Konva.Layer(); var circle = new Konva.Circle({ - x: stage.getWidth() / 2, - y: stage.getHeight() / 2, + x: stage.width() / 2, + y: stage.height() / 2, radius: 70, fill: 'green', stroke: 'black', @@ -652,9 +656,11 @@ suite('Container', function () { assert.equal(shapes.length, 2, 'shapes array should have 2 elements'); var a = 0; - shapes.on('mouseover', function () { - a++; - }); + shapes.forEach((shape) => + shape.on('mouseover', function () { + a++; + }) + ); circle.fire('mouseover'); assert.equal(a, 1, 'listener should have fired for circle'); rect.fire('mouseover'); @@ -662,12 +668,12 @@ suite('Container', function () { }); // ====================================================== - test('test ids and names hashes', function () { + it('test ids and names hashes', function () { var stage = addStage(); var layer = new Konva.Layer(); var circle = new Konva.Circle({ - x: stage.getWidth() / 2, - y: stage.getHeight() / 2, + x: stage.width() / 2, + y: stage.height() / 2, radius: 70, fill: 'green', stroke: 'black', @@ -727,13 +733,13 @@ suite('Container', function () { }); // ====================================================== - test('remove all children from layer', function () { + it('remove all children from layer', function () { var stage = addStage(); var layer = new Konva.Layer(); var group = new Konva.Group(); var circle1 = new Konva.Circle({ x: 100, - y: stage.getHeight() / 2, + y: stage.height() / 2, radius: 70, fill: 'green', stroke: 'black', @@ -742,7 +748,7 @@ suite('Container', function () { var circle2 = new Konva.Circle({ x: 300, - y: stage.getHeight() / 2, + y: stage.height() / 2, radius: 70, fill: 'green', stroke: 'black', @@ -769,7 +775,7 @@ suite('Container', function () { }); // ====================================================== - test('destroy all children from layer', function () { + it('destroy all children from layer', function () { var stage = addStage(); var layer = new Konva.Layer({ name: 'layerName', @@ -778,7 +784,7 @@ suite('Container', function () { var group = new Konva.Group(); var circle1 = new Konva.Circle({ x: 100, - y: stage.getHeight() / 2, + y: stage.height() / 2, radius: 70, fill: 'green', stroke: 'black', @@ -789,7 +795,7 @@ suite('Container', function () { var circle2 = new Konva.Circle({ x: 300, - y: stage.getHeight() / 2, + y: stage.height() / 2, radius: 70, fill: 'green', stroke: 'black', @@ -831,14 +837,14 @@ suite('Container', function () { }); // ====================================================== - test('add group', function () { + it('add group', function () { var stage = addStage(); var layer = new Konva.Layer(); var group = new Konva.Group(); var circle = new Konva.Circle({ - x: stage.getWidth() / 2, - y: stage.getHeight() / 2, + x: stage.width() / 2, + y: stage.height() / 2, radius: 70, fill: 'green', stroke: 'black', @@ -857,7 +863,7 @@ suite('Container', function () { }); // ====================================================== - test('create two groups, move first group', function () { + it('create two groups, move first group', function () { var stage = addStage(); var greenLayer = new Konva.Layer(); var blueLayer = new Konva.Layer(); @@ -865,8 +871,8 @@ suite('Container', function () { var blueGroup = new Konva.Group(); var greencircle = new Konva.Circle({ - x: stage.getWidth() / 2 - 100, - y: stage.getHeight() / 2, + x: stage.width() / 2 - 100, + y: stage.height() / 2, radius: 70, fill: 'green', stroke: 'black', @@ -875,8 +881,8 @@ suite('Container', function () { }); var bluecircle = new Konva.Circle({ - x: stage.getWidth() / 2 + 100, - y: stage.getHeight() / 2, + x: stage.width() / 2 + 100, + y: stage.height() / 2, radius: 70, fill: 'blue', stroke: 'black', @@ -893,8 +899,8 @@ suite('Container', function () { blueLayer.removeChildren(); var blueGroup2 = new Konva.Group(); var bluecircle2 = new Konva.Circle({ - x: stage.getWidth() / 2, - y: stage.getHeight() / 2, + x: stage.width() / 2, + y: stage.height() / 2, radius: 70, fill: 'blue', stroke: 'black', @@ -903,18 +909,18 @@ suite('Container', function () { blueGroup2.add(bluecircle2); blueLayer.add(blueGroup2); blueLayer.draw(); - blueGroup2.setPosition(100, 0); + blueGroup2.position({ x: 100, y: 0 }); blueLayer.draw(); var trace = blueLayer.getContext().getTrace(); assert.equal( trace, - 'clearRect(0,0,578,200);save();transform(1,0,0,1,389,100);beginPath();arc(0,0,70,0,6.283,false);closePath();fillStyle=blue;fill();lineWidth=4;strokeStyle=black;stroke();restore();clearRect(0,0,578,200);save();transform(1,0,0,1,289,100);beginPath();arc(0,0,70,0,6.283,false);closePath();fillStyle=blue;fill();lineWidth=4;strokeStyle=black;stroke();restore();clearRect(0,0,578,200);save();transform(1,0,0,1,289,100);beginPath();arc(0,0,70,0,6.283,false);closePath();fillStyle=blue;fill();lineWidth=4;strokeStyle=black;stroke();restore();' + 'clearRect(0,0,578,200);save();transform(1,0,0,1,389,100);beginPath();arc(0,0,70,0,6.283,false);closePath();fillStyle=blue;fill();lineWidth=4;strokeStyle=black;stroke();restore();clearRect(0,0,578,200);save();transform(1,0,0,1,289,100);beginPath();arc(0,0,70,0,6.283,false);closePath();fillStyle=blue;fill();lineWidth=4;strokeStyle=black;stroke();restore();clearRect(0,0,578,200);save();transform(1,0,0,1,389,100);beginPath();arc(0,0,70,0,6.283,false);closePath();fillStyle=blue;fill();lineWidth=4;strokeStyle=black;stroke();restore();' ); }); // ====================================================== - test('node type selector', function () { + it('node type selector', function () { var stage = addStage(); var layer = new Konva.Layer(); var fooLayer = new Konva.Layer(); @@ -976,7 +982,7 @@ suite('Container', function () { }); // ====================================================== - test('node and shape type selector', function () { + it('node and shape type selector', function () { var stage = addStage(); var layer = new Konva.Layer(); var layer2 = new Konva.Layer(); @@ -1046,8 +1052,8 @@ suite('Container', function () { }); var poly = new Konva.RegularPolygon({ - x: stage.getWidth() / 2, - y: stage.getHeight() / 2, + x: stage.width() / 2, + y: stage.height() / 2, sides: 5, radius: 50, fill: 'green', @@ -1143,7 +1149,7 @@ suite('Container', function () { }); // ====================================================== - test('test find() selector by adding shapes with multiple names', function () { + it('test find() selector by adding shapes with multiple names', function () { var stage = addStage(); var layer = new Konva.Layer({ name: 'layerName', @@ -1258,7 +1264,7 @@ suite('Container', function () { }); // ====================================================== - test('test find() selector by adding shape, then group, then layer', function () { + it('test find() selector by adding shape, then group, then layer', function () { var stage = addStage(); var layer = new Konva.Layer({ name: 'layerName', @@ -1349,7 +1355,7 @@ suite('Container', function () { }); // ====================================================== - test('test find() selector by adding group, then shape, then layer', function () { + it('test find() selector by adding group, then shape, then layer', function () { var stage = addStage(); var layer = new Konva.Layer({ name: 'layerName', @@ -1440,7 +1446,7 @@ suite('Container', function () { }); // ====================================================== - test('test find() selector by adding group, then layer, then shape', function () { + it('test find() selector by adding group, then layer, then shape', function () { var stage = addStage(); var layer = new Konva.Layer({ name: 'layerName', @@ -1531,7 +1537,7 @@ suite('Container', function () { }); // ====================================================== - test('test find() selector by adding layer, then group, then shape', function () { + it('test find() selector by adding layer, then group, then shape', function () { var stage = addStage(); var layer = new Konva.Layer({ name: 'layerName', @@ -1623,7 +1629,7 @@ suite('Container', function () { layer.draw(); }); - test('warn on invalid selector', function () { + it('warn on invalid selector', function () { var stage = addStage(); var layer = new Konva.Layer({ name: 'layerName', @@ -1663,12 +1669,12 @@ suite('Container', function () { }); // ====================================================== - test('add layer then shape', function () { + it('add layer then shape', function () { var stage = addStage(); var layer = new Konva.Layer(); var circle = new Konva.Circle({ - x: stage.getWidth() / 2, - y: stage.getHeight() / 2, + x: stage.width() / 2, + y: stage.height() / 2, radius: 70, fill: 'green', stroke: 'black', @@ -1679,17 +1685,19 @@ suite('Container', function () { stage.add(layer); layer.add(circle); layer.draw(); + + assert(layer.getChildren().length === 1); }); // ====================================================== - test('move blue layer on top of green layer with setZIndex', function () { + it('move blue layer on top of green layer with setZIndex', function () { var stage = addStage(); var blueLayer = new Konva.Layer(); var greenLayer = new Konva.Layer(); var bluecircle = new Konva.Circle({ x: 200, - y: stage.getHeight() / 2, + y: stage.height() / 2, radius: 70, fill: 'blue', stroke: 'black', @@ -1698,7 +1706,7 @@ suite('Container', function () { var greencircle = new Konva.Circle({ x: 280, - y: stage.getHeight() / 2, + y: stage.height() / 2, radius: 70, fill: 'green', stroke: 'black', @@ -1728,14 +1736,14 @@ suite('Container', function () { }); // ====================================================== - test('move blue layer on top of green layer with moveToTop', function () { + it('move blue layer on top of green layer with moveToTop', function () { var stage = addStage(); var blueLayer = new Konva.Layer(); var greenLayer = new Konva.Layer(); var bluecircle = new Konva.Circle({ x: 200, - y: stage.getHeight() / 2, + y: stage.height() / 2, radius: 70, fill: 'blue', stroke: 'black', @@ -1744,7 +1752,7 @@ suite('Container', function () { var greencircle = new Konva.Circle({ x: 280, - y: stage.getHeight() / 2, + y: stage.height() / 2, radius: 70, fill: 'green', stroke: 'black', @@ -1758,17 +1766,20 @@ suite('Container', function () { stage.add(greenLayer); blueLayer.moveToTop(); + + assert(blueLayer.zIndex() === 1); + assert(greenLayer.zIndex() === 0); }); // ====================================================== - test('move green layer below blue layer with moveToBottom', function () { + it('move green layer below blue layer with moveToBottom', function () { var stage = addStage(); var blueLayer = new Konva.Layer(); var greenLayer = new Konva.Layer(); var bluecircle = new Konva.Circle({ x: 200, - y: stage.getHeight() / 2, + y: stage.height() / 2, radius: 70, fill: 'blue', stroke: 'black', @@ -1777,7 +1788,7 @@ suite('Container', function () { var greencircle = new Konva.Circle({ x: 280, - y: stage.getHeight() / 2, + y: stage.height() / 2, radius: 70, fill: 'green', stroke: 'black', @@ -1791,17 +1802,20 @@ suite('Container', function () { stage.add(greenLayer); greenLayer.moveToBottom(); + + assert(blueLayer.zIndex() === 1); + assert(greenLayer.zIndex() === 0); }); // ====================================================== - test('move green layer below blue layer with moveDown', function () { + it('move green layer below blue layer with moveDown', function () { var stage = addStage(); var blueLayer = new Konva.Layer(); var greenLayer = new Konva.Layer(); var bluecircle = new Konva.Circle({ x: 200, - y: stage.getHeight() / 2, + y: stage.height() / 2, radius: 70, fill: 'blue', stroke: 'black', @@ -1810,7 +1824,7 @@ suite('Container', function () { var greencircle = new Konva.Circle({ x: 280, - y: stage.getHeight() / 2, + y: stage.height() / 2, radius: 70, fill: 'green', stroke: 'black', @@ -1823,17 +1837,20 @@ suite('Container', function () { stage.add(blueLayer); stage.add(greenLayer); greenLayer.moveDown(); + + assert(blueLayer.zIndex() === 1); + assert(greenLayer.zIndex() === 0); }); // ====================================================== - test('move blue layer above green layer with moveUp', function () { + it('move blue layer above green layer with moveUp', function () { var stage = addStage(); var blueLayer = new Konva.Layer(); var greenLayer = new Konva.Layer(); var bluecircle = new Konva.Circle({ x: 200, - y: stage.getHeight() / 2, + y: stage.height() / 2, radius: 70, fill: 'blue', stroke: 'black', @@ -1842,7 +1859,7 @@ suite('Container', function () { var greencircle = new Konva.Circle({ x: 280, - y: stage.getHeight() / 2, + y: stage.height() / 2, radius: 70, fill: 'green', stroke: 'black', @@ -1855,16 +1872,19 @@ suite('Container', function () { stage.add(blueLayer); stage.add(greenLayer); blueLayer.moveUp(); + + assert(blueLayer.zIndex() === 1); + assert(greenLayer.zIndex() === 0); }); // ====================================================== - test('move blue circle on top of green circle with moveToTop', function () { + it('move blue circle on top of green circle with moveToTop', function () { var stage = addStage(); var layer = new Konva.Layer(); var bluecircle = new Konva.Circle({ x: 200, - y: stage.getHeight() / 2, + y: stage.height() / 2, radius: 70, fill: 'blue', stroke: 'black', @@ -1873,7 +1893,7 @@ suite('Container', function () { var greencircle = new Konva.Circle({ x: 280, - y: stage.getHeight() / 2, + y: stage.height() / 2, radius: 70, fill: 'green', stroke: 'black', @@ -1912,13 +1932,13 @@ suite('Container', function () { }); // ====================================================== - test('move green circle below blue circle with moveDown', function () { + it('move green circle below blue circle with moveDown', function () { var stage = addStage(); var layer = new Konva.Layer(); var bluecircle = new Konva.Circle({ x: 200, - y: stage.getHeight() / 2, + y: stage.height() / 2, radius: 70, fill: 'blue', stroke: 'black', @@ -1927,7 +1947,7 @@ suite('Container', function () { var greencircle = new Konva.Circle({ x: 280, - y: stage.getHeight() / 2, + y: stage.height() / 2, radius: 70, fill: 'green', stroke: 'black', @@ -1966,13 +1986,13 @@ suite('Container', function () { }); // ====================================================== - test('layer layer when only one layer', function () { + it('layer layer when only one layer', function () { var stage = addStage(); var layer = new Konva.Layer(); var bluecircle = new Konva.Circle({ x: 200, - y: stage.getHeight() / 2, + y: stage.height() / 2, radius: 70, fill: 'blue', stroke: 'black', @@ -1998,7 +2018,7 @@ suite('Container', function () { }); // ====================================================== - test('move blue group on top of green group with moveToTop', function () { + it('move blue group on top of green group with moveToTop', function () { var stage = addStage(); var layer = new Konva.Layer(); var greenGroup = new Konva.Group(); @@ -2006,7 +2026,7 @@ suite('Container', function () { var bluecircle = new Konva.Circle({ x: 200, - y: stage.getHeight() / 2, + y: stage.height() / 2, radius: 70, fill: 'blue', stroke: 'black', @@ -2015,7 +2035,7 @@ suite('Container', function () { var greencircle = new Konva.Circle({ x: 280, - y: stage.getHeight() / 2, + y: stage.height() / 2, radius: 70, fill: 'green', stroke: 'black', @@ -2057,7 +2077,7 @@ suite('Container', function () { }); // ====================================================== - test('move blue group on top of green group with moveUp', function () { + it('move blue group on top of green group with moveUp', function () { var stage = addStage(); var layer = new Konva.Layer(); var greenGroup = new Konva.Group(); @@ -2065,7 +2085,7 @@ suite('Container', function () { var bluecircle = new Konva.Circle({ x: 200, - y: stage.getHeight() / 2, + y: stage.height() / 2, radius: 70, fill: 'blue', stroke: 'black', @@ -2074,7 +2094,7 @@ suite('Container', function () { var greencircle = new Konva.Circle({ x: 280, - y: stage.getHeight() / 2, + y: stage.height() / 2, radius: 70, fill: 'green', stroke: 'black', @@ -2116,7 +2136,7 @@ suite('Container', function () { }); // ====================================================== - test('add and moveTo should work same way (depend on parent)', function () { + it('add and moveTo should work same way (depend on parent)', function () { var stage = addStage(); var layer = new Konva.Layer(); var greenGroup = new Konva.Group(); @@ -2124,7 +2144,7 @@ suite('Container', function () { var bluecircle = new Konva.Circle({ x: 200, - y: stage.getHeight() / 2, + y: stage.height() / 2, radius: 70, fill: 'blue', stroke: 'black', @@ -2165,14 +2185,14 @@ suite('Container', function () { }); // ====================================================== - test('getChildren may use filter function', function () { + it('getChildren may use filter function', function () { var stage = addStage(); var layer = new Konva.Layer(); var group = new Konva.Group(); var circle1 = new Konva.Circle({ x: 200, - y: stage.getHeight() / 2, + y: stage.height() / 2, radius: 70, fill: 'blue', stroke: 'black', @@ -2204,7 +2224,7 @@ suite('Container', function () { layer.draw(); }); - test('add multiple nodes to container', function () { + it('add multiple nodes to container', function () { var stage = addStage(); var layer = new Konva.Layer(); var circle1 = new Konva.Circle({ @@ -2232,7 +2252,7 @@ suite('Container', function () { 'layer has exactly three children' ); }); - test('getClientRect - adding a zero bounds shape should result in zero bounds', function () { + it('getClientRect - adding a zero bounds shape should result in zero bounds', function () { var stage = addStage(); var layer = new Konva.Layer(); stage.add(layer); @@ -2247,7 +2267,7 @@ suite('Container', function () { height: 0, }); }); - test('getClientRect - test empty case', function () { + it('getClientRect - test empty case', function () { var stage = addStage(); var layer = new Konva.Layer(); stage.add(layer); @@ -2264,7 +2284,7 @@ suite('Container', function () { }); }); - test('get client rect with deep nested hidden shape', function () { + it('get client rect with deep nested hidden shape', function () { var stage = addStage(); var layer = new Konva.Layer(); @@ -2304,7 +2324,7 @@ suite('Container', function () { }); }); - test('getClientRect - test group with invisible child', function () { + it('getClientRect - test group with invisible child', function () { var stage = addStage(); var layer = new Konva.Layer(); stage.add(layer); @@ -2339,7 +2359,7 @@ suite('Container', function () { }); }); - test('getClientRect - test group with invisible child inside invisible parent', function () { + it('getClientRect - test group with invisible child inside invisible parent', function () { var stage = addStage(); var layer = new Konva.Layer({ visible: false, @@ -2376,7 +2396,7 @@ suite('Container', function () { }); }); - test('getClientRect - test group with visible child inside invisible parent', function () { + it('getClientRect - test group with visible child inside invisible parent', function () { var stage = addStage(); var layer = new Konva.Layer({ visible: false, @@ -2419,7 +2439,7 @@ suite('Container', function () { }); }); - test('get client rect with deep nested hidden shape 2', function () { + it('get client rect with deep nested hidden shape 2', function () { var layer = new Konva.Layer(); var group = new Konva.Group({ visible: false, @@ -2445,7 +2465,7 @@ suite('Container', function () { }); }); - test('getClientRect - test layer', function () { + it('getClientRect - test layer', function () { var stage = addStage(); var layer = new Konva.Layer(); var group = new Konva.Group(); @@ -2470,7 +2490,7 @@ suite('Container', function () { }); }); - test('getClientRect - nested group with a hidden shapes', function () { + it('getClientRect - nested group with a hidden shapes', function () { var stage = addStage(); var layer = new Konva.Layer(); @@ -2509,7 +2529,7 @@ suite('Container', function () { }); }); - test('clip-cache', function () { + it('clip-cache', function () { var stage = addStage(); var layer = new Konva.Layer(); var group = new Konva.Group(); @@ -2651,7 +2671,7 @@ suite('Container', function () { ); }); - test('clip-cache-scale', function () { + it('clip-cache-scale', function () { var stage = addStage(); var layer = new Konva.Layer(); var group = new Konva.Group(); diff --git a/test/unit/Context-test.js b/test/unit-new/Context-test.ts similarity index 87% rename from test/unit/Context-test.js rename to test/unit-new/Context-test.ts index a8400628..9fe9f586 100644 --- a/test/unit/Context-test.js +++ b/test/unit-new/Context-test.ts @@ -1,4 +1,7 @@ -suite('Context', function () { +import { assert } from 'chai'; +import { addStage, Konva } from './utis'; + +describe('Context', function () { // ====================================================== var contextMethods = [ 'clearRect', @@ -56,7 +59,7 @@ suite('Context', function () { 'globalCompositeOperation', ]; - test('context wrapper should work like native context', function () { + it('context wrapper should work like native context', function () { var stage = addStage(); var layer = new Konva.Layer(); @@ -105,10 +108,10 @@ suite('Context', function () { // test get nativeContext.fillStyle = '#ff0000'; - assert.equal(context.fillStyle, '#ff0000'); + assert.equal(context['fillStyle'], '#ff0000'); // test set - context.globalAlpha = 0.5; - assert.equal(context.globalAlpha, 0.5); + context['globalAlpha'] = 0.5; + assert.equal(context['globalAlpha'], 0.5); }); }); diff --git a/test/unit/DragAndDrop-test.js b/test/unit-new/DragAndDrop-test.ts similarity index 79% rename from test/unit/DragAndDrop-test.js rename to test/unit-new/DragAndDrop-test.ts index 00509f73..6ba49a2e 100644 --- a/test/unit/DragAndDrop-test.js +++ b/test/unit-new/DragAndDrop-test.ts @@ -1,11 +1,23 @@ -suite('DragAndDrop', function () { +import { assert } from 'chai'; +import { + addStage, + Konva, + simulateMouseDown, + simulateMouseMove, + simulateMouseUp, + simulateTouchStart, + simulateTouchEnd, + simulateTouchMove, +} from './utis'; + +describe('DragAndDrop', function () { // ====================================================== - test('test drag and drop properties and methods', function (done) { + it('test drag and drop properties and methods', function (done) { var stage = addStage(); var layer = new Konva.Layer(); var circle = new Konva.Circle({ - x: stage.getWidth() / 2, - y: stage.getHeight() / 2, + x: stage.width() / 2, + y: stage.height() / 2, radius: 70, fill: 'green', stroke: 'black', @@ -29,22 +41,20 @@ suite('DragAndDrop', function () { layer.draw(); - showHit(layer); - // test new properties - assert.equal(circle.getDraggable(), true); + assert.equal(circle.draggable(), true); done(); }, 50); }); // ====================================================== - test('multiple drag and drop sets with setDraggable()', function () { + it('multiple drag and drop sets with setDraggable()', function () { var stage = addStage(); var layer = new Konva.Layer(); var circle = new Konva.Circle({ x: 380, - y: stage.getHeight() / 2, + y: stage.height() / 2, radius: 70, strokeWidth: 4, fill: 'red', @@ -52,24 +62,24 @@ suite('DragAndDrop', function () { }); circle.setDraggable(true); - assert.equal(circle.getDraggable(), true); + assert.equal(circle.draggable(), true); circle.setDraggable(true); - assert.equal(circle.getDraggable(), true); + assert.equal(circle.draggable(), true); circle.setDraggable(false); - assert.equal(!circle.getDraggable(), true); + assert.equal(!circle.draggable(), true); layer.add(circle); stage.add(layer); }); // ====================================================== - test('right click is not for dragging', function () { + it('right click is not for dragging', function () { var stage = addStage(); var layer = new Konva.Layer(); var circle = new Konva.Circle({ - x: stage.getWidth() / 2, - y: stage.getHeight() / 2, + x: stage.width() / 2, + y: stage.height() / 2, radius: 70, fill: 'green', stroke: 'black', @@ -81,32 +91,32 @@ suite('DragAndDrop', function () { layer.add(circle); stage.add(layer); - stage.simulateMouseDown({ + simulateMouseDown(stage, { x: 291, y: 112, }); - stage.simulateMouseMove({ + simulateMouseMove(stage, { x: 311, y: 112, }); assert(circle.isDragging(), 'dragging is ok'); - stage.simulateMouseUp({ + simulateMouseUp(stage, { x: 291, y: 112, }); assert(!circle.isDragging(), 'drag stopped'); - stage.simulateMouseDown({ + simulateMouseDown(stage, { x: 291, y: 112, button: 2, }); - stage.simulateMouseMove({ + simulateMouseMove(stage, { x: 311, y: 112, button: 2, @@ -115,20 +125,20 @@ suite('DragAndDrop', function () { assert(circle.isDragging() === false, 'no dragging with right click'); Konva.dragButtons = [0, 2]; - stage.simulateMouseUp({ + simulateMouseUp(stage, { x: 291, y: 112, button: 2, }); // simulate buttons change - stage.simulateMouseDown({ + simulateMouseDown(stage, { x: 291, y: 112, button: 2, }); - stage.simulateMouseMove({ + simulateMouseMove(stage, { x: 311, y: 112, button: 2, @@ -136,7 +146,7 @@ suite('DragAndDrop', function () { assert(circle.isDragging() === true, 'now dragging with right click'); - stage.simulateMouseUp({ + simulateMouseUp(stage, { x: 291, y: 112, button: 2, @@ -145,13 +155,13 @@ suite('DragAndDrop', function () { }); // ====================================================== - test('changing draggable on mousedown should take effect', function () { + it('changing draggable on mousedown should take effect', function () { var stage = addStage(); var layer = new Konva.Layer(); var circle = new Konva.Circle({ - x: stage.getWidth() / 2, - y: stage.getHeight() / 2, + x: stage.width() / 2, + y: stage.height() / 2, radius: 70, fill: 'green', stroke: 'black', @@ -166,30 +176,28 @@ suite('DragAndDrop', function () { circle.draggable(true); }); - stage.simulateMouseDown({ + simulateMouseDown(stage, { x: circle.x(), y: circle.y(), }); - stage.simulateMouseMove({ + simulateMouseMove(stage, { x: circle.x() + 10, y: circle.y() + 10, }); assert.equal(circle.isDragging(), true); - stage.simulateMouseUp({ + simulateMouseUp(stage, { x: circle.x() + 10, y: circle.y() + 10, }); }); // ====================================================== - test('while dragging do not draw hit', function () { + it('while dragging do not draw hit', function () { var stage = addStage(); - var top = stage.content.getBoundingClientRect().top; - var layer = new Konva.Layer(); stage.add(layer); @@ -197,8 +205,8 @@ suite('DragAndDrop', function () { stage.add(dragLayer); var circle = new Konva.Circle({ - x: stage.getWidth() / 2, - y: stage.getHeight() / 2, + x: stage.width() / 2, + y: stage.height() / 2, radius: 70, fill: 'green', stroke: 'black', @@ -229,12 +237,12 @@ suite('DragAndDrop', function () { assert.equal(shape, rect, 'rect is detected'); - stage.simulateMouseDown({ + simulateMouseDown(stage, { x: stage.width() / 2, y: stage.height() / 2, }); - stage.simulateMouseMove({ + simulateMouseMove(stage, { x: stage.width() / 2 + 5, y: stage.height() / 2, }); @@ -257,18 +265,16 @@ suite('DragAndDrop', function () { // as dragLayer under dragging we should not able to detect intersect assert.equal(!!shape, false, 'circle is not detected'); - stage.simulateMouseUp({ + simulateMouseUp(stage, { x: 291, - y: 112 + top, + y: 112, }); }); // ====================================================== - test('it is possible to change layer while dragging', function () { + it('it is possible to change layer while dragging', function () { var stage = addStage(); - var top = stage.content.getBoundingClientRect().top; - var startDragLayer = new Konva.Layer(); stage.add(startDragLayer); @@ -276,8 +282,8 @@ suite('DragAndDrop', function () { stage.add(endDragLayer); var circle = new Konva.Circle({ - x: stage.getWidth() / 2, - y: stage.getHeight() / 2, + x: stage.width() / 2, + y: stage.height() / 2, radius: 70, fill: 'green', stroke: 'black', @@ -301,12 +307,12 @@ suite('DragAndDrop', function () { endDragLayer.add(rect); endDragLayer.draw(); - stage.simulateMouseDown({ + simulateMouseDown(stage, { x: stage.width() / 2, y: stage.height() / 2, }); - stage.simulateMouseMove({ + simulateMouseMove(stage, { x: stage.width() / 2 + 5, y: stage.height() / 2, }); @@ -333,20 +339,20 @@ suite('DragAndDrop', function () { // as endDragLayer under dragging we should not able to detect intersect assert.equal(!!shape, false, 'circle is not detected'); - stage.simulateMouseUp({ + simulateMouseUp(stage, { x: 291, - y: 112 + top, + y: 112, }); }); // ====================================================== - test('removing parent of draggable node should not throw error', function () { + it('removing parent of draggable node should not throw error', function () { var stage = addStage(); var layer = new Konva.Layer(); stage.add(layer); var circle = new Konva.Circle({ x: 380, - y: stage.getHeight() / 2, + y: stage.height() / 2, radius: 70, strokeWidth: 4, fill: 'red', @@ -355,7 +361,7 @@ suite('DragAndDrop', function () { }); layer.add(circle); - stage.simulateMouseMove({ + simulateMouseMove(stage, { x: stage.width() / 2 + 5, y: stage.height() / 2, }); @@ -369,7 +375,7 @@ suite('DragAndDrop', function () { } }); - test('update hit on stage drag end', function (done) { + it('update hit on stage drag end', function (done) { var stage = addStage(); stage.draggable(true); @@ -378,8 +384,8 @@ suite('DragAndDrop', function () { stage.add(layer); var circle = new Konva.Circle({ - x: stage.getWidth() / 2, - y: stage.getHeight() / 2, + x: stage.width() / 2, + y: stage.height() / 2, radius: 70, fill: 'green', stroke: 'black', @@ -390,19 +396,19 @@ suite('DragAndDrop', function () { layer.add(circle); layer.draw(); - stage.simulateMouseDown({ + simulateMouseDown(stage, { x: stage.width() / 2, y: stage.height() / 2, }); - stage.simulateMouseMove({ + simulateMouseMove(stage, { x: stage.width() / 2 - 50, y: stage.height() / 2, }); setTimeout(function () { assert.equal(stage.isDragging(), true); - stage.simulateMouseUp({ + simulateMouseUp(stage, { x: stage.width() / 2 - 50, y: stage.height() / 2, }); @@ -418,13 +424,13 @@ suite('DragAndDrop', function () { }, 50); }); - test('removing shape while drag and drop should no throw error', function () { + it('removing shape while drag and drop should no throw error', function () { var stage = addStage(); var layer = new Konva.Layer(); var circle = new Konva.Circle({ - x: stage.getWidth() / 2, - y: stage.getHeight() / 2, + x: stage.width() / 2, + y: stage.height() / 2, radius: 70, fill: 'green', stroke: 'black', @@ -436,32 +442,34 @@ suite('DragAndDrop', function () { layer.add(circle); stage.add(layer); - stage.simulateMouseDown({ + simulateMouseDown(stage, { x: 291, y: 112, }); circle.remove(); - stage.simulateMouseMove({ + simulateMouseMove(stage, { x: 311, y: 112, }); - stage.simulateMouseUp({ + simulateMouseUp(stage, { x: 291, y: 112, button: 2, }); + + assert(Konva.isDragging() === false); }); - test('destroying shape while drag and drop should no throw error', function () { + it('destroying shape while drag and drop should no throw error', function () { var stage = addStage(); var layer = new Konva.Layer(); var circle = new Konva.Circle({ - x: stage.getWidth() / 2, - y: stage.getHeight() / 2, + x: stage.width() / 2, + y: stage.height() / 2, radius: 70, fill: 'green', stroke: 'black', @@ -473,25 +481,27 @@ suite('DragAndDrop', function () { layer.add(circle); stage.add(layer); - stage.simulateMouseDown({ + simulateMouseDown(stage, { x: 291, y: 112, }); circle.destroy(); - stage.simulateMouseMove({ + simulateMouseMove(stage, { x: 311, y: 112, }); - stage.simulateMouseUp({ + simulateMouseUp(stage, { x: 291, y: 112, }); + + assert(Konva.isDragging() === false); }); - test('drag start should trigger before movement', function () { + it('drag start should trigger before movement', function () { var stage = addStage(); var layer = new Konva.Layer(); @@ -514,23 +524,23 @@ suite('DragAndDrop', function () { assert.equal(circle.y(), 70); }); - stage.simulateMouseDown({ + simulateMouseDown(stage, { x: 70, y: 70, }); - stage.simulateMouseMove({ + simulateMouseMove(stage, { x: 100, y: 100, }); - stage.simulateMouseUp({ + simulateMouseUp(stage, { x: 100, y: 100, }); }); - test('drag with touch', function () { + it('drag with touch', function () { var stage = addStage(); var layer = new Konva.Layer(); @@ -553,17 +563,17 @@ suite('DragAndDrop', function () { assert.equal(circle.y(), 70); }); - stage.simulateTouchStart({ + simulateTouchStart(stage, { x: 70, y: 70, }); - stage.simulateTouchMove({ + simulateTouchMove(stage, { x: 100, y: 100, }); - stage.simulateTouchEnd({ + simulateTouchEnd(stage, { x: 100, y: 100, }); @@ -571,7 +581,7 @@ suite('DragAndDrop', function () { assert.equal(circle.y(), 100); }); - test('drag with multi-touch (second finger on empty space)', function () { + it('drag with multi-touch (second finger on empty space)', function () { var stage = addStage(); var layer = new Konva.Layer(); @@ -594,7 +604,7 @@ suite('DragAndDrop', function () { assert.equal(circle.y(), 70); }); - stage.simulateTouchStart([ + simulateTouchStart(stage, [ { x: 70, y: 70, @@ -607,7 +617,7 @@ suite('DragAndDrop', function () { }, ]); - stage.simulateTouchMove([ + simulateTouchMove(stage, [ { x: 100, y: 100, @@ -620,7 +630,7 @@ suite('DragAndDrop', function () { }, ]); - stage.simulateTouchEnd([ + simulateTouchEnd(stage, [ { x: 100, y: 100, @@ -636,7 +646,7 @@ suite('DragAndDrop', function () { assert.equal(circle.y(), 100); }); - test('drag with multi-touch (two shapes)', function () { + it('drag with multi-touch (two shapes)', function () { var stage = addStage(); var layer = new Konva.Layer(); stage.add(layer); @@ -685,7 +695,7 @@ suite('DragAndDrop', function () { dragmove2 += 1; }); - stage.simulateTouchStart([ + simulateTouchStart(stage, [ { x: 70, y: 70, @@ -699,7 +709,8 @@ suite('DragAndDrop', function () { ]); // move one finger - stage.simulateTouchMove( + simulateTouchMove( + stage, [ { x: 100, @@ -729,7 +740,7 @@ suite('DragAndDrop', function () { assert.equal(circle1.y(), 100); // move second finger - stage.simulateTouchMove([ + simulateTouchMove(stage, [ { x: 100, y: 100, @@ -749,7 +760,8 @@ suite('DragAndDrop', function () { assert.equal(circle2.y(), 70); // remove first finger - stage.simulateTouchEnd( + simulateTouchEnd( + stage, [ { x: 290, @@ -769,7 +781,8 @@ suite('DragAndDrop', function () { assert.equal(circle2.isDragging(), true); assert.equal(Konva.DD.isDragging, true); // remove first finger - stage.simulateTouchEnd( + simulateTouchEnd( + stage, [], [ { @@ -783,7 +796,7 @@ suite('DragAndDrop', function () { assert.equal(Konva.DD.isDragging, false); }); - test('drag with multi-touch (same shape)', function () { + it('drag with multi-touch (same shape)', function () { var stage = addStage(); var layer = new Konva.Layer(); stage.add(layer); @@ -810,7 +823,7 @@ suite('DragAndDrop', function () { dragmove1 += 1; }); - stage.simulateTouchStart([ + simulateTouchStart(stage, [ { x: 70, y: 70, @@ -818,7 +831,7 @@ suite('DragAndDrop', function () { }, ]); // move one finger - stage.simulateTouchMove([ + simulateTouchMove(stage, [ { x: 75, y: 75, @@ -826,7 +839,8 @@ suite('DragAndDrop', function () { }, ]); - stage.simulateTouchStart( + simulateTouchStart( + stage, [ { x: 75, @@ -848,7 +862,8 @@ suite('DragAndDrop', function () { ] ); - stage.simulateTouchMove( + simulateTouchMove( + stage, [ { x: 75, @@ -877,7 +892,8 @@ suite('DragAndDrop', function () { assert.equal(circle1.y(), 75); // remove first finger - stage.simulateTouchEnd( + simulateTouchEnd( + stage, [], [ { @@ -895,7 +911,7 @@ suite('DragAndDrop', function () { }); // TODO: try to move two shapes on different stages - test('can stop drag on dragstart without changing position later', function () { + it('can stop drag on dragstart without changing position later', function () { var stage = addStage(); var layer = new Konva.Layer(); @@ -920,17 +936,17 @@ suite('DragAndDrop', function () { assert.equal(false, true, 'dragmove called!'); }); - stage.simulateMouseDown({ + simulateMouseDown(stage, { x: 70, y: 70, }); - stage.simulateMouseMove({ + simulateMouseMove(stage, { x: 100, y: 100, }); - stage.simulateMouseUp({ + simulateMouseUp(stage, { x: 100, y: 100, }); @@ -939,7 +955,7 @@ suite('DragAndDrop', function () { assert.equal(circle.y(), 70); }); - test('can force drag at any time (when pointer already registered)', function () { + it('can force drag at any time (when pointer already registered)', function () { var stage = addStage(); var layer = new Konva.Layer(); @@ -957,16 +973,16 @@ suite('DragAndDrop', function () { layer.add(circle); stage.add(layer); - stage.simulateMouseMove({ x: 70, y: 70 }); + simulateMouseMove(stage, { x: 70, y: 70 }); circle.startDrag(); assert.equal(circle.isDragging(), true); - stage.simulateMouseMove({ x: 80, y: 80 }); - stage.simulateMouseUp({ x: 80, y: 80 }); + simulateMouseMove(stage, { x: 80, y: 80 }); + simulateMouseUp(stage, { x: 80, y: 80 }); assert.equal(circle.x(), 80); assert.equal(circle.y(), 80); }); - test('can force drag at any time (when pointer not registered)', function () { + it('can force drag at any time (when pointer not registered)', function () { var stage = addStage(); var layer = new Konva.Layer(); @@ -987,14 +1003,14 @@ suite('DragAndDrop', function () { circle.startDrag(); assert.equal(circle.isDragging(), true); // let us think that offset will be equal 0 if not registered pointers - stage.simulateMouseMove({ x: 80, y: 80 }); - stage.simulateMouseUp({ x: 80, y: 80 }); + simulateMouseMove(stage, { x: 80, y: 80 }); + simulateMouseUp(stage, { x: 80, y: 80 }); assert.equal(circle.x(), 80); assert.equal(circle.y(), 80); }); - test('calling startDrag show still fire event when required', function () { + it('calling startDrag show still fire event when required', function () { var stage = addStage(); var layer = new Konva.Layer(); @@ -1017,19 +1033,19 @@ suite('DragAndDrop', function () { stage.add(layer); // register pointer - stage.simulateMouseMove({ x: 70, y: 80 }); + simulateMouseMove(stage, { x: 70, y: 80 }); circle.startDrag(); assert.equal(dragstart, 1); assert.equal(circle.isDragging(), true); // moving by one pixel should move circle too - stage.simulateMouseMove({ x: 70, y: 81 }); - stage.simulateMouseUp({ x: 70, y: 81 }); + simulateMouseMove(stage, { x: 70, y: 81 }); + simulateMouseUp(stage, { x: 70, y: 81 }); assert.equal(circle.x(), 70); assert.equal(circle.y(), 71); }); - test('make sure we have event object', function () { + it('make sure we have event object', function () { var stage = addStage(); var layer = new Konva.Layer(); @@ -1057,13 +1073,13 @@ suite('DragAndDrop', function () { stage.add(layer); // register pointer - stage.simulateMouseDown({ x: 70, y: 80 }); + simulateMouseDown(stage, { x: 70, y: 80 }); // moving by one pixel should move circle too - stage.simulateMouseMove({ x: 80, y: 80 }); - stage.simulateMouseUp({ x: 70, y: 80 }); + simulateMouseMove(stage, { x: 80, y: 80 }); + simulateMouseUp(stage, { x: 70, y: 80 }); }); - test('try nested dragging', function () { + it('try nested dragging', function () { var stage = addStage(); var layer = new Konva.Layer({ draggable: true, @@ -1085,8 +1101,8 @@ suite('DragAndDrop', function () { layer.add(circle.clone({ x: 30, fill: 'red', draggable: false })); - stage.simulateMouseDown({ x: 70, y: 70 }); - stage.simulateMouseMove({ x: 80, y: 80 }); + simulateMouseDown(stage, { x: 70, y: 70 }); + simulateMouseMove(stage, { x: 80, y: 80 }); assert.equal(circle.x(), 80); assert.equal(circle.y(), 80); @@ -1094,10 +1110,10 @@ suite('DragAndDrop', function () { assert.equal(layer.y(), 0); // layer is not dragging, because drag is registered on circle assert.equal(layer.isDragging(), false); - stage.simulateMouseUp({ x: 80, y: 80 }); + simulateMouseUp(stage, { x: 80, y: 80 }); }); - test('warn on bad dragBoundFunc', function () { + it('warn on bad dragBoundFunc', function () { var stage = addStage(); var layer = new Konva.Layer({ draggable: true, @@ -1112,7 +1128,7 @@ suite('DragAndDrop', function () { strokeWidth: 4, name: 'myCircle', draggable: true, - dragBoundFunc: function () {}, + dragBoundFunc: function () {} as any, }); layer.add(circle); @@ -1123,14 +1139,14 @@ suite('DragAndDrop', function () { Konva.Util.warn = function () { counter += 1; }; - stage.simulateMouseDown({ x: 70, y: 70 }); - stage.simulateMouseMove({ x: 80, y: 80 }); - stage.simulateMouseUp({ x: 80, y: 80 }); + simulateMouseDown(stage, { x: 70, y: 70 }); + simulateMouseMove(stage, { x: 80, y: 80 }); + simulateMouseUp(stage, { x: 80, y: 80 }); assert.equal(counter > 0, true); Konva.Util.warn = oldWarn; }); - test('deletage drag', function () { + it('deletage drag', function () { var stage = addStage(); stage.draggable(true); var layer = new Konva.Layer(); @@ -1155,19 +1171,19 @@ suite('DragAndDrop', function () { } }); - stage.simulateMouseDown({ x: 5, y: 5 }); - stage.simulateMouseMove({ x: 10, y: 10 }); + simulateMouseDown(stage, { x: 5, y: 5 }); + simulateMouseMove(stage, { x: 10, y: 10 }); assert.equal(circle.isDragging(), true); assert.equal(stage.isDragging(), false); - stage.simulateMouseUp({ x: 10, y: 10 }); + simulateMouseUp(stage, { x: 10, y: 10 }); assert.equal(circle.x(), 70); assert.equal(circle.y(), 70); }); - test('disable drag on click', function () { + it('disable drag on click', function () { var stage = addStage(); stage.draggable(true); var layer = new Konva.Layer(); @@ -1201,8 +1217,8 @@ suite('DragAndDrop', function () { dragend += 1; }); - stage.simulateMouseDown({ x: 70, y: 75 }); - stage.simulateMouseUp({ x: 70, y: 70 }); + simulateMouseDown(stage, { x: 70, y: 75 }); + simulateMouseUp(stage, { x: 70, y: 70 }); // drag events should not be called assert.equal(dragstart, 0); diff --git a/test/unit/Global-test.js b/test/unit-new/Global-test.ts similarity index 93% rename from test/unit/Global-test.js rename to test/unit-new/Global-test.ts index 00436e0a..3856bbdd 100644 --- a/test/unit/Global-test.js +++ b/test/unit-new/Global-test.ts @@ -1,11 +1,14 @@ -suite('Global', function () { +import { assert } from 'chai'; +import { Konva } from './utis'; + +describe('Global', function () { // ====================================================== - test('test Konva version number', function () { + it('test Konva version number', function () { assert.equal(!!Konva.version, true); }); // ====================================================== - test('getAngle()', function () { + it('getAngle()', function () { // test that default angleDeg is true assert.equal(Konva.angleDeg, true); assert.equal(Konva.getAngle(180), Math.PI); @@ -18,7 +21,7 @@ suite('Global', function () { }); // ====================================================== - test('UA tests', function () { + it('UA tests', function () { var ua; // Chrome 34.0.1847.137 m diff --git a/test/unit/Group-test.js b/test/unit-new/Group-test.ts similarity index 84% rename from test/unit/Group-test.js rename to test/unit-new/Group-test.ts index 881e4838..ec75dfe9 100644 --- a/test/unit/Group-test.js +++ b/test/unit-new/Group-test.ts @@ -1,6 +1,8 @@ -suite('Group', function () { +import { addStage, cloneAndCompareLayer, Konva } from './utis'; + +describe('Group', function () { // ====================================================== - test('cache group with text', function () { + it('cache group with text', function () { var stage = addStage(); var layer = new Konva.Layer(); diff --git a/test/unit/Layer-test.js b/test/unit-new/Layer-test.ts similarity index 76% rename from test/unit/Layer-test.js rename to test/unit-new/Layer-test.ts index 53c5003d..c0306b1c 100644 --- a/test/unit/Layer-test.js +++ b/test/unit-new/Layer-test.ts @@ -1,13 +1,86 @@ -suite('Layer', function () { +import { assert } from 'chai'; + +import { + addStage, + simulateMouseDown, + simulateMouseMove, + simulateMouseUp, + showHit, + Konva, + loadImage, + isNode, +} from './utis'; + +describe('Layer', function () { // ====================================================== - test('test canvas inline styles', function () { + it('width and height', function () { + Konva.showWarnings = false; + var stage = addStage(); + + var layer = new Konva.Layer(); + assert.equal( + layer.width(), + undefined, + 'while layer is not on stage width is undefined' + ); + assert.equal( + layer.height(), + undefined, + 'while layer is not on stage height is undefined' + ); + + layer.width(10); + assert.equal( + layer.width(), + undefined, + 'while layer is not on stage changing width doing nothing' + ); + layer.height(10); + assert.equal( + layer.height(), + undefined, + 'while layer is not on stage changing height doing nothing' + ); + stage.add(layer); + + assert.equal( + layer.width(), + stage.width(), + 'while layer is on stage width is stage`s width' + ); + assert.equal( + layer.height(), + stage.height(), + 'while layer is on stage height is stage`s height' + ); + + layer.width(10); + assert.equal( + layer.width(), + stage.width(), + 'while layer is on stage changing width doing nothing' + ); + layer.height(10); + assert.equal( + layer.height(), + stage.height(), + 'while layer is on stage changing height doing nothing' + ); + Konva.showWarnings = true; + }); + + // ====================================================== + it('test canvas inline styles', function () { + if (isNode) { + return; + } var stage = addStage(); var layer = new Konva.Layer(); var circle = new Konva.Circle({ x: 100, - y: stage.getHeight() / 2, + y: stage.height() / 2, radius: 70, fill: 'green', stroke: 'black', @@ -40,7 +113,7 @@ suite('Layer', function () { assert.equal(style.left, '0px', 'canvas left should be 0px'); }); - test('test clear()', function () { + it('test clear()', function () { var stage = addStage(); var layer = new Konva.Layer(); var circle = new Konva.Circle({ @@ -82,7 +155,7 @@ suite('Layer', function () { showHit(layer); }); - test('test clear() with bounds', function () { + it('test clear() with bounds', function () { var stage = addStage(); var layer = new Konva.Layer(); var circle = new Konva.Circle({ @@ -125,13 +198,13 @@ suite('Layer', function () { }); // ====================================================== - test('layer getIntersection()', function () { + it('layer getIntersection()', function () { var stage = addStage(); var layer = new Konva.Layer(); var redCircle = new Konva.Circle({ x: 380, - y: stage.getHeight() / 2, + y: stage.height() / 2, radius: 70, strokeWidth: 4, fill: 'red', @@ -141,7 +214,7 @@ suite('Layer', function () { var greenCircle = new Konva.Circle({ x: 300, - y: stage.getHeight() / 2, + y: stage.height() / 2, radius: 70, strokeWidth: 4, fill: 'green', @@ -154,12 +227,12 @@ suite('Layer', function () { stage.add(layer); assert.equal( - layer.getIntersection({ x: 300, y: 100 }).getId(), + layer.getIntersection({ x: 300, y: 100 }).id(), 'greenCircle', 'shape should be greenCircle' ); assert.equal( - layer.getIntersection({ x: 380, y: 100 }).getId(), + layer.getIntersection({ x: 380, y: 100 }).id(), 'redCircle', 'shape should be redCircle' ); @@ -171,7 +244,7 @@ suite('Layer', function () { }); // ====================================================== - test('layer getIntersection() with selector', function () { + it('layer getIntersection() with selector', function () { var stage = addStage(); var layer = new Konva.Layer({ name: 'layer', @@ -182,8 +255,8 @@ suite('Layer', function () { }); var circle = new Konva.Circle({ - x: stage.getWidth() / 2, - y: stage.getHeight() / 2, + x: stage.width() / 2, + y: stage.height() / 2, radius: 70, strokeWidth: 4, fill: 'red', @@ -221,31 +294,19 @@ suite('Layer', function () { }); // ====================================================== - test('set layer visibility', function () { + it('set layer visibility', function () { var stage = addStage(); var layer = new Konva.Layer({ visible: false, }); - var rect = new Konva.Rect({ - x: 200, - width: 100, - height: 50, - fill: 'green', - stroke: 'black', - strokeWidth: 4, - scale: { x: 3, y: 1 }, - draggable: true, - strokeScaleEnabled: false, - }); - rect.colorKey = '000000'; - - layer.add(rect); stage.add(layer); + + assert(layer.getCanvasElement().style.display === 'none'); }); // ====================================================== - test('set clearBeforeDraw to false, and test toDataURL for stage, layer, group, and shape', function () { + it('set clearBeforeDraw to false, and test toDataURL for stage, layer, group, and shape', function () { var stage = addStage(); var layer = new Konva.Layer({ @@ -257,7 +318,7 @@ suite('Layer', function () { var circle = new Konva.Circle({ x: 100, - y: stage.getHeight() / 2, + y: stage.height() / 2, radius: 70, fill: 'green', stroke: 'black', @@ -282,13 +343,13 @@ suite('Layer', function () { }); // ====================================================== - test('save layer as png', function () { + it('save layer as png', function () { var stage = addStage(); var layer = new Konva.Layer(); var Circle = new Konva.Circle({ - x: stage.getWidth() / 2, - y: stage.getHeight() / 2, + x: stage.width() / 2, + y: stage.height() / 2, radius: 70, fill: 'violet', stroke: 'black', @@ -299,16 +360,17 @@ suite('Layer', function () { stage.add(layer); var dataUrl = layer.toDataURL(); + assert(dataUrl.length > 30); }); // ====================================================== - test('save layer as low quality jpg', function () { + it('save layer as low quality jpg', function () { var stage = addStage(); var layer = new Konva.Layer(); var circle = new Konva.Circle({ - x: stage.getWidth() / 2, - y: stage.getHeight() / 2, + x: stage.width() / 2, + y: stage.height() / 2, radius: 70, fill: 'violet', stroke: 'black', @@ -322,39 +384,23 @@ suite('Layer', function () { mimeType: 'image/jpeg', quality: 0.2, }); + + assert( + dataUrl.length < + layer.toDataURL({ + mimeType: 'image/jpeg', + }).length + ); }); // ====================================================== - test('save layer as high quality jpg', function () { + it('hit graph enable disable', function () { var stage = addStage(); var layer = new Konva.Layer(); var circle = new Konva.Circle({ - x: stage.getWidth() / 2, - y: stage.getHeight() / 2, - radius: 70, - fill: 'violet', - stroke: 'black', - strokeWidth: 4, - }); - - layer.add(circle); - stage.add(layer); - - var dataUrl = layer.toDataURL({ - mimeType: 'image/jpeg', - quality: 1, - }); - }); - - // ====================================================== - test('hit graph enable disable', function () { - var stage = addStage(); - var layer = new Konva.Layer(); - - var circle = new Konva.Circle({ - x: stage.getWidth() / 2, - y: stage.getHeight() / 2, + x: stage.width() / 2, + y: stage.height() / 2, radius: 70, fill: 'red', stroke: 'black', @@ -379,14 +425,14 @@ suite('Layer', function () { }); // ====================================================== - test('should not draw hit on stage drag', function () { + it('should not draw hit on stage drag', function () { var stage = addStage(); stage.draggable(true); var layer = new Konva.Layer(); var circle = new Konva.Circle({ - x: stage.getWidth() / 2, - y: stage.getHeight() / 2, + x: stage.width() / 2, + y: stage.height() / 2, radius: 70, fill: 'red', stroke: 'black', @@ -396,25 +442,25 @@ suite('Layer', function () { layer.add(circle); stage.add(layer); - stage.simulateMouseDown({ + simulateMouseDown(stage, { x: circle.x(), y: circle.y(), }); - stage.simulateMouseMove({ + simulateMouseMove(stage, { x: circle.x() + 10, y: circle.y() + 10, }); assert.equal(stage.isDragging(), true, 'dragging of stage is ok'); assert.equal(layer.shouldDrawHit(), false); - stage.simulateMouseUp({ + simulateMouseUp(stage, { x: 291, y: 112, }); }); - test('get/set layer size', function () { + it('get/set layer size', function () { var stage = addStage(); var layer = new Konva.Layer(); stage.add(layer); @@ -423,9 +469,8 @@ suite('Layer', function () { assert.equal(layer.height(), stage.height()); }); - test('get/set imageSmoothingEnabled', function (done) { - var imageObj = new Image(); - imageObj.onload = function () { + it('get/set imageSmoothingEnabled', function (done) { + loadImage('darth-vader.jpg', (imageObj) => { var stage = addStage(); var layer = new Konva.Layer({ @@ -440,19 +485,18 @@ suite('Layer', function () { layer.add(darth); stage.add(layer); - assert.equal(layer.getContext().imageSmoothingEnabled, false); + assert.equal(layer.getContext()['imageSmoothingEnabled'], false); layer.imageSmoothingEnabled(true); - assert.equal(layer.getContext().imageSmoothingEnabled, true); + assert.equal(layer.getContext()['imageSmoothingEnabled'], true); layer.imageSmoothingEnabled(false); // change size stage.width(stage.width() + 1); - assert.equal(layer.getContext().imageSmoothingEnabled, false); + assert.equal(layer.getContext()['imageSmoothingEnabled'], false); done(); - }; - imageObj.src = 'assets/darth-vader.jpg'; + }); }); }); diff --git a/test/unit/Node-cache-test.js b/test/unit-new/Node-cache-test.ts similarity index 88% rename from test/unit/Node-cache-test.js rename to test/unit-new/Node-cache-test.ts index 6c925aff..52367e50 100644 --- a/test/unit/Node-cache-test.js +++ b/test/unit-new/Node-cache-test.ts @@ -1,8 +1,17 @@ -suite('Caching', function () { - // this.timeout(5000); - // CACHING SHAPE +import { assert } from 'chai'; +import { + addStage, + Konva, + compareLayerAndCanvas, + cloneAndCompareLayer, + compareCanvases, + createCanvas, + loadImage, + getPixelRatio, +} from './utis'; - test('cache simple rectangle', function () { +describe('Caching', function () { + it('cache simple rectangle', function () { var stage = addStage(); var layer = new Konva.Layer(); @@ -30,10 +39,9 @@ suite('Caching', function () { compareLayerAndCanvas(layer, canvas, 10); cloneAndCompareLayer(layer); - showHit(layer); }); - test('cache simple rectangle with transform', function () { + it('cache simple rectangle with transform', function () { var stage = addStage(); var layer = new Konva.Layer(); @@ -66,7 +74,7 @@ suite('Caching', function () { cloneAndCompareLayer(layer, 150); }); - test('cache rectangle with fill and stroke', function () { + it('cache rectangle with fill and stroke', function () { var stage = addStage(); var layer = new Konva.Layer(); @@ -98,7 +106,7 @@ suite('Caching', function () { cloneAndCompareLayer(layer, 50); }); - test('cache rectangle with fill and opacity', function () { + it('cache rectangle with fill and opacity', function () { var stage = addStage(); var layer = new Konva.Layer(); @@ -128,7 +136,7 @@ suite('Caching', function () { compareLayerAndCanvas(layer, canvas, 5); }); - test('cache rectangle with fill, stroke opacity', function () { + it('cache rectangle with fill, stroke opacity', function () { var stage = addStage(); var layer = new Konva.Layer(); @@ -154,7 +162,7 @@ suite('Caching', function () { // skip, because opacity rendering of cached shape is different // nothing we can do here - test('cache rectangle with fill, shadow and opacity', function () { + it('cache rectangle with fill, shadow and opacity', function () { var stage = addStage(); var layer = new Konva.Layer(); @@ -180,7 +188,7 @@ suite('Caching', function () { cloneAndCompareLayer(layer, 10); }); - test('cache rectangle with fill and simple shadow', function () { + it('cache rectangle with fill and simple shadow', function () { Konva.pixelRatio = 1; var stage = addStage(); @@ -211,14 +219,11 @@ suite('Caching', function () { context.shadowBlur = 10; context.fill(); - showCanvas(rect._getCanvasCache().scene._canvas); - showCanvas(rect._getCanvasCache().hit._canvas); - showHit(layer); - compareLayerAndCanvas(layer, canvas, 10); - Konva.pixelRatio = undefined; + compareLayerAndCanvas(layer, canvas, 100); + Konva.pixelRatio = getPixelRatio(); }); - test('cache rectangle with fill and shadow with offset', function () { + it('cache rectangle with fill and shadow with offset', function () { var stage = addStage(); var layer = new Konva.Layer(); @@ -248,14 +253,14 @@ suite('Caching', function () { context.closePath(); context.fillStyle = 'green'; context.shadowColor = 'black'; - context.shadowBlur = 10 * canvas.ratio; - context.shadowOffsetX = 10 * canvas.ratio; - context.shadowOffsetY = 10 * canvas.ratio; + context.shadowBlur = 10 * Konva.pixelRatio; + context.shadowOffsetX = 10 * Konva.pixelRatio; + context.shadowOffsetY = 10 * Konva.pixelRatio; context.fill(); compareLayerAndCanvas(layer, canvas, 50); }); - test('cache rectangle with fill and shadow with negative offset', function () { + it('cache rectangle with fill and shadow with negative offset', function () { var stage = addStage(); var layer = new Konva.Layer(); @@ -285,14 +290,14 @@ suite('Caching', function () { context.closePath(); context.fillStyle = 'green'; context.shadowColor = 'black'; - context.shadowBlur = 10 * canvas.ratio; - context.shadowOffsetX = -10 * canvas.ratio; - context.shadowOffsetY = -10 * canvas.ratio; + context.shadowBlur = 10 * Konva.pixelRatio; + context.shadowOffsetX = -10 * Konva.pixelRatio; + context.shadowOffsetY = -10 * Konva.pixelRatio; context.fill(); compareLayerAndCanvas(layer, canvas, 50); }); - test('cache rectangle with fill and shadow with negative offset and scale', function () { + it('cache rectangle with fill and shadow with negative offset and scale', function () { var stage = addStage(); var layer = new Konva.Layer(); @@ -318,7 +323,7 @@ suite('Caching', function () { cloneAndCompareLayer(layer, 200); }); - test('cache rectangle with fill and shadow and some transform', function () { + it('cache rectangle with fill and shadow and some transform', function () { var stage = addStage(); var layer = new Konva.Layer(); @@ -350,15 +355,15 @@ suite('Caching', function () { context.closePath(); context.fillStyle = 'green'; context.shadowColor = 'black'; - context.shadowBlur = 10 * canvas.ratio; - context.shadowOffsetX = -10 * canvas.ratio; - context.shadowOffsetY = -10 * canvas.ratio; + context.shadowBlur = 10 * Konva.pixelRatio; + context.shadowOffsetX = -10 * Konva.pixelRatio; + context.shadowOffsetY = -10 * Konva.pixelRatio; context.fill(); compareLayerAndCanvas(layer, canvas, 50); }); // CACHING CONTAINERS - test('cache group with simple rectangle', function () { + it('cache group with simple rectangle', function () { var stage = addStage(); var layer = new Konva.Layer(); @@ -390,7 +395,7 @@ suite('Caching', function () { cloneAndCompareLayer(layer); }); - test('cache group with simple rectangle with transform', function () { + it('cache group with simple rectangle with transform', function () { var stage = addStage(); var layer = new Konva.Layer(); @@ -416,7 +421,7 @@ suite('Caching', function () { cloneAndCompareLayer(layer, 200); }); - test('cache group with several shape with transform', function () { + it('cache group with several shape with transform', function () { var stage = addStage(); var layer = new Konva.Layer(); @@ -466,9 +471,9 @@ suite('Caching', function () { context.closePath(); context.fillStyle = 'green'; context.shadowColor = 'black'; - context.shadowBlur = 10 * canvas.ratio; - context.shadowOffsetX = 10 * canvas.ratio; - context.shadowOffsetY = 10 * canvas.ratio; + context.shadowBlur = 10 * Konva.pixelRatio; + context.shadowOffsetX = 10 * Konva.pixelRatio; + context.shadowOffsetY = 10 * Konva.pixelRatio; context.fill(); context.restore(); @@ -491,7 +496,7 @@ suite('Caching', function () { compareLayerAndCanvas(layer, canvas, 150); }); - test('cache group with rectangle and text', function () { + it('cache group with rectangle and text', function () { var stage = addStage(); var layer = new Konva.Layer(); @@ -527,7 +532,7 @@ suite('Caching', function () { cloneAndCompareLayer(layer, 100); }); - test('cache layer with several shape with transform', function () { + it('cache layer with several shape with transform', function () { var stage = addStage(); var layer = new Konva.Layer({ @@ -579,9 +584,9 @@ suite('Caching', function () { context.closePath(); context.fillStyle = 'green'; context.shadowColor = 'black'; - context.shadowBlur = 10 * canvas.ratio; - context.shadowOffsetX = 10 * canvas.ratio; - context.shadowOffsetY = 10 * canvas.ratio; + context.shadowBlur = 10 * Konva.pixelRatio; + context.shadowOffsetX = 10 * Konva.pixelRatio; + context.shadowOffsetY = 10 * Konva.pixelRatio; context.fill(); context.restore(); @@ -604,7 +609,7 @@ suite('Caching', function () { compareLayerAndCanvas(layer, canvas, 150); }); - test('cache shape that is larger than stage', function () { + it('cache shape that is larger than stage', function () { var stage = addStage(); var layer = new Konva.Layer(); var group = new Konva.Group(); @@ -641,7 +646,7 @@ suite('Caching', function () { compareLayerAndCanvas(layer, canvas, 150); }); - test('cache shape that is larger than stage but need buffer canvas', function () { + it('cache shape that is larger than stage but need buffer canvas', function () { var stage = addStage(); var layer = new Konva.Layer(); var group = new Konva.Group(); @@ -666,7 +671,7 @@ suite('Caching', function () { cloneAndCompareLayer(layer, 200); }); - test('cache nested groups', function () { + it('cache nested groups', function () { var stage = addStage(); var layer = new Konva.Layer(); @@ -721,7 +726,7 @@ suite('Caching', function () { cloneAndCompareLayer(layer, 150); }); - test('test group with circle + buffer canvas usage', function () { + it('test group with circle + buffer canvas usage', function () { var stage = addStage(); var layer = new Konva.Layer(); stage.add(layer); @@ -750,7 +755,7 @@ suite('Caching', function () { cloneAndCompareLayer(layer, 200); }); - test('test group with opacity', function () { + it('test group with opacity', function () { var stage = addStage(); var layer = new Konva.Layer(); stage.add(layer); @@ -778,7 +783,7 @@ suite('Caching', function () { cloneAndCompareLayer(layer, 210); }); - test('test group with opacity', function () { + it('test group with opacity', function () { var stage = addStage(); var layer = new Konva.Layer(); stage.add(layer); @@ -806,7 +811,7 @@ suite('Caching', function () { cloneAndCompareLayer(layer, 100); }); - test('test rect with float dimensions', function () { + it('test rect with float dimensions', function () { var stage = addStage(); var layer = new Konva.Layer(); stage.add(layer); @@ -829,7 +834,7 @@ suite('Caching', function () { assert.equal(canvas.width, 105 * canvas.pixelRatio); }); - test('cache group with rectangle with fill and opacity', function () { + it('cache group with rectangle with fill and opacity', function () { var stage = addStage(); var layer = new Konva.Layer(); @@ -864,7 +869,7 @@ suite('Caching', function () { compareLayerAndCanvas(layer, canvas, 5); }); - test('even if parent is not visible cache should be created', function () { + it('even if parent is not visible cache should be created', function () { var stage = addStage(); var layer = new Konva.Layer({ @@ -893,12 +898,11 @@ suite('Caching', function () { context.closePath(); context.fillStyle = 'green'; context.fill(); - showHit(layer); compareLayerAndCanvas(layer, canvas, 5); assert.equal(stage.getIntersection({ x: 150, y: 100 }), rect); }); - test('even if parent is not listening cache and hit should be created', function () { + it('even if parent is not listening cache and hit should be created', function () { var stage = addStage(); var layer = new Konva.Layer({ @@ -927,13 +931,12 @@ suite('Caching', function () { context.closePath(); context.fillStyle = 'green'; context.fill(); - showHit(layer); compareLayerAndCanvas(layer, canvas, 5); assert.equal(stage.getIntersection({ x: 150, y: 100 }), rect); }); // hard to fix - test.skip('even if parent is not visible cache should be created - test for group', function () { + it.skip('even if parent is not visible cache should be created - test for group', function () { var stage = addStage(); var layer = new Konva.Layer({ @@ -1096,7 +1099,7 @@ suite('Caching', function () { var called = false; group.getClientRect = function () { called = true; - }; + } as any; group.cache({ x: 0, y: 0, @@ -1347,7 +1350,7 @@ suite('Caching', function () { assert.equal(d[0], 255, 'see red'); }); - test('check image smooth', function () { + it('check image smooth', function () { var stage = addStage(); var layer = new Konva.Layer({ @@ -1378,7 +1381,7 @@ suite('Caching', function () { ); }); - test('getAbsolutePosition for cached container', function () { + it('getAbsolutePosition for cached container', function () { var stage = addStage(); var layer = new Konva.Layer({}); @@ -1408,7 +1411,7 @@ suite('Caching', function () { assert.equal(circle.getAbsolutePosition().y, 110); }); - test('cached node should not have filter canvas until we have a filter', function () { + it('cached node should not have filter canvas until we have a filter', function () { var stage = addStage(); var layer = new Konva.Layer({}); @@ -1438,36 +1441,37 @@ suite('Caching', function () { // assert.equal(circle._cache.get('canvas').filter.width, 0); }); - test('hit from cache + global composite', function (done) { + it('hit from cache + global composite', function (done) { // blend mode should NOT effect hit detection. var stage = addStage(); var layer = new Konva.Layer({}); stage.add(layer); - Konva.Image.fromURL('./assets/lion.png', function (lion) { + loadImage('lion.png', (img) => { + const lion = new Konva.Image({ image: img }); lion.name('lion'); lion.cache(); lion.drawHitFromCache(); layer.add(lion); - Konva.Image.fromURL('./assets/lion.png', function (lion2) { - lion2.position({ - x: 50, - y: 50, - }); - lion2.name('lion2'); - lion2.globalCompositeOperation('overlay'); - lion2.cache(); - lion2.drawHitFromCache(); - layer.add(lion2); - layer.draw(); - layer.toggleHitCanvas(); + const lion2 = new Konva.Image({ image: img }); - var shape = layer.getIntersection({ x: 106, y: 78 }); - assert.equal(shape, lion2); - done(); + lion2.position({ + x: 50, + y: 50, }); + lion2.name('lion2'); + lion2.globalCompositeOperation('overlay'); + lion2.cache(); + lion2.drawHitFromCache(); + layer.add(lion2); + layer.draw(); + // layer.toggleHitCanvas(); + + var shape = layer.getIntersection({ x: 106, y: 78 }); + assert.equal(shape, lion2); + done(); }); }); }); diff --git a/test/unit/Node-test.js b/test/unit-new/Node-test.ts similarity index 84% rename from test/unit/Node-test.js rename to test/unit-new/Node-test.ts index c6033f1e..fd87a6c1 100644 --- a/test/unit/Node-test.js +++ b/test/unit-new/Node-test.ts @@ -1,12 +1,27 @@ -suite('Node', function () { +import { assert } from 'chai'; +import { Shape } from '../../src/Shape'; + +import { + addStage, + simulateMouseDown, + simulateMouseUp, + showHit, + compareLayerAndCanvas, + compareLayers, + addContainer, + loadImage, + Konva, +} from './utis'; + +describe.skip('Node', function () { // ====================================================== - test('getType and getClassName', function () { + it('getType and getClassName', function () { var stage = addStage(); var layer = new Konva.Layer(); var group = new Konva.Group(); var circle = new Konva.Circle({ - x: stage.getWidth() / 2, - y: stage.getHeight() / 2, + x: stage.width() / 2, + y: stage.height() / 2, radius: 70, fill: 'green', stroke: 'black', @@ -28,12 +43,12 @@ suite('Node', function () { assert.equal(circle.getClassName(), 'Circle'); }); // ====================================================== - test('get layer', function () { + it('get layer', function () { var stage = addStage(); var layer = new Konva.Layer(); var circle = new Konva.Circle({ - x: stage.getWidth() / 2, - y: stage.getHeight() / 2, + x: stage.width() / 2, + y: stage.height() / 2, radius: 70, fill: 'green', stroke: 'black', @@ -45,12 +60,12 @@ suite('Node', function () { assert.equal(circle.getLayer(), layer); }); // ====================================================== - test('setAttr', function () { + it('setAttr', function () { var stage = addStage(); var layer = new Konva.Layer(); var circle = new Konva.Circle({ - x: stage.getWidth() / 2, - y: stage.getHeight() / 2, + x: stage.width() / 2, + y: stage.height() / 2, radius: 70, fill: 'green', stroke: 'black', @@ -62,12 +77,12 @@ suite('Node', function () { circle.setAttr('fill', 'red'); layer.draw(); - assert.equal(circle.getFill(), 'red'); + assert.equal(circle.fill(), 'red'); circle.setAttr('position', { x: 5, y: 6 }); - assert.equal(circle.getX(), 5); - assert.equal(circle.getY(), 6); + assert.equal(circle.x(), 5); + assert.equal(circle.y(), 6); circle.setAttr('foobar', 12); @@ -75,12 +90,12 @@ suite('Node', function () { }); // ====================================================== - test('unset attr', function () { + it('unset attr', function () { var stage = addStage(); var layer = new Konva.Layer(); var circle = new Konva.Circle({ - x: stage.getWidth() / 2, - y: stage.getHeight() / 2, + x: stage.width() / 2, + y: stage.height() / 2, radius: 70, fill: 'green', stroke: 'black', @@ -90,27 +105,27 @@ suite('Node', function () { stage.add(layer.add(circle)); circle.setAttr('x', undefined); - assert.equal(circle.getX(), 0); + assert.equal(circle.x(), 0); circle.y(null); assert.equal(circle.y(), 0); }); // ====================================================== - test('set shape and layer opacity to 0.5', function () { + it('set shape and layer opacity to 0.5', function () { var stage = addStage(); var layer = new Konva.Layer(); var circle = new Konva.Circle({ - x: stage.getWidth() / 2, - y: stage.getHeight() / 2, + x: stage.width() / 2, + y: stage.height() / 2, radius: 70, fill: 'green', stroke: 'black', strokeWidth: 4, }); - circle.setOpacity(0.5); - layer.setOpacity(0.5); + circle.opacity(0.5); + layer.opacity(0.5); layer.add(circle); stage.add(layer); @@ -118,12 +133,12 @@ suite('Node', function () { assert.equal(layer.getAbsoluteOpacity(), 0.5); }); // ====================================================== - test('transform cache', function () { + it('transform cache', function () { var stage = addStage(); var layer = new Konva.Layer(); var circle = new Konva.Circle({ - x: stage.getWidth() / 2, - y: stage.getHeight() / 2, + x: stage.width() / 2, + y: stage.height() / 2, radius: 70, fill: 'green', stroke: 'black', @@ -137,19 +152,19 @@ suite('Node', function () { // transform cache assert.notEqual(circle._cache.get('transform'), undefined); - circle.setX(100); + circle.x(100); assert.equal(circle._cache.get('transform').dirty, true); layer.draw(); assert.equal(circle._cache.get('transform').dirty, false); }); // ====================================================== - test('visible cache', function () { + it('visible cache', function () { var stage = addStage(); var layer = new Konva.Layer(); var circle = new Konva.Circle({ - x: stage.getWidth() / 2, - y: stage.getHeight() / 2, + x: stage.width() / 2, + y: stage.height() / 2, radius: 70, fill: 'green', stroke: 'black', @@ -171,12 +186,12 @@ suite('Node', function () { }); // ====================================================== - test('shadow cache', function () { + it('shadow cache', function () { var stage = addStage(); var layer = new Konva.Layer(); var circle = new Konva.Circle({ - x: stage.getWidth() / 2, - y: stage.getHeight() / 2, + x: stage.width() / 2, + y: stage.height() / 2, radius: 70, fill: 'green', stroke: 'black', @@ -187,8 +202,8 @@ suite('Node', function () { // shadow cache assert.equal(circle._cache.get('hasShadow'), false); - circle.setShadowColor('red'); - circle.setShadowOffsetX(10); + circle.shadowColor('red'); + circle.shadowOffsetX(10); assert.equal(circle._cache.get('hasShadow'), undefined); layer.draw(); assert.equal(circle._cache.get('hasShadow'), true); @@ -197,12 +212,12 @@ suite('Node', function () { }); // ====================================================== - test('has shadow', function () { + it('has shadow', function () { var stage = addStage(); var layer = new Konva.Layer(); var rect = new Konva.Rect({ x: 10, - y: stage.getHeight() / 3, + y: stage.height() / 3, width: 100, height: 100, fill: 'red', @@ -220,12 +235,12 @@ suite('Node', function () { }); // ====================================================== - test('opacity cache', function () { + it('opacity cache', function () { var stage = addStage(); var layer = new Konva.Layer(); var circle = new Konva.Circle({ - x: stage.getWidth() / 2, - y: stage.getHeight() / 2, + x: stage.width() / 2, + y: stage.height() / 2, radius: 70, fill: 'green', stroke: 'black', @@ -236,19 +251,19 @@ suite('Node', function () { // opacity cache assert.equal(circle._cache.get('absoluteOpacity'), 1); - circle.setOpacity(0.5); + circle.opacity(0.5); assert.equal(circle._cache.get('absoluteOpacity'), undefined); layer.draw(); assert.equal(circle._cache.get('absoluteOpacity'), 0.5); }); // ====================================================== - test('listening cache', function () { + it('listening cache', function () { var stage = addStage(); var layer = new Konva.Layer(); var circle = new Konva.Circle({ - x: stage.getWidth() / 2, - y: stage.getHeight() / 2, + x: stage.width() / 2, + y: stage.height() / 2, radius: 70, fill: 'green', stroke: 'black', @@ -263,19 +278,19 @@ suite('Node', function () { circle.isListening(); assert.equal(circle._cache.get('listening'), true); - circle.setListening(false); + circle.listening(false); assert.equal(circle._cache.get('listening'), undefined); circle.isListening(); assert.equal(circle._cache.get('listening'), false); }); // ====================================================== - test('stage cache', function () { + it('stage cache', function () { var stage = addStage(); var layer = new Konva.Layer(); var circle = new Konva.Circle({ - x: stage.getWidth() / 2, - y: stage.getHeight() / 2, + x: stage.width() / 2, + y: stage.height() / 2, radius: 70, fill: 'green', stroke: 'black', @@ -290,7 +305,7 @@ suite('Node', function () { }); // ====================================================== - test('toDataURL + HDPI', function (done) { + it('toDataURL + HDPI', function (done) { // this.timeout(5000); var oldRatio = Konva.pixelRatio; Konva.pixelRatio = 2; @@ -314,8 +329,7 @@ suite('Node', function () { stage.toDataURL({ pixelRatio: 2, callback: function (url) { - var img = new Image(); - img.onload = function () { + loadImage(url, (img) => { var image = new Konva.Image({ image: img, scaleX: 0.5, @@ -331,14 +345,13 @@ suite('Node', function () { compareLayers(layer, layer2, 50); Konva.pixelRatio = oldRatio; done(); - }; - img.src = url; + }); }, }); }); // ====================================================== - test('toDataURL with moved layer', function () { + it('toDataURL with moved layer', function () { var stage = addStage(); var layer = new Konva.Layer({ x: 50, @@ -362,7 +375,7 @@ suite('Node', function () { }); // ====================================================== - test('toDataURL with moved layer and moved export', function () { + it('toDataURL with moved layer and moved export', function () { var stage = addStage(); var layer = new Konva.Layer({}); stage.add(layer); @@ -388,7 +401,7 @@ suite('Node', function () { }); // ====================================================== - test('toDataURL of moved shape', function () { + it('toDataURL of moved shape', function () { var stage = addStage(); var layer = new Konva.Layer(); stage.add(layer); @@ -409,7 +422,7 @@ suite('Node', function () { }); // ====================================================== - test('toDataURL of transformer shape', function () { + it('toDataURL of transformer shape', function () { var stage = addStage(); var layer = new Konva.Layer(); stage.add(layer); @@ -431,7 +444,7 @@ suite('Node', function () { }); // ====================================================== - test("listen and don't listen", function () { + it("listen and don't listen", function () { var stage = addStage(); var layer = new Konva.Layer(); var rect = new Konva.Rect({ @@ -454,19 +467,19 @@ suite('Node', function () { layer.add(rect).add(rect2); stage.add(layer); - assert.equal(rect.getListening(), true); + assert.equal(rect.listening(), true); assert.equal(rect.isListening(), true); - rect.setListening(false); - assert.equal(rect.getListening(), false); + rect.listening(false); + assert.equal(rect.listening(), false); - assert.equal(rect2.getListening(), false); - rect2.setListening(true); - assert.equal(rect2.getListening(), true); + assert.equal(rect2.listening(), false); + rect2.listening(true); + assert.equal(rect2.listening(), true); }); // ====================================================== - test("listen and don't listen with one shape", function () { + it("listen and don't listen with one shape", function () { var stage = addStage(); var layer = new Konva.Layer(); var rect = new Konva.Rect({ @@ -480,7 +493,7 @@ suite('Node', function () { layer.add(rect); stage.add(layer); - rect.setListening(false); + rect.listening(false); layer.drawHit(); showHit(layer); @@ -489,7 +502,7 @@ suite('Node', function () { }); // ====================================================== - test('test offset attr change', function () { + it('test offset attr change', function () { /* * the premise of this test to make sure that only * root level attributes trigger an attr change event. @@ -526,7 +539,7 @@ suite('Node', function () { }); // ====================================================== - test('simple clone', function () { + it('simple clone', function () { var stage = addStage(); var layer = new Konva.Layer(); @@ -545,12 +558,12 @@ suite('Node', function () { layer.add(clone); stage.add(layer); - assert.equal(rect.getStroke(), 'red'); - assert.equal(clone.getStroke(), 'green'); + assert.equal(rect.stroke(), 'red'); + assert.equal(clone.stroke(), 'green'); }); // ====================================================== - test('clone - check reference', function () { + it('clone - check reference', function () { var stage = addStage(); var layer = new Konva.Layer(); @@ -573,7 +586,7 @@ suite('Node', function () { }); // ====================================================== - test('complex clone', function () { + it('complex clone', function () { var stage = addStage(); var layer = new Konva.Layer(); var rect = new Konva.Rect({ @@ -595,7 +608,7 @@ suite('Node', function () { var clicks = []; rect.on('click', function () { - clicks.push(this.getName()); + clicks.push(this.name()); }); var clone = rect.clone({ x: 300, @@ -603,26 +616,26 @@ suite('Node', function () { name: 'rectClone', }); - assert.equal(clone.getX(), 300); - assert.equal(clone.getY(), 50); - assert.equal(clone.getWidth(), 200); - assert.equal(clone.getHeight(), 50); - assert.equal(clone.getFill(), 'red'); + assert.equal(clone.x(), 300); + assert.equal(clone.y(), 50); + assert.equal(clone.width(), 200); + assert.equal(clone.height(), 50); + assert.equal(clone.fill(), 'red'); - assert.equal(rect.getShadowColor(), 'black'); - assert.equal(clone.getShadowColor(), 'black'); + assert.equal(rect.shadowColor(), 'black'); + assert.equal(clone.shadowColor(), 'black'); assert.equal(clone.id() === 'myRect', true, 'clone id'); - clone.setShadowColor('green'); + clone.shadowColor('green'); /* * Make sure that when we change a clone object attr that the rect object * attr isn't updated by reference */ - assert.equal(rect.getShadowColor(), 'black'); - assert.equal(clone.getShadowColor(), 'green'); + assert.equal(rect.shadowColor(), 'black'); + assert.equal(clone.shadowColor(), 'green'); layer.add(rect); layer.add(clone); @@ -640,7 +653,7 @@ suite('Node', function () { }); // ====================================================== - test('clone a group', function () { + it('clone a group', function () { var stage = addStage(); var layer = new Konva.Layer(); var group = new Konva.Group({ @@ -658,7 +671,7 @@ suite('Node', function () { offsetX: 10, offsetY: 10, shadowColor: 'black', - shadowOffset: [20, 20], + shadowOffset: { x: 20, y: 20 }, name: 'myRect', myAttr: 'group rect', }); @@ -678,7 +691,7 @@ suite('Node', function () { var taps = []; group.on('click', function () { - clicks.push(this.getName()); + clicks.push(this.name()); }); rect.on('tap', function () { taps.push(this.attrs.myAttr); @@ -694,18 +707,18 @@ suite('Node', function () { layer.add(clone); stage.add(layer); - assert.equal(clone.getX(), 300); - assert.equal(clone.getY(), 0); - assert.equal(clone.getDraggable(), true); + assert.equal(clone.x(), 300); + assert.equal(clone.y(), 0); + assert.equal(clone.draggable(), true); // test alias assert.equal(clone.draggable(), true); - assert.equal(clone.getName(), 'groupClone'); + assert.equal(clone.name(), 'groupClone'); assert.equal(group.getChildren().length, 2); assert.equal(clone.getChildren().length, 2); - assert.equal(group.find('.myText')[0].getFill(), 'blue'); - assert.equal(clone.find('.myText')[0].getFill(), 'blue'); - clone.find('.myText')[0].setFill('black'); + assert.equal(group.find('.myText')[0].fill(), 'blue'); + assert.equal(clone.find('.myText')[0].fill(), 'blue'); + clone.find('.myText')[0].fill('black'); assert.equal(group.find('.myRect')[0].attrs.myAttr, 'group rect'); assert.equal(clone.find('.myRect')[0].attrs.myAttr, 'group rect'); clone.find('.myRect')[0].setAttrs({ @@ -715,8 +728,8 @@ suite('Node', function () { // Make sure that when we change a clone object attr that the rect object // attr isn't updated by reference - assert.equal(group.find('.myText')[0].getFill(), 'blue'); - assert.equal(clone.find('.myText')[0].getFill(), 'black'); + assert.equal(group.find('.myText')[0].fill(), 'blue'); + assert.equal(clone.find('.myText')[0].fill(), 'black'); assert.equal(group.find('.myRect')[0].attrs.myAttr, 'group rect'); assert.equal(clone.find('.myRect')[0].attrs.myAttr, 'clone rect'); @@ -746,7 +759,7 @@ suite('Node', function () { }); // ====================================================== - test('test on attr change', function () { + it('test on attr change', function () { var stage = addStage(); var layer = new Konva.Layer(); var rect = new Konva.Rect({ @@ -759,8 +772,8 @@ suite('Node', function () { }); var circle = new Konva.Circle({ - x: stage.getWidth() / 2, - y: stage.getHeight() / 2, + x: stage.width() / 2, + y: stage.height() / 2, radius: 35, fill: 'green', stroke: 'black', @@ -777,8 +790,8 @@ suite('Node', function () { rect.on('widthChange', function (evt) { widthChanged++; - assert.equal(evt.oldVal, 200); - assert.equal(evt.newVal, 210); + assert.equal(evt['oldVal'], 200); + assert.equal(evt['newVal'], 210); }); rect.on('shadowOffsetChange', function () { @@ -789,11 +802,12 @@ suite('Node', function () { radiusChanged++; }); - circle.setRadius(70); + circle.radius(70); rect.setSize({ width: 210, height: 210 }); - rect.setShadowOffset({ + rect.shadowOffset({ x: 20, + y: 0, }); assert.equal(widthChanged, 1); @@ -802,7 +816,7 @@ suite('Node', function () { }); // ====================================================== - test('test on attr change for same value', function () { + it('test on attr change for same value', function () { var stage = addStage(); var layer = new Konva.Layer(); var rect = new Konva.Rect({ @@ -830,21 +844,21 @@ suite('Node', function () { }); // ====================================================== - test('set shape, layer and stage opacity to 0.5', function () { + it('set shape, layer and stage opacity to 0.5', function () { var stage = addStage(); var layer = new Konva.Layer(); var circle = new Konva.Circle({ - x: stage.getWidth() / 2, - y: stage.getHeight() / 2, + x: stage.width() / 2, + y: stage.height() / 2, radius: 70, fill: 'green', stroke: 'black', strokeWidth: 4, }); - circle.setOpacity(0.5); - layer.setOpacity(0.5); - stage.setOpacity(0.5); + circle.opacity(0.5); + layer.opacity(0.5); + stage.opacity(0.5); layer.add(circle); stage.add(layer); @@ -854,7 +868,7 @@ suite('Node', function () { }); // ====================================================== - test('hide show layer', function () { + it('hide show layer', function () { var stage = addStage(); var layer1 = new Konva.Layer(); @@ -862,7 +876,7 @@ suite('Node', function () { var circle1 = new Konva.Circle({ x: 100, - y: stage.getHeight() / 2, + y: stage.height() / 2, radius: 70, fill: 'green', stroke: 'black', @@ -870,7 +884,7 @@ suite('Node', function () { }); var circle2 = new Konva.Circle({ x: 150, - y: stage.getHeight() / 2, + y: stage.height() / 2, radius: 70, fill: 'red', stroke: 'black', @@ -900,7 +914,7 @@ suite('Node', function () { }); // ====================================================== - test('rotation in degrees', function () { + it('rotation in degrees', function () { var stage = addStage(); var layer = new Konva.Layer(); var rect = new Konva.Rect({ @@ -925,7 +939,7 @@ suite('Node', function () { }); // ====================================================== - test('skew', function () { + it('skew', function () { var stage = addStage(); var layer = new Konva.Layer(); var rect = new Konva.Rect({ @@ -942,8 +956,8 @@ suite('Node', function () { layer.add(rect); stage.add(layer); - assert.equal(rect.getSkewX(), 1); - assert.equal(rect.getSkewY(), 0); + assert.equal(rect.skewX(), 1); + assert.equal(rect.skewY(), 0); /* rect.transitionTo({ @@ -957,7 +971,7 @@ suite('Node', function () { }); // ====================================================== - test('init with position, scale, rotation, then change scale', function () { + it('init with position, scale, rotation, then change scale', function () { var stage = addStage(); var layer = new Konva.Layer(); var rect = new Konva.Rect({ @@ -977,22 +991,21 @@ suite('Node', function () { assert.equal(rect.getPosition().x, 200); assert.equal(rect.getPosition().y, 100); - assert.equal(rect.getScale().x, 0.5); - assert.equal(rect.getScale().y, 0.5); - assert.equal(rect.getRotation(), 20); + assert.equal(rect.scale().x, 0.5); + assert.equal(rect.scale().y, 0.5); + assert.equal(rect.rotation(), 20); - rect.setScale({ x: 2, y: 0.3 }); - assert.equal(rect.getScale().x, 2); - assert.equal(rect.getScale().y, 0.3); + rect.scale({ x: 2, y: 0.3 }); + assert.equal(rect.scale().x, 2); + assert.equal(rect.scale().y, 0.3); layer.add(rect); stage.add(layer); }); // ====================================================== - test('clone sprite', function (done) { - var imageObj = new Image(); - imageObj.onload = function () { + it('clone sprite', function (done) { + loadImage('scorpion-sprite.png', (imageObj) => { var stage = addStage(); var layer = new Konva.Layer(); @@ -1068,13 +1081,15 @@ suite('Node', function () { stage.add(layer); clone.start(); + assert.equal(clone.image(), sprite.image()); + + // just check clone without crashes done(); - }; - imageObj.src = 'assets/scorpion-sprite.png'; + }); }); // ====================================================== - test('node caching', function (done) { + it('node caching', function (done) { var stage = addStage(); var layer = new Konva.Layer(); var group = new Konva.Group(); @@ -1120,7 +1135,7 @@ suite('Node', function () { }); // ====================================================== - test('hide group', function () { + it('hide group', function () { var stage = addStage(); var layer = new Konva.Layer(); @@ -1128,7 +1143,7 @@ suite('Node', function () { var circle1 = new Konva.Circle({ x: 100, - y: stage.getHeight() / 2, + y: stage.height() / 2, radius: 70, fill: 'green', stroke: 'black', @@ -1136,7 +1151,7 @@ suite('Node', function () { }); var circle2 = new Konva.Circle({ x: 150, - y: stage.getHeight() / 2, + y: stage.height() / 2, radius: 70, fill: 'red', stroke: 'black', @@ -1166,12 +1181,12 @@ suite('Node', function () { }); // ====================================================== - test('add shape with custom attr pointing to self', function () { + it('add shape with custom attr pointing to self', function () { var stage = addStage(); var layer = new Konva.Layer(); var circle = new Konva.Circle({ - x: stage.getWidth() / 2, - y: stage.getHeight() / 2, + x: stage.width() / 2, + y: stage.height() / 2, radius: 70, fill: 'green', stroke: 'black', @@ -1210,7 +1225,7 @@ suite('Node', function () { }); // ====================================================== - test('set offset offset after instantiation', function () { + it('set offset offset after instantiation', function () { var stage = addStage(); var layer = new Konva.Layer(); var rect = new Konva.Rect({ @@ -1244,12 +1259,12 @@ suite('Node', function () { }); // ====================================================== - test('test name methods', function () { + it('test name methods', function () { var stage = addStage(); var layer = new Konva.Layer(); var circle = new Konva.Circle({ - x: stage.getWidth() / 2, - y: stage.getHeight() / 2, + x: stage.width() / 2, + y: stage.height() / 2, radius: 70, fill: 'green', stroke: 'black', @@ -1258,16 +1273,16 @@ suite('Node', function () { layer.add(circle); stage.add(layer); - assert.equal(circle.getName(), ''); + assert.equal(circle.name(), ''); circle.addName('foo'); - assert.equal(circle.getName(), 'foo'); + assert.equal(circle.name(), 'foo'); circle.addName('myCircle'); - assert.equal(circle.getName(), 'foo myCircle'); + assert.equal(circle.name(), 'foo myCircle'); // add existing name circle.addName('foo'); - assert.equal(circle.getName(), 'foo myCircle'); + assert.equal(circle.name(), 'foo myCircle'); // check hasName assert.equal(circle.hasName('myCircle'), true); @@ -1279,12 +1294,12 @@ suite('Node', function () { // removing name circle.removeName('foo'); - assert.equal(circle.getName(), 'myCircle'); + assert.equal(circle.name(), 'myCircle'); assert.equal(layer.find('.foo').length, 0); }); // ====================================================== - test('test setting shadow offset', function () { + it('test setting shadow offset', function () { var stage = addStage(); var layer = new Konva.Layer(); var rect = new Konva.Rect({ @@ -1300,33 +1315,33 @@ suite('Node', function () { layer.add(rect); stage.add(layer); - rect.setShadowOffset({ x: 1, y: 2 }); - assert.equal(rect.getShadowOffset().x, 1); - assert.equal(rect.getShadowOffset().y, 2); + rect.shadowOffset({ x: 1, y: 2 }); + assert.equal(rect.shadowOffset().x, 1); + assert.equal(rect.shadowOffset().y, 2); // make sure we still have the other properties - assert.equal(rect.getShadowColor(), 'blue'); - assert.equal(rect.getShadowBlur(), 12); + assert.equal(rect.shadowColor(), 'blue'); + assert.equal(rect.shadowBlur(), 12); - rect.setShadowOffset({ + rect.shadowOffset({ x: 3, y: 4, }); - assert.equal(rect.getShadowOffset().x, 3); - assert.equal(rect.getShadowOffset().y, 4); + assert.equal(rect.shadowOffset().x, 3); + assert.equal(rect.shadowOffset().y, 4); // test partial setting - rect.setShadowOffsetX(5); - assert.equal(rect.getShadowOffset().x, 5); - assert.equal(rect.getShadowOffset().y, 4); + rect.shadowOffsetX(5); + assert.equal(rect.shadowOffset().x, 5); + assert.equal(rect.shadowOffset().y, 4); // test partial setting - rect.setShadowOffsetY(6); - assert.equal(rect.getShadowOffset().x, 5); - assert.equal(rect.getShadowOffset().y, 6); + rect.shadowOffsetY(6); + assert.equal(rect.shadowOffset().x, 5); + assert.equal(rect.shadowOffset().y, 6); }); // ====================================================== - test('test offset', function () { + it('test offset', function () { var stage = addStage(); var layer = new Konva.Layer(); var rect = new Konva.Rect({ @@ -1365,7 +1380,7 @@ suite('Node', function () { }); // ====================================================== - test('test setPosition and move', function () { + it('test setPosition and move', function () { var stage = addStage(); var layer = new Konva.Layer(); var rect = new Konva.Rect({ @@ -1394,11 +1409,11 @@ suite('Node', function () { assert.equal(rect.getPosition().x, 5); assert.equal(rect.getPosition().y, 6); - rect.setX(7); + rect.x(7); assert.equal(rect.getPosition().x, 7); assert.equal(rect.getPosition().y, 6); - rect.setY(8); + rect.y(8); assert.equal(rect.getPosition().x, 7); assert.equal(rect.getPosition().y, 8); @@ -1408,7 +1423,7 @@ suite('Node', function () { }); // ====================================================== - test('test setScale', function () { + it('test setScale', function () { var stage = addStage(); var layer = new Konva.Layer(); var rect = new Konva.Rect({ @@ -1424,40 +1439,40 @@ suite('Node', function () { layer.add(rect); stage.add(layer); - rect.setScale({ x: 2, y: 3 }); - assert.equal(rect.getScale().x, 2); - assert.equal(rect.getScale().y, 3); + rect.scale({ x: 2, y: 3 }); + assert.equal(rect.scale().x, 2); + assert.equal(rect.scale().y, 3); - rect.setScale({ x: 4, y: 4 }); - assert.equal(rect.getScale().x, 4); - assert.equal(rect.getScale().y, 4); + rect.scale({ x: 4, y: 4 }); + assert.equal(rect.scale().x, 4); + assert.equal(rect.scale().y, 4); - rect.setScale({ x: 5, y: 6 }); - assert.equal(rect.getScale().x, 5); - assert.equal(rect.getScale().y, 6); + rect.scale({ x: 5, y: 6 }); + assert.equal(rect.scale().x, 5); + assert.equal(rect.scale().y, 6); - rect.setScale({ x: 7, y: 8 }); - assert.equal(rect.getScale().x, 7); - assert.equal(rect.getScale().y, 8); + rect.scale({ x: 7, y: 8 }); + assert.equal(rect.scale().x, 7); + assert.equal(rect.scale().y, 8); - rect.setScale({ + rect.scale({ x: 9, y: 10, }); - assert.equal(rect.getScale().x, 9); - assert.equal(rect.getScale().y, 10); + assert.equal(rect.scale().x, 9); + assert.equal(rect.scale().y, 10); - rect.setScaleX(11); - assert.equal(rect.getScale().x, 11); - assert.equal(rect.getScale().y, 10); + rect.scaleX(11); + assert.equal(rect.scale().x, 11); + assert.equal(rect.scale().y, 10); - rect.setScaleY(12); - assert.equal(rect.getScale().x, 11); - assert.equal(rect.getScale().y, 12); + rect.scaleY(12); + assert.equal(rect.scale().x, 11); + assert.equal(rect.scale().y, 12); }); // ====================================================== - test('test config scale', function () { + it('test config scale', function () { var stage = addStage(); var layer = new Konva.Layer(); var rect1 = new Konva.Rect({ @@ -1511,24 +1526,24 @@ suite('Node', function () { layer.add(rect1).add(rect2).add(rect3).add(rect4).add(rect5); stage.add(layer); - assert.equal(rect1.getScale().x, 2); - assert.equal(rect1.getScale().y, 3); + assert.equal(rect1.scale().x, 2); + assert.equal(rect1.scale().y, 3); - assert.equal(rect2.getScale().x, 2); - assert.equal(rect2.getScale().y, 2); + assert.equal(rect2.scale().x, 2); + assert.equal(rect2.scale().y, 2); - assert.equal(rect3.getScale().x, 2); - assert.equal(rect3.getScale().y, 3); + assert.equal(rect3.scale().x, 2); + assert.equal(rect3.scale().y, 3); - assert.equal(rect4.getScale().x, 2); - assert.equal(rect4.getScale().y, 1); + assert.equal(rect4.scale().x, 2); + assert.equal(rect4.scale().y, 1); - //assert.equal(rect5.getScale().x, 1); - assert.equal(rect5.getScale().y, 2); + //assert.equal(rect5.scale().x, 1); + assert.equal(rect5.scale().y, 2); }); // ====================================================== - test('test config position', function () { + it('test config position', function () { var stage = addStage(); var layer = new Konva.Layer(); var rect1 = new Konva.Rect({ @@ -1576,7 +1591,7 @@ suite('Node', function () { }); // ====================================================== - test('test getPosition and getAbsolutePosition for shape inside transformed stage', function () { + it('test getPosition and getAbsolutePosition for shape inside transformed stage', function () { var stage = addStage(); var layer = new Konva.Layer(); var rect = new Konva.Rect({ @@ -1594,7 +1609,7 @@ suite('Node', function () { stage.add(layer); stage.rotate(180 / 3); - stage.setScale({ x: 0.5, y: 0.5 }); + stage.scale({ x: 0.5, y: 0.5 }); stage.draw(); @@ -1606,7 +1621,7 @@ suite('Node', function () { }); // ====================================================== - test('test consecutive getAbsolutePositions()s when shape has offset', function () { + it('test consecutive getAbsolutePositions()s when shape has offset', function () { var stage = addStage(); var layer = new Konva.Layer(); var rect = new Konva.Rect({ @@ -1655,7 +1670,7 @@ suite('Node', function () { }); // ====================================================== - test('test getPosition and getAbsolutePosition for transformed parent with offset offset', function () { + it('test getPosition and getAbsolutePosition for transformed parent with offset offset', function () { var side = 100; var diagonal = Math.sqrt(side * side * 2); @@ -1715,7 +1730,7 @@ suite('Node', function () { }); // ====================================================== - test('test relative getAbsolutePosition for transformed parent ', function () { + it('test relative getAbsolutePosition for transformed parent ', function () { var stage = addStage(); var layer = new Konva.Layer({ name: 'layerName', @@ -1745,7 +1760,7 @@ suite('Node', function () { }); // ====================================================== - test( + it( 'results of getAbsoluteTransform limited to position and offset transformations are the same' + " when used with transformsEnabled = 'all' and transformsEnabled = 'position'", function () { @@ -1791,13 +1806,13 @@ suite('Node', function () { layer2.add(group2); stage.add(layer2); - assert.equal(layer1.getTransformsEnabled(), 'all'); - assert.equal(group1.getTransformsEnabled(), 'all'); - assert.equal(rect1.getTransformsEnabled(), 'all'); + assert.equal(layer1.transformsEnabled(), 'all'); + assert.equal(group1.transformsEnabled(), 'all'); + assert.equal(rect1.transformsEnabled(), 'all'); - assert.equal(layer2.getTransformsEnabled(), 'position'); - assert.equal(group2.getTransformsEnabled(), 'position'); - assert.equal(rect2.getTransformsEnabled(), 'position'); + assert.equal(layer2.transformsEnabled(), 'position'); + assert.equal(group2.transformsEnabled(), 'position'); + assert.equal(rect2.transformsEnabled(), 'position'); assert.deepEqual( rect2.getAbsoluteTransform(), @@ -1807,7 +1822,7 @@ suite('Node', function () { ); // ====================================================== - test('test dragDistance', function () { + it('test dragDistance', function () { var stage = addStage(); var layer = new Konva.Layer(); var rect1 = new Konva.Rect({ @@ -1839,7 +1854,7 @@ suite('Node', function () { }); // ====================================================== - test('translate, rotate, scale shape', function () { + it('translate, rotate, scale shape', function () { var stage = addStage(); var layer = new Konva.Layer(); var circle = new Konva.Rect({ @@ -1872,7 +1887,7 @@ suite('Node', function () { }); // ====================================================== - test('test isListening', function () { + it('test isListening', function () { var stage = addStage(); var layer = new Konva.Layer(); var rect = new Konva.Rect({ @@ -1891,30 +1906,30 @@ suite('Node', function () { assert.equal(rect.isListening(), true); - rect.setListening(false); + rect.listening(false); assert.equal(rect.isListening(), false); - rect.setListening(true); + rect.listening(true); assert.equal(rect.isListening(), true); - layer.setListening(false); + layer.listening(false); assert.equal(rect.isListening(), false); - layer.setListening(true); + layer.listening(true); assert.equal(rect.isListening(), true); - stage.setListening(false); + stage.listening(false); assert.equal(rect.isListening(), false); }); // ====================================================== - test('test fire event', function () { + it('test fire event', function () { var stage = addStage(); var layer = new Konva.Layer(); var circle = new Konva.Circle({ - x: stage.getWidth() / 2, - y: stage.getHeight() / 2, + x: stage.width() / 2, + y: stage.height() / 2, radius: 70, fill: 'green', stroke: 'black', @@ -1939,7 +1954,7 @@ suite('Node', function () { }); var foo; circle.on('customEvent', function (evt) { - foo = evt.foo; + foo = evt['foo']; }); layer.on('click', function () { @@ -1969,12 +1984,12 @@ suite('Node', function () { }); // ====================================================== - test('add remove event', function () { + it('add remove event', function () { var stage = addStage(); var layer = new Konva.Layer(); var circle = new Konva.Circle({ - x: stage.getWidth() / 2, - y: stage.getHeight() / 2, + x: stage.width() / 2, + y: stage.height() / 2, radius: 70, fill: 'green', stroke: 'black', @@ -2047,12 +2062,12 @@ suite('Node', function () { }); // ====================================================== - test('remove event with with callback', function () { + it('remove event with with callback', function () { var stage = addStage(); var layer = new Konva.Layer(); var circle = new Konva.Circle({ - x: stage.getWidth() / 2, - y: stage.getHeight() / 2, + x: stage.width() / 2, + y: stage.height() / 2, radius: 70, fill: 'green', stroke: 'black', @@ -2089,12 +2104,12 @@ suite('Node', function () { }); // ====================================================== - test('simulate event bubble', function () { + it('simulate event bubble', function () { var stage = addStage(); var layer = new Konva.Layer(); var circle = new Konva.Circle({ - x: stage.getWidth() / 2, - y: stage.getHeight() / 2, + x: stage.width() / 2, + y: stage.height() / 2, radius: 70, fill: 'green', stroke: 'black', @@ -2123,12 +2138,12 @@ suite('Node', function () { }); // ====================================================== - test('simulate cancel event bubble', function () { + it('simulate cancel event bubble', function () { var stage = addStage(); var layer = new Konva.Layer(); var circle = new Konva.Circle({ - x: stage.getWidth() / 2, - y: stage.getHeight() / 2, + x: stage.width() / 2, + y: stage.height() / 2, radius: 70, fill: 'green', stroke: 'black', @@ -2157,12 +2172,13 @@ suite('Node', function () { assert.equal(clicks.length, 1); }); - test('simple event delegation', function () { + // TODO: should we remove deligation? + it.skip('simple event delegation', function () { var stage = addStage(); var layer = new Konva.Layer(); var circle = new Konva.Circle({ - x: stage.getWidth() / 2, - y: stage.getHeight() / 2, + x: stage.width() / 2, + y: stage.height() / 2, radius: 70, fill: 'green', stroke: 'black', @@ -2175,22 +2191,22 @@ suite('Node', function () { layer.draw(); var fired = false; - layer.on('click', 'Circle', function (e) { - assert.equal(this, circle); - assert.equal(e.currentTarget, circle); - fired = true; - }); + // layer.on('click', 'Circle', function (e) { + // assert.equal(this, circle); + // assert.equal(e.currentTarget, circle); + // fired = true; + // }); circle.fire('click', undefined, true); assert.equal(fired, true); }); - test('complex event delegation', function () { + it.skip('complex event delegation', function () { var stage = addStage(); var layer = new Konva.Layer(); stage.add(layer); var circle = new Konva.Circle({ - x: stage.getWidth() / 2, - y: stage.getHeight() / 2, + x: stage.width() / 2, + y: stage.height() / 2, radius: 70, fill: 'green', stroke: 'black', @@ -2206,23 +2222,23 @@ suite('Node', function () { layer.draw(); var fired = false; - layer.on('click', '.group1', function (e) { - assert.equal(this, group); - assert.equal(e.currentTarget, group); - fired = true; - }); + // layer.on('click', '.group1', function (e) { + // assert.equal(this, group); + // assert.equal(e.currentTarget, group); + // fired = true; + // }); circle.fire('click', undefined, true); assert.equal(fired, true); }); // ====================================================== - test('move shape, group, and layer, and then get absolute position', function () { + it('move shape, group, and layer, and then get absolute position', function () { var stage = addStage(); var layer = new Konva.Layer(); var group = new Konva.Group(); var circle = new Konva.Circle({ - x: stage.getWidth() / 2, - y: stage.getHeight() / 2, + x: stage.width() / 2, + y: stage.height() / 2, radius: 70, fill: 'green', stroke: 'black', @@ -2251,7 +2267,7 @@ suite('Node', function () { }); // ====================================================== - test('scale layer, rotate group, position shape, and then get absolute position', function () { + it('scale layer, rotate group, position shape, and then get absolute position', function () { var stage = addStage(); var layer = new Konva.Layer({ scale: { @@ -2287,12 +2303,12 @@ suite('Node', function () { }); // ====================================================== - test('hide show circle', function () { + it('hide show circle', function () { var stage = addStage(); var layer = new Konva.Layer(); var circle = new Konva.Circle({ - x: stage.getWidth() / 2, - y: stage.getHeight() / 2, + x: stage.width() / 2, + y: stage.height() / 2, radius: 70, fill: 'green', stroke: 'black', @@ -2316,12 +2332,12 @@ suite('Node', function () { }); // ====================================================== - test('set shape opacity to 0.5', function () { + it('set shape opacity to 0.5', function () { var stage = addStage(); var layer = new Konva.Layer(); var circle = new Konva.Circle({ - x: stage.getWidth() / 2, - y: stage.getHeight() / 2, + x: stage.width() / 2, + y: stage.height() / 2, radius: 70, fill: 'green', stroke: 'black', @@ -2329,7 +2345,7 @@ suite('Node', function () { draggable: true, }); - circle.setOpacity(0.5); + circle.opacity(0.5); layer.add(circle); stage.add(layer); @@ -2349,32 +2365,32 @@ suite('Node', function () { ); }); - test('set shape opacity to 0.5 then back to 1', function () { + it('set shape opacity to 0.5 then back to 1', function () { var stage = addStage(); var layer = new Konva.Layer(); var circle = new Konva.Circle({ - x: stage.getWidth() / 2, - y: stage.getHeight() / 2, + x: stage.width() / 2, + y: stage.height() / 2, radius: 70, fill: 'green', stroke: 'black', strokeWidth: 4, }); - circle.setOpacity(0.5); + circle.opacity(0.5); layer.add(circle); stage.add(layer); assert.equal(circle.getAbsoluteOpacity(), 0.5); - circle.setOpacity(1); + circle.opacity(1); layer.draw(); assert.equal(circle.getAbsoluteOpacity(), 1); }); // ====================================================== - test('get absolute z index', function () { + it('get absolute z index', function () { var stage = addStage(); var layer = new Konva.Layer(); var group1 = new Konva.Group(); @@ -2384,14 +2400,14 @@ suite('Node', function () { var shape1 = new Konva.Circle({ x: 150, - y: stage.getHeight() / 2, + y: stage.height() / 2, radius: 40, fill: 'green', }); var shape2 = new Konva.Circle({ x: 250, - y: stage.getHeight() / 2, + y: stage.height() / 2, radius: 40, fill: 'green', }); @@ -2434,7 +2450,7 @@ suite('Node', function () { }); // ====================================================== - test('JPEG toDataURL() Not Hiding Lower Layers with Black', function (done) { + it('JPEG toDataURL() Not Hiding Lower Layers with Black', function (done) { var stage = addStage(); var layer1 = new Konva.Layer(); @@ -2468,8 +2484,7 @@ suite('Node', function () { mimeType: 'image/jpeg', quality: 0.8, callback: function (url) { - var imageObj = new Image(); - imageObj.onload = function () { + loadImage(url, (imageObj) => { layer2.add( new Konva.Image({ x: 200, @@ -2479,20 +2494,19 @@ suite('Node', function () { ); layer2.draw(); done(); - }; - imageObj.src = url; + }); }, }); }); // ====================================================== - test('serialize stage', function () { + it('serialize stage', function () { var stage = addStage(); var layer = new Konva.Layer(); var group = new Konva.Group(); var circle = new Konva.Circle({ - x: stage.getWidth() / 2, - y: stage.getHeight() / 2, + x: stage.width() / 2, + y: stage.height() / 2, radius: 70, fill: 'green', stroke: 'black', @@ -2513,13 +2527,13 @@ suite('Node', function () { }); // ====================================================== - test('serialize shape', function () { + it('serialize shape', function () { var stage = addStage(); var layer = new Konva.Layer(); var group = new Konva.Group(); var circle = new Konva.Circle({ - x: stage.getWidth() / 2, - y: stage.getHeight() / 2, + x: stage.width() / 2, + y: stage.height() / 2, radius: 70, fill: 'green', stroke: 'black', @@ -2541,13 +2555,13 @@ suite('Node', function () { }); // ====================================================== - test('serialize shape with custom attributes', function () { + it('serialize shape with custom attributes', function () { var stage = addStage(); var layer = new Konva.Layer(); var group = new Konva.Group(); var circle = new Konva.Circle({ - x: stage.getWidth() / 2, - y: stage.getHeight() / 2, + x: stage.width() / 2, + y: stage.height() / 2, radius: 70, fill: 'green', stroke: 'black', @@ -2578,7 +2592,7 @@ suite('Node', function () { }); // ====================================================== - test('load stage using json', function () { + it('load stage using json', function () { var container = addContainer(); var json = '{"attrs":{"width":578,"height":200},"className":"Stage","children":[{"attrs":{},"className":"Layer","children":[{"attrs":{},"className":"Group","children":[{"attrs":{"x":289,"y":100,"radius":70,"fill":"green","stroke":"black","strokeWidth":4,"name":"myCircle","draggable":true},"className":"Circle"}]}]}]}'; @@ -2588,7 +2602,7 @@ suite('Node', function () { }); // ====================================================== - test('create node using object', function () { + it('create node using object', function () { var node = new Konva.Circle({ id: 'test', radius: 10, @@ -2598,7 +2612,7 @@ suite('Node', function () { assert.deepEqual(node.toObject(), clone.toObject()); }); - test('make sure we can create non existing node type', function () { + it('make sure we can create non existing node type', function () { var json = '{"attrs":{},"className":"Layer","children":[{"attrs":{},"className":"Group","children":[{"attrs":{"x":289,"y":100,"radius":70,"fill":"green","stroke":"black","strokeWidth":4,"name":"myCircle","draggable":true},"className":"WeirdShape"}]}]}'; var layer = Konva.Node.create(json); @@ -2607,7 +2621,7 @@ suite('Node', function () { }); // ====================================================== - test('serialize stage with custom shape', function () { + it('serialize stage with custom shape', function () { var stage = addStage(); var layer = new Konva.Layer(); var group = new Konva.Group(); @@ -2632,7 +2646,7 @@ suite('Node', function () { layer.add(group); stage.add(layer); - assert.equal(triangle.getId(), 'myTriangle'); + assert.equal(triangle.id(), 'myTriangle'); var expectedJson = '{"attrs":{"width":578,"height":200},"className":"Stage","children":[{"attrs":{},"className":"Layer","children":[{"attrs":{},"className":"Group","children":[{"attrs":{"fill":"#00D2FF","stroke":"black","strokeWidth":4,"id":"myTriangle"},"className":"Shape"}]}]}]}'; @@ -2643,7 +2657,7 @@ suite('Node', function () { }); // ====================================================== - test('load stage with custom shape using json', function () { + it('load stage with custom shape using json', function () { var container = addContainer(); var drawTriangle = function (context) { @@ -2659,7 +2673,7 @@ suite('Node', function () { var stage = Konva.Node.create(json, container); - stage.find('#myTriangle1').each(function (node) { + stage.find('#myTriangle1').forEach(function (node) { node.sceneFunc(drawTriangle); }); @@ -2669,12 +2683,11 @@ suite('Node', function () { }); // ====================================================== - test('serialize stage with an image', function (done) { - var imageObj = new Image(); - imageObj.onload = function () { + it('serialize stage with an image', function (done) { + loadImage('darth-vader.jpg', (imageObj) => { var stage = addStage(); var layer = new Konva.Layer(); - darth = new Konva.Image({ + const darth = new Konva.Image({ x: 200, y: 60, image: imageObj, @@ -2693,37 +2706,34 @@ suite('Node', function () { assert.equal(stage.toJSON(), json); done(); - }; - imageObj.src = 'assets/darth-vader.jpg'; + }); }); // ====================================================== - test('load stage with an image', function (done) { - var imageObj = new Image(); + it('load stage with an image', function (done) { var container = addContainer(); - imageObj.onload = function () { + loadImage('darth-vader.jpg', (imageObj) => { var json = '{"attrs":{"width":578,"height":200},"className":"Stage","children":[{"attrs":{},"className":"Layer","children":[{"attrs":{"x":200,"y":60,"offsetX":50,"offsetY":150,"id":"darth1"},"className":"Image"}]}]}'; var stage = Konva.Node.create(json, container); assert.equal(stage.toJSON(), json); - stage.find('#darth1').each(function (node) { + stage.find('#darth1').forEach(function (node) { node.setImage(imageObj); }); stage.draw(); done(); - }; - imageObj.src = 'assets/darth-vader.jpg'; + }); }); // ====================================================== - test('remove shape', function () { + it('remove shape', function () { var stage = addStage(); var layer = new Konva.Layer(); var circle = new Konva.Circle({ - x: stage.getWidth() / 2, - y: stage.getHeight() / 2, + x: stage.width() / 2, + y: stage.height() / 2, radius: 70, fill: 'green', stroke: 'black', @@ -2746,12 +2756,12 @@ suite('Node', function () { }); // ====================================================== - test('destroy shape', function () { + it('destroy shape', function () { var stage = addStage(); var layer = new Konva.Layer(); var circle = new Konva.Circle({ - x: stage.getWidth() / 2, - y: stage.getHeight() / 2, + x: stage.width() / 2, + y: stage.height() / 2, radius: 70, fill: 'green', stroke: 'black', @@ -2774,12 +2784,12 @@ suite('Node', function () { }); // ====================================================== - test('memory leak test for destroy and a shape with several names', function () { + it('memory leak test for destroy and a shape with several names', function () { var stage = addStage(); var layer = new Konva.Layer(); var circle = new Konva.Circle({ - x: stage.getWidth() / 2, - y: stage.getHeight() / 2, + x: stage.width() / 2, + y: stage.height() / 2, radius: 70, fill: 'green', stroke: 'black', @@ -2800,12 +2810,12 @@ suite('Node', function () { }); // ====================================================== - test('destroy shape without adding its parent to stage', function () { + it('destroy shape without adding its parent to stage', function () { var stage = addStage(); var layer = new Konva.Layer(); var circle = new Konva.Circle({ - x: stage.getWidth() / 2, - y: stage.getHeight() / 2, + x: stage.width() / 2, + y: stage.height() / 2, radius: 70, fill: 'green', stroke: 'black', @@ -2823,14 +2833,14 @@ suite('Node', function () { }); // ====================================================== - test('destroy layer with shape', function () { + it('destroy layer with shape', function () { var stage = addStage(); var layer = new Konva.Layer({ name: 'myLayer', }); var circle = new Konva.Circle({ - x: stage.getWidth() / 2, - y: stage.getHeight() / 2, + x: stage.width() / 2, + y: stage.height() / 2, radius: 70, fill: 'green', stroke: 'black', @@ -2855,14 +2865,14 @@ suite('Node', function () { }); // ====================================================== - test('destroy stage with layer and shape', function () { + it('destroy stage with layer and shape', function () { var stage = addStage(); var layer = new Konva.Layer({ name: 'myLayer', }); var circle = new Konva.Circle({ - x: stage.getWidth() / 2, - y: stage.getHeight() / 2, + x: stage.width() / 2, + y: stage.height() / 2, radius: 70, fill: 'green', stroke: 'black', @@ -2882,7 +2892,7 @@ suite('Node', function () { }); // ====================================================== - test('destroy group with shape', function () { + it('destroy group with shape', function () { var stage = addStage(); var layer = new Konva.Layer({ name: 'myLayer', @@ -2892,8 +2902,8 @@ suite('Node', function () { }); var circle = new Konva.Circle({ - x: stage.getWidth() / 2, - y: stage.getHeight() / 2, + x: stage.width() / 2, + y: stage.height() / 2, radius: 70, fill: 'green', stroke: 'black', @@ -2919,7 +2929,7 @@ suite('Node', function () { }); // ====================================================== - test('destroy layer with no shapes', function () { + it('destroy layer with no shapes', function () { var stage = addStage(); var layer = new Konva.Layer(); stage.add(layer); @@ -2929,7 +2939,7 @@ suite('Node', function () { }); // ====================================================== - test('destroy shape multiple times', function () { + it('destroy shape multiple times', function () { var stage = addStage(); var layer = new Konva.Layer(); var shape1 = new Konva.Circle({ @@ -2963,7 +2973,7 @@ suite('Node', function () { }); // ====================================================== - test('remove layer multiple times', function () { + it('remove layer multiple times', function () { var stage = addStage(); var layer1 = new Konva.Layer(); var layer2 = new Konva.Layer(); @@ -3000,12 +3010,12 @@ suite('Node', function () { }); // ====================================================== - test('destroy shape by id or name', function () { + it('destroy shape by id or name', function () { var stage = addStage(); var layer = new Konva.Layer(); var circle = new Konva.Circle({ - x: stage.getWidth() / 2, - y: stage.getHeight() / 2, + x: stage.width() / 2, + y: stage.height() / 2, radius: 70, fill: 'green', stroke: 'black', @@ -3052,12 +3062,12 @@ suite('Node', function () { }); // ====================================================== - test('destroy should remove only required shape from ids regestry', function () { + it('destroy should remove only required shape from ids regestry', function () { var stage = addStage(); var layer = new Konva.Layer(); var circle = new Konva.Circle({ - x: stage.getWidth() / 2, - y: stage.getHeight() / 2, + x: stage.width() / 2, + y: stage.height() / 2, radius: 70, fill: 'green', stroke: 'black', @@ -3090,7 +3100,7 @@ suite('Node', function () { }); // ====================================================== - test('hide stage', function () { + it('hide stage', function () { var stage = addStage({ visible: false, }); @@ -3130,7 +3140,7 @@ suite('Node', function () { }); // ====================================================== - test('listening, & shouldDrawHit', function () { + it('listening, & shouldDrawHit', function () { var stage = addStage(); var layer = new Konva.Layer(); @@ -3150,14 +3160,14 @@ suite('Node', function () { assert.equal(rect.isListening(), true); assert.equal(rect.shouldDrawHit(), true); - rect.setListening(false); + rect.listening(false); assert.equal(rect.isListening(), false); assert.equal(rect.shouldDrawHit(), false); }); // ====================================================== - test('group, listening, & shouldDrawHit', function () { + it('group, listening, & shouldDrawHit', function () { var stage = addStage(); var layer = new Konva.Layer({ @@ -3208,11 +3218,11 @@ suite('Node', function () { }); showHit(layer); - stage.simulateMouseDown({ + simulateMouseDown(stage, { x: 150, y: 75, }); - stage.simulateMouseUp({ + simulateMouseUp(stage, { x: 150, y: 75, }); @@ -3223,7 +3233,7 @@ suite('Node', function () { }); // ====================================================== - test('isVisible', function () { + it('isVisible', function () { var stage = addStage(); var layer = new Konva.Layer(); var group = new Konva.Group(); @@ -3246,49 +3256,49 @@ suite('Node', function () { assert.equal(layer.isVisible(), true); assert.equal(circle.isVisible(), true); - stage.setVisible(false); + stage.visible(false); assert.equal(stage.isVisible(), false); assert.equal(layer.isVisible(), false); assert.equal(circle.isVisible(), false); - stage.setVisible(true); - layer.setVisible(false); + stage.visible(true); + layer.visible(false); assert.equal(stage.isVisible(), true); assert.equal(layer.isVisible(), false); assert.equal(circle.isVisible(), false); - layer.setVisible(true); - circle.setVisible(false); + layer.visible(true); + circle.visible(false); assert.equal(stage.isVisible(), true); assert.equal(layer.isVisible(), true); assert.equal(circle.isVisible(), false); - circle.setVisible(true); - stage.setVisible(true); + circle.visible(true); + stage.visible(true); assert.equal(stage.isVisible(), true); assert.equal(layer.isVisible(), true); assert.equal(circle.isVisible(), true); - stage.setVisible(true); - layer.setVisible(true); + stage.visible(true); + layer.visible(true); assert.equal(stage.isVisible(), true); assert.equal(layer.isVisible(), true); assert.equal(circle.isVisible(), true); - layer.setVisible(true); - circle.setVisible(true); + layer.visible(true); + circle.visible(true); assert.equal(stage.isVisible(), true); assert.equal(layer.isVisible(), true); assert.equal(circle.isVisible(), true); }); - test('overloaders', function () { + it('overloaders', function () { var stage = addStage(); var layer = new Konva.Layer(); var group = new Konva.Group(); @@ -3380,7 +3390,7 @@ suite('Node', function () { assert.equal(circle.size().height, 11); }); - test('cache shape', function () { + it('cache shape', function () { var stage = addStage(); var layer = new Konva.Layer(); var group = new Konva.Group(); @@ -3428,7 +3438,7 @@ suite('Node', function () { //assert.equal(circle._getCanvasCache().scene.getContext().getTrace(), 'save();translate(74,74);beginPath();arc(0,0,70,0,6.283,false);closePath();fillStyle=green;fill();lineWidth=4;strokeStyle=black;stroke();restore();'); }); - test('cache shape before adding to layer', function () { + it('cache shape before adding to layer', function () { var stage = addStage(); var layer = new Konva.Layer(); var group = new Konva.Group({ @@ -3478,13 +3488,12 @@ suite('Node', function () { assert.equal(shape, rect, 'rect found'); }); - test('stage.toObject() when stage contains an image', function (done) { - var imageObj = new Image(); - imageObj.onload = function () { + it('stage.toObject() when stage contains an image', function (done) { + loadImage('darth-vader.jpg', (imageObj) => { var stage = addStage(); var layer = new Konva.Layer(); - darth = new Konva.Image({ + const darth = new Konva.Image({ x: 200, y: 60, image: imageObj, @@ -3501,31 +3510,30 @@ suite('Node', function () { assert.equal(stage.toObject().className, 'Stage'); done(); - }; - imageObj.src = 'assets/darth-vader.jpg'; + }); }); - test('toObject with extended prototypes', function () { + it('toObject with extended prototypes', function () { var node = new Konva.Circle({ id: 'foo', radius: 10, }); - Number.prototype.customFunc = function () {}; + Number.prototype['customFunc'] = function () {}; assert.equal(node.toObject().attrs.radius, 10); - delete Number.prototype.customFunc; + delete Number.prototype['customFunc']; }); - test('toObject with property in attrs and instanse', function () { + it('toObject with property in attrs and instanse', function () { var node = new Konva.Circle({ id: 'foo1', radius: 10, filled: true, }); - node.filled = true; + node['filled'] = true; assert.equal(node.toObject().attrs.filled, true); }); - test('test findAncestor', function () { + it('test findAncestor', function () { var stage = addStage(); stage.setAttrs({ name: 'stage', @@ -3580,7 +3588,7 @@ suite('Node', function () { assert.equal(rect.findAncestor(), null, 'return null if no selector'); }); - test('moveToTop() properly changes z-indices of the node and its siblings', function () { + it('moveToTop() properly changes z-indices of the node and its siblings', function () { var stage = addStage(); var layer = new Konva.Layer(); stage.add(layer); @@ -3611,7 +3619,7 @@ suite('Node', function () { assert.equal(rect1.getZIndex(), 3); }); - test('moveToBottom() properly changes z-indices of the node and its siblings', function () { + it('moveToBottom() properly changes z-indices of the node and its siblings', function () { var stage = addStage(); var layer = new Konva.Layer(); stage.add(layer); @@ -3642,7 +3650,7 @@ suite('Node', function () { assert.equal(rect2.getZIndex(), 3); }); - test('moveUp() properly changes z-indices of the node and its siblings', function () { + it('moveUp() properly changes z-indices of the node and its siblings', function () { var stage = addStage(); var layer = new Konva.Layer(); stage.add(layer); @@ -3673,7 +3681,7 @@ suite('Node', function () { assert.equal(rect3.getZIndex(), 3); }); - test('moveDown() properly changes z-indices of the node and its siblings', function () { + it('moveDown() properly changes z-indices of the node and its siblings', function () { var stage = addStage(); var layer = new Konva.Layer(); stage.add(layer); @@ -3704,7 +3712,7 @@ suite('Node', function () { assert.equal(rect3.getZIndex(), 3); }); - test('setZIndex() properly changes z-indices of the node and its siblings', function () { + it('setZIndex() properly changes z-indices of the node and its siblings', function () { var stage = addStage(); var layer = new Konva.Layer(); stage.add(layer); @@ -3749,7 +3757,7 @@ suite('Node', function () { assert.equal(rect1.getZIndex(), 3); }); - test('remove() removes the node and properly changes z-indices of its siblings', function () { + it('remove() removes the node and properly changes z-indices of its siblings', function () { var stage = addStage(); var layer = new Konva.Layer(); stage.add(layer); @@ -3785,7 +3793,7 @@ suite('Node', function () { assert.equal(rect3.getZIndex(), 0); }); - test('show warning when we are trying to use non-objects for component setters', function () { + it('show warning when we are trying to use non-objects for component setters', function () { var stage = addStage(); var callCount = 0; @@ -3794,12 +3802,12 @@ suite('Node', function () { callCount += 1; }; - stage.scale(0.5); + stage.scale(1 as any); assert.equal(callCount, 1); Konva.Util.warn = oldWarn; }); - test('show warning for unexpected zIndexes', function () { + it('show warning for unexpected zIndexes', function () { var stage = addStage(); var layer = new Konva.Layer(); @@ -3825,7 +3833,7 @@ suite('Node', function () { Konva.Util.warn = oldWarn; }); - test('check transform caching', function () { + it('check transform caching', function () { var stage = addStage(); var layer = new Konva.Layer(); diff --git a/test/unit/Shape-test.js b/test/unit-new/Shape-test.ts similarity index 81% rename from test/unit/Shape-test.js rename to test/unit-new/Shape-test.ts index 13660083..81364131 100644 --- a/test/unit/Shape-test.js +++ b/test/unit-new/Shape-test.ts @@ -1,6 +1,22 @@ -suite('Shape', function () { +import { assert } from 'chai'; + +import { + addStage, + simulateMouseDown, + simulateMouseMove, + simulateMouseUp, + createCanvas, + isBrowser, + isNode, + compareLayerAndCanvas, + compareLayers, + loadImage, + Konva, +} from './utis'; + +describe('Shape', function () { // ====================================================== - test('test intersects()', function () { + it('test intersects()', function () { var stage = addStage(); var layer = new Konva.Layer(); var rect = new Konva.Rect({ @@ -63,7 +79,7 @@ suite('Shape', function () { }); // ====================================================== - test('test hasShadow() method', function () { + it('test hasShadow() method', function () { var stage = addStage(); var layer = new Konva.Layer(); var shape = new Konva.Shape({ @@ -94,7 +110,7 @@ suite('Shape', function () { 'shape should not have a shadow because opacity is 0' ); - shape.setShadowOpacity(0.5); + shape.shadowOpacity(0.5); assert.equal( shape.hasShadow(), @@ -102,7 +118,7 @@ suite('Shape', function () { 'shape should have a shadow because opacity is nonzero' ); - shape.setShadowEnabled(false); + shape.shadowEnabled(false); assert.equal( shape.hasShadow(), @@ -112,7 +128,7 @@ suite('Shape', function () { }); // ====================================================== - test('custom shape with fill, stroke, and strokeWidth', function () { + it('custom shape with fill, stroke, and strokeWidth', function () { var stage = addStage(); var layer = new Konva.Layer(); var shape = new Konva.Shape({ @@ -143,9 +159,8 @@ suite('Shape', function () { }); // ====================================================== - test('add star with translated, scaled, rotated fill', function (done) { - var imageObj = new Image(); - imageObj.onload = function () { + it('add star with translated, scaled, rotated fill', function (done) { + loadImage('darth-vader.jpg', (imageObj) => { var stage = addStage(); var layer = new Konva.Layer(); @@ -179,88 +194,87 @@ suite('Shape', function () { anim.start(); */ - assert.equal(star.getFillPatternX(), -20, 'star fill x should be -20'); - assert.equal(star.getFillPatternY(), -30, 'star fill y should be -30'); + assert.equal(star.fillPatternX(), -20, 'star fill x should be -20'); + assert.equal(star.fillPatternY(), -30, 'star fill y should be -30'); assert.equal( - star.getFillPatternScale().x, + star.fillPatternScale().x, 0.5, 'star fill scale x should be 0.5' ); assert.equal( - star.getFillPatternScale().y, + star.fillPatternScale().y, 0.5, 'star fill scale y should be 0.5' ); assert.equal( - star.getFillPatternOffset().x, + star.fillPatternOffset().x, 219, 'star fill offset x should be 219' ); assert.equal( - star.getFillPatternOffset().y, + star.fillPatternOffset().y, 150, 'star fill offset y should be 150' ); assert.equal( - star.getFillPatternRotation(), + star.fillPatternRotation(), 90, 'star fill rotation should be 90' ); - star.setFillPatternRotation(180); + star.fillPatternRotation(180); assert.equal( - star.getFillPatternRotation(), + star.fillPatternRotation(), 180, 'star fill rotation should be 180' ); - star.setFillPatternScale({ x: 1, y: 1 }); + star.fillPatternScale({ x: 1, y: 1 }); assert.equal( - star.getFillPatternScale().x, + star.fillPatternScale().x, 1, 'star fill scale x should be 1' ); assert.equal( - star.getFillPatternScale().y, + star.fillPatternScale().y, 1, 'star fill scale y should be 1' ); - star.setFillPatternOffset({ x: 100, y: 120 }); + star.fillPatternOffset({ x: 100, y: 120 }); assert.equal( - star.getFillPatternOffset().x, + star.fillPatternOffset().x, 100, 'star fill offset x should be 100' ); assert.equal( - star.getFillPatternOffset().y, + star.fillPatternOffset().y, 120, 'star fill offset y should be 120' ); done(); - }; - imageObj.src = 'assets/darth-vader.jpg'; + }); }); // ====================================================== - test('test size setters and getters', function () { + it('test size setters and getters', function () { var stage = addStage(); var layer = new Konva.Layer(); var circle = new Konva.Circle({ - x: stage.getWidth() / 2, - y: stage.getHeight() / 2, + x: stage.width() / 2, + y: stage.height() / 2, radius: 50, fill: 'red', }); var ellipse = new Konva.Circle({ - x: stage.getWidth() / 2, - y: stage.getHeight() / 2, + x: stage.width() / 2, + y: stage.height() / 2, radius: 50, fill: 'yellow', }); @@ -270,25 +284,24 @@ suite('Shape', function () { stage.add(layer); // circle tests - assert.equal(circle.getWidth(), 100, 'circle width should be 100'); - assert.equal(circle.getHeight(), 100, 'circle height should be 100'); + assert.equal(circle.width(), 100, 'circle width should be 100'); + assert.equal(circle.height(), 100, 'circle height should be 100'); assert.equal(circle.getSize().width, 100, 'circle width should be 100'); assert.equal(circle.getSize().height, 100, 'circle height should be 100'); - assert.equal(circle.getRadius(), 50, 'circle radius should be 50'); + assert.equal(circle.radius(), 50, 'circle radius should be 50'); circle.setWidth(200); - assert.equal(circle.getWidth(), 200, 'circle width should be 200'); - assert.equal(circle.getHeight(), 200, 'circle height should be 200'); + assert.equal(circle.width(), 200, 'circle width should be 200'); + assert.equal(circle.height(), 200, 'circle height should be 200'); assert.equal(circle.getSize().width, 200, 'circle width should be 200'); assert.equal(circle.getSize().height, 200, 'circle height should be 200'); - assert.equal(circle.getRadius(), 100, 'circle radius should be 100'); + assert.equal(circle.radius(), 100, 'circle radius should be 100'); }); // ====================================================== - test('set image fill to color then image then linear gradient then back to image', function (done) { - var imageObj = new Image(); - imageObj.onload = function () { + it('set image fill to color then image then linear gradient then back to image', function (done) { + loadImage('darth-vader.jpg', (imageObj) => { var stage = addStage(); var layer = new Konva.Layer(); var circle = new Konva.Circle({ @@ -301,52 +314,51 @@ suite('Shape', function () { layer.add(circle); stage.add(layer); - assert.equal(circle.getFill(), 'blue', 'circle fill should be blue'); + assert.equal(circle.fill(), 'blue', 'circle fill should be blue'); - circle.setFill(null); - circle.setFillPatternImage(imageObj); - circle.setFillPatternRepeat('no-repeat'); - circle.setFillPatternOffset({ x: -200, y: -70 }); + circle.fill(null); + circle.fillPatternImage(imageObj); + circle.fillPatternRepeat('no-repeat'); + circle.fillPatternOffset({ x: -200, y: -70 }); assert.notEqual( - circle.getFillPatternImage(), + circle.fillPatternImage(), undefined, 'circle fill image should be defined' ); assert.equal( - circle.getFillPatternRepeat(), + circle.fillPatternRepeat(), 'no-repeat', 'circle fill repeat should be no-repeat' ); assert.equal( - circle.getFillPatternOffset().x, + circle.fillPatternOffset().x, -200, 'circle fill offset x should be -200' ); assert.equal( - circle.getFillPatternOffset().y, + circle.fillPatternOffset().y, -70, 'circle fill offset y should be -70' ); - circle.setFillPatternImage(null); - circle.setFillLinearGradientStartPoint({ x: -35, y: -35 }); - circle.setFillLinearGradientEndPoint({ x: 35, y: 35 }); - circle.setFillLinearGradientColorStops([0, 'red', 1, 'blue']); + circle.fillPatternImage(null); + circle.fillLinearGradientStartPoint({ x: -35, y: -35 }); + circle.fillLinearGradientEndPoint({ x: 35, y: 35 }); + circle.fillLinearGradientColorStops([0, 'red', 1, 'blue']); - circle.setFillLinearGradientStartPoint({ x: 0, y: 0 }); - circle.setFillPatternImage(imageObj); - circle.setFillPatternRepeat('repeat'); - circle.setFillPatternOffset({ x: 0, y: 0 }); + circle.fillLinearGradientStartPoint({ x: 0, y: 0 }); + circle.fillPatternImage(imageObj); + circle.fillPatternRepeat('repeat'); + circle.fillPatternOffset({ x: 0, y: 0 }); layer.draw(); done(); - }; - imageObj.src = 'assets/darth-vader.jpg'; + }); }); - test('stroke gradient', function () { + it('stroke gradient', function () { var stage = addStage(); var layer = new Konva.Layer({ scaleY: 1.5, @@ -380,21 +392,26 @@ suite('Shape', function () { layer.add(shape); stage.add(layer); - var trace = layer.getContext().getTrace(); - - assert.equal( - trace, - 'clearRect(0,0,578,200);save();transform(3,0,0,1.5,10,15);beginPath();rect(0,0,100,100);closePath();fillStyle=[object CanvasGradient];fill();lineWidth=2;createLinearGradient(0,0,100,100);strokeStyle=[object CanvasGradient];stroke();restore();' - ); + if (isNode) { + assert.equal( + layer.getContext().getTrace(true), + 'clearRect();save();transform();beginPath();rect();closePath();fillStyle;fill();lineWidth;createLinearGradient();strokeStyle;stroke();restore();' + ); + } else { + assert.equal( + layer.getContext().getTrace(), + 'clearRect(0,0,578,200);save();transform(3,0,0,1.5,10,15);beginPath();rect(0,0,100,100);closePath();fillStyle=[object CanvasGradient];fill();lineWidth=2;createLinearGradient(0,0,100,100);strokeStyle=[object CanvasGradient];stroke();restore();' + ); + } }); // ====================================================== - test('test enablers and disablers', function () { + it('test enablers and disablers', function () { var stage = addStage(); var layer = new Konva.Layer(); var circle = new Konva.Circle({ - x: stage.getWidth() / 2, - y: stage.getHeight() / 2, + x: stage.width() / 2, + y: stage.height() / 2, radius: 70, fill: 'green', stroke: 'black', @@ -408,39 +425,31 @@ suite('Shape', function () { layer.add(circle); stage.add(layer); - assert.equal(circle.getStrokeScaleEnabled(), true); - assert.equal(circle.getFillEnabled(), true, 'fillEnabled should be true'); - assert.equal( - circle.getStrokeEnabled(), - true, - 'strokeEnabled should be true' - ); - assert.equal( - circle.getShadowEnabled(), - true, - 'shadowEnabled should be true' - ); + assert.equal(circle.strokeScaleEnabled(), true); + assert.equal(circle.fillEnabled(), true, 'fillEnabled should be true'); + assert.equal(circle.strokeEnabled(), true, 'strokeEnabled should be true'); + assert.equal(circle.shadowEnabled(), true, 'shadowEnabled should be true'); assert.equal(circle.dashEnabled(), true, 'dashEnabled should be true'); circle.strokeScaleEnabled(false); - assert.equal(circle.getStrokeScaleEnabled(), false); + assert.equal(circle.strokeScaleEnabled(), false); layer.draw(); // var trace = layer.getContext().getTrace(); circle.fillEnabled(false); - assert.equal(circle.getFillEnabled(), false, 'fillEnabled should be false'); + assert.equal(circle.fillEnabled(), false, 'fillEnabled should be false'); circle.strokeEnabled(false); assert.equal( - circle.getStrokeEnabled(), + circle.strokeEnabled(), false, 'strokeEnabled should be false' ); circle.shadowEnabled(false); assert.equal( - circle.getShadowEnabled(), + circle.shadowEnabled(), false, 'shadowEnabled should be false' ); @@ -451,28 +460,20 @@ suite('Shape', function () { // re-enable circle.dashEnabled(true); - assert.equal(circle.getDashEnabled(), true, 'dashEnabled should be true'); + assert.equal(circle.dashEnabled(), true, 'dashEnabled should be true'); circle.shadowEnabled(true); - assert.equal( - circle.getShadowEnabled(), - true, - 'shadowEnabled should be true' - ); + assert.equal(circle.shadowEnabled(), true, 'shadowEnabled should be true'); circle.strokeEnabled(true); - assert.equal( - circle.getStrokeEnabled(), - true, - 'strokeEnabled should be true' - ); + assert.equal(circle.strokeEnabled(), true, 'strokeEnabled should be true'); circle.fillEnabled(true); - assert.equal(circle.getFillEnabled(), true, 'fillEnabled should be true'); + assert.equal(circle.fillEnabled(), true, 'fillEnabled should be true'); }); // ====================================================== - test('fill with shadow and opacity', function () { + it('fill with shadow and opacity', function () { var stage = addStage(); var layer = new Konva.Layer(); @@ -493,8 +494,8 @@ suite('Shape', function () { layer.add(rect); stage.add(layer); - assert.equal(rect.getX(), 100); - assert.equal(rect.getY(), 50); + assert.equal(rect.x(), 100); + assert.equal(rect.y(), 50); var canvas = createCanvas(); var context = canvas.getContext('2d'); @@ -506,9 +507,9 @@ suite('Shape', function () { context.fillStyle = 'green'; context.shadowColor = 'rgba(0,0,0,0.5)'; - context.shadowBlur = 10 * canvas.ratio; - context.shadowOffsetX = 10 * canvas.ratio; - context.shadowOffsetY = 10 * canvas.ratio; + context.shadowBlur = 10 * Konva.pixelRatio; + context.shadowOffsetX = 10 * Konva.pixelRatio; + context.shadowOffsetY = 10 * Konva.pixelRatio; context.fill(); compareLayerAndCanvas(layer, canvas, 30); @@ -522,7 +523,7 @@ suite('Shape', function () { }); // ====================================================== - test('draw fill after stroke', function () { + it('draw fill after stroke', function () { var stage = addStage(); var layer = new Konva.Layer(); @@ -550,7 +551,7 @@ suite('Shape', function () { }); // ====================================================== - test('test strokeWidth = 0', function () { + it('test strokeWidth = 0', function () { var stage = addStage(); var layer = new Konva.Layer(); @@ -587,7 +588,7 @@ suite('Shape', function () { }); // ====================================================== - test('stroke with shadow and opacity', function () { + it('stroke with shadow and opacity', function () { Konva.pixelRatio = 1; var stage = addStage(); @@ -610,8 +611,8 @@ suite('Shape', function () { layer.add(rect); stage.add(layer); - assert.equal(rect.getX(), 100); - assert.equal(rect.getY(), 50); + assert.equal(rect.x(), 100); + assert.equal(rect.y(), 50); var canvas = createCanvas(); var context = canvas.getContext('2d'); @@ -625,9 +626,9 @@ suite('Shape', function () { context.lineWidth = 20; context.shadowColor = 'rgba(0,0,0,0.5)'; - context.shadowBlur = 10 * canvas.ratio; - context.shadowOffsetX = 10 * canvas.ratio; - context.shadowOffsetY = 10 * canvas.ratio; + context.shadowBlur = 10 * Konva.pixelRatio; + context.shadowOffsetX = 10 * Konva.pixelRatio; + context.shadowOffsetY = 10 * Konva.pixelRatio; context.stroke(); compareLayerAndCanvas(layer, canvas, 10); @@ -641,7 +642,7 @@ suite('Shape', function () { }); // ====================================================== - test('fill and stroke with opacity', function () { + it('fill and stroke with opacity', function () { var stage = addStage(); var layer = new Konva.Layer(); @@ -683,7 +684,7 @@ suite('Shape', function () { }); // ====================================================== - test('fill and stroke with shadow', function () { + it('fill and stroke with shadow', function () { var stage = addStage(); var layer = new Konva.Layer(); @@ -721,24 +722,32 @@ suite('Shape', function () { var c2 = createCanvas(); var ctx2 = c2.getContext('2d'); ctx2.shadowColor = 'grey'; - ctx2.shadowBlur = 10 * canvas.ratio; - ctx2.shadowOffsetX = 20 * canvas.ratio; - ctx2.shadowOffsetY = 20 * canvas.ratio; + ctx2.shadowBlur = 10 * Konva.pixelRatio; + ctx2.shadowOffsetX = 20 * Konva.pixelRatio; + ctx2.shadowOffsetY = 20 * Konva.pixelRatio; ctx2.drawImage(canvas, 0, 0, canvas.width / 2, canvas.height / 2); // compareLayerAndCanvas(layer, c2, 50); - var trace = layer.getContext().getTrace(); - assert.equal( - trace, - 'clearRect(0,0,578,200);save();shadowColor=rgba(128,128,128,1);shadowBlur=10;shadowOffsetX=20;shadowOffsetY=20;drawImage([object HTMLCanvasElement],0,0,578,200);restore();' - ); + if (isBrowser) { + var trace = layer.getContext().getTrace(); + assert.equal( + trace, + 'clearRect(0,0,578,200);save();shadowColor=rgba(128,128,128,1);shadowBlur=10;shadowOffsetX=20;shadowOffsetY=20;drawImage([object HTMLCanvasElement],0,0,578,200);restore();' + ); + } else { + var trace = layer.getContext().getTrace(true); + assert.equal( + trace, + 'clearRect();save();shadowColor;shadowBlur;shadowOffsetX;shadowOffsetY;drawImage();restore();' + ); + } }); // ====================================================== // hard to emulate the same drawing - test('fill and stroke with shadow and opacity', function () { + it('fill and stroke with shadow and opacity', function () { var stage = addStage(); var layer = new Konva.Layer(); @@ -772,9 +781,9 @@ suite('Shape', function () { context.rect(95, 45, 110, 60); context.closePath(); context.shadowColor = 'grey'; - context.shadowBlur = 5 * canvas.ratio; - context.shadowOffsetX = 20 * canvas.ratio; - context.shadowOffsetY = 20 * canvas.ratio; + context.shadowBlur = 5 * Konva.pixelRatio; + context.shadowOffsetX = 20 * Konva.pixelRatio; + context.shadowOffsetY = 20 * Konva.pixelRatio; context.fillStyle = 'black'; context.fill(); context.restore(); @@ -802,15 +811,23 @@ suite('Shape', function () { compareLayerAndCanvas(layer, canvas, 260); - var trace = layer.getContext().getTrace(); - assert.equal( - trace, - 'clearRect(0,0,578,200);save();shadowColor=rgba(128,128,128,1);shadowBlur=5;shadowOffsetX=20;shadowOffsetY=20;globalAlpha=0.5;drawImage([object HTMLCanvasElement],0,0,578,200);restore();' - ); + if (isBrowser) { + var trace = layer.getContext().getTrace(); + assert.equal( + trace, + 'clearRect(0,0,578,200);save();shadowColor=rgba(128,128,128,1);shadowBlur=5;shadowOffsetX=20;shadowOffsetY=20;globalAlpha=0.5;drawImage([object HTMLCanvasElement],0,0,578,200);restore();' + ); + } else { + var trace = layer.getContext().getTrace(true); + assert.equal( + trace, + 'clearRect();save();shadowColor;shadowBlur;shadowOffsetX;shadowOffsetY;globalAlpha;drawImage();restore();' + ); + } }); // ====================================================== - test('text with fill and stroke with shadow', function () { + it('text with fill and stroke with shadow', function () { var stage = addStage(); var layer = new Konva.Layer(); @@ -839,9 +856,9 @@ suite('Shape', function () { context.save(); context.shadowColor = 'black'; - context.shadowBlur = 2 * canvas.ratio; - context.shadowOffsetX = 20 * canvas.ratio; - context.shadowOffsetY = 20 * canvas.ratio; + context.shadowBlur = 2 * Konva.pixelRatio; + context.shadowOffsetX = 20 * Konva.pixelRatio; + context.shadowOffsetY = 20 * Konva.pixelRatio; context.font = 'normal 50px Arial'; context.textBaseline = 'middle'; @@ -871,7 +888,7 @@ suite('Shape', function () { }); // ====================================================== - test('shape intersect with shadow', function () { + it('shape intersect with shadow', function () { var stage = addStage(); var layer = new Konva.Layer(); @@ -894,7 +911,7 @@ suite('Shape', function () { }); // ====================================================== - test('shape intersect while dragging', function () { + it('shape intersect while dragging', function () { var stage = addStage(); var layer = new Konva.Layer(); @@ -911,16 +928,16 @@ suite('Shape', function () { layer.add(rect); stage.add(layer); - stage.simulateMouseDown({ x: 55, y: 55 }); - stage.simulateMouseMove({ x: 65, y: 65 }); + simulateMouseDown(stage, { x: 55, y: 55 }); + simulateMouseMove(stage, { x: 65, y: 65 }); //error here assert.equal(rect.intersects({ x: 65, y: 65 }), true); - stage.simulateMouseUp({ x: 65, y: 65 }); + simulateMouseUp(stage, { x: 65, y: 65 }); }); // ====================================================== - test('overloaded getters and setters', function () { + it('overloaded getters and setters', function () { var stage = addStage(); var layer = new Konva.Layer(); @@ -951,11 +968,12 @@ suite('Shape', function () { rect.strokeWidth(8); assert.equal(rect.strokeWidth(), 8); - rect.sceneFunc('function'); - assert.equal(rect.sceneFunc(), 'function'); + const f = () => {}; + rect.sceneFunc(f); + assert.equal(rect.sceneFunc(), f); - rect.hitFunc('function'); - assert.equal(rect.hitFunc(), 'function'); + rect.hitFunc(f); + assert.equal(rect.hitFunc(), f); rect.dash([1]); assert.equal(rect.dash()[0], 1); @@ -965,13 +983,10 @@ suite('Shape', function () { }); // ====================================================== - test('create image hit region', function (done) { - var imageObj = new Image(); - - var stage = addStage(); - var layer = new Konva.Layer(); - - imageObj.onload = function () { + it('create image hit region', function (done) { + loadImage('lion.png', (imageObj) => { + var stage = addStage(); + var layer = new Konva.Layer(); var lion = new Konva.Image({ x: 0, y: 0, @@ -1002,11 +1017,10 @@ suite('Shape', function () { assert.equal(layer.getIntersection({ x: 10, y: 10 }), null); assert.equal(layer.getIntersection({ x: 50, y: 50 }), lion); done(); - }; - imageObj.src = 'assets/lion.png'; + }); }); - test('test defaults', function () { + it('test defaults', function () { var shape = new Konva.Shape(); assert.equal(shape.strokeWidth(), 2); @@ -1040,7 +1054,7 @@ suite('Shape', function () { }); // ====================================================== - test('hit graph when shape cached before adding to Layer', function () { + it('hit graph when shape cached before adding to Layer', function () { var stage = addStage(); var layer = new Konva.Layer(); var rect = new Konva.Rect({ @@ -1061,16 +1075,12 @@ suite('Shape', function () { layer.add(rect); stage.add(layer); - var top = stage.content.getBoundingClientRect().top; - - showHit(layer); - - stage.simulateMouseDown({ + simulateMouseDown(stage, { x: 300, y: 120, }); - stage.simulateMouseUp({ + simulateMouseUp(stage, { x: 300, y: 120, }); @@ -1082,14 +1092,14 @@ suite('Shape', function () { ); }); - test('class inherence', function () { + it('class inherence', function () { var rect = new Konva.Rect(); assert.equal(rect instanceof Konva.Rect, true); assert.equal(rect instanceof Konva.Shape, true); assert.equal(rect instanceof Konva.Node, true); }); - test('disable stroke for hit', function () { + it('disable stroke for hit', function () { var stage = addStage(); var layer = new Konva.Layer(); @@ -1112,7 +1122,7 @@ suite('Shape', function () { layer.add(rect); stage.add(layer); - assert.equal(rect.getY(), 50); + assert.equal(rect.y(), 50); var trace = layer.getHitCanvas().getContext().getTrace(true); assert.equal( @@ -1121,7 +1131,7 @@ suite('Shape', function () { ); }); - test.skip('hitStrokeWidth', function () { + it.skip('hitStrokeWidth', function () { var stage = addStage(); var layer = new Konva.Layer(); @@ -1171,7 +1181,7 @@ suite('Shape', function () { // ); }); - test('enable hitStrokeWidth even if we have no stroke on scene', function () { + it('enable hitStrokeWidth even if we have no stroke on scene', function () { var stage = addStage(); var layer = new Konva.Layer(); @@ -1195,7 +1205,7 @@ suite('Shape', function () { assert.equal(stage.getIntersection({ x: 5, y: 5 }), rect); }); - test('cache shadow color rgba', function () { + it('cache shadow color rgba', function () { var circle = new Konva.Circle({ fill: 'green', radius: 50, @@ -1221,7 +1231,7 @@ suite('Shape', function () { assert.equal(circle.getShadowRGBA(), undefined); }); - test('scale should also effect shadow offset', function () { + it('scale should also effect shadow offset', function () { var stage = addStage(); var layer = new Konva.Layer(); @@ -1252,8 +1262,8 @@ suite('Shape', function () { context.fillStyle = 'green'; context.shadowColor = 'rgba(0,0,0,1)'; context.shadowBlur = 0; - context.shadowOffsetX = 5 * canvas.ratio; - context.shadowOffsetY = 5 * canvas.ratio; + context.shadowOffsetX = 5 * Konva.pixelRatio; + context.shadowOffsetY = 5 * Konva.pixelRatio; context.fill(); compareLayerAndCanvas(layer, canvas, 10); @@ -1267,7 +1277,7 @@ suite('Shape', function () { }); // TODO: restore it! - test.skip('scale should also effect shadow offset - negative scale', function () { + it.skip('scale should also effect shadow offset - negative scale', function () { var stage = addStage(); var layer = new Konva.Layer(); @@ -1298,8 +1308,8 @@ suite('Shape', function () { context.fillStyle = 'green'; context.shadowColor = 'rgba(0,0,0,1)'; context.shadowBlur = 10; - context.shadowOffsetX = -5 * canvas.ratio; - context.shadowOffsetY = 5 * canvas.ratio; + context.shadowOffsetX = -5 * Konva.pixelRatio; + context.shadowOffsetY = 5 * Konva.pixelRatio; context.fill(); compareLayerAndCanvas(layer, canvas, 150); @@ -1312,7 +1322,7 @@ suite('Shape', function () { // ); }); - test('scale of parent container should also effect shadow offset', function () { + it('scale of parent container should also effect shadow offset', function () { var stage = addStage(); var layer = new Konva.Layer(); @@ -1347,8 +1357,8 @@ suite('Shape', function () { context.fillStyle = 'green'; context.shadowColor = 'rgba(0,0,0,1)'; context.shadowBlur = 0; - context.shadowOffsetX = 5 * canvas.ratio; - context.shadowOffsetY = 5 * canvas.ratio; + context.shadowOffsetX = 5 * Konva.pixelRatio; + context.shadowOffsetY = 5 * Konva.pixelRatio; context.fill(); compareLayerAndCanvas(layer, canvas, 10); @@ -1361,7 +1371,7 @@ suite('Shape', function () { ); }); - test('optional disable buffer canvas', function () { + it('optional disable buffer canvas', function () { var stage = addStage(); var layer = new Konva.Layer(); @@ -1405,7 +1415,7 @@ suite('Shape', function () { ); }); - test('check lineJoin in buffer canvas', function () { + it('check lineJoin in buffer canvas', function () { var stage = addStage(); var layer = new Konva.Layer(); @@ -1447,16 +1457,25 @@ suite('Shape', function () { compareLayerAndCanvas(layer, canvas2, 150); - var trace = layer.getContext().getTrace(); + if (isBrowser) { + var trace = layer.getContext().getTrace(); - assert.equal( - trace, - 'clearRect(0,0,578,200);save();globalAlpha=0.5;drawImage([object HTMLCanvasElement],0,0,578,200);restore();' - ); + assert.equal( + trace, + 'clearRect(0,0,578,200);save();globalAlpha=0.5;drawImage([object HTMLCanvasElement],0,0,578,200);restore();' + ); + } else { + var trace = layer.getContext().getTrace(true); + + assert.equal( + trace, + 'clearRect();save();globalAlpha;drawImage();restore();' + ); + } }); // ====================================================== - test('optional disable shadow for stroke', function () { + it('optional disable shadow for stroke', function () { var stage = addStage(); var layer = new Konva.Layer(); @@ -1488,9 +1507,9 @@ suite('Shape', function () { context.closePath(); context.fillStyle = 'green'; context.shadowColor = 'grey'; - context.shadowBlur = 10 * canvas.ratio; - context.shadowOffsetX = 20 * canvas.ratio; - context.shadowOffsetY = 20 * canvas.ratio; + context.shadowBlur = 10 * Konva.pixelRatio; + context.shadowOffsetX = 20 * Konva.pixelRatio; + context.shadowOffsetY = 20 * Konva.pixelRatio; context.lineWidth = 10; context.fill(); @@ -1506,16 +1525,20 @@ suite('Shape', function () { ); }); - test('clone custom shape', function () { + it('clone custom shape', function () { var className = 'myCustomName'; - var CustomShape = function () { - CustomShape.super.apply(this, arguments); - this.className = className; - }; + class CustomShape extends Konva.Shape { + foo() {} + } + CustomShape.prototype.className = className; + // var CustomShape = function () { + // CustomShape.super.apply(this, arguments); + // this.className = className; + // }; - CustomShape.prototype.foo = function () {}; + // CustomShape.prototype.foo = function () {}; - Konva.Util.extend(CustomShape, Konva.Shape); + // Konva.Util.extend(CustomShape, Konva.Shape); var myShape = new CustomShape({ fill: 'grey', @@ -1529,7 +1552,7 @@ suite('Shape', function () { assert.equal(clone.foo, CustomShape.prototype.foo); }); - test('getClientRect should skip disabled attributes', function () { + it('getClientRect should skip disabled attributes', function () { var stage = addStage(); var layer = new Konva.Layer(); var shape = new Konva.Rect({ @@ -1554,7 +1577,7 @@ suite('Shape', function () { assert.equal(rect.height, 100, 'should not effect width'); }); - test('getClientRect for shape in transformed parent', function () { + it('getClientRect for shape in transformed parent', function () { var stage = addStage(); var layer = new Konva.Layer(); stage.add(layer); @@ -1590,7 +1613,7 @@ suite('Shape', function () { assert.equal(absRect.height, 100); }); - test('getClientRect with skew', function () { + it('getClientRect with skew', function () { var stage = addStage(); var layer = new Konva.Layer(); stage.add(layer); @@ -1621,7 +1644,7 @@ suite('Shape', function () { assert.equal(absRect.height, 100); }); - test('decompose transform', function () { + it('decompose transform', function () { var stage = addStage(); var layer = new Konva.Layer(); stage.add(layer); @@ -1651,7 +1674,7 @@ suite('Shape', function () { assert.equal(shape.getTransform().decompose().scaleY, 2); }); - test('shadow should respect pixel ratio', function () { + it('shadow should respect pixel ratio', function () { var stage = addStage(); var layer = new Konva.Layer(); layer.getCanvas().setPixelRatio(2); @@ -1671,7 +1694,7 @@ suite('Shape', function () { assert.equal(data.data[3], 0, 'pixel should be empty, no shadow here'); }); - test('text shadow blur should take scale into account', function () { + it('text shadow blur should take scale into account', function () { var stage = addStage(); var layer1 = new Konva.Layer(); stage.add(layer1); @@ -1713,7 +1736,7 @@ suite('Shape', function () { }); // ====================================================== - test('sceneFunc and hitFunc should have shape as second argument', function () { + it('sceneFunc and hitFunc should have shape as second argument', function () { var stage = addStage(); var layer = new Konva.Layer(); var shape = new Konva.Shape({ @@ -1744,9 +1767,8 @@ suite('Shape', function () { }); // ====================================================== - test('cache fill pattern', function (done) { - var imageObj = new Image(); - imageObj.onload = function () { + it('cache fill pattern', function (done) { + loadImage('darth-vader.jpg', (imageObj) => { var stage = addStage(); var layer = new Konva.Layer(); @@ -1786,13 +1808,11 @@ suite('Shape', function () { layer.draw(); assert.equal(callCount, 0); done(); - }; - imageObj.src = 'assets/darth-vader.jpg'; + }); }); - test('recache fill pattern on changes', function (done) { - var imageObj = new Image(); - imageObj.onload = function () { + it('recache fill pattern on changes', function (done) { + loadImage('darth-vader.jpg', (imageObj) => { var stage = addStage(); var layer = new Konva.Layer(); @@ -1821,7 +1841,7 @@ suite('Shape', function () { var pattern1 = star._getFillPattern(); - star.fillPatternImage(document.createElement('canvas')); + star.fillPatternImage(Konva.Util.createCanvasElement()); var pattern2 = star._getFillPattern(); @@ -1834,12 +1854,11 @@ suite('Shape', function () { assert.notEqual(pattern2, pattern3); done(); - }; - imageObj.src = 'assets/darth-vader.jpg'; + }); }); // ====================================================== - test('cache linear gradient', function () { + it('cache linear gradient', function () { var stage = addStage(); var layer = new Konva.Layer(); @@ -1876,7 +1895,7 @@ suite('Shape', function () { assert.equal(callCount, 0); }); - test('recache linear gradient on changes', function () { + it('recache linear gradient on changes', function () { var stage = addStage(); var layer = new Konva.Layer(); @@ -1935,7 +1954,7 @@ suite('Shape', function () { }); // ====================================================== - test('cache radial gradient', function () { + it('cache radial gradient', function () { var stage = addStage(); var layer = new Konva.Layer(); @@ -1974,7 +1993,7 @@ suite('Shape', function () { assert.equal(callCount, 0); }); - test('recache linear gradient on changes', function () { + it('recache linear gradient on changes', function () { var stage = addStage(); var layer = new Konva.Layer(); @@ -2046,7 +2065,7 @@ suite('Shape', function () { layer.draw(); }); - test('try to add destroyed shape', function () { + it('try to add destroyed shape', function () { var stage = addStage(); var layer = new Konva.Layer(); stage.add(layer); @@ -2079,7 +2098,7 @@ suite('Shape', function () { Konva.Util.warn = oldWarn; }); - test('hasFill getter', function () { + it('hasFill getter', function () { var stage = addStage(); var layer = new Konva.Layer(); stage.add(layer); @@ -2101,7 +2120,7 @@ suite('Shape', function () { assert.equal(shape.hasFill(), false); }); - test('test hit of non filled shape', function () { + it('test hit of non filled shape', function () { var stage = addStage(); var layer = new Konva.Layer(); stage.add(layer); @@ -2126,7 +2145,7 @@ suite('Shape', function () { assert.equal(shape, line); }); - test('validation on stroke should accept gradients', function () { + it('validation on stroke should accept gradients', function () { var callCount = 0; var oldWarn = Konva.Util.warn; Konva.Util.warn = function () { @@ -2137,7 +2156,7 @@ suite('Shape', function () { var layer = new Konva.Layer(); stage.add(layer); - var canvas = document.createElement('canvas'); + var canvas = createCanvas(); var ctx = canvas.getContext('2d'); var gradient = ctx.createLinearGradient(0, 75, 100, 75); diff --git a/test/unit/Stage-test.js b/test/unit-new/Stage-test.ts similarity index 84% rename from test/unit/Stage-test.js rename to test/unit-new/Stage-test.ts index 084a73a8..7a1545a1 100644 --- a/test/unit/Stage-test.js +++ b/test/unit-new/Stage-test.ts @@ -1,10 +1,31 @@ -suite('Stage', function () { +import { assert } from 'chai'; + +import { + addStage, + simulateMouseDown, + simulateMouseMove, + simulateMouseUp, + simulateTouchStart, + simulateTouchMove, + simulateTouchEnd, + compareCanvases, + createCanvas, + showHit, + getContainer, + isNode, + isBrowser, + Konva, +} from './utis'; + +describe('Stage', function () { // ====================================================== - test('instantiate stage with id', function () { + it('instantiate stage with id', function () { + if (isNode) { + return; + } var container = Konva.document.createElement('div'); container.id = 'container'; - - konvaContainer.appendChild(container); + getContainer().appendChild(container); var stage = new Konva.Stage({ container: 'container', @@ -17,11 +38,14 @@ suite('Stage', function () { }); // ====================================================== - test('test stage buffer canvas and hit buffer canvas', function () { + it('test stage buffer canvas and hit buffer canvas', function () { + if (isNode) { + return; + } var container = Konva.document.createElement('div'); container.id = 'container'; - konvaContainer.appendChild(container); + getContainer().appendChild(container); // simulate pixelRatio = 2 Konva.pixelRatio = 2; @@ -40,10 +64,13 @@ suite('Stage', function () { }); // ====================================================== - test('instantiate stage with dom element', function () { + it('instantiate stage with dom element', function () { + if (isNode) { + return; + } var container = Konva.document.createElement('div'); - konvaContainer.appendChild(container); + getContainer().appendChild(container); var stage = new Konva.Stage({ container: container, @@ -55,12 +82,15 @@ suite('Stage', function () { }); // ====================================================== - test('stage instantiation should clear container', function () { + it('stage instantiation should clear container', function () { + if (isNode) { + return; + } var container = Konva.document.createElement('div'); var dummy = Konva.document.createElement('p'); container.appendChild(dummy); - konvaContainer.appendChild(container); + getContainer().appendChild(container); var stage = new Konva.Stage({ container: container, @@ -76,34 +106,37 @@ suite('Stage', function () { }); // ====================================================== - test('test stage cloning', function () { + it('test stage cloning', function () { + if (isNode) { + return; + } var stage = addStage(); var layer = new Konva.Layer(); stage.add(layer); var stageClone = stage.clone(); assert.notEqual( - stage.getContainer(), - stageClone.getContainer(), + stage.container(), + stageClone.container(), 'clone should be in different container' ); assert.equal( - stage.getContainer().childNodes[0].childNodes.length, + stage.container().childNodes[0].childNodes.length, 1, 'container should not have changes' ); }); // ====================================================== - test('set stage size', function () { + it('set stage size', function () { var stage = addStage(); var layer = new Konva.Layer(); var circle = new Konva.Circle({ - x: stage.getWidth() / 2, - y: stage.getHeight() / 2, + x: stage.width() / 2, + y: stage.height() / 2, radius: 70, fill: 'green', stroke: 'black', @@ -125,10 +158,10 @@ suite('Stage', function () { }); assert.equal(stage.getSize().width, 4); assert.equal(stage.getSize().height, 5); - stage.setWidth(6); + stage.width(6); assert.equal(stage.getSize().width, 6); assert.equal(stage.getSize().height, 5); - stage.setHeight(7); + stage.height(7); assert.equal(stage.getSize().width, 6); assert.equal(stage.getSize().height, 7); stage.setSize({ width: 8, height: 9 }); @@ -145,8 +178,11 @@ suite('Stage', function () { assert.equal(stage.getSize().width, 333); assert.equal(stage.getSize().height, 155); - assert.equal(stage.getContent().style.width, '333px'); - assert.equal(stage.getContent().style.height, '155px'); + if (isBrowser) { + assert.equal(stage.getContent().style.width, '333px'); + assert.equal(stage.getContent().style.height, '155px'); + } + assert.equal( layer.getCanvas()._canvas.width, 333 * layer.getCanvas().getPixelRatio() @@ -158,13 +194,19 @@ suite('Stage', function () { }); // ====================================================== - test('get stage DOM', function () { + it('get stage DOM', function () { + if (isNode) { + return; + } var stage = addStage(); assert.equal(stage.getContent().className, 'konvajs-content'); }); - test('try to move stage ', function () { + it('try to move stage ', function () { + if (isNode) { + return; + } var stage = addStage(); var container = document.createElement('div'); var wrap = stage.container().parentNode; @@ -177,7 +219,10 @@ suite('Stage', function () { assert.equal(stage.content, container.children[0]); }); - test('clone stage ', function () { + it('clone stage ', function () { + if (isNode) { + return; + } var stage = addStage(); var layer = new Konva.Layer(); stage.add(layer); @@ -205,7 +250,10 @@ suite('Stage', function () { assert.equal(clone.content, container.children[0]); }); - test('dangling stage ', function () { + it('dangling stage ', function () { + if (isNode) { + return; + } var stage = addStage(); var container = stage.container(); var parent = stage.content.parentElement; @@ -218,13 +266,13 @@ suite('Stage', function () { }); // ====================================================== - test('stage getIntersection()', function () { + it('stage getIntersection()', function () { var stage = addStage(); var layer = new Konva.Layer(); var redCircle = new Konva.Circle({ x: 380, - y: stage.getHeight() / 2, + y: stage.height() / 2, radius: 70, strokeWidth: 4, fill: 'red', @@ -233,7 +281,7 @@ suite('Stage', function () { var greenCircle = new Konva.Circle({ x: 300, - y: stage.getHeight() / 2, + y: stage.height() / 2, radius: 70, strokeWidth: 4, fill: 'green', @@ -262,7 +310,7 @@ suite('Stage', function () { }); // ====================================================== - test('layer getIntersection() with selector', function () { + it('layer getIntersection() with selector', function () { var stage = addStage(); var layer = new Konva.Layer({ name: 'layer', @@ -273,8 +321,8 @@ suite('Stage', function () { }); var circle = new Konva.Circle({ - x: stage.getWidth() / 2, - y: stage.getHeight() / 2, + x: stage.width() / 2, + y: stage.height() / 2, radius: 70, strokeWidth: 4, fill: 'red', @@ -312,13 +360,13 @@ suite('Stage', function () { }); // ====================================================== - test('stage getIntersection() edge detection', function () { + it('stage getIntersection() edge detection', function () { var stage = addStage(); var layer = new Konva.Layer(); var redCircle = new Konva.Circle({ x: 380, - y: stage.getHeight() / 2, + y: stage.height() / 2, radius: 70, strokeWidth: 4, fill: 'red', @@ -327,7 +375,7 @@ suite('Stage', function () { var greenCircle = new Konva.Circle({ x: 300, - y: stage.getHeight() / 2, + y: stage.height() / 2, radius: 70, strokeWidth: 4, fill: 'green', @@ -364,13 +412,13 @@ suite('Stage', function () { }); // ====================================================== - test('test getAllIntersections', function () { + it('test getAllIntersections', function () { var stage = addStage(); var layer = new Konva.Layer(); var redCircle = new Konva.Circle({ x: 380, - y: stage.getHeight() / 2, + y: stage.height() / 2, radius: 70, strokeWidth: 4, fill: 'red', @@ -380,7 +428,7 @@ suite('Stage', function () { var greenCircle = new Konva.Circle({ x: 300, - y: stage.getHeight() / 2, + y: stage.height() / 2, radius: 70, strokeWidth: 4, fill: 'green', @@ -526,7 +574,7 @@ suite('Stage', function () { }); // ====================================================== - test('test getAllIntersections for text', function () { + it('test getAllIntersections for text', function () { var stage = addStage(); var layer = new Konva.Layer(); @@ -550,7 +598,7 @@ suite('Stage', function () { }); // ====================================================== - test('Should not throw on clip for stage', function () { + it('Should not throw on clip for stage', function () { // no asserts, because we check throw var stage = addStage({ clipFunc: function () {}, @@ -570,12 +618,12 @@ suite('Stage', function () { }); // ====================================================== - test('scale stage after add layer', function () { + it('scale stage after add layer', function () { var stage = addStage(); var layer = new Konva.Layer(); var circle = new Konva.Circle({ - x: stage.getWidth() / 2, - y: stage.getHeight() / 2, + x: stage.width() / 2, + y: stage.height() / 2, radius: 70, fill: 'green', stroke: 'black', @@ -585,42 +633,43 @@ suite('Stage', function () { layer.add(circle); stage.add(layer); - stage.setScale({ x: 0.5, y: 0.5 }); + stage.scale({ x: 0.5, y: 0.5 }); - assert.equal(stage.getScale().x, 0.5, 'stage scale x should be 0.5'); - assert.equal(stage.getScale().y, 0.5, 'stage scale y should be 0.5'); + assert.equal(stage.scale().x, 0.5, 'stage scale x should be 0.5'); + assert.equal(stage.scale().y, 0.5, 'stage scale y should be 0.5'); stage.draw(); }); // ====================================================== - test('scale stage before add shape', function () { + it('scale stage before add shape', function () { var stage = addStage(); var layer = new Konva.Layer(); var circle = new Konva.Circle({ - x: stage.getWidth() / 2, - y: stage.getHeight() / 2, + x: stage.width() / 2, + y: stage.height() / 2, radius: 70, fill: 'green', stroke: 'black', strokeWidth: 4, }); - stage.setScale({ x: 0.5, y: 0.5 }); + stage.scale({ x: 0.5, y: 0.5 }); - assert.equal(stage.getScale().x, 0.5, 'stage scale x should be 0.5'); - assert.equal(stage.getScale().y, 0.5, 'stage scale y should be 0.5'); + assert.equal(stage.scale().x, 0.5, 'stage scale x should be 0.5'); + assert.equal(stage.scale().y, 0.5, 'stage scale y should be 0.5'); layer.add(circle); stage.add(layer); }); // ====================================================== - test('remove stage', function () { + // TODO: restore it, remove should deatach from DOM + it.skip('remove stage', function () { var stage = addStage(); var layer = new Konva.Layer(); var circle = new Konva.Circle({ - x: stage.getWidth() / 2, - y: stage.getHeight() / 2, + x: stage.width() / 2, + y: stage.height() / 2, radius: 70, fill: 'green', stroke: 'black', @@ -632,16 +681,13 @@ suite('Stage', function () { // remove should have no effect, and should cause no JS error stage.remove(); + + assert.equal(stage.content.parentNode, undefined); }); // ====================================================== - test('destroy stage', function () { - var container = Konva.document.createElement('div'); - - konvaContainer.appendChild(container); - - var stage = new Konva.Stage({ - container: container, + it('destroy stage', function () { + var stage = addStage({ width: 578, height: 200, id: 'stageFalconId', @@ -650,8 +696,8 @@ suite('Stage', function () { var layer = new Konva.Layer(); var circle = new Konva.Circle({ - x: stage.getWidth() / 2, - y: stage.getHeight() / 2, + x: stage.width() / 2, + y: stage.height() / 2, radius: 70, fill: 'green', stroke: 'black', @@ -714,19 +760,21 @@ suite('Stage', function () { }); // ====================================================== - test('scale stage with no shapes', function () { + it('scale stage with no shapes', function () { var stage = addStage(); var layer = new Konva.Layer(); stage.add(layer); - stage.setScaleX(0.5); + stage.scaleX(0.5); stage.draw(); + + assert.equal(stage.scaleX(), 0.5); }); // ====================================================== - test('test stage.getStage()', function () { + it('test stage.getStage()', function () { var stage = addStage(); assert.notEqual(stage.getStage(), undefined); @@ -734,7 +782,7 @@ suite('Stage', function () { //console.log(stage.getStage()); }); - test('add multiple layers to stage', function () { + it('add multiple layers to stage', function () { var stage = addStage(); var layer1 = new Konva.Layer(); var layer2 = new Konva.Layer(); @@ -743,7 +791,7 @@ suite('Stage', function () { assert.equal(stage.getLayers().length, 3, 'stage has exactly three layers'); }); // ====================================================== - test('test drag and click', function () { + it('test drag and click', function () { var stage = addStage(); var layer = new Konva.Layer(); var rect = new Konva.Rect({ @@ -765,32 +813,32 @@ suite('Stage', function () { var y = 60; // simulate dragging - stage.simulateMouseDown({ + simulateMouseDown(stage, { x: 60, y: y, }); - stage.simulateMouseMove({ + simulateMouseMove(stage, { x: 61, y: y, }); - stage.simulateMouseMove({ + simulateMouseMove(stage, { x: 62, y: y, }); - stage.simulateMouseMove({ + simulateMouseMove(stage, { x: 63, y: y, }); - stage.simulateMouseMove({ + simulateMouseMove(stage, { x: 64, y: y, }); - stage.simulateMouseUp({ + simulateMouseUp(stage, { x: 65, y: y, }); @@ -798,12 +846,12 @@ suite('Stage', function () { assert.equal(Konva.isDragging(), false); assert.equal(Konva.DD.node, undefined); // simulate click - stage.simulateMouseDown({ + simulateMouseDown(stage, { x: 66, y: y, }); - stage.simulateMouseUp({ + simulateMouseUp(stage, { x: 66, y: y, }); @@ -812,7 +860,7 @@ suite('Stage', function () { }); // ====================================================== - test('do not trigger stage click after dragend', function () { + it('do not trigger stage click after dragend', function () { var stage = addStage(); var layer = new Konva.Layer(); var rect = new Konva.Rect({ @@ -834,12 +882,12 @@ suite('Stage', function () { }); // simulate dragging - stage.simulateMouseDown({ + simulateMouseDown(stage, { x: 25, y: 25, }); - stage.simulateMouseMove({ + simulateMouseMove(stage, { x: 100, y: 100, }); @@ -848,7 +896,7 @@ suite('Stage', function () { rect.x(-30); rect.y(-30); - stage.simulateMouseUp({ + simulateMouseUp(stage, { x: 100, y: 100, }); @@ -856,7 +904,7 @@ suite('Stage', function () { assert.equal(clicks, 0); }); - test('can listen click on empty areas', function () { + it('can listen click on empty areas', function () { var stage = addStage(); var layer = new Konva.Layer(); stage.add(layer); @@ -898,17 +946,17 @@ suite('Stage', function () { }); // simulate dragging - stage.simulateMouseDown({ + simulateMouseDown(stage, { x: 60, y: 10, }); - stage.simulateMouseMove({ + simulateMouseMove(stage, { x: 60, y: 10, }); - stage.simulateMouseUp({ + simulateMouseUp(stage, { x: 65, y: 10, }); @@ -919,12 +967,12 @@ suite('Stage', function () { assert.equal(mousemoves, 1, 'first mousemove registered'); assert.equal(dblicks, 0, 'no dbclicks registered'); - stage.simulateMouseDown({ + simulateMouseDown(stage, { x: 60, y: 10, }); - stage.simulateMouseUp({ + simulateMouseUp(stage, { x: 65, y: 10, }); @@ -935,7 +983,7 @@ suite('Stage', function () { assert.equal(dblicks, 1, 'first dbclick registered'); }); - test('can listen taps on empty areas', function () { + it('can listen taps on empty areas', function () { var stage = addStage(); var layer = new Konva.Layer(); stage.add(layer); @@ -977,11 +1025,11 @@ suite('Stage', function () { }); // simulate dragging - stage.simulateTouchStart([{ x: 100, y: 100, id: 1 }]); + simulateTouchStart(stage, [{ x: 100, y: 100, id: 1 }]); - stage.simulateTouchMove([{ x: 100, y: 100, id: 1 }]); + simulateTouchMove(stage, [{ x: 100, y: 100, id: 1 }]); - stage.simulateTouchEnd([], [{ x: 100, y: 100, id: 1 }]); + simulateTouchEnd(stage, [], [{ x: 100, y: 100, id: 1 }]); assert.equal(touchstarts, 1, 'first touchstart registered'); assert.equal(touchends, 1, 'first touchends registered'); @@ -989,9 +1037,9 @@ suite('Stage', function () { assert.equal(touchmoves, 1, 'first touchmove registered'); assert.equal(dbltaps, 0, 'no dbltap registered'); - stage.simulateTouchStart([{ x: 100, y: 100, id: 1 }]); + simulateTouchStart(stage, [{ x: 100, y: 100, id: 1 }]); - stage.simulateTouchEnd([], [{ x: 100, y: 100, id: 1 }]); + simulateTouchEnd(stage, [], [{ x: 100, y: 100, id: 1 }]); assert.equal(touchstarts, 2, 'first touchstart registered'); assert.equal(touchends, 2, 'first touchends registered'); @@ -999,7 +1047,7 @@ suite('Stage', function () { assert.equal(dbltaps, 1, 'dbltap registered'); }); - test('pass context and wheel events to shape', function () { + it('pass context and wheel events to shape', function () { var stage = addStage(); var layer = new Konva.Layer(); stage.add(layer); @@ -1030,7 +1078,7 @@ suite('Stage', function () { assert.equal(e.currentTarget, stage); }); - var top = stage.content.getBoundingClientRect().top; + var top = stage.content ? stage.content.getBoundingClientRect().top : 0; stage._contextmenu({ clientX: 0, clientY: top + 0, @@ -1071,7 +1119,7 @@ suite('Stage', function () { assert.equal(wheels, 2, 'second wheel registered'); }); - test('make sure it does not trigger too many events', function () { + it('make sure it does not trigger too many events', function () { var stage = addStage(); var layer = new Konva.Layer(); stage.add(layer); @@ -1112,12 +1160,12 @@ suite('Stage', function () { }); // simulate dragging - stage.simulateMouseDown({ + simulateMouseDown(stage, { x: 60, y: 10, }); - stage.simulateMouseUp({ + simulateMouseUp(stage, { x: 65, y: 10, }); @@ -1127,12 +1175,12 @@ suite('Stage', function () { assert.equal(clicks, 1, 'first click registered'); assert.equal(dblicks, 0, 'no dbclicks registered'); - stage.simulateMouseDown({ + simulateMouseDown(stage, { x: 60, y: 10, }); - stage.simulateMouseUp({ + simulateMouseUp(stage, { x: 65, y: 10, }); @@ -1143,7 +1191,7 @@ suite('Stage', function () { assert.equal(dblicks, 1, 'first dbclick registered'); }); - test('test mouseover event on stage', function () { + it('test mouseover event on stage', function () { var stage = addStage(); var layer = new Konva.Layer(); stage.add(layer); @@ -1189,21 +1237,21 @@ suite('Stage', function () { }); assert.equal(mouseover, 1, 'initial over'); - stage.simulateMouseMove({ + simulateMouseMove(stage, { x: 10, y: 10, }); assert.equal(mouseover, 1, 'moved inside stage - no new over events'); - stage.simulateMouseMove({ + simulateMouseMove(stage, { x: 60, y: 60, }); assert.equal(mouseover, 2, 'moved into inner shape, trigger new mouseover'); - stage.simulateMouseMove({ + simulateMouseMove(stage, { x: 110, y: 110, }); @@ -1214,7 +1262,7 @@ suite('Stage', function () { 'moved into second shape, trigger new mouseover' ); - stage.simulateMouseMove({ + simulateMouseMove(stage, { x: 10, y: 10, }); @@ -1226,7 +1274,7 @@ suite('Stage', function () { ); }); - test('toCanvas in sync way', function () { + it('toCanvas in sync way', function () { var stage = addStage(); var layer = new Konva.Layer(); var circle = new Konva.Circle({ @@ -1241,7 +1289,7 @@ suite('Stage', function () { compareCanvases(stage.toCanvas(), layer.toCanvas(), 200); }); - test('listen to mouseleave event on container', function () { + it('listen to mouseleave event on container', function () { var stage = addStage(); var layer = new Konva.Layer(); var circle = new Konva.Circle({ @@ -1264,7 +1312,7 @@ suite('Stage', function () { assert.equal(count, 2); }); - test('toDataURL with hidden layer', function () { + it('toDataURL with hidden layer', function () { var stage = addStage(); var layer = new Konva.Layer(); var circle = new Konva.Circle({ @@ -1281,7 +1329,7 @@ suite('Stage', function () { assert.equal(stage.toDataURL() === stageDataUrl, false); }); - test('toDataURL works as toCanvas', function () { + it('toDataURL works as toCanvas', function () { var stage = addStage(); var layer = new Konva.Layer(); var circle = new Konva.Circle({ @@ -1296,7 +1344,7 @@ suite('Stage', function () { assert.equal(stage.toDataURL(), stage.toCanvas().toDataURL()); }); - test('toDataURL should no relate on stage size', function () { + it('toDataURL should no relate on stage size', function () { var stage = addStage(); var layer = new Konva.Layer(); var circle = new Konva.Circle({ @@ -1311,7 +1359,7 @@ suite('Stage', function () { compareCanvases(stage.toCanvas(circle.getClientRect()), circle.toCanvas()); }); - test('toCanvas with large size', function () { + it('toCanvas with large size', function () { var stage = addStage(); var layer = new Konva.Layer(); @@ -1343,7 +1391,7 @@ suite('Stage', function () { compareCanvases(stageCanvas, canvas, 100); }); - test('check hit graph with stage listening property', function () { + it('check hit graph with stage listening property', function () { var stage = addStage(); var layer = new Konva.Layer(); stage.add(layer); @@ -1375,11 +1423,11 @@ suite('Stage', function () { assert.equal(stage.getIntersection(pos), circle, 'circle again'); }); - test('toDataURL should use pixelRatio 1 by default', function (done) { + it('toDataURL should use pixelRatio 1 by default', function (done) { var stage = addStage(); var url = stage.toDataURL(); - var image = new window.Image(); + var image = Konva.Util.createImageElement(); image.onload = function () { assert.equal(image.width, stage.width()); assert.equal(image.height, stage.height()); @@ -1388,7 +1436,7 @@ suite('Stage', function () { image.src = url; }); - test('show a warning if the stage has too many layers', function () { + it('show a warning if the stage has too many layers', function () { var stage = addStage(); var oldWarn = Konva.Util.warn; var called = false; diff --git a/test/unit/Tween-test.js b/test/unit-new/Tween-test.ts similarity index 56% rename from test/unit/Tween-test.js rename to test/unit-new/Tween-test.ts index 61f51d97..1854a883 100644 --- a/test/unit/Tween-test.js +++ b/test/unit-new/Tween-test.ts @@ -1,13 +1,17 @@ -suite('Tween', function () { +import { assert } from 'chai'; + +import { addStage, Konva } from './utis'; + +describe('Tween', function () { // ====================================================== - test('tween node', function (done) { + it('tween node', function (done) { var stage = addStage(); var layer = new Konva.Layer(); var circle = new Konva.Circle({ x: 100, - y: stage.getHeight() / 2, + y: stage.height() / 2, radius: 70, fill: 'green', stroke: 'blue', @@ -61,14 +65,14 @@ suite('Tween', function () { }); // ====================================================== - test('destroy tween while tweening', function () { + it('destroy tween while tweening', function () { var stage = addStage(); var layer = new Konva.Layer(); var circle = new Konva.Circle({ x: 100, - y: stage.getHeight() / 2, + y: stage.height() / 2, radius: 70, fill: 'green', stroke: 'blue', @@ -99,14 +103,14 @@ suite('Tween', function () { }); // ====================================================== - test('zero duration', function (done) { + it('zero duration', function (done) { var stage = addStage(); var layer = new Konva.Layer(); var circle = new Konva.Circle({ x: 100, - y: stage.getHeight() / 2, + y: stage.height() / 2, radius: 70, fill: 'green', stroke: 'blue', @@ -131,14 +135,14 @@ suite('Tween', function () { }, 60); }); - test('color tweening', function (done) { + it('color tweening', function (done) { var stage = addStage(); var layer = new Konva.Layer(); var circle = new Konva.Circle({ x: 100, - y: stage.getHeight() / 2, + y: stage.height() / 2, radius: 70, fill: 'red', stroke: 'blue', @@ -170,14 +174,14 @@ suite('Tween', function () { tween.play(); }); - test('gradient tweening', function (done) { + it('gradient tweening', function (done) { var stage = addStage(); var layer = new Konva.Layer(); var circle = new Konva.Circle({ x: 100, - y: stage.getHeight() / 2, + y: stage.height() / 2, radius: 70, fillLinearGradientStartPoint: { x: -50, y: -50 }, fillLinearGradientEndPoint: { x: 50, y: 50 }, @@ -213,7 +217,7 @@ suite('Tween', function () { tween.play(); }); - test('to method', function (done) { + it('to method', function (done) { var stage = addStage(); var layer = new Konva.Layer(); @@ -230,7 +234,7 @@ suite('Tween', function () { circle.to({ x: stage.width() / 2, - y: stage.getHeight() / 2, + y: stage.height() / 2, duration: 0.1, onFinish: function () { assert.equal(circle.x(), stage.width() / 2); @@ -240,168 +244,167 @@ suite('Tween', function () { }); }); - test('to method simple usage', function (done) { + it('to method simple usage', function (done) { var stage = addStage(); stage.to({ x: 10, duration: 0.001, - }); - setTimeout(function () { - done(); - }, 50); - }); - - test('tween to call update callback', function (done) { - var stage = addStage(); - var updateCount = 0; - - stage.to({ - x: 10, - duration: 0.01, - onUpdate: function () { - updateCount++; - }, - onFinish: function () { - assert(updateCount === 3, 'updateCount should equal 3'); + onFinish: () => { + assert(stage.x() === 10); done(); }, }); }); - suite('tween array with different length', function () { - test('prepare array closed', function () { - var start = [0, 0, 10, 0, 10, 10]; - var end = [0, 0, 10, 0, 10, 10, 0, 10]; - var newStart = Konva.Util._prepareArrayForTween(start, end, true); - assert.deepEqual(newStart, [0, 0, 10, 0, 10, 10, 5, 5]); - }); + it('tween to call update callback', function (done) { + var stage = addStage(); + var updateCount = 0; - test('prepare array - opened', function () { - var start = [0, 0, 10, 0, 10, 10, 0, 10]; - var end = [0, 0, 10, 0, 7, 9]; - end = Konva.Util._prepareArrayForTween(start, end, false); - assert.deepEqual(end, [0, 0, 10, 0, 7, 9, 7, 9]); - }); - - test('tween array with bigger size', function (done) { - var stage = addStage(); - - var layer = new Konva.Layer(); - stage.add(layer); - - var line = new Konva.Line({ - stroke: 'black', - points: [100, 100, 200, 100, 200, 200], - closed: true, - }); - layer.add(line); - - line.to({ - points: [100, 100, 200, 100, 200, 200, 100, 200], - duration: 0.1, - onFinish: function () { - assert.deepEqual(line.points(), [ - 100, - 100, - 200, - 100, - 200, - 200, - 100, - 200, - ]); - done(); - }, - }); - }); - - test('tween array to lower size', function (done) { - var stage = addStage(); - - var layer = new Konva.Layer(); - stage.add(layer); - - var line = new Konva.Line({ - stroke: 'black', - points: [100, 100, 200, 100, 200, 200, 100, 200], - closed: true, - }); - layer.add(line); - - line.to({ - points: [100, 100, 200, 100, 200, 200], - duration: 0.1, - onFinish: function () { - assert.deepEqual(line.points(), [100, 100, 200, 100, 200, 200]); - done(); - }, - }); - }); - - test('tween array to lower size and go back', function (done) { - var stage = addStage(); - - var layer = new Konva.Layer(); - stage.add(layer); - - var line = new Konva.Line({ - stroke: 'black', - points: [100, 100, 200, 100, 200, 200, 100, 200], - closed: true, - }); - layer.add(line); - - var tween = new Konva.Tween({ - node: line, - points: [100, 100, 200, 100, 200, 200], - duration: 0.01, - onFinish: function () { - tween.reverse(); - }, - onReset: function () { - assert.deepEqual(line.points(), [ - 100, - 100, - 200, - 100, - 200, - 200, - 100, - 200, - ]); - done(); - }, - }); - tween.play(); - }); - - test('tween array to bigger size and go back', function (done) { - var stage = addStage(); - - var layer = new Konva.Layer(); - stage.add(layer); - - var line = new Konva.Line({ - stroke: 'black', - points: [100, 100, 200, 100, 200, 200], - closed: true, - }); - layer.add(line); - - var tween = new Konva.Tween({ - node: line, - points: [100, 100, 200, 100, 200, 200, 100, 200], - duration: 0.01, - onFinish: function () { - tween.reverse(); - }, - onReset: function () { - assert.deepEqual(line.points(), [100, 100, 200, 100, 200, 200]); - done(); - }, - }); - tween.play(); + stage.to({ + x: 10, + duration: 0.1, + onUpdate: function () { + updateCount++; + }, + onFinish: function () { + assert(updateCount > 2); + done(); + }, }); }); + + it('prepare array closed', function () { + var start = [0, 0, 10, 0, 10, 10]; + var end = [0, 0, 10, 0, 10, 10, 0, 10]; + var newStart = Konva.Util._prepareArrayForTween(start, end, true); + assert.deepEqual(newStart, [0, 0, 10, 0, 10, 10, 5, 5]); + }); + + it('prepare array - opened', function () { + var start = [0, 0, 10, 0, 10, 10, 0, 10]; + var end = [0, 0, 10, 0, 7, 9]; + end = Konva.Util._prepareArrayForTween(start, end, false); + assert.deepEqual(end, [0, 0, 10, 0, 7, 9, 7, 9]); + }); + + it('tween array with bigger size', function (done) { + var stage = addStage(); + + var layer = new Konva.Layer(); + stage.add(layer); + + var line = new Konva.Line({ + stroke: 'black', + points: [100, 100, 200, 100, 200, 200], + closed: true, + }); + layer.add(line); + + line.to({ + points: [100, 100, 200, 100, 200, 200, 100, 200], + duration: 0.1, + onFinish: function () { + assert.deepEqual(line.points(), [ + 100, + 100, + 200, + 100, + 200, + 200, + 100, + 200, + ]); + done(); + }, + }); + }); + + it('tween array to lower size', function (done) { + var stage = addStage(); + + var layer = new Konva.Layer(); + stage.add(layer); + + var line = new Konva.Line({ + stroke: 'black', + points: [100, 100, 200, 100, 200, 200, 100, 200], + closed: true, + }); + layer.add(line); + + line.to({ + points: [100, 100, 200, 100, 200, 200], + duration: 0.1, + onFinish: function () { + assert.deepEqual(line.points(), [100, 100, 200, 100, 200, 200]); + done(); + }, + }); + }); + + it('tween array to lower size and go back', function (done) { + var stage = addStage(); + + var layer = new Konva.Layer(); + stage.add(layer); + + var line = new Konva.Line({ + stroke: 'black', + points: [100, 100, 200, 100, 200, 200, 100, 200], + closed: true, + }); + layer.add(line); + + var tween = new Konva.Tween({ + node: line, + points: [100, 100, 200, 100, 200, 200], + duration: 0.01, + onFinish: function () { + tween.reverse(); + }, + onReset: function () { + assert.deepEqual(line.points(), [ + 100, + 100, + 200, + 100, + 200, + 200, + 100, + 200, + ]); + done(); + }, + }); + tween.play(); + }); + + it('tween array to bigger size and go back', function (done) { + var stage = addStage(); + + var layer = new Konva.Layer(); + stage.add(layer); + + var line = new Konva.Line({ + stroke: 'black', + points: [100, 100, 200, 100, 200, 200], + closed: true, + }); + layer.add(line); + + var tween = new Konva.Tween({ + node: line, + points: [100, 100, 200, 100, 200, 200, 100, 200], + duration: 0.01, + onFinish: function () { + tween.reverse(); + }, + onReset: function () { + assert.deepEqual(line.points(), [100, 100, 200, 100, 200, 200]); + done(); + }, + }); + tween.play(); + }); }); diff --git a/test/unit/Util-test.js b/test/unit-new/Util-test.ts similarity index 69% rename from test/unit/Util-test.js rename to test/unit-new/Util-test.ts index 098be7d1..a8f0a89d 100644 --- a/test/unit/Util-test.js +++ b/test/unit-new/Util-test.ts @@ -1,19 +1,22 @@ -suite('Util', function () { - test('get()', function () { +import { assert } from 'chai'; +import { Konva } from './utis'; + +describe('Util', function () { + it('get()', function () { assert.equal(Konva.Util.get(1, 2), 1); assert.equal(Konva.Util.get(undefined, 2), 2); assert.equal(Konva.Util.get(undefined, { foo: 'bar' }).foo, 'bar'); }); - test('test _prepareToStringify', function () { - var o = { + it('test _prepareToStringify', function () { + var o: any = { a: 1, b: 'string1', }; o.c = { d: 'string2', e: o, - f: document.createElement('p'), + f: global.document ? global.document.createElement('p') : { nodeType: 1 }, }; o.g = o; @@ -26,7 +29,7 @@ suite('Util', function () { }); }); - test('colorToRGBA() - from HSL to RGBA conversion', function () { + it('colorToRGBA() - from HSL to RGBA conversion', function () { assert.deepEqual(Konva.Util.colorToRGBA('hsl(0, 0%, 0%)'), { r: 0, g: 0, @@ -49,7 +52,7 @@ suite('Util', function () { }); }); - test('make sure Transform is exported', () => { + it('make sure Transform is exported', () => { assert.equal(!!Konva.Transform, true); }); }); diff --git a/test/unit/filters/Blur-test.js b/test/unit-new/filters/Blur-test.ts similarity index 80% rename from test/unit/filters/Blur-test.js rename to test/unit-new/filters/Blur-test.ts index 56a2f245..c266ad80 100644 --- a/test/unit/filters/Blur-test.js +++ b/test/unit-new/filters/Blur-test.ts @@ -1,13 +1,15 @@ -suite('Blur', function () { +import { assert } from 'chai'; + +import { addStage, Konva, loadImage } from '../utis'; + +describe('Blur', function () { // ====================================================== - test('basic blur', function (done) { - this.timeout(5000); + it('basic blur', function (done) { var stage = addStage(); - var imageObj = new Image(); - imageObj.onload = function () { + loadImage('darth-vader.jpg', (imageObj) => { var layer = new Konva.Layer(); - darth = new Konva.Image({ + const darth = new Konva.Image({ x: 10, y: 10, image: imageObj, @@ -38,11 +40,10 @@ suite('Blur', function () { assert.equal(darth._filterUpToDate, true); done(); - }; - imageObj.src = 'assets/darth-vader.jpg'; + }); }); - test('blur group', function () { + it('blur group', function () { var stage = addStage(); var layer = new Konva.Layer(); var group = new Konva.Group({ @@ -110,13 +111,12 @@ suite('Blur', function () { }); // ====================================================== - test('tween blur', function (done) { + it('tween blur', function (done) { var stage = addStage(); - var imageObj = new Image(); - imageObj.onload = function () { + loadImage('darth-vader.jpg', (imageObj) => { var layer = new Konva.Layer(); - darth = new Konva.Image({ + const darth = new Konva.Image({ x: 10, y: 10, image: imageObj, @@ -147,18 +147,16 @@ suite('Blur', function () { }); done(); - }; - imageObj.src = 'assets/darth-vader.jpg'; + }); }); // ====================================================== - test('crop blur', function (done) { + it('crop blur', function (done) { var stage = addStage(); - var imageObj = new Image(); - imageObj.onload = function () { + loadImage('darth-vader.jpg', (imageObj) => { var layer = new Konva.Layer(); - darth = new Konva.Image({ + const darth = new Konva.Image({ x: 10, y: 10, image: imageObj, @@ -175,18 +173,16 @@ suite('Blur', function () { layer.draw(); done(); - }; - imageObj.src = 'assets/darth-vader.jpg'; + }); }); // ====================================================== - test('crop tween blur', function (done) { + it('crop tween blur', function (done) { var stage = addStage(); - var imageObj = new Image(); - imageObj.onload = function () { + loadImage('darth-vader.jpg', (imageObj) => { var layer = new Konva.Layer(); - darth = new Konva.Image({ + const darth = new Konva.Image({ x: 10, y: 10, image: imageObj, @@ -218,18 +214,16 @@ suite('Blur', function () { }); done(); - }; - imageObj.src = 'assets/darth-vader.jpg'; + }); }); // ====================================================== - test('transparency', function (done) { + it('transparency', function (done) { var stage = addStage(); - var imageObj = new Image(); - imageObj.onload = function () { + loadImage('darth-vader.jpg', (imageObj) => { var layer = new Konva.Layer(); - darth = new Konva.Image({ + const darth = new Konva.Image({ x: 10, y: 10, image: imageObj, @@ -260,18 +254,16 @@ suite('Blur', function () { }); done(); - }; - imageObj.src = 'assets/lion.png'; + }); }); // ====================================================== - test('blur hit region', function (done) { + it('blur hit region', function (done) { var stage = addStage(); - var imageObj = new Image(); - imageObj.onload = function () { + loadImage('lion.png', (imageObj) => { var layer = new Konva.Layer(); - darth = new Konva.Image({ + const darth = new Konva.Image({ x: 10, y: 10, image: imageObj, @@ -289,14 +281,11 @@ suite('Blur', function () { darth.drawHitFromCache(100); layer.draw(); - showCanvas(darth._getCanvasCache().hit._canvas); - //console.log(darth._getCanvasCache().hit.getContext().getTrace()); //assert.equal(darth._getCanvasCache().hit.getContext().getTrace(true), 'save();translate();beginPath();rect();closePath();save();fillStyle;fill();restore();restore();clearRect();getImageData();putImageData();'); done(); - }; - imageObj.src = 'assets/lion.png'; + }); }); }); diff --git a/test/unit/filters/Brighten-test.js b/test/unit-new/filters/Brighten-test.ts similarity index 75% rename from test/unit/filters/Brighten-test.js rename to test/unit-new/filters/Brighten-test.ts index ccf2a87d..5f28249f 100644 --- a/test/unit/filters/Brighten-test.js +++ b/test/unit-new/filters/Brighten-test.ts @@ -1,12 +1,15 @@ -suite('Brighten', function () { +import { assert } from 'chai'; + +import { addStage, Konva, loadImage } from '../utis'; + +describe('Brighten', function () { // ====================================================== - test('basic', function (done) { + it('basic', function (done) { var stage = addStage(); - var imageObj = new Image(); - imageObj.onload = function () { + loadImage('darth-vader.jpg', (imageObj) => { var layer = new Konva.Layer(); - darth = new Konva.Image({ + const darth = new Konva.Image({ x: 10, y: 10, image: imageObj, @@ -24,18 +27,16 @@ suite('Brighten', function () { assert.equal(darth.brightness(), 0.3); done(); - }; - imageObj.src = 'assets/darth-vader.jpg'; + }); }); // ====================================================== - test('tween', function (done) { + it('tween', function (done) { var stage = addStage(); - var imageObj = new Image(); - imageObj.onload = function () { + loadImage('darth-vader.jpg', (imageObj) => { var layer = new Konva.Layer(); - darth = new Konva.Image({ + const darth = new Konva.Image({ x: 10, y: 10, image: imageObj, @@ -66,18 +67,16 @@ suite('Brighten', function () { }); done(); - }; - imageObj.src = 'assets/darth-vader.jpg'; + }); }); // ====================================================== - test('crop', function (done) { + it('crop', function (done) { var stage = addStage(); - var imageObj = new Image(); - imageObj.onload = function () { + loadImage('darth-vader.jpg', (imageObj) => { var layer = new Konva.Layer(); - darth = new Konva.Image({ + const darth = new Konva.Image({ x: 10, y: 10, image: imageObj, @@ -96,18 +95,16 @@ suite('Brighten', function () { assert.equal(darth.brightness(), -0.3); done(); - }; - imageObj.src = 'assets/darth-vader.jpg'; + }); }); // ====================================================== - test('tween transparency', function (done) { + it('tween transparency', function (done) { var stage = addStage(); - var imageObj = new Image(); - imageObj.onload = function () { + loadImage('lion.png', (imageObj) => { var layer = new Konva.Layer(); - darth = new Konva.Image({ + const darth = new Konva.Image({ x: 10, y: 10, image: imageObj, @@ -138,7 +135,6 @@ suite('Brighten', function () { }); done(); - }; - imageObj.src = 'assets/lion.png'; + }); }); }); diff --git a/test/unit/filters/Contrast-test.js b/test/unit-new/filters/Contrast-test.ts similarity index 77% rename from test/unit/filters/Contrast-test.js rename to test/unit-new/filters/Contrast-test.ts index 63d9bf29..14744f85 100644 --- a/test/unit/filters/Contrast-test.js +++ b/test/unit-new/filters/Contrast-test.ts @@ -1,10 +1,13 @@ -suite('Filter Contrast', function () { +import { assert } from 'chai'; + +import { addStage, Konva, loadImage } from '../utis'; + +describe('Filter Contrast', function () { // ====================================================== - test('basic', function (done) { + it('basic', function (done) { var stage = addStage(); - var imageObj = new Image(); - imageObj.onload = function () { + loadImage('darth-vader.jpg', (imageObj) => { var layer = new Konva.Layer(); var darth = new Konva.Image({ x: 10, @@ -24,16 +27,14 @@ suite('Filter Contrast', function () { assert.equal(darth.contrast(), 40); done(); - }; - imageObj.src = 'assets/darth-vader.jpg'; + }); }); // ====================================================== - test('tween', function (done) { + it('tween', function (done) { var stage = addStage(); - var imageObj = new Image(); - imageObj.onload = function () { + loadImage('darth-vader.jpg', (imageObj) => { var layer = new Konva.Layer(); var darth = new Konva.Image({ x: 10, @@ -66,16 +67,14 @@ suite('Filter Contrast', function () { }); done(); - }; - imageObj.src = 'assets/darth-vader.jpg'; + }); }); // ====================================================== - test('crop', function (done) { + it('crop', function (done) { var stage = addStage(); - var imageObj = new Image(); - imageObj.onload = function () { + loadImage('darth-vader.jpg', (imageObj) => { var layer = new Konva.Layer(); var darth = new Konva.Image({ x: 10, @@ -96,7 +95,6 @@ suite('Filter Contrast', function () { assert.equal(darth.contrast(), -40); done(); - }; - imageObj.src = 'assets/darth-vader.jpg'; + }); }); }); diff --git a/test/unit/filters/Emboss-test.js b/test/unit-new/filters/Emboss-test.ts similarity index 79% rename from test/unit/filters/Emboss-test.js rename to test/unit-new/filters/Emboss-test.ts index 0751937b..25d2e72c 100644 --- a/test/unit/filters/Emboss-test.js +++ b/test/unit-new/filters/Emboss-test.ts @@ -1,12 +1,15 @@ -suite('Emboss', function () { +import { assert } from 'chai'; + +import { addStage, Konva, loadImage } from '../utis'; + +describe('Emboss', function () { // ====================================================== - test('basic emboss', function (done) { + it('basic emboss', function (done) { var stage = addStage(); - var imageObj = new Image(); - imageObj.onload = function () { + loadImage('darth-vader.jpg', (imageObj) => { var layer = new Konva.Layer(); - darth = new Konva.Image({ + const darth = new Konva.Image({ x: 10, y: 10, image: imageObj, @@ -39,19 +42,17 @@ suite('Emboss', function () { }); done(); - }; - imageObj.src = 'assets/darth-vader.jpg'; + }); //imageObj.src = 'assets/lion.png'; }); // ====================================================== - test('blended emboss', function (done) { + it('blended emboss', function (done) { var stage = addStage(); - var imageObj = new Image(); - imageObj.onload = function () { + loadImage('darth-vader.jpg', (imageObj) => { var layer = new Konva.Layer(); - darth = new Konva.Image({ + const darth = new Konva.Image({ x: 10, y: 10, image: imageObj, @@ -84,8 +85,7 @@ suite('Emboss', function () { }); done(); - }; - imageObj.src = 'assets/darth-vader.jpg'; + }); //imageObj.src = 'assets/lion.png'; }); }); diff --git a/test/unit/filters/Enhance-test.js b/test/unit-new/filters/Enhance-test.ts similarity index 76% rename from test/unit/filters/Enhance-test.js rename to test/unit-new/filters/Enhance-test.ts index 9802f358..766ba764 100644 --- a/test/unit/filters/Enhance-test.js +++ b/test/unit-new/filters/Enhance-test.ts @@ -1,10 +1,13 @@ -suite('Enhance', function () { +import { assert } from 'chai'; + +import { addStage, Konva, loadImage } from '../utis'; + +describe('Enhance', function () { // ====================================================== - test('on image', function (done) { + it('on image', function (done) { var stage = addStage(); - var imageObj = new Image(); - imageObj.onload = function () { + loadImage('scorpion-sprite.png', (imageObj) => { var layer = new Konva.Layer(); var filt = new Konva.Image({ x: 10, @@ -29,18 +32,16 @@ suite('Enhance', function () { layer.draw(); done(); - }; - imageObj.src = 'assets/scorpion-sprite.png'; + }); }); // ====================================================== - test('tween enhance', function (done) { + it('tween enhance', function (done) { var stage = addStage(); - var imageObj = new Image(); - imageObj.onload = function () { + loadImage('scorpion-sprite.png', (imageObj) => { var layer = new Konva.Layer(); - darth = new Konva.Image({ + const darth = new Konva.Image({ x: 10, y: 10, image: imageObj, @@ -71,7 +72,6 @@ suite('Enhance', function () { }); done(); - }; - imageObj.src = 'assets/scorpion-sprite.png'; + }); }); }); diff --git a/test/unit/filters/Filter-test.js b/test/unit-new/filters/Filter-test.ts similarity index 71% rename from test/unit/filters/Filter-test.js rename to test/unit-new/filters/Filter-test.ts index 12e463e4..793245dd 100644 --- a/test/unit/filters/Filter-test.js +++ b/test/unit-new/filters/Filter-test.ts @@ -1,7 +1,7 @@ -'use strict'; +import { addStage, Konva, cloneAndCompareLayer } from '../utis'; -suite('Filter', function () { - test('pixelRaio check', function () { +describe('Filter', function () { + it('pixelRaio check', function () { Konva.pixelRatio = 2; var stage = addStage(); var layer = new Konva.Layer(); @@ -21,7 +21,7 @@ suite('Filter', function () { circle.blurRadius(0); layer.draw(); - cloneAndCompareLayer(layer, 50); + cloneAndCompareLayer(layer, 150); Konva.pixelRatio = 1; }); }); diff --git a/test/unit/filters/Grayscale-test.js b/test/unit-new/filters/Grayscale-test.ts similarity index 66% rename from test/unit/filters/Grayscale-test.js rename to test/unit-new/filters/Grayscale-test.ts index 01acd70b..4b298659 100644 --- a/test/unit/filters/Grayscale-test.js +++ b/test/unit-new/filters/Grayscale-test.ts @@ -1,12 +1,15 @@ -suite('Grayscale', function () { +import { assert } from 'chai'; + +import { addStage, Konva, loadImage } from '../utis'; + +describe('Grayscale', function () { // ====================================================== - test('basic', function (done) { + it('basic', function (done) { var stage = addStage(); - var imageObj = new Image(); - imageObj.onload = function () { + loadImage('darth-vader.jpg', (imageObj) => { var layer = new Konva.Layer(); - darth = new Konva.Image({ + const darth = new Konva.Image({ x: 10, y: 10, image: imageObj, @@ -21,18 +24,16 @@ suite('Grayscale', function () { layer.draw(); done(); - }; - imageObj.src = 'assets/darth-vader.jpg'; + }); }); // ====================================================== - test('crop', function (done) { + it('crop', function (done) { var stage = addStage(); - var imageObj = new Image(); - imageObj.onload = function () { + loadImage('darth-vader.jpg', (imageObj) => { var layer = new Konva.Layer(); - darth = new Konva.Image({ + const darth = new Konva.Image({ x: 10, y: 10, image: imageObj, @@ -48,18 +49,16 @@ suite('Grayscale', function () { layer.draw(); done(); - }; - imageObj.src = 'assets/darth-vader.jpg'; + }); }); // ====================================================== - test('with transparency', function (done) { + it('with transparency', function (done) { var stage = addStage(); - var imageObj = new Image(); - imageObj.onload = function () { + loadImage('lion.png', (imageObj) => { var layer = new Konva.Layer(); - darth = new Konva.Image({ + const darth = new Konva.Image({ x: 10, y: 10, image: imageObj, @@ -74,7 +73,6 @@ suite('Grayscale', function () { layer.draw(); done(); - }; - imageObj.src = 'assets/lion.png'; + }); }); }); diff --git a/test/unit/filters/HSL-test.js b/test/unit-new/filters/HSL-test.ts similarity index 76% rename from test/unit/filters/HSL-test.js rename to test/unit-new/filters/HSL-test.ts index 83859eff..b96d71ab 100644 --- a/test/unit/filters/HSL-test.js +++ b/test/unit-new/filters/HSL-test.ts @@ -1,12 +1,15 @@ -suite('HSL', function () { +import { assert } from 'chai'; + +import { addStage, Konva, loadImage } from '../utis'; + +describe('HSL', function () { // ====================================================== - test('hue shift tween transparancy', function (done) { + it('hue shift tween transparancy', function (done) { var stage = addStage(); - var imageObj = new Image(); - imageObj.onload = function () { + loadImage('lion.png', (imageObj) => { var layer = new Konva.Layer(); - darth = new Konva.Image({ + const darth = new Konva.Image({ x: 10, y: 10, image: imageObj, @@ -37,18 +40,16 @@ suite('HSL', function () { }); done(); - }; - imageObj.src = 'assets/lion.png'; + }); }); // ====================================================== - test('HSL luminance tween transparancy', function (done) { + it('HSL luminance tween transparancy', function (done) { var stage = addStage(); - var imageObj = new Image(); - imageObj.onload = function () { + loadImage('darth-vader.jpg', (imageObj) => { var layer = new Konva.Layer(); - darth = new Konva.Image({ + const darth = new Konva.Image({ x: 10, y: 10, image: imageObj, @@ -79,18 +80,16 @@ suite('HSL', function () { }); done(); - }; - imageObj.src = 'assets/lion.png'; + }); }); // ====================================================== - test('HSL saturation tween transparancy', function (done) { + it('HSL saturation tween transparancy', function (done) { var stage = addStage(); - var imageObj = new Image(); - imageObj.onload = function () { + loadImage('lion.png', (imageObj) => { var layer = new Konva.Layer(); - darth = new Konva.Image({ + const darth = new Konva.Image({ x: 10, y: 10, image: imageObj, @@ -121,7 +120,6 @@ suite('HSL', function () { }); done(); - }; - imageObj.src = 'assets/lion.png'; + }); }); }); diff --git a/test/unit/filters/HSV-test.js b/test/unit-new/filters/HSV-test.ts similarity index 77% rename from test/unit/filters/HSV-test.js rename to test/unit-new/filters/HSV-test.ts index 2784a65e..0375f5ca 100644 --- a/test/unit/filters/HSV-test.js +++ b/test/unit-new/filters/HSV-test.ts @@ -1,12 +1,15 @@ -suite('HSV', function () { +import { assert } from 'chai'; + +import { addStage, Konva, loadImage } from '../utis'; + +describe('HSV', function () { // ====================================================== - test('hue shift tween transparancy', function (done) { + it('hue shift tween transparancy', function (done) { var stage = addStage(); - var imageObj = new Image(); - imageObj.onload = function () { + loadImage('darth-vader.jpg', (imageObj) => { var layer = new Konva.Layer(); - darth = new Konva.Image({ + const darth = new Konva.Image({ x: 10, y: 10, image: imageObj, @@ -37,18 +40,16 @@ suite('HSV', function () { }); done(); - }; - imageObj.src = 'assets/lion.png'; + }); }); // ====================================================== - test('saturate image', function (done) { + it('saturate image', function (done) { var stage = addStage(); - var imageObj = new Image(); - imageObj.onload = function () { + loadImage('darth-vader.jpg', (imageObj) => { var layer = new Konva.Layer(); - darth = new Konva.Image({ + const darth = new Konva.Image({ x: 10, y: 10, image: imageObj, @@ -80,18 +81,16 @@ suite('HSV', function () { }); done(); - }; - imageObj.src = 'assets/bamoon.jpg'; + }); }); // ====================================================== - test('saturation tween transparancy', function (done) { + it('saturation tween transparancy', function (done) { var stage = addStage(); - var imageObj = new Image(); - imageObj.onload = function () { + loadImage('darth-vader.jpg', (imageObj) => { var layer = new Konva.Layer(); - darth = new Konva.Image({ + const darth = new Konva.Image({ x: 10, y: 10, image: imageObj, @@ -122,18 +121,16 @@ suite('HSV', function () { }); done(); - }; - imageObj.src = 'assets/lion.png'; + }); }); // ====================================================== - test('value tween transparancy', function (done) { + it('value tween transparancy', function (done) { var stage = addStage(); - var imageObj = new Image(); - imageObj.onload = function () { + loadImage('darth-vader.jpg', (imageObj) => { var layer = new Konva.Layer(); - darth = new Konva.Image({ + const darth = new Konva.Image({ x: 10, y: 10, image: imageObj, @@ -164,7 +161,6 @@ suite('HSV', function () { }); done(); - }; - imageObj.src = 'assets/lion.png'; + }); }); }); diff --git a/test/unit/filters/Invert-test.js b/test/unit-new/filters/Invert-test.ts similarity index 66% rename from test/unit/filters/Invert-test.js rename to test/unit-new/filters/Invert-test.ts index 8bbd729d..5205a346 100644 --- a/test/unit/filters/Invert-test.js +++ b/test/unit-new/filters/Invert-test.ts @@ -1,12 +1,15 @@ -suite('Invert', function () { +import { assert } from 'chai'; + +import { addStage, Konva, loadImage } from '../utis'; + +describe('Invert', function () { // ====================================================== - test('basic', function (done) { + it('basic', function (done) { var stage = addStage(); - var imageObj = new Image(); - imageObj.onload = function () { + loadImage('darth-vader.jpg', (imageObj) => { var layer = new Konva.Layer(); - darth = new Konva.Image({ + const darth = new Konva.Image({ x: 10, y: 10, image: imageObj, @@ -21,18 +24,16 @@ suite('Invert', function () { layer.draw(); done(); - }; - imageObj.src = 'assets/darth-vader.jpg'; + }); }); // ====================================================== - test('crop', function (done) { + it('crop', function (done) { var stage = addStage(); - var imageObj = new Image(); - imageObj.onload = function () { + loadImage('darth-vader.jpg', (imageObj) => { var layer = new Konva.Layer(); - darth = new Konva.Image({ + const darth = new Konva.Image({ x: 10, y: 10, image: imageObj, @@ -48,18 +49,16 @@ suite('Invert', function () { layer.draw(); done(); - }; - imageObj.src = 'assets/darth-vader.jpg'; + }); }); // ====================================================== - test('transparancy', function (done) { + it('transparancy', function (done) { var stage = addStage(); - var imageObj = new Image(); - imageObj.onload = function () { + loadImage('darth-vader.jpg', (imageObj) => { var layer = new Konva.Layer(); - darth = new Konva.Image({ + const darth = new Konva.Image({ x: 10, y: 10, image: imageObj, @@ -74,7 +73,6 @@ suite('Invert', function () { layer.draw(); done(); - }; - imageObj.src = 'assets/lion.png'; + }); }); }); diff --git a/test/unit/filters/Kaleidoscope-test.js b/test/unit-new/filters/Kaleidoscope-test.ts similarity index 78% rename from test/unit/filters/Kaleidoscope-test.js rename to test/unit-new/filters/Kaleidoscope-test.ts index aa650695..07dbef92 100644 --- a/test/unit/filters/Kaleidoscope-test.js +++ b/test/unit-new/filters/Kaleidoscope-test.ts @@ -1,12 +1,15 @@ -suite('Kaleidoscope', function () { +import { assert } from 'chai'; + +import { addStage, Konva, loadImage } from '../utis'; + +describe('Kaleidoscope', function () { // ====================================================== - test('basic', function (done) { + it('basic', function (done) { var stage = addStage(); - var imageObj = new Image(); - imageObj.onload = function () { + loadImage('darth-vader.jpg', (imageObj) => { var layer = new Konva.Layer(); - darth = new Konva.Image({ + const darth = new Konva.Image({ x: 10, y: 10, image: imageObj, @@ -37,18 +40,16 @@ suite('Kaleidoscope', function () { assert.equal(darth._filterUpToDate, true); done(); - }; - imageObj.src = 'assets/lion.png'; + }); }); // ====================================================== - test('tween angle', function (done) { + it('tween angle', function (done) { var stage = addStage(); - var imageObj = new Image(); - imageObj.onload = function () { + loadImage('darth-vader.jpg', (imageObj) => { var layer = new Konva.Layer(); - darth = new Konva.Image({ + const darth = new Konva.Image({ x: 10, y: 10, image: imageObj, @@ -80,18 +81,16 @@ suite('Kaleidoscope', function () { }); done(); - }; - imageObj.src = 'assets/lion.png'; + }); }); // ====================================================== - test('tween power', function (done) { + it('tween power', function (done) { var stage = addStage(); - var imageObj = new Image(); - imageObj.onload = function () { + loadImage('darth-vader.jpg', (imageObj) => { var layer = new Konva.Layer(); - darth = new Konva.Image({ + const darth = new Konva.Image({ x: 10, y: 10, image: imageObj, @@ -111,7 +110,7 @@ suite('Kaleidoscope', function () { node: darth, duration: 2.0, kaleidoscopePower: 8, - easing: Konva.EasingsEaseInOut, + easing: Konva.Easings.EaseInOut, }); darth.on('mouseover', function () { @@ -123,7 +122,6 @@ suite('Kaleidoscope', function () { }); done(); - }; - imageObj.src = 'assets/lion.png'; + }); }); }); diff --git a/test/unit/filters/Mask-test.js b/test/unit-new/filters/Mask-test.ts similarity index 78% rename from test/unit/filters/Mask-test.js rename to test/unit-new/filters/Mask-test.ts index 8f77581e..d56679a2 100644 --- a/test/unit/filters/Mask-test.js +++ b/test/unit-new/filters/Mask-test.ts @@ -1,10 +1,11 @@ -suite('Mask', function () { +import { addStage, Konva, loadImage } from '../utis'; + +describe('Mask', function () { // ====================================================== - test('basic', function (done) { + it('basic', function (done) { var stage = addStage(); - var imageObj = new Image(); - imageObj.onload = function () { + loadImage('darth-vader.jpg', (imageObj) => { var layer = new Konva.Layer({ throttle: 999, }); @@ -32,7 +33,6 @@ suite('Mask', function () { layer.draw(); done(); - }; - imageObj.src = 'assets/bamoon.jpg'; + }); }); }); diff --git a/test/unit/filters/Noise-test.js b/test/unit-new/filters/Noise-test.ts similarity index 73% rename from test/unit/filters/Noise-test.js rename to test/unit-new/filters/Noise-test.ts index 54541909..75ef0439 100644 --- a/test/unit/filters/Noise-test.js +++ b/test/unit-new/filters/Noise-test.ts @@ -1,12 +1,15 @@ -suite('Noise', function () { +import { assert } from 'chai'; + +import { addStage, Konva, loadImage } from '../utis'; + +describe('Noise', function () { // ====================================================== - test('noise tween', function (done) { + it('noise tween', function (done) { var stage = addStage(); - var imageObj = new Image(); - imageObj.onload = function () { + loadImage('darth-vader.jpg', (imageObj) => { var layer = new Konva.Layer(); - darth = new Konva.Image({ + const darth = new Konva.Image({ x: 10, y: 10, image: imageObj, @@ -37,7 +40,6 @@ suite('Noise', function () { }); done(); - }; - imageObj.src = 'assets/lion.png'; + }); }); }); diff --git a/test/unit/filters/Pixelate-test.js b/test/unit-new/filters/Pixelate-test.ts similarity index 73% rename from test/unit/filters/Pixelate-test.js rename to test/unit-new/filters/Pixelate-test.ts index ea7becf2..65c5cc34 100644 --- a/test/unit/filters/Pixelate-test.js +++ b/test/unit-new/filters/Pixelate-test.ts @@ -1,12 +1,15 @@ -suite('Pixelate', function () { +import { assert } from 'chai'; + +import { addStage, Konva, loadImage } from '../utis'; + +describe('Pixelate', function () { // ====================================================== - test('tween pixelate', function (done) { + it('tween pixelate', function (done) { var stage = addStage(); - var imageObj = new Image(); - imageObj.onload = function () { + loadImage('darth-vader.jpg', (imageObj) => { var layer = new Konva.Layer(); - lion = new Konva.Image({ + const lion = new Konva.Image({ x: 10, y: 10, image: imageObj, @@ -37,7 +40,6 @@ suite('Pixelate', function () { }); done(); - }; - imageObj.src = 'assets/lion.png'; + }); }); }); diff --git a/test/unit/filters/Posterize-test.js b/test/unit-new/filters/Posterize-test.ts similarity index 73% rename from test/unit/filters/Posterize-test.js rename to test/unit-new/filters/Posterize-test.ts index 675a8039..dfe28102 100644 --- a/test/unit/filters/Posterize-test.js +++ b/test/unit-new/filters/Posterize-test.ts @@ -1,12 +1,15 @@ -suite('Posterize', function () { +import { assert } from 'chai'; + +import { addStage, Konva, loadImage } from '../utis'; + +describe('Posterize', function () { // ====================================================== - test('on image tween', function (done) { + it('on image tween', function (done) { var stage = addStage(); - var imageObj = new Image(); - imageObj.onload = function () { + loadImage('darth-vader.jpg', (imageObj) => { var layer = new Konva.Layer(); - darth = new Konva.Image({ + const darth = new Konva.Image({ x: 10, y: 10, image: imageObj, @@ -37,7 +40,6 @@ suite('Posterize', function () { }); done(); - }; - imageObj.src = 'assets/darth-vader.jpg'; + }); }); }); diff --git a/test/unit-new/filters/RGB-test.ts b/test/unit-new/filters/RGB-test.ts new file mode 100644 index 00000000..f2d65cb4 --- /dev/null +++ b/test/unit-new/filters/RGB-test.ts @@ -0,0 +1,109 @@ +import { assert } from 'chai'; + +import { addStage, Konva, loadImage } from '../utis'; + +describe('RGB', function () { + // ====================================================== + it('colorize basic', function (done) { + var stage = addStage(); + + loadImage('darth-vader.jpg', (imageObj) => { + var layer = new Konva.Layer(); + const darth = new Konva.Image({ + x: 10, + y: 10, + image: imageObj, + draggable: true, + }); + + layer.add(darth); + stage.add(layer); + + darth.cache(); + darth.filters([Konva.Filters.RGB]); + darth.red(255).green(0).blue(128); + layer.draw(); + + // Assert fails even though '[255,0,128] = [255,0,128]' + // assert.deepEqual(darth.getFilterColorizeColor(), [255,0,128]); + + done(); + }); + }); + + // ====================================================== + it('colorize crop', function (done) { + var stage = addStage(); + + loadImage('darth-vader.jpg', (imageObj) => { + var layer = new Konva.Layer(); + const darth = new Konva.Image({ + x: 10, + y: 10, + image: imageObj, + crop: { x: 128, y: 48, width: 256, height: 128 }, + draggable: true, + }); + + layer.add(darth); + stage.add(layer); + + darth.cache(); + darth.filters([Konva.Filters.RGB]); + darth.red(0).green(255).blue(0); + layer.draw(); + + // assert.deepEqual(darth.getFilterColorizeColor(), [0,255,0]); + + done(); + }); + }); + + // ====================================================== + it('colorize transparancy', function (done) { + loadImage('lion.png', (imageObj) => { + var stage = addStage(); + var layer = new Konva.Layer(); + + var colors = [ + [255, 0, 0], + [255, 128, 0], + [255, 255, 0], + [0, 255, 0], + [0, 255, 128], + [0, 255, 255], + [0, 0, 255], + [128, 0, 255], + [255, 0, 255], + [0, 0, 0], + [128, 128, 128], + [255, 255, 255], + ]; + var i, + l = colors.length; + var nAdded = 0; + for (i = 0; i < l; i += 1) { + const color = colors[i]; + const x = -64 + (i / l) * stage.width(); + var darth = new Konva.Image({ + x: x, + y: 32, + image: imageObj, + draggable: true, + }); + layer.add(darth); + + darth.cache(); + darth.filters([Konva.Filters.RGB]); + darth.red(color[0]).green(color[1]).blue(color[2]); + + nAdded += 1; + if (nAdded >= l) { + stage.add(layer); + layer.draw(); + done(); + } + } + }); + }); +}); diff --git a/test/unit/filters/RGBA-test.js b/test/unit-new/filters/RGBA-test.ts similarity index 89% rename from test/unit/filters/RGBA-test.js rename to test/unit-new/filters/RGBA-test.ts index 3e1c1081..9ac90e72 100644 --- a/test/unit/filters/RGBA-test.js +++ b/test/unit-new/filters/RGBA-test.ts @@ -1,6 +1,10 @@ -suite('RGBA', function () { +import { assert } from 'chai'; + +import { addStage, Konva, loadImage } from '../utis'; + +describe('RGBA', function () { // ====================================================== - test.skip('colorize basic', function (done) { + it.skip('colorize basic', function (done) { var data = [ { color: '#2a6511', diff --git a/test/unit/filters/Sepia-test.js b/test/unit-new/filters/Sepia-test.ts similarity index 66% rename from test/unit/filters/Sepia-test.js rename to test/unit-new/filters/Sepia-test.ts index c48824a1..82f3a0e0 100644 --- a/test/unit/filters/Sepia-test.js +++ b/test/unit-new/filters/Sepia-test.ts @@ -1,12 +1,15 @@ -suite('Filter Sepia', function () { +import { assert } from 'chai'; + +import { addStage, Konva, loadImage } from '../utis'; + +describe('Filter Sepia', function () { // ====================================================== - test('basic', function (done) { + it('basic', function (done) { var stage = addStage(); - var imageObj = new Image(); - imageObj.onload = function () { + loadImage('darth-vader.jpg', (imageObj) => { var layer = new Konva.Layer(); - darth = new Konva.Image({ + const darth = new Konva.Image({ x: 10, y: 10, image: imageObj, @@ -21,18 +24,16 @@ suite('Filter Sepia', function () { layer.draw(); done(); - }; - imageObj.src = 'assets/darth-vader.jpg'; + }); }); // ====================================================== - test('crop', function (done) { + it('crop', function (done) { var stage = addStage(); - var imageObj = new Image(); - imageObj.onload = function () { + loadImage('darth-vader.jpg', (imageObj) => { var layer = new Konva.Layer(); - darth = new Konva.Image({ + const darth = new Konva.Image({ x: 10, y: 10, image: imageObj, @@ -48,18 +49,16 @@ suite('Filter Sepia', function () { layer.draw(); done(); - }; - imageObj.src = 'assets/darth-vader.jpg'; + }); }); // ====================================================== - test('with transparency', function (done) { + it('with transparency', function (done) { var stage = addStage(); - var imageObj = new Image(); - imageObj.onload = function () { + loadImage('darth-vader.jpg', (imageObj) => { var layer = new Konva.Layer(); - darth = new Konva.Image({ + const darth = new Konva.Image({ x: 10, y: 10, image: imageObj, @@ -74,7 +73,6 @@ suite('Filter Sepia', function () { layer.draw(); done(); - }; - imageObj.src = 'assets/lion.png'; + }); }); }); diff --git a/test/unit/filters/Solarize-test.js b/test/unit-new/filters/Solarize-test.ts similarity index 62% rename from test/unit/filters/Solarize-test.js rename to test/unit-new/filters/Solarize-test.ts index 53b9d896..43a4a618 100644 --- a/test/unit/filters/Solarize-test.js +++ b/test/unit-new/filters/Solarize-test.ts @@ -1,12 +1,15 @@ -suite('Solarize', function () { +import { assert } from 'chai'; + +import { addStage, Konva, loadImage } from '../utis'; + +describe('Solarize', function () { // ====================================================== - test('solarize', function (done) { + it('solarize', function (done) { var stage = addStage(); - var imageObj = new Image(); - imageObj.onload = function () { + loadImage('darth-vader.jpg', (imageObj) => { var layer = new Konva.Layer(); - darth = new Konva.Image({ + const darth = new Konva.Image({ x: 10, y: 10, image: imageObj, @@ -21,8 +24,7 @@ suite('Solarize', function () { layer.draw(); done(); - }; - imageObj.src = 'assets/darth-vader.jpg'; + }); //imageObj.src = 'assets/lion.png'; }); }); diff --git a/test/unit/filters/Threshold-test.js b/test/unit-new/filters/Threshold-test.ts similarity index 73% rename from test/unit/filters/Threshold-test.js rename to test/unit-new/filters/Threshold-test.ts index e7e2fe9d..b4b8b903 100644 --- a/test/unit/filters/Threshold-test.js +++ b/test/unit-new/filters/Threshold-test.ts @@ -1,12 +1,15 @@ -suite('Threshold', function () { +import { assert } from 'chai'; + +import { addStage, Konva, loadImage } from '../utis'; + +describe('Threshold', function () { // ====================================================== - test('image tween', function (done) { + it('image tween', function (done) { var stage = addStage(); - var imageObj = new Image(); - imageObj.onload = function () { + loadImage('darth-vader.jpg', (imageObj) => { var layer = new Konva.Layer(); - darth = new Konva.Image({ + const darth = new Konva.Image({ x: 10, y: 10, image: imageObj, @@ -37,7 +40,6 @@ suite('Threshold', function () { }); done(); - }; - imageObj.src = 'assets/darth-vader.jpg'; + }); }); }); diff --git a/test/unit-new/imagediff.ts b/test/unit-new/imagediff.ts new file mode 100644 index 00000000..bb1e563f --- /dev/null +++ b/test/unit-new/imagediff.ts @@ -0,0 +1,332 @@ +import { createCanvas, Canvas } from 'canvas'; + +var TYPE_ARRAY = /\[object Array\]/i, + TYPE_CANVAS = /\[object (Canvas|HTMLCanvasElement)\]/i, + TYPE_NODE_CANVAS = /\[object (Canvas|HTMLCanvasElement)\]/i, + TYPE_CONTEXT = /\[object CanvasRenderingContext2D\]/i, + TYPE_IMAGE = /\[object (Image|HTMLImageElement)\]/i, + TYPE_IMAGE_DATA = /\[object ImageData\]/i, + UNDEFINED = 'undefined', + canvas = getCanvas(), + context = canvas.getContext('2d'); + +// Creation +function getCanvas(width?, height?) { + return createCanvas(width, height); +} +function getImageData(width, height) { + canvas.width = width; + canvas.height = height; + context.clearRect(0, 0, width, height); + return context.createImageData(width, height); +} + +// Type Checking +function isImage(object) { + return isType(object, TYPE_IMAGE); +} +function isCanvas(object) { + return isType(object, TYPE_CANVAS) || object instanceof Canvas; +} +function isContext(object) { + return isType(object, TYPE_CONTEXT); +} +function isImageData(object) { + return !!( + object && + isType(object, TYPE_IMAGE_DATA) && + typeof object.width !== UNDEFINED && + typeof object.height !== UNDEFINED && + typeof object.data !== UNDEFINED + ); +} +function isImageType(object) { + return ( + isImage(object) || + isCanvas(object) || + isContext(object) || + isImageData(object) + ); +} +function isType(object, type) { + return ( + typeof object === 'object' && + !!Object.prototype.toString.apply(object).match(type) + ); +} + +// Type Conversion +function copyImageData(imageData) { + var height = imageData.height, + width = imageData.width, + data = imageData.data, + newImageData, + newData, + i; + + canvas.width = width; + canvas.height = height; + newImageData = context.getImageData(0, 0, width, height); + newData = newImageData.data; + + for (i = imageData.data.length; i--; ) { + newData[i] = data[i]; + } + + return newImageData; +} +function toImageData(object) { + if (isImage(object)) { + return toImageDataFromImage(object); + } + if (isCanvas(object)) { + return toImageDataFromCanvas(object); + } + if (isContext(object)) { + return toImageDataFromContext(object); + } + if (isImageData(object)) { + return object; + } +} +function toImageDataFromImage(image) { + var height = image.height, + width = image.width; + canvas.width = width; + canvas.height = height; + context.clearRect(0, 0, width, height); + context.drawImage(image, 0, 0); + return context.getImageData(0, 0, width, height); +} +function toImageDataFromCanvas(canvas) { + var height = canvas.height, + width = canvas.width, + context = canvas.getContext('2d'); + if (!width || !height) { + console.trace(width, height); + } + + return context.getImageData(0, 0, width, height); +} +function toImageDataFromContext(context) { + var canvas = context.canvas, + height = canvas.height, + width = canvas.width; + return context.getImageData(0, 0, width, height); +} +function toCanvas(object) { + var data = toImageData(object), + canvas = getCanvas(data.width, data.height), + context = canvas.getContext('2d'); + + context.putImageData(data, 0, 0); + return canvas; +} + +// ImageData Equality Operators +function equalWidth(a, b) { + return a.width === b.width; +} +function equalHeight(a, b) { + return a.height === b.height; +} +function equalDimensions(a, b) { + return equalHeight(a, b) && equalWidth(a, b); +} + +export function equal(a, b, tolerance, secondTol) { + var aData = a.data, + bData = b.data, + length = aData.length, + i; + + tolerance = tolerance || 0; + + var count = 0; + if (!equalDimensions(a, b)) return false; + for (i = length; i--; ) { + const d = Math.abs(aData[i] - bData[i]); + if (aData[i] !== bData[i] && d > tolerance) { + if (!secondTol) { + console.log('Diff', d); + return false; + } else { + count += 1; + } + if (count > secondTol) { + console.log('Diff', d, count); + return false; + } + } + } + + return true; +} + +// Diff +function diff(a, b, options) { + return (equalDimensions(a, b) ? diffEqual : diffUnequal)(a, b, options); +} +function diffEqual(a, b, options) { + var height = a.height, + width = a.width, + c = getImageData(width, height), // c = a - b + aData = a.data, + bData = b.data, + cData = c.data, + length = cData.length, + row, + column, + i, + j, + k, + v; + + for (i = 0; i < length; i += 4) { + cData[i] = Math.abs(aData[i] - bData[i]); + cData[i + 1] = Math.abs(aData[i + 1] - bData[i + 1]); + cData[i + 2] = Math.abs(aData[i + 2] - bData[i + 2]); + cData[i + 3] = Math.abs(255 - Math.abs(aData[i + 3] - bData[i + 3])); + } + + return c; +} +function diffUnequal(a, b, options) { + var height = Math.max(a.height, b.height), + width = Math.max(a.width, b.width), + c = getImageData(width, height), // c = a - b + aData = a.data, + bData = b.data, + cData = c.data, + align = options && options.align, + rowOffset, + columnOffset, + row, + column, + i, + j, + k, + v; + + for (i = cData.length - 1; i > 0; i = i - 4) { + cData[i] = 255; + } + + // Add First Image + offsets(a); + for (row = a.height; row--; ) { + for (column = a.width; column--; ) { + i = 4 * ((row + rowOffset) * width + (column + columnOffset)); + j = 4 * (row * a.width + column); + cData[i + 0] = aData[j + 0]; // r + cData[i + 1] = aData[j + 1]; // g + cData[i + 2] = aData[j + 2]; // b + // cData[i+3] = aData[j+3]; // a + } + } + + // Subtract Second Image + offsets(b); + for (row = b.height; row--; ) { + for (column = b.width; column--; ) { + i = 4 * ((row + rowOffset) * width + (column + columnOffset)); + j = 4 * (row * b.width + column); + cData[i + 0] = Math.abs(cData[i + 0] - bData[j + 0]); // r + cData[i + 1] = Math.abs(cData[i + 1] - bData[j + 1]); // g + cData[i + 2] = Math.abs(cData[i + 2] - bData[j + 2]); // b + } + } + + // Helpers + function offsets(imageData) { + if (align === 'top') { + rowOffset = 0; + columnOffset = 0; + } else { + rowOffset = Math.floor((height - imageData.height) / 2); + columnOffset = Math.floor((width - imageData.width) / 2); + } + } + + return c; +} + +// Validation +function checkType(...args) { + var i; + for (i = 0; i < args.length; i++) { + if (!isImageType(args[i])) { + throw { + name: 'ImageTypeError', + message: 'Submitted object was not an image.', + }; + } + } +} + +// function formatImageDiffEqualHtmlReport(actual, expected) { +// var div = get('div', 'Expected to be equal.'), +// a = get('div', '
Actual:
'), +// b = get('div', '
Expected:
'), +// c = get('div', '
Diff:
'), +// diff = imagediff.diff(actual, expected), +// canvas = getCanvas(), +// context; + +// canvas.height = diff.height; +// canvas.width = diff.width; + +// div.style.overflow = 'hidden'; +// a.style.float = 'left'; +// b.style.float = 'left'; +// c.style.float = 'left'; + +// context = canvas.getContext('2d'); +// context.putImageData(diff, 0, 0); + +// a.appendChild(toCanvas(actual)); +// b.appendChild(toCanvas(expected)); +// c.appendChild(canvas); + +// div.appendChild(a); +// div.appendChild(b); +// div.appendChild(c); + +// return div.innerHTML; +// } + +// function formatImageDiffEqualTextReport(actual, expected) { +// return 'Expected to be equal.'; +// } + +export const imagediff = { + createCanvas: getCanvas, + createImageData: getImageData, + + isImage: isImage, + isCanvas: isCanvas, + isContext: isContext, + isImageData: isImageData, + isImageType: isImageType, + + toImageData: function (object) { + checkType(object); + if (isImageData(object)) { + return copyImageData(object); + } + return toImageData(object); + }, + + equal: function (a, b, tolerance, secondTol) { + checkType(a, b); + a = toImageData(a); + b = toImageData(b); + return equal(a, b, tolerance, secondTol); + }, + diff: function (a, b, options?) { + checkType(a, b); + a = toImageData(a); + b = toImageData(b); + return diff(a, b, options); + }, +}; diff --git a/test/unit/shapes/Arc-test.js b/test/unit-new/shapes/Arc-test.ts similarity index 90% rename from test/unit/shapes/Arc-test.js rename to test/unit-new/shapes/Arc-test.ts index 3ab0198a..fb7c7b2b 100644 --- a/test/unit/shapes/Arc-test.js +++ b/test/unit-new/shapes/Arc-test.ts @@ -1,6 +1,10 @@ -suite('Arc', function () { +import { assert } from 'chai'; + +import { addStage, Konva, createCanvas, compareLayerAndCanvas } from '../utis'; + +describe('Arc', function () { // ====================================================== - test('add arc', function () { + it('add arc', function () { var stage = addStage(); var layer = new Konva.Layer(); var arc = new Konva.Arc({ @@ -30,7 +34,7 @@ suite('Arc', function () { }); // ====================================================== - test('attrs sync', function () { + it('attrs sync', function () { var stage = addStage(); var layer = new Konva.Layer(); var arc = new Konva.Arc({ @@ -60,7 +64,7 @@ suite('Arc', function () { assert.equal(arc.getHeight(), 120); }); - test('getSelfRect', function () { + it('getSelfRect', function () { var stage = addStage(); var layer = new Konva.Layer(); var arc = new Konva.Arc({ @@ -87,7 +91,7 @@ suite('Arc', function () { }); }); - test('cache', function () { + it('cache', function () { var stage = addStage(); var layer = new Konva.Layer(); var arc = new Konva.Arc({ diff --git a/test/unit/shapes/Arrow-test.js b/test/unit-new/shapes/Arrow-test.ts similarity index 88% rename from test/unit/shapes/Arrow-test.js rename to test/unit-new/shapes/Arrow-test.ts index 34aaa452..dd2a8690 100644 --- a/test/unit/shapes/Arrow-test.js +++ b/test/unit-new/shapes/Arrow-test.ts @@ -1,6 +1,10 @@ -suite('Arrow', function () { +import { assert } from 'chai'; + +import { addStage, Konva, cloneAndCompareLayer } from '../utis'; + +describe('Arrow', function () { // ====================================================== - test('add arrow', function () { + it('add arrow', function () { var stage = addStage(); var layer = new Konva.Layer(); @@ -16,12 +20,12 @@ suite('Arrow', function () { layer.add(arrow); stage.add(layer); - arrow.setPoints([1, 2, 3, 4]); + arrow.points([1, 2, 3, 4]); assert.equal(arrow.points()[0], 1); - arrow.setPoints([5, 6, 7, 8]); - assert.equal(arrow.getPoints()[0], 5); - arrow.setPoints([73, 160, 340, 23, 50, 100, 80, 50]); + arrow.points([5, 6, 7, 8]); + assert.equal(arrow.points()[0], 5); + arrow.points([73, 160, 340, 23, 50, 100, 80, 50]); arrow.tension(0); arrow.pointerLength(15); @@ -33,10 +37,9 @@ suite('Arrow', function () { assert.equal(arrow.getClassName(), 'Arrow'); layer.draw(); - showHit(layer); }); - test('do not draw dash for head', function () { + it('do not draw dash for head', function () { var stage = addStage(); var layer = new Konva.Layer(); @@ -63,7 +66,7 @@ suite('Arrow', function () { ); }); - test('direction with tension', function () { + it('direction with tension', function () { var stage = addStage(); var layer = new Konva.Layer(); @@ -86,7 +89,7 @@ suite('Arrow', function () { ); }); - test('direction with tension 2', function () { + it('direction with tension 2', function () { var stage = addStage(); var layer = new Konva.Layer(); @@ -110,7 +113,7 @@ suite('Arrow', function () { ); }); - test('test cache', function () { + it('test cache', function () { var stage = addStage(); var layer = new Konva.Layer(); diff --git a/test/unit/shapes/Blob-test.js b/test/unit-new/shapes/Blob-test.ts similarity index 85% rename from test/unit/shapes/Blob-test.js rename to test/unit-new/shapes/Blob-test.ts index 7a9df474..9cf685ec 100644 --- a/test/unit/shapes/Blob-test.js +++ b/test/unit-new/shapes/Blob-test.ts @@ -1,6 +1,11 @@ -suite('Blob', function () { +import { assert } from 'chai'; +import { Line } from '../../../src/shapes/Line'; + +import { addStage, Konva, cloneAndCompareLayer } from '../utis'; + +describe('Blob', function () { // ====================================================== - test('add blob', function () { + it('add blob', function () { var stage = addStage(); var layer = new Konva.Layer(); @@ -17,15 +22,15 @@ suite('Blob', function () { layer.add(blob); stage.add(layer); - assert.equal(blob.getTension(), 0.8); + assert.equal(blob.tension(), 0.8); assert.equal(blob.getClassName(), 'Line'); //console.log(blob1.getPoints()) // test setter - blob.setTension(1.5); - assert.equal(blob.getTension(), 1.5); + blob.tension(1.5); + assert.equal(blob.tension(), 1.5); var trace = layer.getContext().getTrace(); assert.equal( @@ -35,7 +40,7 @@ suite('Blob', function () { }); // ====================================================== - test('define tension first', function () { + it('define tension first', function () { var stage = addStage(); var layer = new Konva.Layer(); @@ -52,11 +57,11 @@ suite('Blob', function () { layer.add(blob); stage.add(layer); - assert.equal(stage.find('Line')[0].getPoints().length, 8); + assert.equal(stage.findOne('Line').points().length, 8); }); // ====================================================== - test('check for konva event handlers', function () { + it('check for konva event handlers', function () { var stage = addStage(); var layer = new Konva.Layer(); @@ -92,7 +97,7 @@ suite('Blob', function () { assert.equal(blob.eventListeners.tensionChange, undefined); }); - test('cache', function () { + it('cache', function () { var stage = addStage(); var layer = new Konva.Layer(); var blob = new Konva.Line({ diff --git a/test/unit/shapes/Circle-test.js b/test/unit-new/shapes/Circle-test.ts similarity index 77% rename from test/unit/shapes/Circle-test.js rename to test/unit-new/shapes/Circle-test.ts index 552a0c87..e0f6d23d 100644 --- a/test/unit/shapes/Circle-test.js +++ b/test/unit-new/shapes/Circle-test.ts @@ -1,7 +1,17 @@ -suite('Circle', function () { +import { assert } from 'chai'; + +import { + addStage, + Konva, + createCanvas, + compareLayerAndCanvas, + loadImage, +} from '../utis'; + +describe('Circle', function () { // ====================================================== - test('add circle to stage', function () { + it('add circle to stage', function () { var stage = addStage(); var layer = new Konva.Layer(); var group = new Konva.Group(); @@ -44,7 +54,7 @@ suite('Circle', function () { ); }); - test('clone', function () { + it('clone', function () { var circle = new Konva.Circle(); var clone = circle.clone(); assert.equal(clone instanceof Konva.Circle, true); @@ -52,15 +62,14 @@ suite('Circle', function () { }); // ====================================================== - test('add circle with pattern fill', function (done) { - var imageObj = new Image(); - imageObj.onload = function () { + it('add circle with pattern fill', function (done) { + loadImage('darth-vader.jpg', (imageObj) => { var stage = addStage(); var layer = new Konva.Layer(); var group = new Konva.Group(); var circle = new Konva.Circle({ - x: stage.getWidth() / 2, - y: stage.getHeight() / 2, + x: stage.width() / 2, + y: stage.height() / 2, radius: 70, fillPatternImage: imageObj, fillPatternOffset: { x: -5, y: -5 }, @@ -75,33 +84,32 @@ suite('Circle', function () { layer.add(group); stage.add(layer); - assert.equal(circle.getFillPatternOffset().x, -5); - assert.equal(circle.getFillPatternOffset().y, -5); + assert.equal(circle.fillPatternOffset().x, -5); + assert.equal(circle.fillPatternOffset().y, -5); - circle.setFillPatternOffset({ x: 1, y: 2 }); - assert.equal(circle.getFillPatternOffset().x, 1); - assert.equal(circle.getFillPatternOffset().y, 2); + circle.fillPatternOffset({ x: 1, y: 2 }); + assert.equal(circle.fillPatternOffset().x, 1); + assert.equal(circle.fillPatternOffset().y, 2); - circle.setFillPatternOffset({ + circle.fillPatternOffset({ x: 3, y: 4, }); - assert.equal(circle.getFillPatternOffset().x, 3); - assert.equal(circle.getFillPatternOffset().y, 4); + assert.equal(circle.fillPatternOffset().x, 3); + assert.equal(circle.fillPatternOffset().y, 4); done(); - }; - imageObj.src = 'assets/darth-vader.jpg'; + }); }); // ====================================================== - test('add circle with radial gradient fill', function () { + it('add circle with radial gradient fill', function () { var stage = addStage(); var layer = new Konva.Layer(); var group = new Konva.Group(); var circle = new Konva.Circle({ - x: stage.getWidth() / 2, - y: stage.getHeight() / 2, + x: stage.width() / 2, + y: stage.height() / 2, radius: 70, fillRadialGradientStartPoint: { x: -20, y: -20 }, fillRadialGradientStartRadius: 0, @@ -120,23 +128,23 @@ suite('Circle', function () { layer.add(group); stage.add(layer); - assert.equal(circle.getFillRadialGradientStartPoint().x, -20); - assert.equal(circle.getFillRadialGradientStartPoint().y, -20); - assert.equal(circle.getFillRadialGradientStartRadius(), 0); - assert.equal(circle.getFillRadialGradientEndPoint().x, -60); - assert.equal(circle.getFillRadialGradientEndPoint().y, -60); - assert.equal(circle.getFillRadialGradientEndRadius(), 130); - assert.equal(circle.getFillRadialGradientColorStops().length, 6); + assert.equal(circle.fillRadialGradientStartPoint().x, -20); + assert.equal(circle.fillRadialGradientStartPoint().y, -20); + assert.equal(circle.fillRadialGradientStartRadius(), 0); + assert.equal(circle.fillRadialGradientEndPoint().x, -60); + assert.equal(circle.fillRadialGradientEndPoint().y, -60); + assert.equal(circle.fillRadialGradientEndRadius(), 130); + assert.equal(circle.fillRadialGradientColorStops().length, 6); }); // ====================================================== - test('add shape with linear gradient fill', function () { + it('add shape with linear gradient fill', function () { var stage = addStage(); var layer = new Konva.Layer(); var group = new Konva.Group(); var circle = new Konva.Circle({ - x: stage.getWidth() / 2, - y: stage.getHeight() / 2, + x: stage.width() / 2, + y: stage.height() / 2, radius: 70, fillLinearGradientStartPoint: { x: -35, y: -35 }, fillLinearGradientEndPoint: { x: 35, y: 35 }, @@ -161,7 +169,7 @@ suite('Circle', function () { // build color stops for (var n = 0; n < colorStops.length; n += 2) { - grd.addColorStop(colorStops[n], colorStops[n + 1]); + grd.addColorStop(colorStops[n] as number, colorStops[n + 1] as string); } ctx.beginPath(); ctx.translate(circle.x(), circle.y()); @@ -178,13 +186,13 @@ suite('Circle', function () { }); // ====================================================== - test('set opacity after instantiation', function () { + it('set opacity after instantiation', function () { var stage = addStage(); var layer = new Konva.Layer(); var group = new Konva.Group(); var circle = new Konva.Circle({ - x: stage.getWidth() / 2, - y: stage.getHeight() / 2, + x: stage.width() / 2, + y: stage.height() / 2, radius: 70, fill: 'red', }); @@ -193,10 +201,10 @@ suite('Circle', function () { layer.add(group); stage.add(layer); - circle.setOpacity(0.5); + circle.opacity(0.5); layer.draw(); - circle.setOpacity(1); + circle.opacity(1); layer.draw(); var trace = layer.getContext().getTrace(); @@ -207,12 +215,12 @@ suite('Circle', function () { }); // ====================================================== - test('attrs sync', function () { + it('attrs sync', function () { var stage = addStage(); var layer = new Konva.Layer(); var circle = new Konva.Circle({ - x: stage.getWidth() / 2, - y: stage.getHeight() / 2, + x: stage.width() / 2, + y: stage.height() / 2, radius: 70, fill: 'green', stroke: 'black', @@ -235,12 +243,12 @@ suite('Circle', function () { }); // ====================================================== - test('set fill after instantiation', function () { + it('set fill after instantiation', function () { var stage = addStage(); var layer = new Konva.Layer(); var circle = new Konva.Circle({ - x: stage.getWidth() / 2, - y: stage.getHeight() / 2, + x: stage.width() / 2, + y: stage.height() / 2, radius: 70, fill: 'green', stroke: 'black', @@ -248,7 +256,7 @@ suite('Circle', function () { }); layer.add(circle); - circle.setFill('blue'); + circle.fill('blue'); stage.add(layer); @@ -259,7 +267,7 @@ suite('Circle', function () { ); }); - test('getSelfRect', function () { + it('getSelfRect', function () { var stage = addStage(); var layer = new Konva.Layer(); var circle = new Konva.Circle({ @@ -283,7 +291,7 @@ suite('Circle', function () { }); }); - test('cache', function () { + it('cache', function () { var stage = addStage(); var layer = new Konva.Layer(); var circle = new Konva.Circle({ diff --git a/test/unit/shapes/Ellipse-test.js b/test/unit-new/shapes/Ellipse-test.ts similarity index 74% rename from test/unit/shapes/Ellipse-test.js rename to test/unit-new/shapes/Ellipse-test.ts index 3c729d78..679e315d 100644 --- a/test/unit/shapes/Ellipse-test.js +++ b/test/unit-new/shapes/Ellipse-test.ts @@ -1,12 +1,17 @@ -suite('Ellipse', function () { +import { assert } from 'chai'; + +import { addStage, Konva, createCanvas, compareLayerAndCanvas } from '../utis'; + +describe('Ellipse', function () { // ====================================================== - test('add ellipse', function () { + it('add ellipse', function () { var stage = addStage(); var layer = new Konva.Layer(); var ellipse = new Konva.Ellipse({ - x: stage.getWidth() / 2, - y: stage.getHeight() / 2, - radius: { x: 70, y: 35 }, + x: stage.width() / 2, + y: stage.height() / 2, + radiusX: 70, + radiusY: 35, fill: 'green', stroke: 'black', strokeWidth: 8, @@ -23,13 +28,14 @@ suite('Ellipse', function () { }); // ====================================================== - test('attrs sync', function () { + it('attrs sync', function () { var stage = addStage(); var layer = new Konva.Layer(); var ellipse = new Konva.Ellipse({ - x: stage.getWidth() / 2, - y: stage.getHeight() / 2, - radius: { x: 70, y: 35 }, + x: stage.width() / 2, + y: stage.height() / 2, + radiusX: 70, + radiusY: 35, fill: 'green', stroke: 'black', strokeWidth: 8, @@ -49,13 +55,14 @@ suite('Ellipse', function () { assert.equal(ellipse.radiusY(), 60); }); - test('getSelfRect', function () { + it('getSelfRect', function () { var stage = addStage(); var layer = new Konva.Layer(); var ellipse = new Konva.Ellipse({ - x: stage.getWidth() / 2, - y: stage.getHeight() / 2, - radius: { x: 70, y: 35 }, + x: stage.width() / 2, + y: stage.height() / 2, + radiusX: 70, + radiusY: 35, fill: 'green', stroke: 'black', strokeWidth: 8, @@ -71,13 +78,14 @@ suite('Ellipse', function () { }); }); - test('cache', function () { + it('cache', function () { var stage = addStage(); var layer = new Konva.Layer(); var ellipse = new Konva.Ellipse({ - x: stage.getWidth() / 2, - y: stage.getHeight() / 2, - radius: { x: 70, y: 35 }, + x: stage.width() / 2, + y: stage.height() / 2, + radiusX: 70, + radiusY: 35, fill: 'green', stroke: 'black', strokeWidth: 8, @@ -91,14 +99,7 @@ suite('Ellipse', function () { context.save(); context.beginPath(); context.scale(1, 0.5); - context.arc( - stage.getWidth() / 2, - stage.getHeight(), - 70, - 0, - Math.PI * 2, - false - ); + context.arc(stage.width() / 2, stage.height(), 70, 0, Math.PI * 2, false); context.closePath(); context.restore(); context.fillStyle = 'green'; diff --git a/test/unit-new/shapes/Image-test.ts b/test/unit-new/shapes/Image-test.ts new file mode 100644 index 00000000..bebbb444 --- /dev/null +++ b/test/unit-new/shapes/Image-test.ts @@ -0,0 +1,347 @@ +import { assert } from 'chai'; + +import { + addStage, + Konva, + createCanvas, + compareLayerAndCanvas, + loadImage, + isNode, + isBrowser, +} from '../utis'; + +describe('Image', function () { + // ====================================================== + it('add image', function (done) { + loadImage('darth-vader.jpg', (imageObj) => { + var stage = addStage(); + + var layer = new Konva.Layer(); + var darth = new Konva.Image({ + x: 200, + y: 60, + image: imageObj, + width: 100, + height: 100, + offset: { x: 50, y: 30 }, + crop: { x: 135, y: 7, width: 167, height: 134 }, + draggable: true, + }); + + layer.add(darth); + stage.add(layer); + + darth.width(200); + layer.draw(); + + darth.width(100); + layer.draw(); + + assert.equal(darth.x(), 200); + assert.equal(darth.y(), 60); + assert.equal(darth.getWidth(), 100); + assert.equal(darth.getHeight(), 100); + assert.equal(darth.offset().x, 50); + assert.equal(darth.offset().y, 30); + + var crop = null; + crop = darth.crop(); + + assert.equal(crop.x, 135); + assert.equal(crop.y, 7); + assert.equal(crop.width, 167); + assert.equal(crop.height, 134); + + darth.crop({ + x: 8, + y: 9, + width: 10, + height: 11, + }); + crop = darth.crop(); + assert.equal(crop.x, 8); + assert.equal(crop.y, 9); + assert.equal(crop.width, 10); + assert.equal(crop.height, 11); + + darth.cropX(12); + crop = darth.crop(); + assert.equal(crop.x, 12); + assert.equal(crop.y, 9); + assert.equal(crop.width, 10); + assert.equal(crop.height, 11); + + darth.cropY(13); + crop = darth.crop(); + assert.equal(crop.x, 12); + assert.equal(crop.y, 13); + assert.equal(crop.width, 10); + assert.equal(crop.height, 11); + + darth.cropWidth(14); + crop = darth.crop(); + assert.equal(crop.x, 12); + assert.equal(crop.y, 13); + assert.equal(crop.width, 14); + assert.equal(crop.height, 11); + + darth.cropHeight(15); + crop = darth.crop(); + assert.equal(crop.x, 12); + assert.equal(crop.y, 13); + assert.equal(crop.width, 14); + assert.equal(crop.height, 15); + + darth.setAttrs({ + x: 200, + y: 60, + image: imageObj, + width: 100, + height: 100, + offsetX: 50, + offsetY: 30, + crop: { x: 135, y: 7, width: 167, height: 134 }, + draggable: true, + }); + + assert.equal(darth.getClassName(), 'Image'); + + var trace = layer.getContext().getTrace(); + + if (isBrowser) { + assert.equal( + trace, + 'clearRect(0,0,578,200);save();transform(1,0,0,1,150,30);drawImage([object HTMLImageElement],135,7,167,134,0,0,100,100);restore();clearRect(0,0,578,200);save();transform(1,0,0,1,150,30);drawImage([object HTMLImageElement],135,7,167,134,0,0,200,100);restore();clearRect(0,0,578,200);save();transform(1,0,0,1,150,30);drawImage([object HTMLImageElement],135,7,167,134,0,0,100,100);restore();' + ); + } else { + assert.equal( + trace, + 'clearRect(0,0,578,200);save();transform(1,0,0,1,150,30);drawImage([object Object],135,7,167,134,0,0,100,100);restore();clearRect(0,0,578,200);save();transform(1,0,0,1,150,30);drawImage([object Object],135,7,167,134,0,0,200,100);restore();clearRect(0,0,578,200);save();transform(1,0,0,1,150,30);drawImage([object Object],135,7,167,134,0,0,100,100);restore();' + ); + } + + done(); + }); + }); + + // ====================================================== + it('crop and scale image', function (done) { + loadImage('darth-vader.jpg', (imageObj) => { + var stage = addStage(); + var layer = new Konva.Layer(); + var darth = new Konva.Image({ + x: 200, + y: 75, + image: imageObj, + width: 107, + height: 75, + crop: { x: 186, y: 211, width: 106, height: 74 }, + draggable: true, + scale: { x: 0.5, y: 0.5 }, + }); + + layer.add(darth); + stage.add(layer); + + assert.equal(darth.crop().x, 186); + assert.equal(darth.crop().y, 211); + assert.equal(darth.crop().width, 106); + assert.equal(darth.crop().height, 74); + + assert.equal(darth.cropX(), 186); + assert.equal(darth.cropY(), 211); + assert.equal(darth.cropWidth(), 106); + assert.equal(darth.cropHeight(), 74); + + darth.crop({ x: 1, y: 2, width: 3, height: 4 }); + + assert.equal(darth.crop().x, 1); + assert.equal(darth.crop().y, 2); + assert.equal(darth.crop().width, 3); + assert.equal(darth.crop().height, 4); + + assert.equal(darth.cropX(), 1); + assert.equal(darth.cropY(), 2); + assert.equal(darth.cropWidth(), 3); + assert.equal(darth.cropHeight(), 4); + + darth.cropX(5); + darth.cropY(6); + darth.cropWidth(7); + darth.cropHeight(8); + + assert.equal(darth.crop().x, 5); + assert.equal(darth.crop().y, 6); + assert.equal(darth.crop().width, 7); + assert.equal(darth.crop().height, 8); + + assert.equal(darth.cropX(), 5); + assert.equal(darth.cropY(), 6); + assert.equal(darth.cropWidth(), 7); + assert.equal(darth.cropHeight(), 8); + + done(); + }); + }); + + // ====================================================== + it('image with opacity and shadow', function (done) { + loadImage('darth-vader.jpg', (imageObj) => { + var stage = addStage(); + + var layer = new Konva.Layer(); + var darth = new Konva.Image({ + x: 200, + y: 60, + image: imageObj, + width: 100, + height: 100, + offset: { x: 50, y: 30 }, + draggable: true, + opacity: 0.5, + shadowColor: 'black', + shadowBlur: 10, + shadowOpacity: 0.1, + shadowOffset: { x: 20, y: 20 }, + }); + + layer.add(darth); + stage.add(layer); + + var trace = layer.getContext().getTrace(); + + if (isBrowser) { + assert.equal( + trace, + 'clearRect(0,0,578,200);save();transform(1,0,0,1,150,30);globalAlpha=0.5;shadowColor=rgba(0,0,0,0.1);shadowBlur=10;shadowOffsetX=20;shadowOffsetY=20;drawImage([object HTMLImageElement],0,0,100,100);restore();' + ); + } else { + assert.equal( + trace, + 'clearRect(0,0,578,200);save();transform(1,0,0,1,150,30);globalAlpha=0.5;shadowColor=rgba(0,0,0,0.1);shadowBlur=10;shadowOffsetX=20;shadowOffsetY=20;drawImage([object Object],0,0,100,100);restore();' + ); + } + + done(); + }); + }); + + // ====================================================== + it('image with stroke, opacity and shadow', function (done) { + loadImage('darth-vader.jpg', (imageObj) => { + var stage = addStage(); + + var layer = new Konva.Layer(); + var darth = new Konva.Image({ + x: 200, + y: 60, + image: imageObj, + width: 100, + height: 100, + offset: { x: 50, y: 30 }, + draggable: true, + opacity: 0.5, + shadowColor: 'black', + shadowBlur: 10, + shadowOpacity: 0.5, + shadowOffset: { x: 20, y: 20 }, + stroke: 'red', + strokeWidth: 20, + }); + + layer.add(darth); + stage.add(layer); + + var trace = layer.getContext().getTrace(); + + if (isBrowser) { + assert.equal( + trace, + 'clearRect(0,0,578,200);save();shadowColor=rgba(0,0,0,0.5);shadowBlur=10;shadowOffsetX=20;shadowOffsetY=20;globalAlpha=0.5;drawImage([object HTMLCanvasElement],0,0,578,200);restore();' + ); + } else { + assert.equal( + trace, + 'clearRect(0,0,578,200);save();shadowColor=rgba(0,0,0,0.5);shadowBlur=10;shadowOffsetX=20;shadowOffsetY=20;globalAlpha=0.5;drawImage([object Object],0,0,578,200);restore();' + ); + } + + done(); + }); + }); + + // ====================================================== + it('image caching', function (done) { + loadImage('darth-vader.jpg', (imageObj) => { + var stage = addStage(); + var layer = new Konva.Layer(); + var darth = new Konva.Image({ + x: 200, + y: 60, + image: imageObj, + width: 100, + height: 100, + draggable: true, + }); + + darth.cache(); + layer.add(darth); + stage.add(layer); + + assert.deepEqual(darth.getSelfRect(), { + x: 0, + y: 0, + width: 100, + height: 100, + }); + + var canvas = createCanvas(); + var context = canvas.getContext('2d'); + context.drawImage(imageObj, 200, 60, 100, 100); + compareLayerAndCanvas(layer, canvas, 10); + done(); + }); + }); + + it('image loader', function (done) { + if (isNode) { + done(); + return; + } + loadImage('darth-vader.jpg', (img) => { + var stage = addStage(); + var layer = new Konva.Layer(); + stage.add(layer); + var src = img.src; + Konva.Image.fromURL(src, function (image) { + layer.add(image); + layer.draw(); + assert.equal(image instanceof Konva.Image, true); + var nativeImg = image.image(); + assert.equal(nativeImg instanceof Image, true); + assert.equal(nativeImg.src.indexOf(src) !== -1, true); + assert.equal(nativeImg.complete, true); + done(); + }); + }); + }); + + it('check zero values', function (done) { + loadImage('darth-vader.jpg', (imageObj) => { + var stage = addStage(); + var layer = new Konva.Layer(); + stage.add(layer); + + const image = new Konva.Image({ image: imageObj }); + layer.add(image); + + image.width(0); + image.height(0); + layer.draw(); + + assert.equal(image.width(), 0); + assert.equal(image.height(), 0); + done(); + }); + }); +}); diff --git a/test/unit/shapes/Label-test.js b/test/unit-new/shapes/Label-test.ts similarity index 73% rename from test/unit/shapes/Label-test.js rename to test/unit-new/shapes/Label-test.ts index 547d4a86..d7e5cc26 100644 --- a/test/unit/shapes/Label-test.js +++ b/test/unit-new/shapes/Label-test.ts @@ -1,6 +1,10 @@ -suite('Label', function () { +import { assert } from 'chai'; + +import { addStage, Konva, cloneAndCompareLayer, isBrowser } from '../utis'; + +describe('Label', function () { // ====================================================== - test('add label', function () { + it('add label', function () { var stage = addStage(); var layer = new Konva.Layer(); @@ -42,11 +46,11 @@ suite('Label', function () { layer.add(label); stage.add(layer); - label.getText().setFontSize(100); + label.getText().fontSize(100); - label.getText().setFontSize(50); + label.getText().fontSize(50); - label.getText().setText('Hello big world'); + label.getText().text('Hello big world'); layer.draw(); @@ -55,15 +59,15 @@ suite('Label', function () { // use relaxed trace because text can be a slightly different size in different browsers, // resulting in slightly different tag dimensions - var trace = layer.getContext().getTrace(); + var trace = layer.getContext().getTrace(true); assert.equal( trace, - 'clearRect(0,0,578,200);save();lineJoin=round;transform(1,0,0,1,100,120);shadowColor=rgba(0,0,0,0.2);shadowBlur=10;shadowOffsetX=10;shadowOffsetY=10;beginPath();moveTo(0,0);lineTo(-10,0);lineTo(0,-20);lineTo(10,0);lineTo(0,0);arc(0,0,0,4.712,0,false);lineTo(0,60);arc(0,60,0,0,1.571,false);lineTo(0,60);arc(0,60,0,1.571,3.142,false);lineTo(0,0);arc(0,0,0,3.142,4.712,false);closePath();fillStyle=#bbb;fill();restore();save();transform(1,0,0,1,100,120);restore();clearRect(0,0,578,200);save();lineJoin=round;transform(1,0,0,1,-63.965,120);shadowColor=rgba(0,0,0,0.2);shadowBlur=10;shadowOffsetX=10;shadowOffsetY=10;beginPath();moveTo(5,0);lineTo(153.965,0);lineTo(163.965,-20);lineTo(173.965,0);lineTo(322.93,0);arc(322.93,5,5,4.712,0,false);lineTo(327.93,55);arc(322.93,55,5,0,1.571,false);lineTo(5,60);arc(5,55,5,1.571,3.142,false);lineTo(0,5);arc(5,5,5,3.142,4.712,false);closePath();fillStyle=#bbb;fill();restore();save();transform(1,0,0,1,-63.965,120);font=normal normal 50px Arial;textBaseline=middle;textAlign=left;translate(0,0);save();fillStyle=green;fillText(Hello big world,0,30);restore();restore();' + 'clearRect();save();lineJoin;transform();shadowColor;shadowBlur;shadowOffsetX;shadowOffsetY;beginPath();moveTo();lineTo();lineTo();lineTo();lineTo();arc();lineTo();arc();lineTo();arc();lineTo();arc();closePath();fillStyle;fill();restore();save();transform();restore();clearRect();save();lineJoin;transform();shadowColor;shadowBlur;shadowOffsetX;shadowOffsetY;beginPath();moveTo();lineTo();lineTo();lineTo();lineTo();arc();lineTo();arc();lineTo();arc();lineTo();arc();closePath();fillStyle;fill();restore();save();transform();font;textBaseline;textAlign;translate();save();fillStyle;fillText();restore();restore();' ); }); // ====================================================== - test('create label from json', function () { + it('create label from json', function () { var stage = addStage(); var json = @@ -77,13 +81,20 @@ suite('Label', function () { var trace = layer.getContext().getTrace(); - assert.equal( - trace, - 'clearRect(0,0,578,200);save();lineJoin=round;transform(1,0,0,1,-63.965,120);shadowColor=rgba(0,0,0,0.2);shadowBlur=10;shadowOffsetX=10;shadowOffsetY=10;beginPath();moveTo(5,0);lineTo(153.965,0);lineTo(163.965,-20);lineTo(173.965,0);lineTo(322.93,0);arc(322.93,5,5,4.712,0,false);lineTo(327.93,55);arc(322.93,55,5,0,1.571,false);lineTo(5,60);arc(5,55,5,1.571,3.142,false);lineTo(0,5);arc(5,5,5,3.142,4.712,false);closePath();fillStyle=#bbb;fill();restore();save();transform(1,0,0,1,-63.965,120);font=normal normal 50px Arial;textBaseline=middle;textAlign=left;translate(0,0);save();fillStyle=green;fillText(Hello big world,0,30);restore();restore();' - ); + if (isBrowser) { + assert.equal( + trace, + 'clearRect(0,0,578,200);save();lineJoin=round;transform(1,0,0,1,-63.965,120);shadowColor=rgba(0,0,0,0.2);shadowBlur=10;shadowOffsetX=10;shadowOffsetY=10;beginPath();moveTo(5,0);lineTo(153.965,0);lineTo(163.965,-20);lineTo(173.965,0);lineTo(322.93,0);arc(322.93,5,5,4.712,0,false);lineTo(327.93,55);arc(322.93,55,5,0,1.571,false);lineTo(5,60);arc(5,55,5,1.571,3.142,false);lineTo(0,5);arc(5,5,5,3.142,4.712,false);closePath();fillStyle=#bbb;fill();restore();save();transform(1,0,0,1,-63.965,120);font=normal normal 50px Arial;textBaseline=middle;textAlign=left;translate(0,0);save();fillStyle=green;fillText(Hello big world,0,30);restore();restore();' + ); + } else { + assert.equal( + trace, + 'clearRect(0,0,578,200);save();lineJoin=round;transform(1,0,0,1,-64.5,120);shadowColor=rgba(0,0,0,0.2);shadowBlur=10;shadowOffsetX=10;shadowOffsetY=10;beginPath();moveTo(5,0);lineTo(154.5,0);lineTo(164.5,-20);lineTo(174.5,0);lineTo(324,0);arc(324,5,5,4.712,0,false);lineTo(329,55);arc(324,55,5,0,1.571,false);lineTo(5,60);arc(5,55,5,1.571,3.142,false);lineTo(0,5);arc(5,5,5,3.142,4.712,false);closePath();fillStyle=#bbb;fill();restore();save();transform(1,0,0,1,-64.5,120);font=normal normal 50px Arial;textBaseline=middle;textAlign=left;translate(0,0);save();fillStyle=green;fillText(Hello big world,0,30);restore();restore();' + ); + } }); - test('find label class', function () { + it('find label class', function () { var stage = addStage(); var layer = new Konva.Layer(); @@ -114,7 +125,7 @@ suite('Label', function () { }); // caching doesn't give exactly the same result. WHY? - test.skip('cache label', function () { + it.skip('cache label', function () { var stage = addStage(); var layer = new Konva.Layer(); @@ -245,14 +256,14 @@ suite('Label', function () { ); // add the labels to layer layer.add(tooltip, tooltipUp, labelLeft, labelRight, simpleLabel); - layer.children.cache(); + layer.children.forEach((child) => child.cache()); stage.add(layer); cloneAndCompareLayer(layer, 250); }); - test('tag should list text size changes', function () { + it('tag should list text size changes', function () { var stage = addStage(); var layer = new Konva.Layer(); stage.add(layer); @@ -282,7 +293,7 @@ suite('Label', function () { assert.equal(tag.height(), text.height()); }); - test('tag cornerRadius', function () { + it('tag cornerRadius', function () { var stage = addStage(); var layer = new Konva.Layer(); diff --git a/test/unit/shapes/Line-test.js b/test/unit-new/shapes/Line-test.ts similarity index 91% rename from test/unit/shapes/Line-test.js rename to test/unit-new/shapes/Line-test.ts index 4665b4bb..c24ba3a7 100644 --- a/test/unit/shapes/Line-test.js +++ b/test/unit-new/shapes/Line-test.ts @@ -1,6 +1,16 @@ -suite('Line', function () { +import { assert } from 'chai'; + +import { + addStage, + Konva, + createCanvas, + compareLayerAndCanvas, + compareLayers, +} from '../utis'; + +describe('Line', function () { // ====================================================== - test('add line', function () { + it('add line', function () { var stage = addStage(); var layer = new Konva.Layer(); @@ -16,23 +26,22 @@ suite('Line', function () { layer.add(line); stage.add(layer); - line.setPoints([1, 2, 3, 4]); - assert.equal(line.getPoints()[0], 1); + line.points([1, 2, 3, 4]); + assert.equal(line.points()[0], 1); - line.setPoints([5, 6, 7, 8]); - assert.equal(line.getPoints()[0], 5); + line.points([5, 6, 7, 8]); + assert.equal(line.points()[0], 5); - line.setPoints([73, 160, 340, 23, 340, 80]); - assert.equal(line.getPoints()[0], 73); + line.points([73, 160, 340, 23, 340, 80]); + assert.equal(line.points()[0], 73); assert.equal(line.getClassName(), 'Line'); layer.draw(); - showHit(layer); }); // ====================================================== - test('test default ponts array for two lines', function () { + it('test default ponts array for two lines', function () { var stage = addStage(); var layer = new Konva.Layer(); @@ -53,18 +62,18 @@ suite('Line', function () { draggable: true, }); - line.setPoints([0, 1, 2, 3]); - redLine.setPoints([4, 5, 6, 7]); + line.points([0, 1, 2, 3]); + redLine.points([4, 5, 6, 7]); layer.add(line).add(redLine); stage.add(layer); - assert.equal(line.getPoints()[0], 0); - assert.equal(redLine.getPoints()[0], 4); + assert.equal(line.points()[0], 0); + assert.equal(redLine.points()[0], 4); }); // ====================================================== - test('add dashed line', function () { + it('add dashed line', function () { var stage = addStage(); var layer = new Konva.Layer(); @@ -109,11 +118,12 @@ suite('Line', function () { line.dash([10, 10]); assert.equal(line.dash().length, 2); - assert.equal(line.getPoints().length, 8); + assert.equal(line.points().length, 8); }); // ====================================================== - test('add line with shadow', function () { + it('add line with shadow', function () { + const oldRatio = Konva.pixelRatio; Konva.pixelRatio = 1; var stage = addStage(); var layer = new Konva.Layer(); @@ -157,7 +167,7 @@ suite('Line', function () { // context.fill(); context.restore(); - Konva.pixelRatio = undefined; + Konva.pixelRatio = oldRatio; compareLayerAndCanvas(layer, canvas, 50); @@ -169,7 +179,7 @@ suite('Line', function () { ); }); - test('line hit test with strokeScaleEnabled = false', function () { + it('line hit test with strokeScaleEnabled = false', function () { var stage = addStage(); var scale = 0.1; var layer = new Konva.Layer(); @@ -200,7 +210,6 @@ suite('Line', function () { layer.add(group); stage.add(layer); - showHit(layer); var shape = layer.getIntersection({ x: 10, @@ -215,7 +224,7 @@ suite('Line', function () { assert.equal(shape, line1, 'first line detected'); }); - test('line get size', function () { + it('line get size', function () { var stage = addStage(); var layer = new Konva.Layer(); @@ -235,7 +244,7 @@ suite('Line', function () { }); }); - test('getSelfRect', function () { + it('getSelfRect', function () { var stage = addStage(); var layer = new Konva.Layer(); var blob = new Konva.Line({ @@ -260,7 +269,7 @@ suite('Line', function () { }); }); - test('getClientRect', function () { + it('getClientRect', function () { var stage = addStage(); var layer = new Konva.Layer(); @@ -280,7 +289,7 @@ suite('Line', function () { layer.add(poly); stage.add(layer); - var rect = layer.getClientRect({ relativeTo: stage }); + var rect = layer.getClientRect({ relativeTo: stage as any }); assert.deepEqual(rect, { x: -100, y: 0, @@ -289,7 +298,7 @@ suite('Line', function () { }); }); - test('getClientRect with tension', function () { + it('getClientRect with tension', function () { var stage = addStage(); stage.draggable(true); var layer = new Konva.Layer(); @@ -315,7 +324,7 @@ suite('Line', function () { assert.equal(Math.round(client.height), 147, 'check height'); }); - test('getClientRect with tension 2', function () { + it('getClientRect with tension 2', function () { var stage = addStage(); stage.draggable(true); var layer = new Konva.Layer(); @@ -566,7 +575,7 @@ suite('Line', function () { assert.equal(Math.round(client.height), 597, 'check height'); }); - test('getClientRect with low number of points', function () { + it('getClientRect with low number of points', function () { var stage = addStage(); var layer = new Konva.Layer(); stage.add(layer); @@ -597,8 +606,7 @@ suite('Line', function () { assert.equal(client.height, 2, 'check height'); }); - test('line caching', function () { - // Konva.pixelRatio = 1; + it('line caching', function () { var stage = addStage(); var layer = new Konva.Layer(); var blob = new Konva.Line({ @@ -620,10 +628,9 @@ suite('Line', function () { stage.add(layer2); layer2.hide(); compareLayers(layer, layer2, 150); - // Konva.pixelRatio = undefined; }); - test('updating points with old mutable array should trigger recalculations', function () { + it('updating points with old mutable array should trigger recalculations', function () { var stage = addStage(); var layer = new Konva.Layer(); @@ -641,7 +648,7 @@ suite('Line', function () { var tensionPoints = blob.getTensionPoints(); points.push(250, 100); - blob.setPoints(points); + blob.points(points); layer.add(blob); stage.add(layer); @@ -653,7 +660,7 @@ suite('Line', function () { ); }); - test('hit test for scaled line', function () { + it('hit test for scaled line', function () { var stage = addStage(); var scale = 42; stage.scaleX(scale); @@ -679,7 +686,7 @@ suite('Line', function () { layer.toggleHitCanvas(); }); - test('getClientRect with scaling', function () { + it('getClientRect with scaling', function () { var stage = addStage(); var scale = 42; stage.scaleX(scale); diff --git a/test/unit/shapes/Path-test.js b/test/unit-new/shapes/Path-test.ts similarity index 81% rename from test/unit/shapes/Path-test.js rename to test/unit-new/shapes/Path-test.ts index fb1cf669..ca093fc2 100644 --- a/test/unit/shapes/Path-test.js +++ b/test/unit-new/shapes/Path-test.ts @@ -1,6 +1,20 @@ -suite('Path', function () { +import { assert } from 'chai'; + +import worldMap from '../../assets/worldMap'; +import tiger from '../../assets/tiger'; + +import { + addStage, + Konva, + createCanvas, + compareLayerAndCanvas, + cloneAndCompareLayer, + isNode, +} from '../utis'; + +describe('Path', function () { // ====================================================== - test('add simple path', function () { + it('add simple path', function () { var stage = addStage(); var layer = new Konva.Layer(); @@ -18,12 +32,12 @@ suite('Path', function () { }); path.on('mouseover', function () { - this.setFill('red'); + this.fill('red'); layer.draw(); }); path.on('mouseout', function () { - this.setFill('#ccc'); + this.fill('#ccc'); layer.draw(); }); @@ -31,21 +45,21 @@ suite('Path', function () { stage.add(layer); - assert.equal(path.getData(), 'M200,100h100v50z'); + assert.equal(path.data(), 'M200,100h100v50z'); assert.equal(path.dataArray.length, 4); - path.setData('M200'); + path.data('M200'); - assert.equal(path.getData(), 'M200'); + assert.equal(path.data(), 'M200'); assert.equal(path.dataArray.length, 1); - path.setData('M200,100h100v50z'); + path.data('M200,100h100v50z'); assert.equal(path.getClassName(), 'Path'); }); // ====================================================== - test('add path with line cap and line join', function () { + it('add path with line cap and line join', function () { var stage = addStage(); var layer = new Konva.Layer(); @@ -71,7 +85,7 @@ suite('Path', function () { }); //======================================================= - test('add path with double closed path and releative moveto', function () { + it('add path with double closed path and releative moveto', function () { var stage = addStage(); var layer = new Konva.Layer(); @@ -97,7 +111,7 @@ suite('Path', function () { }); //======================================================= - test('complex path made of many different closed and open paths (Sopwith Camel)', function () { + it('complex path made of many different closed and open paths (Sopwith Camel)', function () { var stage = addStage(); var layer = new Konva.Layer(); @@ -123,7 +137,7 @@ suite('Path', function () { }); //======================================================= - test('complex path made of many different closed and open paths (Sopwith Camel) cached', function () { + it('complex path made of many different closed and open paths (Sopwith Camel) cached', function () { var stage = addStage(); var layer = new Konva.Layer(); @@ -145,11 +159,10 @@ suite('Path', function () { layer.draw(); // layer.draw(); cloneAndCompareLayer(layer, 230); - showHit(layer); }); // ====================================================== - test('moveTo with implied lineTos and trailing comma', function () { + it('moveTo with implied lineTos and trailing comma', function () { var stage = addStage(); var layer = new Konva.Layer(); @@ -166,12 +179,12 @@ suite('Path', function () { }); path.on('mouseover', function () { - this.setFill('red'); + this.fill('red'); layer.draw(); }); path.on('mouseout', function () { - this.setFill('#ccc'); + this.fill('#ccc'); layer.draw(); }); @@ -179,7 +192,7 @@ suite('Path', function () { stage.add(layer); - assert.equal(path.getData(), 'm200,100,100,0,0,50,-100,0z'); + assert.equal(path.data(), 'm200,100,100,0,0,50,-100,0z'); assert.equal(path.dataArray.length, 5); assert.equal(path.dataArray[1].command, 'L'); @@ -195,16 +208,16 @@ suite('Path', function () { context.closePath(); context.fillStyle = '#fcc'; context.shadowColor = 'maroon'; - context.shadowBlur = 2 * canvas.ratio; - context.shadowOffsetX = 10 * canvas.ratio; - context.shadowOffsetY = 10 * canvas.ratio; + context.shadowBlur = 2 * Konva.pixelRatio; + context.shadowOffsetX = 10 * Konva.pixelRatio; + context.shadowOffsetY = 10 * Konva.pixelRatio; context.fill(); // context.stroke(); compareLayerAndCanvas(layer, canvas, 20); }); // ====================================================== - test('add map path', function () { + it('add map path', function () { var stage = addStage(); var mapLayer = new Konva.Layer(); @@ -223,12 +236,12 @@ suite('Path', function () { } path.on('mouseover', function () { - this.setFill('red'); + this.fill('red'); mapLayer.drawScene(); }); path.on('mouseout', function () { - this.setFill('#ccc'); + this.fill('#ccc'); mapLayer.drawScene(); }); @@ -241,7 +254,7 @@ suite('Path', function () { }); // ====================================================== - test('curved arrow path', function () { + it('curved arrow path', function () { var stage = addStage(); var layer = new Konva.Layer(); @@ -256,12 +269,12 @@ suite('Path', function () { }); path.on('mouseover', function () { - this.setFill('red'); + this.fill('red'); layer.draw(); }); path.on('mouseout', function () { - this.setFill('#ccc'); + this.fill('#ccc'); layer.draw(); }); @@ -277,7 +290,7 @@ suite('Path', function () { }); // ====================================================== - test('Quadradic Curve test from SVG w3c spec', function () { + it('Quadradic Curve test from SVG w3c spec', function () { var stage = addStage(); var layer = new Konva.Layer(); @@ -345,10 +358,16 @@ suite('Path', function () { ); stage.add(layer); + + var trace = layer.getContext().getTrace(); + assert.equal( + trace, + 'clearRect(0,0,578,200);save();transform(1,0,0,1,0,0);beginPath();moveTo(200,300);quadraticCurveTo(400,50,600,300);quadraticCurveTo(800,550,1000,300);lineWidth=5;strokeStyle=red;stroke();restore();save();transform(1,0,0,1,200,300);beginPath();arc(0,0,10,0,6.283,false);closePath();fillStyle=black;fill();restore();save();transform(1,0,0,1,600,300);beginPath();arc(0,0,10,0,6.283,false);closePath();fillStyle=black;fill();restore();save();transform(1,0,0,1,1000,300);beginPath();arc(0,0,10,0,6.283,false);closePath();fillStyle=black;fill();restore();save();transform(1,0,0,1,400,50);beginPath();arc(0,0,10,0,6.283,false);closePath();fillStyle=#888;fill();restore();save();transform(1,0,0,1,800,550);beginPath();arc(0,0,10,0,6.283,false);closePath();fillStyle=#888;fill();restore();save();transform(1,0,0,1,0,0);beginPath();moveTo(200,300);lineTo(400,50);lineTo(600,300);lineTo(800,550);lineTo(1000,300);lineWidth=2;strokeStyle=#888;stroke();restore();' + ); }); // ====================================================== - test('Cubic Bezier Curve test from SVG w3c spec using setData', function () { + it('Cubic Bezier Curve test from SVG w3c spec using data', function () { var stage = addStage(); var layer = new Konva.Layer(); @@ -359,7 +378,7 @@ suite('Path', function () { strokeWidth: 5, }); - path.setData(c); + path.data(c); layer.add(path); @@ -427,10 +446,16 @@ suite('Path', function () { ); stage.add(layer); + + var trace = layer.getContext().getTrace(); + assert.equal( + trace, + 'clearRect(0,0,578,200);save();transform(1,0,0,1,0,0);beginPath();moveTo(100,200);bezierCurveTo(100,100,250,100,250,200);bezierCurveTo(250,300,400,300,400,200);lineWidth=5;strokeStyle=red;stroke();restore();save();transform(1,0,0,1,100,200);beginPath();arc(0,0,10,0,6.283,false);closePath();lineWidth=2;strokeStyle=#888;stroke();restore();save();transform(1,0,0,1,250,200);beginPath();arc(0,0,10,0,6.283,false);closePath();lineWidth=2;strokeStyle=#888;stroke();restore();save();transform(1,0,0,1,400,200);beginPath();arc(0,0,10,0,6.283,false);closePath();lineWidth=2;strokeStyle=#888;stroke();restore();save();transform(1,0,0,1,100,100);beginPath();arc(0,0,10,0,6.283,false);closePath();fillStyle=#888;fill();restore();save();transform(1,0,0,1,250,100);beginPath();arc(0,0,10,0,6.283,false);closePath();fillStyle=#888;fill();restore();save();transform(1,0,0,1,400,300);beginPath();arc(0,0,10,0,6.283,false);closePath();fillStyle=#888;fill();restore();save();transform(1,0,0,1,250,300);beginPath();arc(0,0,10,0,6.283,false);closePath();lineWidth=2;strokeStyle=blue;stroke();restore();' + ); }); // ====================================================== - test('path arc', function () { + it('path arc', function () { var stage = addStage(); var layer = new Konva.Layer(); @@ -445,21 +470,27 @@ suite('Path', function () { }); path.on('mouseover', function () { - this.setFill('red'); + this.fill('red'); layer.draw(); }); path.on('mouseout', function () { - this.setFill('none'); + this.fill('none'); layer.draw(); }); layer.add(path); stage.add(layer); + + var trace = layer.getContext().getTrace(); + assert.equal( + trace, + 'clearRect(0,0,578,200);save();transform(1,0,0,1,0,0);beginPath();moveTo(100,350);lineTo(150,325);translate(175,312.5);rotate(-0.524);scale(1,1);arc(0,0,27.951,-3.082,0.06,0);scale(1,1);rotate(0.524);translate(-175,-312.5);lineTo(250,275);translate(275,262.5);rotate(-0.524);scale(0.5,1);arc(0,0,55.826,-3.112,0.03,0);scale(2,1);rotate(0.524);translate(-275,-262.5);lineTo(350,225);translate(375,212.5);rotate(-0.524);scale(0.333,1);arc(0,0,83.719,-3.122,0.02,0);scale(3,1);rotate(0.524);translate(-375,-212.5);lineTo(450,175);translate(475,162.5);rotate(-0.524);scale(0.25,1);arc(0,0,111.615,-3.127,0.015,0);scale(4,1);rotate(0.524);translate(-475,-162.5);lineTo(550,125);fillStyle=none;fill();lineWidth=1;strokeStyle=#999;stroke();restore();' + ); }); // ====================================================== - test('Tiger (RAWR!)', function () { + it('Tiger (RAWR!)', function () { this.timeout(5000); var stage = addStage(); var layer = new Konva.Layer(); @@ -474,11 +505,15 @@ suite('Path', function () { layer.add(group); stage.add(layer); - showHit(layer); + var trace = layer.getContext().getTrace(); + assert.equal( + trace, + 'moveTo(-44.4,313.001);bezierCurveTo(-44.4,313.001,-32.8,290.601,-54.6,316.401);bezierCurveTo(-54.6,316.401,-43.6,306.601,-44.4,313.001);closePath();fillStyle=#cccccc;fill();restore();save();transform(1,0,0,1,0,0);beginPath();moveTo(-59.8,298.401);bezierCurveTo(-59.8,298.401,-55,279.601,-52.4,279.801);bezierCurveTo(-52.4,279.801,-44.2,270.801,-50.8,281.401);bezierCurveTo(-50.8,281.401,-56.8,291.001,-56.2,300.801);bezierCurveTo(-56.2,300.801,-56.8,291.201,-59.8,298.401);closePath();fillStyle=#cccccc;fill();restore();save();transform(1,0,0,1,0,0);beginPath();moveTo(270.5,287);bezierCurveTo(270.5,287,258.5,277,256,273.5);bezierCurveTo(256,273.5,269.5,292,269.5,299);bezierCurveTo(269.5,299,272,291.5,270.5,287);closePath();fillStyle=#cccccc;fill();restore();save();transform(1,0,0,1,0,0);beginPath();moveTo(276,265);bezierCurveTo(276,265,255,250,251.5,242.5);bezierCurveTo(251.5,242.5,278,272,278,276.5);bezierCurveTo(278,276.5,278.5,267.5,276,265);closePath();fillStyle=#cccccc;fill();restore();save();transform(1,0,0,1,0,0);beginPath();moveTo(293,111);bezierCurveTo(293,111,281,103,279.5,105);bezierCurveTo(279.5,105,290,111.5,292.5,120);bezierCurveTo(292.5,120,291,111,293,111);closePath();fillStyle=#cccccc;fill();restore();save();transform(1,0,0,1,0,0);beginPath();moveTo(301.5,191.5);lineTo(284,179.5);bezierCurveTo(284,179.5,303,196.5,303.5,200.5);lineTo(301.5,191.5);closePath();fillStyle=#cccccc;fill();restore();save();transform(1,0,0,1,0,0);beginPath();moveTo(-89.25,169);lineTo(-67.25,173.75);lineWidth=2;strokeStyle=#000000;stroke();restore();save();transform(1,0,0,1,0,0);beginPath();moveTo(-39,331);bezierCurveTo(-39,331,-39.5,327.5,-48.5,338);lineWidth=2;strokeStyle=#000000;stroke();restore();save();transform(1,0,0,1,0,0);beginPath();moveTo(-33.5,336);bezierCurveTo(-33.5,336,-31.5,329.5,-38,334);lineWidth=2;strokeStyle=#000000;stroke();restore();save();transform(1,0,0,1,0,0);beginPath();moveTo(20.5,344.5);bezierCurveTo(20.5,344.5,22,333.5,10.5,346.5);lineWidth=2;strokeStyle=#000000;stroke();restore();' + ); }); // ====================================================== - test('Tiger (RAWR!) cached', function () { + it('Tiger (RAWR!) cached', function () { var stage = addStage(); var layer = new Konva.Layer(); var group = new Konva.Group(); @@ -494,13 +529,11 @@ suite('Path', function () { group.cache(); layer.draw(); - showHit(layer); - cloneAndCompareLayer(layer, 200); }); // ====================================================== - test('Able to determine point on line some distance from another point on line', function () { + it('Able to determine point on line some distance from another point on line', function () { var stage = addStage(); var layer = new Konva.Layer(); @@ -512,7 +545,7 @@ suite('Path', function () { strokeWidth: 3, }); - path.setData(c); + path.data(c); layer.add(path); layer.add( @@ -542,7 +575,7 @@ suite('Path', function () { }); // ====================================================== - test('Able to determine points on Cubic Bezier Curve', function () { + it('Able to determine points on Cubic Bezier Curve', function () { var stage = addStage(); var layer = new Konva.Layer(); @@ -553,12 +586,12 @@ suite('Path', function () { strokeWidth: 3, }); - path.setData(c); + path.data(c); layer.add(path); c = 'M 100 200'; - for (t = 0.25; t <= 1; t += 0.25) { + for (let t = 0.25; t <= 1; t += 0.25) { var p1 = Konva.Path.getPointOnCubicBezier( t, 100, @@ -573,7 +606,7 @@ suite('Path', function () { c += ' ' + p1.x.toString() + ' ' + p1.y.toString(); } - for (t = 0.25; t <= 1; t += 0.25) { + for (let t = 0.25; t <= 1; t += 0.25) { var p1 = Konva.Path.getPointOnCubicBezier( t, 250, @@ -596,10 +629,15 @@ suite('Path', function () { layer.add(testPath); stage.add(layer); + + assert.equal( + c, + 'M 100 200 123.4375 143.75 175 125 226.5625 143.75 250 200 273.4375 256.25 325 275 376.5625 256.25 400 200' + ); }); // ====================================================== - test('Able to determine points on Quadratic Curve', function () { + it('Able to determine points on Quadratic Curve', function () { var stage = addStage(); var layer = new Konva.Layer(); @@ -610,12 +648,12 @@ suite('Path', function () { strokeWidth: 3, }); - path.setData(c); + path.data(c); layer.add(path); c = 'M 200 300'; - for (t = 0.333; t <= 1; t += 0.333) { + for (let t = 0.333; t <= 1; t += 0.333) { var p1 = Konva.Path.getPointOnQuadraticBezier( t, 200, @@ -628,7 +666,7 @@ suite('Path', function () { c += ' ' + p1.x.toString() + ' ' + p1.y.toString(); } - for (t = 0.333; t <= 1; t += 0.333) { + for (let t = 0.333; t <= 1; t += 0.333) { var p1 = Konva.Path.getPointOnQuadraticBezier( t, 600, @@ -649,10 +687,15 @@ suite('Path', function () { layer.add(testPath); stage.add(layer); + + assert.equal( + c, + 'M 200 300 333.20000000000005 188.9445 466.40000000000003 188.77800000000002 599.6 299.50050000000005 733.2 411.05550000000005 866.4 411.222 999.6 300.49949999999995' + ); }); // ====================================================== - test('Able to determine points on Elliptical Arc with clockwise stroke', function () { + it('Able to determine points on Elliptical Arc with clockwise stroke', function () { var stage = addStage(); var layer = new Konva.Layer(); @@ -663,7 +706,7 @@ suite('Path', function () { strokeWidth: 3, }); - path.setData(c); + path.data(c); layer.add(path); @@ -700,7 +743,7 @@ suite('Path', function () { if ( dTheta < 0 // clockwise ) { - for (t = start - inc; t > end; t -= inc) { + for (let t = start - inc; t > end; t -= inc) { p1 = Konva.Path.getPointOnEllipticalArc( centerParamPoints[0], centerParamPoints[1], @@ -713,7 +756,7 @@ suite('Path', function () { } } else { // counter-clockwise - for (t = start + inc; t < end; t += inc) { + for (let t = start + inc; t < end; t += inc) { p1 = Konva.Path.getPointOnEllipticalArc( centerParamPoints[0], centerParamPoints[1], @@ -743,10 +786,15 @@ suite('Path', function () { layer.add(testpath); stage.add(layer); + + assert.equal( + c, + 'M 50 100 63.39745962155612 75.00000000000001 99.99999999999996 56.698729810778076 149.99999999999997 50 200 56.69872981077807 236.60254037844388 75.00000000000001 250 100.00000000000003 236.60254037844382 125.00000000000004 199.9999999999999 143.30127018922195 150.00000000000003 150' + ); }); // ====================================================== - test('Able to determine points on Elliptical Arc with counter-clockwise stroke', function () { + it('Able to determine points on Elliptical Arc with counter-clockwise stroke', function () { var stage = addStage(); var layer = new Konva.Layer(); @@ -757,7 +805,7 @@ suite('Path', function () { strokeWidth: 3, }); - path.setData(c); + path.data(c); layer.add(path); @@ -794,7 +842,7 @@ suite('Path', function () { if ( dTheta < 0 // clockwise ) { - for (t = start - inc; t > end; t -= inc) { + for (let t = start - inc; t > end; t -= inc) { p1 = Konva.Path.getPointOnEllipticalArc( centerParamPoints[0], centerParamPoints[1], @@ -807,7 +855,7 @@ suite('Path', function () { } } else { // counter-clockwise - for (t = start + inc; t < end; t += inc) { + for (let t = start + inc; t < end; t += inc) { p1 = Konva.Path.getPointOnEllipticalArc( centerParamPoints[0], centerParamPoints[1], @@ -837,10 +885,15 @@ suite('Path', function () { layer.add(testpath); stage.add(layer); + + assert.equal( + c, + 'M 250 100 236.60254037844388 75 200 56.69872981077807 150 50 100.00000000000003 56.69872981077806 63.39745962155615 74.99999999999999 50 99.99999999999997 63.397459621556095 124.99999999999997 99.99999999999996 143.30127018922192 149.99999999999997 150' + ); }); // ====================================================== - test('Able to determine points on Elliptical Arc when rotated', function () { + it('Able to determine points on Elliptical Arc when rotated', function () { var stage = addStage(); var layer = new Konva.Layer(); @@ -851,7 +904,7 @@ suite('Path', function () { strokeWidth: 3, }); - path.setData(c); + path.data(c); layer.add(path); @@ -890,7 +943,7 @@ suite('Path', function () { if ( dTheta < 0 // clockwise ) { - for (t = start - inc; t > end; t -= inc) { + for (let t = start - inc; t > end; t -= inc) { p1 = Konva.Path.getPointOnEllipticalArc( centerParamPoints[0], centerParamPoints[1], @@ -903,7 +956,7 @@ suite('Path', function () { } } else { // counter-clockwise - for (t = start + inc; t < end; t += inc) { + for (let t = start + inc; t < end; t += inc) { p1 = Konva.Path.getPointOnEllipticalArc( centerParamPoints[0], centerParamPoints[1], @@ -933,10 +986,15 @@ suite('Path', function () { layer.add(testpath); stage.add(layer); + + assert.equal( + c, + 'M 250 99.99999999999999 209.63024270137728 69.46654531272594 162.9710386647049 50.769536422212866 122.52468393108823 48.91882176155127 99.12874658818252 64.41029882948584 99.0521491531885 93.09303885609827 122.31541584695515 127.28152481454595 150 150' + ); }); // ====================================================== - test('getPointOnLine for different directions', function () { + it('getPointOnLine for different directions', function () { var origo = { x: 0, y: 0, @@ -1016,14 +1074,14 @@ suite('Path', function () { }); // ====================================================== - test('get path length', function () { + it('get path length', function () { var path = new Konva.Path({ data: 'M 10,10 L 20,10 L 20,20' }); assert.equal(path.getLength(), 20); }); // ====================================================== - test('get point at path', function () { + it('get point at path', function () { var stage = addStage(); var layer = new Konva.Layer(); @@ -1084,7 +1142,7 @@ suite('Path', function () { }); // ====================================================== - test('Borneo Map (has scientific notation: -10e-4)', function () { + it('Borneo Map (has scientific notation: -10e-4)', function () { var stage = addStage(); var layer = new Konva.Layer(); @@ -1095,10 +1153,16 @@ suite('Path', function () { }); layer.add(borneo); stage.add(layer); + + var trace = layer.getContext().getTrace(); + assert.equal( + trace, + 'bezierCurveTo(209.761,60.371,209.972,60.483,210.442,60.058);bezierCurveTo(211.208,59.365,213.182,59.458,213.948,60.224);bezierCurveTo(214.736,61.012,214.765,61.779,214.028,62.324);bezierCurveTo(213.189,62.943,213.944,63.507,215.605,63.499);bezierCurveTo(217.222,63.492,217.781,63.851,217.781,64.895);bezierCurveTo(217.781,65.486,217.609,65.654,217.004,65.654);bezierCurveTo(216.521,65.654,216.154,65.884,216.034,66.262);bezierCurveTo(215.769,67.097,213.92,67.912,211.587,68.222);bezierCurveTo(209.683,68.475,206.345,69.33,203.995,70.167);bezierCurveTo(202.899,70.558,202.813,70.688,202.617,72.249);bezierCurveTo(202.363,74.286,201.938,74.673,200.082,74.559);bezierCurveTo(199.287,74.51,198.551,74.557,198.446,74.662);bezierCurveTo(198.34,74.768,198.767,75.264,199.394,75.764);bezierCurveTo(200.02,76.264,200.533,76.907,200.533,77.193);bezierCurveTo(200.533,77.479,200.749,77.892,201.012,78.111);bezierCurveTo(202.035,78.959,201.313,80.549,199.46,81.533);bezierCurveTo(198.933,81.813,198.976,81.872,199.841,82.045);bezierCurveTo(201.097,82.296,201.599,83.24,201.328,84.842);bezierCurveTo(201.174,85.751,200.96,86.096,200.549,86.096);bezierCurveTo(199.119,86.096,197.177,83.389,197.943,82.465);bezierCurveTo(198.444,81.862,196.364,81.6,193.066,81.852);bezierCurveTo(190.688,82.034,190.609,82.064,191.629,82.393);bezierCurveTo(192.308,82.613,192.886,83.097,193.187,83.7);bezierCurveTo(193.602,84.53,193.817,84.646,194.794,84.564);bezierCurveTo(195.65,84.492,196.096,84.654,196.643,85.236);bezierCurveTo(197.523,86.172,197.905,88.129,197.342,88.808);bezierCurveTo(196.885,89.358,194.763,89.46,194.26,88.957);bezierCurveTo(194.029,88.726,193.803,88.772,193.524,89.109);bezierCurveTo(193.179,89.525,193.332,89.65,194.607,89.991);bezierCurveTo(196.673,90.544,197.454,91.336,197.239,92.661);bezierCurveTo(197.113,93.437,197.228,93.85,197.683,94.263);bezierCurveTo(198.021,94.568,198.299,95.12,198.3,95.488);bezierCurveTo(198.3,95.897,198.676,96.37,199.264,96.705);bezierCurveTo(199.867,97.048,200.472,97.824,200.882,98.78);bezierCurveTo(201.256,99.652,202.464,101.266,203.7,102.544);bezierCurveTo(206.428,105.365,206.72,105.913,206.452,107.706);bezierCurveTo(206.275,108.883,206.02,109.279,204.931,110.068);bezierCurveTo(204.211,110.589,203.274,111.529,202.848,112.155);bezierCurveTo(202.187,113.128,202.126,113.421,202.43,114.156);bezierCurveTo(202.626,114.629,203.437,115.409,204.231,115.889);bezierCurveTo(205.026,116.369,205.903,117.156,206.181,117.638);bezierCurveTo(206.75,118.625,208.71,120.184,210.606,121.159);bezierCurveTo(211.302,121.517,212.303,122.268,212.83,122.827);bezierCurveTo(213.357,123.386,214.352,124.133,215.04,124.487);bezierCurveTo(216.574,125.276,219.378,127.343,219.378,127.685);bezierCurveTo(219.378,128.328,221.742,130.469,222.67,130.666);bezierCurveTo(225.788,131.329,225.383,134.112,221.782,136.763);lineTo(220.496,137.71);lineTo(215.169,137.666);bezierCurveTo(210.75,137.63,209.701,137.531,209.016,137.082);bezierCurveTo(207.896,136.348,205.324,135.868,205.324,136.393);bezierCurveTo(205.324,137.28,204.095,137.929,202.756,137.75);bezierCurveTo(201.628,137.598,201.302,137.705,200.353,138.538);bezierCurveTo(199.75,139.068,199.256,139.655,199.256,139.843);bezierCurveTo(199.256,140.453,197.238,144.688,196.606,145.403);bezierCurveTo(195.771,146.35,194.672,151.087,195.102,151.89);bezierCurveTo(195.603,152.825,195.482,154.187,194.784,155.489);bezierCurveTo(194.005,156.942,193.993,157.386,194.68,159.303);bezierCurveTo(195.14,160.586,195.356,160.818,196.167,160.9);bezierCurveTo(197.651,161.049,197.909,161.802,197.095,163.609);bezierCurveTo(196.713,164.455,196.31,165.966,196.197,166.966);bezierCurveTo(196.078,168.026,195.774,168.981,195.468,169.256);bezierCurveTo(194.785,169.872,191.766,171.055,190.86,171.063);bezierCurveTo(190.139,171.07,187.442,173.918,185.502,176.721);bezierCurveTo(184.451,178.241,182.649,179.177,181.289,178.911);bezierCurveTo(180.534,178.762,180.411,178.842,180.411,179.479);bezierCurveTo(180.411,180.392,179.659,181.079,178.121,181.573);bezierCurveTo(176.683,182.034,176.4,182.376,176.159,183.941);bezierCurveTo(175.921,185.489,175.475,186.024,173.804,186.765);lineTo(172.467,187.358);lineTo(173.245,188.136);bezierCurveTo(173.939,188.83,174.023,189.188,174.023,191.461);bezierCurveTo(174.023,193.313,173.891,194.14,173.538,194.493);bezierCurveTo(173.104,194.927,173.18,195.013,174.257,195.313);bezierCurveTo(174.919,195.496,175.775,195.648,176.16,195.649);bezierCurveTo(176.545,195.65,176.942,195.782,177.041,195.944);bezierCurveTo(177.3,196.362,176.658,200.643,176.068,202.438);lineTo(175.569,203.955);lineTo(173.918,203.954);lineTo(172.266,203.953);lineTo(172.365,207.577);lineTo(172.463,211.202);lineTo(171.316,212.209);bezierCurveTo(170.684,212.763,169.975,213.217,169.74,213.217);bezierCurveTo(169.451,213.217,169.264,213.792,169.165,214.984);bezierCurveTo(169.047,216.405,168.827,216.952,168.04,217.778);bezierCurveTo(166.908,218.969,165.08,222.471,165.08,223.449);bezierCurveTo(165.08,224.561,164.519,225.259,163.452,225.472);bezierCurveTo(162.895,225.583,161.776,226.146,160.965,226.723);bezierCurveTo(159.745,227.591,154.764,229.826,154.05,229.826);bezierCurveTo(153.939,229.826,152.818,230.265,151.559,230.801);bezierCurveTo(150.3,231.338,148.697,232.021,147.998,232.319);bezierCurveTo(147.298,232.616,144.961,233.758,142.803,234.856);bezierCurveTo(140.646,235.954,138.548,236.852,138.142,236.852);bezierCurveTo(137.736,236.852,137.08,236.508,136.685,236.088);closePath();fillStyle=blue;fill();restore();' + ); }); // ====================================================== - test('Stroke and fill when no closed', function () { + it('Stroke and fill when no closed', function () { // https://github.com/konvajs/konva/issues/150 var stage = addStage(); @@ -1114,20 +1178,18 @@ suite('Path', function () { path.colorKey = 'black'; path.on('mouseover', function () { - this.setStroke('#f00'); + this.stroke('#f00'); layer.draw(); }); path.on('mouseout', function () { - this.setStroke('#000'); + this.stroke('#000'); layer.draw(); }); layer.add(path); stage.add(layer); - showHit(layer); - var trace = layer.getContext().getTrace(); //console.log(trace); @@ -1147,7 +1209,7 @@ suite('Path', function () { // ====================================================== // do we need to fill hit, when it is not closed? - test('Stroke when no closed', function () { + it('Stroke when no closed', function () { // https://github.com/konvajs/konva/issues/867 var stage = addStage(); @@ -1162,20 +1224,18 @@ suite('Path', function () { path.colorKey = 'black'; path.on('mouseover', function () { - this.setStroke('#f00'); + this.stroke('#f00'); layer.draw(); }); path.on('mouseout', function () { - this.setStroke('#000'); + this.stroke('#000'); layer.draw(); }); layer.add(path); stage.add(layer); - showHit(layer); - var trace = layer.getContext().getTrace(); var hitTrace = layer.hitCanvas.getContext().getTrace(); @@ -1191,7 +1251,7 @@ suite('Path', function () { }); // ====================================================== - test('draw path with no space in numbers', function () { + it('draw path with no space in numbers', function () { // https://github.com/konvajs/konva/issues/329 var stage = addStage(); @@ -1213,7 +1273,7 @@ suite('Path', function () { ); }); - test('getClientRect', function () { + it('getClientRect', function () { var stage = addStage(); var layer = new Konva.Layer(); stage.add(layer); @@ -1228,7 +1288,11 @@ suite('Path', function () { assert.deepEqual(rect, { x: 60, y: 184, width: 106, height: 102 }); }); - test('getClientRect of complex path', function () { + it('getClientRect of complex path', function () { + // TODO: it is failing on Node + if (isNode) { + return; + } var stage = addStage(); var layer = new Konva.Layer(); stage.add(layer); @@ -1255,7 +1319,7 @@ suite('Path', function () { assert.deepEqual(rect, { x: 9, y: 66, width: 95, height: 55 }); }); - test('getClientRect of another complex path', function () { + it('getClientRect of another complex path', function () { var stage = addStage(); var layer = new Konva.Layer(); stage.add(layer); @@ -1290,7 +1354,7 @@ suite('Path', function () { }); }); - test('getClientRect of one more path', function () { + it('getClientRect of one more path', function () { var stage = addStage(); var layer = new Konva.Layer(); stage.add(layer); @@ -1319,7 +1383,7 @@ suite('Path', function () { assert.deepEqual(rect, { x: 49, y: 49, width: 43, height: 48 }); }); - test('getClientRect for arc', function () { + it('getClientRect for arc', function () { var stage = addStage(); var layer = new Konva.Layer(); stage.add(layer); diff --git a/test/unit/shapes/Polygon-test.js b/test/unit-new/shapes/Polygon-test.ts similarity index 72% rename from test/unit/shapes/Polygon-test.js rename to test/unit-new/shapes/Polygon-test.ts index 90ad9bde..0c76340a 100644 --- a/test/unit/shapes/Polygon-test.js +++ b/test/unit-new/shapes/Polygon-test.ts @@ -1,5 +1,9 @@ -suite('Polygon', function () { - test('add polygon', function () { +import { assert } from 'chai'; + +import { addStage, Konva } from '../utis'; + +describe('Polygon', function () { + it('add polygon', function () { var stage = addStage(); var layer = new Konva.Layer(); diff --git a/test/unit/shapes/Rect-test.js b/test/unit-new/shapes/Rect-test.ts similarity index 85% rename from test/unit/shapes/Rect-test.js rename to test/unit-new/shapes/Rect-test.ts index 103832e9..58da17a3 100644 --- a/test/unit/shapes/Rect-test.js +++ b/test/unit-new/shapes/Rect-test.ts @@ -1,6 +1,10 @@ -suite('Rect', function () { +import { assert } from 'chai'; + +import { addStage, Konva, createCanvas, compareLayerAndCanvas } from '../utis'; + +describe('Rect', function () { // ====================================================== - test('add rect to stage', function () { + it('add rect to stage', function () { var stage = addStage(); var layer = new Konva.Layer(); @@ -17,8 +21,8 @@ suite('Rect', function () { layer.add(rect); stage.add(layer); - assert.equal(rect.getX(), 100); - assert.equal(rect.getY(), 50); + assert.equal(rect.x(), 100); + assert.equal(rect.y(), 50); var trace = layer.getContext().getTrace(); //console.log(trace); @@ -36,7 +40,7 @@ suite('Rect', function () { }); // ====================================================== - test('add rect with shadow, corner radius, and opacity', function () { + it('add rect with shadow, corner radius, and opacity', function () { var stage = addStage(); var layer = new Konva.Layer(); @@ -59,17 +63,17 @@ suite('Rect', function () { layer.add(rect); stage.add(layer); - assert.equal(rect.getShadowColor(), 'red'); - assert.equal(rect.getShadowBlur(), 10); - assert.equal(rect.getShadowOffsetX(), 5); - assert.equal(rect.getShadowOffsetY(), 5); - assert.equal(rect.getShadowOpacity(), 0.5); - assert.equal(rect.getOpacity(), 0.4); - assert.equal(rect.getCornerRadius(), 5); + assert.equal(rect.shadowColor(), 'red'); + assert.equal(rect.shadowBlur(), 10); + assert.equal(rect.shadowOffsetX(), 5); + assert.equal(rect.shadowOffsetY(), 5); + assert.equal(rect.shadowOpacity(), 0.5); + assert.equal(rect.opacity(), 0.4); + assert.equal(rect.cornerRadius(), 5); }); // ====================================================== - test('draw rect', function () { + it('draw rect', function () { var stage = addStage(); var layer = new Konva.Layer(); var rect = new Konva.Rect({ @@ -95,7 +99,7 @@ suite('Rect', function () { }); // ====================================================== - test('add fill stroke rect', function () { + it('add fill stroke rect', function () { var stage = addStage(); var layer = new Konva.Layer(); var rect = new Konva.Rect({ @@ -125,7 +129,7 @@ suite('Rect', function () { }); // ====================================================== - test('add stroke rect', function () { + it('add stroke rect', function () { var stage = addStage(); var layer = new Konva.Layer(); var rect = new Konva.Rect({ @@ -152,7 +156,7 @@ suite('Rect', function () { }); // ====================================================== - test('use default stroke width (stroke width should be 2)', function () { + it('use default stroke width (stroke width should be 2)', function () { var stage = addStage(); var layer = new Konva.Layer(); var rect = new Konva.Rect({ @@ -177,7 +181,7 @@ suite('Rect', function () { }); // ====================================================== - test('limit corner radius', function () { + it('limit corner radius', function () { var stage = addStage(); var layer = new Konva.Layer(); var rect = new Konva.Rect({ @@ -203,7 +207,7 @@ suite('Rect', function () { }); // ====================================================== - test('array for corner radius', function () { + it('array for corner radius', function () { var stage = addStage(); var layer = new Konva.Layer(); var rect = new Konva.Rect({ diff --git a/test/unit/shapes/RegularPolygon-test.js b/test/unit-new/shapes/RegularPolygon-test.ts similarity index 90% rename from test/unit/shapes/RegularPolygon-test.js rename to test/unit-new/shapes/RegularPolygon-test.ts index 893100bb..ebf1a661 100644 --- a/test/unit/shapes/RegularPolygon-test.js +++ b/test/unit-new/shapes/RegularPolygon-test.ts @@ -1,6 +1,10 @@ -suite('RegularPolygon', function () { +import { assert } from 'chai'; + +import { addStage, Konva, cloneAndCompareLayer } from '../utis'; + +describe('RegularPolygon', function () { // ====================================================== - test('add regular polygon triangle', function () { + it('add regular polygon triangle', function () { var stage = addStage(); var layer = new Konva.Layer(); @@ -27,7 +31,7 @@ suite('RegularPolygon', function () { }); // ====================================================== - test('add regular polygon square', function () { + it('add regular polygon square', function () { var stage = addStage(); var layer = new Konva.Layer(); @@ -54,7 +58,7 @@ suite('RegularPolygon', function () { }); // ====================================================== - test('add regular polygon pentagon', function () { + it('add regular polygon pentagon', function () { var stage = addStage(); var layer = new Konva.Layer(); @@ -81,7 +85,7 @@ suite('RegularPolygon', function () { }); // ====================================================== - test('add regular polygon octogon', function () { + it('add regular polygon octogon', function () { var stage = addStage(); var layer = new Konva.Layer(); @@ -108,7 +112,7 @@ suite('RegularPolygon', function () { }); // ====================================================== - test('attr sync', function () { + it('attr sync', function () { var stage = addStage(); var layer = new Konva.Layer(); @@ -138,8 +142,7 @@ suite('RegularPolygon', function () { assert.equal(poly.getHeight(), 140); }); - test('polygon cache', function () { - Konva.pixelRatio = 1; + it('polygon cache', function () { var stage = addStage(); var layer = new Konva.Layer(); @@ -165,10 +168,9 @@ suite('RegularPolygon', function () { }); cloneAndCompareLayer(layer, 254); - Konva.pixelRatio = undefined; }); - test('triangle - bounding box', function () { + it('triangle - bounding box', function () { var stage = addStage(); var layer = new Konva.Layer(); diff --git a/test/unit/shapes/Ring-test.js b/test/unit-new/shapes/Ring-test.ts similarity index 87% rename from test/unit/shapes/Ring-test.js rename to test/unit-new/shapes/Ring-test.ts index 0270f307..5cf35353 100644 --- a/test/unit/shapes/Ring-test.js +++ b/test/unit-new/shapes/Ring-test.ts @@ -1,11 +1,15 @@ -suite('Ring', function () { +import { assert } from 'chai'; + +import { addStage, Konva, compareLayers } from '../utis'; + +describe('Ring', function () { // ====================================================== - test('add ring', function () { + it('add ring', function () { var stage = addStage(); var layer = new Konva.Layer(); var ring = new Konva.Ring({ - x: stage.getWidth() / 2, - y: stage.getHeight() / 2, + x: stage.width() / 2, + y: stage.height() / 2, innerRadius: 50, outerRadius: 90, fill: 'green', @@ -25,7 +29,7 @@ suite('Ring', function () { }); // ====================================================== - test('ring attrs sync', function () { + it('ring attrs sync', function () { var stage = addStage(); var layer = new Konva.Layer(); var ring = new Konva.Ring({ @@ -54,7 +58,7 @@ suite('Ring', function () { assert(ring.outerRadius(), 60); }); - test('ring cache', function () { + it('ring cache', function () { var stage = addStage(); var layer = new Konva.Layer(); var ring = new Konva.Ring({ diff --git a/test/unit/shapes/Spline-test.js b/test/unit-new/shapes/Spline-test.ts similarity index 87% rename from test/unit/shapes/Spline-test.js rename to test/unit-new/shapes/Spline-test.ts index 3f697cbc..64eb3369 100644 --- a/test/unit/shapes/Spline-test.js +++ b/test/unit-new/shapes/Spline-test.ts @@ -1,6 +1,10 @@ -suite('Spline', function () { +import { assert } from 'chai'; + +import { addStage, Konva } from '../utis'; + +describe('Spline', function () { // ====================================================== - test('add splines', function () { + it('add splines', function () { var stage = addStage(); var layer = new Konva.Layer(); @@ -51,7 +55,7 @@ suite('Spline', function () { }); // ====================================================== - test('update spline points', function () { + it('update spline points', function () { var stage = addStage(); var layer = new Konva.Layer(); @@ -70,7 +74,7 @@ suite('Spline', function () { assert.equal(spline.getTensionPoints().length, 12); - spline.setPoints([73, 160, 340, 23, 500, 109]); + spline.points([73, 160, 340, 23, 500, 109]); assert.equal(spline.getTensionPoints().length, 6); @@ -78,7 +82,7 @@ suite('Spline', function () { }); // ====================================================== - test('add point to spline points', function () { + it('add point to spline points', function () { var stage = addStage(); var layer = new Konva.Layer(); @@ -95,14 +99,14 @@ suite('Spline', function () { layer.add(spline); stage.add(layer); - assert.equal(spline.getPoints().length, 8); + assert.equal(spline.points().length, 8); - var points = spline.getPoints(); + var points = spline.points(); points.push(300); points.push(200); spline.clearCache(); - assert.equal(spline.getPoints().length, 10); + assert.equal(spline.points().length, 10); layer.draw(); }); diff --git a/test/unit/shapes/Sprite-test.js b/test/unit-new/shapes/Sprite-test.ts similarity index 86% rename from test/unit/shapes/Sprite-test.js rename to test/unit-new/shapes/Sprite-test.ts index 36f66516..8a3a4df0 100644 --- a/test/unit/shapes/Sprite-test.js +++ b/test/unit-new/shapes/Sprite-test.ts @@ -1,8 +1,11 @@ -suite('Sprite', function () { +import { assert } from 'chai'; + +import { addStage, Konva, loadImage } from '../utis'; + +describe('Sprite', function () { // ====================================================== - test('add sprite', function (done) { - var imageObj = new Image(); - imageObj.onload = function () { + it('add sprite', function (done) { + loadImage('scorpion-sprite.png', (imageObj) => { var stage = addStage(); var layer = new Konva.Layer(); @@ -79,8 +82,6 @@ suite('Sprite', function () { assert.equal(sprite.getClassName(), 'Sprite'); assert.equal(sprite.frameIndex(), 0); - showHit(layer); - var trace = layer.hitCanvas.getContext().getTrace(); assert.equal(trace.indexOf(sprite.colorKey) >= 0, true); @@ -89,10 +90,10 @@ suite('Sprite', function () { // kick once setTimeout(function () { - sprite.setAnimation('kicking'); + sprite.animation('kicking'); sprite.on('indexChange', function (evt) { - if (evt.newVal === 0 && this.getAnimation() === 'kicking') { - sprite.setAnimation('standing'); + if (evt['newVal'] === 0 && this.animation() === 'kicking') { + sprite.animation('standing'); } }); }, 2000); @@ -101,14 +102,12 @@ suite('Sprite', function () { }, 3000); done(); - }; - imageObj.src = 'assets/scorpion-sprite.png'; + }); }); // ====================================================== - test('don`t update layer too many times', function (done) { - var imageObj = new Image(); - imageObj.onload = function () { + it('don`t update layer too many times', function (done) { + loadImage('scorpion-sprite.png', (imageObj) => { var stage = addStage(); var layer = new Konva.Layer(); @@ -161,6 +160,7 @@ suite('Sprite', function () { layer.draw = function () { updateCount++; oldDraw.call(layer); + return layer; }; sprite.start(); @@ -169,14 +169,12 @@ suite('Sprite', function () { assert.equal(updateCount < 7, true); done(); }, 1000); - }; - imageObj.src = 'assets/scorpion-sprite.png'; + }); }); // ====================================================== - test('don`t update layer too many times 2', function (done) { - var imageObj = new Image(); - imageObj.onload = function () { + it('don`t update layer too many times 2', function (done) { + loadImage('scorpion-sprite.png', (imageObj) => { var stage = addStage(); var layer = new Konva.Layer(); @@ -260,6 +258,7 @@ suite('Sprite', function () { layer.draw = function () { updateCount++; oldDraw.call(layer); + return layer; }; sprite.start(); @@ -271,13 +270,11 @@ suite('Sprite', function () { assert.equal(updateCount < 27, true); done(); }, 1000); - }; - imageObj.src = 'assets/scorpion-sprite.png'; + }); }); - test('check is sprite running', function (done) { - var imageObj = new Image(); - imageObj.onload = function () { + it('check is sprite running', function (done) { + loadImage('scorpion-sprite.png', (imageObj) => { var stage = addStage(); var layer = new Konva.Layer(); @@ -329,13 +326,11 @@ suite('Sprite', function () { assert.equal(sprite.isRunning(), true); sprite.stop(); done(); - }; - imageObj.src = 'assets/scorpion-sprite.png'; + }); }); - test('start do nothing if animation is already running', function (done) { - var imageObj = new Image(); - imageObj.onload = function () { + it('start do nothing if animation is already running', function (done) { + loadImage('scorpion-sprite.png', (imageObj) => { var stage = addStage(); var layer = new Konva.Layer(); @@ -396,14 +391,12 @@ suite('Sprite', function () { assert.equal(counter, 0); done(); }, 200); - }; - imageObj.src = 'assets/scorpion-sprite.png'; + }); }); // need fix. - test.skip('can change frame rate on fly', function (done) { - var imageObj = new Image(); - imageObj.onload = function () { + it.skip('can change frame rate on fly', function (done) { + loadImage('scorpion-sprite.png', (imageObj) => { var stage = addStage(); var layer = new Konva.Layer(); @@ -466,7 +459,6 @@ suite('Sprite', function () { assert.equal(sprite.frameIndex() > 2, true, '2'); done(); }, 68); - }; - imageObj.src = 'assets/scorpion-sprite.png'; + }); }); }); diff --git a/test/unit/shapes/Star-test.js b/test/unit-new/shapes/Star-test.ts similarity index 86% rename from test/unit/shapes/Star-test.js rename to test/unit-new/shapes/Star-test.ts index c4319adf..06f804ff 100644 --- a/test/unit/shapes/Star-test.js +++ b/test/unit-new/shapes/Star-test.ts @@ -1,6 +1,10 @@ -suite('Star', function () { +import { assert } from 'chai'; + +import { addStage, Konva, cloneAndCompareLayer } from '../utis'; + +describe('Star', function () { // ====================================================== - test('add five point star', function () { + it('add five point star', function () { var stage = addStage(); var layer = new Konva.Layer(); @@ -32,7 +36,7 @@ suite('Star', function () { }); // ====================================================== - test('add star with line join and shadow', function () { + it('add star with line join and shadow', function () { var stage = addStage(); var layer = new Konva.Layer(); @@ -66,15 +70,15 @@ suite('Star', function () { stage.add(layer); - assert.equal(star.getLineJoin(), 'round'); - star.setLineJoin('bevel'); - assert.equal(star.getLineJoin(), 'bevel'); + assert.equal(star.lineJoin(), 'round'); + star.lineJoin('bevel'); + assert.equal(star.lineJoin(), 'bevel'); - star.setLineJoin('round'); + star.lineJoin('round'); }); // ====================================================== - test('attr sync', function () { + it('attr sync', function () { var stage = addStage(); var layer = new Konva.Layer(); @@ -112,7 +116,7 @@ suite('Star', function () { }); // ====================================================== - test('star cache', function () { + it('star cache', function () { var stage = addStage(); var layer = new Konva.Layer(); diff --git a/test/unit/shapes/Text-test.js b/test/unit-new/shapes/Text-test.ts similarity index 71% rename from test/unit/shapes/Text-test.js rename to test/unit-new/shapes/Text-test.ts index b6c22f75..6e15104e 100644 --- a/test/unit/shapes/Text-test.js +++ b/test/unit-new/shapes/Text-test.ts @@ -1,8 +1,19 @@ -'use strict'; +import { assert } from 'chai'; -suite('Text', function () { +import { + addStage, + Konva, + createCanvas, + compareLayerAndCanvas, + compareLayers, + loadImage, + isBrowser, + isNode, +} from '../utis'; + +describe('Text', function () { // ====================================================== - test('text with empty config is allowed', function () { + it('text with empty config is allowed', function () { var stage = addStage(); var layer = new Konva.Layer(); @@ -20,7 +31,7 @@ suite('Text', function () { // ====================================================== // TODO: what is the best UX here? - test('check text with FALSY values', function () { + it('check text with FALSY values', function () { var stage = addStage(); var layer = new Konva.Layer(); @@ -30,21 +41,21 @@ suite('Text', function () { layer.add(text); layer.draw(); - text.text(0); + text.text(0 as any); assert.equal(text.text(), '0'); - text.text(true); + text.text(true as any); assert.equal(text.text(), 'true'); - text.text(false); + text.text(false as any); assert.equal(text.text(), 'false'); - text.setText(undefined); + text.text(undefined); assert.equal(text.text(), ''); }); // ====================================================== - test('text with undefined text property should not throw an error', function () { + it('text with undefined text property should not throw an error', function () { var stage = addStage(); var layer = new Konva.Layer(); @@ -57,13 +68,13 @@ suite('Text', function () { assert.equal(text.getWidth(), 0); }); - test('add text with shadows', function () { + it('add text with shadows', function () { var stage = addStage(); var layer = new Konva.Layer(); var rect = new Konva.Rect({ - x: stage.getWidth() / 2, - y: stage.getHeight() / 2, + x: stage.width() / 2, + y: stage.height() / 2, stroke: '#555', strokeWidth: 5, fill: '#ddd', @@ -77,8 +88,8 @@ suite('Text', function () { }); var text = new Konva.Text({ - x: stage.getWidth() / 2, - y: stage.getHeight() / 2, + x: stage.width() / 2, + y: stage.height() / 2, text: 'Hello World!', fontSize: 50, fontFamily: 'Calibri', @@ -101,7 +112,7 @@ suite('Text', function () { }); // center text box - rect.offsetX(text.getWidth() / 2, text.getHeight() / 2); + rect.offsetX(text.getWidth() / 2); group.add(rect); group.add(text); @@ -111,7 +122,7 @@ suite('Text', function () { assert.equal(text.getClassName(), 'Text', 'getClassName should be Text'); }); - test('text with fill and shadow', function () { + it('text with fill and shadow', function () { var stage = addStage(); var layer = new Konva.Layer(); @@ -142,7 +153,7 @@ suite('Text', function () { compareLayerAndCanvas(layer, canvas, 254); }); - test('check emoji with letterSpacing', function () { + it('check emoji with letterSpacing', function () { var stage = addStage(); var layer = new Konva.Layer(); @@ -167,7 +178,12 @@ suite('Text', function () { compareLayerAndCanvas(layer, canvas, 254); }); - test('text cache with fill and shadow', function () { + it('text cache with fill and shadow', function () { + // TODO: on node-canvas it doesn't work + // text scaling is not correct + if (isNode) { + return; + } var stage = addStage(); var layer1 = new Konva.Layer(); layer1.getCanvas().setPixelRatio(1); @@ -191,13 +207,13 @@ suite('Text', function () { var layer2 = new Konva.Layer(); layer2.getCanvas().setPixelRatio(1); - layer2.add(text1.clone().cache({ pixelRatio: 2 })); + layer2.add(text1.clone().cache({ pixelRatio: 4 })); stage.add(layer1, layer2); compareLayers(layer1, layer2, 220); }); - test('text cache with fill and shadow and some scale', function () { + it('text cache with fill and shadow and some scale', function () { var stage = addStage(); var layer1 = new Konva.Layer(); stage.add(layer1); @@ -238,7 +254,7 @@ suite('Text', function () { }); // ====================================================== - test('add text with letter spacing', function () { + it('add text with letter spacing', function () { var stage = addStage(); var layer = new Konva.Layer(); @@ -256,13 +272,13 @@ suite('Text', function () { layer.draw(); }); // ====================================================== - test('text getters and setters', function () { + it('text getters and setters', function () { var stage = addStage(); var layer = new Konva.Layer(); var text = new Konva.Text({ - x: stage.getWidth() / 2, - y: stage.getHeight() / 2, + x: stage.width() / 2, + y: stage.height() / 2, text: 'Hello World!', fontSize: 50, fontFamily: 'Calibri', @@ -277,13 +293,13 @@ suite('Text', function () { padding: 10, shadowColor: 'black', shadowBlur: 1, - shadowOffset: { X: 10, y: 10 }, + shadowOffset: { x: 10, y: 10 }, shadowOpacity: 0.2, draggable: true, }); // center text box - text.offsetX(text.getWidth() / 2, text.getHeight() / 2); + text.offsetX(text.getWidth() / 2); layer.add(text); stage.add(layer); @@ -292,61 +308,61 @@ suite('Text', function () { * test getters and setters */ - assert.equal(text.getX(), stage.getWidth() / 2); - assert.equal(text.getY(), stage.getHeight() / 2); - assert.equal(text.getText(), 'Hello World!'); - assert.equal(text.getFontSize(), 50); - assert.equal(text.getFontFamily(), 'Calibri'); - assert.equal(text.getFontStyle(), 'normal'); - assert.equal(text.getFontVariant(), 'normal'); - assert.equal(text.getFill(), '#888'); - assert.equal(text.getStroke(), '#333'); - assert.equal(text.getAlign(), 'right'); - assert.equal(text.getLineHeight(), 1.2); + assert.equal(text.x(), stage.width() / 2); + assert.equal(text.y(), stage.height() / 2); + assert.equal(text.text(), 'Hello World!'); + assert.equal(text.fontSize(), 50); + assert.equal(text.fontFamily(), 'Calibri'); + assert.equal(text.fontStyle(), 'normal'); + assert.equal(text.fontVariant(), 'normal'); + assert.equal(text.fill(), '#888'); + assert.equal(text.stroke(), '#333'); + assert.equal(text.align(), 'right'); + assert.equal(text.lineHeight(), 1.2); assert.equal(text.getWidth(), 400); - assert.equal(text.getHeight(), 100); - assert.equal(text.getPadding(), 10); - assert.equal(text.getShadowColor(), 'black'); - assert.equal(text.getDraggable(), true); + assert.equal(text.height(), 100); + assert.equal(text.padding(), 10); + assert.equal(text.shadowColor(), 'black'); + assert.equal(text.draggable(), true); assert.equal(text.getWidth(), 400); - assert.equal(text.getHeight(), 100); + assert.equal(text.height(), 100); assert(text.getTextWidth() > 0, 'text width should be greater than 0'); assert(text.fontSize() > 0, 'text height should be greater than 0'); - text.setX(1); - text.setY(2); - text.setText('bye world!'); - text.setFontSize(10); - text.setFontFamily('Arial'); - text.setFontStyle('bold'); - text.setFontVariant('small-caps'); - text.setFill('green'); - text.setStroke('yellow'); - text.setAlign('left'); - text.setWidth(300); - text.setHeight(75); - text.setPadding(20); - text.setShadowColor('green'); + text.x(1); + text.y(2); + text.text('bye world!'); + text.fontSize(10); + text.fontFamily('Arial'); + text.fontStyle('bold'); + text.fontVariant('small-caps'); + text.fill('green'); + text.stroke('yellow'); + text.align('left'); + text.width(300); + text.height(75); + text.padding(20); + text.shadowColor('green'); text.setDraggable(false); - assert.equal(text.getX(), 1); - assert.equal(text.getY(), 2); - assert.equal(text.getText(), 'bye world!'); - assert.equal(text.getFontSize(), 10); - assert.equal(text.getFontFamily(), 'Arial'); - assert.equal(text.getFontStyle(), 'bold'); - assert.equal(text.getFontVariant(), 'small-caps'); - assert.equal(text.getFill(), 'green'); - assert.equal(text.getStroke(), 'yellow'); - assert.equal(text.getAlign(), 'left'); + assert.equal(text.x(), 1); + assert.equal(text.y(), 2); + assert.equal(text.text(), 'bye world!'); + assert.equal(text.fontSize(), 10); + assert.equal(text.fontFamily(), 'Arial'); + assert.equal(text.fontStyle(), 'bold'); + assert.equal(text.fontVariant(), 'small-caps'); + assert.equal(text.fill(), 'green'); + assert.equal(text.stroke(), 'yellow'); + assert.equal(text.align(), 'left'); assert.equal(text.getWidth(), 300); - assert.equal(text.getHeight(), 75); - assert.equal(text.getPadding(), 20); - assert.equal(text.getShadowColor(), 'green'); - assert.equal(text.getDraggable(), false); + assert.equal(text.height(), 75); + assert.equal(text.padding(), 20); + assert.equal(text.shadowColor(), 'green'); + assert.equal(text.draggable(), false); // test set text to integer - text.setText(5); + text.text(5 as any); //document.body.appendChild(layer.bufferCanvas.element) @@ -355,7 +371,7 @@ suite('Text', function () { }); // ====================================================== - test('reset text auto width', function () { + it('reset text auto width', function () { var stage = addStage(); var layer = new Konva.Layer(); @@ -375,7 +391,7 @@ suite('Text', function () { }); // ====================================================== - test('text multi line', function () { + it('text multi line', function () { var stage = addStage(); var layer = new Konva.Layer(); @@ -407,18 +423,18 @@ suite('Text', function () { wrap: 'WORD', }); - rect.height(text.getHeight()); + rect.height(text.height()); // center text box //text.setOffset(text.getBoxWidth() / 2, text.getBoxHeight() / 2); layer.add(rect).add(text); stage.add(layer); - assert.equal(text.getLineHeight(), 20); + assert.equal(text.lineHeight(), 20); }); // ====================================================== - test('text single line with ellipsis', function () { + it('text single line with ellipsis', function () { var stage = addStage(); var layer = new Konva.Layer(); @@ -455,7 +471,7 @@ suite('Text', function () { }); // ====================================================== - test('multiline with ellipsis', function () { + it('multiline with ellipsis', function () { var stage = addStage(); var layer = new Konva.Layer(); @@ -465,7 +481,7 @@ suite('Text', function () { text: "HEADING\n\nAll the world's a stage, merely players. They have theirrrrrrr exits and theirrrrr entrances; And one man in his time plays many parts.", fontSize: 14, - fontFamily: 'Calibri', + fontFamily: 'Arial', fontStyle: 'normal', width: 100, padding: 0, @@ -480,15 +496,16 @@ suite('Text', function () { assert.equal(text.textArr.length, 7); assert.equal(text.textArr[6].text.slice(-1), '…'); - var trace = - "clearRect(0,0,578,200);save();transform(1,0,0,1,10,10);font=normal normal 14px Calibri;textBaseline=middle;textAlign=left;translate(0,0);save();fillStyle=black;fillText(HEADING,18.117,7);restore();save();fillStyle=black;fillText(,50,21);restore();save();fillStyle=black;fillText(All the world's,8.687,35);restore();save();fillStyle=black;fillText(a stage, merely,7.826,49);restore();save();fillStyle=black;fillText(players. They,11.903,63);restore();save();fillStyle=black;fillText(have theirrrrrrr,8.222,77);restore();save();fillStyle=black;fillText(exits and…,17.922,91);restore();restore();"; - - console.log(layer.getContext().getTrace()); - assert.equal(layer.getContext().getTrace(), trace); + if (isBrowser) { + assert.equal( + layer.getContext().getTrace(false, true), + "clearRect(0,0,578,200);save();transform(1,0,0,1,10,10);font=normal normal 14px Arial;textBaseline=middle;textAlign=left;translate(0,0);save();fillStyle=black;fillText(HEADING,18,7);restore();save();fillStyle=black;fillText(,50,21);restore();save();fillStyle=black;fillText(All the world's,7,35);restore();save();fillStyle=black;fillText(a stage,,25,49);restore();save();fillStyle=black;fillText(merely,28,63);restore();save();fillStyle=black;fillText(players. They,7,77);restore();save();fillStyle=black;fillText(have…,27,91);restore();restore();" + ); + } }); // ====================================================== - test('make sure we respect false for ellipsis', function () { + it('make sure we respect false for ellipsis', function () { var stage = addStage(); var layer = new Konva.Layer(); @@ -510,7 +527,7 @@ suite('Text', function () { }); // ====================================================== - test('wrap none check', function () { + it('wrap none check', function () { var stage = addStage(); var layer = new Konva.Layer(); @@ -544,7 +561,7 @@ suite('Text', function () { }); // ====================================================== - test('text multi line with justify align', function () { + it('text multi line with justify align', function () { var stage = addStage(); var layer = new Konva.Layer(); @@ -562,7 +579,7 @@ suite('Text', function () { text: "HEADING\n\n All the world's a stage, merely players. They have their exits and their entrances; And one man in his time plays many parts.", fontSize: 14, - fontFamily: 'Calibri', + fontFamily: 'Arial', fontStyle: 'normal', fill: '#555', width: 380, @@ -571,19 +588,19 @@ suite('Text', function () { draggable: true, }); - rect.height(text.getHeight()); + rect.height(text.height()); layer.add(rect).add(text); stage.add(layer); var trace = - 'fillText();fillStyle;fillText();fillStyle;fillText();fillStyle;fillText();fillStyle;fillText();fillStyle;fillText();fillStyle;fillText();fillStyle;fillText();fillStyle;fillText();fillStyle;fillText();fillStyle;fillText();fillStyle;fillText();fillStyle;fillText();fillStyle;fillText();fillStyle;fillText();fillStyle;fillText();fillStyle;fillText();fillStyle;fillText();fillStyle;fillText();fillStyle;fillText();fillStyle;fillText();fillStyle;fillText();fillStyle;fillText();fillStyle;fillText();fillStyle;fillText();fillStyle;fillText();restore();save();fillStyle;fillText();fillStyle;fillText();fillStyle;fillText();fillStyle;fillText();fillStyle;fillText();fillStyle;fillText();fillStyle;fillText();fillStyle;fillText();fillStyle;fillText();fillStyle;fillText();fillStyle;fillText();fillStyle;fillText();fillStyle;fillText();fillStyle;fillText();fillStyle;fillText();fillStyle;fillText();fillStyle;fillText();fillStyle;fillText();fillStyle;fillText();fillStyle;fillText();fillStyle;fillText();fillStyle;fillText();restore();restore();'; + 'fillText();fillStyle;fillText();fillStyle;fillText();fillStyle;fillText();fillStyle;fillText();fillStyle;fillText();fillStyle;fillText();fillStyle;fillText();fillStyle;fillText();fillStyle;fillText();fillStyle;fillText();fillStyle;fillText();fillStyle;fillText();fillStyle;fillText();fillStyle;fillText();fillStyle;fillText();fillStyle;fillText();fillStyle;fillText();fillStyle;fillText();fillStyle;fillText();fillStyle;fillText();fillStyle;fillText();restore();save();fillStyle;fillText();fillStyle;fillText();fillStyle;fillText();fillStyle;fillText();fillStyle;fillText();fillStyle;fillText();fillStyle;fillText();fillStyle;fillText();fillStyle;fillText();fillStyle;fillText();fillStyle;fillText();fillStyle;fillText();fillStyle;fillText();fillStyle;fillText();fillStyle;fillText();fillStyle;fillText();fillStyle;fillText();fillStyle;fillText();fillStyle;fillText();fillStyle;fillText();fillStyle;fillText();fillStyle;fillText();fillStyle;fillText();fillStyle;fillText();fillStyle;fillText();fillStyle;fillText();restore();restore();'; assert.equal(layer.getContext().getTrace(true), trace); }); // ====================================================== - test('text multi line with justify align and decoration', function () { + it('text multi line with justify align and decoration', function () { var stage = addStage(); var layer = new Konva.Layer(); @@ -601,7 +618,7 @@ suite('Text', function () { text: "HEADING\n\n All the world's a stage, merely players. They have their exits and their entrances; And one man in his time plays many parts.", fontSize: 14, - fontFamily: 'Calibri', + fontFamily: 'Arial', fontStyle: 'normal', fill: '#555', width: 380, @@ -612,20 +629,20 @@ suite('Text', function () { draggable: true, }); - rect.height(text.getHeight()); + rect.height(text.height()); layer.add(rect).add(text); stage.add(layer); var trace = - 'fillText();fillStyle;fillText();fillStyle;fillText();fillStyle;fillText();fillStyle;fillText();restore();save();save();beginPath();moveTo();lineTo();stroke();restore();fillStyle;fillText();fillStyle;fillText();fillStyle;fillText();fillStyle;fillText();fillStyle;fillText();fillStyle;fillText();fillStyle;fillText();fillStyle;fillText();fillStyle;fillText();fillStyle;fillText();fillStyle;fillText();fillStyle;fillText();fillStyle;fillText();fillStyle;fillText();fillStyle;fillText();fillStyle;fillText();fillStyle;fillText();fillStyle;fillText();fillStyle;fillText();fillStyle;fillText();fillStyle;fillText();fillStyle;fillText();fillStyle;fillText();fillStyle;fillText();fillStyle;fillText();fillStyle;fillText();fillStyle;fillText();fillStyle;fillText();fillStyle;fillText();fillStyle;fillText();restore();save();save();beginPath();moveTo();lineTo();stroke();restore();fillStyle;fillText();fillStyle;fillText();fillStyle;fillText();fillStyle;fillText();fillStyle;fillText();fillStyle;fillText();restore();restore();'; + 'fillText();fillStyle;fillText();fillStyle;fillText();fillStyle;fillText();fillStyle;fillText();fillStyle;fillText();fillStyle;fillText();fillStyle;fillText();fillStyle;fillText();fillStyle;fillText();fillStyle;fillText();fillStyle;fillText();fillStyle;fillText();fillStyle;fillText();fillStyle;fillText();fillStyle;fillText();fillStyle;fillText();fillStyle;fillText();fillStyle;fillText();fillStyle;fillText();fillStyle;fillText();fillStyle;fillText();fillStyle;fillText();restore();save();save();beginPath();moveTo();lineTo();stroke();restore();fillStyle;fillText();fillStyle;fillText();fillStyle;fillText();fillStyle;fillText();fillStyle;fillText();fillStyle;fillText();fillStyle;fillText();fillStyle;fillText();fillStyle;fillText();fillStyle;fillText();fillStyle;fillText();fillStyle;fillText();fillStyle;fillText();fillStyle;fillText();fillStyle;fillText();fillStyle;fillText();fillStyle;fillText();fillStyle;fillText();fillStyle;fillText();fillStyle;fillText();fillStyle;fillText();fillStyle;fillText();restore();restore();'; assert.equal(layer.getContext().getTrace(true), trace); }); // ====================================================== - test('text multi line with shadows', function () { + it('text multi line with shadows', function () { var stage = addStage(); var layer = new Konva.Layer(); @@ -656,14 +673,21 @@ suite('Text', function () { layer.add(text); stage.add(layer); - assert.equal( - layer.getContext().getTrace(), - "clearRect(0,0,578,200);save();transform(1,0,0,1,10,10);shadowColor=rgba(255,0,0,0.5);shadowBlur=1;shadowOffsetX=10;shadowOffsetY=10;font=normal normal 16px Calibri;textBaseline=middle;textAlign=left;translate(20,20);save();fillStyle=#555;fillText(HEADING,133.563,8);restore();save();fillStyle=#555;fillText(,170,24);restore();save();fillStyle=#555;fillText(All the world's a stage, and all the men and women,6.602,40);restore();save();fillStyle=#555;fillText(merely players. They have their exits and their,21.168,56);restore();save();fillStyle=#555;fillText(entrances; And one man in his time plays many,18.035,72);restore();save();fillStyle=#555;fillText(parts.,152.449,88);restore();restore();" - ); + if (isBrowser) { + assert.equal( + layer.getContext().getTrace(), + "clearRect(0,0,578,200);save();transform(1,0,0,1,10,10);shadowColor=rgba(255,0,0,0.5);shadowBlur=1;shadowOffsetX=10;shadowOffsetY=10;font=normal normal 16px Calibri;textBaseline=middle;textAlign=left;translate(20,20);save();fillStyle=#555;fillText(HEADING,133.563,8);restore();save();fillStyle=#555;fillText(,170,24);restore();save();fillStyle=#555;fillText(All the world's a stage, and all the men and women,6.602,40);restore();save();fillStyle=#555;fillText(merely players. They have their exits and their,21.168,56);restore();save();fillStyle=#555;fillText(entrances; And one man in his time plays many,18.035,72);restore();save();fillStyle=#555;fillText(parts.,152.449,88);restore();restore();" + ); + } else { + assert.equal( + layer.getContext().getTrace(), + "clearRect(0,0,578,200);save();transform(1,0,0,1,10,10);shadowColor=rgba(255,0,0,0.5);shadowBlur=1;shadowOffsetX=10;shadowOffsetY=10;font=normal normal 16px Calibri;textBaseline=middle;textAlign=left;translate(20,20);save();fillStyle=#555;fillText(HEADING,133,8);restore();save();fillStyle=#555;fillText(,170,24);restore();save();fillStyle=#555;fillText(All the world's a stage, and all the men and,18.5,40);restore();save();fillStyle=#555;fillText(women merely players. They have their exits,12.5,56);restore();save();fillStyle=#555;fillText(and their entrances; And one man in his time,13,72);restore();save();fillStyle=#555;fillText(plays many parts.,108,88);restore();restore();" + ); + } }); // ====================================================== - test('text multi line with underline and spacing', function () { + it('text multi line with underline and spacing', function () { var stage = addStage(); var layer = new Konva.Layer(); @@ -681,14 +705,21 @@ suite('Text', function () { layer.add(text); stage.add(layer); - var trace = - 'clearRect(0,0,578,200);save();transform(1,0,0,1,10,10);font=normal normal 80px Arial;textBaseline=middle;textAlign=left;translate(0,0);save();save();beginPath();moveTo(0,80);lineTo(189,80);stroke();restore();fillStyle=red;fillText(h,0,40);fillStyle=red;fillText(e,49.492,40);fillStyle=red;fillText(l,98.984,40);fillStyle=red;fillText(l,121.758,40);fillStyle=red;fillText(o,144.531,40);restore();save();save();beginPath();moveTo(0,160);lineTo(211,160);stroke();restore();fillStyle=red;fillText(w,0,120);fillStyle=red;fillText(o,62.773,120);fillStyle=red;fillText(r,112.266,120);fillStyle=red;fillText(l,143.906,120);fillStyle=red;fillText(d,166.68,120);restore();restore();'; + if (isBrowser) { + var trace = + 'clearRect(0,0,578,200);save();transform(1,0,0,1,10,10);font=normal normal 80px Arial;textBaseline=middle;textAlign=left;translate(0,0);save();save();beginPath();moveTo(0,80);lineTo(189,80);stroke();restore();fillStyle=red;fillText(h,0,40);fillStyle=red;fillText(e,49.492,40);fillStyle=red;fillText(l,98.984,40);fillStyle=red;fillText(l,121.758,40);fillStyle=red;fillText(o,144.531,40);restore();save();save();beginPath();moveTo(0,160);lineTo(211,160);stroke();restore();fillStyle=red;fillText(w,0,120);fillStyle=red;fillText(o,62.773,120);fillStyle=red;fillText(r,112.266,120);fillStyle=red;fillText(l,143.906,120);fillStyle=red;fillText(d,166.68,120);restore();restore();'; - assert.equal(layer.getContext().getTrace(), trace); + assert.equal(layer.getContext().getTrace(), trace); + } else { + var trace = + 'clearRect(0,0,578,200);save();transform(1,0,0,1,10,10);font=normal normal 80px Arial;textBaseline=middle;textAlign=left;translate(0,0);save();save();beginPath();moveTo(0,80);lineTo(188,80);stroke();restore();fillStyle=red;fillText(h,0,40);fillStyle=red;fillText(e,49,40);fillStyle=red;fillText(l,98,40);fillStyle=red;fillText(l,121,40);fillStyle=red;fillText(o,144,40);restore();save();save();beginPath();moveTo(0,160);lineTo(211,160);stroke();restore();fillStyle=red;fillText(w,0,120);fillStyle=red;fillText(o,63,120);fillStyle=red;fillText(r,112,120);fillStyle=red;fillText(l,144,120);fillStyle=red;fillText(d,167,120);restore();restore();'; + + assert.equal(layer.getContext().getTrace(), trace); + } }); // ====================================================== - test('test text with crazy font families', function () { + it('test text with crazy font families', function () { var stage = addStage(); var layer = new Konva.Layer(); stage.add(layer); @@ -714,7 +745,7 @@ suite('Text', function () { }); // ====================================================== - test('text with underline and large line height', function () { + it('text with underline and large line height', function () { var stage = addStage(); var layer = new Konva.Layer(); @@ -744,7 +775,7 @@ suite('Text', function () { compareLayerAndCanvas(layer, canvas, 50); }); - test('text multi line with strike', function () { + it('text multi line with strike', function () { var stage = addStage(); var layer = new Konva.Layer(); @@ -765,7 +796,7 @@ suite('Text', function () { assert.equal(layer.getContext().getTrace(true), trace); }); - test('text multi line with underline and strike', function () { + it('text multi line with underline and strike', function () { var stage = addStage(); var layer = new Konva.Layer(); @@ -788,7 +819,7 @@ suite('Text', function () { }); // ====================================================== - test('change font size should update text data', function () { + it('change font size should update text data', function () { var stage = addStage(); var layer = new Konva.Layer(); @@ -806,19 +837,19 @@ suite('Text', function () { }); var width = text.getWidth(); - var height = text.getHeight(); + var height = text.height(); layer.add(text); stage.add(layer); - text.setFontSize(30); + text.fontSize(30); layer.draw(); assert(text.getWidth() > width, 'width should have increased'); - assert(text.getHeight() > height, 'height should have increased'); + assert(text.height() > height, 'height should have increased'); }); - test('text vertical align', function () { + it('text vertical align', function () { var stage = addStage(); var layer = new Konva.Layer(); @@ -851,13 +882,20 @@ suite('Text', function () { layer.add(text); stage.add(layer); - var trace = - 'clearRect(0,0,578,200);save();transform(1,0,0,1,10,10);beginPath();rect(0,0,200,100);closePath();lineWidth=2;strokeStyle=black;stroke();restore();save();transform(1,0,0,1,10,10);font=normal normal 16px Arial;textBaseline=middle;textAlign=left;translate(10,42);save();fillStyle=#555;fillText(Some awesome text,17.523,8);restore();restore();'; + if (isBrowser) { + var trace = + 'clearRect(0,0,578,200);save();transform(1,0,0,1,10,10);beginPath();rect(0,0,200,100);closePath();lineWidth=2;strokeStyle=black;stroke();restore();save();transform(1,0,0,1,10,10);font=normal normal 16px Arial;textBaseline=middle;textAlign=left;translate(10,42);save();fillStyle=#555;fillText(Some awesome text,17.523,8);restore();restore();'; - assert.equal(layer.getContext().getTrace(), trace); + assert.equal(layer.getContext().getTrace(), trace); + } else { + var trace = + 'clearRect(0,0,578,200);save();transform(1,0,0,1,10,10);beginPath();rect(0,0,200,100);closePath();lineWidth=2;strokeStyle=black;stroke();restore();save();transform(1,0,0,1,10,10);font=normal normal 16px Arial;textBaseline=middle;textAlign=left;translate(10,42);save();fillStyle=#555;fillText(Some awesome text,18,8);restore();restore();'; + + assert.equal(layer.getContext().getTrace(), trace); + } }); - test('get text width', function () { + it('get text width', function () { var stage = addStage(); var layer = new Konva.Layer(); stage.add(layer); @@ -872,7 +910,7 @@ suite('Text', function () { assert.equal(text.getTextWidth() > 0 && text.getTextWidth() < 100, true); }); - test('get text width of long text with spacing (check it visually!)', function () { + it('get text width of long text with spacing (check it visually!)', function () { var stage = addStage(); stage.draggable(true); var layer = new Konva.Layer(); @@ -939,18 +977,25 @@ suite('Text', function () { layer.draw(); - assert.almostEqual(text1.width(), 1724.50048828125); - assert.almostEqual(text2.width(), 2612.50048828125); - assert.almostEqual(text3.width(), 2005.376953125); - assert.almostEqual(text4.width(), 1932.30810546875); + if (isBrowser) { + assert.almostEqual(Math.round(text1.width()), 1725); + assert.almostEqual(Math.round(text2.width()), 2613); + assert.almostEqual(Math.round(text3.width()), 2005); + assert.almostEqual(Math.round(text4.width()), 1932); + } else { + assert.almostEqual(Math.round(text1.width()), 1745); + assert.almostEqual(Math.round(text2.width()), 2633); + assert.almostEqual(Math.round(text3.width()), 1995); + assert.almostEqual(Math.round(text4.width()), 1981); + } }); - test('default text color should be black', function () { + it('default text color should be black', function () { var text = new Konva.Text(); assert.equal(text.fill(), 'black'); }); - test('text with stoke and strokeScaleEnabled', function () { + it('text with stoke and strokeScaleEnabled', function () { var stage = addStage(); var layer = new Konva.Layer(); @@ -981,7 +1026,7 @@ suite('Text', function () { compareLayerAndCanvas(layer, canvas); }); - test('text getSelfRect', function () { + it('text getSelfRect', function () { var stage = addStage(); var layer = new Konva.Layer(); @@ -1006,7 +1051,7 @@ suite('Text', function () { }); }); - test('linear gradient', function () { + it('linear gradient', function () { // Konva.pixelRatio = 1; var stage = addStage(); var layer = new Konva.Layer(); @@ -1036,7 +1081,7 @@ suite('Text', function () { // build color stops for (var n = 0; n < colorStops.length; n += 2) { - grd.addColorStop(colorStops[n], colorStops[n + 1]); + grd.addColorStop(colorStops[n] as number, colorStops[n + 1] as string); } ctx.fillStyle = grd; @@ -1045,7 +1090,8 @@ suite('Text', function () { compareLayerAndCanvas(layer, canvas, 200); }); - test('linear gradient multiline', function () { + it('linear gradient multiline', function () { + const oldRatio = Konva.pixelRatio; Konva.pixelRatio = 1; var stage = addStage(); var layer = new Konva.Layer(); @@ -1075,7 +1121,7 @@ suite('Text', function () { // build color stops for (var n = 0; n < colorStops.length; n += 2) { - grd.addColorStop(colorStops[n], colorStops[n + 1]); + grd.addColorStop(colorStops[n] as number, colorStops[n + 1] as string); } ctx.fillStyle = grd; @@ -1093,10 +1139,12 @@ suite('Text', function () { compareLayerAndCanvas(layer, canvas, 200); var data = layer.getContext().getImageData(25, 41, 1, 1).data; - delete Konva.pixelRatio; + Konva.pixelRatio = oldRatio; }); - test('radial gradient', function () { + it('radial gradient', function () { + const oldRatio = Konva.pixelRatio; + Konva.pixelRatio = 1; var stage = addStage(); var layer = new Konva.Layer(); @@ -1129,7 +1177,7 @@ suite('Text', function () { // build color stops for (var n = 0; n < colorStops.length; n += 2) { - grd.addColorStop(colorStops[n], colorStops[n + 1]); + grd.addColorStop(colorStops[n] as number, colorStops[n + 1] as string); } ctx.fillStyle = grd; @@ -1137,10 +1185,12 @@ suite('Text', function () { ctx.fillText(text.text(), 0, 0); - compareLayerAndCanvas(layer, canvas, 200); + Konva.pixelRatio = oldRatio; + + compareLayerAndCanvas(layer, canvas, 100, 30); }); - test('text should be centered in line height', function () { + it('text should be centered in line height', function () { var stage = addStage(); var layer = new Konva.Layer(); @@ -1169,7 +1219,7 @@ suite('Text', function () { assert.equal(layer.getContext().getTrace(), trace); }); - test('check wrapping', function () { + it('check wrapping', function () { var stage = addStage(); var layer = new Konva.Layer(); @@ -1191,7 +1241,7 @@ suite('Text', function () { assert.equal(lines[0].text, 'Hello, this'); }); - test('check trip when go to new line', function () { + it('check trip when go to new line', function () { var stage = addStage(); var layer = new Konva.Layer(); @@ -1202,7 +1252,7 @@ suite('Text', function () { layer.add(text); stage.add(layer); - text.setWidth(245); + text.width(245); var lines = text.textArr; @@ -1212,7 +1262,7 @@ suite('Text', function () { assert.equal(lines[0].text, 'Hello, this is some'); assert.equal(lines[1].text, 'good text'); - text.setWidth(261); + text.width(261); var lines = text.textArr; assert.equal(lines[0].text, 'Hello, this is some'); @@ -1220,7 +1270,7 @@ suite('Text', function () { layer.draw(); }); - test.skip('we should be able to clip underline by group', function () { + it.skip('we should be able to clip underline by group', function () { var stage = addStage(); var layer = new Konva.Layer(); stage.add(layer); @@ -1238,23 +1288,20 @@ suite('Text', function () { y: 10, width: 100, text: 'Hello World', - textDecoration: ['underline'], + textDecoration: 'underline', fontSize: 40, }); group.add(text); layer.draw(); - console.log(layer.getContext().getTrace()); - - // assert.equal(layer.getContext().getTrace(), trace); throw 1; }); - test('image gradient for text', function (done) { + it('image gradient for text', function (done) { + const oldRatio = Konva.pixelRatio; Konva.pixelRatio = 1; - var imageObj = new Image(); - imageObj.onload = function () { + loadImage('darth-vader.jpg', (imageObj) => { var stage = addStage(); var layer = new Konva.Layer(); @@ -1279,16 +1326,15 @@ suite('Text', function () { ctx.fillText(text.text(), 0, 15); compareLayerAndCanvas(layer, canvas, 200); - delete Konva.pixelRatio; + Konva.pixelRatio = oldRatio; done(); - }; - imageObj.src = 'assets/darth-vader.jpg'; + }); }); - test('image gradient for text with scale', function (done) { + it('image gradient for text with scale', function (done) { + const oldRatio = Konva.pixelRatio; Konva.pixelRatio = 1; - var imageObj = new Image(); - imageObj.onload = function () { + loadImage('darth-vader.jpg', (imageObj) => { var stage = addStage(); var layer = new Konva.Layer(); @@ -1310,22 +1356,24 @@ suite('Text', function () { ctx.textBaseline = 'middle'; var grd = ctx.createPattern(imageObj, 'repeat'); - grd.setTransform({ - a: 0.5, // Horizontal scaling. A value of 1 results in no scaling. - b: 0, // Vertical skewing. - c: 0, // Horizontal skewing. - d: 0.5, // Vertical scaling. A value of 1 results in no scaling. - e: 0, // Horizontal translation (moving). - f: 0, // Vertical translation (moving). - }); + if (isBrowser) { + grd.setTransform({ + a: 0.5, // Horizontal scaling. A value of 1 results in no scaling. + b: 0, // Vertical skewing. + c: 0, // Horizontal skewing. + d: 0.5, // Vertical scaling. A value of 1 results in no scaling. + e: 0, // Horizontal translation (moving). + f: 0, // Vertical translation (moving). + }); + } + ctx.fillStyle = grd; ctx.fillText(text.text(), 0, 15); compareLayerAndCanvas(layer, canvas, 200); - delete Konva.pixelRatio; + Konva.pixelRatio = oldRatio; done(); - }; - imageObj.src = 'assets/darth-vader.jpg'; + }); }); }); diff --git a/test/unit/shapes/TextPath-test.js b/test/unit-new/shapes/TextPath-test.ts similarity index 83% rename from test/unit/shapes/TextPath-test.js rename to test/unit-new/shapes/TextPath-test.ts index 8f4013d7..930053a0 100644 --- a/test/unit/shapes/TextPath-test.js +++ b/test/unit-new/shapes/TextPath-test.ts @@ -1,6 +1,10 @@ -suite('TextPath', function () { +import { assert } from 'chai'; + +import { addStage, Konva, cloneAndCompareLayer, isBrowser } from '../utis'; + +describe('TextPath', function () { // ====================================================== - test('Render Text Along Line', function () { + it('Render Text Along Line', function () { var stage = addStage(); var layer = new Konva.Layer(); @@ -22,17 +26,16 @@ suite('TextPath', function () { data: c, }); textpath.on('mouseover', function () { - this.setFill('blue'); + this.fill('blue'); layer.drawScene(); }); textpath.on('mouseout', function () { - this.setFill('orange'); + this.fill('orange'); layer.drawScene(); }); layer.add(textpath); stage.add(layer); - showHit(layer); assert.equal( textpath.getClassName(), @@ -49,7 +52,7 @@ suite('TextPath', function () { }); // ====================================================== - test.skip('Find Next Segment when Arc is in Path', function () { + it.skip('Find Next Segment when Arc is in Path', function () { var stage = addStage(); var layer = new Konva.Layer(); @@ -85,7 +88,7 @@ suite('TextPath', function () { }); // ====================================================== - test('Check getter and setter', function () { + it('Check getter and setter', function () { var stage = addStage(); var layer = new Konva.Layer(); @@ -99,15 +102,15 @@ suite('TextPath', function () { layer.add(path); stage.add(layer); - assert.equal(path.getData(), undefined); + assert.equal(path.data(), undefined); path.data(c); - assert.equal(path.getData(), c); + assert.equal(path.data(), c); layer.draw(); }); // ====================================================== - test('Render Text Along Vertical Line', function () { + it('Render Text Along Vertical Line', function () { var stage = addStage(); var layer = new Konva.Layer(); @@ -157,10 +160,15 @@ suite('TextPath', function () { layer.add(textpath); stage.add(layer); + + assert.equal( + layer.getContext().getTrace(true), + 'rotate();fillStyle;fillText();lineWidth;strokeStyle;strokeText();restore();save();translate();rotate();fillStyle;fillText();lineWidth;strokeStyle;strokeText();restore();save();translate();rotate();fillStyle;fillText();lineWidth;strokeStyle;strokeText();restore();save();translate();rotate();fillStyle;fillText();lineWidth;strokeStyle;strokeText();restore();save();translate();rotate();fillStyle;fillText();lineWidth;strokeStyle;strokeText();restore();save();translate();rotate();fillStyle;fillText();lineWidth;strokeStyle;strokeText();restore();save();translate();rotate();fillStyle;fillText();lineWidth;strokeStyle;strokeText();restore();save();translate();rotate();fillStyle;fillText();lineWidth;strokeStyle;strokeText();restore();save();translate();rotate();fillStyle;fillText();lineWidth;strokeStyle;strokeText();restore();save();translate();rotate();fillStyle;fillText();lineWidth;strokeStyle;strokeText();restore();save();translate();rotate();fillStyle;fillText();lineWidth;strokeStyle;strokeText();restore();restore();restore();' + ); }); // ====================================================== - test('Render Text Along two connected Bezier', function () { + it('Render Text Along two connected Bezier', function () { var stage = addStage(); var layer = new Konva.Layer(); @@ -186,10 +194,15 @@ suite('TextPath', function () { layer.add(textpath); stage.add(layer); + + assert.equal( + layer.getContext().getTrace(true), + 'rotate();fillStyle;fillText();lineWidth;strokeStyle;strokeText();restore();save();translate();rotate();fillStyle;fillText();lineWidth;strokeStyle;strokeText();restore();save();translate();rotate();fillStyle;fillText();lineWidth;strokeStyle;strokeText();restore();save();translate();rotate();fillStyle;fillText();lineWidth;strokeStyle;strokeText();restore();save();translate();rotate();fillStyle;fillText();lineWidth;strokeStyle;strokeText();restore();save();translate();rotate();fillStyle;fillText();lineWidth;strokeStyle;strokeText();restore();save();translate();rotate();fillStyle;fillText();lineWidth;strokeStyle;strokeText();restore();save();translate();rotate();fillStyle;fillText();lineWidth;strokeStyle;strokeText();restore();save();translate();rotate();fillStyle;fillText();lineWidth;strokeStyle;strokeText();restore();save();translate();rotate();fillStyle;fillText();lineWidth;strokeStyle;strokeText();restore();save();translate();rotate();fillStyle;fillText();lineWidth;strokeStyle;strokeText();restore();restore();restore();' + ); }); // ====================================================== - test('Render Text Along Elliptical Arc', function () { + it('Render Text Along Elliptical Arc', function () { var stage = addStage(); var layer = new Konva.Layer(); @@ -212,10 +225,15 @@ suite('TextPath', function () { layer.add(textpath); stage.add(layer); + + assert.equal( + layer.getContext().getTrace(true), + 'restore();save();translate();rotate();fillStyle;fillText();restore();save();translate();rotate();fillStyle;fillText();restore();save();translate();rotate();fillStyle;fillText();restore();save();translate();rotate();fillStyle;fillText();restore();save();translate();rotate();fillStyle;fillText();restore();save();translate();rotate();fillStyle;fillText();restore();save();translate();rotate();fillStyle;fillText();restore();save();translate();rotate();fillStyle;fillText();restore();save();translate();rotate();fillStyle;fillText();restore();save();translate();rotate();fillStyle;fillText();restore();save();translate();rotate();fillStyle;fillText();restore();save();translate();rotate();fillStyle;fillText();restore();save();translate();rotate();fillStyle;fillText();restore();save();translate();rotate();fillStyle;fillText();restore();save();translate();rotate();fillStyle;fillText();restore();save();translate();rotate();fillStyle;fillText();restore();restore();restore();' + ); }); // ====================================================== - test('Render Text Along complex path', function () { + it('Render Text Along complex path', function () { var stage = addStage(); var layer = new Konva.Layer(); @@ -234,10 +252,15 @@ suite('TextPath', function () { layer.add(textpath); stage.add(layer); + + assert.equal( + layer.getContext().getTrace(true), + 'restore();save();translate();rotate();fillStyle;fillText();restore();save();translate();rotate();fillStyle;fillText();restore();save();translate();rotate();fillStyle;fillText();restore();save();translate();rotate();fillStyle;fillText();restore();save();translate();rotate();fillStyle;fillText();restore();save();translate();rotate();fillStyle;fillText();restore();save();translate();rotate();fillStyle;fillText();restore();save();translate();rotate();fillStyle;fillText();restore();save();translate();rotate();fillStyle;fillText();restore();save();translate();rotate();fillStyle;fillText();restore();save();translate();rotate();fillStyle;fillText();restore();save();translate();rotate();fillStyle;fillText();restore();save();translate();rotate();fillStyle;fillText();restore();save();translate();rotate();fillStyle;fillText();restore();save();translate();rotate();fillStyle;fillText();restore();save();translate();rotate();fillStyle;fillText();restore();restore();restore();' + ); }); // ====================================================== - test('Render Text Along complex path cached', function () { + it('Render Text Along complex path cached', function () { var stage = addStage(); var layer = new Konva.Layer(); @@ -261,10 +284,9 @@ suite('TextPath', function () { stage.add(layer); cloneAndCompareLayer(layer, 200); - showHit(layer); }); - test('Text path with letter spacing', function () { + it('Text path with letter spacing', function () { var stage = addStage(); var layer = new Konva.Layer(); @@ -287,10 +309,9 @@ suite('TextPath', function () { layer.add(textpath); stage.add(layer); cloneAndCompareLayer(layer, 200); - showHit(layer); }); - test('Text path with align', function () { + it('Text path with align', function () { var stage = addStage(); var layer = new Konva.Layer(); @@ -315,7 +336,7 @@ suite('TextPath', function () { assert.equal(layer.getContext().getTrace(true), trace); }); - test('Text path with emoji', function () { + it('Text path with emoji', function () { var stage = addStage(); var layer = new Konva.Layer(); @@ -334,13 +355,13 @@ suite('TextPath', function () { layer.add(textpath); stage.add(layer); - var trace = - 'clearRect(0,0,578,200);save();transform(1,0,0,1,0,0);font=normal normal 10px Arial;textBaseline=middle;textAlign=left;save();save();translate(144.438,10);rotate(0);fillStyle=black;fillText(😬,0,0);restore();restore();restore();'; - - assert.equal(layer.getContext().getTrace(), trace); + assert.equal( + layer.getContext().getTrace(true), + 'clearRect();save();transform();font;textBaseline;textAlign;save();save();translate();rotate();fillStyle;fillText();restore();restore();restore();' + ); }); - test.skip('Text path with center align - arc', function () { + it('Text path with center align - arc', function () { var stage = addStage(); var layer = new Konva.Layer(); @@ -360,13 +381,13 @@ suite('TextPath', function () { layer.add(path); stage.add(layer); - var trace = - 'restore();save();translate();rotate();fillStyle;fillText();restore();save();translate();rotate();fillStyle;fillText();restore();save();translate();rotate();fillStyle;fillText();restore();save();translate();rotate();fillStyle;fillText();restore();save();translate();rotate();fillStyle;fillText();restore();save();translate();rotate();fillStyle;fillText();restore();save();translate();rotate();fillStyle;fillText();restore();save();translate();rotate();fillStyle;fillText();restore();save();translate();rotate();fillStyle;fillText();restore();save();translate();rotate();fillStyle;fillText();restore();save();translate();rotate();fillStyle;fillText();restore();save();translate();rotate();fillStyle;fillText();restore();save();translate();rotate();fillStyle;fillText();restore();save();translate();rotate();fillStyle;fillText();restore();save();translate();rotate();fillStyle;fillText();restore();save();translate();rotate();fillStyle;fillText();restore();restore();restore();'; - - assert.equal(layer.getContext().getTrace(true), trace); + assert.equal( + layer.getContext().getTrace(true), + 'clearRect();save();transform();font;textBaseline;textAlign;save();save();translate();rotate();fillStyle;fillText();restore();save();translate();rotate();fillStyle;fillText();restore();save();translate();rotate();fillStyle;fillText();restore();save();translate();rotate();fillStyle;fillText();restore();save();translate();rotate();fillStyle;fillText();restore();save();translate();rotate();fillStyle;fillText();restore();save();translate();rotate();fillStyle;fillText();restore();save();translate();rotate();fillStyle;fillText();restore();save();translate();rotate();fillStyle;fillText();restore();save();translate();rotate();fillStyle;fillText();restore();save();translate();rotate();fillStyle;fillText();restore();save();translate();rotate();fillStyle;fillText();restore();restore();restore();save();transform();beginPath();moveTo();translate();rotate();scale();arc();scale();rotate();translate();lineWidth;strokeStyle;stroke();restore();' + ); }); - test('Text path with align right', function () { + it('Text path with align right', function () { var stage = addStage(); var layer = new Konva.Layer(); @@ -391,13 +412,13 @@ suite('TextPath', function () { layer.add(textpath); stage.add(layer); - var trace = - "restore();save();translate(228.335,10);rotate(0);fillStyle=black;fillText(w,0,0);restore();save();translate(235.557,10);rotate(0);fillStyle=black;fillText(o,0,0);restore();save();translate(241.118,10);rotate(0);fillStyle=black;fillText(r,0,0);restore();save();translate(244.448,10);rotate(0);fillStyle=black;fillText(l,0,0);restore();save();translate(246.67,10);rotate(0);fillStyle=black;fillText(d,0,0);restore();save();translate(252.231,10);rotate(0);fillStyle=black;fillText(',0,0);restore();save();translate(254.141,10);rotate(0);fillStyle=black;fillText(s,0,0);restore();save();translate(259.141,10);rotate(0);fillStyle=black;fillText( ,0,0);restore();save();translate(261.919,10);rotate(0);fillStyle=black;fillText(a,0,0);restore();save();translate(267.48,10);rotate(0);fillStyle=black;fillText( ,0,0);restore();save();translate(270.259,10);rotate(0);fillStyle=black;fillText(s,0,0);restore();save();translate(275.259,10);rotate(0);fillStyle=black;fillText(t,0,0);restore();save();translate(278.037,10);rotate(0);fillStyle=black;fillText(a,0,0);restore();save();translate(283.599,10);rotate(0);fillStyle=black;fillText(g,0,0);restore();save();translate(289.16,10);rotate(0);fillStyle=black;fillText(e,0,0);restore();save();translate(294.722,10);rotate(0);fillStyle=black;fillText(.,0,0);restore();restore();restore();"; - - assert.equal(layer.getContext().getTrace(), trace); + assert.equal( + layer.getContext().getTrace(true), + 'restore();save();translate();rotate();fillStyle;fillText();restore();save();translate();rotate();fillStyle;fillText();restore();save();translate();rotate();fillStyle;fillText();restore();save();translate();rotate();fillStyle;fillText();restore();save();translate();rotate();fillStyle;fillText();restore();save();translate();rotate();fillStyle;fillText();restore();save();translate();rotate();fillStyle;fillText();restore();save();translate();rotate();fillStyle;fillText();restore();save();translate();rotate();fillStyle;fillText();restore();save();translate();rotate();fillStyle;fillText();restore();save();translate();rotate();fillStyle;fillText();restore();save();translate();rotate();fillStyle;fillText();restore();save();translate();rotate();fillStyle;fillText();restore();save();translate();rotate();fillStyle;fillText();restore();save();translate();rotate();fillStyle;fillText();restore();save();translate();rotate();fillStyle;fillText();restore();restore();restore();' + ); }); - test('Text path with justify align', function () { + it('Text path with justify align', function () { var stage = addStage(); var layer = new Konva.Layer(); @@ -424,7 +445,7 @@ suite('TextPath', function () { assert.equal(layer.getContext().getTrace(true), trace); }); - test('Text path with underline', function () { + it('Text path with underline', function () { var stage = addStage(); var layer = new Konva.Layer(); @@ -450,7 +471,7 @@ suite('TextPath', function () { assert.equal(layer.getContext().getTrace(true), trace); }); - test('Text with baseline', function () { + it('Text with baseline', function () { var stage = addStage(); var layer = new Konva.Layer(); @@ -473,24 +494,28 @@ suite('TextPath', function () { textBaseline: 'top', }); textpath.on('mouseover', function () { - this.setFill('blue'); + this.fill('blue'); layer.drawScene(); }); textpath.on('mouseout', function () { - this.setFill('orange'); + this.fill('orange'); layer.drawScene(); }); layer.add(textpath); stage.add(layer); - showHit(layer); + + assert.equal( + layer.getContext().getTrace(true), + 'restore();save();translate();rotate();fillStyle;fillText();restore();save();translate();rotate();fillStyle;fillText();restore();save();translate();rotate();fillStyle;fillText();restore();save();translate();rotate();fillStyle;fillText();restore();save();translate();rotate();fillStyle;fillText();restore();save();translate();rotate();fillStyle;fillText();restore();save();translate();rotate();fillStyle;fillText();restore();save();translate();rotate();fillStyle;fillText();restore();save();translate();rotate();fillStyle;fillText();restore();save();translate();rotate();fillStyle;fillText();restore();save();translate();rotate();fillStyle;fillText();restore();save();translate();rotate();fillStyle;fillText();restore();save();translate();rotate();fillStyle;fillText();restore();save();translate();rotate();fillStyle;fillText();restore();save();translate();rotate();fillStyle;fillText();restore();save();translate();rotate();fillStyle;fillText();restore();restore();restore();' + ); }); - test('Text with kerning', function () { + it('Text with kerning', function () { var stage = addStage(); // simulate lack of kerning support - stage.getContainer().style.fontKerning = 'none'; + stage.content && (stage.container().style.fontKerning = 'none'); var layer = new Konva.Layer(); var pairs = { @@ -535,11 +560,11 @@ suite('TextPath', function () { ); }); - test('Text with invalid kerning getter should not fail (fallback to unkerned)', function () { + it('Text with invalid kerning getter should not fail (fallback to unkerned)', function () { var stage = addStage(); // simulate lack of kerning support - stage.getContainer().style.fontKerning = 'none'; + stage.content && (stage.container().style.fontKerning = 'none'); var layer = new Konva.Layer(); @@ -576,11 +601,11 @@ suite('TextPath', function () { ); }); - test('can set kerning after initialization', function () { + it('can set kerning after initialization', function () { var stage = addStage(); // simulate lack of kerning support - stage.getContainer().style.fontKerning = 'none'; + stage.content && (stage.container().style.fontKerning = 'none'); var layer = new Konva.Layer(); stage.add(layer); @@ -606,7 +631,7 @@ suite('TextPath', function () { assert.equal(called, true); }); - test.skip('linear gradient for path', function () { + it.skip('linear gradient for path', function () { var stage = addStage(); var layer = new Konva.Layer(); @@ -615,7 +640,6 @@ suite('TextPath', function () { const text = new Konva.TextPath({ x: 0, y: 30, - text: 'AV', fontSize: 20, data: 'M0,0 L200,0', fillLinearGradientStartPoint: { x: 0, y: 0 }, @@ -625,11 +649,9 @@ suite('TextPath', function () { }); layer.add(text); layer.draw(); - - var trace = layer.getContext().getTrace(); }); - test('visual check for text path', function () { + it('visual check for text path', function () { var stage = addStage(); var layer = new Konva.Layer(); @@ -680,9 +702,14 @@ suite('TextPath', function () { }) ); layer.draw(); + + assert.equal( + layer.getContext().getTrace(true), + 'save();translate();rotate();fillStyle;fillText();restore();save();translate();rotate();fillStyle;fillText();restore();restore();restore();save();transform();font;textBaseline;textAlign;translate();save();fillStyle;fillText();restore();restore();save();transform();font;textBaseline;textAlign;save();save();translate();rotate();fillStyle;fillText();restore();save();translate();rotate();fillStyle;fillText();restore();save();translate();rotate();fillStyle;fillText();restore();save();translate();rotate();fillStyle;fillText();restore();save();translate();rotate();fillStyle;fillText();restore();save();translate();rotate();fillStyle;fillText();restore();save();translate();rotate();fillStyle;fillText();restore();save();translate();rotate();fillStyle;fillText();restore();save();translate();rotate();fillStyle;fillText();restore();save();translate();rotate();fillStyle;fillText();restore();save();translate();rotate();fillStyle;fillText();restore();restore();restore();' + ); }); - test('client rect calculations', function () { + it('client rect calculations', function () { var stage = addStage(); var layer = new Konva.Layer(); @@ -710,7 +737,7 @@ suite('TextPath', function () { assert.equal(rect.height, 0, 'check height'); }); - test('check bad calculations', function () { + it('check bad calculations', function () { var stage = addStage(); stage.draggable(true); @@ -740,14 +767,19 @@ suite('TextPath', function () { var rect = textpath.getClientRect(); - assert.equal(rect.height, 328.9307620828596, 'check height'); + // just different results in different envs + if (isBrowser) { + assert.equal(Math.round(rect.height), 329, 'check height'); + } else { + assert.equal(Math.round(rect.height), 331, 'check height'); + } textpath.text(''); rect = textpath.getClientRect(); assert.equal(rect.height, 0, 'check height'); }); - test('check bad calculations 2', function () { + it('check bad calculations 2', function () { var stage = addStage(); var layer = new Konva.Layer(); @@ -789,7 +821,7 @@ suite('TextPath', function () { layer.draw(); var rect = textpath.getClientRect(); - assert.equal(rect.width, 298.50662860798093); - assert.equal(rect.height, 170.7386880372827); + assert.equal(Math.round(rect.width), 299); + assert.equal(Math.round(rect.height), 171); }); }); diff --git a/test/unit/shapes/Transformer-test.js b/test/unit-new/shapes/Transformer-test.ts similarity index 87% rename from test/unit/shapes/Transformer-test.js rename to test/unit-new/shapes/Transformer-test.ts index c11c01a4..d68dbe5f 100644 --- a/test/unit/shapes/Transformer-test.js +++ b/test/unit-new/shapes/Transformer-test.ts @@ -1,26 +1,45 @@ -suite('Transformer', function () { +import { assert } from 'chai'; +import { Transformer } from '../../../src/shapes/Transformer'; + +import { + addStage, + isNode, + Konva, + simulateMouseDown as sd, + simulateMouseMove as sm, + simulateMouseUp as su, +} from '../utis'; + +function simulateMouseDown(tr, pos) { + sd(tr.getStage(), pos); +} + +function simulateMouseMove(tr, pos) { + const stage = tr.getStage(); + var top = (stage.content && stage.content.getBoundingClientRect().top) || 0; + tr._handleMouseMove({ + ...pos, + clientX: pos.x, + clientY: pos.y + top, + }); + sm(stage, pos); +} + +function simulateMouseUp(tr: Transformer, pos = { x: 0, y: 0 }) { + const stage = tr.getStage(); + var top = (stage.content && stage.content.getBoundingClientRect().top) || 0; + tr._handleMouseUp({ + clientX: pos.x, + clientY: pos.y + top, + }); + su(tr.getStage(), pos || { x: 1, y: 1 }); +} + +describe('Transformer', function () { function isClose(a, b) { return Math.abs(a - b) < 0.000001; } - Konva.Transformer.prototype.simulateMouseDown = function (pos) { - this.getStage().simulateMouseDown(pos); - }; - - Konva.Transformer.prototype.simulateMouseMove = function (pos) { - var top = this.getStage().content.getBoundingClientRect().top; - this._handleMouseMove({ - clientX: pos.x, - clientY: pos.y + top, - }); - this.getStage().simulateMouseMove(pos); - }; - - Konva.Transformer.prototype.simulateMouseUp = function (pos) { - this._handleMouseUp(pos); - this.getStage().simulateMouseUp(pos || { x: 1, y: 1 }); - }; - assert.almostEqual = function (val1, val2) { if (!isClose(val1, val2)) { throw new Error('Expected ' + val1 + ' to be almost equal to ' + val2); @@ -28,7 +47,7 @@ suite('Transformer', function () { }; // ====================================================== - test('init transformer on simple rectangle', function () { + it('init transformer on simple rectangle', function () { var stage = addStage(); var layer = new Konva.Layer(); stage.add(layer); @@ -63,7 +82,7 @@ suite('Transformer', function () { assert.equal(pos.y, rect.y() + rect.height()); }); - test('can attach transformer into several nodes', function () { + it('can attach transformer into several nodes', function () { var stage = addStage(); var layer = new Konva.Layer(); stage.add(layer); @@ -102,7 +121,7 @@ suite('Transformer', function () { assert.equal(tr.rotation(), 0); }); - test('try set/get node', function () { + it('try set/get node', function () { var stage = addStage(); var layer = new Konva.Layer(); stage.add(layer); @@ -138,7 +157,7 @@ suite('Transformer', function () { layer.draw(); }); - test('try to fit simple rectangle', function () { + it('try to fit simple rectangle', function () { var stage = addStage(); var layer = new Konva.Layer(); stage.add(layer); @@ -174,7 +193,7 @@ suite('Transformer', function () { assert.equal(tr.rotation(), rect.rotation()); }); - test('try to fit simple rotated rectangle', function () { + it('try to fit simple rotated rectangle', function () { var stage = addStage(); var layer = new Konva.Layer(); stage.add(layer); @@ -211,7 +230,7 @@ suite('Transformer', function () { assert.almostEqual(tr.rotation(), rect.rotation()); }); - test('transformer should follow rotation on single node', function () { + it('transformer should follow rotation on single node', function () { var stage = addStage(); var layer = new Konva.Layer(); stage.add(layer); @@ -239,7 +258,7 @@ suite('Transformer', function () { assert.equal(tr.rotation(), 45); }); - test('try to fit simple rotated rectangle in group', function () { + it('try to fit simple rotated rectangle in group', function () { var stage = addStage(); var layer = new Konva.Layer(); stage.add(layer); @@ -280,7 +299,7 @@ suite('Transformer', function () { assert.almostEqual(rect.rotation(), -45); }); - test('transformer should follow rotation on single node inside group', function () { + it('transformer should follow rotation on single node inside group', function () { var stage = addStage(); var layer = new Konva.Layer(); stage.add(layer); @@ -313,7 +332,7 @@ suite('Transformer', function () { assert.equal(isClose(tr.rotation(), 90), true); }); - test('try to fit simple rotated rectangle - 2', function () { + it('try to fit simple rotated rectangle - 2', function () { var stage = addStage(); var layer = new Konva.Layer(); stage.add(layer); @@ -351,7 +370,7 @@ suite('Transformer', function () { assert.almostEqual(rect.rotation(), 0); }); - test('rotate around center', function () { + it('rotate around center', function () { var stage = addStage(); var layer = new Konva.Layer(); stage.add(layer); @@ -389,7 +408,7 @@ suite('Transformer', function () { assert.almostEqual(rect.rotation(), 0); }); - test('change transform of parent', function () { + it('change transform of parent', function () { var stage = addStage(); var layer = new Konva.Layer(); stage.add(layer); @@ -411,13 +430,13 @@ suite('Transformer', function () { layer.draw(); - assert.equal(tr.x(), 50); + assert.equal(tr.x(), 50, 'first x'); stage.scaleX(2); stage.scaleY(2); // check attrs - assert.equal(tr.x(), 100); + assert.equal(tr.x(), 100, 'second x'); assert.equal(tr.width(), 200); // check visual var pos = tr.findOne('.top-right').getAbsolutePosition(); @@ -426,10 +445,7 @@ suite('Transformer', function () { stage.draw(); }); - // TODO: try to rotate rect manually - // it produce the weird result - // we need skew here! - test('rotated inside scaled (in one direction) parent', function () { + it('rotated inside scaled (in one direction) parent', function () { var stage = addStage(); stage.scaleX(2); var layer = new Konva.Layer(); @@ -451,9 +467,20 @@ suite('Transformer', function () { layer.add(tr); layer.draw(); + tr._fitNodesInto({ + x: 100, + y: 0, + width: 50, + height: 50, + rotation: Konva.getAngle(45), + }); + + assert.equal(rect.x(), 50); + assert.equal(rect.skewX(), 0.75); + assert.equal(rect.skewY(), 0); }); - test('try to fit rectangle with skew', function () { + it('try to fit rectangle with skew', function () { var stage = addStage(); var layer = new Konva.Layer(); stage.add(layer); @@ -492,7 +519,7 @@ suite('Transformer', function () { assert.almostEqual(rect.skewX(), 0.2); }); - test('try to resize in draggable stage', function () { + it('try to resize in draggable stage', function () { var stage = addStage(); stage.draggable(true); var layer = new Konva.Layer(); @@ -527,42 +554,42 @@ suite('Transformer', function () { dragend += 1; }); - tr.simulateMouseDown({ + simulateMouseDown(tr, { x: 50, y: 50, }); - tr.simulateMouseMove({ + simulateMouseMove(tr, { x: 60, y: 60, }); assert.equal(stage.isDragging(), false); assert.equal(dragstart, 0); - tr.simulateMouseUp({ x: 60, y: 60 }); + simulateMouseUp(tr, { x: 60, y: 60 }); assert.equal(dragmove, 0); assert.equal(dragend, 0); - stage.simulateMouseDown({ + simulateMouseDown(tr, { x: 40, y: 40, }); - stage.simulateMouseMove({ + sm(stage, { x: 45, y: 45, }); - stage.simulateMouseMove({ + sm(stage, { x: 50, y: 50, }); assert.equal(stage.isDragging(), true); assert.equal(stage.x(), 10); assert.equal(stage.y(), 10); - stage.simulateMouseUp({ + su(stage, { x: 45, y: 45, }); }); - test('try to fit simple rectangle into negative scale', function () { + it('try to fit simple rectangle into negative scale', function () { var stage = addStage(); var layer = new Konva.Layer(); stage.add(layer); @@ -603,7 +630,7 @@ suite('Transformer', function () { layer.draw(); }); - test('try to fit rectangle with ignoreStroke = false', function () { + it('try to fit rectangle with ignoreStroke = false', function () { var stage = addStage(); var layer = new Konva.Layer(); stage.add(layer); @@ -645,7 +672,7 @@ suite('Transformer', function () { assert.almostEqual(rect.scaleX(), 2); }); - test('listen shape changes', function () { + it('listen shape changes', function () { var stage = addStage(); var layer = new Konva.Layer(); stage.add(layer); @@ -677,7 +704,7 @@ suite('Transformer', function () { assert.equal(tr.findOne('.back').width(), rect.width()); }); - test('add transformer for transformed rect', function () { + it('add transformer for transformed rect', function () { var stage = addStage(); var layer = new Konva.Layer(); stage.add(layer); @@ -710,7 +737,7 @@ suite('Transformer', function () { assert.equal(tr.rotation(), rect.rotation()); }); - test('try to fit a transformed rect', function () { + it('try to fit a transformed rect', function () { var stage = addStage(); var layer = new Konva.Layer(); stage.add(layer); @@ -748,7 +775,7 @@ suite('Transformer', function () { assert.almostEqual(rect.rotation(), rect.rotation()); }); - test('add transformer for transformed rect with offset', function () { + it('add transformer for transformed rect with offset', function () { var stage = addStage(); var layer = new Konva.Layer(); stage.add(layer); @@ -781,7 +808,7 @@ suite('Transformer', function () { assert.equal(tr.rotation(), rect.rotation()); }); - test('fit rect with offset', function () { + it('fit rect with offset', function () { var stage = addStage(); var layer = new Konva.Layer(); stage.add(layer); @@ -824,7 +851,7 @@ suite('Transformer', function () { assert.almostEqual(rect.rotation(), rect.rotation()); }); - test('add transformer for circle', function () { + it('add transformer for circle', function () { var stage = addStage(); var layer = new Konva.Layer(); stage.add(layer); @@ -852,7 +879,7 @@ suite('Transformer', function () { assert.equal(tr.rotation(), circle.rotation()); }); - test('fit a circle', function () { + it('fit a circle', function () { var stage = addStage(); var layer = new Konva.Layer(); stage.add(layer); @@ -890,7 +917,7 @@ suite('Transformer', function () { assert.equal(tr.height(), 80); }); - test('fit a rotated circle', function () { + it('fit a rotated circle', function () { var stage = addStage(); var layer = new Konva.Layer(); stage.add(layer); @@ -929,7 +956,7 @@ suite('Transformer', function () { assert.almostEqual(tr.height(), 80); }); - test('add transformer for transformed circle', function () { + it('add transformer for transformed circle', function () { var stage = addStage(); var layer = new Konva.Layer(); stage.add(layer); @@ -958,7 +985,7 @@ suite('Transformer', function () { assert.equal(tr.rotation(), 0); }); - test('add transformer for rotated circle', function () { + it('add transformer for rotated circle', function () { var stage = addStage(); var layer = new Konva.Layer(); stage.add(layer); @@ -987,7 +1014,7 @@ suite('Transformer', function () { assert.equal(tr.rotation(), circle.rotation()); }); - test('add transformer to group', function () { + it('add transformer to group', function () { var stage = addStage(); var layer = new Konva.Layer(); stage.add(layer); @@ -1033,7 +1060,7 @@ suite('Transformer', function () { assert.equal(tr.rotation(), 0); }); - test('rotated fit group', function () { + it('rotated fit group', function () { var stage = addStage(); var layer = new Konva.Layer(); stage.add(layer); @@ -1091,7 +1118,7 @@ suite('Transformer', function () { assert.almostEqual(tr.height(), 100); }); - test('add transformer to another group', function () { + it('add transformer to another group', function () { var stage = addStage(); var layer = new Konva.Layer(); stage.add(layer); @@ -1135,7 +1162,7 @@ suite('Transformer', function () { assert.equal(tr.rotation(), 0); }); - test('fit group', function () { + it('fit group', function () { var stage = addStage(); var layer = new Konva.Layer(); stage.add(layer); @@ -1192,7 +1219,7 @@ suite('Transformer', function () { assert.almostEqual(tr.height(), 100); }); - test('toJSON should not save attached node and children', function () { + it('toJSON should not save attached node and children', function () { var stage = addStage(); var layer = new Konva.Layer(); stage.add(layer); @@ -1220,18 +1247,20 @@ suite('Transformer', function () { assert.equal(object.children, undefined); }); - test('make sure we can work without inner node', function () { + it('make sure we can work without inner node', function () { var stage = addStage(); var layer = new Konva.Layer(); stage.add(layer); var tr = new Konva.Transformer(); layer.add(tr); - layer.draw(); + + // just check not throw + assert.equal(1, 1); }); - test('reset attrs on node set', function () { + it('reset attrs on node set', function () { var stage = addStage(); var layer = new Konva.Layer(); stage.add(layer); @@ -1256,12 +1285,14 @@ suite('Transformer', function () { assert.equal(tr.getWidth(), 100); }); - test('can destroy without attached node', function () { + it('can destroy without attached node', function () { var tr = new Konva.Transformer(); tr.destroy(); + // just check not throw + assert.equal(1, 1); }); - test('can destroy with attached node while resize', function () { + it('can destroy with attached node while resize', function () { var stage = addStage(); var layer = new Konva.Layer(); stage.add(layer); @@ -1283,7 +1314,7 @@ suite('Transformer', function () { layer.draw(); - stage.simulateMouseDown({ + simulateMouseDown(tr, { x: 100, y: 60, }); @@ -1296,13 +1327,13 @@ suite('Transformer', function () { assert.equal(tr.getNode(), undefined); - stage.simulateMouseUp({ + su(stage, { x: 100, y: 60, }); }); - test('can add padding', function () { + it('can add padding', function () { var stage = addStage(); var layer = new Konva.Layer(); stage.add(layer); @@ -1324,22 +1355,17 @@ suite('Transformer', function () { layer.add(tr); layer.draw(); - stage.simulateMouseDown({ + simulateMouseDown(tr, { x: 10, y: 80, }); - var top = stage.content.getBoundingClientRect().top; - tr._handleMouseMove({ - clientX: 60, - clientY: 80 + top, + simulateMouseMove(tr, { + x: 60, + y: 80, }); - tr._handleMouseUp({ - clientX: 200, - clientY: 150, - }); - stage.simulateMouseUp({ + simulateMouseUp(tr, { x: 200, y: 150, }); @@ -1352,7 +1378,7 @@ suite('Transformer', function () { assert.almostEqual(rect.scaleY(), 1); }); - test('keep ratio should allow negative scaling', function () { + it('keep ratio should allow negative scaling', function () { var stage = addStage(); var layer = new Konva.Layer(); stage.add(layer); @@ -1376,15 +1402,15 @@ suite('Transformer', function () { var anchor = tr.findOne('.top-right'); var pos = anchor.getAbsolutePosition(); - tr.simulateMouseDown({ + simulateMouseDown(tr, { x: pos.x, y: pos.y, }); - tr.simulateMouseMove({ + simulateMouseMove(tr, { x: pos.x - 100, y: pos.y + 100, }); - tr.simulateMouseUp({ + simulateMouseUp(tr, { x: pos.x - 100, y: pos.y + 100, }); @@ -1394,7 +1420,7 @@ suite('Transformer', function () { assert.almostEqual(rect.rotation(), -180); }); - test.skip('visual test', function (done) { + it.skip('visual test', function (done) { var stage = addStage(); var layer = new Konva.Layer(); stage.add(layer); @@ -1420,7 +1446,7 @@ suite('Transformer', function () { }); }); - test('slightly move for cache check (top-left anchor)', function () { + it('slightly move for cache check (top-left anchor)', function () { var stage = addStage(); var layer = new Konva.Layer(); stage.add(layer); @@ -1445,24 +1471,24 @@ suite('Transformer', function () { var anchor = tr.findOne('.top-left'); assert.almostEqual(anchor.getAbsolutePosition().x, 20); - tr.simulateMouseDown({ + simulateMouseDown(tr, { x: 20, y: 20, }); - tr.simulateMouseMove({ + simulateMouseMove(tr, { x: 20, y: 20, }); - tr.simulateMouseUp(); + simulateMouseUp(tr); layer.draw(); assert.almostEqual(rect.x(), 20); assert.almostEqual(rect.y(), 20); }); - test('rotation snaps', function () { + it('rotation snaps', function () { var stage = addStage(); var layer = new Konva.Layer(); stage.add(layer); @@ -1485,76 +1511,76 @@ suite('Transformer', function () { layer.draw(); - tr.simulateMouseDown({ + simulateMouseDown(tr, { x: 100, y: 0, }); // move to almost 45 deg - tr.simulateMouseMove({ + simulateMouseMove(tr, { x: 199, y: 0, }); assert.equal(rect.rotation(), 0); // move to more than 45 deg - tr.simulateMouseMove({ + simulateMouseMove(tr, { x: 200, y: 2, }); assert.equal(rect.rotation(), 90); - tr.simulateMouseMove({ + simulateMouseMove(tr, { x: 200, y: 199, }); assert.equal(rect.rotation(), 90); - tr.simulateMouseMove({ + simulateMouseMove(tr, { x: 199, y: 200, }); assert.equal(rect.rotation(), 180); - tr.simulateMouseMove({ + simulateMouseMove(tr, { x: 1, y: 200, }); assert.equal(rect.rotation(), 180); - tr.simulateMouseMove({ + simulateMouseMove(tr, { x: 0, y: 199, }); assert.almostEqual(rect.rotation(), -90); - tr.simulateMouseMove({ + simulateMouseMove(tr, { x: 0, y: 50, }); assert.almostEqual(rect.rotation(), -90); - tr.simulateMouseMove({ + simulateMouseMove(tr, { x: 0, y: 45, }); assert.almostEqual(rect.rotation(), -90); - tr.simulateMouseMove({ + simulateMouseMove(tr, { x: 0, y: 1, }); assert.almostEqual(rect.rotation(), -90); - tr.simulateMouseMove({ + simulateMouseMove(tr, { x: 1, y: 0, }); assert.equal(rect.rotation(), 0); - tr.simulateMouseUp(); + simulateMouseUp(tr); }); - test('switch scaling with padding - x', function () { + it('switch scaling with padding - x', function () { var stage = addStage(); var layer = new Konva.Layer(); stage.add(layer); @@ -1577,12 +1603,12 @@ suite('Transformer', function () { layer.draw(); - tr.simulateMouseDown({ + simulateMouseDown(tr, { x: 0, y: 60, }); - tr.simulateMouseMove({ + simulateMouseMove(tr, { x: 125, y: 60, }); @@ -1595,7 +1621,7 @@ suite('Transformer', function () { assert.almostEqual(rect.height(), 100); assert.almostEqual(rect.rotation(), -180); - tr.simulateMouseMove({ + simulateMouseMove(tr, { x: 125, y: 60, }); @@ -1608,7 +1634,7 @@ suite('Transformer', function () { assert.almostEqual(rect.scaleY(), -1); // switch again - tr.simulateMouseMove({ + simulateMouseMove(tr, { x: 90, y: 60, }); @@ -1620,10 +1646,10 @@ suite('Transformer', function () { assert.almostEqual(rect.scaleX(), 0.1); assert.almostEqual(rect.height(), 100); - tr.simulateMouseUp(); + simulateMouseUp(tr); }); - test('switch scaling with padding - y', function () { + it('switch scaling with padding - y', function () { var stage = addStage(); var layer = new Konva.Layer(); stage.add(layer); @@ -1646,12 +1672,12 @@ suite('Transformer', function () { layer.draw(); - tr.simulateMouseDown({ + simulateMouseDown(tr, { x: 60, y: 0, }); - tr.simulateMouseMove({ + simulateMouseMove(tr, { x: 60, y: 125, }); @@ -1663,7 +1689,7 @@ suite('Transformer', function () { assert.almostEqual(rect.height(), 100); assert.almostEqual(rect.rotation(), 0); - tr.simulateMouseMove({ + simulateMouseMove(tr, { x: 60, y: 125, }); @@ -1676,7 +1702,7 @@ suite('Transformer', function () { assert.almostEqual(rect.rotation(), 0); // switch again - tr.simulateMouseMove({ + simulateMouseMove(tr, { x: 60, y: 90, }); @@ -1689,10 +1715,10 @@ suite('Transformer', function () { assert.almostEqual(rect.height(), 100); assert.almostEqual(rect.rotation(), 0); - tr.simulateMouseUp(); + simulateMouseUp(tr); }); - test('switch horizontal scaling with (top-left anchor)', function () { + it('switch horizontal scaling with (top-left anchor)', function () { var stage = addStage(); var layer = new Konva.Layer(); stage.add(layer); @@ -1714,12 +1740,12 @@ suite('Transformer', function () { layer.draw(); - tr.simulateMouseDown({ + simulateMouseDown(tr, { x: 0, y: 0, }); - tr.simulateMouseMove({ + simulateMouseMove(tr, { x: 150, y: 50, }); @@ -1733,45 +1759,45 @@ suite('Transformer', function () { assert.almostEqual(rect.height(), 100); assert.almostEqual(rect.rotation(), -180); - tr.simulateMouseMove({ + simulateMouseMove(tr, { x: 98, y: 2.859375, }); - tr.simulateMouseMove({ + simulateMouseMove(tr, { x: 98, y: 2.859375, }); - tr.simulateMouseMove({ + simulateMouseMove(tr, { x: 98, y: 2.859375, }); - tr.simulateMouseMove({ + simulateMouseMove(tr, { x: 100, y: 2.859375, }); layer.draw(); - tr.simulateMouseMove({ + simulateMouseMove(tr, { x: 101, y: 2.859375, }); layer.draw(); - tr.simulateMouseMove({ + simulateMouseMove(tr, { x: 101, y: 2.859375, }); layer.draw(); - tr.simulateMouseMove({ + simulateMouseMove(tr, { x: 101, y: 2.859375, }); layer.draw(); - tr.simulateMouseMove({ + simulateMouseMove(tr, { x: 102, y: 2.859375, }); layer.draw(); // switch again - tr.simulateMouseMove({ + simulateMouseMove(tr, { x: 0, y: 0, }); @@ -1783,10 +1809,10 @@ suite('Transformer', function () { assert.almostEqual(rect.scaleX(), 1); assert.almostEqual(rect.height(), 100); - tr.simulateMouseUp(); + simulateMouseUp(tr); }); - test('switch vertical scaling with (top-left anchor)', function () { + it('switch vertical scaling with (top-left anchor)', function () { var stage = addStage(); var layer = new Konva.Layer(); stage.add(layer); @@ -1808,12 +1834,12 @@ suite('Transformer', function () { layer.draw(); - tr.simulateMouseDown({ + simulateMouseDown(tr, { x: 0, y: 0, }); - tr.simulateMouseMove({ + simulateMouseMove(tr, { x: 0, y: 200, }); @@ -1826,12 +1852,12 @@ suite('Transformer', function () { assert.almostEqual(rect.height(), 100); assert.almostEqual(rect.rotation(), 0); - tr.simulateMouseMove({ + simulateMouseMove(tr, { x: 0, y: 0, }); layer.draw(); - tr.simulateMouseUp(); + simulateMouseUp(tr); assert.almostEqual(rect.x(), 0); assert.almostEqual(rect.y(), 0); @@ -1842,7 +1868,7 @@ suite('Transformer', function () { assert.almostEqual(rect.scaleY(), 1); }); - test('switch scaling with padding for rotated - x', function () { + it('switch scaling with padding for rotated - x', function () { var stage = addStage(); var layer = new Konva.Layer(); stage.add(layer); @@ -1866,12 +1892,12 @@ suite('Transformer', function () { layer.draw(); - tr.simulateMouseDown({ + simulateMouseDown(tr, { x: 60, y: 0, }); - tr.simulateMouseMove({ + simulateMouseMove(tr, { x: 60, y: 125, }); @@ -1884,7 +1910,7 @@ suite('Transformer', function () { assert.almostEqual(rect.height(), 100); assert.almostEqual(rect.rotation(), -90); - tr.simulateMouseMove({ + simulateMouseMove(tr, { x: 60, y: 125, }); @@ -1899,7 +1925,7 @@ suite('Transformer', function () { layer.draw(); // switch again - tr.simulateMouseMove({ + simulateMouseMove(tr, { x: 60, y: 90, }); @@ -1912,10 +1938,10 @@ suite('Transformer', function () { assert.almostEqual(rect.height(), 100); - tr.simulateMouseUp(); + simulateMouseUp(tr); }); - test('switch scaling with padding for rotated - y', function () { + it('switch scaling with padding for rotated - y', function () { var stage = addStage(); var layer = new Konva.Layer(); stage.add(layer); @@ -1939,12 +1965,12 @@ suite('Transformer', function () { layer.draw(); - tr.simulateMouseDown({ + simulateMouseDown(tr, { x: 0, y: 60, }); - tr.simulateMouseMove({ + simulateMouseMove(tr, { x: 125, y: 60, }); @@ -1957,7 +1983,7 @@ suite('Transformer', function () { assert.almostEqual(rect.height(), 100); assert.almostEqual(rect.rotation(), 90); - tr.simulateMouseMove({ + simulateMouseMove(tr, { x: 125, y: 60, }); @@ -1971,7 +1997,7 @@ suite('Transformer', function () { assert.almostEqual(rect.rotation(), 90); // switch again - tr.simulateMouseMove({ + simulateMouseMove(tr, { x: 90, y: 60, }); @@ -1983,10 +2009,10 @@ suite('Transformer', function () { assert.almostEqual(rect.scaleY(), 0.1); assert.almostEqual(rect.height(), 100); - tr.simulateMouseUp(); + simulateMouseUp(tr); }); - test('transformer should automatically track attr changes of a node', function () { + it('transformer should automatically track attr changes of a node', function () { var stage = addStage(); var layer = new Konva.Layer(); stage.add(layer); @@ -2039,7 +2065,7 @@ suite('Transformer', function () { layer.batchDraw(); }); - test('on detach should remove all listeners', function () { + it('on detach should remove all listeners', function () { var stage = addStage(); var layer = new Konva.Layer(); stage.add(layer); @@ -2077,7 +2103,7 @@ suite('Transformer', function () { assert.equal(called, false, 'don not call clear cache'); }); - test('check transformer with drag&drop', function () { + it('check transformer with drag&drop', function () { var stage = addStage(); var layer = new Konva.Layer(); @@ -2101,17 +2127,17 @@ suite('Transformer', function () { layer.draw(); - stage.simulateMouseDown({ + simulateMouseDown(tr, { x: 20, y: 20, }); - stage.simulateMouseMove({ + sm(stage, { x: 30, y: 30, }); - stage.simulateMouseUp({ + su(stage, { x: 30, y: 30, }); @@ -2123,7 +2149,7 @@ suite('Transformer', function () { assert.equal(tr.y(), 10); }); - test('check transformer with drag&drop and scaled shape', function () { + it('check transformer with drag&drop and scaled shape', function () { var stage = addStage(); var layer = new Konva.Layer(); @@ -2148,12 +2174,12 @@ suite('Transformer', function () { layer.draw(); - stage.simulateMouseDown({ + simulateMouseDown(tr, { x: 20, y: 20, }); - stage.simulateMouseMove({ + sm(stage, { x: 30, y: 30, }); @@ -2168,13 +2194,13 @@ suite('Transformer', function () { assert.equal(tr.width(), 200); - stage.simulateMouseUp({ + su(stage, { x: 30, y: 30, }); }); - test('try rotate scaled rect', function () { + it('try rotate scaled rect', function () { var stage = addStage(); var layer = new Konva.Layer(); stage.add(layer); @@ -2199,15 +2225,15 @@ suite('Transformer', function () { var rotater = tr.findOne('.rotater'); var pos = rotater.getAbsolutePosition(); - tr.simulateMouseDown({ + simulateMouseDown(tr, { x: pos.x, y: pos.y, }); - tr.simulateMouseMove({ + simulateMouseMove(tr, { x: pos.x + 100, y: pos.y + 100, }); - tr.simulateMouseUp({ + simulateMouseUp(tr, { x: pos.x + 100, y: pos.y + 100, }); @@ -2215,7 +2241,10 @@ suite('Transformer', function () { assert.equal(rect.rotation(), 90); }); - test('check correct cursor on scaled shape', function () { + it('check correct cursor on scaled shape', function () { + if (isNode) { + return; + } var stage = addStage(); var layer = new Konva.Layer(); stage.add(layer); @@ -2237,14 +2266,17 @@ suite('Transformer', function () { layer.add(tr); layer.draw(); - stage.simulateMouseMove({ + sm(stage, { x: 50, y: 1, }); assert.equal(stage.content.style.cursor, 'nwse-resize'); }); - test('check correct cursor off on Transformer destroy', function () { + it('check correct cursor off on Transformer destroy', function () { + if (isNode) { + return; + } var stage = addStage(); var layer = new Konva.Layer(); stage.add(layer); @@ -2265,11 +2297,11 @@ suite('Transformer', function () { layer.add(tr); layer.draw(); - stage.simulateMouseMove({ + sm(stage, { x: 100, y: 100, }); - stage.simulateMouseDown({ + simulateMouseDown(tr, { x: 100, y: 100, }); @@ -2280,31 +2312,33 @@ suite('Transformer', function () { x: 100, y: 100, }); - var top = stage.content.getBoundingClientRect().top; - tr._handleMouseMove({ - clientX: 120, - clientY: 100 + top, + simulateMouseMove(tr, { + x: 120, + y: 100, }); // here is duplicate, because transformer is listening window events - tr._handleMouseUp({ - clientX: 120, - clientY: 100 + top, + simulateMouseUp(tr, { + x: 120, + y: 100, }); - stage.simulateMouseUp({ + su(stage, { x: 120, y: 100, }); tr.destroy(); - stage.simulateMouseMove({ + sm(stage, { x: 140, y: 100, }); assert.equal(stage.content.style.cursor, ''); }); - test('check correct cursor on scaled parent', function () { + it('check correct cursor on scaled parent', function () { + if (isNode) { + return; + } var stage = addStage(); var layer = new Konva.Layer({ y: 100, @@ -2328,14 +2362,14 @@ suite('Transformer', function () { layer.add(tr); layer.draw(); - stage.simulateMouseMove({ + sm(stage, { x: 50, y: 1, }); assert.equal(stage.content.style.cursor, 'nwse-resize'); }); - test('changing parent transform should recalculate transformer attrs', function () { + it('changing parent transform should recalculate transformer attrs', function () { var stage = addStage(); var layer = new Konva.Layer(); stage.add(layer); @@ -2363,7 +2397,10 @@ suite('Transformer', function () { assert.equal(tr.width(), 200); }); - test('check fit and correct cursor on rotated parent', function () { + it('check fit and correct cursor on rotated parent', function () { + if (isNode) { + return; + } var stage = addStage(); var layer = new Konva.Layer({ x: 100, @@ -2402,14 +2439,14 @@ suite('Transformer', function () { assert.equal(Math.round(tr.width()), Math.round(box.width)); assert.equal(Math.round(tr.height()), Math.round(box.height)); - stage.simulateMouseMove({ + sm(stage, { x: 50, y: 1, }); assert.equal(stage.content.style.cursor, 'ns-resize'); }); - test('check drag with transformer', function () { + it('check drag with transformer', function () { var stage = addStage(); stage.draggable(true); var layer = new Konva.Layer(); @@ -2431,21 +2468,21 @@ suite('Transformer', function () { layer.add(tr); layer.draw(); - stage.simulateMouseDown({ + simulateMouseDown(tr, { x: 50, y: 50, }); - stage.simulateMouseMove({ + sm(stage, { x: 55, y: 50, }); - stage.simulateMouseMove({ + sm(stage, { x: 60, y: 50, }); - stage.simulateMouseUp({ + su(stage, { x: 60, y: 50, }); @@ -2454,7 +2491,7 @@ suite('Transformer', function () { assert.equal(rect.y(), 0); }); - test('stopTransform method', function () { + it('stopTransform method', function () { var stage = addStage(); var layer = new Konva.Layer(); stage.add(layer); @@ -2475,15 +2512,14 @@ suite('Transformer', function () { layer.add(tr); layer.draw(); - stage.simulateMouseDown({ + simulateMouseDown(tr, { x: 50, y: 50, }); - var top = stage.content.getBoundingClientRect().top; - tr._handleMouseMove({ - clientX: 60, - clientY: 60 + top, + simulateMouseMove(tr, { + x: 60, + y: 60, }); assert.equal(tr.isTransforming(), true); @@ -2502,13 +2538,13 @@ suite('Transformer', function () { assert.equal(rect.x(), 60); // here is duplicate, because transformer is listening window events - stage.simulateMouseUp({ + su(stage, { x: 100, y: 100, }); }); - test('transform events check', function () { + it('transform events check', function () { var stage = addStage(); var layer = new Konva.Layer(); stage.add(layer); @@ -2563,17 +2599,17 @@ suite('Transformer', function () { assert.equal(e.target, rect); }); - tr.simulateMouseDown({ + simulateMouseDown(tr, { x: 50, y: 50, }); - tr.simulateMouseMove({ + simulateMouseMove(tr, { x: 60, y: 60, }); - tr.simulateMouseUp({ + simulateMouseUp(tr, { x: 60, y: 60, }); @@ -2582,7 +2618,7 @@ suite('Transformer', function () { assert.equal(tr.getActiveAnchor(), null); }); - test('on force update should clear transform', function () { + it('on force update should clear transform', function () { var stage = addStage(); var layer = new Konva.Layer(); stage.add(layer); @@ -2629,7 +2665,7 @@ suite('Transformer', function () { // assert.equal(rect.rotation(), rect.rotation()); }); - test('test cache reset on attach', function () { + it('test cache reset on attach', function () { var stage = addStage(); var layer = new Konva.Layer(); stage.add(layer); @@ -2661,7 +2697,7 @@ suite('Transformer', function () { assert.equal(shape.name(), 'top-left _anchor'); }); - test('check rotator size on scaled transformer', function () { + it('check rotator size on scaled transformer', function () { var stage = addStage(); var layer = new Konva.Layer({ scaleX: 10, @@ -2815,7 +2851,7 @@ suite('Transformer', function () { // } ]; - test('if alt is pressed should transform around center', function () { + it('if alt is pressed should transform around center', function () { var stage = addStage(); var layer = new Konva.Layer(); stage.add(layer); @@ -2844,23 +2880,22 @@ suite('Transformer', function () { layer.draw(); - stage.simulateMouseDown(test.startPos); + simulateMouseDown(tr, test.startPos); var target = stage.getIntersection(test.startPos); - var top = stage.content.getBoundingClientRect().top; - tr._handleMouseMove({ + simulateMouseMove(tr, { target: target, - clientX: test.endPos.x, - clientY: test.endPos.y + top, + x: test.endPos.x, + y: test.endPos.y, altKey: true, }); // here is duplicate, because transformer is listening window events - tr._handleMouseUp({ - clientX: test.endPos.x, - clientY: test.endPos.y + top, + simulateMouseUp(tr, { + x: test.endPos.x, + y: test.endPos.y, }); - stage.simulateMouseUp({ + su(stage, { x: test.endPos.x, y: test.endPos.y, }); @@ -2879,7 +2914,7 @@ suite('Transformer', function () { }); }); - test('centered scaling - no keep ratio', function () { + it('centered scaling - no keep ratio', function () { var stage = addStage(); var layer = new Konva.Layer(); stage.add(layer); @@ -2910,22 +2945,21 @@ suite('Transformer', function () { layer.draw(); - stage.simulateMouseDown(test.startPos); + simulateMouseDown(tr, test.startPos); var target = stage.getIntersection(test.startPos); - var top = stage.content.getBoundingClientRect().top; - tr._handleMouseMove({ + simulateMouseMove(tr, { target: target, - clientX: test.endPos.x, - clientY: test.endPos.y + top, + x: test.endPos.x, + y: test.endPos.y, }); // here is duplicate, because transformer is listening window events - tr._handleMouseUp({ - clientX: test.endPos.x, - clientY: test.endPos.y + top, + simulateMouseUp(tr, { + x: test.endPos.x, + y: test.endPos.y, }); - stage.simulateMouseUp({ + su(stage, { x: test.endPos.x, y: test.endPos.y, }); @@ -2944,7 +2978,7 @@ suite('Transformer', function () { }); }); - test('centered scaling', function () { + it('centered scaling', function () { var stage = addStage(); var layer = new Konva.Layer(); stage.add(layer); @@ -2974,22 +3008,21 @@ suite('Transformer', function () { layer.draw(); - stage.simulateMouseDown(test.startPos); + simulateMouseDown(tr, test.startPos); var target = stage.getIntersection(test.startPos); - var top = stage.content.getBoundingClientRect().top; - tr._handleMouseMove({ + simulateMouseMove(tr, { target: target, - clientX: test.endPos.x, - clientY: test.endPos.y + top, + x: test.endPos.x, + y: test.endPos.y, }); // here is duplicate, because transformer is listening window events - tr._handleMouseUp({ - clientX: test.endPos.x, - clientY: test.endPos.y + top, + simulateMouseUp(tr, { + x: test.endPos.x, + y: test.endPos.y, }); - stage.simulateMouseUp({ + su(stage, { x: test.endPos.x, y: test.endPos.y, }); @@ -3008,7 +3041,7 @@ suite('Transformer', function () { }); }); - test('centered scaling on flip + keep ratio', function () { + it('centered scaling on flip + keep ratio', function () { var stage = addStage(); var layer = new Konva.Layer(); stage.add(layer); @@ -3063,8 +3096,8 @@ suite('Transformer', function () { layer.draw(); // move from start to end - tr.simulateMouseDown(start); - tr.simulateMouseMove(end); + simulateMouseDown(tr, start); + simulateMouseMove(tr, end); var box = rect.getClientRect(); assert.almostEqual(box.x, 0); assert.almostEqual(box.y, 0); @@ -3072,7 +3105,7 @@ suite('Transformer', function () { assert.almostEqual(box.height, 100); // make extra move on end - tr.simulateMouseMove(end); + simulateMouseMove(tr, end); var box = rect.getClientRect(); assert.almostEqual(box.x, 0); assert.almostEqual(box.y, 0); @@ -3080,8 +3113,8 @@ suite('Transformer', function () { assert.almostEqual(box.height, 100); // move back - tr.simulateMouseMove(start); - tr.simulateMouseUp(); + simulateMouseMove(tr, start); + simulateMouseUp(tr); assert.almostEqual(box.x, 0); assert.almostEqual(box.y, 0); assert.almostEqual(box.width, 200); @@ -3089,7 +3122,7 @@ suite('Transformer', function () { }); }); - test('transform scaled (in one direction) node', function () { + it('transform scaled (in one direction) node', function () { var stage = addStage(); var layer = new Konva.Layer(); stage.add(layer); @@ -3114,7 +3147,7 @@ suite('Transformer', function () { layer.draw(); - stage.simulateMouseDown({ + simulateMouseDown(tr, { x: 150, y: 150, }); @@ -3123,18 +3156,17 @@ suite('Transformer', function () { x: 150, y: 150, }); - var top = Math.round(stage.content.getBoundingClientRect().top); - tr._handleMouseMove({ - clientX: 100, - clientY: 100 + top, + simulateMouseMove(tr, { + x: 100, + y: 100, }); // here is duplicate, because transformer is listening window events - tr._handleMouseUp({ - clientX: 100, - clientY: 100 + top, + simulateMouseUp(tr, { + x: 100, + y: 100, }); - stage.simulateMouseUp({ + su(stage, { x: 100, y: 100, }); @@ -3144,7 +3176,7 @@ suite('Transformer', function () { assert.equal(rect.height() * rect.scaleY() + 50 < 1, true, ' height check'); }); - test('transformer should ignore shadow', function () { + it('transformer should ignore shadow', function () { var stage = addStage(); var layer = new Konva.Layer(); stage.add(layer); @@ -3187,7 +3219,7 @@ suite('Transformer', function () { assert.equal(rect.height(), 100); }); - test.skip('transformer should skip scale on stroke if strokeScaleEnabled = false', function () { + it.skip('transformer should skip scale on stroke if strokeScaleEnabled = false', function () { var stage = addStage(); var layer = new Konva.Layer(); stage.add(layer); @@ -3235,7 +3267,7 @@ suite('Transformer', function () { assert.equal(rect.height(), 100); }); - test.skip('check calculations when the size = 0', function () { + it.skip('check calculations when the size = 0', function () { var stage = addStage(); var layer = new Konva.Layer(); stage.add(layer); @@ -3268,14 +3300,14 @@ suite('Transformer', function () { assert.equal(rect.scaleX(), 1); }); - test('attrs change - arc', function () { + it('attrs change - arc', function () { var stage = addStage(); var layer = new Konva.Layer(); stage.add(layer); var shape = new Konva.Arc({ - x: stage.getWidth() / 2, - y: stage.getHeight() / 2, + x: stage.width() / 2, + y: stage.height() / 2, innerRadius: 40, outerRadius: 70, angle: 60, @@ -3301,14 +3333,14 @@ suite('Transformer', function () { layer.draw(); }); - test('attrs change - line', function () { + it('attrs change - line', function () { var stage = addStage(); var layer = new Konva.Layer(); stage.add(layer); var shape = new Konva.Arrow({ - x: stage.getWidth() / 4, - y: stage.getHeight() / 4, + x: stage.width() / 4, + y: stage.height() / 4, points: [0, 0, stage.width() / 2, stage.height() / 2], pointerLength: 20, pointerWidth: 20, @@ -3339,14 +3371,14 @@ suite('Transformer', function () { assert.deepEqual(shape.getClientRect(), rect); }); - test('attrs change - circle', function () { + it('attrs change - circle', function () { var stage = addStage(); var layer = new Konva.Layer(); stage.add(layer); var shape = new Konva.Circle({ - x: stage.getWidth() / 2, - y: stage.getHeight() / 2, + x: stage.width() / 2, + y: stage.height() / 2, radius: 40, fill: 'yellow', stroke: 'black', @@ -3366,18 +3398,16 @@ suite('Transformer', function () { assert.deepEqual(shape.getClientRect(), rect); }); - test('attrs change - ellipse', function () { + it('attrs change - ellipse', function () { var stage = addStage(); var layer = new Konva.Layer(); stage.add(layer); var shape = new Konva.Ellipse({ - x: stage.getWidth() / 2, - y: stage.getHeight() / 2, - radius: { - x: 100, - y: 50, - }, + x: stage.width() / 2, + y: stage.height() / 2, + radiusX: 100, + radiusY: 50, fill: 'yellow', stroke: 'black', strokeWidth: 4, @@ -3404,14 +3434,14 @@ suite('Transformer', function () { layer.draw(); }); - test('attrs change - rect', function () { + it('attrs change - rect', function () { var stage = addStage(); var layer = new Konva.Layer(); stage.add(layer); var shape = new Konva.Rect({ - x: stage.getWidth() / 2, - y: stage.getHeight() / 2, + x: stage.width() / 2, + y: stage.height() / 2, width: 100, height: 100, fill: 'yellow', @@ -3440,7 +3470,7 @@ suite('Transformer', function () { layer.draw(); }); - test('attrs change - path', function () { + it('attrs change - path', function () { var stage = addStage(); var layer = new Konva.Layer(); stage.add(layer); @@ -3467,7 +3497,7 @@ suite('Transformer', function () { assert.deepEqual(shape.getClientRect(), rect); }); - test('attrs change - regular polygon', function () { + it('attrs change - regular polygon', function () { var stage = addStage(); var layer = new Konva.Layer(); stage.add(layer); @@ -3496,14 +3526,14 @@ suite('Transformer', function () { assert.deepEqual(shape.getClientRect(), rect); }); - test('attrs change - ring', function () { + it('attrs change - ring', function () { var stage = addStage(); var layer = new Konva.Layer(); stage.add(layer); var shape = new Konva.Ring({ - x: stage.getWidth() / 2, - y: stage.getHeight() / 2, + x: stage.width() / 2, + y: stage.height() / 2, innerRadius: 40, outerRadius: 70, fill: 'yellow', @@ -3532,14 +3562,14 @@ suite('Transformer', function () { layer.draw(); }); - test('attrs change - star', function () { + it('attrs change - star', function () { var stage = addStage(); var layer = new Konva.Layer(); stage.add(layer); var shape = new Konva.Star({ - x: stage.getWidth() / 2, - y: stage.getHeight() / 2, + x: stage.width() / 2, + y: stage.height() / 2, numPoints: 6, innerRadius: 40, outerRadius: 70, @@ -3569,14 +3599,14 @@ suite('Transformer', function () { layer.draw(); }); - test('attrs change - wedge', function () { + it('attrs change - wedge', function () { var stage = addStage(); var layer = new Konva.Layer(); stage.add(layer); var shape = new Konva.Wedge({ - x: stage.getWidth() / 2, - y: stage.getHeight() / 2, + x: stage.width() / 2, + y: stage.height() / 2, radius: 70, angle: 60, fill: 'red', @@ -3597,13 +3627,13 @@ suite('Transformer', function () { assert.deepEqual(shape.getClientRect(), rect); }); - test('attrs change - text', function () { + it('attrs change - text', function () { var stage = addStage(); var layer = new Konva.Layer(); stage.add(layer); var shape = new Konva.Text({ - x: stage.getWidth() / 2, + x: stage.width() / 2, y: 15, text: 'Simple Text', fontSize: 60, @@ -3654,7 +3684,7 @@ suite('Transformer', function () { assert.deepEqual(shape.getClientRect(), rect, 'change height'); }); - test('attrs change - text path', function () { + it('attrs change - text path', function () { var stage = addStage(); var layer = new Konva.Layer(); stage.add(layer); @@ -3695,7 +3725,7 @@ suite('Transformer', function () { assert.deepEqual(shape.getClientRect(), rect), 'change data'; }); - test('make sure transformer events are not cloned', function () { + it('make sure transformer events are not cloned', function () { var stage = addStage(); var layer = new Konva.Layer(); stage.add(layer); @@ -3733,10 +3763,15 @@ suite('Transformer', function () { // should not throw error rect2.width(100); + assert(tr2.width(), 200); + stage.draw(); }); - test('try to move anchor on scaled with css stage', function () { + it('try to move anchor on scaled with css stage', function () { + if (isNode) { + return; + } var stage = addStage(); stage.container().style.transform = 'scale(0.5)'; stage.container().style.transformOrigin = 'top left'; @@ -3761,11 +3796,11 @@ suite('Transformer', function () { layer.add(tr); layer.draw(); - stage.simulateMouseMove({ + sm(stage, { x: 50, y: 50, }); - stage.simulateMouseDown({ + simulateMouseDown(tr, { x: 50, y: 50, }); @@ -3774,18 +3809,17 @@ suite('Transformer', function () { x: 50, y: 50, }); - var top = stage.content.getBoundingClientRect().top; - tr._handleMouseMove({ - clientX: 100, - clientY: 50 + top, + simulateMouseMove(tr, { + x: 100, + y: 50, }); // here is duplicate, because transformer is listening window events - tr._handleMouseUp({ - clientX: 100, - clientY: 50 + top, + simulateMouseUp(tr, { + x: 100, + y: 50, }); - stage.simulateMouseUp({ + su(stage, { x: 100, y: 50, }); @@ -3793,7 +3827,7 @@ suite('Transformer', function () { assert.almostEqual(rect.width() * rect.scaleX(), 200); }); - test('rotate several nodes', function () { + it('rotate several nodes', function () { var stage = addStage(); var layer = new Konva.Layer(); stage.add(layer); @@ -3862,7 +3896,7 @@ suite('Transformer', function () { assert.almostEqual(tr.rotation(), 180); }); - test('events on several nodes', function () { + it('events on several nodes', function () { var stage = addStage(); var layer = new Konva.Layer(); stage.add(layer); @@ -3917,18 +3951,17 @@ suite('Transformer', function () { layer.draw(); - stage.simulateMouseDown({ + simulateMouseDown(tr, { x: 100, y: 60, }); - var top = stage.content.getBoundingClientRect().top; - tr._handleMouseMove({ - clientX: 105, - clientY: 60 + top, + simulateMouseMove(tr, { + x: 105, + y: 60, }); - tr.simulateMouseUp({ + simulateMouseUp(tr, { x: 105, y: 60, }); @@ -3938,7 +3971,7 @@ suite('Transformer', function () { assert.equal(transformend, 2); }); - test('transform several rotated nodes', function () { + it('transform several rotated nodes', function () { var stage = addStage(); var layer = new Konva.Layer(); stage.add(layer); @@ -4006,7 +4039,7 @@ suite('Transformer', function () { assert.almostEqual(tr.y(), 100); }); - test('drag several nodes', function () { + it('drag several nodes', function () { var stage = addStage(); var layer = new Konva.Layer(); stage.add(layer); @@ -4072,21 +4105,21 @@ suite('Transformer', function () { layer.add(tr); layer.draw(); - stage.simulateMouseDown({ + simulateMouseDown(tr, { x: 75, y: 75, }); - stage.simulateMouseMove({ + sm(stage, { x: 80, y: 80, }); - stage.simulateMouseMove({ + sm(stage, { x: 85, y: 85, }); - stage.simulateMouseUp({ + su(stage, { x: 80, y: 80, }); @@ -4099,7 +4132,7 @@ suite('Transformer', function () { assert.equal(dragend, 2); }); - test('reattach from several and drag one', function () { + it('reattach from several and drag one', function () { var stage = addStage(); var layer = new Konva.Layer(); stage.add(layer); @@ -4134,16 +4167,16 @@ suite('Transformer', function () { tr.nodes([rect1]); // now drag just the first - stage.simulateMouseDown({ + simulateMouseDown(tr, { x: 125, y: 125, }); - stage.simulateMouseMove({ + sm(stage, { x: 130, y: 130, }); - stage.simulateMouseUp({ + su(stage, { x: 130, y: 130, }); @@ -4153,7 +4186,7 @@ suite('Transformer', function () { assert.equal(rect1.y(), 50); }); - test('transformer should not hide shapes', function () { + it('transformer should not hide shapes', function () { var stage = addStage(); var layer = new Konva.Layer(); stage.add(layer); @@ -4180,16 +4213,16 @@ suite('Transformer', function () { layer.add(tr); layer.draw(); - stage.simulateMouseDown({ + simulateMouseDown(tr, { x: 75, y: 75, }); - stage.simulateMouseMove({ + sm(stage, { x: 75, y: 75, }); - stage.simulateMouseUp({ + su(stage, { x: 75, y: 75, }); @@ -4198,7 +4231,7 @@ suite('Transformer', function () { assert.equal(click, 1); }); - test('drag several nodes by transformer back', function () { + it('drag several nodes by transformer back', function () { var stage = addStage(); var layer = new Konva.Layer(); stage.add(layer); @@ -4264,23 +4297,23 @@ suite('Transformer', function () { layer.add(tr); layer.draw(); - stage.simulateMouseDown({ + simulateMouseDown(tr, { x: 110, y: 90, }); // move mouse twice // because first move will jus trigger start dragging - stage.simulateMouseMove({ + sm(stage, { x: 120, y: 90, }); - stage.simulateMouseMove({ + sm(stage, { x: 120, y: 90, }); - stage.simulateMouseUp({ + su(stage, { x: 120, y: 90, }); @@ -4295,7 +4328,7 @@ suite('Transformer', function () { assert.equal(dragend, 3); }); - test('reattach to several nodes', function () { + it('reattach to several nodes', function () { var stage = addStage(); var layer = new Konva.Layer(); stage.add(layer); @@ -4351,7 +4384,7 @@ suite('Transformer', function () { assert.almostEqual(tr.rotation(), 0); }); - test('rotate several nodes inside different parents', function () { + it('rotate several nodes inside different parents', function () { var stage = addStage(); var layer = new Konva.Layer(); stage.add(layer); @@ -4427,7 +4460,7 @@ suite('Transformer', function () { assert.almostEqual(rect2.rotation(), 0); }); - test('can attach transformer into several nodes and fit into negative scale', function () { + it('can attach transformer into several nodes and fit into negative scale', function () { var stage = addStage(); var layer = new Konva.Layer(); stage.add(layer); @@ -4482,7 +4515,7 @@ suite('Transformer', function () { assert.almostEqual(tr.rotation(), 0); }); - test('boundBoxFox should work in absolute coordinates', function () { + it('boundBoxFox should work in absolute coordinates', function () { var stage = addStage(); var layer = new Konva.Layer({ x: 10, @@ -4547,8 +4580,8 @@ suite('Transformer', function () { assert.equal(callCount, 1); }); - // TODO: what can we test here? - test('performance check - drag several nodes', function () { + // TODO: move to manual tests + it.skip('performance check - drag several nodes', function () { var stage = addStage(); var layer = new Konva.Layer(); stage.add(layer); @@ -4563,23 +4596,25 @@ suite('Transformer', function () { }); layer.add(shape); } - var shapes = layer.find('Circle').toArray(); + var shapes = layer.find('Circle'); var tr = new Konva.Transformer({ nodes: shapes, }); layer.add(tr); layer.draw(); + + throw 1; }); // we don't support height = 0 - test.skip('try to tranform zero size shape', function () { + it.skip('try to transform zero size shape', function () { var stage = addStage(); var layer = new Konva.Layer(); stage.add(layer); var shape = new Konva.Line({ - x: stage.getWidth() / 4, - y: stage.getHeight() / 4, + x: stage.width() / 4, + y: stage.height() / 4, points: [0, 0, 200, 0], fill: 'black', stroke: 'black', @@ -4597,15 +4632,15 @@ suite('Transformer', function () { layer.draw(); - tr.simulateMouseDown({ + simulateMouseDown(tr, { x: stage.width() / 2, y: stage.height() / 2, }); - tr.simulateMouseDown({ + simulateMouseDown(tr, { x: stage.width() / 2 + 100, y: stage.height() / 2, }); - tr.simulateMouseUp(); + simulateMouseUp(tr); assert.equal(shape.scaleX(), 0.5); }); }); diff --git a/test/unit/shapes/Wedge-test.js b/test/unit-new/shapes/Wedge-test.ts similarity index 84% rename from test/unit/shapes/Wedge-test.js rename to test/unit-new/shapes/Wedge-test.ts index e35e17b1..28800228 100644 --- a/test/unit/shapes/Wedge-test.js +++ b/test/unit-new/shapes/Wedge-test.ts @@ -1,6 +1,10 @@ -suite('Wedge', function () { +import { assert } from 'chai'; + +import { addStage, Konva } from '../utis'; + +describe('Wedge', function () { // ====================================================== - test('add wedge', function () { + it('add wedge', function () { var stage = addStage(); var layer = new Konva.Layer(); var wedge = new Konva.Wedge({ @@ -28,12 +32,12 @@ suite('Wedge', function () { ); }); - test('attrs sync', function () { + it('attrs sync', function () { var stage = addStage(); var layer = new Konva.Layer(); var wedge = new Konva.Wedge({ - x: stage.getWidth() / 2, - y: stage.getHeight() / 2, + x: stage.width() / 2, + y: stage.height() / 2, angle: 180 * 0.4, radius: 70, fill: 'green', @@ -56,12 +60,12 @@ suite('Wedge', function () { assert.equal(wedge.getHeight(), 120); }); - test('getSelfRect', function () { + it('getSelfRect', function () { var stage = addStage(); var layer = new Konva.Layer(); var wedge = new Konva.Wedge({ - x: stage.getWidth() / 2, - y: stage.getHeight() / 2, + x: stage.width() / 2, + y: stage.height() / 2, angle: 180 * 0.4, radius: 70, fill: 'green', diff --git a/test/unit-new/utis.ts b/test/unit-new/utis.ts new file mode 100644 index 00000000..a523f2bb --- /dev/null +++ b/test/unit-new/utis.ts @@ -0,0 +1,362 @@ +import { assert } from 'chai'; +import KonvaModule from '../../src/index'; +import '../../src/index-node'; + +export const Konva = KonvaModule; + +import * as canvas from 'canvas'; + +Konva.enableTrace = true; +Konva.showWarnings = true; + +import { imagediff } from './imagediff'; +import { Layer } from '../../src/Layer'; + +export const isNode = typeof global.document === 'undefined'; +export const isBrowser = !isNode; + +export function getContainer() { + return document.getElementById('konva-container'); +} + +export function addContainer() { + if (isNode) { + return; + } + var container = document.createElement('div'); + + getContainer().appendChild(container); + return container; +} + +export function addStage(attrs?) { + var container = !isNode && global.document.createElement('div'); + + var stage = new Konva.Stage({ + container: container, + width: 578, + height: 200, + ...attrs, + }); + + if (!isNode) { + getContainer().appendChild(container); + } + + return stage; +} + +beforeEach(function () { + Konva.inDblClickWindow = false; + + if ( + !( + this.currentTest.body.indexOf('assert') !== -1 || + this.currentTest.body.toLowerCase().indexOf('compare') !== -1 + ) + ) { + console.error('Found test without asserts: ' + this.currentTest.title); + } +}); + +export function loadImage(url, callback) { + const isBase64 = url.indexOf('base64') >= 0; + if (isNode && !isBase64) { + url = './test/assets/' + url; + } else if (!isBase64) { + url = (document.getElementById(url) as HTMLImageElement).src; + } + + return canvas + .loadImage(url) + .then(callback) + .catch((e) => { + console.error(e); + }); +} + +export function getPixelRatio() { + return (typeof window !== 'undefined' && window.devicePixelRatio) || 1; +} + +function get(element, content?) { + element = document.createElement(element); + if (element && content) { + element.innerHTML = content; + } + return element; +} + +export function compareCanvases(canvas1, canvas2, tol?, secondTol?) { + // don't test in PhantomJS as it use old chrome engine + // it it has opacity + shadow bug + var equal = imagediff.equal(canvas1, canvas2, tol, secondTol); + if (!equal) { + const diff = imagediff.diff(canvas1, canvas2); + const diffCanvas = createCanvas(); + + const context = diffCanvas.getContext('2d'); + context.putImageData(diff, 0, 0); + + var base64 = diffCanvas.toDataURL(); + console.error('Diff image:'); + console.error(base64); + + if (isBrowser) { + var div = get('div'), + b = get('div', '
Expected:
'), + c = get('div', '
Diff:
'); + div.style.overflow = 'hidden'; + b.style.float = 'left'; + c.style.float = 'left'; + canvas2.style.position = ''; + canvas2.style.display = ''; + b.appendChild(canvas2); + c.appendChild(diffCanvas); + div.appendChild(b); + div.appendChild(c); + getContainer().appendChild(div); + } + } + assert.equal( + equal, + true, + 'Result from Konva is different with canvas result' + ); +} + +export function compareLayerAndCanvas(layer: Layer, canvas, tol?, secondTol?) { + compareCanvases(layer.getCanvasElement(), canvas, tol, secondTol); +} + +export function cloneAndCompareLayer(layer: Layer, tol?) { + var layer2 = layer.clone(); + layer.getStage().add(layer2); + layer2.hide(); + compareLayers(layer, layer2, tol); +} + +export function compareLayers(layer1: Layer, layer2: Layer, tol?) { + compareLayerAndCanvas(layer1, layer2.getCanvasElement(), tol); +} + +export function createCanvas() { + var node = canvas.createCanvas(300, 300); + node.width = 578 * Konva.pixelRatio; + node.height = 200 * Konva.pixelRatio; + node.getContext('2d').scale(Konva.pixelRatio, Konva.pixelRatio); + return node; +} + +export function showHit(layer) { + if (isNode) { + return; + } + var canvas = layer.hitCanvas._canvas; + canvas.style.position = 'relative'; + + getContainer().appendChild(canvas); +} + +Konva.UA.mobile = false; + +afterEach(function () { + var isFailed = this.currentTest.state == 'failed'; + var isManual = this.currentTest.parent.title === 'Manual'; + + Konva.stages.forEach(function (stage) { + clearTimeout(stage.dblTimeout); + }); + + if (!isFailed && !isManual) { + Konva.stages.forEach(function (stage) { + stage.destroy(); + }); + if (Konva.DD._dragElements.size) { + throw 'Why drag elements are not cleaned?'; + } + } +}); + +export function simulateMouseDown(stage, pos) { + var top = isNode ? 0 : stage.content.getBoundingClientRect().top; + + stage._mousedown({ + clientX: pos.x, + clientY: pos.y + top, + button: pos.button || 0, + }); +} + +export function simulateMouseMove(stage, pos) { + var top = isNode ? 0 : stage.content.getBoundingClientRect().top; + var evt = { + clientX: pos.x, + clientY: pos.y + top, + button: pos.button || 0, + }; + + stage._mousemove(evt); + Konva.DD._drag(evt); +} + +export function simulateMouseUp(stage, pos) { + var top = isNode ? 0 : stage.content.getBoundingClientRect().top; + var evt = { + clientX: pos.x, + clientY: pos.y + top, + button: pos.button || 0, + }; + + Konva.DD._endDragBefore(evt); + stage._mouseup(evt); + Konva.DD._endDragAfter(evt); +} + +export function simulateTouchStart(stage, pos, changed?) { + var top = isNode ? 0 : stage.content.getBoundingClientRect().top; + var touches; + var changedTouches; + if (Array.isArray(pos)) { + touches = pos.map(function (touch) { + return { + identifier: touch.id, + clientX: touch.x, + clientY: touch.y + top, + }; + }); + changedTouches = (changed || pos).map(function (touch) { + return { + identifier: touch.id, + clientX: touch.x, + clientY: touch.y + top, + }; + }); + } else { + changedTouches = touches = [ + { + clientX: pos.x, + clientY: pos.y + top, + id: 0, + }, + ]; + } + var evt = { + touches: touches, + changedTouches: changedTouches, + }; + + stage._touchstart(evt); +} + +export function simulateTouchMove(stage, pos, changed?) { + var top = isNode ? 0 : stage.content.getBoundingClientRect().top; + var touches; + var changedTouches; + if (Array.isArray(pos)) { + touches = pos.map(function (touch) { + return { + identifier: touch.id, + clientX: touch.x, + clientY: touch.y + top, + }; + }); + changedTouches = (changed || pos).map(function (touch) { + return { + identifier: touch.id, + clientX: touch.x, + clientY: touch.y + top, + }; + }); + } else { + changedTouches = touches = [ + { + clientX: pos.x, + clientY: pos.y + top, + id: 0, + }, + ]; + } + var evt = { + touches: touches, + changedTouches: changedTouches, + }; + + stage._touchmove(evt); + Konva.DD._drag(evt); +} + +export function simulateTouchEnd(stage, pos, changed?) { + var top = isNode ? 0 : stage.content.getBoundingClientRect().top; + var touches; + var changedTouches; + if (Array.isArray(pos)) { + touches = pos.map(function (touch) { + return { + identifier: touch.id, + clientX: touch.x, + clientY: touch.y + top, + }; + }); + changedTouches = (changed || pos).map(function (touch) { + return { + identifier: touch.id, + clientX: touch.x, + clientY: touch.y + top, + }; + }); + } else { + changedTouches = touches = [ + { + clientX: pos.x, + clientY: pos.y + top, + id: 0, + }, + ]; + } + var evt = { + touches: touches, + changedTouches: changedTouches, + }; + + Konva.DD._endDragBefore(evt); + stage._touchend(evt); + Konva.DD._endDragAfter(evt); +} + +export function simulatePointerDown(stage, pos) { + var top = isNode ? 0 : stage.content.getBoundingClientRect().top; + stage._mousedown({ + clientX: pos.x, + clientY: pos.y + top, + button: pos.button || 0, + pointerId: pos.pointerId || 1, + }); +} + +export function simulatePointerMove(stage, pos) { + var top = isNode ? 0 : stage.content.getBoundingClientRect().top; + var evt = { + clientX: pos.x, + clientY: pos.y + top, + button: pos.button || 0, + pointerId: pos.pointerId || 1, + }; + + stage._mousemove(evt); + Konva.DD._drag(evt); +} + +export function simulatePointerUp(stage, pos) { + var top = isNode ? 0 : stage.content.getBoundingClientRect().top; + var evt = { + clientX: pos.x, + clientY: pos.y + top, + button: pos.button || 0, + pointerId: pos.pointerId || 1, + }; + + Konva.DD._endDragBefore(evt); + stage._mouseup(evt); + Konva.DD._endDragAfter(evt); +} diff --git a/test/unit/BaseLayer-test.js b/test/unit/BaseLayer-test.js deleted file mode 100644 index db62fb63..00000000 --- a/test/unit/BaseLayer-test.js +++ /dev/null @@ -1,58 +0,0 @@ -suite('BaseLayer', function () { - // ====================================================== - test('width and height', function () { - Konva.showWarnings = false; - var stage = addStage(); - - var layer = new Konva.FastLayer(); - assert.equal( - layer.width(), - undefined, - 'while layer is not on stage width is undefined' - ); - assert.equal( - layer.height(), - undefined, - 'while layer is not on stage height is undefined' - ); - - layer.width(10); - assert.equal( - layer.width(), - undefined, - 'while layer is not on stage changing width doing nothing' - ); - layer.height(10); - assert.equal( - layer.height(), - undefined, - 'while layer is not on stage changing height doing nothing' - ); - stage.add(layer); - - assert.equal( - layer.width(), - stage.width(), - 'while layer is on stage width is stage`s width' - ); - assert.equal( - layer.height(), - stage.height(), - 'while layer is on stage height is stage`s height' - ); - - layer.width(10); - assert.equal( - layer.width(), - stage.width(), - 'while layer is on stage changing width doing nothing' - ); - layer.height(10); - assert.equal( - layer.height(), - stage.height(), - 'while layer is on stage changing height doing nothing' - ); - Konva.showWarnings = true; - }); -}); diff --git a/test/unit/Collection-test.js b/test/unit/Collection-test.js deleted file mode 100644 index 93140349..00000000 --- a/test/unit/Collection-test.js +++ /dev/null @@ -1,54 +0,0 @@ -suite('Collection', function () { - test('test collection method mapping', function () { - // Node method - assert.notEqual(Konva.Collection.prototype.on, undefined); - - // Layer method - assert.notEqual(Konva.Collection.prototype.getContext, undefined); - - // Container method - assert.notEqual(Konva.Collection.prototype.hasChildren, undefined); - - // Shape method - assert.notEqual(Konva.Collection.prototype.strokeWidth, undefined); - }); - - test('add circle to stage', function () { - var stage = addStage(); - var layer = new Konva.Layer(); - var circle1 = new Konva.Circle({ - x: 100, - y: 100, - radius: 70, - fill: 'green', - stroke: 'black', - strokeWidth: 4, - name: 'myCircle', - draggable: true, - }); - - var circle2 = new Konva.Circle({ - x: 300, - y: 100, - radius: 70, - fill: 'red', - stroke: 'black', - strokeWidth: 4, - name: 'myCircle', - draggable: true, - }); - - layer.add(circle1).add(circle2); - stage.add(layer); - - layer.find('Circle').fill('blue').stroke('green'); - layer.draw(); - - //console.log(layer.getContext().getTrace()); - - assert.equal( - layer.getContext().getTrace(), - 'clearRect(0,0,578,200);save();transform(1,0,0,1,100,100);beginPath();arc(0,0,70,0,6.283,false);closePath();fillStyle=green;fill();lineWidth=4;strokeStyle=black;stroke();restore();save();transform(1,0,0,1,300,100);beginPath();arc(0,0,70,0,6.283,false);closePath();fillStyle=red;fill();lineWidth=4;strokeStyle=black;stroke();restore();clearRect(0,0,578,200);save();transform(1,0,0,1,100,100);beginPath();arc(0,0,70,0,6.283,false);closePath();fillStyle=blue;fill();lineWidth=4;strokeStyle=green;stroke();restore();save();transform(1,0,0,1,300,100);beginPath();arc(0,0,70,0,6.283,false);closePath();fillStyle=blue;fill();lineWidth=4;strokeStyle=green;stroke();restore();' - ); - }); -}); diff --git a/test/unit/filters/RGB-test.js b/test/unit/filters/RGB-test.js deleted file mode 100644 index 9567792e..00000000 --- a/test/unit/filters/RGB-test.js +++ /dev/null @@ -1,111 +0,0 @@ -suite('RGB', function () { - // ====================================================== - test('colorize basic', function (done) { - var stage = addStage(); - - var imageObj = new Image(); - imageObj.onload = function () { - var layer = new Konva.Layer(); - darth = new Konva.Image({ - x: 10, - y: 10, - image: imageObj, - draggable: true, - }); - - layer.add(darth); - stage.add(layer); - - darth.cache(); - darth.filters([Konva.Filters.RGB]); - darth.red(255).green(0).blue(128); - layer.draw(); - - // Assert fails even though '[255,0,128] = [255,0,128]' - // assert.deepEqual(darth.getFilterColorizeColor(), [255,0,128]); - - done(); - }; - imageObj.src = 'assets/darth-vader.jpg'; - }); - - // ====================================================== - test('colorize crop', function (done) { - var stage = addStage(); - - var imageObj = new Image(); - imageObj.onload = function () { - var layer = new Konva.Layer(); - darth = new Konva.Image({ - x: 10, - y: 10, - image: imageObj, - crop: { x: 128, y: 48, width: 256, height: 128 }, - draggable: true, - }); - - layer.add(darth); - stage.add(layer); - - darth.cache(); - darth.filters([Konva.Filters.RGB]); - darth.red(0).green(255).blue(0); - layer.draw(); - - // assert.deepEqual(darth.getFilterColorizeColor(), [0,255,0]); - - done(); - }; - imageObj.src = 'assets/darth-vader.jpg'; - }); - - // ====================================================== - test('colorize transparancy', function (done) { - var stage = addStage(); - var layer = new Konva.Layer(); - - var colors = [ - [255, 0, 0], - [255, 128, 0], - [255, 255, 0], - [0, 255, 0], - [0, 255, 128], - [0, 255, 255], - [0, 0, 255], - [128, 0, 255], - [255, 0, 255], - [0, 0, 0], - [128, 128, 128], - [255, 255, 255], - ]; - var i, - l = colors.length; - var nAdded = 0; - for (i = 0; i < l; i += 1) { - var imageObj = new Image(); - imageObj.onload = (function (color, x) { - return function () { - var darth = new Konva.Image({ - x: x, - y: 32, - image: imageObj, - draggable: true, - }); - layer.add(darth); - - darth.cache(); - darth.filters([Konva.Filters.RGB]); - darth.red(color[0]).green(color[1]).blue(color[2]); - - nAdded += 1; - if (nAdded >= l) { - stage.add(layer); - layer.draw(); - done(); - } - }; - })(colors[i], -64 + (i / l) * stage.getWidth()); - imageObj.src = 'assets/lion.png'; - } - }); -}); diff --git a/test/unit/filters/Ripple-test.js b/test/unit/filters/Ripple-test.js deleted file mode 100644 index 14983a05..00000000 --- a/test/unit/filters/Ripple-test.js +++ /dev/null @@ -1,130 +0,0 @@ -suite('Ripple', function () { - // ====================================================== - test('basic ripple', function (done) { - var stage = addStage(); - - var imageObj = new Image(); - imageObj.onload = function () { - var layer = new Konva.Layer(); - darth = new Konva.Image({ - x: 10, - y: 10, - image: imageObj, - draggable: true, - }); - - layer.add(darth); - stage.add(layer); - - darth.cache(); - darth.filters([Konva.Filters.Ripple]); - darth.rippleSize(10); - - assert.equal(darth.rippleSize(), 10); - assert.equal(darth._filterUpToDate, false); - - layer.draw(); - - assert.equal(darth._filterUpToDate, true); - - darth.rippleSize(20); - - assert.equal(darth.rippleSize(), 20); - assert.equal(darth._filterUpToDate, false); - - layer.draw(); - - assert.equal(darth._filterUpToDate, true); - - done(); - }; - imageObj.src = 'assets/lion.png'; - }); - - // ====================================================== - test('tween ripple offset', function (done) { - var stage = addStage(); - - var imageObj = new Image(); - imageObj.onload = function () { - var layer = new Konva.Layer(); - darth = new Konva.Image({ - x: 10, - y: 10, - image: imageObj, - draggable: true, - }); - - layer.add(darth); - stage.add(layer); - - darth.cache(); - darth.filters([Konva.Filters.Ripple]); - darth.rippleSize(16); - darth.rippleOffset(0); - layer.draw(); - - var tween = new Konva.Tween({ - node: darth, - duration: 2.0, - rippleOffset: 32, - //rippleSize: 64, - easing: Konva.Easings.EaseInOut, - }); - - darth.on('mouseover', function () { - tween.play(); - }); - - darth.on('mouseout', function () { - tween.reverse(); - }); - - done(); - }; - imageObj.src = 'assets/lion.png'; - }); - - // ====================================================== - test('tween ripple size', function (done) { - var stage = addStage(); - - var imageObj = new Image(); - imageObj.onload = function () { - var layer = new Konva.Layer(); - darth = new Konva.Image({ - x: 10, - y: 10, - image: imageObj, - draggable: true, - }); - - layer.add(darth); - stage.add(layer); - - darth.cache(); - darth.filters([Konva.Filters.Ripple]); - darth.rippleSize(16); - darth.rippleOffset(0); - layer.draw(); - - var tween = new Konva.Tween({ - node: darth, - duration: 2.0, - rippleSize: 64, - easing: Konva.Easings.EaseInOut, - }); - - darth.on('mouseover', function () { - tween.play(); - }); - - darth.on('mouseout', function () { - tween.reverse(); - }); - - done(); - }; - imageObj.src = 'assets/lion.png'; - }); -}); diff --git a/test/unit/shapes/Image-test.js b/test/unit/shapes/Image-test.js deleted file mode 100644 index 5fa305c0..00000000 --- a/test/unit/shapes/Image-test.js +++ /dev/null @@ -1,390 +0,0 @@ -suite('Image', function () { - // ====================================================== - test('add image', function (done) { - var imageObj = new Image(); - imageObj.onload = function () { - var stage = addStage(); - - var layer = new Konva.Layer(); - var darth = new Konva.Image({ - x: 200, - y: 60, - image: imageObj, - width: 100, - height: 100, - offset: { x: 50, y: 30 }, - crop: { x: 135, y: 7, width: 167, height: 134 }, - draggable: true, - }); - - layer.add(darth); - stage.add(layer); - - darth.setHeight(200); - layer.draw(); - - darth.setHeight(100); - layer.draw(); - - assert.equal(darth.getX(), 200); - assert.equal(darth.getY(), 60); - assert.equal(darth.getWidth(), 100); - assert.equal(darth.getHeight(), 100); - assert.equal(darth.offset().x, 50); - assert.equal(darth.offset().y, 30); - assert.equal(Konva.Util._isElement(darth.getImage()), true); - - var crop = null; - crop = darth.getCrop(); - - assert.equal(crop.x, 135); - assert.equal(crop.y, 7); - assert.equal(crop.width, 167); - assert.equal(crop.height, 134); - - darth.setCrop({ - x: 8, - y: 9, - width: 10, - height: 11, - }); - crop = darth.getCrop(); - assert.equal(crop.x, 8); - assert.equal(crop.y, 9); - assert.equal(crop.width, 10); - assert.equal(crop.height, 11); - - darth.setCropX(12); - crop = darth.getCrop(); - assert.equal(crop.x, 12); - assert.equal(crop.y, 9); - assert.equal(crop.width, 10); - assert.equal(crop.height, 11); - - darth.setCropY(13); - crop = darth.getCrop(); - assert.equal(crop.x, 12); - assert.equal(crop.y, 13); - assert.equal(crop.width, 10); - assert.equal(crop.height, 11); - - darth.setCropWidth(14); - crop = darth.getCrop(); - assert.equal(crop.x, 12); - assert.equal(crop.y, 13); - assert.equal(crop.width, 14); - assert.equal(crop.height, 11); - - darth.setCropHeight(15); - crop = darth.getCrop(); - assert.equal(crop.x, 12); - assert.equal(crop.y, 13); - assert.equal(crop.width, 14); - assert.equal(crop.height, 15); - - darth.setAttrs({ - x: 200, - y: 60, - image: imageObj, - width: 100, - height: 100, - offsetX: 50, - offsetY: 30, - crop: { x: 135, y: 7, width: 167, height: 134 }, - draggable: true, - }); - - //document.body.appendChild(layer.bufferCanvas.element) - - assert.equal(darth.getClassName(), 'Image'); - - var trace = layer.getContext().getTrace(); - //console.log(trace); - - assert.equal( - trace, - 'clearRect(0,0,578,200);save();transform(1,0,0,1,150,30);drawImage([object HTMLImageElement],135,7,167,134,0,0,100,100);restore();clearRect(0,0,578,200);save();transform(1,0,0,1,150,30);drawImage([object HTMLImageElement],135,7,167,134,0,0,100,200);restore();clearRect(0,0,578,200);save();transform(1,0,0,1,150,30);drawImage([object HTMLImageElement],135,7,167,134,0,0,100,100);restore();' - ); - - done(); - }; - imageObj.src = 'assets/darth-vader.jpg'; - }); - - // ====================================================== - test('crop and scale image', function (done) { - var imageObj = new Image(); - imageObj.onload = function () { - var stage = addStage(); - var layer = new Konva.Layer(); - var darth = new Konva.Image({ - x: 200, - y: 75, - image: imageObj, - width: 107, - height: 75, - crop: { x: 186, y: 211, width: 106, height: 74 }, - draggable: true, - scale: { x: 0.5, y: 0.5 }, - }); - - layer.add(darth); - stage.add(layer); - - assert.equal(darth.getCrop().x, 186); - assert.equal(darth.getCrop().y, 211); - assert.equal(darth.getCrop().width, 106); - assert.equal(darth.getCrop().height, 74); - - assert.equal(darth.getCropX(), 186); - assert.equal(darth.getCropY(), 211); - assert.equal(darth.getCropWidth(), 106); - assert.equal(darth.getCropHeight(), 74); - - darth.setCrop({ x: 1, y: 2, width: 3, height: 4 }); - - assert.equal(darth.getCrop().x, 1); - assert.equal(darth.getCrop().y, 2); - assert.equal(darth.getCrop().width, 3); - assert.equal(darth.getCrop().height, 4); - - assert.equal(darth.getCropX(), 1); - assert.equal(darth.getCropY(), 2); - assert.equal(darth.getCropWidth(), 3); - assert.equal(darth.getCropHeight(), 4); - - darth.setCropX(5); - darth.setCropY(6); - darth.setCropWidth(7); - darth.setCropHeight(8); - - assert.equal(darth.getCrop().x, 5); - assert.equal(darth.getCrop().y, 6); - assert.equal(darth.getCrop().width, 7); - assert.equal(darth.getCrop().height, 8); - - assert.equal(darth.getCropX(), 5); - assert.equal(darth.getCropY(), 6); - assert.equal(darth.getCropWidth(), 7); - assert.equal(darth.getCropHeight(), 8); - - done(); - }; - imageObj.src = 'assets/darth-vader.jpg'; - }); - - // ====================================================== - // TODO: what can we test here? - test('image with svg source', function (done) { - var imageObj = new Image(); - - var stage = addStage(); - var layer = new Konva.Layer(); - - imageObj.onload = function () { - var tiger = new Konva.Image({ - x: 0, - y: 0, - image: imageObj, - draggable: true, - scale: { x: 0.25, y: 0.25 }, - }); - - layer.add(tiger); - stage.add(layer); - - done(); - }; - imageObj.src = 'assets/Ghostscript_Tiger.svg'; - }); - - // ====================================================== - test.skip('opacity test for image with svg source', function (done) { - var imageObj = new Image(); - - var stage = addStage(); - var layer = new Konva.Layer(); - - layer.add( - new Konva.Line({ - points: [0, 0, 578, 200], - stroke: 'black', - strokeWidth: 5, - }) - ); - - imageObj.onload = function () { - var tiger = new Konva.Image({ - x: 0, - y: 0, - image: imageObj, - draggable: true, - scaleX: 0.25, - opacity: 0.5, - }); - - layer.add(tiger); - - layer.add( - new Konva.Line({ - points: [578, 0, 0, 200], - stroke: 'blue', - strokeWidth: 5, - }) - ); - - stage.add(layer); - - done(); - }; - imageObj.style.opacity = 0.5; - imageObj.src = 'assets/Ghostscript_Tiger.svg'; - }); - - // ====================================================== - test('image with opacity and shadow', function (done) { - var imageObj = new Image(); - imageObj.onload = function () { - var stage = addStage(); - - var layer = new Konva.Layer(); - var darth = new Konva.Image({ - x: 200, - y: 60, - image: imageObj, - width: 100, - height: 100, - offset: { x: 50, y: 30 }, - draggable: true, - opacity: 0.5, - shadowColor: 'black', - shadowBlur: 10, - shadowOpacity: 0.1, - shadowOffset: { x: 20, y: 20 }, - }); - - layer.add(darth); - stage.add(layer); - - var trace = layer.getContext().getTrace(); - //console.log(trace); - assert.equal( - trace, - 'clearRect(0,0,578,200);save();transform(1,0,0,1,150,30);globalAlpha=0.5;shadowColor=rgba(0,0,0,0.1);shadowBlur=10;shadowOffsetX=20;shadowOffsetY=20;drawImage([object HTMLImageElement],0,0,100,100);restore();' - ); - - done(); - }; - imageObj.src = 'assets/darth-vader.jpg'; - }); - - // ====================================================== - test('image with stroke, opacity and shadow', function (done) { - var imageObj = new Image(); - imageObj.onload = function () { - var stage = addStage(); - - var layer = new Konva.Layer(); - var darth = new Konva.Image({ - x: 200, - y: 60, - image: imageObj, - width: 100, - height: 100, - offset: { x: 50, y: 30 }, - draggable: true, - opacity: 0.5, - shadowColor: 'black', - shadowBlur: 10, - shadowOpacity: 0.5, - shadowOffset: { x: 20, y: 20 }, - stroke: 'red', - strokeWidth: 20, - }); - - layer.add(darth); - stage.add(layer); - - var trace = layer.getContext().getTrace(); - //console.log(trace); - assert.equal( - trace, - 'clearRect(0,0,578,200);save();shadowColor=rgba(0,0,0,0.5);shadowBlur=10;shadowOffsetX=20;shadowOffsetY=20;globalAlpha=0.5;drawImage([object HTMLCanvasElement],0,0,578,200);restore();' - ); - - done(); - }; - imageObj.src = 'assets/darth-vader.jpg'; - }); - - // ====================================================== - test('image caching', function (done) { - var imageObj = new Image(); - imageObj.onload = function () { - var stage = addStage(); - var layer = new Konva.Layer(); - var darth = new Konva.Image({ - x: 200, - y: 60, - image: imageObj, - width: 100, - height: 100, - draggable: true, - }); - - darth.cache(); - layer.add(darth); - stage.add(layer); - - assert.deepEqual(darth.getSelfRect(), { - x: 0, - y: 0, - width: 100, - height: 100, - }); - - var canvas = createCanvas(); - var context = canvas.getContext('2d'); - context.drawImage(imageObj, 200, 60, 100, 100); - compareLayerAndCanvas(layer, canvas, 10); - done(); - }; - imageObj.src = 'assets/darth-vader.jpg'; - }); - - test('image loader', function (done) { - var stage = addStage(); - var layer = new Konva.Layer(); - stage.add(layer); - var src = 'assets/darth-vader.jpg'; - Konva.Image.fromURL(src, function (image) { - layer.add(image); - layer.draw(); - assert.equal(image instanceof Konva.Image, true); - var nativeImg = image.image(); - assert.equal(nativeImg instanceof Image, true); - assert.equal(nativeImg.src.indexOf(src) !== -1, true); - assert.equal(nativeImg.complete, true); - done(); - }); - }); - - test('check zero values', function (done) { - var stage = addStage(); - var layer = new Konva.Layer(); - stage.add(layer); - var src = 'assets/darth-vader.jpg'; - Konva.Image.fromURL(src, function (image) { - layer.add(image); - layer.draw(); - - image.width(0); - image.height(0); - layer.draw(); - - assert.equal(image.width(), 0); - assert.equal(image.height(), 0); - done(); - }); - }); -}); diff --git a/tsconfig.json b/tsconfig.json index 7de988a0..e50c968d 100644 --- a/tsconfig.json +++ b/tsconfig.json @@ -2,13 +2,11 @@ "compilerOptions": { "outDir": "lib", "module": "ES2015", - "target": "ES5", + "target": "ES2015", "noEmitOnError": true, - "lib": ["es2015", "dom"] - // "noImplicitAny": true - // "strict": true - // "strictFunctionTypes": true + "lib": ["ES2015", "dom"], + "moduleResolution": "node", + "declaration": true }, "include": ["./src/*.ts"] - // "include": ["./types/*.ts"] } diff --git a/tsconfig.testing.json b/tsconfig.testing.json new file mode 100644 index 00000000..913de75a --- /dev/null +++ b/tsconfig.testing.json @@ -0,0 +1,10 @@ +{ + "compilerOptions": { + "outDir": "lib", + "target": "ES2015", + "noEmitOnError": true, + "moduleResolution": "node", + "lib": ["ES2015", "dom"] + }, + "include": ["./src/*.ts"] +}