index.tsx 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561
  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, tipFormatterBasicType } 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: tipFormatterBasicType | tipFormatterBasicType[]) => 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, clickTrack = false): 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 (!clickTrack && this.foundation.valueFormatIsCorrect(value)) {
  204. // still require afterChangeCallback when click on the track directly, need skip here
  205. return false;
  206. }
  207. this.setState({
  208. currentValue: outPutValue,
  209. }, stateChangeCallback);
  210. }
  211. },
  212. setEventDefault: (e: React.MouseEvent) => {
  213. e.stopPropagation();
  214. e.preventDefault();
  215. },
  216. setStateVal: <K extends keyof SliderState>(name: K, val: SliderState[K]) => {
  217. this.setState({ [name]: val } as Pick<SliderState, K>);
  218. },
  219. checkAndUpdateIsInRenderTreeState: () => {
  220. const sliderDOMIsInRenderTree = domIsInRenderTree(this.sliderEl.current);
  221. if (sliderDOMIsInRenderTree !== this.state.isInRenderTree) {
  222. this.setState({ isInRenderTree: sliderDOMIsInRenderTree });
  223. }
  224. return sliderDOMIsInRenderTree;
  225. },
  226. onHandleEnter: (pos: SliderState['focusPos']) => {
  227. this.setState({ focusPos: pos });
  228. },
  229. onHandleLeave: () => {
  230. this.setState({ focusPos: '' });
  231. },
  232. onHandleUpBefore: (e: React.MouseEvent) => {
  233. e.stopPropagation();
  234. e.preventDefault();
  235. document.body.removeEventListener('mousemove', this.foundation.onHandleMove, false);
  236. document.body.removeEventListener('mouseup', this.foundation.onHandleUp, false);
  237. },
  238. onHandleUpAfter: () => {
  239. const { currentValue } = this.state;
  240. const value = this.foundation.outPutValue(currentValue);
  241. this.props.onAfterChange(value);
  242. },
  243. unSubscribeEventListener: () => {
  244. Array.from(this.eventListenerSet).forEach(clear => clear());
  245. },
  246. };
  247. }
  248. componentDidMount() {
  249. this.foundation.init();
  250. }
  251. componentDidUpdate(prevProps: SliderProps, prevState: SliderState) {
  252. const hasPropValueChange = !isEqual(this.props.value, prevProps.value);
  253. const hasPropDisabledChange = this.props.disabled !== prevProps.disabled;
  254. if (hasPropDisabledChange) {
  255. this.foundation.handleDisabledChange(this.props.disabled);
  256. }
  257. if (hasPropValueChange) {
  258. const nextValue = this.props.value;
  259. const prevValue = this.state.currentValue;
  260. this.foundation.handleValueChange(prevValue, nextValue);
  261. }
  262. }
  263. componentWillUnmount() {
  264. this.foundation.destroy();
  265. }
  266. renderHandle = () => {
  267. const { vertical, range, tooltipVisible, tipFormatter } = this.props;
  268. const { chooseMovePos, isDrag, isInRenderTree } = this.state;
  269. const stylePos = vertical ? 'top' : 'left';
  270. const percentInfo = this.foundation.getMinAndMaxPercent(this.state.currentValue);
  271. const minPercent = percentInfo.min;
  272. const maxPercent = percentInfo.max;
  273. const { tipVisible, tipChildren } = this.foundation.computeHandleVisibleVal(
  274. tooltipVisible && isInRenderTree,
  275. tipFormatter,
  276. range
  277. );
  278. const transform = { top: 'translateY(-50%)', left: 'translateX(-50%)' };
  279. const minClass = cls(cssClasses.HANDLE, {
  280. [`${cssClasses.HANDLE}-clicked`]: chooseMovePos === 'min' && isDrag,
  281. });
  282. const maxClass = cls(cssClasses.HANDLE, {
  283. [`${cssClasses.HANDLE}-clicked`]: chooseMovePos === 'max' && isDrag,
  284. });
  285. const handleContents = !range ? (
  286. <Tooltip
  287. content={tipChildren.min}
  288. position="top"
  289. trigger="custom"
  290. rePosKey={minPercent}
  291. visible={isInRenderTree && tipVisible.min}
  292. className={`${cssClasses.HANDLE}-tooltip`}
  293. >
  294. <span
  295. onMouseOver={this.foundation.checkAndUpdateIsInRenderTreeState}
  296. ref={this.minHanleEl}
  297. className={minClass}
  298. style={{
  299. [stylePos]: `${minPercent * 100}%`,
  300. zIndex: chooseMovePos === 'min' && isDrag ? 2 : 1,
  301. transform: transform[stylePos],
  302. }}
  303. onMouseDown={e => {
  304. this.foundation.onHandleDown(e, 'min');
  305. }}
  306. onMouseEnter={() => {
  307. this.foundation.onHandleEnter('min');
  308. }}
  309. onTouchStart={e => {
  310. this.foundation.onHandleTouchStart(e, 'min');
  311. }}
  312. onMouseLeave={() => {
  313. this.foundation.onHandleLeave();
  314. }}
  315. onMouseUp={e => {
  316. this.foundation.onHandleUp(e);
  317. }}
  318. onKeyUp={e => {
  319. this.foundation.onHandleUp(e);
  320. }}
  321. onTouchEnd={e => {
  322. this.foundation.onHandleUp(e);
  323. }}
  324. />
  325. </Tooltip>
  326. ) : (
  327. <React.Fragment>
  328. <Tooltip
  329. content={tipChildren.min}
  330. position="top"
  331. trigger="custom"
  332. rePosKey={minPercent}
  333. visible={isInRenderTree && tipVisible.min}
  334. className={`${cssClasses.HANDLE}-tooltip`}
  335. >
  336. <span
  337. ref={this.minHanleEl}
  338. className={minClass}
  339. style={{
  340. [stylePos]: `${minPercent * 100}%`,
  341. zIndex: chooseMovePos === 'min' ? 2 : 1,
  342. transform: transform[stylePos],
  343. }}
  344. onMouseDown={e => {
  345. this.foundation.onHandleDown(e, 'min');
  346. }}
  347. onMouseEnter={() => {
  348. this.foundation.onHandleEnter('min');
  349. }}
  350. onTouchStart={e => {
  351. this.foundation.onHandleTouchStart(e, 'min');
  352. }}
  353. onMouseLeave={() => {
  354. this.foundation.onHandleLeave();
  355. }}
  356. onMouseUp={e => {
  357. this.foundation.onHandleUp(e);
  358. }}
  359. onKeyUp={e => {
  360. this.foundation.onHandleUp(e);
  361. }}
  362. onTouchEnd={e => {
  363. this.foundation.onHandleUp(e);
  364. }}
  365. />
  366. </Tooltip>
  367. <Tooltip
  368. content={tipChildren.max}
  369. position="top"
  370. trigger="custom"
  371. rePosKey={maxPercent}
  372. visible={isInRenderTree && tipVisible.max}
  373. className={`${cssClasses.HANDLE}-tooltip`}
  374. >
  375. <span
  376. ref={this.maxHanleEl}
  377. className={maxClass}
  378. style={{
  379. [stylePos]: `${maxPercent * 100}%`,
  380. zIndex: chooseMovePos === 'max' ? 2 : 1,
  381. transform: transform[stylePos],
  382. }}
  383. onMouseDown={e => {
  384. this.foundation.onHandleDown(e, 'max');
  385. }}
  386. onMouseEnter={() => {
  387. this.foundation.onHandleEnter('max');
  388. }}
  389. onMouseLeave={() => {
  390. this.foundation.onHandleLeave();
  391. }}
  392. onMouseUp={e => {
  393. this.foundation.onHandleUp(e);
  394. }}
  395. onKeyUp={e => {
  396. this.foundation.onHandleUp(e);
  397. }}
  398. onTouchStart={e => {
  399. this.foundation.onHandleTouchStart(e, 'max');
  400. }}
  401. onTouchEnd={e => {
  402. this.foundation.onHandleUp(e);
  403. }}
  404. />
  405. </Tooltip>
  406. </React.Fragment>
  407. );
  408. return handleContents;
  409. };
  410. renderTrack = () => {
  411. const { range, included, vertical } = this.props;
  412. const percentInfo = this.foundation.getMinAndMaxPercent(this.state.currentValue);
  413. const minPercent = percentInfo.min;
  414. const maxPercent = percentInfo.max;
  415. let trackStyle: CSSProperties = !vertical ?
  416. {
  417. width: range ? `${(maxPercent - minPercent) * 100}%` : `${minPercent * 100}%`,
  418. left: range ? `${minPercent * 100}%` : 0,
  419. } :
  420. {
  421. height: range ? `${(maxPercent - minPercent) * 100}%` : `${minPercent * 100}%`,
  422. top: range ? `${minPercent * 100}%` : 0,
  423. };
  424. trackStyle = included ? trackStyle : {};
  425. return (
  426. <div className={cssClasses.TRACK} style={trackStyle} onClick={e => this.foundation.handleWrapClick(e)}>
  427. {/* {this.renderTrack} */}
  428. </div>
  429. );
  430. };
  431. renderStepDot = () => {
  432. const { min, max, vertical, marks } = this.props;
  433. const stylePos = vertical ? 'top' : 'left';
  434. const labelContent =
  435. marks && Object.keys(marks).length > 0 ? (
  436. <div className={cssClasses.DOTS}>
  437. {Object.keys(marks).map(mark => {
  438. const activeResult = this.foundation.isMarkActive(Number(mark));
  439. const markClass = cls(`${prefixCls}-dot`, {
  440. [`${prefixCls}-dot-active`]: this.foundation.isMarkActive(Number(mark)) === 'active',
  441. });
  442. const markPercent = (Number(mark) - min) / (max - min);
  443. return activeResult ? (
  444. <span
  445. key={mark}
  446. className={markClass}
  447. style={{ [stylePos]: `calc(${markPercent * 100}% - 2px)` }}
  448. />
  449. ) : null;
  450. })}
  451. </div>
  452. ) : null;
  453. return labelContent;
  454. };
  455. renderLabel = () => {
  456. const { min, max, vertical, marks, verticalReverse } = this.props;
  457. const stylePos = vertical ? 'top' : 'left';
  458. const labelContent =
  459. marks && Object.keys(marks).length > 0 ? (
  460. <div className={cssClasses.MARKS + ((vertical && verticalReverse) ? '-reverse' : '')}>
  461. {Object.keys(marks).map(mark => {
  462. const activeResult = this.foundation.isMarkActive(Number(mark));
  463. const markPercent = (Number(mark) - min) / (max - min);
  464. return activeResult ? (
  465. <span
  466. key={mark}
  467. className={cls(`${prefixCls}-mark${(vertical && verticalReverse) ? '-reverse' : ''}`)}
  468. style={{ [stylePos]: `${markPercent * 100}%` }}
  469. >
  470. {marks[mark]}
  471. </span>
  472. ) : null;
  473. })}
  474. </div>
  475. ) : null;
  476. return labelContent;
  477. };
  478. render() {
  479. const wrapperClass = cls(
  480. `${prefixCls}-wrapper`,
  481. {
  482. [`${prefixCls}-disabled`]: this.state.disabled,
  483. [`${cssClasses.VERTICAL}-wrapper`]: this.props.vertical,
  484. [`${prefixCls}-reverse`]: this.props.vertical && this.props.verticalReverse
  485. },
  486. this.props.className
  487. );
  488. const boundaryClass = cls(`${prefixCls}-boundary`, {
  489. [`${prefixCls}-boundary-show`]: this.props.showBoundary && this.state.showBoundary,
  490. });
  491. const sliderCls = cls({
  492. [`${prefixCls}`]: !this.props.vertical,
  493. [cssClasses.VERTICAL]: this.props.vertical,
  494. });
  495. const slider = (
  496. <div
  497. className={wrapperClass}
  498. style={this.props.style}
  499. ref={this.sliderEl}
  500. onMouseEnter={() => this.foundation.handleWrapperEnter()}
  501. onMouseLeave={() => this.foundation.handleWrapperLeave()}
  502. >
  503. <div
  504. className={`${prefixCls}-rail`}
  505. onClick={e => this.foundation.handleWrapClick(e)}
  506. style={this.props.railStyle}
  507. />
  508. {this.renderTrack()}
  509. {this.renderStepDot()}
  510. <div>{this.renderHandle()}</div>
  511. {this.renderLabel()}
  512. <div className={boundaryClass}>
  513. <span className={`${prefixCls}-boundary-min`}>{this.state.min}</span>
  514. <span className={`${prefixCls}-boundary-max`}>{this.state.max}</span>
  515. </div>
  516. </div>
  517. );
  518. if (!this.props.vertical) {
  519. return <div className={sliderCls}>{slider}</div>;
  520. }
  521. return slider;
  522. }
  523. private _addEventListener<T extends keyof HTMLElementEventMap>(target: HTMLElement, eventName: T, callback: (e: HTMLElementEventMap[T]) => void, ...rests: any) {
  524. if (target.addEventListener) {
  525. target.addEventListener(eventName, callback, ...rests);
  526. const clearSelf = () => {
  527. target?.removeEventListener(eventName, callback);
  528. Promise.resolve().then(() => {
  529. this.eventListenerSet.delete(clearSelf);
  530. });
  531. };
  532. this.eventListenerSet.add(clearSelf);
  533. return clearSelf;
  534. } else {
  535. return noop;
  536. }
  537. }
  538. }