konva 10.7.0 → 10.8.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.
package/lib/Container.js CHANGED
@@ -60,6 +60,7 @@ export class Container extends Node {
60
60
  });
61
61
  this.children = [];
62
62
  // because all children were detached from parent, request draw via container
63
+ this._notifySubtreeChange();
63
64
  this._requestDraw();
64
65
  return this;
65
66
  }
@@ -77,6 +78,7 @@ export class Container extends Node {
77
78
  });
78
79
  this.children = [];
79
80
  // because all children were detached from parent, request draw via container
81
+ this._notifySubtreeChange();
80
82
  this._requestDraw();
81
83
  return this;
82
84
  }
@@ -115,6 +117,7 @@ export class Container extends Node {
115
117
  this._fire('add', {
116
118
  child: child,
117
119
  });
120
+ this._notifySubtreeChange();
118
121
  this._requestDraw();
119
122
  // chainable
120
123
  return this;
@@ -315,6 +318,7 @@ export class Container extends Node {
315
318
  (_a = this.children) === null || _a === void 0 ? void 0 : _a.forEach(function (child, n) {
316
319
  child.index = n;
317
320
  });
321
+ this._notifySubtreeChange();
318
322
  this._requestDraw();
319
323
  }
320
324
  drawScene(can, top) {
package/lib/Global.js CHANGED
@@ -1,5 +1,5 @@
1
1
  /*
2
- * Konva JavaScript Framework v10.7.0
2
+ * Konva JavaScript Framework v10.8.0
3
3
  * http://konvajs.org/
4
4
  * Licensed under the MIT
5
5
  * Date: @@date
@@ -29,7 +29,7 @@ export const glob = typeof global !== 'undefined'
29
29
  : {};
30
30
  export const Konva = {
31
31
  _global: glob,
32
- version: '10.7.0',
32
+ version: '10.8.0',
33
33
  isBrowser: detectBrowser(),
34
34
  isUnminified: /param/.test(function (param) { }.toString()),
35
35
  dblClickWindow: 400,
package/lib/Node.d.ts CHANGED
@@ -11,6 +11,9 @@ import { Transform, type AnyString } from './Util.ts';
11
11
  export type FilterFunction = (this: Node, imageData: ImageData, pixelRatio?: number) => void;
12
12
  export type Filter = FilterFunction | string;
13
13
  type Filters = Array<FilterFunction | string>;
14
+ type SubtreeObserver = {
15
+ _onSubtreeChange(node: Node): void;
16
+ };
14
17
  type globalCompositeOperationType = '' | 'source-over' | 'source-in' | 'source-out' | 'source-atop' | 'destination-over' | 'destination-in' | 'destination-out' | 'destination-atop' | 'lighter' | 'copy' | 'xor' | 'multiply' | 'screen' | 'overlay' | 'darken' | 'lighten' | 'color-dodge' | 'color-burn' | 'hard-light' | 'soft-light' | 'difference' | 'exclusion' | 'hue' | 'saturation' | 'color' | 'luminosity';
15
18
  export type NodeConfig = {
16
19
  x?: number;
@@ -108,6 +111,8 @@ export declare abstract class Node<Config extends NodeConfig = NodeConfig> {
108
111
  } | null;
109
112
  _attrsAffectingSize: string[];
110
113
  _attrsVersion?: number;
114
+ _subtreeObservers?: Set<SubtreeObserver>;
115
+ static _subtreeObserverCount: number;
111
116
  _batchingTransformChange: boolean;
112
117
  _needClearTransformCache: boolean;
113
118
  _filterUpToDate: boolean;
@@ -871,6 +876,9 @@ export declare abstract class Node<Config extends NodeConfig = NodeConfig> {
871
876
  * node.setAttr('x', 5);
872
877
  */
873
878
  setAttr<AttrConfig extends Config, K extends AnyString<keyof Config>>(attr: K, val: K extends keyof AttrConfig ? AttrConfig[K] : any): this;
879
+ _addSubtreeObserver(observer: SubtreeObserver): void;
880
+ _removeSubtreeObserver(observer: SubtreeObserver): void;
881
+ _notifySubtreeChange(): void;
874
882
  _requestDraw(): void;
875
883
  _setAttr<AttrConfig extends Config, K extends AnyString<keyof Config>>(key: K, val: K extends keyof AttrConfig ? AttrConfig[K] : any): void;
876
884
  _fireAndBubble(eventType: any, evt: any, compareShape?: any): void;
package/lib/Node.js CHANGED
@@ -4,7 +4,7 @@ import { DD } from "./DragAndDrop.js";
4
4
  import * as PointerEvents from "./PointerEvents.js";
5
5
  import { Factory } from "./Factory.js";
6
6
  import { Konva } from "./Global.js";
7
- import { Transform, Util } from "./Util.js";
7
+ import { Transform, TypedArray, Util } from "./Util.js";
8
8
  import { getBooleanValidator, getNumberValidator, getStringValidator, } from "./Validators.js";
9
9
  // CSS filter parser for fallback to function filters.
10
10
  function parseCSSFilters(cssFilter) {
@@ -1299,6 +1299,10 @@ export class Node {
1299
1299
  };
1300
1300
  for (key in attrs) {
1301
1301
  val = attrs[key];
1302
+ // JSON has no typed arrays, so typed line points are written as an array
1303
+ if (val instanceof TypedArray) {
1304
+ val = Array.from(val);
1305
+ }
1302
1306
  // if value is object and object is not plain
1303
1307
  // like class instance, we should skip it and to not include
1304
1308
  nonPlainObject =
@@ -2007,7 +2011,34 @@ export class Node {
2007
2011
  }
2008
2012
  return this;
2009
2013
  }
2014
+ _addSubtreeObserver(observer) {
2015
+ var _a;
2016
+ ((_a = this._subtreeObservers) !== null && _a !== void 0 ? _a : (this._subtreeObservers = new Set())).add(observer);
2017
+ Node._subtreeObserverCount++;
2018
+ }
2019
+ _removeSubtreeObserver(observer) {
2020
+ var _a;
2021
+ if ((_a = this._subtreeObservers) === null || _a === void 0 ? void 0 : _a.delete(observer)) {
2022
+ Node._subtreeObserverCount--;
2023
+ }
2024
+ }
2025
+ // Tells the observers of this node and of its ancestors that something below
2026
+ // them changed. A node's own changes reach its observers through its change
2027
+ // events, so a draw request starts at the parent. A container calls this
2028
+ // itself when its child list changes.
2029
+ _notifySubtreeChange() {
2030
+ if (!Node._subtreeObserverCount)
2031
+ return;
2032
+ for (let node = this; node; node = node.parent) {
2033
+ const observers = node._subtreeObservers;
2034
+ if (observers)
2035
+ for (const o of observers)
2036
+ o._onSubtreeChange(node);
2037
+ }
2038
+ }
2010
2039
  _requestDraw() {
2040
+ var _a;
2041
+ (_a = this.parent) === null || _a === void 0 ? void 0 : _a._notifySubtreeChange();
2011
2042
  if (Konva.autoDrawEnabled) {
2012
2043
  const drawNode = this.getLayer() || this.getStage();
2013
2044
  drawNode === null || drawNode === void 0 ? void 0 : drawNode.batchDraw();
@@ -2379,6 +2410,8 @@ export class Node {
2379
2410
  return no;
2380
2411
  }
2381
2412
  }
2413
+ // Number of registered observers. The ancestor walk is skipped while it is 0.
2414
+ Node._subtreeObserverCount = 0;
2382
2415
  // Perf: lets a listener inside an absoluteTransform cascade (e.g. Konva
2383
2416
  // .Transformer reacting to a stage drag fan-out across N attached nodes)
2384
2417
  // defer work until the cascade ends — collapses O(N) listener-driven calls
package/lib/Shape.js CHANGED
@@ -372,12 +372,16 @@ export class Shape extends Node {
372
372
  const forDrawing = config._forDrawing;
373
373
  // Painted bounds are measured in the canvas that draws the shape
374
374
  // (relativeTo): non-scaling strokes and shadows use that canvas's axes.
375
- // The identity transform normalizes negative sizes.
376
- const fillRect = !forDrawing
377
- ? this.getSelfRect()
378
- : this.strokeScaleEnabled()
379
- ? new Transform()._getTransformedRect(this._getSelfRectForDrawing())
380
- : this._transformedRect(this._getSelfRectForDrawing(), relativeTo);
375
+ let fillRect = forDrawing
376
+ ? this._getSelfRectForDrawing()
377
+ : this.getSelfRect();
378
+ if (forDrawing && !this.strokeScaleEnabled()) {
379
+ fillRect = this._transformedRect(fillRect, relativeTo);
380
+ }
381
+ else if (fillRect.width < 0 || fillRect.height < 0) {
382
+ // The identity transform normalizes negative sizes.
383
+ fillRect = new Transform()._getTransformedRect(fillRect);
384
+ }
381
385
  const applyStroke = !config.skipStroke && this.hasStroke();
382
386
  const strokeWidth = applyStroke
383
387
  ? forDrawing
@@ -3,8 +3,9 @@ import { Node } from '../Node.ts';
3
3
  import { Shape } from '../Shape.ts';
4
4
  import { Rect } from './Rect.ts';
5
5
  import { Group } from '../Group.ts';
6
- import type { ContainerConfig } from '../Container.ts';
6
+ import { type ContainerConfig } from '../Container.ts';
7
7
  import type { GetSet, IRect, Vector2d } from '../types.ts';
8
+ import type { HitCanvas, SceneCanvas } from '../Canvas.ts';
8
9
  export interface Box extends IRect {
9
10
  rotation: number;
10
11
  }
@@ -18,6 +19,7 @@ export interface TransformerConfig extends ContainerConfig {
18
19
  rotateAnchorOffset?: number;
19
20
  rotateAnchorAngle?: number;
20
21
  rotateAnchorCursor?: string;
22
+ rotateMode?: 'handle' | 'corners' | 'both';
21
23
  borderEnabled?: boolean;
22
24
  borderStroke?: string;
23
25
  borderStrokeWidth?: number;
@@ -54,6 +56,7 @@ export interface TransformerConfig extends ContainerConfig {
54
56
  * @param {Number} [config.rotateAnchorOffset] Default is 50
55
57
  * @param {Number} [config.rotateAnchorAngle] Angle of the rotate anchor around the box, in degrees. Default is 0 (top)
56
58
  * @param {String} [config.rotateAnchorCursor] Default is crosshair
59
+ * @param {String} [config.rotateMode] How the user rotates: 'handle' (the rotate anchor), 'corners' (invisible zones just outside the corners) or 'both'. Default is 'handle'
57
60
  * @param {Number} [config.padding] Default is 0
58
61
  * @param {Boolean} [config.borderEnabled] Should we draw border? Default is true
59
62
  * @param {String} [config.borderStroke] Border stroke color
@@ -65,7 +68,7 @@ export interface TransformerConfig extends ContainerConfig {
65
68
  * @param {Number} [config.anchorStrokeWidth] Anchor stroke size
66
69
  * @param {Number} [config.anchorSize] Default is 10
67
70
  * @param {Boolean} [config.keepRatio] Should we keep ratio when we are moving edges? Default is true
68
- * @param {String} [config.shiftBehavior] How does transformer react on shift key press when we are moving edges? Default is 'default'
71
+ * @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'
69
72
  * @param {Boolean} [config.centeredScaling] Should we resize relative to node's center? Default is false
70
73
  * @param {Array} [config.enabledAnchors] Array of names of enabled handles
71
74
  * @param {Boolean} [config.flipEnabled] Can we flip/mirror shape on transform?. True by default
@@ -104,12 +107,17 @@ export declare class Transformer extends Group {
104
107
  _fitting: boolean;
105
108
  _transformWindow: Window | null;
106
109
  _anchorDragOffset: Vector2d;
110
+ _rotateStart?: {
111
+ pointerAngle: number;
112
+ rotation: number;
113
+ };
107
114
  sin: number;
108
115
  cos: number;
109
116
  _cursorChange: boolean;
110
117
  _elementsCreated: boolean;
111
118
  _updateScheduled: boolean;
112
119
  _lastNodeRect?: Readonly<Box>;
120
+ _subtreeChanged: boolean;
113
121
  static isTransforming: () => boolean;
114
122
  static _isLayerTransforming(layer: Node): boolean;
115
123
  constructor(config?: TransformerConfig);
@@ -160,6 +168,10 @@ export declare class Transformer extends Group {
160
168
  * });
161
169
  */
162
170
  _resetTransformCache(changedNode?: Node): void;
171
+ _onSubtreeChange(node: Node): void;
172
+ _syncSubtreeChange(): void;
173
+ drawScene(can?: SceneCanvas, top?: Node): this;
174
+ drawHit(can?: HitCanvas, top?: Node): this;
163
175
  _getNodeRect(): any;
164
176
  __getNodeRect(): {
165
177
  x: number;
@@ -173,7 +185,8 @@ export declare class Transformer extends Group {
173
185
  getWidth(): any;
174
186
  getHeight(): any;
175
187
  _createElements(): void;
176
- _createAnchor(name: any): void;
188
+ _createAnchor(name: string, className?: string): Rect;
189
+ _setAnchorCursor(name: string, rad?: number): void;
177
190
  _createBack(): void;
178
191
  _handleMouseDown(e: any): void;
179
192
  _handleMouseMove(e: any): void;
@@ -186,7 +199,9 @@ export declare class Transformer extends Group {
186
199
  _scheduleUpdate(): void;
187
200
  /**
188
201
  * force update of Konva.Transformer.
189
- * Use it when you updated attached Konva.Group and now you need to reset transformer size
202
+ * The transformer follows attribute changes of attached nodes and, for an attached group, any change of its descendants.
203
+ * Use it after a change that sets no attribute, for example a `Line` points array mutated in place
204
+ * or a custom `getSelfRect()` that depends on outside state.
190
205
  * @method
191
206
  * @name Konva.Transformer#forceUpdate
192
207
  */
@@ -228,6 +243,7 @@ export declare class Transformer extends Group {
228
243
  rotateAnchorAngle: GetSet<number, this>;
229
244
  rotationSnapTolerance: GetSet<number, this>;
230
245
  rotateAnchorCursor: GetSet<string, this>;
246
+ rotateMode: GetSet<'handle' | 'corners' | 'both', this>;
231
247
  padding: GetSet<number, this>;
232
248
  borderEnabled: GetSet<boolean, this>;
233
249
  borderStroke: GetSet<string, this>;
@@ -4,6 +4,7 @@ import { Node } from "../Node.js";
4
4
  import { Shape } from "../Shape.js";
5
5
  import { Rect } from "./Rect.js";
6
6
  import { Group } from "../Group.js";
7
+ import { Container } from "../Container.js";
7
8
  import { Konva } from "../Global.js";
8
9
  import { getBooleanValidator, getNumberValidator } from "../Validators.js";
9
10
  import { _registerNode } from "../Global.js";
@@ -13,6 +14,7 @@ const ATTR_CHANGE_LIST = [
13
14
  'rotateAnchorOffsetChange',
14
15
  'rotateAnchorAngleChange',
15
16
  'rotateEnabledChange',
17
+ 'rotateModeChange',
16
18
  'enabledAnchorsChange',
17
19
  'anchorSizeChange',
18
20
  'borderEnabledChange',
@@ -61,10 +63,37 @@ const ANGLES = {
61
63
  'bottom-right': 135,
62
64
  };
63
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
+ }
64
88
  function getCursor(anchorName, rad, rotateCursor) {
65
89
  if (anchorName === 'rotater') {
66
90
  return rotateCursor;
67
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
+ }
68
97
  rad += Util.degToRad(ANGLES[anchorName] || 0);
69
98
  const angle = ((Util.radToDeg(rad) % 360) + 360) % 360;
70
99
  if (Util._inRange(angle, 315 + 22.5, 360) || Util._inRange(angle, 0, 22.5)) {
@@ -206,6 +235,7 @@ const activeTransformers = new Set();
206
235
  * @param {Number} [config.rotateAnchorOffset] Default is 50
207
236
  * @param {Number} [config.rotateAnchorAngle] Angle of the rotate anchor around the box, in degrees. Default is 0 (top)
208
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'
209
239
  * @param {Number} [config.padding] Default is 0
210
240
  * @param {Boolean} [config.borderEnabled] Should we draw border? Default is true
211
241
  * @param {String} [config.borderStroke] Border stroke color
@@ -217,7 +247,7 @@ const activeTransformers = new Set();
217
247
  * @param {Number} [config.anchorStrokeWidth] Anchor stroke size
218
248
  * @param {Number} [config.anchorSize] Default is 10
219
249
  * @param {Boolean} [config.keepRatio] Should we keep ratio when we are moving edges? Default is true
220
- * @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'
221
251
  * @param {Boolean} [config.centeredScaling] Should we resize relative to node's center? Default is false
222
252
  * @param {Array} [config.enabledAnchors] Array of names of enabled handles
223
253
  * @param {Boolean} [config.flipEnabled] Can we flip/mirror shape on transform?. True by default
@@ -260,6 +290,8 @@ export class Transformer extends Group {
260
290
  this._transformWindow = null;
261
291
  this._elementsCreated = false;
262
292
  this._updateScheduled = false;
293
+ // an attached container's descendants changed after the last layout
294
+ this._subtreeChanged = false;
263
295
  this._createElements();
264
296
  // bindings
265
297
  this._handleMouseMove = this._handleMouseMove.bind(this);
@@ -358,6 +390,8 @@ export class Transformer extends Group {
358
390
  }
359
391
  node.on(TRANSFORM_CHANGE_STR.map((e) => e + `.${this._getEventNamespace()}`).join(' '), onChange);
360
392
  node.on(`absoluteTransformChange.${this._getEventNamespace()}`, onChange);
393
+ if (node instanceof Container)
394
+ node._addSubtreeObserver(this);
361
395
  node.on(`destroy.${this._getEventNamespace()}`, () => {
362
396
  // a destroyed node has nothing left to transform
363
397
  this.setNodes(this._nodes.filter((n) => n !== node));
@@ -434,6 +468,7 @@ export class Transformer extends Group {
434
468
  if (this._nodes) {
435
469
  this._nodes.forEach((node) => {
436
470
  node.off('.' + this._getEventNamespace());
471
+ node._removeSubtreeObserver(this);
437
472
  });
438
473
  }
439
474
  this._nodes = [];
@@ -463,6 +498,42 @@ export class Transformer extends Group {
463
498
  this._clearCache('transform');
464
499
  this._clearSelfAndDescendantCache('absoluteTransform');
465
500
  }
501
+ // Called for every change below an attached container. A burst of child
502
+ // changes only drops cached values here. The new bounds are measured once,
503
+ // before the next frame, or earlier if a draw or transform step comes first
504
+ // (_syncSubtreeChange).
505
+ _onSubtreeChange(node) {
506
+ var _a, _b;
507
+ if (this._fitting)
508
+ return;
509
+ // nothing was measured since the last change, so nothing cached is stale
510
+ if (this._subtreeChanged && !this._cache[NODES_RECT])
511
+ return;
512
+ this._resetTransformCache(node);
513
+ if (!this._subtreeChanged) {
514
+ this._subtreeChanged = true;
515
+ // queued ahead of the draw the change requests, so that draw shows the
516
+ // new layout. Updating inside the draw would request one more frame.
517
+ Util.requestAnimFrame(() => this._syncSubtreeChange(), (_a = this.getStage()) === null || _a === void 0 ? void 0 : _a._getOwnerWindow());
518
+ // the transformer can be on another layer than the changed node
519
+ (_b = this.getLayer()) === null || _b === void 0 ? void 0 : _b.batchDraw();
520
+ }
521
+ }
522
+ _syncSubtreeChange() {
523
+ var _a;
524
+ // while dragging, the dragmove handler updates the layout
525
+ if (this._subtreeChanged && ((_a = this._nodes) === null || _a === void 0 ? void 0 : _a.length) && !this.isDragging()) {
526
+ this._update();
527
+ }
528
+ }
529
+ drawScene(can, top) {
530
+ this._syncSubtreeChange();
531
+ return super.drawScene(can, top);
532
+ }
533
+ drawHit(can, top) {
534
+ this._syncSubtreeChange();
535
+ return super.drawHit(can, top);
536
+ }
466
537
  _getNodeRect() {
467
538
  return this._getCache(NODES_RECT, this.__getNodeRect);
468
539
  }
@@ -577,18 +648,27 @@ export class Transformer extends Group {
577
648
  }
578
649
  _createElements() {
579
650
  this._createBack();
651
+ // below the resize anchors, so a resize anchor wins where they overlap
652
+ ROTATE_ZONE_NAMES.forEach((name) => {
653
+ // invisible, but its fill keeps it in the hit graph
654
+ this._createAnchor(name, '_rotate-zone').setAttrs({
655
+ fill: 'transparent',
656
+ strokeEnabled: false,
657
+ visible: false,
658
+ });
659
+ });
580
660
  ANCHORS_NAMES.forEach((name) => {
581
661
  this._createAnchor(name);
582
662
  });
583
663
  this._createAnchor('rotater');
584
664
  this._elementsCreated = true;
585
665
  }
586
- _createAnchor(name) {
666
+ _createAnchor(name, className = '_anchor') {
587
667
  const anchor = new Rect({
588
668
  stroke: 'rgb(0, 161, 255)',
589
669
  fill: 'white',
590
670
  strokeWidth: 1,
591
- name: name + ' _anchor',
671
+ name: name + ' ' + className,
592
672
  dragDistance: 0,
593
673
  // make it draggable,
594
674
  // so activating the anchor will not start drag&drop of any parent
@@ -611,11 +691,7 @@ export class Transformer extends Group {
611
691
  anchor.on('mouseenter', () => {
612
692
  if (this.isTransforming())
613
693
  return;
614
- const rad = Konva.getAngle(this.rotation());
615
- const rotateCursor = this.rotateAnchorCursor();
616
- const cursor = getCursor(name, rad, rotateCursor);
617
- anchor.getStage().content &&
618
- (anchor.getStage().content.style.cursor = cursor);
694
+ this._setAnchorCursor(name);
619
695
  this._cursorChange = true;
620
696
  });
621
697
  anchor.on('mouseout', () => {
@@ -626,6 +702,14 @@ export class Transformer extends Group {
626
702
  (anchor.getStage().content.style.cursor = '');
627
703
  });
628
704
  this.add(anchor);
705
+ return anchor;
706
+ }
707
+ _setAnchorCursor(name, rad = Konva.getAngle(this.rotation())) {
708
+ var _a;
709
+ const content = (_a = this.getStage()) === null || _a === void 0 ? void 0 : _a.content;
710
+ if (content) {
711
+ content.style.cursor = getCursor(name, rad, this.rotateAnchorCursor());
712
+ }
629
713
  }
630
714
  _createBack() {
631
715
  const back = new Shape({
@@ -641,7 +725,9 @@ export class Transformer extends Group {
641
725
  const height = shape.height();
642
726
  ctx.beginPath();
643
727
  ctx.rect(-padding, -padding, width + padding * 2, height + padding * 2);
644
- if (tr.rotateEnabled() && tr.rotateLineVisible()) {
728
+ if (tr.rotateEnabled() &&
729
+ tr.rotateLineVisible() &&
730
+ tr.rotateMode() !== 'corners') {
645
731
  const line = getRotaterLine(tr, width, height);
646
732
  ctx.moveTo(line.edgeX, line.edgeY);
647
733
  ctx.lineTo(line.endX, line.endY);
@@ -713,6 +799,13 @@ export class Transformer extends Group {
713
799
  x: pos.x - ap.x,
714
800
  y: pos.y - ap.y,
715
801
  };
802
+ if (isRotateAnchor(this._movingAnchorName)) {
803
+ const center = getCenter(attrs);
804
+ this._rotateStart = {
805
+ pointerAngle: Math.atan2(pos.y - center.y, pos.x - center.x),
806
+ rotation: attrs.rotation,
807
+ };
808
+ }
716
809
  activeTransformers.add(this);
717
810
  this._fire('transformstart', { evt: e.evt, target: this.getNode() });
718
811
  this._nodes.forEach((target) => {
@@ -724,6 +817,8 @@ export class Transformer extends Group {
724
817
  (_a = this.getStage()) === null || _a === void 0 ? void 0 : _a._batchEvents(() => this._moveTransform(e));
725
818
  }
726
819
  _moveTransform(e) {
820
+ // anchors must show the current bounds before they are measured against
821
+ this._syncSubtreeChange();
727
822
  let x, y, newHypotenuse;
728
823
  const anchorNode = this._anchors[this._movingAnchorName];
729
824
  const stage = anchorNode.getStage();
@@ -746,19 +841,33 @@ export class Transformer extends Group {
746
841
  if (oldAbs.x === newAbs.x && oldAbs.y === newAbs.y) {
747
842
  return;
748
843
  }
749
- // rotater is working very differently, so do it first
750
- if (this._movingAnchorName === 'rotater') {
844
+ // rotation is working very differently, so do it first
845
+ if (isRotateAnchor(this._movingAnchorName)) {
751
846
  const attrs = this._getNodeRect();
752
- x = anchorNode.x() - attrs.width / 2;
753
- y = -anchorNode.y() + attrs.height / 2;
754
- // Calculate angle from center to current anchor position
755
- // Offset by rotateAnchorAngle so we measure rotation from the anchor's starting position
756
- const rotateAnchorAngleRad = Util.degToRad(this.rotateAnchorAngle());
757
- let delta = Math.atan2(-y, x) + Math.PI / 2 - rotateAnchorAngleRad;
758
- const oldRotation = Konva.getAngle(this.rotation());
759
- const newRotation = oldRotation + delta;
760
- const tol = Konva.getAngle(this.rotationSnapTolerance());
761
- const snappedRot = getSnap(this.rotationSnaps(), newRotation, tol);
847
+ const center = getCenter(attrs);
848
+ const start = this._rotateStart;
849
+ // the grabbed point turns around the center by as much as the box,
850
+ // so the box follows the pointer wherever it was grabbed
851
+ const point = {
852
+ x: newAbs.x + this._anchorDragOffset.x,
853
+ y: newAbs.y + this._anchorDragOffset.y,
854
+ };
855
+ const pointerAngle = Math.atan2(point.y - center.y, point.x - center.x);
856
+ const newRotation = start.rotation + pointerAngle - start.pointerAngle;
857
+ let snappedRot;
858
+ if (e.shiftKey && this.shiftBehavior() !== 'none') {
859
+ snappedRot =
860
+ Math.round(newRotation / SHIFT_ROTATION_STEP) * SHIFT_ROTATION_STEP;
861
+ }
862
+ else {
863
+ const tol = Konva.getAngle(this.rotationSnapTolerance());
864
+ snappedRot = getSnap(this.rotationSnaps(), newRotation, tol);
865
+ }
866
+ // a corner zone cursor shows the direction of the turned corner,
867
+ // set before the transform event so its handlers can override it
868
+ if (this._movingAnchorName !== 'rotater') {
869
+ this._setAnchorCursor(this._movingAnchorName, snappedRot);
870
+ }
762
871
  const diff = snappedRot - attrs.rotation;
763
872
  const shape = rotateAroundCenter(attrs, diff);
764
873
  this._fitNodesInto(shape, e);
@@ -1161,7 +1270,9 @@ export class Transformer extends Group {
1161
1270
  }
1162
1271
  /**
1163
1272
  * force update of Konva.Transformer.
1164
- * Use it when you updated attached Konva.Group and now you need to reset transformer size
1273
+ * The transformer follows attribute changes of attached nodes and, for an attached group, any change of its descendants.
1274
+ * Use it after a change that sets no attribute, for example a `Line` points array mutated in place
1275
+ * or a custom `getSelfRect()` that depends on outside state.
1165
1276
  * @method
1166
1277
  * @name Konva.Transformer#forceUpdate
1167
1278
  */
@@ -1177,6 +1288,7 @@ export class Transformer extends Group {
1177
1288
  }
1178
1289
  _update() {
1179
1290
  var _a;
1291
+ this._subtreeChanged = false;
1180
1292
  const attrs = this._getNodeRect();
1181
1293
  this._updateElements(attrs);
1182
1294
  const draggable = this.nodes().some((node) => node.draggable());
@@ -1185,7 +1297,7 @@ export class Transformer extends Group {
1185
1297
  }
1186
1298
  const styleFunc = this.anchorStyleFunc();
1187
1299
  if (styleFunc) {
1188
- Object.values(this._anchors).forEach((node) => styleFunc(node));
1300
+ Object.values(this._anchors).forEach((node) => node.hasName('_anchor') && styleFunc(node));
1189
1301
  }
1190
1302
  (_a = this.getLayer()) === null || _a === void 0 ? void 0 : _a.batchDraw();
1191
1303
  }
@@ -1209,7 +1321,7 @@ export class Transformer extends Group {
1209
1321
  const resizeEnabled = this.resizeEnabled();
1210
1322
  const padding = this.padding();
1211
1323
  const anchorSize = this.anchorSize();
1212
- const anchors = Object.values(this._anchors);
1324
+ const anchors = Object.values(this._anchors).filter((node) => node.hasName('_anchor'));
1213
1325
  anchors.forEach((node) => {
1214
1326
  node.setAttrs({
1215
1327
  width: anchorSize,
@@ -1274,11 +1386,25 @@ export class Transformer extends Group {
1274
1386
  offsetY: anchorSize / 2 - padding,
1275
1387
  visible: resizeEnabled && enabledAnchors.indexOf('bottom-right') >= 0,
1276
1388
  });
1389
+ const rotateMode = this.rotateMode();
1277
1390
  const rotaterLine = getRotaterLine(this, width, height);
1278
1391
  this._anchors['rotater'].setAttrs({
1279
1392
  x: rotaterLine.endX,
1280
1393
  y: rotaterLine.endY,
1281
- visible: this.rotateEnabled(),
1394
+ visible: this.rotateEnabled() && rotateMode !== 'corners',
1395
+ });
1396
+ // each zone is a square that touches its corner from the outside
1397
+ const zoneSize = anchorSize * 2;
1398
+ const zonesVisible = this.rotateEnabled() && rotateMode !== 'handle';
1399
+ const near = -padding - zoneSize;
1400
+ ROTATE_ZONE_NAMES.forEach((name) => {
1401
+ this._anchors[name].setAttrs({
1402
+ x: name.includes('left') ? near : width + padding,
1403
+ y: name.includes('top') ? near : height + padding,
1404
+ width: zoneSize,
1405
+ height: zoneSize,
1406
+ visible: zonesVisible,
1407
+ });
1282
1408
  });
1283
1409
  this._back.setAttrs({
1284
1410
  width: width,
@@ -1517,6 +1643,23 @@ Factory.addGetterSetter(Transformer, 'rotateAnchorAngle', 0, getNumberValidator(
1517
1643
  * transformer.rotateAnchorCursor('grab');
1518
1644
  */
1519
1645
  Factory.addGetterSetter(Transformer, 'rotateAnchorCursor', 'crosshair');
1646
+ /**
1647
+ * get/set how the user rotates the nodes. 'handle' shows the rotate anchor,
1648
+ * 'corners' makes invisible zones just outside the box corners rotate,
1649
+ * 'both' enables both. Hold Shift while rotating to snap to 15 degree steps, unless shiftBehavior is 'none'.
1650
+ * While a corner zone rotates, `getActiveAnchor()` returns its name, such as 'rotater-top-left'.
1651
+ * @name Konva.Transformer#rotateMode
1652
+ * @method
1653
+ * @param {String} mode
1654
+ * @returns {String}
1655
+ * @example
1656
+ * // get
1657
+ * var rotateMode = transformer.rotateMode();
1658
+ *
1659
+ * // set
1660
+ * transformer.rotateMode('corners');
1661
+ */
1662
+ Factory.addGetterSetter(Transformer, 'rotateMode', 'handle');
1520
1663
  /**
1521
1664
  * get/set distance for rotation tolerance
1522
1665
  * @name Konva.Transformer#rotationSnapTolerance
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "konva",
3
- "version": "10.7.0",
3
+ "version": "10.8.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",