Dragger.js 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322
  1. import React from 'react'
  2. import PropTypes from 'prop-types'
  3. import { int, innerHeight, innerWidth, outerHeight, outerWidth, parseBounds, isNumber } from './utils'
  4. const doc = document
  5. export default class Dragger extends React.Component {
  6. constructor(...props) {
  7. super(...props)
  8. this.move = this.move.bind(this)
  9. this.onDragEnd = this.onDragEnd.bind(this)
  10. }
  11. static propTypes = {
  12. /**
  13. * 给予元素一个x,y的初始位置,单位是px
  14. */
  15. x: PropTypes.number,
  16. y: PropTypes.number,
  17. /**
  18. * 拖动范围限制
  19. * 如果不规定范围,那么子元素就可以随意拖动不受限制
  20. * 1.可以提供自定义的范围限制
  21. * 2.也可以提供父类为边框的范围限制(string === parent)
  22. */
  23. bounds: PropTypes.oneOfType([
  24. PropTypes.shape({
  25. left: PropTypes.number,
  26. right: PropTypes.number,
  27. top: PropTypes.number,
  28. bottom: PropTypes.number
  29. }),
  30. PropTypes.string
  31. ]),
  32. /**
  33. * 以网格的方式移动,每次移动并不是平滑的移动
  34. * [20,30],鼠标x轴方向移动了20 px ,y方向移动了30 px,整个子元素才会移动
  35. */
  36. grid: PropTypes.arrayOf(PropTypes.number),
  37. /**只允许移动x轴 */
  38. allowX: PropTypes.bool,
  39. /**只允许移动y轴 */
  40. allowY: PropTypes.bool,
  41. /**
  42. * 内部的移动拖拽把手
  43. * 拖拽把手className一定要设置成handle并且这个属性设置成true
  44. * <Dragger hasDraggerHandle={true}>
  45. * <div className={handle} >点击我拖动</div>
  46. * </Dragger>
  47. */
  48. hasDraggerHandle: PropTypes.bool,
  49. /**
  50. * 是否由用户移动
  51. * 可能是通过外部props改变
  52. */
  53. isUserMove: PropTypes.bool,
  54. /**
  55. * 生命周期回调
  56. */
  57. onDragStart: PropTypes.func,
  58. onMove: PropTypes.func,
  59. onDragEnd: PropTypes.func
  60. }
  61. /** props end */
  62. /**
  63. * 初始变量设置
  64. */
  65. static defaultProps = {
  66. allowX: true,
  67. allowY: true,
  68. hasDraggerHandle: false,
  69. isUserMove: true
  70. }
  71. state = {
  72. /** x轴位移,单位是px */
  73. x: null,
  74. /** y轴位移,单位是px */
  75. y: null,
  76. /**鼠标点击元素的原始位置,单位是px */
  77. originX: 0,
  78. originY: 0,
  79. isUserMove: true,
  80. /**已经移动的位移,单位是px */
  81. lastX: 0,
  82. lastY: 0,
  83. /**堆叠的层级 */
  84. zIndex: 1
  85. }
  86. // shouldComponentUpdate(nextProps, nextState) {
  87. // return this.props.x !== nextProps.x ||
  88. // this.props.y !== nextProps.y ||
  89. // this.state.x !== nextProps.x ||
  90. // this.state.y !== nextProps.y;
  91. // }
  92. move(event) {
  93. let { lastX, lastY } = this.state
  94. /* event.client - this.state.origin 表示的是移动的距离,
  95. * elX表示的是原来已经有的位移
  96. */
  97. let deltaX, deltaY;
  98. if (event.clientX) {
  99. deltaX = event.clientX - this.state.originX + lastX
  100. deltaY = event.clientY - this.state.originY + lastY
  101. } else {
  102. deltaX = event.touches[0].clientX - this.state.originX + lastX
  103. deltaY = event.touches[0].clientY - this.state.originY + lastY
  104. }
  105. const { bounds } = this.props
  106. if (bounds) {
  107. /**
  108. * 如果用户指定一个边界,那么在这里处理
  109. */
  110. let NewBounds = typeof bounds !== 'string' ? bounds : parseBounds(bounds)
  111. /**
  112. * 网格式移动范围设定,永远移动 n 的倍数
  113. * 注意:设定移动范围的时候,一定要在判断bounds之前,否则会造成bounds不对齐
  114. */
  115. const { grid } = this.props
  116. if (Array.isArray(grid) && grid.length === 2) {
  117. deltaX = Math.round(deltaX / grid[0]) * grid[0]
  118. deltaY = Math.round(deltaY / grid[1]) * grid[1]
  119. }
  120. if (this.props.bounds === 'parent') {
  121. NewBounds = {
  122. left: int(this.parent.style.paddingLeft) + int(this.self.style.marginLeft) - this.self.offsetLeft,
  123. top: int(this.parent.style.paddingTop) + int(this.self.style.marginTop) - this.self.offsetTop,
  124. right: innerWidth(this.parent) - outerWidth(this.self) - this.self.offsetLeft +
  125. int(this.parent.style.paddingRight) - int(this.self.style.marginRight),
  126. bottom: innerHeight(this.parent) - outerHeight(this.self) - this.self.offsetTop +
  127. int(this.parent.style.paddingBottom) - int(this.self.style.marginBottom)
  128. }
  129. }
  130. /**
  131. * 保证不超出右边界和底部
  132. * keep element right and bot can not cross the bounds
  133. */
  134. if (isNumber(NewBounds.right)) deltaX = Math.min(deltaX, NewBounds.right)
  135. if (isNumber(NewBounds.bottom)) deltaY = Math.min(deltaY, NewBounds.bottom)
  136. /**
  137. * 保证不超出左边和上边
  138. * keep element left and top can not cross the bounds
  139. */
  140. if (isNumber(NewBounds.left)) deltaX = Math.max(deltaX, NewBounds.left)
  141. if (isNumber(NewBounds.top)) deltaY = Math.max(deltaY, NewBounds.top)
  142. }
  143. /**如果设置了x,y限制 */
  144. deltaX = this.props.allowX ? deltaX : 0
  145. deltaY = this.props.allowY ? deltaY : 0
  146. /**移动时回调,用于外部控制 */
  147. if (this.props.onMove) this.props.onMove(event, deltaX, deltaY)
  148. this.setState({
  149. x: deltaX,
  150. y: deltaY
  151. })
  152. }
  153. onDragStart(event) {
  154. /** 保证用户在移动元素的时候不会选择到元素内部的东西 */
  155. doc.body.style.userSelect = 'none'
  156. if (this.props.hasDraggerHandle) {
  157. if (event.target.className !== 'handle') return
  158. }
  159. /**
  160. * 把监听事件的回掉函数,绑定在document上
  161. * 当设置边界的时候,用户鼠标会离开元素的范围
  162. * 绑定在document上可以使得其依旧能够监听
  163. * 如果绑定在元素上,则鼠标离开元素,就不会再被监听了
  164. */
  165. doc.addEventListener('mousemove', this.move)
  166. doc.addEventListener('touchmove', this.move)
  167. doc.addEventListener('mouseup', this.onDragEnd)
  168. doc.addEventListener('touchend', this.onDragEnd)
  169. if (this.props.bounds === 'parent' &&
  170. /**为了让 这段代码不会重复执行 */
  171. (typeof this.parent === 'undefined' || this.parent === null)) {
  172. /**
  173. * 在这里我们将父节点缓存下来,保证当用户鼠标离开拖拽区域时,我们仍然能获取到父节点
  174. * what we do here is
  175. * making sure that we still can retrieve our parent when user's mouse left this node.
  176. */
  177. this.parent = event.currentTarget.offsetParent
  178. /**
  179. * 我们自己
  180. * ourself
  181. */
  182. this.self = event.currentTarget
  183. }
  184. this.props.onDragStart(this.state.x, this.state.y)
  185. let originX, originY;
  186. if (event.clientX) {
  187. originX = event.clientX
  188. originY = event.clientY
  189. } else {
  190. originX = event.touches[0].clientX
  191. originY = event.touches[0].clientY
  192. }
  193. this.setState({
  194. originX: originX,
  195. originY: originY,
  196. lastX: this.state.x,
  197. lastY: this.state.y,
  198. zIndex: 10
  199. })
  200. }
  201. onDragEnd(event) {
  202. /** 取消用户选择限制,用户可以重新选择 */
  203. doc.body.style.userSelect = ''
  204. this.parent = null
  205. this.self = null
  206. doc.removeEventListener('mousemove', this.move)
  207. doc.removeEventListener('touchmove', this.move)
  208. doc.removeEventListener('touchend', this.onDragEnd)
  209. doc.removeEventListener('mouseup', this.onDragEnd)
  210. this.setState({
  211. zIndex: 1
  212. })
  213. this.props.onDragEnd(event)
  214. }
  215. componentDidMount() {
  216. /**
  217. * 这个函数只会调用一次
  218. * 这个只是一个临时的解决方案,因为这样会使得元素进行两次刷新
  219. */
  220. if (typeof this.props.x === 'number' &&
  221. typeof this.props.y === 'number') {
  222. this.setState({
  223. x: this.props.x,
  224. y: this.props.y
  225. })
  226. }
  227. }
  228. componentWillReceiveProps(nextProps) {
  229. /**
  230. * 外部props 改变的时候更新元素的内部位置
  231. * 这个api设计其实很不好
  232. * 以后可能会修改掉
  233. */
  234. const { isUserMove } = nextProps
  235. if (!isUserMove) {
  236. if (typeof nextProps.x === 'number' &&
  237. typeof nextProps.y === 'number') {
  238. this.setState({
  239. x: nextProps.x,
  240. y: nextProps.y,
  241. lastX: nextProps.x,
  242. lastY: nextProps.y
  243. })
  244. }
  245. }
  246. }
  247. render() {
  248. let { x, y, zIndex } = this.state
  249. const { bounds, style, className, others } = this.props
  250. if (!this.props.isUserMove) {
  251. /**当外部设置其props的x,y初始属性的时候,我们在这里设置元素的初始位移 */
  252. x = this.props.x
  253. y = this.props.y
  254. }
  255. /**主要是为了让用户定义自己的className去修改css */
  256. const fixedClassName = typeof className === 'undefined' ? '' : className + ' '
  257. return (
  258. <div className={`${fixedClassName}WrapDragger`}
  259. style={{ ...style, zIndex: zIndex, touchAction: 'none!important', transform: `translate(${x}px,${y}px)` }}
  260. onMouseDown={this.onDragStart.bind(this)}
  261. onTouchStart={this.onDragStart.bind(this)}
  262. onTouchEnd={this.onDragEnd.bind(this)}
  263. onMouseUp={this.onDragEnd.bind(this)}
  264. {...others}
  265. >
  266. {/**
  267. *
  268. * React.Children.only 只允许子元素有一个根节点
  269. */}
  270. {React.Children.only(this.props.children)}
  271. </div>
  272. )
  273. }
  274. }