index.tsx 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560
  1. /* eslint-disable max-lines-per-function */
  2. /* eslint-disable react/no-find-dom-node */
  3. import React, { CSSProperties } from 'react';
  4. import ReactDOM from 'react-dom';
  5. import PropTypes from 'prop-types';
  6. import cls from 'classnames';
  7. import { cssClasses } from '@douyinfe/semi-foundation/slider/constants';
  8. import BaseComponent from '../_base/baseComponent';
  9. import SliderFoundation, { SliderAdapter, SliderProps as BasicSliceProps, SliderState } from '@douyinfe/semi-foundation/slider/foundation';
  10. import Tooltip from '../tooltip/index';
  11. import '@douyinfe/semi-foundation/slider/slider.scss';
  12. import { isEqual, noop } from 'lodash-es';
  13. const prefixCls = cssClasses.PREFIX;
  14. export interface SliderProps extends BasicSliceProps {
  15. style?: CSSProperties;
  16. railStyle?: CSSProperties;
  17. }
  18. export {
  19. SliderState
  20. };
  21. function domIsInRenderTree(e: HTMLElement) {
  22. if (!e) {
  23. return false;
  24. }
  25. return Boolean(e.offsetWidth || e.offsetHeight || e.getClientRects().length);
  26. }
  27. export default class Slider extends BaseComponent<SliderProps, SliderState> {
  28. static propTypes = {
  29. // allowClear: PropTypes.bool,
  30. defaultValue: PropTypes.oneOfType([PropTypes.number, PropTypes.array]),
  31. disabled: PropTypes.bool,
  32. included: PropTypes.bool, // Whether to juxtapose. Allow dragging
  33. marks: PropTypes.object, // Scale
  34. max: PropTypes.number,
  35. min: PropTypes.number,
  36. range: PropTypes.bool, // Whether both sides
  37. step: PropTypes.number,
  38. tipFormatter: PropTypes.func,
  39. value: PropTypes.oneOfType([PropTypes.number, PropTypes.array]),
  40. vertical: PropTypes.bool,
  41. onAfterChange: PropTypes.func, // OnmouseUp and triggered when clicked
  42. onChange: PropTypes.func,
  43. tooltipVisible: PropTypes.bool,
  44. style: PropTypes.object,
  45. className: PropTypes.string,
  46. showBoundary: PropTypes.bool,
  47. railStyle: PropTypes.object,
  48. verticalReverse: PropTypes.bool,
  49. } as any;
  50. static defaultProps: Partial<SliderProps> = {
  51. // allowClear: false,
  52. disabled: false,
  53. included: true, // No is juxtaposition. Allow dragging
  54. max: 100,
  55. min: 0,
  56. range: false, // Whether both sides
  57. step: 1,
  58. tipFormatter: (value: number) => value,
  59. vertical: false,
  60. showBoundary: false,
  61. onAfterChange: (value: number | number[]) => {
  62. // console.log(value);
  63. },
  64. onChange: (value: number | number[]) => {
  65. // console.log(value);
  66. },
  67. verticalReverse: false
  68. };
  69. private sliderEl: React.RefObject<HTMLDivElement>;
  70. private minHanleEl: React.RefObject<HTMLDivElement>;
  71. private maxHanleEl: React.RefObject<HTMLDivElement>;
  72. private dragging: boolean[];
  73. private eventListenerSet: Set<() => void>;
  74. private chooseMovePos: 'min' | 'max';
  75. constructor(props: SliderProps) {
  76. super(props);
  77. let { value } = this.props;
  78. if (!value) {
  79. value = this.props.defaultValue;
  80. }
  81. this.state = {
  82. // eslint-disable-next-line no-nested-ternary
  83. currentValue: value ? value : this.props.range ? [0, 0] : 0,
  84. min: this.props.min || 0,
  85. max: this.props.max || 0,
  86. focusPos: '',
  87. onChange: this.props.onChange,
  88. disabled: this.props.disabled || false,
  89. chooseMovePos: '',
  90. isDrag: false,
  91. clickValue: 0,
  92. showBoundary: false,
  93. isInRenderTree: true
  94. };
  95. this.sliderEl = React.createRef();
  96. this.minHanleEl = React.createRef();
  97. this.maxHanleEl = React.createRef();
  98. this.dragging = [false, false];
  99. // this.chooseMovePos = 'min';
  100. // this.isDrag = false;
  101. this.foundation = new SliderFoundation(this.adapter);
  102. this.eventListenerSet = new Set();
  103. }
  104. get adapter(): SliderAdapter {
  105. return {
  106. ...super.adapter,
  107. getSliderLengths: () => {
  108. if (this.sliderEl && this.sliderEl.current) {
  109. const rect = this.sliderEl.current.getBoundingClientRect();
  110. const offset = {
  111. x: this.sliderEl.current.offsetLeft,
  112. y: this.sliderEl.current.offsetTop,
  113. };
  114. return {
  115. sliderX: offset.x,
  116. sliderY: offset.y,
  117. sliderWidth: rect.width,
  118. sliderHeight: rect.height,
  119. };
  120. }
  121. return {
  122. sliderX: 0,
  123. sliderY: 0,
  124. sliderWidth: 0,
  125. sliderHeight: 0,
  126. };
  127. },
  128. getParentRect: (): DOMRect | undefined => {
  129. const parentObj = this.sliderEl && this.sliderEl.current && this.sliderEl.current.offsetParent;
  130. if (!parentObj) {
  131. return undefined;
  132. }
  133. return parentObj.getBoundingClientRect();
  134. },
  135. getScrollParentVal: () => {
  136. const scrollParent = this.foundation.getScrollParent(this.sliderEl.current);
  137. return {
  138. scrollTop: scrollParent.scrollTop,
  139. scrollLeft: scrollParent.scrollLeft,
  140. };
  141. },
  142. isEventFromHandle: (e: React.MouseEvent) => {
  143. const handles = [this.minHanleEl, this.maxHanleEl];
  144. let flag = false;
  145. handles.forEach(handle => {
  146. if (!handle) {
  147. return;
  148. }
  149. const handleInstance = handle && handle.current;
  150. const handleDom = ReactDOM.findDOMNode(handleInstance);
  151. if (handleDom && handleDom.contains(e.target as Node)) {
  152. flag = true;
  153. }
  154. });
  155. return flag;
  156. },
  157. getOverallVars: () => ({
  158. dragging: this.dragging,
  159. chooseMovePos: this.chooseMovePos,
  160. }),
  161. updateDisabled: (disabled: boolean) => {
  162. this.setState({ disabled });
  163. },
  164. transNewPropsToState<K extends keyof SliderState>(stateObj: Pick<SliderState, K>, callback = noop) {
  165. this.setState(stateObj, callback);
  166. },
  167. notifyChange: (cbValue: number | number[]) => this.props.onChange(cbValue),
  168. setDragging: (value: boolean[]) => {
  169. this.dragging = value;
  170. },
  171. updateCurrentValue: (value: number | number[]) => {
  172. const { currentValue } = this.state;
  173. if (value !== currentValue) {
  174. this.setState({ currentValue: value });
  175. }
  176. },
  177. setOverallVars: (key: string, value: any) => {
  178. this[key] = value;
  179. },
  180. getMinHandleEl: () => this.minHanleEl,
  181. getMaxHandleEl: () => this.maxHanleEl,
  182. onHandleDown: (e: React.MouseEvent) => {
  183. e.stopPropagation();
  184. e.preventDefault();
  185. this._addEventListener(document.body, 'mousemove', this.foundation.onHandleMove, false);
  186. this._addEventListener(document.body, 'mouseup', this.foundation.onHandleUp, false);
  187. this._addEventListener(document.body, 'touchmove', this.foundation.onHandleTouchMove, false);
  188. },
  189. onHandleMove: (mousePos: number, isMin: boolean, stateChangeCallback = noop): boolean | void => {
  190. const sliderDOMIsInRenderTree = this.foundation.checkAndUpdateIsInRenderTreeState();
  191. if (!sliderDOMIsInRenderTree) {
  192. return;
  193. }
  194. const { value, onChange } = this.props;
  195. const moveValue = this.foundation.transPosToValue(mousePos, isMin);
  196. if (moveValue === false) {
  197. return;
  198. }
  199. const outPutValue = this.foundation.outPutValue(moveValue);
  200. const { currentValue } = this.state;
  201. if (!isEqual(this.foundation.outPutValue(currentValue), outPutValue)) {
  202. onChange(outPutValue);
  203. if (this.foundation.valueFormatIsCorrect(value)) {
  204. return false;
  205. }
  206. this.setState({
  207. currentValue: outPutValue,
  208. }, stateChangeCallback);
  209. }
  210. },
  211. setEventDefault: (e: React.MouseEvent) => {
  212. e.stopPropagation();
  213. e.preventDefault();
  214. },
  215. setStateVal: <K extends keyof SliderState>(name: K, val: SliderState[K]) => {
  216. this.setState({ [name]: val } as Pick<SliderState, K>);
  217. },
  218. checkAndUpdateIsInRenderTreeState: () => {
  219. const sliderDOMIsInRenderTree = domIsInRenderTree(this.sliderEl.current);
  220. if (sliderDOMIsInRenderTree !== this.state.isInRenderTree) {
  221. this.setState({ isInRenderTree: sliderDOMIsInRenderTree });
  222. }
  223. return sliderDOMIsInRenderTree;
  224. },
  225. onHandleEnter: (pos: SliderState['focusPos']) => {
  226. this.setState({ focusPos: pos });
  227. },
  228. onHandleLeave: () => {
  229. this.setState({ focusPos: '' });
  230. },
  231. onHandleUpBefore: (e: React.MouseEvent) => {
  232. e.stopPropagation();
  233. e.preventDefault();
  234. document.body.removeEventListener('mousemove', this.foundation.onHandleMove, false);
  235. document.body.removeEventListener('mouseup', this.foundation.onHandleUp, false);
  236. },
  237. onHandleUpAfter: () => {
  238. const { currentValue } = this.state;
  239. const value = this.foundation.outPutValue(currentValue);
  240. this.props.onAfterChange(value);
  241. },
  242. unSubscribeEventListener: () => {
  243. Array.from(this.eventListenerSet).forEach(clear => clear());
  244. },
  245. };
  246. }
  247. componentDidMount() {
  248. this.foundation.init();
  249. }
  250. componentDidUpdate(prevProps: SliderProps, prevState: SliderState) {
  251. const hasPropValueChange = !isEqual(this.props.value, prevProps.value);
  252. const hasPropDisabledChange = this.props.disabled !== prevProps.disabled;
  253. if (hasPropDisabledChange) {
  254. this.foundation.handleDisabledChange(this.props.disabled);
  255. }
  256. if (hasPropValueChange) {
  257. const nextValue = this.props.value;
  258. const prevValue = this.state.currentValue;
  259. this.foundation.handleValueChange(prevValue, nextValue);
  260. }
  261. }
  262. componentWillUnmount() {
  263. this.foundation.destroy();
  264. }
  265. renderHandle = () => {
  266. const { vertical, range, tooltipVisible, tipFormatter } = this.props;
  267. const { chooseMovePos, isDrag, isInRenderTree } = this.state;
  268. const stylePos = vertical ? 'top' : 'left';
  269. const percentInfo = this.foundation.getMinAndMaxPercent(this.state.currentValue);
  270. const minPercent = percentInfo.min;
  271. const maxPercent = percentInfo.max;
  272. const { tipVisible, tipChildren } = this.foundation.computeHandleVisibleVal(
  273. tooltipVisible && isInRenderTree,
  274. tipFormatter,
  275. range
  276. );
  277. const transform = { top: 'translateY(-50%)', left: 'translateX(-50%)' };
  278. const minClass = cls(cssClasses.HANDLE, {
  279. [`${cssClasses.HANDLE}-clicked`]: chooseMovePos === 'min' && isDrag,
  280. });
  281. const maxClass = cls(cssClasses.HANDLE, {
  282. [`${cssClasses.HANDLE}-clicked`]: chooseMovePos === 'max' && isDrag,
  283. });
  284. const handleContents = !range ? (
  285. <Tooltip
  286. content={tipChildren.min}
  287. position="top"
  288. trigger="custom"
  289. rePosKey={minPercent}
  290. visible={isInRenderTree && tipVisible.min}
  291. className={`${cssClasses.HANDLE}-tooltip`}
  292. >
  293. <span
  294. onMouseOver={this.foundation.checkAndUpdateIsInRenderTreeState}
  295. ref={this.minHanleEl}
  296. className={minClass}
  297. style={{
  298. [stylePos]: `${minPercent * 100}%`,
  299. zIndex: chooseMovePos === 'min' && isDrag ? 2 : 1,
  300. transform: transform[stylePos],
  301. }}
  302. onMouseDown={e => {
  303. this.foundation.onHandleDown(e, 'min');
  304. }}
  305. onMouseEnter={() => {
  306. this.foundation.onHandleEnter('min');
  307. }}
  308. onTouchStart={e => {
  309. this.foundation.onHandleTouchStart(e, 'min');
  310. }}
  311. onMouseLeave={() => {
  312. this.foundation.onHandleLeave();
  313. }}
  314. onMouseUp={e => {
  315. this.foundation.onHandleUp(e);
  316. }}
  317. onKeyUp={e => {
  318. this.foundation.onHandleUp(e);
  319. }}
  320. onTouchEnd={e => {
  321. this.foundation.onHandleUp(e);
  322. }}
  323. />
  324. </Tooltip>
  325. ) : (
  326. <React.Fragment>
  327. <Tooltip
  328. content={tipChildren.min}
  329. position="top"
  330. trigger="custom"
  331. rePosKey={minPercent}
  332. visible={isInRenderTree && tipVisible.min}
  333. className={`${cssClasses.HANDLE}-tooltip`}
  334. >
  335. <span
  336. ref={this.minHanleEl}
  337. className={minClass}
  338. style={{
  339. [stylePos]: `${minPercent * 100}%`,
  340. zIndex: chooseMovePos === 'min' ? 2 : 1,
  341. transform: transform[stylePos],
  342. }}
  343. onMouseDown={e => {
  344. this.foundation.onHandleDown(e, 'min');
  345. }}
  346. onMouseEnter={() => {
  347. this.foundation.onHandleEnter('min');
  348. }}
  349. onTouchStart={e => {
  350. this.foundation.onHandleTouchStart(e, 'min');
  351. }}
  352. onMouseLeave={() => {
  353. this.foundation.onHandleLeave();
  354. }}
  355. onMouseUp={e => {
  356. this.foundation.onHandleUp(e);
  357. }}
  358. onKeyUp={e => {
  359. this.foundation.onHandleUp(e);
  360. }}
  361. onTouchEnd={e => {
  362. this.foundation.onHandleUp(e);
  363. }}
  364. />
  365. </Tooltip>
  366. <Tooltip
  367. content={tipChildren.max}
  368. position="top"
  369. trigger="custom"
  370. rePosKey={maxPercent}
  371. visible={isInRenderTree && tipVisible.max}
  372. className={`${cssClasses.HANDLE}-tooltip`}
  373. >
  374. <span
  375. ref={this.maxHanleEl}
  376. className={maxClass}
  377. style={{
  378. [stylePos]: `${maxPercent * 100}%`,
  379. zIndex: chooseMovePos === 'max' ? 2 : 1,
  380. transform: transform[stylePos],
  381. }}
  382. onMouseDown={e => {
  383. this.foundation.onHandleDown(e, 'max');
  384. }}
  385. onMouseEnter={() => {
  386. this.foundation.onHandleEnter('max');
  387. }}
  388. onMouseLeave={() => {
  389. this.foundation.onHandleLeave();
  390. }}
  391. onMouseUp={e => {
  392. this.foundation.onHandleUp(e);
  393. }}
  394. onKeyUp={e => {
  395. this.foundation.onHandleUp(e);
  396. }}
  397. onTouchStart={e => {
  398. this.foundation.onHandleTouchStart(e, 'max');
  399. }}
  400. onTouchEnd={e => {
  401. this.foundation.onHandleUp(e);
  402. }}
  403. />
  404. </Tooltip>
  405. </React.Fragment>
  406. );
  407. return handleContents;
  408. };
  409. renderTrack = () => {
  410. const { range, included, vertical } = this.props;
  411. const percentInfo = this.foundation.getMinAndMaxPercent(this.state.currentValue);
  412. const minPercent = percentInfo.min;
  413. const maxPercent = percentInfo.max;
  414. let trackStyle: CSSProperties = !vertical ?
  415. {
  416. width: range ? `${(maxPercent - minPercent) * 100}%` : `${minPercent * 100}%`,
  417. left: range ? `${minPercent * 100}%` : 0,
  418. } :
  419. {
  420. height: range ? `${(maxPercent - minPercent) * 100}%` : `${minPercent * 100}%`,
  421. top: range ? `${minPercent * 100}%` : 0,
  422. };
  423. trackStyle = included ? trackStyle : {};
  424. return (
  425. <div className={cssClasses.TRACK} style={trackStyle} onClick={e => this.foundation.handleWrapClick(e)}>
  426. {/* {this.renderTrack} */}
  427. </div>
  428. );
  429. };
  430. renderStepDot = () => {
  431. const { min, max, vertical, marks } = this.props;
  432. const stylePos = vertical ? 'top' : 'left';
  433. const labelContent =
  434. marks && Object.keys(marks).length > 0 ? (
  435. <div className={cssClasses.DOTS}>
  436. {Object.keys(marks).map(mark => {
  437. const activeResult = this.foundation.isMarkActive(Number(mark));
  438. const markClass = cls(`${prefixCls}-dot`, {
  439. [`${prefixCls}-dot-active`]: this.foundation.isMarkActive(Number(mark)) === 'active',
  440. });
  441. const markPercent = (Number(mark) - min) / (max - min);
  442. return activeResult ? (
  443. <span
  444. key={mark}
  445. className={markClass}
  446. style={{ [stylePos]: `calc(${markPercent * 100}% - 2px)` }}
  447. />
  448. ) : null;
  449. })}
  450. </div>
  451. ) : null;
  452. return labelContent;
  453. };
  454. renderLabel = () => {
  455. const { min, max, vertical, marks, verticalReverse } = this.props;
  456. const stylePos = vertical ? 'top' : 'left';
  457. const labelContent =
  458. marks && Object.keys(marks).length > 0 ? (
  459. <div className={cssClasses.MARKS + ((vertical && verticalReverse) ? '-reverse' : '')}>
  460. {Object.keys(marks).map(mark => {
  461. const activeResult = this.foundation.isMarkActive(Number(mark));
  462. const markPercent = (Number(mark) - min) / (max - min);
  463. return activeResult ? (
  464. <span
  465. key={mark}
  466. className={cls(`${prefixCls}-mark${(vertical && verticalReverse) ? '-reverse' : ''}`)}
  467. style={{ [stylePos]: `${markPercent * 100}%` }}
  468. >
  469. {marks[mark]}
  470. </span>
  471. ) : null;
  472. })}
  473. </div>
  474. ) : null;
  475. return labelContent;
  476. };
  477. render() {
  478. const wrapperClass = cls(
  479. `${prefixCls}-wrapper`,
  480. {
  481. [`${prefixCls}-disabled`]: this.state.disabled,
  482. [`${cssClasses.VERTICAL}-wrapper`]: this.props.vertical,
  483. [`${prefixCls}-reverse`]: this.props.vertical && this.props.verticalReverse
  484. },
  485. this.props.className
  486. );
  487. const boundaryClass = cls(`${prefixCls}-boundary`, {
  488. [`${prefixCls}-boundary-show`]: this.props.showBoundary && this.state.showBoundary,
  489. });
  490. const sliderCls = cls({
  491. [`${prefixCls}`]: !this.props.vertical,
  492. [cssClasses.VERTICAL]: this.props.vertical,
  493. });
  494. const slider = (
  495. <div
  496. className={wrapperClass}
  497. style={this.props.style}
  498. ref={this.sliderEl}
  499. onMouseEnter={() => this.foundation.handleWrapperEnter()}
  500. onMouseLeave={() => this.foundation.handleWrapperLeave()}
  501. >
  502. <div
  503. className={`${prefixCls}-rail`}
  504. onClick={e => this.foundation.handleWrapClick(e)}
  505. style={this.props.railStyle}
  506. />
  507. {this.renderTrack()}
  508. {this.renderStepDot()}
  509. <div>{this.renderHandle()}</div>
  510. {this.renderLabel()}
  511. <div className={boundaryClass}>
  512. <span className={`${prefixCls}-boundary-min`}>{this.state.min}</span>
  513. <span className={`${prefixCls}-boundary-max`}>{this.state.max}</span>
  514. </div>
  515. </div>
  516. );
  517. if (!this.props.vertical) {
  518. return <div className={sliderCls}>{slider}</div>;
  519. }
  520. return slider;
  521. }
  522. private _addEventListener<T extends keyof HTMLElementEventMap>(target: HTMLElement, eventName: T, callback: (e: HTMLElementEventMap[T]) => void, ...rests: any) {
  523. if (target.addEventListener) {
  524. target.addEventListener(eventName, callback, ...rests);
  525. const clearSelf = () => {
  526. target?.removeEventListener(eventName, callback);
  527. Promise.resolve().then(() => {
  528. this.eventListenerSet.delete(clearSelf);
  529. });
  530. };
  531. this.eventListenerSet.add(clearSelf);
  532. return clearSelf;
  533. } else {
  534. return noop;
  535. }
  536. }
  537. }