Du kan inte välja fler än 25 ämnen Ämnen måste starta med en bokstav eller siffra, kan innehålla bindestreck ('-') och vara max 35 tecken långa.

arrow.tsx 14KB

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