konva 10.3.3 → 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 +1 -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 +12 -16
@@ -4,31 +4,28 @@ import { Shape } from "../Shape.js";
4
4
  import { Konva } from "../Global.js";
5
5
  import { getNumberValidator, getStringValidator, getNumberOrAutoValidator, getBooleanValidator, } from "../Validators.js";
6
6
  import { _registerNode } from "../Global.js";
7
+ // grapheme segmentation: one entry per user-perceived character, so flags,
8
+ // ZWJ emoji sequences and combining marks stay together
9
+ const segmenter = typeof Intl !== 'undefined' && Intl.Segmenter
10
+ ? new Intl.Segmenter(undefined, { granularity: 'grapheme' })
11
+ : null;
12
+ // canvas has no API for the underline thickness of a font. This is close to
13
+ // what browsers draw for the common fonts
14
+ export function getDecorationLineWidth(fontSize) {
15
+ return fontSize / 15;
16
+ }
7
17
  export function stringToArray(string) {
8
- return [...string].reduce((acc, char, index, array) => {
9
- if (/\p{Emoji}/u.test(char)) {
10
- const nextChar = array[index + 1];
11
- if (nextChar && /\p{Emoji_Modifier}|\u200D/u.test(nextChar)) {
12
- acc.push(char + nextChar);
13
- array[index + 1] = '';
14
- }
15
- else {
16
- acc.push(char);
17
- }
18
- }
19
- else if (/\p{Regional_Indicator}{2}/u.test(char + (array[index + 1] || ''))) {
20
- acc.push(char + array[index + 1]);
21
- }
22
- else if (index > 0 && /\p{Mn}|\p{Me}|\p{Mc}/u.test(char)) {
23
- acc[acc.length - 1] += char;
24
- }
25
- else if (char) {
26
- acc.push(char);
27
- }
28
- return acc;
29
- }, []);
18
+ if (!segmenter) {
19
+ // no Intl.Segmenter (Firefox < 125): flags, then a code point with its
20
+ // combining marks, skin tone modifiers, variation selectors and ZWJ joins
21
+ return (string.match(/\p{RI}\p{RI}|\P{M}(?:\p{M}|\p{Emoji_Modifier}|\uFE0F|\u200D\P{M})*|\p{M}+/gu) || []);
22
+ }
23
+ return Array.from(segmenter.segment(string), (s) => s.segment);
30
24
  }
31
- const AUTO = 'auto', CENTER = 'center', INHERIT = 'inherit', JUSTIFY = 'justify', CHANGE_KONVA = 'Change.konva', CONTEXT_2D = '2d', DASH = '-', LEFT = 'left', TEXT = 'text', TEXT_UPPER = 'Text', TOP = 'top', BOTTOM = 'bottom', MIDDLE = 'middle', NORMAL = 'normal', PX_SPACE = 'px ', SPACE = ' ', RIGHT = 'right', RTL = 'rtl', WORD = 'word', CHAR = 'char', NONE = 'none', ELLIPSIS = '…', ATTR_CHANGE_LIST = [
25
+ // constants
26
+ const AUTO = 'auto',
27
+ //CANVAS = 'canvas',
28
+ CENTER = 'center', INHERIT = 'inherit', JUSTIFY = 'justify', CHANGE_KONVA = 'Change.konva', CONTEXT_2D = '2d', DASH = '-', LEFT = 'left', TEXT = 'text', TEXT_UPPER = 'Text', TOP = 'top', BOTTOM = 'bottom', MIDDLE = 'middle', NORMAL = 'normal', PX_SPACE = 'px ', SPACE = ' ', RIGHT = 'right', RTL = 'rtl', WORD = 'word', CHAR = 'char', NONE = 'none', ELLIPSIS = '…', ATTR_CHANGE_LIST = [
32
29
  'direction',
33
30
  'fontFamily',
34
31
  'fontSize',
@@ -44,15 +41,20 @@ const AUTO = 'auto', CENTER = 'center', INHERIT = 'inherit', JUSTIFY = 'justify'
44
41
  'wrap',
45
42
  'ellipsis',
46
43
  'letterSpacing',
47
- ], attrChangeListLen = ATTR_CHANGE_LIST.length;
44
+ ];
45
+ // Safari on macOS renders text shadow even when globalAlpha is 0.
46
+ // This feature check detects that bug so we can work around it with a buffer canvas.
47
+ // Not covered by automated tests (our CI doesn't run Safari).
48
+ // Once Safari fixes the issue this check can be removed.
48
49
  let _shadowOpacityBuggy = null;
49
50
  function hasShadowOpacityBug() {
50
51
  if (_shadowOpacityBuggy !== null) {
51
52
  return _shadowOpacityBuggy;
52
53
  }
53
54
  _shadowOpacityBuggy = false;
55
+ let c;
54
56
  try {
55
- const c = document.createElement('canvas');
57
+ c = Util.createCanvasElement();
56
58
  c.width = 10;
57
59
  c.height = 10;
58
60
  const ctx = c.getContext(CONTEXT_2D);
@@ -75,6 +77,12 @@ function hasShadowOpacityBug() {
75
77
  }
76
78
  }
77
79
  catch (e) {
80
+ // no-op (SSR or restricted canvas)
81
+ }
82
+ finally {
83
+ if (c) {
84
+ Util.releaseCanvas(c);
85
+ }
78
86
  }
79
87
  return _shadowOpacityBuggy;
80
88
  }
