index.tsx 29 KB

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