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