konva 10.3.2 → 10.4.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.
Files changed (123) hide show
  1. package/README.md +5 -1
  2. package/konva.js +1327 -1572
  3. package/konva.min.js +4 -4
  4. package/lib/Animation.d.ts +63 -3
  5. package/lib/Animation.js +86 -65
  6. package/lib/BezierFunctions.d.ts +10 -0
  7. package/lib/BezierFunctions.js +32 -0
  8. package/lib/Canvas.d.ts +53 -0
  9. package/lib/Canvas.js +93 -34
  10. package/lib/Container.d.ts +156 -9
  11. package/lib/Container.js +260 -25
  12. package/lib/Context.d.ts +247 -0
  13. package/lib/Context.js +312 -74
  14. package/lib/Core.js +1 -0
  15. package/lib/DragAndDrop.d.ts +1 -0
  16. package/lib/DragAndDrop.js +66 -17
  17. package/lib/Factory.d.ts +24 -1
  18. package/lib/Factory.js +14 -20
  19. package/lib/FastLayer.d.ts +14 -1
  20. package/lib/FastLayer.js +14 -1
  21. package/lib/Global.d.ts +114 -3
  22. package/lib/Global.js +134 -5
  23. package/lib/Group.d.ts +11 -0
  24. package/lib/Group.js +11 -0
  25. package/lib/Layer.d.ts +128 -3
  26. package/lib/Layer.js +260 -49
  27. package/lib/Node.d.ts +692 -30
  28. package/lib/Node.js +1534 -202
  29. package/lib/PointerEvents.d.ts +2 -1
  30. package/lib/PointerEvents.js +19 -1
  31. package/lib/Shape.d.ts +99 -14
  32. package/lib/Shape.js +1101 -67
  33. package/lib/Stage.d.ts +81 -1
  34. package/lib/Stage.js +166 -7
  35. package/lib/Tween.d.ts +159 -4
  36. package/lib/Tween.js +243 -24
  37. package/lib/Util.d.ts +147 -4
  38. package/lib/Util.js +332 -82
  39. package/lib/Validators.d.ts +0 -2
  40. package/lib/Validators.js +3 -25
  41. package/lib/_CoreInternals.d.ts +10 -6
  42. package/lib/_CoreInternals.js +1 -0
  43. package/lib/_FullInternals.d.ts +15 -6
  44. package/lib/_FullInternals.js +7 -0
  45. package/lib/canvas-backend.js +6 -0
  46. package/lib/filters/Blur.d.ts +18 -0
  47. package/lib/filters/Blur.js +97 -24
  48. package/lib/filters/Brighten.d.ts +21 -0
  49. package/lib/filters/Brighten.js +24 -0
  50. package/lib/filters/Brightness.d.ts +11 -0
  51. package/lib/filters/Brightness.js +16 -0
  52. package/lib/filters/Contrast.d.ts +10 -0
  53. package/lib/filters/Contrast.js +21 -0
  54. package/lib/filters/Emboss.d.ts +20 -0
  55. package/lib/filters/Emboss.js +68 -8
  56. package/lib/filters/Enhance.d.ts +14 -0
  57. package/lib/filters/Enhance.js +34 -0
  58. package/lib/filters/Grayscale.d.ts +9 -0
  59. package/lib/filters/Grayscale.js +12 -0
  60. package/lib/filters/HSL.d.ts +17 -0
  61. package/lib/filters/HSL.js +48 -5
  62. package/lib/filters/HSV.d.ts +18 -0
  63. package/lib/filters/HSV.js +49 -5
  64. package/lib/filters/Invert.d.ts +9 -0
  65. package/lib/filters/Invert.js +12 -0
  66. package/lib/filters/Kaleidoscope.d.ts +12 -0
  67. package/lib/filters/Kaleidoscope.js +83 -0
  68. package/lib/filters/Mask.d.ts +11 -0
  69. package/lib/filters/Mask.js +18 -0
  70. package/lib/filters/Noise.d.ts +19 -0
  71. package/lib/filters/Noise.js +19 -0
  72. package/lib/filters/Pixelate.d.ts +20 -0
  73. package/lib/filters/Pixelate.js +28 -1
  74. package/lib/filters/Posterize.d.ts +21 -0
  75. package/lib/filters/Posterize.js +22 -0
  76. package/lib/filters/RGB.d.ts +21 -0
  77. package/lib/filters/RGB.js +43 -28
  78. package/lib/filters/RGBA.d.ts +23 -0
  79. package/lib/filters/RGBA.js +28 -41
  80. package/lib/filters/Sepia.d.ts +9 -0
  81. package/lib/filters/Sepia.js +10 -0
  82. package/lib/filters/Solarize.d.ts +10 -0
  83. package/lib/filters/Solarize.js +11 -0
  84. package/lib/filters/Threshold.d.ts +22 -0
  85. package/lib/filters/Threshold.js +22 -0
  86. package/lib/shapes/Arc.d.ts +40 -0
  87. package/lib/shapes/Arc.js +89 -6
  88. package/lib/shapes/Arrow.d.ts +24 -1
  89. package/lib/shapes/Arrow.js +83 -0
  90. package/lib/shapes/Circle.d.ts +18 -0
  91. package/lib/shapes/Circle.js +36 -9
  92. package/lib/shapes/Ellipse.d.ts +34 -2
  93. package/lib/shapes/Ellipse.js +67 -9
  94. package/lib/shapes/Image.d.ts +49 -0
  95. package/lib/shapes/Image.js +151 -22
  96. package/lib/shapes/Label.d.ts +65 -1
  97. package/lib/shapes/Label.js +113 -20
  98. package/lib/shapes/Line.d.ts +50 -8
  99. package/lib/shapes/Line.js +116 -20
  100. package/lib/shapes/Path.d.ts +40 -6
  101. package/lib/shapes/Path.js +187 -128
  102. package/lib/shapes/Rect.d.ts +18 -0
  103. package/lib/shapes/Rect.js +36 -0
  104. package/lib/shapes/RegularPolygon.d.ts +22 -0
  105. package/lib/shapes/RegularPolygon.js +70 -0
  106. package/lib/shapes/Ring.d.ts +19 -0
  107. package/lib/shapes/Ring.js +51 -5
  108. package/lib/shapes/Sprite.d.ts +78 -0
  109. package/lib/shapes/Sprite.js +238 -25
  110. package/lib/shapes/Star.d.ts +23 -0
  111. package/lib/shapes/Star.js +62 -0
  112. package/lib/shapes/Text.d.ts +59 -1
  113. package/lib/shapes/Text.js +481 -97
  114. package/lib/shapes/TextPath.d.ts +49 -3
  115. package/lib/shapes/TextPath.js +278 -34
  116. package/lib/shapes/Transformer.d.ts +108 -11
  117. package/lib/shapes/Transformer.js +744 -102
  118. package/lib/shapes/Wedge.d.ts +22 -0
  119. package/lib/shapes/Wedge.js +67 -3
  120. package/lib/skia-backend.js +9 -0
  121. package/lib/types.d.ts +2 -23
  122. package/lib/types.js +1 -21
  123. package/package.json +24 -21
