konva 10.10.0 → 10.11.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
@@ -1,5 +1,5 @@
1
1
  import { Factory } from './Factory.js';
2
- import { Node } from './Node.js';
2
+ import { Node, _parseSelector } from './Node.js';
3
3
  import { getNumberValidator } from './Validators.js';
4
4
  /**
5
5
  * Container constructor.  Containers are used to contain nodes or other containers
@@ -193,8 +193,9 @@ export class Container extends Node {
193
193
  }
194
194
  _generalFind(selector, findOne) {
195
195
  const retArr = [];
196
+ const match = _parseSelector(selector);
196
197
  this._descendants((node) => {
197
- const valid = node._isMatch(selector);
198
+ const valid = match(node);
198
199
  if (valid) {
199
200
  retArr.push(node);
200
201
  }
package/lib/Context.js CHANGED
@@ -664,26 +664,16 @@ export class SceneContext extends Context {
664
664
  }
665
665
  _getFillStyle(shape) {
666
666
  const color = shape.fill();
667
- const priority = shape.fillPriority();
668
- if (color && priority === 'color')
669
- return color;
670
- const pattern = shape.fillPatternImage();
671
- if (pattern && priority === 'pattern')
672
- return this._getFillPattern(shape);
673
- const linear = shape.fillLinearGradientColorStops();
674
- if (linear && priority === 'linear-gradient')
675
- return shape._getLinearGradient();
676
- const radial = shape.fillRadialGradientColorStops();
677
- if (radial && priority === 'radial-gradient')
678
- return shape._getRadialGradient();
679
- if (color)
680
- return color;
681
- if (pattern)
682
- return this._getFillPattern(shape);
683
- if (linear)
684
- return shape._getLinearGradient();
685
- if (radial)
686
- return shape._getRadialGradient();
667
+ switch (shape._getFillType(color)) {
668
+ case 'color':
669
+ return color;
670
+ case 'pattern':
671
+ return this._getFillPattern(shape);
672
+ case 'linear-gradient':
673
+ return shape._getLinearGradient();
674
+ case 'radial-gradient':
675
+ return shape._getRadialGradient();
676
+ }
687
677
  }
688
678
  _fill(shape) {
689
679
  const style = this._getFillStyle(shape);
package/lib/Global.js CHANGED
@@ -1,5 +1,5 @@
1
1
  /*
2
- * Konva JavaScript Framework v10.10.0
2
+ * Konva JavaScript Framework v10.11.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.10.0',
32
+ version: '10.11.0',
33
33
  isBrowser: detectBrowser(),
34
34
  isUnminified: /param/.test(function (param) { }.toString()),
35
35
  dblClickWindow: 400,
package/lib/Node.d.ts CHANGED
@@ -45,6 +45,8 @@ export type NodeConfig = {
45
45
  filters?: Filters;
46
46
  [string: string]: any;
47
47
  };
48
+ type SelectorMatch = (node: Node) => boolean;
49
+ export declare function _parseSelector(selector: string | Function): SelectorMatch;
48
50
  type NodeEventMap = GlobalEventHandlersEventMap & {
49
51
  [index: string]: any;
50
52
  };
@@ -598,7 +600,7 @@ export declare abstract class Node<Config extends NodeConfig = NodeConfig> {
598
600
  * var group = node.findAncestors('.mygroup');
599
601
  */
600
602
  findAncestor(selector: string | Function, includeSelf?: boolean, stopNode?: Container): Node<NodeConfig>;
