1
0

index.tsx 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598
  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';
  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. foundation: SliderFoundation;
  76. constructor(props: SliderProps) {
  77. super(props);
  78. let { value } = this.props;
  79. if (!value) {
  80. value = this.props.defaultValue;
  81. }
  82. this.state = {
  83. // eslint-disable-next-line no-nested-ternary
  84. currentValue: value ? value : this.props.range ? [0, 0] : 0,
  85. min: this.props.min || 0,
  86. max: this.props.max || 0,
  87. focusPos: '',
  88. onChange: this.props.onChange,
  89. disabled: this.props.disabled || false,
  90. chooseMovePos: '',
  91. isDrag: false,
  92. clickValue: 0,
  93. showBoundary: false,
  94. isInRenderTree: true
  95. };
  96. this.sliderEl = React.createRef();
  97. this.minHanleEl = React.createRef();
  98. this.maxHanleEl = React.createRef();
  99. this.dragging = [false, false];
  100. // this.chooseMovePos = 'min';
  101. // this.isDrag = false;
  102. this.foundation = new SliderFoundation(this.adapter);
  103. this.eventListenerSet = new Set();
  104. }
  105. get adapter(): SliderAdapter {
  106. return {
  107. ...super.adapter,
  108. getSliderLengths: () => {
  109. if (this.sliderEl && this.sliderEl.current) {
  110. const rect = this.sliderEl.current.getBoundingClientRect();
  111. const offset = {
  112. x: this.sliderEl.current.offsetLeft,
  113. y: this.sliderEl.current.offsetTop,
  114. };
  115. return {
  116. sliderX: offset.x,
  117. sliderY: offset.y,
  118. sliderWidth: rect.width,
  119. sliderHeight: rect.height,
  120. };
  121. }
  122. return {
  123. sliderX: 0,
  124. sliderY: 0,
  125. sliderWidth: 0,
  126. sliderHeight: 0,
  127. };
  128. },
  129. getParentRect: (): DOMRect | undefined => {
  130. const parentObj = this.sliderEl && this.sliderEl.current && this.sliderEl.current.offsetParent;
  131. if (!parentObj) {
  132. return undefined;
  133. }
  134. return parentObj.getBoundingClientRect();
  135. },
  136. getScrollParentVal: () => {
  137. const scrollParent = this.foundation.getScrollParent(this.sliderEl.current);
  138. return {
  139. scrollTop: scrollParent.scrollTop,
  140. scrollLeft: scrollParent.scrollLeft,
  141. };
  142. },
  143. isEventFromHandle: (e: React.MouseEvent) => {
  144. const handles = [this.minHanleEl, this.maxHanleEl];
  145. let flag = false;
  146. handles.forEach(handle => {
  147. if (!handle) {
  148. return;
  149. }
  150. const handleInstance = handle && handle.current;
  151. const handleDom = ReactDOM.findDOMNode(handleInstance);
  152. if (handleDom && handleDom.contains(e.target as Node)) {
  153. flag = true;
  154. }
  155. });
  156. return flag;
  157. },
  158. getOverallVars: () => ({
  159. dragging: this.dragging,
  160. chooseMovePos: this.chooseMovePos,
  161. }),
  162. updateDisabled: (disabled: boolean) => {
  163. this.setState({ disabled });
  164. },
  165. transNewPropsToState<K extends keyof SliderState>(stateObj: Pick<SliderState, K>, callback = noop) {
  166. this.setState(stateObj, callback);
  167. },
  168. notifyChange: (cbValue: number | number[]) => this.props.onChange(cbValue),
  169. setDragging: (value: boolean[]) => {
  170. this.dragging = value;
  171. },
  172. updateCurrentValue: (value: number | number[]) => {
  173. const { currentValue } = this.state;
  174. if (value !== currentValue) {
  175. this.setState({ currentValue: value });
  176. }
  177. },
  178. setOverallVars: (key: string, value: any) => {
  179. this[key] = value;
  180. },
  181. getMinHandleEl: () => this.minHanleEl,
  182. getMaxHandleEl: () => this.maxHanleEl,
  183. onHandleDown: (e: React.MouseEvent) => {
  184. e.stopPropagation();
  185. e.preventDefault();
  186. this._addEventListener(document.body, 'mousemove', this.foundation.onHandleMove, false);
  187. this._addEventListener(document.body, 'mouseup', this.foundation.onHandleUp, false);
  188. this._addEventListener(document.body, 'touchmove', this.foundation.onHandleTouchMove, false);
  189. },
  190. onHandleMove: (mousePos: number, isMin: boolean, stateChangeCallback = noop, clickTrack = false): boolean | void => {
  191. const sliderDOMIsInRenderTree = this.foundation.checkAndUpdateIsInRenderTreeState();
  192. if (!sliderDOMIsInRenderTree) {
  193. return;
  194. }
  195. const { value, onChange } = this.props;
  196. const moveValue = this.foundation.transPosToValue(mousePos, isMin);
  197. if (moveValue === false) {
  198. return;
  199. }
  200. const outPutValue = this.foundation.outPutValue(moveValue);
  201. const { currentValue } = this.state;
  202. if (!isEqual(this.foundation.outPutValue(currentValue), outPutValue)) {
  203. onChange(outPutValue);
  204. if (!clickTrack && this.foundation.valueFormatIsCorrect(value)) {
  205. // still require afterChangeCallback when click on the track directly, need skip here
  206. return false;
  207. }
  208. this.setState({
  209. currentValue: outPutValue,
  210. }, stateChangeCallback);
  211. }
  212. },
  213. setEventDefault: (e: React.MouseEvent) => {
  214. e.stopPropagation();
  215. e.preventDefault();
  216. },
  217. setStateVal: <K extends keyof SliderState>(name: K, val: SliderState[K]) => {
  218. this.setState({ [name]: val } as Pick<SliderState, K>);
  219. },
  220. checkAndUpdateIsInRenderTreeState: () => {
  221. const sliderDOMIsInRenderTree = domIsInRenderTree(this.sliderEl.current);
  222. if (sliderDOMIsInRenderTree !== this.state.isInRenderTree) {
  223. this.setState({ isInRenderTree: sliderDOMIsInRenderTree });
  224. }
  225. return sliderDOMIsInRenderTree;
  226. },
  227. onHandleEnter: (pos: SliderState['focusPos']) => {
  228. this.setState({ focusPos: pos });
  229. },
  230. onHandleLeave: () => {
  231. this.setState({ focusPos: '' });
  232. },
  233. onHandleUpBefore: (e: React.MouseEvent) => {
  234. e.stopPropagation();
  235. e.preventDefault();
  236. document.body.removeEventListener('mousemove', this.foundation.onHandleMove, false);
  237. document.body.removeEventListener('mouseup', this.foundation.onHandleUp, false);
  238. },
  239. onHandleUpAfter: () => {
  240. const { currentValue } = this.state;
  241. const value = this.foundation.outPutValue(currentValue);
  242. this.props.onAfterChange(value);
  243. },
  244. unSubscribeEventListener: () => {
  245. Array.from(this.eventListenerSet).forEach(clear => clear());
  246. },
  247. };
  248. }
  249. componentDidMount() {
  250. this.foundation.init();
  251. }
  252. componentDidUpdate(prevProps: SliderProps, prevState: SliderState) {
  253. const hasPropValueChange = !isEqual(this.props.value, prevProps.value);
  254. const hasPropDisabledChange = this.props.disabled !== prevProps.disabled;
  255. if (hasPropDisabledChange) {
  256. this.foundation.handleDisabledChange(this.props.disabled);
  257. }
  258. if (hasPropValueChange) {
  259. const nextValue = this.props.value;
  260. const prevValue = this.state.currentValue;
  261. this.foundation.handleValueChange(prevValue, nextValue);
  262. }
  263. }
  264. componentWillUnmount() {
  265. this.foundation.destroy();
  266. }
  267. renderHandle = () => {
  268. const { vertical, range, tooltipVisible, tipFormatter, 'aria-label': ariaLabel, 'aria-labelledby': ariaLabelledby, 'aria-valuetext': ariaValueText, getAriaValueText, disabled } = this.props;
  269. const { chooseMovePos, isDrag, isInRenderTree } = this.state;
  270. const stylePos = vertical ? 'top' : 'left';
  271. const percentInfo = this.foundation.getMinAndMaxPercent(this.state.currentValue);
  272. const minPercent = percentInfo.min;
  273. const maxPercent = percentInfo.max;
  274. const { tipVisible, tipChildren } = this.foundation.computeHandleVisibleVal(
  275. tooltipVisible && isInRenderTree,
  276. tipFormatter,
  277. range
  278. );
  279. const transform = { top: 'translateY(-50%)', left: 'translateX(-50%)' };
  280. const minClass = cls(cssClasses.HANDLE, {
  281. [`${cssClasses.HANDLE}-clicked`]: chooseMovePos === 'min' && isDrag,
  282. });
  283. const maxClass = cls(cssClasses.HANDLE, {
  284. [`${cssClasses.HANDLE}-clicked`]: chooseMovePos === 'max' && isDrag,
  285. });
  286. const {min, max, currentValue} = this.state;
  287. const commonAria = {
  288. 'aria-label': ariaLabel,
  289. 'aria-labelledby': ariaLabelledby,
  290. 'aria-disabled': disabled
  291. };
  292. vertical && Object.assign(commonAria, {'aria-orientation': 'vertical'});
  293. const handleContents = !range ? (
  294. <Tooltip
  295. content={tipChildren.min}
  296. position="top"
  297. trigger="custom"
  298. rePosKey={minPercent}
  299. visible={isInRenderTree && tipVisible.min}
  300. className={`${cssClasses.HANDLE}-tooltip`}
  301. >
  302. <span
  303. onMouseOver={this.foundation.checkAndUpdateIsInRenderTreeState}
  304. ref={this.minHanleEl}
  305. className={minClass}
  306. style={{
  307. [stylePos]: `${minPercent * 100}%`,
  308. zIndex: chooseMovePos === 'min' && isDrag ? 2 : 1,
  309. transform: transform[stylePos],
  310. }}
  311. onMouseDown={e => {
  312. this.foundation.onHandleDown(e, 'min');
  313. }}
  314. onMouseEnter={() => {
  315. this.foundation.onHandleEnter('min');
  316. }}
  317. onTouchStart={e => {
  318. this.foundation.onHandleTouchStart(e, 'min');
  319. }}
  320. onMouseLeave={() => {
  321. this.foundation.onHandleLeave();
  322. }}
  323. onMouseUp={e => {
  324. this.foundation.onHandleUp(e);
  325. }}
  326. onKeyUp={e => {
  327. this.foundation.onHandleUp(e);
  328. }}
  329. onTouchEnd={e => {
  330. this.foundation.onHandleUp(e);
  331. }}
  332. onFocus={e => this.foundation.onFocus(e, 'min')}
  333. role="slider"
  334. tabIndex={0}
  335. {...commonAria}
  336. aria-valuenow={currentValue as number}
  337. aria-valuemax={max}
  338. aria-valuemin={min}
  339. aria-valuetext={getAriaValueText ? getAriaValueText(currentValue as number) : ariaValueText}
  340. />
  341. </Tooltip>
  342. ) : (
  343. <React.Fragment>
  344. <Tooltip
  345. content={tipChildren.min}
  346. position="top"
  347. trigger="custom"
  348. rePosKey={minPercent}
  349. visible={isInRenderTree && tipVisible.min}
  350. className={`${cssClasses.HANDLE}-tooltip`}
  351. >
  352. <span
  353. ref={this.minHanleEl}
  354. className={minClass}
  355. style={{
  356. [stylePos]: `${minPercent * 100}%`,
  357. zIndex: chooseMovePos === 'min' ? 2 : 1,
  358. transform: transform[stylePos],
  359. }}
  360. onMouseDown={e => {
  361. this.foundation.onHandleDown(e, 'min');
  362. }}
  363. onMouseEnter={() => {
  364. this.foundation.onHandleEnter('min');
  365. }}
  366. onTouchStart={e => {
  367. this.foundation.onHandleTouchStart(e, 'min');
  368. }}
  369. onMouseLeave={() => {
  370. this.foundation.onHandleLeave();
  371. }}
  372. onMouseUp={e => {
  373. this.foundation.onHandleUp(e);
  374. }}
  375. onKeyUp={e => {
  376. this.foundation.onHandleUp(e);
  377. }}
  378. onTouchEnd={e => {
  379. this.foundation.onHandleUp(e);
  380. }}
  381. onFocus={e => this.foundation.onFocus(e, 'min')}
  382. role="slider"
  383. tabIndex={0}
  384. {...commonAria}
  385. aria-valuenow={currentValue[0]}
  386. aria-valuetext={getAriaValueText ? getAriaValueText(currentValue[0]) : ariaValueText}
  387. aria-valuemax={currentValue[1]}
  388. aria-valuemin={min}
  389. />
  390. </Tooltip>
  391. <Tooltip
  392. content={tipChildren.max}
  393. position="top"
  394. trigger="custom"
  395. rePosKey={maxPercent}
  396. visible={isInRenderTree && tipVisible.max}
  397. className={`${cssClasses.HANDLE}-tooltip`}
  398. >
  399. <span
  400. ref={this.maxHanleEl}
  401. className={maxClass}
  402. style={{
  403. [stylePos]: `${maxPercent * 100}%`,
  404. zIndex: chooseMovePos === 'max' ? 2 : 1,
  405. transform: transform[stylePos],
  406. }}
  407. onMouseDown={e => {
  408. this.foundation.onHandleDown(e, 'max');
  409. }}
  410. onMouseEnter={() => {
  411. this.foundation.onHandleEnter('max');
  412. }}
  413. onMouseLeave={() => {
  414. this.foundation.onHandleLeave();
  415. }}
  416. onMouseUp={e => {
  417. this.foundation.onHandleUp(e);
  418. }}
  419. onKeyUp={e => {
  420. this.foundation.onHandleUp(e);
  421. }}
  422. onTouchStart={e => {
  423. this.foundation.onHandleTouchStart(e, 'max');
  424. }}
  425. onTouchEnd={e => {
  426. this.foundation.onHandleUp(e);
  427. }}
  428. onFocus={e => this.foundation.onFocus(e, 'min')}
  429. role="slider"
  430. tabIndex={0}
  431. {...commonAria}
  432. aria-valuenow={currentValue[1]}
  433. aria-valuetext={getAriaValueText ? getAriaValueText(currentValue[1]) : ariaValueText}
  434. aria-valuemax={max}
  435. aria-valuemin={currentValue[0]}
  436. />
  437. </Tooltip>
  438. </React.Fragment>
  439. );
  440. return handleContents;
  441. };
  442. renderTrack = () => {
  443. const { range, included, vertical } = this.props;
  444. const percentInfo = this.foundation.getMinAndMaxPercent(this.state.currentValue);
  445. const minPercent = percentInfo.min;
  446. const maxPercent = percentInfo.max;
  447. let trackStyle: CSSProperties = !vertical ?
  448. {
  449. width: range ? `${(maxPercent - minPercent) * 100}%` : `${minPercent * 100}%`,
  450. left: range ? `${minPercent * 100}%` : 0,
  451. } :
  452. {
  453. height: range ? `${(maxPercent - minPercent) * 100}%` : `${minPercent * 100}%`,
  454. top: range ? `${minPercent * 100}%` : 0,
  455. };
  456. trackStyle = included ? trackStyle : {};
  457. return (// eslint-disable-next-line jsx-a11y/click-events-have-key-events, jsx-a11y/no-static-element-interactions
  458. <div className={cssClasses.TRACK} style={trackStyle} onClick={e => this.foundation.handleWrapClick(e)}>
  459. {/* {this.renderTrack} */}
  460. </div>
  461. );
  462. };
  463. renderStepDot = () => {
  464. const { min, max, vertical, marks } = this.props;
  465. const stylePos = vertical ? 'top' : 'left';
  466. const labelContent =
  467. marks && Object.keys(marks).length > 0 ? (
  468. <div className={cssClasses.DOTS}>
  469. {Object.keys(marks).map(mark => {
  470. const activeResult = this.foundation.isMarkActive(Number(mark));
  471. const markClass = cls(`${prefixCls}-dot`, {
  472. [`${prefixCls}-dot-active`]: this.foundation.isMarkActive(Number(mark)) === 'active',
  473. });
  474. const markPercent = (Number(mark) - min) / (max - min);
  475. return activeResult ? (
  476. <span
  477. key={mark}
  478. onClick={e => this.foundation.handleWrapClick(e)}
  479. className={markClass}
  480. style={{ [stylePos]: `calc(${markPercent * 100}% - 2px)` }}
  481. />
  482. ) : null;
  483. })}
  484. </div>
  485. ) : null;
  486. return labelContent;
  487. };
  488. renderLabel = () => {
  489. const { min, max, vertical, marks, verticalReverse } = this.props;
  490. const stylePos = vertical ? 'top' : 'left';
  491. const labelContent =
  492. marks && Object.keys(marks).length > 0 ? (
  493. <div className={cssClasses.MARKS + ((vertical && verticalReverse) ? '-reverse' : '')}>
  494. {Object.keys(marks).map(mark => {
  495. const activeResult = this.foundation.isMarkActive(Number(mark));
  496. const markPercent = (Number(mark) - min) / (max - min);
  497. return activeResult ? (
  498. <span
  499. key={mark}
  500. className={cls(`${prefixCls}-mark${(vertical && verticalReverse) ? '-reverse' : ''}`)}
  501. style={{ [stylePos]: `${markPercent * 100}%` }}
  502. >
  503. {marks[mark]}
  504. </span>
  505. ) : null;
  506. })}
  507. </div>
  508. ) : null;
  509. return labelContent;
  510. };
  511. render() {
  512. const wrapperClass = cls(
  513. `${prefixCls}-wrapper`,
  514. {
  515. [`${prefixCls}-disabled`]: this.state.disabled,
  516. [`${cssClasses.VERTICAL}-wrapper`]: this.props.vertical,
  517. [`${prefixCls}-reverse`]: this.props.vertical && this.props.verticalReverse
  518. },
  519. this.props.className
  520. );
  521. const boundaryClass = cls(`${prefixCls}-boundary`, {
  522. [`${prefixCls}-boundary-show`]: this.props.showBoundary && this.state.showBoundary,
  523. });
  524. const sliderCls = cls({
  525. [`${prefixCls}`]: !this.props.vertical,
  526. [cssClasses.VERTICAL]: this.props.vertical,
  527. });
  528. const slider = (
  529. <div
  530. className={wrapperClass}
  531. style={this.props.style}
  532. ref={this.sliderEl}
  533. onMouseEnter={() => this.foundation.handleWrapperEnter()}
  534. onMouseLeave={() => this.foundation.handleWrapperLeave()}
  535. >
  536. {// eslint-disable-next-line jsx-a11y/click-events-have-key-events, jsx-a11y/no-static-element-interactions
  537. <div
  538. className={`${prefixCls}-rail`}
  539. onClick={e => this.foundation.handleWrapClick(e)}
  540. style={this.props.railStyle}
  541. />
  542. }
  543. {this.renderTrack()}
  544. {this.renderStepDot()}
  545. <div>{this.renderHandle()}</div>
  546. {this.renderLabel()}
  547. <div className={boundaryClass}>
  548. <span className={`${prefixCls}-boundary-min`}>{this.state.min}</span>
  549. <span className={`${prefixCls}-boundary-max`}>{this.state.max}</span>
  550. </div>
  551. </div>
  552. );
  553. if (!this.props.vertical) {
  554. return <div className={sliderCls}>{slider}</div>;
  555. }
  556. return slider;
  557. }
  558. private _addEventListener<T extends keyof HTMLElementEventMap>(target: HTMLElement, eventName: T, callback: (e: HTMLElementEventMap[T]) => void, ...rests: any) {
  559. if (target.addEventListener) {
  560. target.addEventListener(eventName, callback, ...rests);
  561. const clearSelf = () => {
  562. target?.removeEventListener(eventName, callback);
  563. Promise.resolve().then(() => {
  564. this.eventListenerSet.delete(clearSelf);
  565. });
  566. };
  567. this.eventListenerSet.add(clearSelf);
  568. return clearSelf;
  569. } else {
  570. return noop;
  571. }
  572. }
  573. }