package/lib/Util.js CHANGED
@@ -1,7 +1,7 @@
1
1
  import { Konva } from "./Global.js";
2
2
  const NODE_ERROR = `Konva.js unsupported environment.
3
3
 
4
- Looks like you are trying to use Konva.js in Node.js environment. because "document" object is undefined.
4
+ Looks like you are trying to use Konva.js in Node.js environment (or in a Web Worker), because "document" object is undefined.
5
5
 
6
6
  To use Konva.js in Node.js environment, you need to use the "canvas-backend" or "skia-backend" module.
7
7
 
@@ -18,10 +18,33 @@ const ensureBrowser = () => {
18
18
  throw new Error(NODE_ERROR);
19
19
  }
20
20
  };
21
+ /*
22
+ * Last updated November 2011
23
+ * By Simon Sarris
24
+ * www.simonsarris.com
25
+ * sarris@acm.org
26
+ *
27
+ * Free to use and distribute at will
28
+ * So long as you are nice to people, etc
29
+ */
30
+ /*
31
+ * The usage of this class was inspired by some of the work done by a forked
32
+ * project, KineticJS-Ext by Wappworks, which is based on Simon's Transform
33
+ * class. Modified by Eric Rowell
34
+ */
35
+ /**
36
+ * Transform constructor.
37
+ * In most of the cases you don't need to use it in your app. Because it is for internal usage in Konva core.
38
+ * But there is a documentation for that class in case you still want
39
+ * to make some manual calculations.
40
+ * @constructor
41
+ * @param {Array} [m] Optional six-element matrix
42
+ * @memberof Konva
43
+ */
21
44
  export class Transform {
22
- constructor(m = [1, 0, 0, 1, 0, 0]) {
45
+ constructor(m) {
23
46
  this.dirty = false;
24
- this.m = (m && m.slice()) || [1, 0, 0, 1, 0, 0];
47
+ this.m = m ? m.slice() : [1, 0, 0, 1, 0, 0];
25
48
  }
26
49
  reset() {
27
50
  this.m[0] = 1;
@@ -31,6 +54,14 @@ export class Transform {
31
54
  this.m[4] = 0;
32
55
  this.m[5] = 0;
33
56
  }
57
+ /**
58
+ * Copy Konva.Transform object
59
+ * @method
60
+ * @name Konva.Transform#copy
61
+ * @returns {Konva.Transform}
62
+ * @example
63
+ * const tr = shape.getTransform().copy()
64
+ */
34
65
  copy() {
35
66
  return new Transform(this.m);
36
67
  }
@@ -42,6 +73,13 @@ export class Transform {
42
73
  tr.m[4] = this.m[4];
43
74
  tr.m[5] = this.m[5];
44
75
  }
76
+ /**
77
+ * Transform point
78
+ * @method
79
+ * @name Konva.Transform#point
80
+ * @param {Object} point 2D point(x, y)
81
+ * @returns {Object} 2D point(x, y)
82
+ */
45
83
  point(point) {
46
84
  const m = this.m;
47
85
  return {
@@ -49,11 +87,27 @@ export class Transform {
49
87
  y: m[1] * point.x + m[3] * point.y + m[5],
50
88
  };
51
89
  }
90
+ /**
91
+ * Apply translation
92
+ * @method
93
+ * @name Konva.Transform#translate
94
+ * @param {Number} x
95
+ * @param {Number} y
96
+ * @returns {Konva.Transform}
97
+ */
52
98
  translate(x, y) {
53
99
  this.m[4] += this.m[0] * x + this.m[2] * y;
54
100
  this.m[5] += this.m[1] * x + this.m[3] * y;
55
101
  return this;
56
102
  }
103
+ /**
104
+ * Apply scale
105
+ * @method
106
+ * @name Konva.Transform#scale
107
+ * @param {Number} sx
108
+ * @param {Number} sy
109
+ * @returns {Konva.Transform}
110
+ */
57
111
  scale(sx, sy) {
58
112
  this.m[0] *= sx;
59
113
  this.m[1] *= sx;
@@ -61,6 +115,13 @@ export class Transform {
61
115
  this.m[3] *= sy;
62
116
  return this;
63
117
  }
118
+ /**
119
+ * Apply rotation
120
+ * @method
121
+ * @name Konva.Transform#rotate
122
+ * @param {Number} rad Angle in radians
123
+ * @returns {Konva.Transform}
124
+ */
64
125
  rotate(rad) {
65
126
  const c = Math.cos(rad);
66
127
  const s = Math.sin(rad);
@@ -74,12 +135,26 @@ export class Transform {
74
135
  this.m[3] = m22;
75
136
  return this;
76
137
  }
138
+ /**
139
+ * Returns the translation
140
+ * @method
141
+ * @name Konva.Transform#getTranslation
142
+ * @returns {Object} 2D point(x, y)
143
+ */
77
144
  getTranslation() {
78
145
  return {
79
146
  x: this.m[4],
80
147
  y: this.m[5],
81
148
  };
82
149
  }
150
+ /**
151
+ * Apply skew
152
+ * @method
153
+ * @name Konva.Transform#skew
154
+ * @param {Number} sx
155
+ * @param {Number} sy
156
+ * @returns {Konva.Transform}
157
+ */
83
158
  skew(sx, sy) {
84
159
  const m11 = this.m[0] + this.m[2] * sy;
85
160
  const m12 = this.m[1] + this.m[3] * sy;
@@ -91,6 +166,13 @@ export class Transform {
91
166
  this.m[3] = m22;
92
167
  return this;
93
168
  }
169
+ /**
170
+ * Transform multiplication
171
+ * @method
172
+ * @name Konva.Transform#multiply
173
+ * @param {Konva.Transform} matrix
174
+ * @returns {Konva.Transform}
175
+ */
94
176
  multiply(matrix) {
95
177
  const m11 = this.m[0] * matrix.m[0] + this.m[2] * matrix.m[1];
96
178
  const m12 = this.m[1] * matrix.m[0] + this.m[3] * matrix.m[1];
@@ -106,6 +188,16 @@ export class Transform {
106
188
  this.m[5] = dy;
107
189
  return this;
108
190
  }
191
+ /**
192
+ * Invert the matrix
193
+ * @method
194
+ * @name Konva.Transform#invert
195
+ * @returns {Konva.Transform}
196
+ */
197
+ // a transform with a zero scale on an axis has no inverse
198
+ isInvertible() {
199
+ return this.m[0] * this.m[3] - this.m[1] * this.m[2] !== 0;
200
+ }
109
201
  invert() {
110
202
  const d = 1 / (this.m[0] * this.m[3] - this.m[1] * this.m[2]);
111
203
  const m0 = this.m[3] * d;
@@ -122,9 +214,20 @@ export class Transform {
122
214
  this.m[5] = m5;
123
215
  return this;
124
216
  }
217
+ /**
218
+ * return matrix
219
+ * @method
220
+ * @name Konva.Transform#getMatrix
221
+ */
125
222
  getMatrix() {
126
223
  return this.m;
127
224
  }
225
+ /**
226
+ * convert transformation matrix back into node's attributes
227
+ * @method
228
+ * @name Konva.Transform#decompose
229
+ * @returns {Konva.Transform}
230
+ */
128
231
  decompose() {
129
232
  const a = this.m[0];
130
233
  const b = this.m[1];
@@ -142,12 +245,15 @@ export class Transform {
142
245
  skewX: 0,
143
246
  skewY: 0,
144
247
  };
248
+ // Apply the QR-like decomposition. A zero determinant (a scale of 0, or
249
+ // a shear that collapses the plane) has no skew, rather than a NaN or
250
+ // an infinite one
145
251
  if (a != 0 || b != 0) {
146
252
  const r = Math.sqrt(a * a + b * b);
147
253
  result.rotation = b > 0 ? Math.acos(a / r) : -Math.acos(a / r);
148
254
  result.scaleX = r;
149
255
  result.scaleY = delta / r;
150
- result.skewX = (a * c + b * d) / delta;
256
+ result.skewX = delta && (a * c + b * d) / delta;
151
257
  result.skewY = 0;
152
258
  }
153
259
  else if (c != 0 || d != 0) {
@@ -157,14 +263,16 @@ export class Transform {
157
263
  result.scaleX = delta / s;
158
264
  result.scaleY = s;
159
265
  result.skewX = 0;
160
- result.skewY = (a * c + b * d) / delta;
266
+ result.skewY = delta && (a * c + b * d) / delta;
161
267
  }
162
268
  else {
269
+ // a = b = c = d = 0
163
270
  }
164
271
  result.rotation = Util._getRotation(result.rotation);
165
272
  return result;
166
273
  }
167
274
  }
275
+ // CONSTANTS
168
276
  const 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: ', COLORS = {
169
277
  aliceblue: [240, 248, 255],
170
278
  antiquewhite: [250, 235, 215],
@@ -306,7 +414,7 @@ const OBJECT_ARRAY = '[object Array]', OBJECT_NUMBER = '[object Number]', OBJECT
306
414
  tan: [210, 180, 140],
307
415
  teal: [0, 128, 128],
308
416
  thistle: [216, 191, 216],
309
- transparent: [255, 255, 255, 0],
417
+ transparent: [0, 0, 0, 0],
310
418
  tomato: [255, 99, 71],
311
419
  turquoise: [64, 224, 208],
312
420
  violet: [238, 130, 238],
@@ -316,7 +424,11 @@ const OBJECT_ARRAY = '[object Array]', OBJECT_NUMBER = '[object Number]', OBJECT
316
424
  yellow: [255, 255, 0],
317
425
  yellowgreen: [154, 205, 50],
318
426
  };
427
+ // Cache for canvas farbling detection
319
428
  let _isCanvasFarblingActive = null;
429
+ // A stage may be rendered in another window than the one Konva was imported
430
+ // into, and a window that is not visible gives almost no frames. So frames are
431
+ // asked from the window of the stage, and the callbacks are kept per window
320
432
  const defaultWindow = typeof window !== 'undefined' ? window : {};
321
433
  const animQueues = new WeakMap();
322
434
  const requestFrame = (win, f) => {
@@ -327,18 +439,31 @@ const requestFrame = (win, f) => {
327
439
  requestAnimationFrame(f);
328
440
  }
329
441
  else {
330
- setTimeout(f, 16);
442
+ setTimeout(f, 16); // 60fps ≈ 16.67ms per frame
331
443
  }
332
444
  };
333
445
  const capitalizeCache = new Map();
446
+ // the common ancestor of every typed array
447
+ // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray#description
448
+ export const TypedArray = Object.getPrototypeOf(Int8Array);
449
+ // Split the components of rgb()/hsl(). CSS separates them with commas (legacy
450
+ // syntax), or with spaces and a slash before the alpha (CSS Color 4 syntax),
451
+ // but never with both. Keep the two apart, so that a space inside a
452
+ // comma-separated color adds no component. A component the user left empty
453
+ // stays as "", which then fails the color.
334
454
  const splitColorComponents = (str) => {
335
455
  const components = str.trim();
336
456
  return components.indexOf(',') === -1
337
457
  ? components.split(/\s*\/\s*|\s+/)
338
458
  : components.split(/\s*,\s*/);
339
459
  };
460
+ // A CSS number: "50", "-0.5", ".5", "1e2". Everything else, from "50abc" to
461
+ // "0x10" and "1.2.3", is not a number and makes the color fail.
340
462
  const NUMBER_SOURCE = '[+-]?(?:\\d+\\.?\\d*|\\.\\d+)(?:e[+-]?\\d+)?';
463
+ // A component is a number with an optional "%" sign.
341
464
  const COLOR_COMPONENT_REGEX = new RegExp(`^(${NUMBER_SOURCE})(%?)$`, 'i');
465
+ // Parse one color component. 100% is `max`: 255 for the color channels of
466
+ // rgb(), 1 for the alpha, 100 for the saturation and the lightness of hsl().
342
467
  const parseColorComponent = (value, max) => {
343
468
  const match = COLOR_COMPONENT_REGEX.exec(value);
344
469
  if (!match) {
@@ -346,8 +471,13 @@ const parseColorComponent = (value, max) => {
346
471
  }
347
472
  return match[2] ? (Number(match[1]) / 100) * max : Number(match[1]);
348
473
  };
474
+ // parseInt() stops at the first character it can not read, so "#0g0000" would
475
+ // give a valid black instead of failing. The hex parsers test the shape first.
349
476
  const HEX_COLOR_REGEX = /^#[0-9a-f]+$/i;
477
+ // Keep a fraction in [0, 1]. NaN stays NaN, so a bad value still fails.
350
478
  const clamp01 = (value) => Math.min(Math.max(value, 0), 1);
479
+ // The hue of hsl() is the same number, with a CSS Color 4 angle unit
480
+ // instead of the "%" sign. No unit means degrees.
351
481
  const HUE_REGEX = new RegExp(`^(${NUMBER_SOURCE})(deg|grad|rad|turn)?$`, 'i');
352
482
  const HUE_UNITS = {
353
483
  deg: 1,
@@ -355,7 +485,18 @@ const HUE_UNITS = {
355
485
  rad: DEG180_OVER_PI,
356
486
  turn: 360,
357
487
  };
488
+ /**
489
+ * @namespace Util
490
+ * @memberof Konva
491
+ */
492
+ // a negative corner radius would throw in context.arc()
493
+ function clampRadius(radius, max) {
494
+ return Math.min(Math.max(radius || 0, 0), max);
495
+ }
358
496
  export const Util = {
497
+ /*
498
+ * cherry-picked utilities from underscore.js
499
+ */
359
500
  _isElement(obj) {
360
501
  return !!(obj && obj.nodeType == 1);
361
502
  },
@@ -379,6 +520,7 @@ export const Util = {
379
520
  _isBoolean(obj) {
380
521
  return Object.prototype.toString.call(obj) === OBJECT_BOOLEAN;
381
522
  },
523
+ // arrays are objects too
382
524
  isObject(val) {
383
525
  return val instanceof Object;
384
526
  },
@@ -393,6 +535,8 @@ export const Util = {
393
535
  },
394
536
  _sign(number) {
395
537
  if (number === 0) {
538
+ // that is not what sign usually returns
539
+ // but that is what we need
396
540
  return 1;
397
541
  }
398
542
  if (number > 0) {
@@ -420,6 +564,7 @@ export const Util = {
420
564
  createCanvasElement() {
421
565
  ensureBrowser();
422
566
  const canvas = document.createElement('canvas');
567
+ // on some environments canvas.style is readonly
423
568
  try {
424
569
  canvas.style = canvas.style || {};
425
570
  }
@@ -431,9 +576,15 @@ export const Util = {
431
576
  return document.createElement('img');
432
577
  },
433
578
  _isInDocument(el) {
579
+ // not `el.parentNode == document`, because the element may belong to
580
+ // another document: an iframe, or a popout window
434
581
  return !!el.isConnected;
435
582
  },
583
+ /*
584
+ * arg can be an image object or image data
585
+ */
436
586
  _urlToImage(url, callback) {
587
+ // if arg is a string, then it's a data url
437
588
  const imageObj = Util.createImageElement();
438
589
  imageObj.onload = function () {
439
590
  callback(imageObj);
@@ -452,6 +603,13 @@ export const Util = {
452
603
  b: bigint & 255,
453
604
  };
454
605
  },
606
+ /**
607
+ * return random hex color
608
+ * @method
609
+ * @memberof Konva.Util
610
+ * @example
611
+ * shape.fill(Konva.Util.getRandomColor());
612
+ */
455
613
  getRandomColor() {
456
614
  let randColor = ((Math.random() * 0xffffff) << 0).toString(16);
457
615
  while (randColor.length < 6) {
@@ -459,6 +617,12 @@ export const Util = {
459
617
  }
460
618
  return HASH + randColor;
461
619
  },
620
+ /**
621
+ * Check if canvas farbling is active (e.g., Brave browser fingerprinting protection)
622
+ * @method
623
+ * @memberof Konva.Util
624
+ * @returns {Boolean}
625
+ */
462
626
  isCanvasFarblingActive() {
463
627
  if (_isCanvasFarblingActive !== null) {
464
628
  return _isCanvasFarblingActive;
@@ -474,7 +638,7 @@ export const Util = {
474
638
  willReadFrequently: true,
475
639
  });
476
640
  ctx.clearRect(0, 0, 10, 10);
477
- ctx.fillStyle = '#282828';
641
+ ctx.fillStyle = '#282828'; // 40, 40, 40
478
642
  ctx.fillRect(0, 0, 10, 10);
479
643
  const d = ctx.getImageData(0, 0, 10, 10).data;
480
644
  let isFarbling = false;
@@ -491,31 +655,67 @@ export const Util = {
491
655
  this.releaseCanvas(c);
492
656
  return _isCanvasFarblingActive;
493
657
  },
658
+ /**
659
+ * Get a random color for hit detection (snapped to the hit color grid)
660
+ * @method
661
+ * @memberof Konva.Util
662
+ * @returns {String} hex color string
663
+ */
494
664
  getHitColor() {
495
- const color = this.getRandomColor();
496
- return this.isCanvasFarblingActive()
497
- ? this.getSnappedHexColor(color)
498
- : color;
665
+ const channel = () => (Math.random() * 256) | 0;
666
+ return this.getHitColorKey(channel(), channel(), channel());
499
667
  },
668
+ /**
669
+ * Get hit color key from RGB values (snapped to the hit color grid)
670
+ * @method
671
+ * @memberof Konva.Util
672
+ * @param {Number} r - red component (0-255)
673
+ * @param {Number} g - green component (0-255)
674
+ * @param {Number} b - blue component (0-255)
675
+ * @returns {String} hex color key string
676
+ */
500
677
  getHitColorKey(r, g, b) {
501
- if (this.isCanvasFarblingActive()) {
502
- r = Math.round(r / 5) * 5;
503
- g = Math.round(g / 5) * 5;
504
- b = Math.round(b / 5) * 5;
505
- }
506
- return HASH + this._rgbToHex(r, g, b);
678
+ // hit colours live on a grid, so a pixel of the hit graph that reads
679
+ // back slightly off still rounds to the key of its shape: an edge pixel
680
+ // is stored premultiplied by its alpha and comes back off by up to one
681
+ // per channel, canvas farbling (Brave) adds a little noise on top
682
+ const step = this.isCanvasFarblingActive() ? 5 : 3;
683
+ const snap = (value) => Math.round(value / step) * step;
684
+ return HASH + this._rgbToHex(snap(r), snap(g), snap(b));
507
685
  },
686
+ /**
687
+ * Snap a hex color to the hit color grid
688
+ * @method
689
+ * @memberof Konva.Util
690
+ * @param {String} hex - hex color string (e.g., "#ff00ff")
691
+ * @returns {String} snapped hex color string
692
+ */
508
693
  getSnappedHexColor(hex) {
509
- const rgb = this._hexToRgb(hex);
510
- return (HASH +
511
- this._rgbToHex(Math.round(rgb.r / 5) * 5, Math.round(rgb.g / 5) * 5, Math.round(rgb.b / 5) * 5));
694
+ const { r, g, b } = this._hexToRgb(hex);
695
+ return this.getHitColorKey(r, g, b);
512
696
  },
697
+ /**
698
+ * get RGB components of a color
699
+ * @method
700
+ * @memberof Konva.Util
701
+ * @param {String} color
702
+ * @example
703
+ * // each of the following examples return {r:0, g:0, b:255}
704
+ * var rgb = Konva.Util.getRGB('blue');
705
+ * var rgb = Konva.Util.getRGB('#0000ff');
706
+ * var rgb = Konva.Util.getRGB('rgb(0,0,255)');
707
+ */
513
708
  getRGB(color) {
514
709
  var _a;
710
+ // black for a color we can not parse
515
711
  const { r = 0, g = 0, b = 0 } = (_a = Util.colorToRGBA(color)) !== null && _a !== void 0 ? _a : {};
516
712
  return { r, g, b };
517
713
  },
714
+ // convert any color string to RGBA object
715
+ // from https://github.com/component/color-parser
518
716
  colorToRGBA(str) {
717
+ // a CSS custom property keeps the space after the colon,
718
+ // so "--brand: #ff0000" gives us " #ff0000"
519
719
  str = (str || '').trim() || 'black';
520
720
  const color = Util._namedColorToRBA(str) ||
521
721
  Util._hex3ColorToRGBA(str) ||
@@ -524,10 +724,13 @@ export const Util = {
524
724
  Util._hex8ColorToRGBA(str) ||
525
725
  Util._rgbColorToRGBA(str) ||
526
726
  Util._hslColorToRGBA(str);
727
+ // a NaN component stays invisible until it reaches the canvas and drops the
728
+ // shape, so a color we can not fully parse must fail as a whole
527
729
  if (color && [color.r, color.g, color.b, color.a].every(Util._isNumber)) {
528
730
  return color;
529
731
  }
530
732
  },
733
+ // Parse named css color. Like "green"
531
734
  _namedColorToRBA(str) {
532
735
  const c = COLORS[str.toLowerCase()];
533
736
  if (!c) {
@@ -540,6 +743,7 @@ export const Util = {
540
743
  a: c.length > 3 ? c[3] : 1,
541
744
  };
542
745
  },
746
+ // Parse rgb(n, n, n), rgba(n, n, n, n) and rgb(n n n / n)
543
747
  _rgbColorToRGBA(str) {
544
748
  const match = /^rgba?\(([^)]*)\)$/i.exec(str);
545
749
  if (!match) {
@@ -556,6 +760,7 @@ export const Util = {
556
760
  a: parts.length > 3 ? parseColorComponent(parts[3], 1) : 1,
557
761
  };
558
762
  },
763
+ // Parse #nnnnnnnn
559
764
  _hex8ColorToRGBA(str) {
560
765
  if (str.length === 9 && HEX_COLOR_REGEX.test(str)) {
561
766
  return {
@@ -566,6 +771,7 @@ export const Util = {
566
771
  };
567
772
  }
568
773
  },
774
+ // Parse #nnnnnn
569
775
  _hex6ColorToRGBA(str) {
570
776
  if (str.length === 7 && HEX_COLOR_REGEX.test(str)) {
571
777
  return {
@@ -576,6 +782,7 @@ export const Util = {
576
782
  };
577
783
  }
578
784
  },
785
+ // Parse #nnnn
579
786
  _hex4ColorToRGBA(str) {
580
787
  if (str.length === 5 && HEX_COLOR_REGEX.test(str)) {
581
788
  return {
@@ -586,6 +793,7 @@ export const Util = {
586
793
  };
587
794
  }
588
795
  },
796
+ // Parse #nnn
589
797
  _hex3ColorToRGBA(str) {
590
798
  if (str.length === 4 && HEX_COLOR_REGEX.test(str)) {
591
799
  return {
@@ -596,6 +804,8 @@ export const Util = {
596
804
  };
597
805
  }
598
806
  },
807
+ // Code adapted from https://github.com/Qix-/color-convert/blob/master/conversions.js#L244
808
+ // Parse hsl(h, s%, l%), hsla(h, s%, l%, n) and hsl(h s% l% / n)
599
809
  _hslColorToRGBA(str) {
600
810
  const match = /^hsla?\(([^)]*)\)$/i.exec(str);
601
811
  if (!match) {
@@ -605,6 +815,8 @@ export const Util = {
605
815
  if (parts.length < 3 || parts.length > 4) {
606
816
  return;
607
817
  }
818
+ // a hue we can not parse gives a gray color instead of a NaN one,
819
+ // so colorToRGBA() can not catch it at the end
608
820
  const hue = HUE_REGEX.exec(parts[0]);
609
821
  if (!hue) {
610
822
  return;
@@ -614,7 +826,13 @@ export const Util = {
614
826
  if (!isFinite(degrees)) {
615
827
  return;
616
828
  }
829
+ // the hue is an angle, so keep it in [0, 360) to also accept
830
+ // negative angles and angles over one full turn
617
831
  const h = (((degrees % 360) + 360) % 360) / 360;
832
+ // the saturation and the lightness are percentages of 1, written with or
833
+ // without the "%" sign, so read them out of 100 and then scale them down.
834
+ // CSS keeps them in [0, 1]; out of that range the math gives a negative
835
+ // channel, which the canvas can not read at all.
618
836
  const s = clamp01(parseColorComponent(parts[1], 100) / 100);
619
837
  const l = clamp01(parseColorComponent(parts[2], 100) / 100);
620
838
  const a = parts.length > 3 ? parseColorComponent(parts[3], 1) : 1;
@@ -651,26 +869,71 @@ export const Util = {
651
869
  a,
652
870
  };
653
871
  },
872
+ // the bounds of a flat [x0, y0, x1, y1, ...] array. A NaN coordinate is
873
+ // skipped so one bad point cannot turn the whole box into NaN; no usable
874
+ // point at all is an empty rect
875
+ _getPointsRect(points) {
876
+ let minX = Infinity;
877
+ let minY = Infinity;
878
+ let maxX = -Infinity;
879
+ let maxY = -Infinity;
880
+ for (let i = 0; i < points.length; i += 2) {
881
+ const x = points[i];
882
+ const y = points[i + 1];
883
+ if (!isNaN(x)) {
884
+ minX = Math.min(minX, x);
885
+ maxX = Math.max(maxX, x);
886
+ }
887
+ if (!isNaN(y)) {
888
+ minY = Math.min(minY, y);
889
+ maxY = Math.max(maxY, y);
890
+ }
891
+ }
892
+ if (!isFinite(minX + minY)) {
893
+ return { x: 0, y: 0, width: 0, height: 0 };
894
+ }
895
+ return {
896
+ x: minX,
897
+ y: minY,
898
+ width: maxX - minX,
899
+ height: maxY - minY,
900
+ };
901
+ },
902
+ /**
903
+ * check intersection of two client rectangles
904
+ * @method
905
+ * @memberof Konva.Util
906
+ * @param {Object} r1 - { x, y, width, height } client rectangle
907
+ * @param {Object} r2 - { x, y, width, height } client rectangle
908
+ * @example
909
+ * const overlapping = Konva.Util.haveIntersection(shape1.getClientRect(), shape2.getClientRect());
910
+ */
654
911
  haveIntersection(r1, r2) {
655
912
  return !(r2.x > r1.x + r1.width ||
656
913
  r2.x + r2.width < r1.x ||
657
914
  r2.y > r1.y + r1.height ||
658
915
  r2.y + r2.height < r1.y);
659
916
  },
917
+ // a deep copy of plain objects and arrays; class instances and elements
918
+ // are shared, typed arrays are copied
660
919
  cloneObject(obj) {
661
- const retObj = {};
920
+ const copy = {};
662
921
  for (const key in obj) {
663
- if (this._isPlainObject(obj[key])) {
664
- retObj[key] = this.cloneObject(obj[key]);
665
- }
666
- else if (this._isArray(obj[key])) {
667
- retObj[key] = this.cloneArray(obj[key]);
668
- }
669
- else {
670
- retObj[key] = obj[key];
671
- }
922
+ copy[key] = Util._cloneValue(obj[key]);
672
923
  }
673
- return retObj;
924
+ return copy;
925
+ },
926
+ _cloneValue(val) {
927
+ if (Util._isArray(val)) {
928
+ // a flat array (points) is sliced, an array holding objects copied deep
929
+ return val.some((item) => typeof item === 'object')
930
+ ? val.map(Util._cloneValue)
931
+ : val.slice();
932
+ }
933
+ if (Util._isPlainObject(val)) {
934
+ return Util.cloneObject(val);
935
+ }
936
+ return val instanceof TypedArray ? val.slice() : val;
674
937
  },
675
938
  cloneArray(arr) {
676
939
  return arr.slice(0);
@@ -681,17 +944,10 @@ export const Util = {
681
944
  radToDeg(rad) {
682
945
  return rad * DEG180_OVER_PI;
683
946
  },
684
- _degToRad(deg) {
685
- Util.warn('Util._degToRad is removed. Please use public Util.degToRad instead.');
686
- return Util.degToRad(deg);
687
- },
688
- _radToDeg(rad) {
689
- Util.warn('Util._radToDeg is removed. Please use public Util.radToDeg instead.');
690
- return Util.radToDeg(rad);
691
- },
692
947
  _getRotation(radians) {
693
948
  return Konva.angleDeg ? Util.radToDeg(radians) : radians;
694
949
  },
950
+ // Memoized — called per-attr per setAttrs; input vocabulary is bounded.
695
951
  _capitalize(str) {
696
952
  const cached = capitalizeCache.get(str);
697
953
  if (cached !== undefined)
@@ -748,6 +1004,8 @@ export const Util = {
748
1004
  }
749
1005
  return [x, y, dist];
750
1006
  },
1007
+ // line as array of points.
1008
+ // line might be closed
751
1009
  _getProjectionToLine(pt, line, isClosed) {
752
1010
  const pc = Util.cloneObject(pt);
753
1011
  let dist = Number.MAX_VALUE;
@@ -793,35 +1051,26 @@ export const Util = {
793
1051
  });
794
1052
  return newStart;
795
1053
  },
796
- _prepareToStringify(obj) {
797
- let desc;
798
- obj.visitedByCircularReferenceRemoval = true;
799
- for (const key in obj) {
800
- if (!(obj.hasOwnProperty(key) && obj[key] && typeof obj[key] == 'object')) {
1054
+ // copies plain objects and arrays without DOM elements and circular
1055
+ // references, so the input (the live attrs of a node) is never modified.
1056
+ // Other objects (Date, class instances) are kept as they are
1057
+ _prepareToStringify(obj, ancestors = new Set()) {
1058
+ const copy = Util._isArray(obj) ? [] : {};
1059
+ ancestors.add(obj);
1060
+ for (const key of Object.keys(obj)) {
1061
+ const val = obj[key];
1062
+ if (Util._isElement(val) || ancestors.has(val)) {
801
1063
  continue;
802
1064
  }
803
- desc = Object.getOwnPropertyDescriptor(obj, key);
804
- if (obj[key].visitedByCircularReferenceRemoval ||
805
- Util._isElement(obj[key])) {
806
- if (desc.configurable) {
807
- delete obj[key];
808
- }
809
- else {
810
- return null;
811
- }
812
- }
813
- else if (Util._prepareToStringify(obj[key]) === null) {
814
- if (desc.configurable) {
815
- delete obj[key];
816
- }
817
- else {
818
- return null;
819
- }
820
- }
1065
+ copy[key] =
1066
+ Util._isPlainObject(val) || Util._isArray(val)
1067
+ ? Util._prepareToStringify(val, ancestors)
1068
+ : val;
821
1069
  }
822
- delete obj.visitedByCircularReferenceRemoval;
823
- return obj;
1070
+ ancestors.delete(obj);
1071
+ return copy;
824
1072
  },
1073
+ // very simplified version of Object.assign
825
1074
  _assign(target, source) {
826
1075
  for (const key in source) {
827
1076
  target[key] = source[key];
@@ -830,6 +1079,7 @@ export const Util = {
830
1079
  },
831
1080
  _getFirstPointerId(evt) {
832
1081
  if (!evt.touches) {
1082
+ // try to use pointer id or fake id
833
1083
  return evt.pointerId || 999;
834
1084
  }
835
1085
  else {
@@ -844,28 +1094,27 @@ export const Util = {
844
1094
  c.height = 0;
845
1095
  });
846
1096
  },
1097
+ // [topLeft, topRight, bottomRight, bottomLeft] radii that fit the box
1098
+ _cornerRadii(cornerRadius, width, height) {
1099
+ const max = Math.min(width, height) / 2;
1100
+ if (typeof cornerRadius === 'number') {
1101
+ const radius = clampRadius(cornerRadius, max);
1102
+ return [radius, radius, radius, radius];
1103
+ }
1104
+ return [
1105
+ clampRadius(cornerRadius[0], max),
1106
+ clampRadius(cornerRadius[1], max),
1107
+ clampRadius(cornerRadius[2], max),
1108
+ clampRadius(cornerRadius[3], max),
1109
+ ];
1110
+ },
847
1111
  drawRoundedRectPath(context, width, height, cornerRadius) {
1112
+ // if negative dimensions, abs width/height and move rectangle
848
1113
  let xOrigin = width < 0 ? width : 0;
849
1114
  let yOrigin = height < 0 ? height : 0;
850
1115
  width = Math.abs(width);
851
1116
  height = Math.abs(height);
852
- let topLeft = 0;
853
- let topRight = 0;
854
- let bottomLeft = 0;
855
- let bottomRight = 0;
856
- if (typeof cornerRadius === 'number') {
857
- topLeft =
858
- topRight =
859
- bottomLeft =
860
- bottomRight =
861
- Math.min(cornerRadius, width / 2, height / 2);
862
- }
863
- else {
864
- topLeft = Math.min(cornerRadius[0] || 0, width / 2, height / 2);
865
- topRight = Math.min(cornerRadius[1] || 0, width / 2, height / 2);
866
- bottomRight = Math.min(cornerRadius[2] || 0, width / 2, height / 2);
867
- bottomLeft = Math.min(cornerRadius[3] || 0, width / 2, height / 2);
868
- }
1117
+ const [topLeft, topRight, bottomRight, bottomLeft] = Util._cornerRadii(cornerRadius, width, height);
869
1118
  context.moveTo(xOrigin + topLeft, yOrigin);
870
1119
  context.lineTo(xOrigin + width - topRight, yOrigin);
871
1120
  context.arc(xOrigin + width - topRight, yOrigin + topRight, topRight, (Math.PI * 3) / 2, 0, false);
@@ -894,6 +1143,7 @@ export const Util = {
894
1143
  currCornerRadius = i < cornerRadius.length ? cornerRadius[i] : 0;
895
1144
  }
896
1145
  const maxCornerRadius = radius * Math.cos(Math.PI / sides);
1146
+ // cornerRadius creates perfect circle at 1/2 radius
897
1147
  currCornerRadius =
898
1148
  maxCornerRadius * Math.min(1, (currCornerRadius / radius) * 2);
899
1149
  const normalVec1 = { x: vec1.x / len1, y: vec1.y / len1 };