@@ -93,7 +101,7 @@ function normalizeFontFamily(fontFamily) {
93
101
  .join(', ');
94
102
  }
95
103
  let dummyContext;
96
- function getDummyContext() {
104
+ export function getDummyContext() {
97
105
  if (dummyContext) {
98
106
  return dummyContext;
99
107
  }
@@ -101,6 +109,7 @@ function getDummyContext() {
101
109
  return dummyContext;
102
110
  }
103
111
  function _fillFunc(context) {
112
+ // re-apply a per-character style set by charRenderFunc (see _sceneFunc)
104
113
  if (this._partialFillStyle) {
105
114
  context.setAttr('fillStyle', this._partialFillStyle);
106
115
  }
@@ -115,6 +124,7 @@ function _strokeFunc(context) {
115
124
  }
116
125
  function checkDefaultFill(config) {
117
126
  config = config || {};
127
+ // set default color to black
118
128
  if (!config.fillLinearGradientColorStops &&
119
129
  !config.fillRadialGradientColorStops &&
120
130
  !config.fillPatternImage) {
@@ -122,14 +132,43 @@ function checkDefaultFill(config) {
122
132
  }
123
133
  return config;
124
134
  }
135
+ /**
136
+ * Text constructor
137
+ * @constructor
138
+ * @memberof Konva
139
+ * @augments Konva.Shape
140
+ * @param {Object} config
141
+ * @param {String} [config.direction] default is inherit
142
+ * @param {String} [config.fontFamily] default is Arial
143
+ * @param {Number} [config.fontSize] in pixels. Default is 12
144
+ * @param {String} [config.fontStyle] can be 'normal', 'italic', or 'bold', '500' or even 'italic bold'. 'normal' is the default.
145
+ * @param {String} [config.fontVariant] can be normal or small-caps. Default is normal
146
+ * @param {String} [config.textDecoration] can be line-through, underline or empty string. Default is empty string.
147
+ * @param {Number} [config.underlineOffset] offset for underline line. Default is calculated based on font size.
148
+ * @param {String} config.text
149
+ * @param {String} [config.align] can be left, center, right or justify
150
+ * @param {String} [config.verticalAlign] can be top, middle or bottom
151
+ * @param {Number} [config.padding]
152
+ * @param {Number} [config.lineHeight] default is 1
153
+ * @param {String} [config.wrap] can be "word", "char", or "none". Default is word
154
+ * @param {Boolean} [config.ellipsis] can be true or false. Default is false. If true, text that does not fit is cut and ends with "…". That needs a fixed height or wrap="none"
155
+ * @@shapeParams
156
+ * @@nodeParams
157
+ * @example
158
+ * var text = new Konva.Text({
159
+ * x: 10,
160
+ * y: 15,
161
+ * text: 'Simple Text',
162
+ * fontSize: 30,
163
+ * fontFamily: 'Calibri',
164
+ * fill: 'green'
165
+ * });
166
+ */
125
167
  export class Text extends Shape {
126
168
  constructor(config) {
127
169
  super(checkDefaultFill(config));
128
170
  this._partialTextX = 0;
129
171
  this._partialTextY = 0;
130
- for (let n = 0; n < attrChangeListLen; n++) {
131
- this.on(ATTR_CHANGE_LIST[n] + CHANGE_KONVA, this._setTextData);
132
- }
133
172
  this._setTextData();
134
173
  }
135
174
  _sceneFunc(context) {
@@ -143,7 +182,7 @@ export class Text extends Shape {
143
182
  let translateY = lineHeightPx / 2;
144
183
  let baseline = MIDDLE;
145
184
  if (!Konva.legacyTextRendering) {
146
- const metrics = this.measureSize('M');
185
+ const metrics = this.measureSize('M'); // Use a sample character to get the ascent
147
186
  baseline = 'alphabetic';
148
187
  const ascent = (_a = metrics.fontBoundingBoxAscent) !== null && _a !== void 0 ? _a : metrics.actualBoundingBoxAscent;
149
188
  const descent = (_b = metrics.fontBoundingBoxDescent) !== null && _b !== void 0 ? _b : metrics.actualBoundingBoxDescent;
@@ -155,6 +194,7 @@ export class Text extends Shape {
155
194
  context.setAttr('font', this._getContextFont());
156
195
  context.setAttr('textBaseline', baseline);
157
196
  context.setAttr('textAlign', LEFT);
197
+ // handle vertical alignment
158
198
  if (verticalAlign === MIDDLE) {
159
199
  alignY = (this.getHeight() - textArrLen * lineHeightPx - padding * 2) / 2;
160
200
  }
@@ -162,12 +202,19 @@ export class Text extends Shape {
162
202
  alignY = this.getHeight() - textArrLen * lineHeightPx - padding * 2;
163
203
  }
164
204
  context.translate(padding, alignY + padding);
205
+ // context styles entering the loop, used to detect styles set by
206
+ // charRenderFunc; every character is drawn inside save()/restore(),
207
+ // so the entry state is the same for each one
165
208
  const fillStyleBefore = charRenderFunc ? context.fillStyle : undefined;
166
209
  const strokeStyleBefore = charRenderFunc ? context.strokeStyle : undefined;
210
+ // global grapheme index passed to charRenderFunc, runs across lines
211
+ let charIndex = 0;
212
+ // draw text lines
167
213
  for (n = 0; n < textArrLen; n++) {
168
214
  let lineTranslateX = 0;
169
215
  let lineTranslateY = 0;
170
216
  const obj = textArr[n], text = obj.text, width = obj.width, lastLine = obj.lastInParagraph;
217
+ // horizontal alignment
171
218
  context.save();
172
219
  if (align === RIGHT) {
173
220
  lineTranslateX += totalWidth - width - padding * 2;
@@ -186,30 +233,39 @@ export class Text extends Shape {
186
233
  context.moveTo(x, y);
187
234
  const lineWidth = align === JUSTIFY && !lastLine ? totalWidth - padding * 2 : width;
188
235
  context.lineTo(x + Math.round(lineWidth), y);
189
- context.lineWidth = fontSize / 15;
236
+ context.lineWidth = getDecorationLineWidth(fontSize);
190
237
  const gradient = this._getLinearGradient();
191
238
  context.strokeStyle = gradient || fill;
192
239
  context.stroke();
193
240
  context.restore();
194
241
  }
242
+ // store the starting x position for line-through which is drawn after text
195
243
  const lineThroughStartX = lineTranslateX;
244
+ // As `letterSpacing` isn't supported on Safari, we use this polyfill.
245
+ // The exception is for RTL text, which we rely on native as it cannot
246
+ // be supported otherwise.
196
247
  if (direction !== RTL &&
197
248
  (letterSpacing !== 0 || align === JUSTIFY || charRenderFunc)) {
249
+ // var words = text.split(' ');
198
250
  const spacesNumber = text.split(' ').length - 1;
199
251
  const array = stringToArray(text);
200
252
  for (let li = 0; li < array.length; li++) {
201
253
  const letter = array[li];
254
+ // skip justify for the last line
202
255
  if (letter === ' ' && !lastLine && align === JUSTIFY) {
203
256
  lineTranslateX += (totalWidth - padding * 2 - width) / spacesNumber;
257
+ // context.translate(
258
+ // Math.floor((totalWidth - padding * 2 - width) / spacesNumber),
259
+ // 0
260
+ // );
204
261
  }
205
262
  this._partialTextX = lineTranslateX;
206
263
  this._partialTextY = translateY + lineTranslateY;
207
264
  this._partialText = letter;
265
+ // the font of the shape is already set on the context
266
+ const letterWidth = context.measureText(letter).width;
208
267
  if (charRenderFunc) {
209
268
  context.save();
210
- const previousLines = textArr.slice(0, n);
211
- const previousGraphemes = previousLines.reduce((acc, line) => acc + stringToArray(line.text).length, 0);
212
- const charIndex = li + previousGraphemes;
213
269
  charRenderFunc({
214
270
  char: letter,
215
271
  index: charIndex,
@@ -217,10 +273,13 @@ export class Text extends Shape {
217
273
  y: translateY + lineTranslateY,
218
274
  lineIndex: n,
219
275
  column: li,
220
- isLastInLine: lastLine,
221
- width: this.measureSize(letter).width,
276
+ isLastInLine: li === array.length - 1,
277
+ width: letterWidth,
222
278
  context,
223
279
  });
280
+ // a style the callback set on the context wins for this character;
281
+ // fillStrokeShape() overwrites the context styles from the shape
282
+ // attributes, so stash them for _fillFunc/_strokeFunc to re-apply
224
283
  const fillStyleAfter = context.fillStyle;
225
284
  if (fillStyleAfter !== fillStyleBefore) {
226
285
  this._partialFillStyle = fillStyleAfter;
@@ -236,7 +295,8 @@ export class Text extends Shape {
236
295
  this._partialStrokeStyle = undefined;
237
296
  context.restore();
238
297
  }
239
- lineTranslateX += this.measureSize(letter).width + letterSpacing;
298
+ lineTranslateX += letterWidth + letterSpacing;
299
+ charIndex++;
240
300
  }
241
301
  }
242
302
  else {
@@ -248,6 +308,7 @@ export class Text extends Shape {
248
308
  this._partialText = text;
249
309
  context.fillStrokeShape(this);
250
310
  }
311
+ // draw line-through above the text content
251
312
  if (shouldLineThrough) {
252
313
  context.save();
253
314
  context.beginPath();
@@ -258,7 +319,7 @@ export class Text extends Shape {
258
319
  context.moveTo(x, translateY + lineTranslateY + yOffset);
259
320
  const lineWidth = align === JUSTIFY && !lastLine ? totalWidth - padding * 2 : width;
260
321
  context.lineTo(x + Math.round(lineWidth), translateY + lineTranslateY + yOffset);
261
- context.lineWidth = fontSize / 15;
322
+ context.lineWidth = getDecorationLineWidth(fontSize);
262
323
  const gradient = this._getLinearGradient();
263
324
  context.strokeStyle = gradient || fill;
264
325
  context.stroke();
@@ -297,6 +358,12 @@ export class Text extends Shape {
297
358
  this.padding() * 2
298
359
  : this.attrs.height;
299
360
  }
361
+ /**
362
+ * get pure text width without padding
363
+ * @method
364
+ * @name Konva.Text#getTextWidth
365
+ * @returns {Number}
366
+ */
300
367
  getTextWidth() {
301
368
  return this.textWidth;
302
369
  }
@@ -304,6 +371,14 @@ export class Text extends Shape {
304
371
  Util.warn('text.getTextHeight() method is deprecated. Use text.height() - for full height and text.fontSize() - for one line height.');
305
372
  return this.textHeight;
306
373
  }
374
+ /**
375
+ * measure string with the font of current text shape.
376
+ * That method can't handle multiline text.
377
+ * @method
378
+ * @name Konva.Text#measureSize
379
+ * @param {String} text text to measure
380
+ * @returns {Object} { width , height } of measured text
381
+ */
307
382
  measureSize(text) {
308
383
  var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l;
309
384
  let _context = getDummyContext(), fontSize = this.fontSize(), metrics;
@@ -311,13 +386,15 @@ export class Text extends Shape {
311
386
  _context.font = this._getContextFont();
312
387
  metrics = _context.measureText(text);
313
388
  _context.restore();
389
+ // Scale the fallback values based on the provided fontSize compared to the sample size (100 in your new case)
314
390
  const scaleFactor = fontSize / 100;
391
+ // Note, fallback values are from chrome browser with 100px font size and font-family "Arial"
315
392
  return {
316
393
  actualBoundingBoxAscent: (_a = metrics.actualBoundingBoxAscent) !== null && _a !== void 0 ? _a : 71.58203125 * scaleFactor,
317
- actualBoundingBoxDescent: (_b = metrics.actualBoundingBoxDescent) !== null && _b !== void 0 ? _b : 0,
394
+ actualBoundingBoxDescent: (_b = metrics.actualBoundingBoxDescent) !== null && _b !== void 0 ? _b : 0, // Remains zero as there is no descent in the provided metrics
318
395
  actualBoundingBoxLeft: (_c = metrics.actualBoundingBoxLeft) !== null && _c !== void 0 ? _c : -7.421875 * scaleFactor,
319
396
  actualBoundingBoxRight: (_d = metrics.actualBoundingBoxRight) !== null && _d !== void 0 ? _d : 75.732421875 * scaleFactor,
320
- alphabeticBaseline: (_e = metrics.alphabeticBaseline) !== null && _e !== void 0 ? _e : 0,
397
+ alphabeticBaseline: (_e = metrics.alphabeticBaseline) !== null && _e !== void 0 ? _e : 0, // Remains zero as it's typically relative to the baseline itself
321
398
  emHeightAscent: (_f = metrics.emHeightAscent) !== null && _f !== void 0 ? _f : 100 * scaleFactor,
322
399
  emHeightDescent: (_g = metrics.emHeightDescent) !== null && _g !== void 0 ? _g : -20 * scaleFactor,
323
400
  fontBoundingBoxAscent: (_h = metrics.fontBoundingBoxAscent) !== null && _h !== void 0 ? _h : 91 * scaleFactor,
@@ -325,7 +402,7 @@ export class Text extends Shape {
325
402
  hangingBaseline: (_k = metrics.hangingBaseline) !== null && _k !== void 0 ? _k : 72.80000305175781 * scaleFactor,
326
403
  ideographicBaseline: (_l = metrics.ideographicBaseline) !== null && _l !== void 0 ? _l : -21 * scaleFactor,
327
404
  width: metrics.width,
328
- height: fontSize,
405
+ height: fontSize, // Typically set to the font size
329
406
  };
330
407
  }
331
408
  _getContextFont() {
@@ -334,6 +411,7 @@ export class Text extends Shape {
334
411
  this.fontVariant() +
335
412
  SPACE +
336
413
  (this.fontSize() + PX_SPACE) +
414
+ // wrap font family into " so font families with spaces works ok
337
415
  normalizeFontFamily(this.fontFamily()));
338
416
  }
339
417
  _addTextLine(line) {
@@ -348,13 +426,18 @@ export class Text extends Shape {
348
426
  lastInParagraph: false,
349
427
  });
350
428
  }
351
- _getTextWidth(text) {
429
+ _getTextWidth(text, graphemes) {
352
430
  const letterSpacing = this.letterSpacing();
353
- const length = text.length;
354
- return getDummyContext().measureText(text).width + letterSpacing * length;
431
+ // one spacing per grapheme, as the per-character rendering draws them
432
+ const spacing = letterSpacing
433
+ ? letterSpacing * (graphemes !== null && graphemes !== void 0 ? graphemes : stringToArray(text).length)
434
+ : 0;
435
+ return getDummyContext().measureText(text).width + spacing;
355
436
  }
356
437
  _setTextData() {
357
- let lines = this.text().split('\n'), fontSize = +this.fontSize(), textWidth = 0, lineHeightPx = this.lineHeight() * fontSize, width = this.attrs.width, height = this.attrs.height, fixedWidth = width !== AUTO && width !== undefined, fixedHeight = height !== AUTO && height !== undefined, padding = this.padding(), maxWidth = width - padding * 2, maxHeightPx = height - padding * 2, currentHeightPx = 0, wrap = this.wrap(), shouldWrap = wrap !== NONE, wrapAtWord = wrap !== CHAR && shouldWrap, shouldAddEllipsis = this.ellipsis();
438
+ let lines = this.text().split('\n'), fontSize = +this.fontSize(), textWidth = 0, lineHeightPx = this.lineHeight() * fontSize, width = this.attrs.width, height = this.attrs.height, fixedWidth = width !== AUTO && width !== undefined, fixedHeight = height !== AUTO && height !== undefined, padding = this.padding(), maxWidth = width - padding * 2, maxHeightPx = height - padding * 2, currentHeightPx = 0, wrap = this.wrap(),
439
+ // align = this.align(),
440
+ shouldWrap = wrap !== NONE, wrapAtWord = wrap !== CHAR && shouldWrap, shouldAddEllipsis = this.ellipsis();
358
441
  this.textArr = [];
359
442
  getDummyContext().font = this._getContextFont();
360
443
  const additionalWidth = shouldAddEllipsis
@@ -364,72 +447,101 @@ export class Text extends Shape {
364
447
  let line = lines[i];
365
448
  let lineWidth = this._getTextWidth(line);
366
449
  if (fixedWidth && lineWidth > maxWidth) {
367
- while (line.length > 0) {
368
- const lineArray = stringToArray(line);
369
- let low = 0, high = lineArray.length, match = '', matchWidth = 0;
370
- while (low < high) {
371
- const mid = (low + high) >>> 1, substr = lineArray.slice(0, mid + 1).join(''), substrWidth = this._getTextWidth(substr);
372
- const shouldConsiderEllipsis = shouldAddEllipsis &&
373
- fixedHeight &&
374
- currentHeightPx + lineHeightPx > maxHeightPx;
375
- const effectiveWidth = shouldConsiderEllipsis
376
- ? substrWidth + additionalWidth
377
- : substrWidth;
378
- if (effectiveWidth <= maxWidth) {
379
- low = mid + 1;
380
- match = substr;
381
- matchWidth = substrWidth;
450
+ /*
451
+ * if width is fixed and line does not fit entirely
452
+ * break the line into multiple fitting lines
453
+ */
454
+ const graphemes = stringToArray(line);
455
+ const length = graphemes.length;
456
+ let start = 0;
457
+ const text = (end) => graphemes.slice(start, end).join('');
458
+ const isBreak = (char) => char === SPACE || char === DASH;
459
+ // graphemes per line, estimated from the average grapheme width
460
+ const perLine = Math.max(1, Math.ceil((length * maxWidth) / lineWidth));
461
+ while (start < length) {
462
+ // only reserve the ellipsis width on a line that may be the last
463
+ // visible one
464
+ const extraWidth = shouldAddEllipsis &&
465
+ fixedHeight &&
466
+ currentHeightPx + lineHeightPx > maxHeightPx
467
+ ? additionalWidth
468
+ : 0;
469
+ // width of the longest fitting prefix found so far
470
+ let matchWidth = 0;
471
+ const fits = (end) => {
472
+ const width = this._getTextWidth(text(end), end - start);
473
+ if (width + extraWidth > maxWidth) {
474
+ return false;
475
+ }
476
+ matchWidth = width;
477
+ return true;
478
+ };
479
+ /*
480
+ * find the longest prefix that fits in the specified width:
481
+ * grow a window from the estimate until it stops fitting, then
482
+ * binary search inside it. Every probe measures about one line,
483
+ * not the whole remaining text, so wrapping stays linear
484
+ */
485
+ let low = start, high = Math.min(length, start + perLine);
486
+ while (fits(high)) {
487
+ low = high;
488
+ if (high === length) {
489
+ break;
490
+ }
491
+ high = Math.min(length, high + (high - start));
492
+ }
493
+ while (high - low > 1) {
494
+ const mid = (low + high) >>> 1;
495
+ if (fits(mid)) {
496
+ low = mid;
382
497
  }
383
498
  else {
384
499
  high = mid;
385
500
  }
386
501
  }
387
- if (match) {
388
- if (wrapAtWord) {
389
- const matchArray = stringToArray(match);
390
- const nextChar = lineArray[matchArray.length];
391
- const nextIsSpaceOrDash = nextChar === SPACE || nextChar === DASH;
392
- let wrapIndex;
393
- if (nextIsSpaceOrDash && matchWidth <= maxWidth) {
394
- wrapIndex = matchArray.length;
395
- }
396
- else {
397
- const lastSpaceIndex = matchArray.lastIndexOf(SPACE);
398
- const lastDashIndex = matchArray.lastIndexOf(DASH);
399
- wrapIndex = Math.max(lastSpaceIndex, lastDashIndex) + 1;
400
- }
401
- if (wrapIndex > 0) {
402
- low = wrapIndex;
403
- match = lineArray.slice(0, low).join('');
404
- matchWidth = this._getTextWidth(match);
405
- }
406
- }
407
- match = match.trimRight();
408
- this._addTextLine(match);
409
- textWidth = Math.max(textWidth, matchWidth);
502
+ if (low === start) {
503
+ // not even one character could fit in the element, abort
504
+ break;
505
+ }
506
+ if (low === length) {
507
+ // the rest of the paragraph fits on one line: kept untrimmed and
508
+ // without the ellipsis check, like a paragraph that never wrapped
509
+ this._addTextLine(text(length));
410
510
  currentHeightPx += lineHeightPx;
411
- const shouldHandleEllipsis = this._shouldHandleEllipsis(currentHeightPx);
412
- if (shouldHandleEllipsis) {
413
- this._tryToAddEllipsisToLastLine();
414
- break;
511
+ textWidth = Math.max(textWidth, matchWidth);
512
+ break;
513
+ }
514
+ if (wrapAtWord && !isBreak(graphemes[low])) {
515
+ // wrap at the last space or dash of the line instead
516
+ let wrapIndex = low - 1;
517
+ while (wrapIndex >= start && !isBreak(graphemes[wrapIndex])) {
518
+ wrapIndex--;
415
519
  }
416
- line = lineArray.slice(low).join('').trimLeft();
417
- if (line.length > 0) {
418
- lineWidth = this._getTextWidth(line);
419
- if (lineWidth <= maxWidth) {
420
- this._addTextLine(line);
421
- currentHeightPx += lineHeightPx;
422
- textWidth = Math.max(textWidth, lineWidth);
423
- break;
424
- }
520
+ if (wrapIndex >= start) {
521
+ low = wrapIndex + 1;
522
+ matchWidth = this._getTextWidth(text(low), low - start);
425
523
  }
426
524
  }
427
- else {
525
+ this._addTextLine(text(low).trimRight());
526
+ textWidth = Math.max(textWidth, matchWidth);
527
+ currentHeightPx += lineHeightPx;
528
+ if (this._shouldHandleEllipsis(currentHeightPx)) {
529
+ this._tryToAddEllipsisToLastLine();
530
+ /*
531
+ * stop wrapping if wrapping is disabled or if adding
532
+ * one more line would overflow the fixed height
533
+ */
428
534
  break;
429
535
  }
536
+ // the next line starts after the whitespace of the break
537
+ start = low;
538
+ while (start < length && !graphemes[start].trim()) {
539
+ start++;
540
+ }
430
541
  }
431
542
  }
432
543
  else {
544
+ // element width is automatically adjusted to max line width
433
545
  this._addTextLine(line);
434
546
  currentHeightPx += lineHeightPx;
435
547
  textWidth = Math.max(textWidth, lineWidth);
@@ -437,6 +549,7 @@ export class Text extends Shape {
437
549
  this._tryToAddEllipsisToLastLine();
438
550
  }
439
551
  }
552
+ // if element height is fixed, abort if adding one more line would overflow
440
553
  if (this.textArr[this.textArr.length - 1]) {
441
554
  this.textArr[this.textArr.length - 1].lastInParagraph = true;
442
555
  }
@@ -445,8 +558,19 @@ export class Text extends Shape {
445
558
  }
446
559
  }
447
560
  this.textHeight = fontSize;
561
+ // var maxTextWidth = 0;
562
+ // for(var j = 0; j < this.textArr.length; j++) {
563
+ // maxTextWidth = Math.max(maxTextWidth, this.textArr[j].width);
564
+ // }
448
565
  this.textWidth = textWidth;
449
566
  }
567
+ /**
568
+ * whether to handle ellipsis, there are two cases:
569
+ * 1. the current line is the last line
570
+ * 2. wrap is NONE
571
+ * @param {Number} currentHeightPx
572
+ * @returns {Boolean}
573
+ */
450
574
  _shouldHandleEllipsis(currentHeightPx) {
451
575
  const fontSize = +this.fontSize(), lineHeightPx = this.lineHeight() * fontSize, height = this.attrs.height, fixedHeight = height !== AUTO && height !== undefined, padding = this.padding(), maxHeightPx = height - padding * 2, wrap = this.wrap(), shouldWrap = wrap !== NONE;
452
576
  return (!shouldWrap ||
@@ -467,6 +591,8 @@ export class Text extends Shape {
467
591
  this.textArr.splice(this.textArr.length - 1, 1);
468
592
  this._addTextLine(lastLine.text + ELLIPSIS);
469
593
  }
594
+ // for text we can't disable stroke scaling
595
+ // if we do, the result will be unexpected
470
596
  getStrokeScaleEnabled() {
471
597
  return true;
472
598
  }
@@ -495,21 +621,279 @@ Text.prototype._attrsAffectingSize = [
495
621
  'letterSpacing',
496
622
  ];
497
623
  _registerNode(Text);
624
+ // update text data for certain attr changes
625
+ Text.prototype.on(ATTR_CHANGE_LIST.map((attr) => attr + CHANGE_KONVA).join(' '), function () {
626
+ this._setTextData();
627
+ });
628
+ /**
629
+ * get/set width of text area, which includes padding.
630
+ * @name Konva.Text#width
631
+ * @method
632
+ * @param {Number} width
633
+ * @returns {Number}
634
+ * @example
635
+ * // get width
636
+ * var width = text.width();
637
+ *
638
+ * // set width
639
+ * text.width(20);
640
+ *
641
+ * // set to auto
642
+ * text.width('auto');
643
+ * text.width() // will return calculated width, and not "auto"
644
+ */
498
645
  Factory.overWriteSetter(Text, 'width', getNumberOrAutoValidator());
646
+ /**
647
+ * get/set the height of the text area, which takes into account multi-line text, line heights, and padding.
648
+ * @name Konva.Text#height
649
+ * @method
650
+ * @param {Number} height
651
+ * @returns {Number}
652
+ * @example
653
+ * // get height
654
+ * var height = text.height();
655
+ *
656
+ * // set height
657
+ * text.height(20);
658
+ *
659
+ * // set to auto
660
+ * text.height('auto');
661
+ * text.height() // will return calculated height, and not "auto"
662
+ */
499
663
  Factory.overWriteSetter(Text, 'height', getNumberOrAutoValidator());
664
+ /**
665
+ * get/set direction
666
+ * @name Konva.Text#direction
667
+ * @method
668
+ * @param {String} direction
669
+ * @returns {String}
670
+ * @example
671
+ * // get direction
672
+ * var direction = text.direction();
673
+ *
674
+ * // set direction
675
+ * text.direction('rtl');
676
+ */
500
677
  Factory.addGetterSetter(Text, 'direction', INHERIT);
678
+ /**
679
+ * get/set font family
680
+ * @name Konva.Text#fontFamily
681
+ * @method
682
+ * @param {String} fontFamily
683
+ * @returns {String}
684
+ * @example
685
+ * // get font family
686
+ * var fontFamily = text.fontFamily();
687
+ *
688
+ * // set font family
689
+ * text.fontFamily('Arial');
690
+ */
501
691
  Factory.addGetterSetter(Text, 'fontFamily', 'Arial');
692
+ /**
693
+ * get/set font size in pixels
694
+ * @name Konva.Text#fontSize
695
+ * @method
696
+ * @param {Number} fontSize
697
+ * @returns {Number}
698
+ * @example
699
+ * // get font size
700
+ * var fontSize = text.fontSize();
701
+ *
702
+ * // set font size to 22px
703
+ * text.fontSize(22);
704
+ */
502
705
  Factory.addGetterSetter(Text, 'fontSize', 12, getNumberValidator());
706
+ /**
707
+ * get/set font style. Can be 'normal', 'italic', or 'bold', '500' or even 'italic bold'. 'normal' is the default.
708
+ * @name Konva.Text#fontStyle
709
+ * @method
710
+ * @param {String} fontStyle
711
+ * @returns {String}
712
+ * @example
713
+ * // get font style
714
+ * var fontStyle = text.fontStyle();
715
+ *
716
+ * // set font style
717
+ * text.fontStyle('bold');
718
+ */
503
719
  Factory.addGetterSetter(Text, 'fontStyle', NORMAL);
720
+ /**
721
+ * get/set font variant. Can be 'normal' or 'small-caps'. 'normal' is the default.
722
+ * @name Konva.Text#fontVariant
723
+ * @method
724
+ * @param {String} fontVariant
725
+ * @returns {String}
726
+ * @example
727
+ * // get font variant
728
+ * var fontVariant = text.fontVariant();
729
+ *
730
+ * // set font variant
731
+ * text.fontVariant('small-caps');
732
+ */
504
733
  Factory.addGetterSetter(Text, 'fontVariant', NORMAL);
734
+ /**
735
+ * get/set padding
736
+ * @name Konva.Text#padding
737
+ * @method
738
+ * @param {Number} padding
739
+ * @returns {Number}
740
+ * @example
741
+ * // get padding
742
+ * var padding = text.padding();
743
+ *
744
+ * // set padding to 10 pixels
745
+ * text.padding(10);
746
+ */
505
747
  Factory.addGetterSetter(Text, 'padding', 0, getNumberValidator());
748
+ /**
749
+ * get/set horizontal align of text. Can be 'left', 'center', 'right' or 'justify'
750
+ * @name Konva.Text#align
751
+ * @method
752
+ * @param {String} align
753
+ * @returns {String}
754
+ * @example
755
+ * // get text align
756
+ * var align = text.align();
757
+ *
758
+ * // center text
759
+ * text.align('center');
760
+ *
761
+ * // align text to right
762
+ * text.align('right');
763
+ *
764
+ * // justify text
765
+ */
506
766
  Factory.addGetterSetter(Text, 'align', LEFT);
767
+ /**
768
+ * get/set vertical align of text. Can be 'top', 'middle', 'bottom'.
769
+ * @name Konva.Text#verticalAlign
770
+ * @method
771
+ * @param {String} verticalAlign
772
+ * @returns {String}
773
+ * @example
774
+ * // get text vertical align
775
+ * var verticalAlign = text.verticalAlign();
776
+ *
777
+ * // center text
778
+ * text.verticalAlign('middle');
779
+ */
507
780
  Factory.addGetterSetter(Text, 'verticalAlign', TOP);
781
+ /**
782
+ * get/set line height. The default is 1.
783
+ * @name Konva.Text#lineHeight
784
+ * @method
785
+ * @param {Number} lineHeight
786
+ * @returns {Number}
787
+ * @example
788
+ * // get line height
789
+ * var lineHeight = text.lineHeight();
790
+ *
791
+ * // set the line height
792
+ * text.lineHeight(2);
793
+ */
508
794
  Factory.addGetterSetter(Text, 'lineHeight', 1, getNumberValidator());
795
+ /**
796
+ * get/set wrap. Can be "word", "char", or "none". Default is "word".
797
+ * In "word" wrapping any word still can be wrapped if it can't be placed in the required width
798
+ * without breaks.
799
+ * @name Konva.Text#wrap
800
+ * @method
801
+ * @param {String} wrap
802
+ * @returns {String}
803
+ * @example
804
+ * // get wrap
805
+ * var wrap = text.wrap();
806
+ *
807
+ * // set wrap
808
+ * text.wrap('word');
809
+ */
509
810
  Factory.addGetterSetter(Text, 'wrap', WORD);
811
+ /**
812
+ * get/set ellipsis. Can be true or false. Default is false. If ellipsis is true,
813
+ * Konva cuts the text that does not fit and ends it with "…" (one character).
814
+ * That needs a fixed height or wrap set to "none"
815
+ * @name Konva.Text#ellipsis
816
+ * @method
817
+ * @param {Boolean} ellipsis
818
+ * @returns {Boolean}
819
+ * @example
820
+ * // get ellipsis param, returns true or false
821
+ * var ellipsis = text.ellipsis();
822
+ *
823
+ * // set ellipsis
824
+ * text.ellipsis(true);
825
+ */
510
826
  Factory.addGetterSetter(Text, 'ellipsis', false, getBooleanValidator());
827
+ /**
828
+ * set letter spacing property. Default value is 0.
829
+ * @name Konva.Text#letterSpacing
830
+ * @method
831
+ * @param {Number} letterSpacing
832
+ */
511
833
  Factory.addGetterSetter(Text, 'letterSpacing', 0, getNumberValidator());
834
+ /**
835
+ * get/set text
836
+ * @name Konva.Text#text
837
+ * @method
838
+ * @param {String} text
839
+ * @returns {String}
840
+ * @example
841
+ * // get text
842
+ * var text = text.text();
843
+ *
844
+ * // set text
845
+ * text.text('Hello world!');
846
+ */
512
847
  Factory.addGetterSetter(Text, 'text', '', getStringValidator());
848
+ /**
849
+ * get/set text decoration of a text. Possible values are 'underline', 'line-through' or combination of these values separated by space
850
+ * @name Konva.Text#textDecoration
851
+ * @method
852
+ * @param {String} textDecoration
853
+ * @returns {String}
854
+ * @example
855
+ * // get text decoration
856
+ * var textDecoration = text.textDecoration();
857
+ *
858
+ * // underline text
859
+ * text.textDecoration('underline');
860
+ *
861
+ * // strike text
862
+ * text.textDecoration('line-through');
863
+ *
864
+ * // underline and strike text
865
+ * text.textDecoration('underline line-through');
866
+ */
513
867
  Factory.addGetterSetter(Text, 'textDecoration', '');
868
+ /**
869
+ * get/set text underline decoration offset. Offset for underline line. Default is calculated based on font size.
870
+ * @name Konva.Text#underlineOffset
871
+ * @method
872
+ * @param {Number} underlineOffset
873
+ * @returns {Number}
874
+ * @example
875
+ * // get underline offset
876
+ * var underlineOffset = text.underlineOffset();
877
+ *
878
+ * // set underline offset
879
+ * text.underlineOffset(5);
880
+ */
514
881
  Factory.addGetterSetter(Text, 'underlineOffset', undefined, getNumberValidator());
882
+ /**
883
+ * get/set per-character render hook. The callback is invoked for each grapheme before drawing.
884
+ * It can mutate the provided context (e.g. translate, rotate, change styles) and should return void.
885
+ * Note: per-character rendering may disable native kerning/ligatures.
886
+ * @name Konva.Text#charRenderFunc
887
+ * @method
888
+ * @param {Function} charRenderFunc
889
+ * @returns {Function}
890
+ * @example
891
+ * // apply small x-translation and a custom color to every second character
892
+ * text.charRenderFunc(function(props) {
893
+ * if (props.index % 2 === 1) {
894
+ * props.context.translate(2, 0);
895
+ * props.context.fillStyle = 'red';
896
+ * }
897
+ * });
898
+ */
515
899
  Factory.addGetterSetter(Text, 'charRenderFunc', undefined);