UNPKG

react-aim

Version:

Determine the cursor aim for triggering mouse events.

97 lines (84 loc) 3.04 kB
'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); exports.distance = distance; exports.side = side; exports.bullseye = bullseye; exports.default = aiming; var _corners = require('./corners'); var _corners2 = _interopRequireDefault(_corners); var _pointInPolygon = require('./utils/pointInPolygon'); var _pointInPolygon2 = _interopRequireDefault(_pointInPolygon); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function distance(source, target) { var a = source.x - target.x; var b = source.y - target.y; return Math.sqrt(a * a + b * b); } function side(corners) { if (corners[0] === 'top-right' && corners[1] === 'bottom-right') return 'right';else if (corners[0] === 'top-left' && corners[1] === 'bottom-right') return 'top-right';else if (corners[0] === 'top-left' && corners[1] === 'top-right') return 'top';else if (corners[0] === 'bottom-left' && corners[1] === 'top-right') return 'top-left';else if (corners[0] === 'bottom-left' && corners[1] === 'top-left') return 'left';else if (corners[0] === 'bottom-right' && corners[1] === 'top-left') return 'bottom-left';else if (corners[0] === 'bottom-right' && corners[1] === 'bottom-left') return 'bottom';else if (corners[0] === 'top-right' && corners[1] === 'bottom-left') return 'bottom-right'; } function bullseye(corners, boundaries, mousePosition) { switch (side(corners)) { case 'right': return { x: boundaries[0].x, y: mousePosition.y }; case 'top-right': return { x: boundaries[1].x, y: boundaries[0].y }; case 'top': return { x: mousePosition.x, y: boundaries[0].y }; case 'top-left': return { x: boundaries[0].x, y: boundaries[1].y }; case 'left': return { x: boundaries[0].x, y: mousePosition.y }; case 'bottom-left': return { x: boundaries[1].x, y: boundaries[0].y }; case 'bottom': return { x: mousePosition.x, y: boundaries[0].y }; case 'bottom-right': return { x: boundaries[0].x, y: boundaries[1].y }; } } function formatPoints(points) { var finalPoints = []; for (var i = 0, len = points.length; i < len; ++i) { finalPoints.push([points[i].x, points[i].y]); } return finalPoints; } function aiming(e, mousePosition, prevMousePosition, target, alreadyAiming) { if (!prevMousePosition) return false;else if (!alreadyAiming && mousePosition.x === prevMousePosition.x && mousePosition.y === prevMousePosition.y) { return false; } var corners = (0, _corners2.default)(e, target); var bound = (0, _corners.boundaries)(corners, prevMousePosition, target); if ((0, _pointInPolygon2.default)([mousePosition.x, mousePosition.y], formatPoints(bound))) { var dist = Math.round(distance(mousePosition, bullseye(corners, bound, mousePosition))); return Math.max(dist, 1); } return false; }