Slide.js 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596
  1. const { cloneElement, Component } = require('preact')
  2. const classNames = require('classnames')
  3. const transitionName = 'uppy-transition-slideDownUp'
  4. const duration = 250
  5. /**
  6. * Vertical slide transition.
  7. *
  8. * This can take a _single_ child component, which _must_ accept a `className` prop.
  9. *
  10. * Currently this is specific to the `uppy-transition-slideDownUp` transition,
  11. * but it should be simple to extend this for any type of single-element
  12. * transition by setting the CSS name and duration as props.
  13. */
  14. class Slide extends Component {
  15. constructor (props) {
  16. super(props)
  17. this.state = {
  18. cachedChildren: null,
  19. className: ''
  20. }
  21. }
  22. componentWillUpdate (nextProps) {
  23. const { cachedChildren } = this.state
  24. const child = nextProps.children[0]
  25. if (cachedChildren === child) return
  26. const patch = {
  27. cachedChildren: child
  28. }
  29. // Enter transition
  30. if (child && !cachedChildren) {
  31. patch.className = `${transitionName}-enter`
  32. cancelAnimationFrame(this.animationFrame)
  33. clearTimeout(this.leaveTimeout)
  34. this.leaveTimeout = undefined
  35. this.animationFrame = requestAnimationFrame(() => {
  36. // Force it to render before we add the active class
  37. this.base.getBoundingClientRect()
  38. this.setState({
  39. className: `${transitionName}-enter ${transitionName}-enter-active`
  40. })
  41. this.enterTimeout = setTimeout(() => {
  42. this.setState({ className: '' })
  43. }, duration)
  44. })
  45. }
  46. // Leave transition
  47. if (cachedChildren && !child && this.leaveTimeout === undefined) {
  48. patch.cachedChildren = cachedChildren
  49. patch.className = `${transitionName}-leave`
  50. cancelAnimationFrame(this.animationFrame)
  51. clearTimeout(this.enterTimeout)
  52. this.enterTimeout = undefined
  53. this.animationFrame = requestAnimationFrame(() => {
  54. this.setState({
  55. className: `${transitionName}-leave ${transitionName}-leave-active`
  56. })
  57. this.leaveTimeout = setTimeout(() => {
  58. this.setState({
  59. cachedChildren: null,
  60. className: ''
  61. })
  62. }, duration)
  63. })
  64. }
  65. this.setState(patch)
  66. }
  67. render () {
  68. const { cachedChildren, className } = this.state
  69. if (!cachedChildren) {
  70. return null
  71. }
  72. return cloneElement(cachedChildren, {
  73. className: classNames(className, cachedChildren.attributes.className)
  74. })
  75. }
  76. }
  77. module.exports = Slide