react-lasso-select 1.2.2 → 2.0.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/index.esm.js DELETED
@@ -1,881 +0,0 @@
1
- import React from 'react';
2
- import PropTypes from 'prop-types';
3
-
4
- /*! *****************************************************************************
5
- Copyright (c) Microsoft Corporation.
6
-
7
- Permission to use, copy, modify, and/or distribute this software for any
8
- purpose with or without fee is hereby granted.
9
-
10
- THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
11
- REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
12
- AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
13
- INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
14
- LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
15
- OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
16
- PERFORMANCE OF THIS SOFTWARE.
17
- ***************************************************************************** */
18
- /* global Reflect, Promise */
19
-
20
- var extendStatics = function(d, b) {
21
- extendStatics = Object.setPrototypeOf ||
22
- ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
23
- function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
24
- return extendStatics(d, b);
25
- };
26
-
27
- function __extends(d, b) {
28
- if (typeof b !== "function" && b !== null)
29
- throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
30
- extendStatics(d, b);
31
- function __() { this.constructor = d; }
32
- d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
33
- }
34
-
35
- var __assign = function() {
36
- __assign = Object.assign || function __assign(t) {
37
- for (var s, i = 1, n = arguments.length; i < n; i++) {
38
- s = arguments[i];
39
- for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p];
40
- }
41
- return t;
42
- };
43
- return __assign.apply(this, arguments);
44
- };
45
-
46
- function __rest(s, e) {
47
- var t = {};
48
- for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
49
- t[p] = s[p];
50
- if (s != null && typeof Object.getOwnPropertySymbols === "function")
51
- for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
52
- if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))
53
- t[p[i]] = s[p[i]];
54
- }
55
- return t;
56
- }
57
-
58
- function __spreadArray(to, from) {
59
- for (var i = 0, il = from.length, j = to.length; i < il; i++, j++)
60
- to[j] = from[i];
61
- return to;
62
- }
63
-
64
- var objectToClassName = function (obj) {
65
- return Object.keys(obj)
66
- .filter(function (key) { return obj[key]; })
67
- .join(' ');
68
- };
69
- var arePointsEqual = function (p1, p2) { return p1.x === p2.x && p1.y === p2.y; };
70
- var arePointListEqual = function (arr1, arr2) {
71
- if ((!arr1 && arr2) || (arr1 && !arr2) || arr1.length !== arr2.length)
72
- return false;
73
- return arr1.every(function (point, i) { return arePointsEqual(point, arr2[i]); });
74
- };
75
- var roundPointCoordinates = function (_a, p) {
76
- var x = _a.x, y = _a.y;
77
- if (p === void 0) { p = 1; }
78
- return ({
79
- x: Math.round((x + Number.EPSILON) * p) / p,
80
- y: Math.round((y + Number.EPSILON) * p) / p
81
- });
82
- };
83
- var findPointByPosition = function (points, position, r) {
84
- if (r === void 0) { r = 0; }
85
- var index = points.findIndex(function (point) { return Math.max(Math.abs(point.x - position.x), Math.abs(point.y - position.y)) <= r; });
86
- return { point: __assign({}, (points[index] || { x: NaN, y: NaN })), index: index };
87
- };
88
- var getDistance = function (p1, p2) {
89
- return Math.hypot(p2.x - p1.x, p2.y - p1.y);
90
- };
91
- var getAngle = function (p1, p2) {
92
- return Math.atan2(p2.y - p1.y, p2.x - p1.x);
93
- };
94
- var approximateToAnAngleMultiplicity = function (startPoint, endPoint, minAngle) {
95
- var r = getDistance(startPoint, endPoint);
96
- var angle = getAngle(startPoint, endPoint);
97
- var newAngle = Math.round(angle / minAngle) * minAngle;
98
- return {
99
- x: startPoint.x + r * Math.cos(newAngle),
100
- y: startPoint.y + r * Math.sin(newAngle)
101
- };
102
- };
103
- var approximateToAngles = function (startPoint, endPoint, angles) {
104
- var r = getDistance(startPoint, endPoint);
105
- var angle = getAngle(startPoint, endPoint);
106
- var nearestAngle = angles.reduce(function (prev, now) { return (Math.abs(now - angle) < Math.abs(prev - angle) ? now : prev); }, Infinity);
107
- if (nearestAngle !== Infinity) {
108
- endPoint.x = startPoint.x + r * Math.cos(nearestAngle);
109
- endPoint.y = startPoint.y + r * Math.sin(nearestAngle);
110
- }
111
- return endPoint;
112
- };
113
- var calculateAnglesBeetwenPoints = function (points) {
114
- var angles = [];
115
- for (var i = 1; i < points.length; i++) {
116
- var alpha = Math.atan2(points[i].y - points[i - 1].y, points[i].x - points[i - 1].x);
117
- var alpha2 = alpha + Math.PI;
118
- angles.push(alpha, alpha2 > Math.PI ? alpha2 - 2 * Math.PI : alpha2);
119
- }
120
- return angles.filter(function (val, idx, arr) { return arr.indexOf(val) === idx; });
121
- };
122
- function getClippedImageCanvas(src, path, callback, crop) {
123
- if (crop === void 0) { crop = true; }
124
- var image = new Image();
125
- image.crossOrigin = 'Anonymous';
126
- var canvas = document.createElement('canvas');
127
- var ctx = canvas.getContext('2d');
128
- if (!ctx) {
129
- return callback(new Error('CTX is null'), canvas);
130
- }
131
- image.onerror = function () {
132
- callback(new Error('Failed to load image'), canvas);
133
- };
134
- image.onload = function () {
135
- try {
136
- canvas.width = image.naturalWidth + 2;
137
- canvas.height = image.naturalHeight + 2;
138
- ctx.drawImage(image, 0, 0);
139
- if (path.length < 3) {
140
- callback(null, canvas);
141
- return;
142
- }
143
- ctx.beginPath();
144
- ctx.moveTo(0, 0);
145
- ctx.lineTo(canvas.width, 0);
146
- ctx.lineTo(canvas.width, canvas.height);
147
- ctx.lineTo(0, canvas.height);
148
- ctx.lineTo(0, 0);
149
- ctx.lineTo(path[0].x + 1, path[0].y + 1);
150
- path.slice(1).forEach(function (_a) {
151
- var x = _a.x, y = _a.y;
152
- return ctx.lineTo(x + 1, y + 1);
153
- });
154
- ctx.lineTo(path[0].x + 1, path[0].y + 1);
155
- ctx.lineTo(0, 0);
156
- ctx.closePath();
157
- ctx.clip('evenodd');
158
- ctx.globalCompositeOperation = 'destination-out';
159
- ctx.fill();
160
- if (crop) {
161
- var xAxis = path.map(function (_a) {
162
- var x = _a.x;
163
- return x + 1;
164
- });
165
- var yAxis = path.map(function (_a) {
166
- var y = _a.y;
167
- return y + 1;
168
- });
169
- var _a = [Math.min.apply(null, xAxis), Math.min.apply(null, yAxis)], minX = _a[0], minY = _a[1];
170
- var _b = [Math.max.apply(null, xAxis), Math.max.apply(null, yAxis)], maxX = _b[0], maxY = _b[1];
171
- var _c = [maxX - minX, maxY - minY], width = _c[0], height = _c[1];
172
- var imageData = ctx.getImageData(minX, minY, width, height);
173
- canvas.width = width;
174
- canvas.height = height;
175
- ctx.putImageData(imageData, 0, 0);
176
- }
177
- callback(null, canvas);
178
- }
179
- catch (err) {
180
- callback(err instanceof Error ? err : new Error(String(err)), canvas);
181
- }
182
- };
183
- image.src = src;
184
- }
185
-
186
- var SVGHelper = /** @class */ (function () {
187
- function SVGHelper(getSvgElement) {
188
- this.getSvgElement = getSvgElement;
189
- }
190
- SVGHelper.prototype.getSvg = function () {
191
- var svg = this.getSvgElement();
192
- if (!svg)
193
- throw new Error('SVG is null');
194
- return svg;
195
- };
196
- SVGHelper.prototype.getCTM = function () {
197
- var svg = this.getSvg();
198
- var ctm = svg.getCTM();
199
- if (ctm === null) {
200
- // https://www.w3.org/TR/SVGTiny12/coords.html#TransformMatrixDefined
201
- var svgChild = svg.querySelector('rect[visibility="hidden"]');
202
- ctm = svgChild.getCTM();
203
- }
204
- if (!ctm)
205
- throw new Error('CTM is null');
206
- return ctm;
207
- };
208
- SVGHelper.prototype.getViewboxSize = function () {
209
- return this.getSvg().viewBox.baseVal;
210
- };
211
- SVGHelper.prototype.getRealSize = function () {
212
- var svg = this.getSvg();
213
- // Firefox have problems with SVGSVGElement.width.baseVal.value
214
- return {
215
- width: svg.clientWidth,
216
- height: svg.clientHeight
217
- };
218
- };
219
- SVGHelper.prototype.getViewboxOffset = function () {
220
- var svg = this.getSvg();
221
- var _a = this.getRealSize(), rWidth = _a.width, rHeight = _a.height;
222
- var _b = this.getViewboxSize(), vWidth = _b.width, vHeight = _b.height;
223
- var point = Object.assign(svg.createSVGPoint(), {
224
- x: rWidth,
225
- y: rHeight
226
- });
227
- var ctm = this.getCTM();
228
- var _c = point.matrixTransform(ctm.inverse()), x = _c.x, y = _c.y;
229
- // only for preserveAspectRatio="xMidYMid meet" !!!
230
- return {
231
- x: x - vWidth,
232
- y: y - vHeight
233
- };
234
- };
235
- SVGHelper.prototype.convertViewboxPointsToReal = function (points) {
236
- var svg = this.getSvg();
237
- var ctm = this.getCTM();
238
- return points.map(function (_a) {
239
- var x = _a.x, y = _a.y;
240
- var p = Object.assign(svg.createSVGPoint(), { x: x, y: y }).matrixTransform(ctm);
241
- return roundPointCoordinates(p);
242
- });
243
- };
244
- SVGHelper.prototype.convertRealPointsToViewbox = function (points) {
245
- var svg = this.getSvg();
246
- var ctm = this.getCTM().inverse();
247
- return points.map(function (_a) {
248
- var x = _a.x, y = _a.y;
249
- var p = Object.assign(svg.createSVGPoint(), { x: x, y: y }).matrixTransform(ctm);
250
- return roundPointCoordinates(p, 1e3);
251
- });
252
- };
253
- SVGHelper.prototype.getBorderPoints = function (repeatFirst) {
254
- if (repeatFirst === void 0) { repeatFirst = true; }
255
- var _a = this.getViewboxSize(), width = _a.width, height = _a.height;
256
- var _b = this.getViewboxOffset(), offsetX = _b.x, offsetY = _b.y;
257
- var arr = [
258
- { x: -offsetX, y: -offsetY },
259
- { x: width + offsetX, y: -offsetY },
260
- { x: width + offsetX, y: height + offsetY },
261
- { x: -offsetX, y: height + offsetY }
262
- ];
263
- if (repeatFirst) {
264
- arr.push({ x: -offsetX, y: -offsetY });
265
- }
266
- return arr;
267
- };
268
- SVGHelper.prototype.isAboveTheBorder = function (_a) {
269
- var x = _a.x, y = _a.y;
270
- var _b = this.getViewboxSize(), width = _b.width, height = _b.height;
271
- var _c = this.getViewboxOffset(), offsetX = _c.x, offsetY = _c.y;
272
- return x < -offsetX || x > width + offsetX || y < -offsetY || y > height + offsetY;
273
- };
274
- SVGHelper.prototype.getMouseCoordinates = function (event) {
275
- var e = event;
276
- var _a = e.changedTouches && e.touches ? e.changedTouches[0] || e.touches[0] : e, clientX = _a.clientX, clientY = _a.clientY;
277
- var svg = this.getSvg();
278
- var ctm = svg.getScreenCTM();
279
- if (!ctm)
280
- throw new Error('ScreenCTM is null');
281
- var point = svg.createSVGPoint();
282
- point.x = clientX;
283
- point.y = clientY;
284
- var _b = point.matrixTransform(ctm.inverse()), x = _b.x, y = _b.y;
285
- return { x: x, y: y };
286
- };
287
- return SVGHelper;
288
- }());
289
-
290
- // eslint-disable-next-line @typescript-eslint/ban-types
291
- var withDraggable = function (Component) {
292
- return /** @class */ (function (_super) {
293
- __extends(DraggableHOC, _super);
294
- function DraggableHOC() {
295
- var _this = _super !== null && _super.apply(this, arguments) || this;
296
- _this.ref = React.createRef();
297
- _this.svg = new SVGHelper(function () { var _a, _b; return (_b = (_a = _this.ref) === null || _a === void 0 ? void 0 : _a.current) === null || _b === void 0 ? void 0 : _b.ownerSVGElement; });
298
- _this.dragLastPosition = null;
299
- _this.wasMoved = false;
300
- _this.onMouseTouchDown = function (e) {
301
- if (e.target === _this.ref.current && _this.props.draggable) {
302
- e.stopImmediatePropagation();
303
- e.preventDefault();
304
- var target = e.target;
305
- _this.dragLastPosition = _this.getMousePosition(e);
306
- if (target.ownerSVGElement) {
307
- target.ownerSVGElement.focus({ preventScroll: true });
308
- }
309
- }
310
- };
311
- _this.onMouseTouchMove = function (e) {
312
- if (_this.dragLastPosition) {
313
- e.stopImmediatePropagation();
314
- e.preventDefault();
315
- var _a = _this.getMousePosition(e), x = _a.x, y = _a.y;
316
- var dx = x - _this.dragLastPosition.x;
317
- var dy = y - _this.dragLastPosition.y;
318
- if (!_this.wasMoved && _this.props.onDragStart) {
319
- _this.props.onDragStart({
320
- x: _this.dragLastPosition.x,
321
- y: _this.dragLastPosition.y,
322
- dx: dx,
323
- dy: dy
324
- });
325
- }
326
- if (_this.props.onDrag) {
327
- _this.props.onDrag({ dx: dx, dy: dy });
328
- }
329
- _this.dragLastPosition = { x: x, y: y };
330
- _this.wasMoved = true;
331
- }
332
- };
333
- _this.onMouseTouchUp = function (e) {
334
- if (_this.dragLastPosition && _this.wasMoved) {
335
- e.stopImmediatePropagation();
336
- e.preventDefault();
337
- if (e instanceof MouseEvent || !e.touches) {
338
- window.addEventListener('click', function (e) { return e.stopPropagation(); }, {
339
- capture: true,
340
- once: true
341
- });
342
- }
343
- if (_this.props.onDragEnd) {
344
- _this.props.onDragEnd({
345
- x: _this.dragLastPosition.x,
346
- y: _this.dragLastPosition.y
347
- });
348
- }
349
- }
350
- _this.dragLastPosition = null;
351
- _this.wasMoved = false;
352
- };
353
- return _this;
354
- }
355
- DraggableHOC.prototype.render = function () {
356
- var _a = this.props, draggable = _a.draggable; _a.onDrag; _a.onDragStart; _a.onDragEnd; var rest = __rest(_a, ["draggable", "onDrag", "onDragStart", "onDragEnd"]);
357
- return React.createElement(Component, __assign({ ref: this.ref }, rest, { draggable: draggable }));
358
- };
359
- DraggableHOC.prototype.componentDidUpdate = function (prevProps) {
360
- if (prevProps.draggable && !this.props.draggable) {
361
- // cleanup after props.draggable changed to false
362
- if (this.dragLastPosition && this.wasMoved) {
363
- if (this.props.onDragEnd) {
364
- this.props.onDragEnd({
365
- x: this.dragLastPosition.x,
366
- y: this.dragLastPosition.y
367
- });
368
- }
369
- this.dragLastPosition = null;
370
- this.wasMoved = false;
371
- }
372
- }
373
- };
374
- DraggableHOC.prototype.componentDidMount = function () {
375
- window.addEventListener('mousedown', this.onMouseTouchDown, true);
376
- window.addEventListener('mousemove', this.onMouseTouchMove, true);
377
- window.addEventListener('mouseup', this.onMouseTouchUp, true);
378
- window.addEventListener('touchstart', this.onMouseTouchDown, true);
379
- window.addEventListener('touchmove', this.onMouseTouchMove, true);
380
- window.addEventListener('touchend', this.onMouseTouchUp, true);
381
- };
382
- DraggableHOC.prototype.componentWillUnmount = function () {
383
- window.removeEventListener('mousedown', this.onMouseTouchDown);
384
- window.removeEventListener('mousemove', this.onMouseTouchMove);
385
- window.removeEventListener('mouseup', this.onMouseTouchUp);
386
- window.removeEventListener('touchstart', this.onMouseTouchDown);
387
- window.removeEventListener('touchmove', this.onMouseTouchMove);
388
- window.removeEventListener('touchend', this.onMouseTouchUp);
389
- };
390
- DraggableHOC.prototype.getMousePosition = function (ev) {
391
- var e = ev;
392
- return this.svg.getMouseCoordinates(e);
393
- };
394
- return DraggableHOC;
395
- }(React.Component));
396
- };
397
-
398
- var SVGPolyline = withDraggable(React.forwardRef(function SVGPolyline(_a, ref) {
399
- var path = _a.path, animate = _a.animate, draggable = _a.draggable;
400
- return (React.createElement("polyline", { ref: ref, style: { cursor: draggable ? 'move' : '' }, points: path.map(function (_a) {
401
- var x = _a.x, y = _a.y;
402
- return x + "," + y;
403
- }).join(' '), fill: "rgba(0,0,0,0)", stroke: "white", strokeWidth: "1.5", shapeRendering: "geometricPrecision", strokeDasharray: "3", strokeDashoffset: "0", vectorEffect: "non-scaling-stroke" }, animate && (React.createElement("animate", { attributeName: "stroke-dashoffset", values: "0;1000;0", dur: "100s", repeatCount: "indefinite" }))));
404
- }));
405
-
406
- function SVGPolygon(_a) {
407
- var path = _a.path;
408
- return (React.createElement("polygon", { style: {
409
- pointerEvents: 'none',
410
- transform: 'translate(-1px, -1px)'
411
- }, points: path.map(function (_a) {
412
- var x = _a.x, y = _a.y;
413
- return x + "," + y;
414
- }).join(' '), fill: "rgba(0, 0, 0, 0.5)", fillRule: "evenodd", stroke: "null", shapeRendering: "geometricPrecision" }));
415
- }
416
-
417
- var SVGPoint = withDraggable(React.forwardRef(function SVGPoint(_a, ref) {
418
- var x = _a.x, y = _a.y, onClickTouchEvent = _a.onClickTouchEvent, draggable = _a.draggable, style = _a.style;
419
- var _b = style.cursor, cursor = _b === void 0 ? draggable ? 'move' : 'default' : _b, rest = __rest(style, ["cursor"]);
420
- return (React.createElement("rect", { style: __assign({ cursor: cursor }, rest), ref: ref, x: x - 10, y: y - 10, onClick: function (e) {
421
- e.stopPropagation();
422
- e.preventDefault();
423
- onClickTouchEvent(e);
424
- }, onTouchEnd: function (e) {
425
- e.stopPropagation();
426
- e.preventDefault();
427
- onClickTouchEvent(e);
428
- }, width: "20px", height: "20", fill: "rgba(0, 0, 0, 0)", stroke: "white", strokeWidth: "1.25", vectorEffect: "non-scaling-stroke" }));
429
- }));
430
-
431
- var pathActions;
432
- (function (pathActions) {
433
- pathActions["ADD"] = "ADD";
434
- pathActions["DELETE"] = "DELETE";
435
- pathActions["MODIFY"] = "MODIFY";
436
- pathActions["MOVE"] = "MOVE";
437
- pathActions["RESET"] = "RESET";
438
- pathActions["CHANGE"] = "CHANGE";
439
- })(pathActions || (pathActions = {}));
440
- function pathReducer(state, action) {
441
- var length = state.points.length;
442
- switch (action.type) {
443
- case pathActions.ADD: {
444
- if (state.closed)
445
- return [state, false];
446
- if ((length > 0 && arePointsEqual(state.points[length - 1], action.payload)) ||
447
- (length > 1 && arePointsEqual(state.points[length - 2], action.payload))) {
448
- return [state, false];
449
- }
450
- var needToBeClosed = length > 2 && arePointsEqual(state.points[0], action.payload);
451
- if (needToBeClosed)
452
- return [{ points: __spreadArray([], state.points), closed: true }, true];
453
- return [{ points: __spreadArray(__spreadArray([], state.points, true), [action.payload]), closed: false }, true];
454
- }
455
- case pathActions.DELETE: {
456
- return [
457
- {
458
- points: __spreadArray([], state.points.filter(function (_, idx) { return action.payload !== idx; })),
459
- closed: length > 4 && state.closed
460
- },
461
- true
462
- ];
463
- }
464
- case pathActions.MODIFY: {
465
- var _a = state.points[action.payload.index], sx_1 = _a.x, sy_1 = _a.y;
466
- var newPoints = state.points.map(function (_a) {
467
- var x = _a.x, y = _a.y;
468
- if (x === sx_1 && y === sy_1) {
469
- return {
470
- x: action.payload.x,
471
- y: action.payload.y
472
- };
473
- }
474
- return { x: x, y: y };
475
- });
476
- return [
477
- { points: newPoints, closed: state.closed },
478
- !!(action.payload.x || action.payload.y)
479
- ];
480
- }
481
- case pathActions.MOVE: {
482
- return [
483
- {
484
- points: state.points.map(function (_a) {
485
- var x = _a.x, y = _a.y;
486
- return ({
487
- x: x + action.payload.x,
488
- y: y + action.payload.y
489
- });
490
- }),
491
- closed: state.closed
492
- },
493
- !!(action.payload.x || action.payload.y)
494
- ];
495
- }
496
- case pathActions.CHANGE: {
497
- var wasModified = !arePointListEqual(action.payload, state.points);
498
- return [
499
- {
500
- points: action.payload,
501
- closed: wasModified ? action.payload.length > 2 : state.closed
502
- },
503
- wasModified
504
- ];
505
- }
506
- case pathActions.RESET:
507
- return [{ points: [], closed: false }, !!state.points.length];
508
- default:
509
- return [state, false];
510
- }
511
- }
512
-
513
- var ReactLasso = /** @class */ (function (_super) {
514
- __extends(ReactLasso, _super);
515
- function ReactLasso(props) {
516
- var _this = _super.call(this, props) || this;
517
- _this.imageRef = React.createRef();
518
- _this.svgRef = React.createRef();
519
- _this.svg = new SVGHelper(function () { var _a; return (_a = _this.svgRef) === null || _a === void 0 ? void 0 : _a.current; });
520
- _this.angles = [];
521
- _this.path = {
522
- points: [],
523
- closed: false
524
- };
525
- _this.lastEmittedPoints = [];
526
- _this.lastUpdatedPoints = [];
527
- _this.imgError = false;
528
- _this.setPathFromPropsOnMediaLoad = true;
529
- _this.hidePointer = function () {
530
- var lastPoint = _this.path.points[_this.path.points.length - 1] || {
531
- x: 0,
532
- y: 0
533
- };
534
- _this.setPointer(__assign({}, lastPoint), true); // tricky way to hide pointer line
535
- };
536
- // Events
537
- _this.onShapeDrag = function (_a) {
538
- var dx = _a.dx, dy = _a.dy;
539
- var newPath = _this.path.points.map(function (_a) {
540
- var x = _a.x, y = _a.y;
541
- return ({
542
- x: x + dx,
543
- y: y + dy
544
- });
545
- });
546
- if (!newPath.some(function (point) { return _this.svg.isAboveTheBorder(point); })) {
547
- _this.dispatchPathAction({
548
- type: pathActions.MOVE,
549
- payload: { x: dx, y: dy }
550
- });
551
- }
552
- };
553
- _this.onPointDrag = function (idx, _a) {
554
- var dx = _a.dx, dy = _a.dy;
555
- var point = __assign({}, _this.path.points[idx]);
556
- point.x += dx;
557
- point.y += dy;
558
- if (!_this.svg.isAboveTheBorder(point)) {
559
- _this.dispatchPathAction({
560
- type: pathActions.MODIFY,
561
- payload: __assign(__assign({}, point), { index: idx })
562
- });
563
- }
564
- };
565
- _this.onPointClick = function (idx) {
566
- if (_this.isLoaded() && !_this.props.disabled && !_this.path.closed) {
567
- _this.dispatchPathAction({
568
- type: pathActions.ADD,
569
- payload: _this.path.points[idx]
570
- });
571
- }
572
- };
573
- _this.onDragEnd = function () {
574
- _this.checkIfPathUpdated(false);
575
- };
576
- _this.onMediaLoaded = function (e) {
577
- if (_this.setPathFromPropsOnMediaLoad) {
578
- _this.setPathStateFromProps();
579
- _this.setPathFromPropsOnMediaLoad = false;
580
- }
581
- _this.imgError = false;
582
- _this.props.onImageLoad(e);
583
- };
584
- _this.onMediaError = function (e) {
585
- _this.dispatchPathAction({ type: pathActions.RESET });
586
- _this.imgError = true;
587
- _this.props.onImageError(e);
588
- };
589
- _this.onClickTouchEvent = function (e) {
590
- if (_this.isLoaded() && !_this.props.disabled) {
591
- if (_this.path.closed) {
592
- if (e.target === _this.svgRef.current) {
593
- _this.dispatchPathAction({
594
- type: pathActions.RESET
595
- });
596
- }
597
- return;
598
- }
599
- var pointer = _this.getMousePosition(e)[0];
600
- if (!_this.svg.isAboveTheBorder(pointer)) {
601
- _this.dispatchPathAction({
602
- type: pathActions.ADD,
603
- payload: roundPointCoordinates(pointer, 1e3),
604
- pointer: pointer
605
- });
606
- }
607
- else {
608
- _this.hidePointer();
609
- }
610
- }
611
- };
612
- _this.onClick = function (e) {
613
- _this.onClickTouchEvent(e);
614
- };
615
- _this.onTouchEnd = function (e) {
616
- if (e.cancelable) {
617
- e.preventDefault();
618
- _this.onClickTouchEvent(e);
619
- }
620
- _this.hidePointer();
621
- };
622
- _this.onMouseTouchMove = function (e) {
623
- if (_this.isLoaded()) {
624
- var pointer = _this.getMousePosition(e)[0];
625
- _this.setPointer(pointer);
626
- }
627
- };
628
- _this.onContextMenu = function (e) {
629
- if (_this.isLoaded()) {
630
- e.preventDefault();
631
- if (!_this.props.disabled && !_this.path.closed) {
632
- var _a = _this.getMousePosition(e), pointer = _a[0], index = _a[1].index;
633
- if (index > -1) {
634
- _this.dispatchPathAction({
635
- type: pathActions.DELETE,
636
- payload: index,
637
- pointer: pointer
638
- });
639
- }
640
- else {
641
- _this.setPointer(pointer);
642
- }
643
- }
644
- }
645
- };
646
- _this.state = {
647
- path: {
648
- points: [],
649
- closed: false
650
- },
651
- pointer: {
652
- x: props.viewBox.width / 2,
653
- y: props.viewBox.width / 2
654
- }
655
- };
656
- return _this;
657
- }
658
- ReactLasso.prototype.render = function () {
659
- var _this = this;
660
- return (React.createElement("div", { className: objectToClassName({
661
- ReactFreeSelect__Component: true,
662
- ReactFreeSelect__Closed: this.state.path.closed,
663
- ReactFreeSelect__Disabled: this.props.disabled
664
- }), style: __assign({ display: 'inline-block', position: 'relative', margin: '0', padding: '0', fontSize: '0', cursor: this.props.disabled ? 'not-allowed' : 'default' }, this.props.style) },
665
- React.createElement("img", { ref: this.imageRef, src: this.props.src, alt: this.props.imageAlt, crossOrigin: this.props.crossOrigin, style: this.props.imageStyle, onLoad: this.onMediaLoaded, onError: this.onMediaError }),
666
- React.createElement("svg", { ref: this.svgRef, style: {
667
- position: 'absolute',
668
- top: '0',
669
- left: '0',
670
- width: '100%',
671
- height: '100%',
672
- overflow: 'hidden',
673
- userSelect: 'none',
674
- touchAction: 'none'
675
- }, viewBox: "0 0 " + this.props.viewBox.width + " " + this.props.viewBox.height, onMouseMove: this.onMouseTouchMove, onTouchMove: this.onMouseTouchMove, onClick: this.onClick, onTouchEnd: this.onTouchEnd, onContextMenu: this.onContextMenu, onMouseLeave: this.hidePointer },
676
- React.createElement("rect", { visibility: "hidden" }),
677
- !!this.state.path.points.length && React.createElement(SVGPolygon, { path: this.getPolygonPoints() }),
678
- React.createElement(SVGPolyline, { draggable: this.state.path.closed && !this.props.disabled, onDrag: this.onShapeDrag, onDragEnd: this.onDragEnd, animate: !this.props.disabled, path: this.getPolylinePoints() }),
679
- this.getRoundedPoints().map(function (_a, idx) {
680
- var x = _a.x, y = _a.y;
681
- return (React.createElement(SVGPoint, { key: idx, x: x, y: y, draggable: !_this.props.disabled, style: {
682
- cursor: !idx && _this.state.path.points.length > 2 && !_this.state.path.closed
683
- ? 'pointer'
684
- : undefined
685
- }, onDrag: function (_a) {
686
- var dx = _a.dx, dy = _a.dy;
687
- return _this.onPointDrag(idx, { dx: dx, dy: dy });
688
- }, onDragEnd: _this.onDragEnd, onClickTouchEvent: function () { return _this.onPointClick(idx); } }));
689
- }))));
690
- };
691
- ReactLasso.prototype.componentDidUpdate = function (prevProps) {
692
- if (!prevProps.disabled && this.props.disabled && !this.path.closed) {
693
- this.hidePointer();
694
- }
695
- if (prevProps.src && prevProps.src !== this.props.src) {
696
- this.dispatchPathAction({ type: pathActions.RESET });
697
- }
698
- else if (!arePointListEqual(prevProps.value, this.props.value)) {
699
- if (this.isLoaded()) {
700
- this.setPathStateFromProps();
701
- }
702
- else {
703
- this.setPathFromPropsOnMediaLoad = true;
704
- }
705
- }
706
- };
707
- ReactLasso.prototype.convertPoints = function (points) {
708
- var aspectRatio = this.getAspectRatio();
709
- return this.svg.convertViewboxPointsToReal(points).map(function (_a) {
710
- var x = _a.x, y = _a.y;
711
- return ({
712
- x: Math.round(x / aspectRatio.x),
713
- y: Math.round(y / aspectRatio.y)
714
- });
715
- });
716
- };
717
- ReactLasso.prototype.checkIfPathUpdated = function (wasClosedBefore) {
718
- if (this.path.closed || wasClosedBefore) {
719
- var convertedPoints = this.convertPoints(this.path.points);
720
- if (!arePointListEqual(convertedPoints, this.lastUpdatedPoints)) {
721
- this.emitOnComplete(convertedPoints);
722
- this.lastUpdatedPoints = convertedPoints.map(function (_a) {
723
- var x = _a.x, y = _a.y;
724
- return ({ x: x, y: y });
725
- });
726
- }
727
- }
728
- };
729
- ReactLasso.prototype.emitOnChange = function (_a) {
730
- var points = _a.points;
731
- if (this.props.onChange) {
732
- var convertedPoints = this.convertPoints(points);
733
- this.lastEmittedPoints = convertedPoints;
734
- this.props.onChange(convertedPoints);
735
- }
736
- };
737
- ReactLasso.prototype.emitOnComplete = function (convertedPoints) {
738
- if (this.props.onComplete) {
739
- this.props.onComplete(convertedPoints);
740
- }
741
- };
742
- ReactLasso.prototype.setPointer = function (_a, force) {
743
- var x = _a.x, y = _a.y;
744
- if (force === void 0) { force = false; }
745
- if (force || !this.props.disabled) {
746
- this.setState({
747
- path: this.path,
748
- pointer: { x: x, y: y }
749
- });
750
- }
751
- };
752
- ReactLasso.prototype.dispatchPathAction = function (action) {
753
- var wasClosedBefore = this.path.closed;
754
- var _a = pathReducer(this.path, action), newPathState = _a[0], wasModified = _a[1];
755
- newPathState.points = newPathState.points.map(function (point) { return roundPointCoordinates(point, 1e3); });
756
- if (wasModified) {
757
- this.path = newPathState;
758
- this.setState({
759
- pointer: action.pointer || this.path.points[this.path.points.length - 1] || { x: 0, y: 0 },
760
- path: newPathState
761
- });
762
- this.angles = calculateAnglesBeetwenPoints(newPathState.points);
763
- this.emitOnChange(newPathState);
764
- if (![pathActions.MODIFY, pathActions.MOVE].includes(action.type)) {
765
- this.checkIfPathUpdated(wasClosedBefore); // optimized version of onChange
766
- }
767
- }
768
- };
769
- ReactLasso.prototype.isLoaded = function () {
770
- if (this.imgError || !this.svgRef.current)
771
- return false;
772
- var svg = this.svgRef.current;
773
- return !!(svg.width.baseVal.value && svg.height.baseVal.value);
774
- };
775
- ReactLasso.prototype.getAspectRatio = function () {
776
- if (!this.imageRef.current) {
777
- return { x: NaN, y: NaN };
778
- }
779
- // original * aspectRatio = size
780
- return {
781
- x: this.imageRef.current.clientWidth / this.imageRef.current.naturalWidth,
782
- y: this.imageRef.current.clientHeight / this.imageRef.current.naturalHeight
783
- };
784
- };
785
- ReactLasso.prototype.setPathStateFromProps = function () {
786
- if (arePointListEqual(this.lastEmittedPoints, this.props.value))
787
- return;
788
- var aspectRatio = this.getAspectRatio();
789
- var value = this.svg.convertRealPointsToViewbox(this.props.value.map(function (_a) {
790
- var x = _a.x, y = _a.y;
791
- return ({
792
- x: x * aspectRatio.x,
793
- y: y * aspectRatio.y
794
- });
795
- }));
796
- this.dispatchPathAction({
797
- type: pathActions.CHANGE,
798
- payload: value
799
- });
800
- };
801
- ReactLasso.prototype.getRoundedPoints = function () {
802
- return this.state.path.points.map(function (point) { return roundPointCoordinates(point); });
803
- };
804
- ReactLasso.prototype.getBorder = function () {
805
- return this.svg
806
- .getBorderPoints()
807
- .map(function (point) { return roundPointCoordinates(point); })
808
- .map(function (_a) {
809
- var x = _a.x, y = _a.y;
810
- return ({ x: x - 1, y: y + 1 });
811
- }); // fishy bug here so i have to margin area
812
- };
813
- ReactLasso.prototype.getPolygonPoints = function () {
814
- var roundedPoints = this.getRoundedPoints();
815
- var border = this.getBorder();
816
- return this.state.path.closed
817
- ? __spreadArray(__spreadArray(__spreadArray([], border, true), roundedPoints, true), [roundedPoints[0], border[0]]) : border;
818
- };
819
- ReactLasso.prototype.getPolylinePoints = function () {
820
- var roundedPoints = this.getRoundedPoints();
821
- return roundedPoints.concat(this.state.path.closed ? roundedPoints[0] : roundPointCoordinates(this.state.pointer));
822
- };
823
- ReactLasso.prototype.getMousePosition = function (e, lookupForNearlyPoints, lookupForApproximation) {
824
- if (lookupForNearlyPoints === void 0) { lookupForNearlyPoints = true; }
825
- if (lookupForApproximation === void 0) { lookupForApproximation = true; }
826
- var pointer = this.svg.getMouseCoordinates(e);
827
- if (lookupForApproximation) {
828
- var ctrlCmdPressed = navigator.platform.includes('Mac') ? e.metaKey : e.ctrlKey;
829
- var lastPoint = this.path.points[this.path.points.length - 1];
830
- // straighten path from last point
831
- if (ctrlCmdPressed && lastPoint) {
832
- if (e.shiftKey) {
833
- // lookup for parallel lines
834
- pointer = approximateToAngles(lastPoint, pointer, this.angles);
835
- }
836
- else {
837
- // angle approximation to 15 deg
838
- pointer = approximateToAnAngleMultiplicity(lastPoint, pointer, Math.PI / 12);
839
- }
840
- }
841
- }
842
- var _a = findPointByPosition(this.path.points, pointer, 10), point = _a.point, index = _a.index;
843
- if (lookupForNearlyPoints && index > -1) {
844
- pointer = __assign({}, point);
845
- }
846
- return [pointer, { point: point, index: index }];
847
- };
848
- ReactLasso.propTypes = {
849
- value: PropTypes.arrayOf(PropTypes.exact({
850
- x: PropTypes.number.isRequired,
851
- y: PropTypes.number.isRequired
852
- })),
853
- style: PropTypes.shape({}),
854
- viewBox: PropTypes.exact({
855
- width: PropTypes.number.isRequired,
856
- height: PropTypes.number.isRequired
857
- }),
858
- disabled: PropTypes.bool,
859
- onChange: PropTypes.func,
860
- onComplete: PropTypes.func,
861
- src: PropTypes.string.isRequired,
862
- imageAlt: PropTypes.string,
863
- crossOrigin: PropTypes.string,
864
- imageStyle: PropTypes.shape({}),
865
- onImageLoad: PropTypes.func,
866
- onImageError: PropTypes.func
867
- };
868
- ReactLasso.defaultProps = {
869
- value: [],
870
- style: {},
871
- imageStyle: {},
872
- viewBox: { width: 1e3, height: 1e3 },
873
- disabled: false,
874
- onImageError: Function.prototype,
875
- onImageLoad: Function.prototype
876
- };
877
- return ReactLasso;
878
- }(React.Component));
879
-
880
- export { ReactLasso as Component, ReactLasso, ReactLasso as default, getClippedImageCanvas as getCanvas };
881
- //# sourceMappingURL=index.esm.js.map