konva 10.7.1 → 10.9.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -14,6 +14,7 @@ const ATTR_CHANGE_LIST = [
14
14
  'rotateAnchorOffsetChange',
15
15
  'rotateAnchorAngleChange',
16
16
  'rotateEnabledChange',
17
+ 'rotateModeChange',
17
18
  'enabledAnchorsChange',
18
19
  'anchorSizeChange',
19
20
  'borderEnabledChange',
@@ -62,10 +63,37 @@ const ANGLES = {
62
63
  'bottom-right': 135,
63
64
  };
64
65
  const TOUCH_DEVICE = 'ontouchstart' in Konva._global;
66
+ // invisible zones just outside the corners, the rotate area of rotateMode 'corners'
67
+ const ROTATE_ZONE_NAMES = [
68
+ 'rotater-top-left',
69
+ 'rotater-top-right',
70
+ 'rotater-bottom-left',
71
+ 'rotater-bottom-right',
72
+ ];
73
+ function isRotateAnchor(anchorName) {
74
+ return anchorName.startsWith('rotater');
75
+ }
76
+ // with Shift pressed the rotation snaps to this step
77
+ const SHIFT_ROTATION_STEP = Math.PI / 12;
78
+ // curved double arrow drawn for the top-right corner, rotated for others
79
+ function getRotateZoneCursor(deg, fallback) {
80
+ const svg = '<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24">' +
81
+ `<g transform="rotate(${deg} 12 12)" stroke-linejoin="round">` +
82
+ '<path d="M5 8 A11 11 0 0 1 16 19" fill="none" stroke="white" stroke-width="4"/>' +
83
+ '<path d="M2 8 L6 4.5 L6 11.5 Z M16 22 L12.5 18 L19.5 18 Z" fill="black" stroke="white"/>' +
84
+ '<path d="M5 8 A11 11 0 0 1 16 19" fill="none" stroke="black" stroke-width="1.5"/>' +
85
+ '</g></svg>';
86
+ return `url("data:image/svg+xml,${encodeURIComponent(svg)}") 12 12, ${fallback}`;
87
+ }
65
88
  function getCursor(anchorName, rad, rotateCursor) {
66
89
  if (anchorName === 'rotater') {
67
90
  return rotateCursor;
68
91
  }
92
+ if (isRotateAnchor(anchorName)) {
93
+ const corner = anchorName.slice('rotater-'.length);
94
+ const deg = Math.round(Util.radToDeg(rad) + ANGLES[corner] - 45);
95
+ return getRotateZoneCursor(deg, rotateCursor);
96
+ }
69
97
  rad += Util.degToRad(ANGLES[anchorName] || 0);
70
98
  const angle = ((Util.radToDeg(rad) % 360) + 360) % 360;
71
99
  if (Util._inRange(angle, 315 + 22.5, 360) || Util._inRange(angle, 0, 22.5)) {
@@ -207,6 +235,7 @@ const activeTransformers = new Set();
207
235
  * @param {Number} [config.rotateAnchorOffset] Default is 50
208
236
  * @param {Number} [config.rotateAnchorAngle] Angle of the rotate anchor around the box, in degrees. Default is 0 (top)
209
237
  * @param {String} [config.rotateAnchorCursor] Default is crosshair
238
+ * @param {String} [config.rotateMode] How the user rotates: 'handle' (the rotate anchor), 'corners' (invisible zones just outside the corners) or 'both'. Default is 'handle'
210
239
  * @param {Number} [config.padding] Default is 0
211
240
  * @param {Boolean} [config.borderEnabled] Should we draw border? Default is true
212
241
  * @param {String} [config.borderStroke] Border stroke color
@@ -218,7 +247,7 @@ const activeTransformers = new Set();
218
247
  * @param {Number} [config.anchorStrokeWidth] Anchor stroke size
219
248
  * @param {Number} [config.anchorSize] Default is 10
220
249
  * @param {Boolean} [config.keepRatio] Should we keep ratio when we are moving edges? Default is true
221
- * @param {String} [config.shiftBehavior] How does transformer react on shift key press when we are moving edges? Default is 'default'
250
+ * @param {String} [config.shiftBehavior] How does transformer react on shift key press when we are moving edges? 'none' also turns off the Shift rotation snap. Default is 'default'
222
251
  * @param {Boolean} [config.centeredScaling] Should we resize relative to node's center? Default is false
223
252
  * @param {Array} [config.enabledAnchors] Array of names of enabled handles
224
253
  * @param {Boolean} [config.flipEnabled] Can we flip/mirror shape on transform?. True by default
@@ -260,14 +289,14 @@ export class Transformer extends Group {
260
289
  // rendered in another window than the one Konva was imported into
261
290
  this._transformWindow = null;
262
291
  this._elementsCreated = false;
263
- this._updateScheduled = false;
264
- // an attached container's descendants changed after the last layout
265
- this._subtreeChanged = false;
292
+ // the layout is stale; the next sync point runs _update() (see _syncUpdate)
293
+ this._updatePending = false;
266
294
  this._createElements();
267
295
  // bindings
268
296
  this._handleMouseMove = this._handleMouseMove.bind(this);
269
297
  this._handleMouseUp = this._handleMouseUp.bind(this);
270
298
  this.update = this.update.bind(this);
299
+ this._syncUpdate = this._syncUpdate.bind(this);
271
300
  // update transformer data for certain attr changes
272
301
  this.on(ATTR_CHANGE_LIST, (event) => {
273
302
  if (event.type === 'ignoreStrokeChange')
@@ -323,12 +352,7 @@ export class Transformer extends Group {
323
352
  return true;
324
353
  });
325
354
  this._nodes = nodes = filteredNodes;
326
- if (nodes.length === 1 && this.useSingleNodeRotation()) {
327
- this.rotation(nodes[0].getAbsoluteRotation());
328
- }
329
- else {
330
- this.rotation(0);
331
- }
355
+ this._resetRotation();
332
356
  this._nodes.forEach((node) => {
333
357
  const onChange = () => {
334
358
  var _a;
@@ -340,6 +364,7 @@ export class Transformer extends Group {
340
364
  (_a = this._nodeRectCache) === null || _a === void 0 ? void 0 : _a.delete(node);
341
365
  return;
342
366
  }
367
+ // unlike _resetRotation, a multi-node box keeps its rotation here
343
368
  if (this.nodes().length === 1 && this.useSingleNodeRotation()) {
344
369
  this.rotation(this.nodes()[0].getAbsoluteRotation());
345
370
  }
@@ -364,8 +389,7 @@ export class Transformer extends Group {
364
389
  if (node instanceof Container)
365
390
  node._addSubtreeObserver(this);
366
391
  node.on(`destroy.${this._getEventNamespace()}`, () => {
367
- // a destroyed node has nothing left to transform
368
- this.setNodes(this._nodes.filter((n) => n !== node));
392
+ this._removeNode(node);
369
393
  });
370
394
  this._proxyDrag(node);
371
395
  });
@@ -411,6 +435,23 @@ export class Transformer extends Group {
411
435
  lastPos = null;
412
436
  });
413
437
  }
438
+ _detachNode(node) {
439
+ node.off('.' + this._getEventNamespace());
440
+ node._removeSubtreeObserver(this);
441
+ }
442
+ _resetRotation() {
443
+ const single = this._nodes.length === 1 && this.useSingleNodeRotation();
444
+ this.rotation(single ? this._nodes[0].getAbsoluteRotation() : 0);
445
+ }
446
+ // Drops one destroyed node. Re-attaching the survivors instead costs
447
+ // O(N) listener rebinds per destroyed node, O(N^2) for a deleted selection.
448
+ _removeNode(node) {
449
+ this._detachNode(node);
450
+ this._nodes = this._nodes.filter((n) => n !== node);
451
+ this._resetRotation();
452
+ this._resetTransformCache(node);
453
+ this._scheduleUpdate();
454
+ }
414
455
  getNodes() {
415
456
  return this._nodes || [];
416
457
  }
@@ -434,17 +475,12 @@ export class Transformer extends Group {
434
475
  * transformer.detach();
435
476
  */
436
477
  detach() {
437
- var _a;
438
- // remove events
439
- if (this._nodes) {
440
- this._nodes.forEach((node) => {
441
- node.off('.' + this._getEventNamespace());
442
- node._removeSubtreeObserver(this);
443
- });
444
- }
478
+ var _a, _b;
479
+ (_a = this._nodes) === null || _a === void 0 ? void 0 : _a.forEach((node) => this._detachNode(node));
445
480
  this._nodes = [];
481
+ this._updatePending = false;
446
482
  this._resetTransformCache();
447
- (_a = this.getLayer()) === null || _a === void 0 ? void 0 : _a.batchDraw();
483
+ (_b = this.getLayer()) === null || _b === void 0 ? void 0 : _b.batchDraw();
448
484
  }
449
485
  /**
450
486
  * bind events to the Transformer. You can use events: `transform`, `transformstart`, `transformend`, `dragstart`, `dragmove`, `dragend`
@@ -472,37 +508,42 @@ export class Transformer extends Group {
472
508
  // Called for every change below an attached container. A burst of child
473
509
  // changes only drops cached values here. The new bounds are measured once,
474
510
  // before the next frame, or earlier if a draw or transform step comes first
475
- // (_syncSubtreeChange).
511
+ // (_syncUpdate).
476
512
  _onSubtreeChange(node) {
477
513
  var _a, _b;
478
514
  if (this._fitting)
479
515
  return;
480
516
  // nothing was measured since the last change, so nothing cached is stale
481
- if (this._subtreeChanged && !this._cache[NODES_RECT])
517
+ const measured = !this._updatePending || !!this._cache[NODES_RECT];
518
+ if (measured)
519
+ this._resetTransformCache(node);
520
+ if (Node._updateBatchDepth > 0) {
521
+ // the batch flush lays the new bounds out, no frame needed
522
+ this._scheduleUpdate();
482
523
  return;
483
- this._resetTransformCache(node);
484
- if (!this._subtreeChanged) {
485
- this._subtreeChanged = true;
524
+ }
525
+ if (!this._updatePending) {
526
+ this._updatePending = true;
486
527
  // queued ahead of the draw the change requests, so that draw shows the
487
528
  // new layout. Updating inside the draw would request one more frame.
488
- Util.requestAnimFrame(() => this._syncSubtreeChange(), (_a = this.getStage()) === null || _a === void 0 ? void 0 : _a._getOwnerWindow());
529
+ Util.requestAnimFrame(this._syncUpdate, (_a = this.getStage()) === null || _a === void 0 ? void 0 : _a._getOwnerWindow());
489
530
  // the transformer can be on another layer than the changed node
490
531
  (_b = this.getLayer()) === null || _b === void 0 ? void 0 : _b.batchDraw();
491
532
  }
492
533
  }
493
- _syncSubtreeChange() {
494
- var _a;
534
+ // Runs a deferred update before anything draws or measures the anchors.
535
+ _syncUpdate() {
495
536
  // while dragging, the dragmove handler updates the layout
496
- if (this._subtreeChanged && ((_a = this._nodes) === null || _a === void 0 ? void 0 : _a.length) && !this.isDragging()) {
537
+ if (this._updatePending && !this._fitting && !this.isDragging()) {
497
538
  this._update();
498
539
  }
499
540
  }
500
541
  drawScene(can, top) {
501
- this._syncSubtreeChange();
542
+ this._syncUpdate();
502
543
  return super.drawScene(can, top);
503
544
  }
504
545
  drawHit(can, top) {
505
- this._syncSubtreeChange();
546
+ this._syncUpdate();
506
547
  return super.drawHit(can, top);
507
548
  }
508
549
  _getNodeRect() {
@@ -619,18 +660,27 @@ export class Transformer extends Group {
619
660
  }
620
661
  _createElements() {
621
662
  this._createBack();
663
+ // below the resize anchors, so a resize anchor wins where they overlap
664
+ ROTATE_ZONE_NAMES.forEach((name) => {
665
+ // invisible, but its fill keeps it in the hit graph
666
+ this._createAnchor(name, '_rotate-zone').setAttrs({
667
+ fill: 'transparent',
668
+ strokeEnabled: false,
669
+ visible: false,
670
+ });
671
+ });
622
672
  ANCHORS_NAMES.forEach((name) => {
623
673
  this._createAnchor(name);
624
674
  });
625
675
  this._createAnchor('rotater');
626
676
  this._elementsCreated = true;
627
677
  }
628
- _createAnchor(name) {
678
+ _createAnchor(name, className = '_anchor') {
629
679
  const anchor = new Rect({
630
680
  stroke: 'rgb(0, 161, 255)',
631
681
  fill: 'white',
632
682
  strokeWidth: 1,
633
- name: name + ' _anchor',
683
+ name: name + ' ' + className,
634
684
  dragDistance: 0,
635
685
  // make it draggable,
636
686
  // so activating the anchor will not start drag&drop of any parent
@@ -653,11 +703,7 @@ export class Transformer extends Group {
653
703
  anchor.on('mouseenter', () => {
654
704
  if (this.isTransforming())
655
705
  return;
656
- const rad = Konva.getAngle(this.rotation());
657
- const rotateCursor = this.rotateAnchorCursor();
658
- const cursor = getCursor(name, rad, rotateCursor);
659
- anchor.getStage().content &&
660
- (anchor.getStage().content.style.cursor = cursor);
706
+ this._setAnchorCursor(name);
661
707
  this._cursorChange = true;
662
708
  });
663
709
  anchor.on('mouseout', () => {
@@ -668,6 +714,14 @@ export class Transformer extends Group {
668
714
  (anchor.getStage().content.style.cursor = '');
669
715
  });
670
716
  this.add(anchor);
717
+ return anchor;
718
+ }
719
+ _setAnchorCursor(name, rad = Konva.getAngle(this.rotation())) {
720
+ var _a;
721
+ const content = (_a = this.getStage()) === null || _a === void 0 ? void 0 : _a.content;
722
+ if (content) {
723
+ content.style.cursor = getCursor(name, rad, this.rotateAnchorCursor());
724
+ }
671
725
  }
672
726
  _createBack() {
673
727
  const back = new Shape({
@@ -683,7 +737,9 @@ export class Transformer extends Group {
683
737
  const height = shape.height();
684
738
  ctx.beginPath();
685
739
  ctx.rect(-padding, -padding, width + padding * 2, height + padding * 2);
686
- if (tr.rotateEnabled() && tr.rotateLineVisible()) {
740
+ if (tr.rotateEnabled() &&
741
+ tr.rotateLineVisible() &&
742
+ tr.rotateMode() !== 'corners') {
687
743
  const line = getRotaterLine(tr, width, height);
688
744
  ctx.moveTo(line.edgeX, line.edgeY);
689
745
  ctx.lineTo(line.endX, line.endY);
@@ -755,6 +811,13 @@ export class Transformer extends Group {
755
811
  x: pos.x - ap.x,
756
812
  y: pos.y - ap.y,
757
813
  };
814
+ if (isRotateAnchor(this._movingAnchorName)) {
815
+ const center = getCenter(attrs);
816
+ this._rotateStart = {
817
+ pointerAngle: Math.atan2(pos.y - center.y, pos.x - center.x),
818
+ rotation: attrs.rotation,
819
+ };
820
+ }
758
821
  activeTransformers.add(this);
759
822
  this._fire('transformstart', { evt: e.evt, target: this.getNode() });
760
823
  this._nodes.forEach((target) => {
@@ -767,7 +830,7 @@ export class Transformer extends Group {
767
830
  }
768
831
  _moveTransform(e) {
769
832
  // anchors must show the current bounds before they are measured against
770
- this._syncSubtreeChange();
833
+ this._syncUpdate();
771
834
  let x, y, newHypotenuse;
772
835
  const anchorNode = this._anchors[this._movingAnchorName];
773
836
  const stage = anchorNode.getStage();
@@ -790,19 +853,33 @@ export class Transformer extends Group {
790
853
  if (oldAbs.x === newAbs.x && oldAbs.y === newAbs.y) {
791
854
  return;
792
855
  }
793
- // rotater is working very differently, so do it first
794
- if (this._movingAnchorName === 'rotater') {
856
+ // rotation is working very differently, so do it first
857
+ if (isRotateAnchor(this._movingAnchorName)) {
795
858
  const attrs = this._getNodeRect();
796
- x = anchorNode.x() - attrs.width / 2;
797
- y = -anchorNode.y() + attrs.height / 2;
798
- // Calculate angle from center to current anchor position
799
- // Offset by rotateAnchorAngle so we measure rotation from the anchor's starting position
800
- const rotateAnchorAngleRad = Util.degToRad(this.rotateAnchorAngle());
801
- let delta = Math.atan2(-y, x) + Math.PI / 2 - rotateAnchorAngleRad;
802
- const oldRotation = Konva.getAngle(this.rotation());
803
- const newRotation = oldRotation + delta;
804
- const tol = Konva.getAngle(this.rotationSnapTolerance());
805
- const snappedRot = getSnap(this.rotationSnaps(), newRotation, tol);
859
+ const center = getCenter(attrs);
860
+ const start = this._rotateStart;
861
+ // the grabbed point turns around the center by as much as the box,
862
+ // so the box follows the pointer wherever it was grabbed
863
+ const point = {
864
+ x: newAbs.x + this._anchorDragOffset.x,
865
+ y: newAbs.y + this._anchorDragOffset.y,
866
+ };
867
+ const pointerAngle = Math.atan2(point.y - center.y, point.x - center.x);
868
+ const newRotation = start.rotation + pointerAngle - start.pointerAngle;
869
+ let snappedRot;
870
+ if (e.shiftKey && this.shiftBehavior() !== 'none') {
871
+ snappedRot =
872
+ Math.round(newRotation / SHIFT_ROTATION_STEP) * SHIFT_ROTATION_STEP;
873
+ }
874
+ else {
875
+ const tol = Konva.getAngle(this.rotationSnapTolerance());
876
+ snappedRot = getSnap(this.rotationSnaps(), newRotation, tol);
877
+ }
878
+ // a corner zone cursor shows the direction of the turned corner,
879
+ // set before the transform event so its handlers can override it
880
+ if (this._movingAnchorName !== 'rotater') {
881
+ this._setAnchorCursor(this._movingAnchorName, snappedRot);
882
+ }
806
883
  const diff = snappedRot - attrs.rotation;
807
884
  const shape = rotateAroundCenter(attrs, diff);
808
885
  this._fitNodesInto(shape, e);
@@ -1187,21 +1264,10 @@ export class Transformer extends Group {
1187
1264
  layersToDraw.add(this.getLayer());
1188
1265
  layersToDraw.forEach((layer) => layer && layer.batchDraw());
1189
1266
  }
1190
- // Inside an absoluteTransform cascade, queue a single update to run when
1191
- // the cascade ends; outside a cascade, run synchronously so reads of
1192
- // transformer state stay consistent.
1267
+ // deferred to the batch flush when one is open, else synchronous
1193
1268
  _scheduleUpdate() {
1194
- if (this._updateScheduled)
1195
- return;
1196
- this._updateScheduled = true;
1197
- Node._runAfterAbsTransformCascade(() => {
1198
- var _a;
1199
- this._updateScheduled = false;
1200
- if (!((_a = this._nodes) === null || _a === void 0 ? void 0 : _a.length) || this._fitting || this.isDragging()) {
1201
- return;
1202
- }
1203
- this._update();
1204
- });
1269
+ this._updatePending = true;
1270
+ Node._runAfterUpdateBatch(this._syncUpdate);
1205
1271
  }
1206
1272
  /**
1207
1273
  * force update of Konva.Transformer.
@@ -1223,7 +1289,7 @@ export class Transformer extends Group {
1223
1289
  }
1224
1290
  _update() {
1225
1291
  var _a;
1226
- this._subtreeChanged = false;
1292
+ this._updatePending = false;
1227
1293
  const attrs = this._getNodeRect();
1228
1294
  this._updateElements(attrs);
1229
1295
  const draggable = this.nodes().some((node) => node.draggable());
@@ -1232,7 +1298,7 @@ export class Transformer extends Group {
1232
1298
  }
1233
1299
  const styleFunc = this.anchorStyleFunc();
1234
1300
  if (styleFunc) {
1235
- Object.values(this._anchors).forEach((node) => styleFunc(node));
1301
+ Object.values(this._anchors).forEach((node) => node.hasName('_anchor') && styleFunc(node));
1236
1302
  }
1237
1303
  (_a = this.getLayer()) === null || _a === void 0 ? void 0 : _a.batchDraw();
1238
1304
  }
@@ -1256,7 +1322,7 @@ export class Transformer extends Group {
1256
1322
  const resizeEnabled = this.resizeEnabled();
1257
1323
  const padding = this.padding();
1258
1324
  const anchorSize = this.anchorSize();
1259
- const anchors = Object.values(this._anchors);
1325
+ const anchors = Object.values(this._anchors).filter((node) => node.hasName('_anchor'));
1260
1326
  anchors.forEach((node) => {
1261
1327
  node.setAttrs({
1262
1328
  width: anchorSize,
@@ -1321,11 +1387,25 @@ export class Transformer extends Group {
1321
1387
  offsetY: anchorSize / 2 - padding,
1322
1388
  visible: resizeEnabled && enabledAnchors.indexOf('bottom-right') >= 0,
1323
1389
  });
1390
+ const rotateMode = this.rotateMode();
1324
1391
  const rotaterLine = getRotaterLine(this, width, height);
1325
1392
  this._anchors['rotater'].setAttrs({
1326
1393
  x: rotaterLine.endX,
1327
1394
  y: rotaterLine.endY,
1328
- visible: this.rotateEnabled(),
1395
+ visible: this.rotateEnabled() && rotateMode !== 'corners',
1396
+ });
1397
+ // each zone is a square that touches its corner from the outside
1398
+ const zoneSize = anchorSize * 2;
1399
+ const zonesVisible = this.rotateEnabled() && rotateMode !== 'handle';
1400
+ const near = -padding - zoneSize;
1401
+ ROTATE_ZONE_NAMES.forEach((name) => {
1402
+ this._anchors[name].setAttrs({
1403
+ x: name.includes('left') ? near : width + padding,
1404
+ y: name.includes('top') ? near : height + padding,
1405
+ width: zoneSize,
1406
+ height: zoneSize,
1407
+ visible: zonesVisible,
1408
+ });
1329
1409
  });
1330
1410
  this._back.setAttrs({
1331
1411
  width: width,
@@ -1389,6 +1469,7 @@ export class Transformer extends Group {
1389
1469
  return node;
1390
1470
  }
1391
1471
  getClientRect(config) {
1472
+ this._syncUpdate();
1392
1473
  if (this.nodes().length > 0) {
1393
1474
  return super.getClientRect(config);
1394
1475
  }
@@ -1564,6 +1645,23 @@ Factory.addGetterSetter(Transformer, 'rotateAnchorAngle', 0, getNumberValidator(
1564
1645
  * transformer.rotateAnchorCursor('grab');
1565
1646
  */
1566
1647
  Factory.addGetterSetter(Transformer, 'rotateAnchorCursor', 'crosshair');
1648
+ /**
1649
+ * get/set how the user rotates the nodes. 'handle' shows the rotate anchor,
1650
+ * 'corners' makes invisible zones just outside the box corners rotate,
1651
+ * 'both' enables both. Hold Shift while rotating to snap to 15 degree steps, unless shiftBehavior is 'none'.
1652
+ * While a corner zone rotates, `getActiveAnchor()` returns its name, such as 'rotater-top-left'.
1653
+ * @name Konva.Transformer#rotateMode
1654
+ * @method
1655
+ * @param {String} mode
1656
+ * @returns {String}
1657
+ * @example
1658
+ * // get
1659
+ * var rotateMode = transformer.rotateMode();
1660
+ *
1661
+ * // set
1662
+ * transformer.rotateMode('corners');
1663
+ */
1664
+ Factory.addGetterSetter(Transformer, 'rotateMode', 'handle');
1567
1665
  /**
1568
1666
  * get/set distance for rotation tolerance
1569
1667
  * @name Konva.Transformer#rotationSnapTolerance
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "konva",
3
- "version": "10.7.1",
3
+ "version": "10.9.0",
4
4
  "description": "HTML5 2d canvas library for interactive graphics, design editors, whiteboards, and diagrams.",
5
5
  "author": "Anton Lavrenov",
6
6
  "type": "module",