You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

arrow.tsx 14KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557
  1. import { getArcLength, uniqueId } from 'utils'
  2. import vec from 'utils/vec'
  3. import {
  4. getSvgPathFromStroke,
  5. rng,
  6. getBoundsFromPoints,
  7. translateBounds,
  8. pointInBounds,
  9. pointInCircle,
  10. } from 'utils'
  11. import {
  12. ArrowShape,
  13. DashStyle,
  14. Decoration,
  15. ShapeHandle,
  16. ShapeType,
  17. } from 'types'
  18. import { circleFromThreePoints, isAngleBetween } from 'utils'
  19. import {
  20. intersectArcBounds,
  21. intersectLineSegmentBounds,
  22. } from 'utils/intersections'
  23. import { defaultStyle, getShapeStyle } from 'state/shape-styles'
  24. import getStroke from 'perfect-freehand'
  25. import React from 'react'
  26. import { registerShapeUtils } from './register'
  27. import { getPerfectDashProps } from 'utils/dashes'
  28. const pathCache = new WeakMap<ArrowShape, string>([])
  29. // A cache for semi-expensive circles calculated from three points
  30. function getCtp(shape: ArrowShape) {
  31. const { start, end, bend } = shape.handles
  32. return circleFromThreePoints(start.point, end.point, bend.point)
  33. }
  34. const arrow = registerShapeUtils<ArrowShape>({
  35. boundsCache: new WeakMap([]),
  36. create(props) {
  37. const {
  38. point = [0, 0],
  39. handles = {
  40. start: {
  41. id: 'start',
  42. index: 0,
  43. point: [0, 0],
  44. },
  45. end: {
  46. id: 'end',
  47. index: 1,
  48. point: [1, 1],
  49. },
  50. bend: {
  51. id: 'bend',
  52. index: 2,
  53. point: [0.5, 0.5],
  54. },
  55. },
  56. } = props
  57. return {
  58. id: uniqueId(),
  59. type: ShapeType.Arrow,
  60. isGenerated: false,
  61. name: 'Arrow',
  62. parentId: 'page1',
  63. childIndex: 0,
  64. point,
  65. rotation: 0,
  66. isAspectRatioLocked: false,
  67. isLocked: false,
  68. isHidden: false,
  69. bend: 0,
  70. handles,
  71. decorations: {
  72. start: null,
  73. middle: null,
  74. end: Decoration.Arrow,
  75. },
  76. ...props,
  77. style: {
  78. ...defaultStyle,
  79. ...props.style,
  80. isFilled: false,
  81. },
  82. }
  83. },
  84. shouldRender(shape, prev) {
  85. return shape.handles !== prev.handles || shape.style !== prev.style
  86. },
  87. render(shape) {
  88. const { id, bend, handles, style } = shape
  89. const { start, end, bend: _bend } = handles
  90. const isStraightLine = vec.isEqual(
  91. _bend.point,
  92. vec.med(start.point, end.point)
  93. )
  94. const styles = getShapeStyle(style)
  95. const strokeWidth = +styles.strokeWidth
  96. const sw =
  97. strokeWidth * (style.dash === DashStyle.Solid && bend === 0 ? 1 : 1.618)
  98. const arrowDist = vec.dist(start.point, end.point)
  99. let shaftPath: JSX.Element
  100. let startAngle: number
  101. let endAngle: number
  102. if (isStraightLine) {
  103. if (shape.style.dash === DashStyle.Solid && !pathCache.has(shape)) {
  104. renderFreehandArrowShaft(shape)
  105. }
  106. const path =
  107. shape.style.dash === DashStyle.Solid
  108. ? pathCache.get(shape)
  109. : 'M' + start.point + 'L' + end.point
  110. const { strokeDasharray, strokeDashoffset } =
  111. shape.style.dash === DashStyle.Solid
  112. ? {
  113. strokeDasharray: 'none',
  114. strokeDashoffset: '0',
  115. }
  116. : getPerfectDashProps(
  117. arrowDist,
  118. sw,
  119. shape.style.dash === DashStyle.Dotted ? 'dotted' : 'dashed',
  120. 2
  121. )
  122. startAngle = Math.PI
  123. endAngle = 0
  124. shaftPath = (
  125. <>
  126. <path
  127. d={path}
  128. stroke="transparent"
  129. fill="none"
  130. strokeWidth={Math.max(8, strokeWidth * 2)}
  131. strokeDasharray="none"
  132. strokeDashoffset="none"
  133. strokeLinecap="round"
  134. />
  135. <path
  136. d={path}
  137. fill="none"
  138. strokeWidth={sw}
  139. strokeDasharray={strokeDasharray}
  140. strokeDashoffset={strokeDashoffset}
  141. strokeLinecap="round"
  142. ></path>
  143. </>
  144. )
  145. } else {
  146. const circle = getCtp(shape)
  147. const path = getArrowArcPath(start, end, circle, bend)
  148. const { strokeDasharray, strokeDashoffset } =
  149. shape.style.dash === DashStyle.Solid
  150. ? {
  151. strokeDasharray: 'none',
  152. strokeDashoffset: '0',
  153. }
  154. : getPerfectDashProps(
  155. getArcLength(
  156. [circle[0], circle[1]],
  157. circle[2],
  158. start.point,
  159. end.point
  160. ) - 1,
  161. sw,
  162. shape.style.dash === DashStyle.Dotted ? 'dotted' : 'dashed',
  163. 2
  164. )
  165. startAngle =
  166. vec.angle([circle[0], circle[1]], start.point) -
  167. vec.angle(end.point, start.point) +
  168. (Math.PI / 2) * (bend > 0 ? 0.98 : -0.98)
  169. endAngle =
  170. vec.angle([circle[0], circle[1]], end.point) -
  171. vec.angle(start.point, end.point) +
  172. (Math.PI / 2) * (bend > 0 ? 0.98 : -0.98)
  173. shaftPath = (
  174. <>
  175. <path
  176. d={path}
  177. stroke="transparent"
  178. fill="none"
  179. strokeWidth={Math.max(8, strokeWidth * 2)}
  180. strokeDasharray="none"
  181. strokeDashoffset="none"
  182. strokeLinecap="round"
  183. />
  184. <path
  185. d={path}
  186. fill="none"
  187. strokeWidth={sw}
  188. strokeDasharray={strokeDasharray}
  189. strokeDashoffset={strokeDashoffset}
  190. strokeLinecap="round"
  191. ></path>
  192. </>
  193. )
  194. }
  195. return (
  196. <g id={id}>
  197. {shaftPath}
  198. {shape.decorations.start === Decoration.Arrow && (
  199. <path
  200. d={getArrowHeadPath(shape, start.point, startAngle)}
  201. strokeWidth={strokeWidth * 1.618}
  202. fill="none"
  203. strokeDashoffset="none"
  204. strokeDasharray="none"
  205. />
  206. )}
  207. {shape.decorations.end === Decoration.Arrow && (
  208. <path
  209. d={getArrowHeadPath(shape, end.point, endAngle)}
  210. strokeWidth={strokeWidth * 1.618}
  211. fill="none"
  212. strokeDashoffset="none"
  213. strokeDasharray="none"
  214. />
  215. )}
  216. </g>
  217. )
  218. },
  219. rotateBy(shape, delta) {
  220. const { start, end, bend } = shape.handles
  221. const mp = vec.med(start.point, end.point)
  222. start.point = vec.rotWith(start.point, mp, delta)
  223. end.point = vec.rotWith(end.point, mp, delta)
  224. bend.point = vec.rotWith(bend.point, mp, delta)
  225. this.onHandleChange(shape, shape.handles)
  226. return this
  227. },
  228. rotateTo(shape, rotation, delta) {
  229. const { start, end, bend } = shape.handles
  230. const mp = vec.med(start.point, end.point)
  231. start.point = vec.rotWith(start.point, mp, delta)
  232. end.point = vec.rotWith(end.point, mp, delta)
  233. bend.point = vec.rotWith(bend.point, mp, delta)
  234. this.onHandleChange(shape, shape.handles)
  235. return this
  236. },
  237. getBounds(shape) {
  238. if (!this.boundsCache.has(shape)) {
  239. const { start, bend, end } = shape.handles
  240. this.boundsCache.set(
  241. shape,
  242. getBoundsFromPoints([start.point, bend.point, end.point])
  243. )
  244. }
  245. return translateBounds(this.boundsCache.get(shape), shape.point)
  246. },
  247. getRotatedBounds(shape) {
  248. const { start, bend, end } = shape.handles
  249. return translateBounds(
  250. getBoundsFromPoints([start.point, bend.point, end.point], shape.rotation),
  251. shape.point
  252. )
  253. },
  254. getCenter(shape) {
  255. const { start, end } = shape.handles
  256. return vec.add(shape.point, vec.med(start.point, end.point))
  257. },
  258. hitTest(shape, point) {
  259. const { start, end } = shape.handles
  260. if (shape.bend === 0) {
  261. return (
  262. vec.distanceToLineSegment(
  263. start.point,
  264. end.point,
  265. vec.sub(point, shape.point)
  266. ) < 4
  267. )
  268. }
  269. const [cx, cy, r] = getCtp(shape)
  270. return !pointInCircle(point, vec.add(shape.point, [cx, cy]), r - 4)
  271. },
  272. hitTestBounds(this, shape, brushBounds) {
  273. const { start, end, bend } = shape.handles
  274. const sp = vec.add(shape.point, start.point)
  275. const ep = vec.add(shape.point, end.point)
  276. if (pointInBounds(sp, brushBounds) || pointInBounds(ep, brushBounds)) {
  277. return true
  278. }
  279. if (vec.isEqual(vec.med(start.point, end.point), bend.point)) {
  280. return intersectLineSegmentBounds(sp, ep, brushBounds).length > 0
  281. } else {
  282. const [cx, cy, r] = getCtp(shape)
  283. const cp = vec.add(shape.point, [cx, cy])
  284. return intersectArcBounds(sp, ep, cp, r, brushBounds).length > 0
  285. }
  286. },
  287. transform(shape, bounds, { initialShape, scaleX, scaleY }) {
  288. const initialShapeBounds = this.getBounds(initialShape)
  289. // let nw = initialShape.point[0] / initialShapeBounds.width
  290. // let nh = initialShape.point[1] / initialShapeBounds.height
  291. // shape.point = [
  292. // bounds.width * (scaleX < 0 ? 1 - nw : nw),
  293. // bounds.height * (scaleY < 0 ? 1 - nh : nh),
  294. // ]
  295. shape.point = [bounds.minX, bounds.minY]
  296. const handles = ['start', 'end']
  297. handles.forEach((handle) => {
  298. const [x, y] = initialShape.handles[handle].point
  299. const nw = x / initialShapeBounds.width
  300. const nh = y / initialShapeBounds.height
  301. shape.handles[handle].point = [
  302. bounds.width * (scaleX < 0 ? 1 - nw : nw),
  303. bounds.height * (scaleY < 0 ? 1 - nh : nh),
  304. ]
  305. })
  306. const { start, bend, end } = shape.handles
  307. const dist = vec.dist(start.point, end.point)
  308. const midPoint = vec.med(start.point, end.point)
  309. const bendDist = (dist / 2) * initialShape.bend
  310. const u = vec.uni(vec.vec(start.point, end.point))
  311. const point = vec.add(midPoint, vec.mul(vec.per(u), bendDist))
  312. bend.point = Math.abs(bendDist) < 10 ? midPoint : point
  313. return this
  314. },
  315. onDoublePointHandle(shape, handle) {
  316. switch (handle) {
  317. case 'bend': {
  318. shape.bend = 0
  319. shape.handles.bend.point = getBendPoint(shape)
  320. break
  321. }
  322. case 'start': {
  323. shape.decorations.start = shape.decorations.start
  324. ? null
  325. : Decoration.Arrow
  326. break
  327. }
  328. case 'end': {
  329. shape.decorations.end = shape.decorations.end ? null : Decoration.Arrow
  330. break
  331. }
  332. }
  333. return this
  334. },
  335. onHandleChange(shape, handles) {
  336. for (const id in handles) {
  337. const handle = handles[id]
  338. shape.handles[handle.id] = handle
  339. }
  340. if ('bend' in handles) {
  341. const { start, end, bend } = shape.handles
  342. const dist = vec.dist(start.point, end.point)
  343. const midPoint = vec.med(start.point, end.point)
  344. const u = vec.uni(vec.vec(start.point, end.point))
  345. const ap = vec.add(midPoint, vec.mul(vec.per(u), dist / 2))
  346. const bp = vec.sub(midPoint, vec.mul(vec.per(u), dist / 2))
  347. bend.point = vec.nearestPointOnLineSegment(ap, bp, bend.point, true)
  348. shape.bend = vec.dist(bend.point, midPoint) / (dist / 2)
  349. const sa = vec.angle(end.point, start.point)
  350. const la = sa - Math.PI / 2
  351. if (isAngleBetween(sa, la, vec.angle(end.point, bend.point))) {
  352. shape.bend *= -1
  353. }
  354. }
  355. shape.handles.bend.point = getBendPoint(shape)
  356. return this
  357. },
  358. onSessionComplete(shape) {
  359. const bounds = this.getBounds(shape)
  360. const offset = vec.sub([bounds.minX, bounds.minY], shape.point)
  361. this.translateTo(shape, vec.add(shape.point, offset))
  362. const { start, end, bend } = shape.handles
  363. start.point = vec.sub(start.point, offset)
  364. end.point = vec.sub(end.point, offset)
  365. bend.point = vec.sub(bend.point, offset)
  366. shape.handles = { ...shape.handles }
  367. return this
  368. },
  369. applyStyles(shape, style) {
  370. Object.assign(shape.style, style)
  371. shape.style.isFilled = false
  372. return this
  373. },
  374. canStyleFill: false,
  375. })
  376. export default arrow
  377. function getArrowArcPath(
  378. start: ShapeHandle,
  379. end: ShapeHandle,
  380. circle: number[],
  381. bend: number
  382. ) {
  383. return [
  384. 'M',
  385. start.point[0],
  386. start.point[1],
  387. 'A',
  388. circle[2],
  389. circle[2],
  390. 0,
  391. 0,
  392. bend < 0 ? 0 : 1,
  393. end.point[0],
  394. end.point[1],
  395. ].join(' ')
  396. }
  397. function getBendPoint(shape: ArrowShape) {
  398. const { start, end } = shape.handles
  399. const dist = vec.dist(start.point, end.point)
  400. const midPoint = vec.med(start.point, end.point)
  401. const bendDist = (dist / 2) * shape.bend
  402. const u = vec.uni(vec.vec(start.point, end.point))
  403. return Math.abs(bendDist) < 10
  404. ? midPoint
  405. : vec.add(midPoint, vec.mul(vec.per(u), bendDist))
  406. }
  407. function renderFreehandArrowShaft(shape: ArrowShape) {
  408. const { style, id } = shape
  409. const { start, end } = shape.handles
  410. const getRandom = rng(id)
  411. const strokeWidth = +getShapeStyle(style).strokeWidth * 2
  412. const m = vec.add(
  413. vec.lrp(start.point, end.point, 0.25 + Math.abs(getRandom()) / 2),
  414. [getRandom() * strokeWidth, getRandom() * strokeWidth]
  415. )
  416. const stroke = getStroke(
  417. [
  418. ...vec.pointsBetween(start.point, m),
  419. ...vec.pointsBetween(m, end.point),
  420. end.point,
  421. end.point,
  422. end.point,
  423. ],
  424. {
  425. size: 1 + strokeWidth,
  426. thinning: 0.6,
  427. easing: (t) => t * t * t * t,
  428. end: { taper: strokeWidth * 2 },
  429. start: { taper: strokeWidth * 2 },
  430. simulatePressure: false,
  431. }
  432. )
  433. pathCache.set(shape, getSvgPathFromStroke(stroke))
  434. }
  435. function getArrowHeadPath(shape: ArrowShape, point: number[], angle = 0) {
  436. const { left, right } = getArrowHeadPoints(shape, point, angle)
  437. return ['M', left, 'L', point, right].join(' ')
  438. }
  439. function getArrowHeadPoints(shape: ArrowShape, point: number[], angle = 0) {
  440. const { start, end } = shape.handles
  441. const stroke = +getShapeStyle(shape.style).strokeWidth * 2
  442. const arrowDist = vec.dist(start.point, end.point)
  443. const arrowHeadlength = Math.min(arrowDist / 3, stroke * 4)
  444. // Unit vector from start to end
  445. const u = vec.uni(vec.vec(start.point, end.point))
  446. // The end of the arrowhead wings
  447. const v = vec.rot(vec.mul(vec.neg(u), arrowHeadlength), angle)
  448. // Use the shape's random seed to create minor offsets for the angles
  449. const getRandom = rng(shape.id)
  450. return {
  451. left: vec.add(point, vec.rot(v, Math.PI / 6 + (Math.PI / 8) * getRandom())),
  452. right: vec.add(
  453. point,
  454. vec.rot(v, -(Math.PI / 6) + (Math.PI / 8) * getRandom())
  455. ),
  456. }
  457. }