index.tsx 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308
  1. import React, { ReactNode, Children, ReactChild, ReactFragment, ReactPortal, isValidElement } from 'react';
  2. import cls from 'classnames';
  3. import PropTypes from 'prop-types';
  4. import BaseComponent from "../_base/baseComponent";
  5. import { CarouselProps } from './interface';
  6. import { cssClasses, numbers, strings } from '@douyinfe/semi-foundation/carousel/constants';
  7. import CarouselFoundation, { CarouselAdapter } from '@douyinfe/semi-foundation/carousel/foundation';
  8. import CarouselIndicator from './CarouselIndicator';
  9. import CarouselArrow from './CarouselArrow';
  10. import '@douyinfe/semi-foundation/carousel/carousel.scss';
  11. import { debounce, isEqual, pick } from 'lodash';
  12. import isNullOrUndefined from '@douyinfe/semi-foundation/utils/isNullOrUndefined';
  13. export interface CarouselState {
  14. activeIndex: number;
  15. children: (ReactChild | ReactFragment | ReactPortal)[];
  16. preIndex: number;
  17. isReverse: boolean;
  18. isInit: boolean
  19. }
  20. class Carousel extends BaseComponent<CarouselProps, CarouselState> {
  21. static propTypes = {
  22. activeIndex: PropTypes.number,
  23. animation: PropTypes.oneOf(strings.ANIMATION_MAP),
  24. arrowProps: PropTypes.object,
  25. autoPlay: PropTypes.oneOfType([PropTypes.bool, PropTypes.object]),
  26. className: PropTypes.string,
  27. defaultActiveIndex: PropTypes.number,
  28. indicatorPosition: PropTypes.oneOf(strings.POSITION_MAP),
  29. indicatorSize: PropTypes.oneOf(strings.SIZE),
  30. indicatorType: PropTypes.oneOf(strings.TYPE_MAP),
  31. theme: PropTypes.oneOf(strings.THEME_MAP),
  32. onChange: PropTypes.func,
  33. arrowType: PropTypes.oneOf(strings.ARROW_MAP),
  34. showArrow: PropTypes.bool,
  35. showIndicator: PropTypes.bool,
  36. slideDirection: PropTypes.oneOf(strings.DIRECTION),
  37. speed: PropTypes.number,
  38. style: PropTypes.object,
  39. trigger: PropTypes.oneOf(strings.TRIGGER)
  40. };
  41. static defaultProps: CarouselProps = {
  42. children: [],
  43. animation: 'slide',
  44. autoPlay: true,
  45. arrowType: 'always',
  46. defaultActiveIndex: numbers.DEFAULT_ACTIVE_INDEX,
  47. indicatorPosition: 'center',
  48. indicatorSize: 'small',
  49. indicatorType: 'dot',
  50. theme: 'light',
  51. onChange: () => undefined,
  52. showArrow: true,
  53. showIndicator: true,
  54. slideDirection: 'left',
  55. speed: numbers.DEFAULT_SPEED,
  56. trigger: 'click'
  57. };
  58. foundation: CarouselFoundation;
  59. constructor(props: CarouselProps) {
  60. super(props);
  61. this.foundation = new CarouselFoundation(this.adapter);
  62. const defaultActiveIndex = this.foundation.getDefaultActiveIndex();
  63. this.state = {
  64. activeIndex: defaultActiveIndex,
  65. children: this.getChildren(),
  66. preIndex: defaultActiveIndex,
  67. isReverse: false,
  68. isInit: true
  69. };
  70. }
  71. get adapter(): CarouselAdapter<CarouselProps, CarouselState> {
  72. return {
  73. ...super.adapter,
  74. notifyChange: (activeIndex: number, preIndex: number): void => {
  75. this.props.onChange(activeIndex, preIndex);
  76. },
  77. setNewActiveIndex: (activeIndex: number): void => {
  78. this.setState({ activeIndex });
  79. },
  80. setPreActiveIndex: (preIndex: number): void => {
  81. this.setState({ preIndex });
  82. },
  83. setIsReverse: (isReverse: boolean): void => {
  84. this.setState({ isReverse });
  85. },
  86. setIsInit: (isInit: boolean): void => {
  87. this.setState({ isInit });
  88. }
  89. };
  90. }
  91. static getDerivedStateFromProps(props: CarouselProps, state: CarouselState): Partial<CarouselState> {
  92. const states: Partial<CarouselState> = {};
  93. if (!isNullOrUndefined(props.activeIndex) && props.activeIndex !== state.activeIndex) {
  94. states.activeIndex = props.activeIndex;
  95. }
  96. return states;
  97. }
  98. componentDidMount(): void {
  99. this.handleAutoPlay();
  100. }
  101. componentDidUpdate(prevProps: Readonly<CarouselProps>, prevState: Readonly<CarouselState>, snapshot?: any): void {
  102. const prevChildrenKeys = React.Children.toArray(prevProps.children).map((child) =>
  103. isValidElement(child) ? child.key : null
  104. );
  105. const nowChildrenKeys = React.Children.toArray(this.props.children).map((child) =>
  106. isValidElement(child) ? child.key : null
  107. );
  108. if (!isEqual(prevChildrenKeys, nowChildrenKeys)) {
  109. this.setState({ children: this.getChildren() });
  110. }
  111. }
  112. componentWillUnmount(): void {
  113. this.foundation.destroy();
  114. }
  115. play = (): void => {
  116. this.foundation.setForcePlay(true);
  117. return this.foundation.handleAutoPlay();
  118. }
  119. stop = (): void => {
  120. this.foundation.setForcePlay(false);
  121. return this.foundation.stop();
  122. };
  123. goTo = ( targetIndex: number): void => {
  124. return this.foundation.goTo(targetIndex);
  125. };
  126. prev = (): void => {
  127. return this.foundation.prev();
  128. };
  129. next = (): void => {
  130. return this.foundation.next();
  131. };
  132. handleAutoPlay = (): void => {
  133. if (!this.foundation.getIsControlledComponent()) {
  134. this.foundation.handleAutoPlay();
  135. }
  136. }
  137. handleMouseEnter = (): void => {
  138. const { autoPlay } = this.props;
  139. if ((autoPlay === true) || (typeof autoPlay === 'object' && autoPlay.hoverToPause)) {
  140. this.foundation.stop();
  141. }
  142. }
  143. handleMouseLeave = (): void => {
  144. const { autoPlay } = this.props;
  145. if ((typeof autoPlay !== 'object' || autoPlay.hoverToPause) && !this.foundation.getIsControlledComponent()) {
  146. this.foundation.handleAutoPlay();
  147. }
  148. }
  149. onIndicatorChange = (activeIndex: number): void => {
  150. return this.foundation.onIndicatorChange(activeIndex);
  151. };
  152. getChildren = (): (ReactChild | ReactFragment | ReactPortal)[] => {
  153. const { children: originChildren } = this.props;
  154. return Children.toArray(originChildren).filter(child=>{
  155. return React.isValidElement(child);
  156. });
  157. }
  158. getValidIndex = (activeIndex: number): number => {
  159. return this.foundation.getValidIndex(activeIndex);
  160. };
  161. renderChildren = () => {
  162. const { speed, animation } = this.props;
  163. const { activeIndex, children, preIndex, isInit } = this.state;
  164. return (
  165. <>
  166. {children.map((child: any, index: number) => {
  167. const isCurrent = index === activeIndex;
  168. const isPrev = index === this.getValidIndex(activeIndex - 1);
  169. const isNext = index === this.getValidIndex(activeIndex + 1);
  170. const animateStyle = {
  171. transitionTimingFunction: 'ease',
  172. transitionDuration: `${speed}ms`,
  173. animationTimingFunction: 'ease',
  174. animationDuration: `${speed}ms`,
  175. };
  176. return React.cloneElement(child, {
  177. style: {
  178. ...child.props.style,
  179. ...animateStyle,
  180. },
  181. className: cls(child.props.className, {
  182. [`${cssClasses.CAROUSEL_CONTENT}-item-prev`]: isPrev,
  183. [`${cssClasses.CAROUSEL_CONTENT}-item-next`]: isNext,
  184. [`${cssClasses.CAROUSEL_CONTENT}-item-current`]: isCurrent,
  185. [`${cssClasses.CAROUSEL_CONTENT}-item`]: true,
  186. [`${cssClasses.CAROUSEL_CONTENT}-item-active`]: isCurrent,
  187. [`${cssClasses.CAROUSEL_CONTENT}-item-slide-in`]: animation === 'slide' && !isInit && isCurrent,
  188. [`${cssClasses.CAROUSEL_CONTENT}-item-slide-out`]: animation === 'slide' && !isInit && index === preIndex,
  189. })
  190. });
  191. })}
  192. </>
  193. );
  194. }
  195. renderIndicator = () => {
  196. const { children, activeIndex } = this.state;
  197. const { showIndicator, indicatorType, theme, indicatorPosition, indicatorSize, trigger } = this.props;
  198. const carouselIndicatorCls = cls({
  199. [cssClasses.CAROUSEL_INDICATOR]: true
  200. });
  201. if (showIndicator && children.length > 1) {
  202. return (
  203. <div className={carouselIndicatorCls}>
  204. <CarouselIndicator
  205. type={indicatorType}
  206. total={children.length}
  207. activeIndex={activeIndex}
  208. position={indicatorPosition}
  209. trigger={trigger}
  210. size={indicatorSize}
  211. theme={theme}
  212. onIndicatorChange={this.onIndicatorChange}
  213. />
  214. </div>
  215. );
  216. }
  217. return null;
  218. }
  219. renderArrow = () => {
  220. const { children } = this.state;
  221. const { showArrow, arrowType, theme, arrowProps } = this.props;
  222. if (showArrow && children.length > 1) {
  223. return (
  224. <CarouselArrow
  225. type={arrowType}
  226. theme={theme}
  227. prev={this.prev}
  228. next={this.next}
  229. arrowProps={arrowProps}
  230. />
  231. );
  232. }
  233. return null;
  234. };
  235. render(): ReactNode {
  236. const { animation, className, style, slideDirection } = this.props;
  237. const { isReverse } = this.state;
  238. const carouselWrapperCls = cls(className, {
  239. [cssClasses.CAROUSEL]: true
  240. });
  241. return (
  242. <div
  243. // role='listbox'
  244. // tabIndex={0}
  245. className={carouselWrapperCls}
  246. style={style}
  247. onMouseEnter={debounce(this.handleMouseEnter, 400)}
  248. onMouseLeave={debounce(this.handleMouseLeave, 400)}
  249. {...this.getDataAttr(this.props)}
  250. // onMouseEnter={this.handleMouseEnter}
  251. // onMouseLeave={this.handleMouseLeave}
  252. // onKeyDown={e => this.foundation.handleKeyDown(e)}
  253. >
  254. <div
  255. className={cls([`${cssClasses.CAROUSEL_CONTENT}-${animation}`], {
  256. [`${cssClasses.CAROUSEL_CONTENT}`]: true,
  257. [`${cssClasses.CAROUSEL_CONTENT}-reverse`]: slideDirection === 'left' ? isReverse : !isReverse,
  258. })}
  259. x-semi-prop="children"
  260. >
  261. {this.renderChildren()}
  262. </div>
  263. {this.renderIndicator()}
  264. {this.renderArrow()}
  265. </div>
  266. );
  267. }
  268. }
  269. export default Carousel;