601
- _isMatch(selector: string | Function): any;
603
+ _isMatch(selector: string | Function): boolean;
602
604
  /**
603
605
  * get layer ancestor
604
606
  * @method
package/lib/Node.js CHANGED
@@ -84,6 +84,56 @@ const ABSOLUTE_OPACITY = 'absoluteOpacity', ABSOLUTE_TRANSFORM = 'absoluteTransf
84
84
  'transformsEnabledChange.konva',
85
85
  ].join(SPACE);
86
86
  let idCounter = 1;
87
+ const WHITESPACE = /\s/;
88
+ const matchNothing = () => false;
89
+ // Turn a selector like "#id, .name, Rect" into a test for one node.
90
+ // find(), findAncestors() and delegated events test many nodes against the
91
+ // same selector, so they parse it once with this.
92
+ export function _parseSelector(selector) {
93
+ if (typeof selector === 'function') {
94
+ return selector;
95
+ }
96
+ if (!selector) {
97
+ return matchNothing;
98
+ }
99
+ const ids = [], names = [], types = [];
100
+ for (const sel of selector.replace(/ /g, '').split(',')) {
101
+ if (!Util.isValidSelector(sel)) {
102
+ Util.warn('Selector "' +
103
+ sel +
104
+ '" is invalid. Allowed selectors examples are "#foo", ".bar" or "Group".');
105
+ Util.warn('If you have a custom shape with such className, please change it to start with upper letter like "Triangle".');
106
+ Util.warn('Konva is awesome, right?');
107
+ }
108
+ if (sel.charAt(0) === '#') {
109
+ ids.push(sel.slice(1));
110
+ }
111
+ else if (sel.charAt(0) === '.') {
112
+ names.push(sel.slice(1));
113
+ }
114
+ else {
115
+ types.push(sel);
116
+ }
117
+ }
118
+ // runs for every visited node: the length guards and the plain loop
119
+ // (instead of names.some()) measured ~40% faster on find('#id') and find('Rect')
120
+ return (node) => {
121
+ if (ids.length && ids.indexOf(node.id()) !== -1) {
122
+ return true;
123
+ }
124
+ if (types.length &&
125
+ (types.indexOf(node.className) !== -1 ||
126
+ types.indexOf(node.nodeType) !== -1)) {
127
+ return true;
128
+ }
129
+ for (let i = 0; i < names.length; i++) {
130
+ if (node.hasName(names[i])) {
131
+ return true;
132
+ }
133
+ }
134
+ return false;
135
+ };
136
+ }
87
137
  /**
88
138
  * Node constructor. Nodes are entities that can be transformed, layered,
89
139
  * and have bound events. The stage, layers, groups, and shapes all extend Node.
@@ -698,9 +748,11 @@ export class Node {
698
748
  // like node.on
699
749
  _delegate(event, selector, handler) {
700
750
  const stopNode = this;
751
+ // parse once here, not on every event
752
+ const match = _parseSelector(selector);
701
753
  this.on(event, function (evt) {
702
754
  const original = evt;
703
- const targets = evt.target.findAncestors(selector, true, stopNode);
755
+ const targets = evt.target.findAncestors(match, true, stopNode);
704
756
  for (let i = 0; i < targets.length; i++) {
705
757
  evt = Util.cloneObject(evt);
706
758
  evt.currentTarget = targets[i];
@@ -1378,7 +1430,8 @@ export class Node {
1378
1430
  */
