├── .babelrc ├── CHANGELOG.md ├── test ├── beziers.ts ├── interpolation.test.ts ├── box.test.ts ├── path.test.ts └── __snapshots__ │ └── path.test.ts.snap ├── .parcelrc ├── src ├── index.ts ├── types.ts ├── box.ts ├── interpolation.ts └── path.ts ├── .eslintrc.js ├── tsconfig.json ├── .github └── workflows │ └── ci.yml ├── LICENSE ├── package.json ├── README.md ├── .gitignore └── jest.config.ts /.babelrc: -------------------------------------------------------------------------------- 1 | { 2 | "presets": ["@babel/preset-env", "@babel/preset-typescript"] 3 | } 4 | -------------------------------------------------------------------------------- /CHANGELOG.md: -------------------------------------------------------------------------------- 1 | # 0.1.0 2 | 3 | - Initial Release! 4 | - No options to manipulate the control points for now. Soon. 5 | -------------------------------------------------------------------------------- /test/beziers.ts: -------------------------------------------------------------------------------- 1 | export const easeInOutCubic = { 2 | start: { x: 0, y: 100 }, 3 | control1: { x: 65, y: 0 }, 4 | control2: { x: 35, y: 1 }, 5 | end: { x: 100, y: 100 } 6 | } 7 | -------------------------------------------------------------------------------- /.parcelrc: -------------------------------------------------------------------------------- 1 | { 2 | "extends": "@parcel/config-default", 3 | "transformers": { 4 | "*.{js,mjs,jsx,cjs,ts,tsx}": [ 5 | "@parcel/transformer-js", 6 | "@parcel/transformer-react-refresh-wrap" 7 | ] 8 | } 9 | } 10 | -------------------------------------------------------------------------------- /src/index.ts: -------------------------------------------------------------------------------- 1 | export type { Box, Point, CubicBezier } from './types' 2 | export { getBoxToBoxCurve, getCurve, getCubicBezierSVGPath } from './path' 3 | export { interpolateCubicBezier, interpolateCubicBezierAngle } from './interpolation' 4 | -------------------------------------------------------------------------------- /src/types.ts: -------------------------------------------------------------------------------- 1 | export interface Point { 2 | x: number; 3 | y: number; 4 | } 5 | 6 | export interface Box { 7 | x: number; 8 | y: number; 9 | w: number; 10 | h: number; 11 | } 12 | 13 | export interface CubicBezier { 14 | start: Point; 15 | control1: Point; 16 | control2: Point; 17 | end: Point; 18 | } 19 | -------------------------------------------------------------------------------- /.eslintrc.js: -------------------------------------------------------------------------------- 1 | module.exports = { 2 | env: { 3 | browser: true, 4 | es2021: true, 5 | node: true, 6 | 'jest/globals': true 7 | }, 8 | extends: [ 9 | 'standard' 10 | ], 11 | parser: '@typescript-eslint/parser', 12 | parserOptions: { 13 | ecmaVersion: 'latest', 14 | sourceType: 'module' 15 | }, 16 | plugins: [ 17 | '@typescript-eslint', 18 | 'jest' 19 | ], 20 | rules: { 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /tsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "include": ["src", "types"], 3 | "compilerOptions": { 4 | "target": "esnext", 5 | "module": "esnext", 6 | "moduleResolution": "node", 7 | "lib": ["dom", "esnext"], 8 | "strict": true, 9 | "noUnusedLocals": true, 10 | "noUnusedParameters": true, 11 | "noImplicitReturns": true, 12 | "noFallthroughCasesInSwitch": true, 13 | "baseUrl": "./", 14 | "paths": { 15 | "*": ["src/*", "node_modules/*"] 16 | }, 17 | "esModuleInterop": true, 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /.github/workflows/ci.yml: -------------------------------------------------------------------------------- 1 | name: build 2 | 3 | on: [push] 4 | 5 | jobs: 6 | build: 7 | runs-on: ubuntu-latest 8 | steps: 9 | - uses: actions/checkout@v1 10 | - uses: actions/setup-node@v1 11 | with: 12 | node-version: 17.6.0 13 | 14 | - name: List Versions 15 | run: | 16 | node --version 17 | npm --version 18 | 19 | - name: Install Dependencies 20 | run: npm ci 21 | 22 | - name: Run Tests & Lint 23 | run: | 24 | npm test 25 | npm run lint 26 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2022 [Kristian Muñiz](https://krismuniz.com) 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /test/interpolation.test.ts: -------------------------------------------------------------------------------- 1 | import { interpolateCubicBezier, interpolateCubicBezierAngle } from '../src/interpolation' 2 | import { easeInOutCubic } from './beziers' 3 | 4 | describe('interpolateCubicBezier', function () { 5 | it('correctly interpolates a cubic bezier', function () { 6 | expect(interpolateCubicBezier(easeInOutCubic, 0)).toEqual({ x: 0, y: 100 }) 7 | expect(interpolateCubicBezier(easeInOutCubic, 0.25)).toEqual({ x: 33.90625, y: 43.890625 }) 8 | expect(interpolateCubicBezier(easeInOutCubic, 0.5)).toEqual({ x: 50, y: 25.375 }) 9 | expect(interpolateCubicBezier(easeInOutCubic, 0.75)).toEqual({ x: 66.09375, y: 44.171875 }) 10 | expect(interpolateCubicBezier(easeInOutCubic, 1)).toEqual({ x: 100, y: 100 }) 11 | }) 12 | }) 13 | 14 | describe('interpolateCubicBezierAngle', function () { 15 | it('correctly interpolates a cubic bezier and gets its angle', function () { 16 | expect(interpolateCubicBezierAngle(easeInOutCubic, 0)).toBeCloseTo(-56.9761, 4) 17 | expect(interpolateCubicBezierAngle(easeInOutCubic, 0.25)).toBeCloseTo(-59.4086, 4) 18 | expect(interpolateCubicBezierAngle(easeInOutCubic, 0.5)).toBeCloseTo(0.8185, 4) 19 | expect(interpolateCubicBezierAngle(easeInOutCubic, 0.75)).toBeCloseTo(59.47166, 4) 20 | expect(interpolateCubicBezierAngle(easeInOutCubic, 1)).toBeCloseTo(56.7125, 4) 21 | }) 22 | }) 23 | -------------------------------------------------------------------------------- /test/box.test.ts: -------------------------------------------------------------------------------- 1 | import { getBoxBounds, getIdealBoxSides, isPointOnLeftOrRightSide } from '../src/box' 2 | 3 | describe('getBoxBounds', function () { 4 | it('properly returns all bounds of a rectangle', function () { 5 | expect(getBoxBounds({ x: 0, y: 0, w: 10, h: 10 })).toEqual([ 6 | { x: 0, y: 5 }, 7 | { x: 10, y: 5 }, 8 | { x: 5, y: 0 }, 9 | { x: 5, y: 10 } 10 | ]) 11 | }) 12 | }) 13 | 14 | describe('getIdealBoxSides', function () { 15 | it('properly finds the ideal points to draw a path from/to', function () { 16 | expect(getIdealBoxSides({ x: 2, y: 18, w: 4, h: 4 }, { x: 18, y: 2, w: 4, h: 4 })).toEqual({ 17 | startPoint: { x: 6, y: 20 }, // right side 18 | endPoint: { x: 20, y: 6 } // bottom side 19 | }) 20 | 21 | expect(getIdealBoxSides({ x: 2, y: 13, w: 4, h: 4 }, { x: 18, y: 13, w: 4, h: 4 })).toEqual({ 22 | startPoint: { x: 6, y: 15 }, // right side 23 | endPoint: { x: 18, y: 15 } // left side 24 | }) 25 | }) 26 | }) 27 | 28 | describe('isPointOnLeftOrRightSide', function () { 29 | it('properly detects when a point is on the left/right side of a box', function () { 30 | expect(isPointOnLeftOrRightSide({ x: 0, y: 2 }, { x: 0, y: 0, w: 4, h: 4 })).toEqual(true) // left side 31 | expect(isPointOnLeftOrRightSide({ x: 4, y: 2 }, { x: 0, y: 0, w: 4, h: 4 })).toEqual(true) // right side 32 | expect(isPointOnLeftOrRightSide({ x: 2, y: 0 }, { x: 0, y: 0, w: 4, h: 4 })).toEqual(false) // top side 33 | expect(isPointOnLeftOrRightSide({ x: 2, y: 4 }, { x: 0, y: 0, w: 4, h: 4 })).toEqual(false) // bottom side 34 | }) 35 | }) 36 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "proto-arrows", 3 | "version": "0.1.3", 4 | "description": "Utility functions for drawing beautiful arrows using cubic bezier paths", 5 | "source": "src/index.ts", 6 | "main": "dist/index.js", 7 | "module": "dist/module.js", 8 | "types": "dist/types.d.ts", 9 | "scripts": { 10 | "lint": "eslint src/**/*.ts", 11 | "watch": "parcel watch", 12 | "build": "parcel build", 13 | "test": "jest", 14 | "prepare": "npm run build", 15 | "release": "npm run lint && npm run test && git commit -am $npm_package_version && git tag $npm_package_version && git push && git push --tags && npm publish" 16 | }, 17 | "keywords": [ 18 | "arrow", 19 | "path", 20 | "cubic-bezier", 21 | "prototyping", 22 | "svg" 23 | ], 24 | "author": "Kristian Muñiz (https://krismuniz.com)", 25 | "homepage": "https://github.com/krismuniz/proto-arrows", 26 | "repository": { 27 | "type": "git", 28 | "url": "https://github.com/krismuniz/proto-arrows" 29 | }, 30 | "files": [ 31 | "dist", 32 | "src" 33 | ], 34 | "license": "MIT", 35 | "devDependencies": { 36 | "@babel/core": "^7.17.5", 37 | "@babel/preset-env": "^7.16.11", 38 | "@babel/preset-typescript": "^7.16.7", 39 | "@parcel/packager-ts": "^2.3.2", 40 | "@parcel/transformer-typescript-types": "^2.3.2", 41 | "@types/jest": "^27.4.1", 42 | "@typescript-eslint/eslint-plugin": "^5.13.0", 43 | "@typescript-eslint/parser": "^5.13.0", 44 | "eslint": "^7.32.0", 45 | "eslint-config-standard": "^16.0.3", 46 | "eslint-plugin-import": "^2.25.4", 47 | "eslint-plugin-jest": "^26.1.1", 48 | "eslint-plugin-node": "^11.1.0", 49 | "eslint-plugin-promise": "^5.2.0", 50 | "jest": "^27.5.1", 51 | "parcel": "^2.3.2", 52 | "ts-node": "^10.7.0", 53 | "typescript": "^4.6.2" 54 | } 55 | } 56 | -------------------------------------------------------------------------------- /test/path.test.ts: -------------------------------------------------------------------------------- 1 | import { getBoxToBoxCurve, getCubicBezierSVGPath, getCurve, getLineCenter } from '../src/path' 2 | import { easeInOutCubic } from './beziers' 3 | 4 | describe('getLineCenter', function () { 5 | it('properly gets the center point using linear interpolation', function () { 6 | expect(getLineCenter({ x: 0, y: 0 }, { x: 10, y: 10 })).toEqual({ x: 5, y: 5 }) 7 | expect(getLineCenter({ x: 0, y: 0 }, { x: -10, y: -10 })).toEqual({ x: -5, y: -5 }) 8 | expect(getLineCenter({ x: 0, y: 0 }, { x: 0, y: 10 })).toEqual({ x: 0, y: 5 }) 9 | expect(getLineCenter({ x: 0, y: 0 }, { x: 10, y: 0 })).toEqual({ x: 5, y: 0 }) 10 | }) 11 | }) 12 | 13 | describe('getCubicBezierSVGPath', function () { 14 | it('returns a proper svg path in the correct format', function () { 15 | expect(getCubicBezierSVGPath(easeInOutCubic)).toEqual('M0,100 C65,0 35,1 100,100') 16 | }) 17 | }) 18 | 19 | describe('getCurve', function () { 20 | it('returns the right curve given two points', function () { 21 | expect(getCurve({ x: 0, y: 0 }, { x: 10, y: 10 })).toMatchSnapshot() 22 | expect(getCurve({ x: 0, y: 0 }, { x: -10, y: -10 })).toMatchSnapshot() 23 | expect(getCurve({ x: 0, y: 0 }, { x: 0, y: 10 })).toMatchSnapshot() 24 | expect(getCurve({ x: 0, y: 0 }, { x: 10, y: 0 })).toMatchSnapshot() 25 | }) 26 | }) 27 | 28 | describe('getBoxToBoxCurve', function () { 29 | it('returns the right curve given two boxes', function () { 30 | expect(getBoxToBoxCurve({ x: 0, y: 0, w: 4, h: 4 }, { x: 0, y: 0, w: 4, h: 4 })).toMatchSnapshot() 31 | // on the right side of the other box 32 | expect(getBoxToBoxCurve({ x: 0, y: 0, w: 4, h: 4 }, { x: 4, y: 0, w: 4, h: 4 })).toMatchSnapshot() 33 | // above the other one 34 | expect(getBoxToBoxCurve({ x: 0, y: 0, w: 4, h: 4 }, { x: 0, y: -4, w: 4, h: 4 })).toMatchSnapshot() 35 | // below the other one 36 | expect(getBoxToBoxCurve({ x: 0, y: 0, w: 4, h: 4 }, { x: 0, y: 4, w: 4, h: 4 })).toMatchSnapshot() 37 | // left side of the other box 38 | expect(getBoxToBoxCurve({ x: 0, y: 0, w: 4, h: 4 }, { x: -4, y: 0, w: 4, h: 4 })).toMatchSnapshot() 39 | }) 40 | }) 41 | -------------------------------------------------------------------------------- /src/box.ts: -------------------------------------------------------------------------------- 1 | import { Box, Point } from './types' 2 | 3 | /** 4 | * Get a list of points set up at the center 5 | * of every side of the box (left, right, top, bottom) 6 | */ 7 | export function getBoxBounds (box: Box): [Point, Point, Point, Point] { 8 | return [ 9 | { x: box.x, y: box.y + box.h / 2 }, // left 10 | { x: box.x + box.w, y: box.y + box.h / 2 }, // right 11 | { x: box.x + box.w / 2, y: box.y }, // top 12 | { x: box.x + box.w / 2, y: box.y + box.h } // bottom 13 | ] 14 | } 15 | 16 | export function euclideanDistance (pointA: Point, pointB: Point): number { 17 | return Math.hypot(pointA.x - pointB.x, pointA.y - pointB.y) 18 | } 19 | 20 | export function xDistance (pointA: Point, pointB: Point): number { 21 | return Math.abs(pointA.x - pointB.x) 22 | } 23 | 24 | export function yDistance (pointA: Point, pointB: Point): number { 25 | return Math.abs(pointA.y - pointB.y) 26 | } 27 | 28 | /** 29 | * Find the ideal points to draw an edge 30 | * between the two boxes by finding the 31 | * shortest linear distance between the 32 | * two. 33 | */ 34 | export function getIdealBoxSides ( 35 | startBox: Box, 36 | endBox: Box 37 | ): { 38 | startPoint: Point 39 | endPoint: Point 40 | } { 41 | const startPts = getBoxBounds(startBox) 42 | const endPts = getBoxBounds(endBox) 43 | 44 | let minDistanceSource: [number, Point] = [Infinity, { x: 0, y: 0 }] 45 | let minDistanceTarget: [number, Point] = [Infinity, { x: 0, y: 0 }] 46 | 47 | for (const pointA of startPts) { 48 | for (const pointB of endPts) { 49 | const distance = euclideanDistance(pointA, pointB) 50 | 51 | if (distance < minDistanceSource[0]) { 52 | minDistanceSource = [distance, pointA] 53 | } 54 | 55 | if (distance < minDistanceTarget[0]) { 56 | minDistanceTarget = [distance, pointB] 57 | } 58 | } 59 | } 60 | 61 | return { 62 | startPoint: minDistanceSource[1], 63 | endPoint: minDistanceTarget[1] 64 | } 65 | } 66 | 67 | /** 68 | * Infer if a point is on the left or right side of a box 69 | */ 70 | export function isPointOnLeftOrRightSide (point: Point, box: Box): boolean { 71 | return point.x === box.x || point.x === box.x + box.w 72 | } 73 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # `proto-arrows` 2 | 3 | [![License:MIT](https://img.shields.io/badge/license-MIT-blue.svg)](http://opensource.org/licenses/MIT) [![build](https://github.com/krismuniz/proto-arrows/actions/workflows/ci.yml/badge.svg)](https://github.com/krismuniz/proto-arrows/actions/workflows/ci.yml) ![Type Declarations](https://img.shields.io/npm/types/combi.svg) 4 | 5 | 6 | 7 | A set of utility functions for drawing beautiful arrows using cubic bezier paths. Inspired by [`perfect-arrows`](https://github.com/steveruizok/perfect-arrows). 8 | 9 | Why `proto-arrows`? Because cubic bezier curves look delicious for prototyping software like Sketch or Figma. So, why not make a library that simplifies the process of drawing them too? 10 | 11 | ## Example Usage 12 | 13 | ### An Arrow component in React 14 | 15 | ```tsx 16 | import React from 'react' 17 | import { 18 | getCurve, 19 | interpolateCubicBezierAngle, 20 | getCubicBezierSVGPath, 21 | } from 'proto-arrows' 22 | 23 | export function Arrow() { 24 | const curve = getCurve({ x: 128, y: 128 }, { x: 256, y: 256 }) 25 | const svgPath = getCubicBezierSVGPath(curve) 26 | const endAngle = interpolateCubicBezierAngle(curve, 1) 27 | 28 | return ( 29 | 36 | 37 | 38 | 42 | 43 | ) 44 | } 45 | ``` 46 | 47 | ## Special Thanks 48 | 49 | * [Steve Ruiz - (steveruizok)](https://github.com/steveruizok) for building the [`perfect-arrows` (MIT)](https://github.com/steveruizok/perfect-arrows) library, which inspired this library. 50 | 51 | * [Peter Beshai - (pbeshai)](https://github.com/pbeshai) for building [`vis-utils` (MIT)](https://github.com/pbeshai/vis-utils), from which I borrowed the interpolation functions for cubic bezier paths. 52 | -------------------------------------------------------------------------------- /src/interpolation.ts: -------------------------------------------------------------------------------- 1 | import { CubicBezier, Point } from './types' 2 | 3 | /** 4 | * Given the definition of a cubic bezier: a start point, two control points, 5 | * and end point, get the point at a given time `t` (where `0 <= t <= 1`). 6 | * 7 | * For example, at t = 0, this function returns the point at the start of the 8 | * curve, at t = 0.5, it returns the point midway through the curve and at 9 | * t = 1 it returns the point at the end of the curve. 10 | * 11 | * B(t) = (1 - t)^3P0 + 3(1 - t)^2tP1 + 3(1 - t)t^2P2 + t^3P3 12 | * Adapted from https://github.com/pbeshai/vis-utils 13 | */ 14 | export function interpolateCubicBezier ({ 15 | start, 16 | control1, 17 | control2, 18 | end 19 | }: CubicBezier, t: number): Point { 20 | /** 21 | * Get the point on the curve at a given t, 22 | * where t is a number between 0 and 1. 23 | * 24 | * 0 is the start point, 1 is the end point. 25 | */ 26 | return { 27 | x: Math.pow(1 - t, 3) * start.x + 28 | 3 * Math.pow(1 - t, 2) * t * control1.x + 29 | 3 * (1 - t) * Math.pow(t, 2) * control2.x + 30 | Math.pow(t, 3) * end.x, 31 | y: Math.pow(1 - t, 3) * start.y + 32 | 3 * Math.pow(1 - t, 2) * t * control1.y + 33 | 3 * (1 - t) * Math.pow(t, 2) * control2.y + 34 | Math.pow(t, 3) * end.y 35 | } 36 | } 37 | 38 | /** 39 | * Given the definition of a cubic bezier: a start point, two control points, 40 | * and end point, get the angle at a given time `t` (where `0 <= t <= 1`). 41 | * 42 | * For example, at t = 0, this function returns the angle at the start 43 | * point, at t = 0.5, it returns the angle midway through the curve and at 44 | * t = 1 it returns the angle at the end of the curve (useful for things like 45 | * arrowheads). The angles are in degrees. 46 | * 47 | * B'(t) = 3(1- t)^2(P1 - P0) + 6(1 - t)t(P2 - P1) + 3t^2(P3 - P2) 48 | * 49 | * Adapted from https://github.com/pbeshai/vis-utils 50 | */ 51 | export function interpolateCubicBezierAngle ({ 52 | start, 53 | control1, 54 | control2, 55 | end 56 | }: CubicBezier, t: number) { 57 | /** 58 | * Get the angle of the point on the curve at a given t, 59 | * where t is a number between 0 and 1. 60 | * 61 | * 0 is the start point, 1 is the end point. 62 | */ 63 | const tangentX = 3 * Math.pow(1 - t, 2) * (control1.x - start.x) + 64 | 6 * (1 - t) * t * (control2.x - control1.x) + 65 | 3 * Math.pow(t, 2) * (end.x - control2.x) 66 | const tangentY = 3 * Math.pow(1 - t, 2) * (control1.y - start.y) + 67 | 6 * (1 - t) * t * (control2.y - control1.y) + 68 | 3 * Math.pow(t, 2) * (end.y - control2.y) 69 | 70 | return Math.atan2(tangentY, tangentX) * (180 / Math.PI) 71 | } 72 | -------------------------------------------------------------------------------- /src/path.ts: -------------------------------------------------------------------------------- 1 | import { Box, CubicBezier, Point } from './types' 2 | import { getIdealBoxSides, isPointOnLeftOrRightSide } from './box' 3 | 4 | /** 5 | * Find the center of two points using rudimentary 6 | * linear interpolation. 7 | */ 8 | export function getLineCenter (pointA: Point, pointB: Point): Point { 9 | return { 10 | x: (pointA.x + pointB.x) / 2, 11 | y: (pointA.y + pointB.y) / 2 12 | } 13 | } 14 | 15 | /** 16 | * Given a cubic bezier curve, produce its corresponding 17 | * SVG path string. 18 | */ 19 | export function getCubicBezierSVGPath (bezier: CubicBezier): string { 20 | const { start, control1, control2, end } = bezier 21 | 22 | return [ 23 | `M${start.x},${start.y}`, 24 | `C${control1.x},${control1.y} ${control2.x},${control2.y}`, 25 | `${end.x},${end.y}` 26 | ].join(' ') 27 | } 28 | 29 | /** 30 | * Controls how "curvy" the path is by offsetting 31 | * the control points from the ideal points. 32 | */ 33 | const CONTROL_POINT_OFFSET_RATE = 0.75 34 | 35 | /** 36 | * Given two points, produce a cubic bezier curve that 37 | * links them. 38 | */ 39 | export function getCurve (start: Point, end: Point, options?: { flip?: boolean }): CubicBezier { 40 | const dX = (end.x - start.x) * (options?.flip ? CONTROL_POINT_OFFSET_RATE : 0) 41 | const dY = (end.y - start.y) * (options?.flip ? 0 : -CONTROL_POINT_OFFSET_RATE) 42 | 43 | const controlPoints: [Point, Point] = 44 | options?.flip 45 | ? [ 46 | { 47 | x: start.x + dX, 48 | y: start.y - dY 49 | }, 50 | { 51 | x: end.x - dX, 52 | y: end.y + dY 53 | } 54 | ] 55 | : [ 56 | { 57 | x: start.x + dX, 58 | y: start.y - dY 59 | }, 60 | { 61 | x: end.x - dX, 62 | y: end.y + dY 63 | } 64 | ] 65 | 66 | return { start: start, control1: controlPoints[0], control2: controlPoints[1], end: end } 67 | } 68 | 69 | /** 70 | * Given two boxes, produce a cubic bezier curve that 71 | * links them. 72 | */ 73 | export function getBoxToBoxCurve (startBox: Box, endBox: Box): CubicBezier { 74 | const { startPoint, endPoint } = getIdealBoxSides(startBox, endBox) 75 | 76 | return getCurve( 77 | startPoint, 78 | endPoint, 79 | { 80 | // Flip the curve if the `startPoint` is on the left/right 81 | // side of the `startBox` AND the `endPoint` is on the 82 | // left/right side of the `endBox`. 83 | // 84 | // In the future we'll make this an option. 85 | flip: isPointOnLeftOrRightSide(startPoint, startBox) && 86 | isPointOnLeftOrRightSide(endPoint, endBox) 87 | } 88 | ) 89 | } 90 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Logs 2 | logs 3 | *.log 4 | npm-debug.log* 5 | yarn-debug.log* 6 | yarn-error.log* 7 | lerna-debug.log* 8 | .pnpm-debug.log* 9 | 10 | # Diagnostic reports (https://nodejs.org/api/report.html) 11 | report.[0-9]*.[0-9]*.[0-9]*.[0-9]*.json 12 | 13 | # Runtime data 14 | pids 15 | *.pid 16 | *.seed 17 | *.pid.lock 18 | 19 | # Directory for instrumented libs generated by jscoverage/JSCover 20 | lib-cov 21 | 22 | # Coverage directory used by tools like istanbul 23 | coverage 24 | *.lcov 25 | 26 | # nyc test coverage 27 | .nyc_output 28 | 29 | # Grunt intermediate storage (https://gruntjs.com/creating-plugins#storing-task-files) 30 | .grunt 31 | 32 | # Bower dependency directory (https://bower.io/) 33 | bower_components 34 | 35 | # node-waf configuration 36 | .lock-wscript 37 | 38 | # Compiled binary addons (https://nodejs.org/api/addons.html) 39 | build/Release 40 | 41 | # Dependency directories 42 | node_modules/ 43 | jspm_packages/ 44 | 45 | # Snowpack dependency directory (https://snowpack.dev/) 46 | web_modules/ 47 | 48 | # TypeScript cache 49 | *.tsbuildinfo 50 | 51 | # Optional npm cache directory 52 | .npm 53 | 54 | # Optional eslint cache 55 | .eslintcache 56 | 57 | # Optional stylelint cache 58 | .stylelintcache 59 | 60 | # Microbundle cache 61 | .rpt2_cache/ 62 | .rts2_cache_cjs/ 63 | .rts2_cache_es/ 64 | .rts2_cache_umd/ 65 | 66 | # Optional REPL history 67 | .node_repl_history 68 | 69 | # Output of 'npm pack' 70 | *.tgz 71 | 72 | # Yarn Integrity file 73 | .yarn-integrity 74 | 75 | # dotenv environment variable files 76 | .env 77 | .env.development.local 78 | .env.test.local 79 | .env.production.local 80 | .env.local 81 | 82 | # parcel-bundler cache (https://parceljs.org/) 83 | .cache 84 | .parcel-cache 85 | 86 | # Next.js build output 87 | .next 88 | out 89 | 90 | # Nuxt.js build / generate output 91 | .nuxt 92 | dist 93 | 94 | # Gatsby files 95 | .cache/ 96 | # Comment in the public line in if your project uses Gatsby and not Next.js 97 | # https://nextjs.org/blog/next-9-1#public-directory-support 98 | # public 99 | 100 | # vuepress build output 101 | .vuepress/dist 102 | 103 | # vuepress v2.x temp and cache directory 104 | .temp 105 | .cache 106 | 107 | # Docusaurus cache and generated files 108 | .docusaurus 109 | 110 | # Serverless directories 111 | .serverless/ 112 | 113 | # FuseBox cache 114 | .fusebox/ 115 | 116 | # DynamoDB Local files 117 | .dynamodb/ 118 | 119 | # TernJS port file 120 | .tern-port 121 | 122 | # Stores VSCode versions used for testing VSCode extensions 123 | .vscode-test 124 | 125 | # yarn v2 126 | .yarn/cache 127 | .yarn/unplugged 128 | .yarn/build-state.yml 129 | .yarn/install-state.gz 130 | .pnp.* 131 | -------------------------------------------------------------------------------- /test/__snapshots__/path.test.ts.snap: -------------------------------------------------------------------------------- 1 | // Jest Snapshot v1, https://goo.gl/fbAQLP 2 | 3 | exports[`getBoxToBoxCurve returns the right curve given two boxes 1`] = ` 4 | Object { 5 | "control1": Object { 6 | "x": 0, 7 | "y": 2, 8 | }, 9 | "control2": Object { 10 | "x": 0, 11 | "y": 2, 12 | }, 13 | "end": Object { 14 | "x": 0, 15 | "y": 2, 16 | }, 17 | "start": Object { 18 | "x": 0, 19 | "y": 2, 20 | }, 21 | } 22 | `; 23 | 24 | exports[`getBoxToBoxCurve returns the right curve given two boxes 2`] = ` 25 | Object { 26 | "control1": Object { 27 | "x": 4, 28 | "y": 2, 29 | }, 30 | "control2": Object { 31 | "x": 4, 32 | "y": 2, 33 | }, 34 | "end": Object { 35 | "x": 4, 36 | "y": 2, 37 | }, 38 | "start": Object { 39 | "x": 4, 40 | "y": 2, 41 | }, 42 | } 43 | `; 44 | 45 | exports[`getBoxToBoxCurve returns the right curve given two boxes 3`] = ` 46 | Object { 47 | "control1": Object { 48 | "x": 2, 49 | "y": 0, 50 | }, 51 | "control2": Object { 52 | "x": 2, 53 | "y": 0, 54 | }, 55 | "end": Object { 56 | "x": 2, 57 | "y": 0, 58 | }, 59 | "start": Object { 60 | "x": 2, 61 | "y": 0, 62 | }, 63 | } 64 | `; 65 | 66 | exports[`getBoxToBoxCurve returns the right curve given two boxes 4`] = ` 67 | Object { 68 | "control1": Object { 69 | "x": 2, 70 | "y": 4, 71 | }, 72 | "control2": Object { 73 | "x": 2, 74 | "y": 4, 75 | }, 76 | "end": Object { 77 | "x": 2, 78 | "y": 4, 79 | }, 80 | "start": Object { 81 | "x": 2, 82 | "y": 4, 83 | }, 84 | } 85 | `; 86 | 87 | exports[`getBoxToBoxCurve returns the right curve given two boxes 5`] = ` 88 | Object { 89 | "control1": Object { 90 | "x": 0, 91 | "y": 2, 92 | }, 93 | "control2": Object { 94 | "x": 0, 95 | "y": 2, 96 | }, 97 | "end": Object { 98 | "x": 0, 99 | "y": 2, 100 | }, 101 | "start": Object { 102 | "x": 0, 103 | "y": 2, 104 | }, 105 | } 106 | `; 107 | 108 | exports[`getCurve returns the right curve given two points 1`] = ` 109 | Object { 110 | "control1": Object { 111 | "x": 0, 112 | "y": 7.5, 113 | }, 114 | "control2": Object { 115 | "x": 10, 116 | "y": 2.5, 117 | }, 118 | "end": Object { 119 | "x": 10, 120 | "y": 10, 121 | }, 122 | "start": Object { 123 | "x": 0, 124 | "y": 0, 125 | }, 126 | } 127 | `; 128 | 129 | exports[`getCurve returns the right curve given two points 2`] = ` 130 | Object { 131 | "control1": Object { 132 | "x": 0, 133 | "y": -7.5, 134 | }, 135 | "control2": Object { 136 | "x": -10, 137 | "y": -2.5, 138 | }, 139 | "end": Object { 140 | "x": -10, 141 | "y": -10, 142 | }, 143 | "start": Object { 144 | "x": 0, 145 | "y": 0, 146 | }, 147 | } 148 | `; 149 | 150 | exports[`getCurve returns the right curve given two points 3`] = ` 151 | Object { 152 | "control1": Object { 153 | "x": 0, 154 | "y": 7.5, 155 | }, 156 | "control2": Object { 157 | "x": 0, 158 | "y": 2.5, 159 | }, 160 | "end": Object { 161 | "x": 0, 162 | "y": 10, 163 | }, 164 | "start": Object { 165 | "x": 0, 166 | "y": 0, 167 | }, 168 | } 169 | `; 170 | 171 | exports[`getCurve returns the right curve given two points 4`] = ` 172 | Object { 173 | "control1": Object { 174 | "x": 0, 175 | "y": 0, 176 | }, 177 | "control2": Object { 178 | "x": 10, 179 | "y": 0, 180 | }, 181 | "end": Object { 182 | "x": 10, 183 | "y": 0, 184 | }, 185 | "start": Object { 186 | "x": 0, 187 | "y": 0, 188 | }, 189 | } 190 | `; 191 | -------------------------------------------------------------------------------- /jest.config.ts: -------------------------------------------------------------------------------- 1 | /* 2 | * For a detailed explanation regarding each configuration property and type check, visit: 3 | * https://jestjs.io/docs/configuration 4 | */ 5 | 6 | export default { 7 | // All imported modules in your tests should be mocked automatically 8 | // automock: false, 9 | 10 | // Stop running tests after `n` failures 11 | // bail: 0, 12 | 13 | // The directory where Jest should store its cached dependency information 14 | // cacheDirectory: "/private/var/folders/kh/nwk8xkf971v4tgsd82m3mh0c0000gn/T/jest_dx", 15 | 16 | // Automatically clear mock calls, instances and results before every test 17 | clearMocks: true, 18 | 19 | // Indicates whether the coverage information should be collected while executing the test 20 | collectCoverage: true, 21 | 22 | // An array of glob patterns indicating a set of files for which coverage information should be collected 23 | // collectCoverageFrom: undefined, 24 | 25 | // The directory where Jest should output its coverage files 26 | coverageDirectory: 'coverage', 27 | 28 | // An array of regexp pattern strings used to skip coverage collection 29 | // coveragePathIgnorePatterns: [ 30 | // "/node_modules/" 31 | // ], 32 | 33 | // Indicates which provider should be used to instrument code for coverage 34 | // coverageProvider: "babel", 35 | 36 | // A list of reporter names that Jest uses when writing coverage reports 37 | // coverageReporters: [ 38 | // "json", 39 | // "text", 40 | // "lcov", 41 | // "clover" 42 | // ], 43 | 44 | // An object that configures minimum threshold enforcement for coverage results 45 | // coverageThreshold: undefined, 46 | 47 | // A path to a custom dependency extractor 48 | // dependencyExtractor: undefined, 49 | 50 | // Make calling deprecated APIs throw helpful error messages 51 | // errorOnDeprecated: false, 52 | 53 | // Force coverage collection from ignored files using an array of glob patterns 54 | // forceCoverageMatch: [], 55 | 56 | // A path to a module which exports an async function that is triggered once before all test suites 57 | // globalSetup: undefined, 58 | 59 | // A path to a module which exports an async function that is triggered once after all test suites 60 | // globalTeardown: undefined, 61 | 62 | // A set of global variables that need to be available in all test environments 63 | // globals: {}, 64 | 65 | // The maximum amount of workers used to run your tests. Can be specified as % or a number. E.g. maxWorkers: 10% will use 10% of your CPU amount + 1 as the maximum worker number. maxWorkers: 2 will use a maximum of 2 workers. 66 | // maxWorkers: "50%", 67 | 68 | // An array of directory names to be searched recursively up from the requiring module's location 69 | // moduleDirectories: [ 70 | // "node_modules" 71 | // ], 72 | 73 | // An array of file extensions your modules use 74 | moduleFileExtensions: [ 75 | 'js', 76 | 'jsx', 77 | 'ts', 78 | 'tsx', 79 | 'json', 80 | 'node' 81 | ] 82 | 83 | // A map from regular expressions to module names or to arrays of module names that allow to stub out resources with a single module 84 | // moduleNameMapper: {}, 85 | 86 | // An array of regexp pattern strings, matched against all module paths before considered 'visible' to the module loader 87 | // modulePathIgnorePatterns: [], 88 | 89 | // Activates notifications for test results 90 | // notify: false, 91 | 92 | // An enum that specifies notification mode. Requires { notify: true } 93 | // notifyMode: "failure-change", 94 | 95 | // A preset that is used as a base for Jest's configuration 96 | // preset: undefined, 97 | 98 | // Run tests from one or more projects 99 | // projects: undefined, 100 | 101 | // Use this configuration option to add custom reporters to Jest 102 | // reporters: undefined, 103 | 104 | // Automatically reset mock state before every test 105 | // resetMocks: false, 106 | 107 | // Reset the module registry before running each individual test 108 | // resetModules: false, 109 | 110 | // A path to a custom resolver 111 | // resolver: undefined, 112 | 113 | // Automatically restore mock state and implementation before every test 114 | // restoreMocks: false, 115 | 116 | // The root directory that Jest should scan for tests and modules within 117 | // rootDir: undefined, 118 | 119 | // A list of paths to directories that Jest should use to search for files in 120 | // roots: [ 121 | // "" 122 | // ], 123 | 124 | // Allows you to use a custom runner instead of Jest's default test runner 125 | // runner: "jest-runner", 126 | 127 | // The paths to modules that run some code to configure or set up the testing environment before each test 128 | // setupFiles: [], 129 | 130 | // A list of paths to modules that run some code to configure or set up the testing framework before each test 131 | // setupFilesAfterEnv: [], 132 | 133 | // The number of seconds after which a test is considered as slow and reported as such in the results. 134 | // slowTestThreshold: 5, 135 | 136 | // A list of paths to snapshot serializer modules Jest should use for snapshot testing 137 | // snapshotSerializers: [], 138 | 139 | // The test environment that will be used for testing 140 | // testEnvironment: "jest-environment-node", 141 | 142 | // Options that will be passed to the testEnvironment 143 | // testEnvironmentOptions: {}, 144 | 145 | // Adds a location field to test results 146 | // testLocationInResults: false, 147 | 148 | // The glob patterns Jest uses to detect test files 149 | // testMatch: [ 150 | // "**/__tests__/**/*.[jt]s?(x)", 151 | // "**/?(*.)+(spec|test).[tj]s?(x)" 152 | // ], 153 | 154 | // An array of regexp pattern strings that are matched against all test paths, matched tests are skipped 155 | // testPathIgnorePatterns: [ 156 | // "/node_modules/" 157 | // ], 158 | 159 | // The regexp pattern or array of patterns that Jest uses to detect test files 160 | // testRegex: [], 161 | 162 | // This option allows the use of a custom results processor 163 | // testResultsProcessor: undefined, 164 | 165 | // This option allows use of a custom test runner 166 | // testRunner: "jest-circus/runner", 167 | 168 | // This option sets the URL for the jsdom environment. It is reflected in properties such as location.href 169 | // testURL: "http://localhost", 170 | 171 | // Setting this value to "fake" allows the use of fake timers for functions such as "setTimeout" 172 | // timers: "real", 173 | 174 | // A map from regular expressions to paths to transformers 175 | // transform: undefined, 176 | 177 | // An array of regexp pattern strings that are matched against all source file paths, matched files will skip transformation 178 | // transformIgnorePatterns: [ 179 | // "/node_modules/", 180 | // "\\.pnp\\.[^\\/]+$" 181 | // ], 182 | 183 | // An array of regexp pattern strings that are matched against all modules before the module loader will automatically return a mock for them 184 | // unmockedModulePathPatterns: undefined, 185 | 186 | // Indicates whether each individual test should be reported during the run 187 | // verbose: undefined, 188 | 189 | // An array of regexp patterns that are matched against all source file paths before re-running tests in watch mode 190 | // watchPathIgnorePatterns: [], 191 | 192 | // Whether to use watchman for file crawling 193 | // watchman: true, 194 | } 195 | --------------------------------------------------------------------------------