path.mjs 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. // @ts-nocheck
  2. /* eslint-disable */
  3. // import { checkCollinear, getDistance, moveTo } from './math'
  4. /**
  5. * From https://github.com/unsplash/react-trend/blob/master/src/helpers/DOM.helpers.js#L18
  6. */
  7. export function genPath(points, radius) {
  8. let fill = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false;
  9. let height = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : 75;
  10. if (points.length === 0) return '';
  11. const start = points.shift();
  12. const end = points[points.length - 1];
  13. return (fill ? `M${start.x} ${height - start.x + 2} L${start.x} ${start.y}` : `M${start.x} ${start.y}`) + points.map((point, index) => {
  14. const next = points[index + 1];
  15. const prev = points[index - 1] || start;
  16. const isCollinear = next && checkCollinear(next, point, prev);
  17. if (!next || isCollinear) {
  18. return `L${point.x} ${point.y}`;
  19. }
  20. const threshold = Math.min(getDistance(prev, point), getDistance(next, point));
  21. const isTooCloseForRadius = threshold / 2 < radius;
  22. const radiusForPoint = isTooCloseForRadius ? threshold / 2 : radius;
  23. const before = moveTo(prev, point, radiusForPoint);
  24. const after = moveTo(next, point, radiusForPoint);
  25. return `L${before.x} ${before.y}S${point.x} ${point.y} ${after.x} ${after.y}`;
  26. }).join('') + (fill ? `L${end.x} ${height - start.x + 2} Z` : '');
  27. }
  28. function int(value) {
  29. return parseInt(value, 10);
  30. }
  31. /**
  32. * https://en.wikipedia.org/wiki/Collinearity
  33. * x=(x1+x2)/2
  34. * y=(y1+y2)/2
  35. */
  36. export function checkCollinear(p0, p1, p2) {
  37. return int(p0.x + p2.x) === int(2 * p1.x) && int(p0.y + p2.y) === int(2 * p1.y);
  38. }
  39. export function getDistance(p1, p2) {
  40. return Math.sqrt(Math.pow(p2.x - p1.x, 2) + Math.pow(p2.y - p1.y, 2));
  41. }
  42. export function moveTo(to, from, radius) {
  43. const vector = {
  44. x: to.x - from.x,
  45. y: to.y - from.y
  46. };
  47. const length = Math.sqrt(vector.x * vector.x + vector.y * vector.y);
  48. const unitVector = {
  49. x: vector.x / length,
  50. y: vector.y / length
  51. };
  52. return {
  53. x: from.x + unitVector.x * radius,
  54. y: from.y + unitVector.y * radius
  55. };
  56. }
  57. //# sourceMappingURL=path.mjs.map