1379
1431
  findAncestors(selector, includeSelf, stopNode) {
1380
1432
  const res = [];
1381
- if (includeSelf && this._isMatch(selector)) {
1433
+ const match = _parseSelector(selector);
1434
+ if (includeSelf && match(this)) {
1382
1435
  res.push(this);
1383
1436
  }
1384
1437
  let ancestor = this.parent;
@@ -1386,7 +1439,7 @@ export class Node {
1386
1439
  if (ancestor === stopNode) {
1387
1440
  return res;
1388
1441
  }
1389
- if (ancestor._isMatch(selector)) {
1442
+ if (match(ancestor)) {
1390
1443
  res.push(ancestor);
1391
1444
  }
1392
1445
  ancestor = ancestor.parent;
@@ -1411,41 +1464,10 @@ export class Node {
1411
1464
  findAncestor(selector, includeSelf, stopNode) {
1412
1465
  return this.findAncestors(selector, includeSelf, stopNode)[0];
1413
1466
  }
1414
- // is current node match passed selector?
1467
+ // does this node match the selector? Konva itself uses _parseSelector to
1468
+ // parse once per call; this stays for code outside Konva that calls it
1415
1469
  _isMatch(selector) {
1416
- if (!selector) {
1417
- return false;
1418
- }
1419
- if (typeof selector === 'function') {
1420
- return selector(this);
1421
- }
1422
- let selectorArr = selector.replace(/ /g, '').split(','), len = selectorArr.length, n, sel;
1423
- for (n = 0; n < len; n++) {
1424
- sel = selectorArr[n];
1425
- if (!Util.isValidSelector(sel)) {
1426
- Util.warn('Selector "' +
1427
- sel +
1428
- '" is invalid. Allowed selectors examples are "#foo", ".bar" or "Group".');
1429
- Util.warn('If you have a custom shape with such className, please change it to start with upper letter like "Triangle".');
1430
- Util.warn('Konva is awesome, right?');
1431
- }
1432
- // id selector
1433
- if (sel.charAt(0) === '#') {
1434
- if (this.id() === sel.slice(1)) {
1435
- return true;
1436
- }
1437
- }
1438
- else if (sel.charAt(0) === '.') {
1439
- // name selector
1440
- if (this.hasName(sel.slice(1))) {
1441
- return true;
1442
- }
1443
- }
1444
- else if (this.className === sel || this.nodeType === sel) {
1445
- return true;
1446
- }
1447
- }
1448
- return false;
1470
+ return _parseSelector(selector)(this);
1449
1471
  }
1450
1472
  /**
1451
1473
  * get layer ancestor
@@ -1995,9 +2017,20 @@ export class Node {
1995
2017
  if (!fullName) {
1996
2018
  return false;
1997
2019
  }
1998
- // if name is '' the "names" will be [''], so I added extra check above
1999
- const names = (fullName || '').split(/\s/g);
2000
- return names.indexOf(name) !== -1;
2020
+ // find('.name') calls this for every node, so look for a whole
2021
+ // whitespace-separated word instead of splitting fullName into an array
2022
+ let i = fullName.indexOf(name);
2023
+ while (i !== -1) {
2024
+ const end = i + name.length;
2025
+ if ((i === 0 || WHITESPACE.test(fullName[i - 1])) &&
2026
+ (end === fullName.length || WHITESPACE.test(fullName[end]))) {
2027
+ // a word never contains whitespace; checked only on a hit so the
2028
+ // common miss in find('.name') stays cheap (~25% faster than up front)
2029
+ return !WHITESPACE.test(name);
2030
+ }
2031
+ i = fullName.indexOf(name, i + 1);
2032
+ }
2033
+ return false;
2001
2034
  }
2002
2035
  /**
2003
2036
  * remove name from node
package/lib/Shape.d.ts CHANGED
@@ -45,6 +45,9 @@ export type ShapeConfig = NodeConfig & {
45
45
  fillRadialGradientStartRadius?: number;
46
46
  fillRadialGradientEndRadius?: number;
47
47
  fillRadialGradientColorStops?: Array<number | string>;
48
+ fillRadialGradientScale?: Vector2d;
49
+ fillRadialGradientScaleX?: number;
50
+ fillRadialGradientScaleY?: number;
48
51
  fillEnabled?: boolean;
49
52
  fillPriority?: string;
50
53
  fillRule?: CanvasFillRule;
@@ -132,6 +135,7 @@ export declare class Shape<Config extends ShapeConfig = ShapeConfig> extends Nod
132
135
  */
133
136
  hasShadow(): any;
134
137
  _hasShadow(): boolean;
138
+ _getFillType(color?: string | CanvasGradient): "color" | "linear-gradient" | "pattern" | "radial-gradient" | undefined;
135
139
  _toStyleSpace(point: Vector2d): Vector2d;
136
140
  _getFillPattern(): any;
137
141
  _createFillPattern(): CanvasPattern | null | undefined;
@@ -139,7 +143,7 @@ export declare class Shape<Config extends ShapeConfig = ShapeConfig> extends Nod
139
143
  _getLinearGradient(): any;
140
144
  __getLinearGradient(): CanvasGradient | undefined;
141
145
  _getRadialGradient(): any;
142
- __getRadialGradient(): CanvasGradient | undefined;
146
+ __getRadialGradient(shrink?: number): CanvasGradient | undefined;
143
147
  getShadowRGBA(): any;
144
148
  _getShadowRGBA(): string | undefined;
145
149
  /**
@@ -235,6 +239,9 @@ export declare class Shape<Config extends ShapeConfig = ShapeConfig> extends Nod
235
239
  fillRadialGradientEndPoint: GetSet<Vector2d, this>;
236
240
  fillRadialGradientEndPointX: GetSet<number, this>;
237
241
  fillRadialGradientEndPointY: GetSet<number, this>;
242
+ fillRadialGradientScale: GetSet<Vector2d, this>;
243
+ fillRadialGradientScaleX: GetSet<number, this>;
244
+ fillRadialGradientScaleY: GetSet<number, this>;
238
245
  fillPatternOffset: GetSet<Vector2d, this>;
239
246
  fillPatternOffsetX: GetSet<number, this>;
240
247
  fillPatternOffsetY: GetSet<number, this>;
package/lib/Shape.js CHANGED
@@ -13,7 +13,7 @@ const patternImage = 'patternImage';
13
13
  const linearGradient = 'linearGradient';
14
14
  const radialGradient = 'radialGradient';
15
15
  export const shapes = {};
16
- function _fillFunc(context) {
16
+ function fillPath(context) {
17
17
  const fillRule = this.attrs.fillRule;
18
18
  if (fillRule) {
19
19
  context.fill(fillRule);
@@ -22,6 +22,46 @@ function _fillFunc(context) {
22
22
  context.fill();
23
23
  }
24
24
  }
25
+ // Below this scale the ellipse is under a millionth of its radius across, so
26
+ // only its last color stop shows.
27
+ const MIN_GRADIENT_SCALE = 1e-6;
28
+ // Fills the current path. A canvas maps the path when it is built and the
29
+ // fill style when it is painted, so a transform set here moves only the
30
+ // gradient: that is how fillRadialGradientScale makes an ellipse.
31
+ function _fillFunc(context) {
32
+ const scaleX = this.fillRadialGradientScaleX();
33
+ const scaleY = this.fillRadialGradientScaleY();
34
+ if ((scaleX === 1 && scaleY === 1) ||
35
+ this._getFillType() !== 'radial-gradient') {
36
+ fillPath.call(this, context);
37
+ return;
38
+ }
39
+ const min = Math.min(Math.abs(scaleX), Math.abs(scaleY));
40
+ context.save();
41
+ try {
42
+ if (min < MIN_GRADIENT_SCALE) {
43
+ const stops = this.fillRadialGradientColorStops();
44
+ context.setAttr('fillStyle', stops[stops.length - 1]);
45
+ }
46
+ else {
47
+ // The smaller scale of the transform is made 1 and the gradient shrinks
48
+ // by that factor instead. It is the same ellipse, but a pixel far from
49
+ // it stays close to it in gradient space: node-canvas on Linux (Cairo
50
+ // fixed point) paints nothing, or breaks the context, past ~32k there.
51
+ const sx = scaleX / min;
52
+ const sy = scaleY / min;
53
+ const { x, y } = this.fillRadialGradientEndPoint();
54
+ context.transform(sx, 0, 0, sy, x - sx * x, y - sy * y);
55
+ if (min !== 1) {
56
+ context.setAttr('fillStyle', this.__getRadialGradient(min));
57
+ }
58
+ }
59
+ fillPath.call(this, context);
60
+ }
61
+ finally {
62
+ context.restore();
63
+ }
64
+ }
25
65
  function _strokeFunc(context) {
26
66
  context.stroke();
27
67
  }
@@ -130,6 +170,29 @@ export class Shape extends Node {
130
170
  this.shadowOffsetX() ||
131
171
  this.shadowOffsetY()));
132
172
  }
173
+ // The fill the shape paints with, by fillPriority, then the first one set.
174
+ _getFillType(color = this.fill()) {
175
+ const priority = this.fillPriority();
176
+ if (color && priority === 'color')
177
+ return 'color';
178
+ const pattern = this.fillPatternImage();
179
+ if (pattern && priority === 'pattern')
180
+ return 'pattern';
181
+ const linear = this.fillLinearGradientColorStops();
182
+ if (linear && priority === 'linear-gradient')
183
+ return 'linear-gradient';
184
+ const radial = this.fillRadialGradientColorStops();
185
+ if (radial && priority === 'radial-gradient')
186
+ return 'radial-gradient';
187
+ if (color)
188
+ return 'color';
189
+ if (pattern)
190
+ return 'pattern';
191
+ if (linear)
192
+ return 'linear-gradient';
193
+ if (radial)
194
+ return 'radial-gradient';
195
+ }
133
196
  _toStyleSpace(point) {
134
197
  return this._styleTransform ? this._styleTransform.point(point) : point;
135
198
  }
@@ -180,14 +243,15 @@ export class Shape extends Node {
180
243
  return this.__getRadialGradient();
181
244
  return this._getCache(radialGradient, this.__getRadialGradient);
182
245
  }
183
- __getRadialGradient() {
246
+ // shrink scales the gradient about its end point (see _fillFunc)
247
+ __getRadialGradient(shrink = 1) {
184
248
  const colorStops = this.fillRadialGradientColorStops();
185
249
  if (colorStops) {
186
250
  const ctx = getDummyContext();
187
251
  // a rigid transform keeps the radii
188
252
  const start = this._toStyleSpace(this.fillRadialGradientStartPoint());
189
253
  const end = this._toStyleSpace(this.fillRadialGradientEndPoint());
190
- const grd = ctx.createRadialGradient(start.x, start.y, this.fillRadialGradientStartRadius(), end.x, end.y, this.fillRadialGradientEndRadius());
254
+ const grd = ctx.createRadialGradient(end.x + (start.x - end.x) * shrink, end.y + (start.y - end.y) * shrink, this.fillRadialGradientStartRadius() * shrink, end.x, end.y, this.fillRadialGradientEndRadius() * shrink);
191
255
  // build color stops
192
256
  for (let n = 0; n < colorStops.length; n += 2) {
193
257
  grd.addColorStop(colorStops[n], colorStops[n + 1]);
@@ -642,8 +706,7 @@ export class Shape extends Node {
642
706
  }
643
707
  Shape.prototype._fillFunc = _fillFunc;
644
708
  Shape.prototype._strokeFunc = _strokeFunc;
645
- // the hit graph is filled and stroked the same way as the scene
646
- Shape.prototype._fillFuncHit = _fillFunc;
709
+ Shape.prototype._fillFuncHit = fillPath;
647
710
  Shape.prototype._strokeFuncHit = _strokeFunc;
648
711
  Shape.prototype._centroid = false;
649
712
  Shape.prototype.nodeType = 'Shape';
@@ -1148,6 +1211,59 @@ Factory.addGetterSetter(Shape, 'fillRadialGradientColorStops');
1148
1211
  * // halfway through, and then changes to green
1149
1212
  * shape.fillRadialGradientColorStops(0, 'red', 0.5, 'blue', 1, 'green');
1150
1213
  */
1214
+ Factory.addComponentsGetterSetter(Shape, 'fillRadialGradientScale', ['x', 'y']);
1215
+ /**
1216
+ * get/set fill radial gradient scale. The whole gradient, both of its circles,
1217
+ * is scaled about the end point, so a scale that differs on the two axes makes
1218
+ * an elliptical gradient. A scale of 0 paints the last color stop. Applies to
1219
+ * the path a shape builds and fills with `context.fillShape()` or
1220
+ * `context.fillStrokeShape()`: built-in shapes and custom `sceneFunc` shapes.
1221
+ * Shapes with their own fill function ignore it, among them `Konva.Text` and
1222
+ * `Konva.TextPath`, which fill glyphs.
1223
+ * @name Konva.Shape#fillRadialGradientScale
1224
+ * @method
1225
+ * @param {Object} scale
1226
+ * @param {Number} scale.x
1227
+ * @param {Number} scale.y
1228
+ * @returns {Object}
1229
+ * @example
1230
+ * // get fill radial gradient scale
1231
+ * var gradientScale = shape.fillRadialGradientScale();
1232
+ *
1233
+ * // an ellipse half as tall as it is wide
1234
+ * shape.fillRadialGradientScale({
1235
+ * x: 1,
1236
+ * y: 0.5
1237
+ * });
1238
+ */
1239
+ Factory.addGetterSetter(Shape, 'fillRadialGradientScaleX', 1, getNumberValidator());
1240
+ /**
1241
+ * get/set fill radial gradient scale x
1242
+ * @name Konva.Shape#fillRadialGradientScaleX
1243
+ * @method
1244
+ * @param {Number} x
1245
+ * @returns {Number}
1246
+ * @example
1247
+ * // get fill radial gradient scale x
1248
+ * var gradientScaleX = shape.fillRadialGradientScaleX();
1249
+ *
1250
+ * // set fill radial gradient scale x
1251
+ * shape.fillRadialGradientScaleX(2);
1252
+ */
1253
+ Factory.addGetterSetter(Shape, 'fillRadialGradientScaleY', 1, getNumberValidator());
1254
+ /**
1255
+ * get/set fill radial gradient scale y
1256
+ * @name Konva.Shape#fillRadialGradientScaleY
1257
+ * @method
1258
+ * @param {Number} y
1259
+ * @returns {Number}
1260
+ * @example
1261
+ * // get fill radial gradient scale y
1262
+ * var gradientScaleY = shape.fillRadialGradientScaleY();
1263
+ *
1264
+ * // set fill radial gradient scale y
1265
+ * shape.fillRadialGradientScaleY(0.5);
1266
+ */
1151
1267
  Factory.addGetterSetter(Shape, 'fillPatternRepeat', 'repeat');
1152
1268
  /**
1153
1269
  * get/set fill pattern repeat. Can be 'repeat', 'repeat-x', 'repeat-y', or 'no-repeat'. The default is 'repeat'
package/lib/Util.js CHANGED
@@ -535,7 +535,7 @@ export const Util = {
535
535
  return val instanceof Object;
536
536
  },
537
537
  isValidSelector(selector) {
538
- if (typeof selector !== 'string') {
538
+ if (typeof selector !== 'string' || !selector) {
539
539
  return false;
540
540
  }
541
541
  const firstChar = selector[0];
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "konva",
3
- "version": "10.10.0",
3
+ "version": "10.11.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",