index.tsx 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348
  1. import React, { ReactNode, Component } from 'react';
  2. import cls from 'classnames';
  3. import PropTypes from 'prop-types';
  4. import { cssClasses, strings } from '@douyinfe/semi-foundation/progress/constants';
  5. import getDataAttr from '@douyinfe/semi-foundation/utils/getDataAttr';
  6. import '@douyinfe/semi-foundation/progress/progress.scss';
  7. import { Animation } from '@douyinfe/semi-animation';
  8. import { Motion } from '../_base/base';
  9. import { generateColor, StrokeArr } from '@douyinfe/semi-foundation/progress/generates';
  10. const prefixCls = cssClasses.PREFIX;
  11. export interface ProgressProps {
  12. 'aria-label'?: string;
  13. 'aria-labelledby'?: string;
  14. 'aria-valuetext'?: string;
  15. className?: string;
  16. direction?: 'horizontal' | 'vertical';
  17. format?: (percent: number) => React.ReactNode;
  18. id?: string;
  19. motion?: Motion;
  20. orbitStroke?: string;
  21. percent?: number;
  22. showInfo?: boolean;
  23. size?: 'default' | 'small' | 'large';
  24. stroke?: string | StrokeArr;
  25. strokeGradient?: boolean;
  26. strokeLinecap?: 'round' | 'square';
  27. strokeWidth?: number;
  28. style?: React.CSSProperties;
  29. type?: 'line' | 'circle';
  30. width?: number
  31. }
  32. export interface ProgressState {
  33. percentNumber: number
  34. }
  35. class Progress extends Component<ProgressProps, ProgressState> {
  36. static propTypes = {
  37. 'aria-label': PropTypes.string,
  38. 'aria-labelledby': PropTypes.string,
  39. 'aria-valuetext': PropTypes.string,
  40. className: PropTypes.string,
  41. direction: PropTypes.oneOf(strings.directions),
  42. format: PropTypes.oneOfType([PropTypes.func, PropTypes.node]),
  43. id: PropTypes.string,
  44. motion: PropTypes.oneOfType([PropTypes.bool, PropTypes.func, PropTypes.object]),
  45. orbitStroke: PropTypes.string,
  46. percent: PropTypes.number,
  47. scale: PropTypes.number,
  48. showInfo: PropTypes.bool,
  49. size: PropTypes.oneOf(strings.sizes),
  50. stroke: PropTypes.oneOfType([
  51. PropTypes.string,
  52. PropTypes.arrayOf(
  53. PropTypes.shape({
  54. percent: PropTypes.number,
  55. color: PropTypes.string,
  56. })
  57. ),
  58. ]),
  59. strokeGradient: PropTypes.bool,
  60. strokeLinecap: PropTypes.oneOf(strings.strokeLineCap),
  61. strokeWidth: PropTypes.number,
  62. style: PropTypes.object,
  63. type: PropTypes.oneOf(strings.types),
  64. width: PropTypes.number,
  65. };
  66. static defaultProps = {
  67. className: '',
  68. direction: strings.DEFAULT_DIRECTION,
  69. format: (text: string): string => `${text}%`,
  70. motion: true,
  71. percent: 0,
  72. showInfo: false,
  73. size: strings.DEFAULT_SIZE,
  74. strokeGradient: false,
  75. strokeLinecap: strings.DEFAULT_LINECAP,
  76. strokeWidth: 4,
  77. style: {},
  78. type: strings.DEFAULT_TYPE,
  79. };
  80. _mounted: boolean = true;
  81. animation: Animation;
  82. constructor(props: ProgressProps) {
  83. super(props);
  84. this._mounted = true;
  85. this.state = {
  86. percentNumber: this.props.percent, // Specially used for animation of numbers
  87. };
  88. }
  89. componentDidUpdate(prevProps: ProgressProps): void {
  90. if (isNaN(this.props.percent) || isNaN(prevProps.percent)) {
  91. throw new Error('[Semi Progress]:percent can not be NaN');
  92. return;
  93. }
  94. if (prevProps.percent !== this.props.percent) {
  95. if (!this.props.motion) {
  96. this.setState({ percentNumber: this.props.percent });
  97. return;
  98. }
  99. if (this.animation && this.animation.destroy) {
  100. this.animation.destroy();
  101. }
  102. this.animation = new Animation(
  103. {
  104. from: { value: prevProps.percent },
  105. to: { value: this.props.percent },
  106. },
  107. {
  108. // easing: 'cubic-bezier(0, .68, .3, 1)'
  109. easing: 'linear',
  110. duration: 300,
  111. }
  112. );
  113. this.animation.on('frame', (props: any) => {
  114. // prevent setState while component is unmounted but this timer is called
  115. if (this._mounted === false) {
  116. return;
  117. }
  118. // let percentNumber = Number.isInteger(props.value) ? props.value : Math.floor(props.value * 100) / 100;
  119. const percentNumber = parseInt(props.value);
  120. this.setState({ percentNumber });
  121. });
  122. this.animation.on('rest', () => {
  123. // prevent setState while component is unmounted but this timer is called
  124. if (this._mounted === false) {
  125. return;
  126. }
  127. this.setState({ percentNumber: this.props.percent });
  128. });
  129. this.animation.start();
  130. }
  131. }
  132. componentWillUnmount(): void {
  133. this.animation && this.animation.destroy();
  134. this._mounted = false;
  135. }
  136. renderCircleProgress(): ReactNode {
  137. const {
  138. strokeLinecap,
  139. style,
  140. className,
  141. strokeWidth,
  142. format,
  143. size,
  144. stroke,
  145. strokeGradient,
  146. showInfo,
  147. percent,
  148. orbitStroke,
  149. id,
  150. ...rest
  151. } = this.props;
  152. const ariaLabel = this.props['aria-label'];
  153. const ariaLabelledBy = this.props['aria-labelledby'];
  154. const ariaValueText = this.props['aria-valuetext'];
  155. const { percentNumber } = this.state;
  156. const classNames = {
  157. wrapper: cls(`${prefixCls}-circle`, className),
  158. svg: cls(`${prefixCls}-circle-ring`),
  159. circle: cls(`${prefixCls}-circle-ring-inner`),
  160. track: cls(`${prefixCls}-circle-ring-track`),
  161. };
  162. const perc = this.calcPercent(percent);
  163. const percNumber = this.calcPercent(percentNumber);
  164. let width;
  165. if (this.props.width) {
  166. width = this.props.width;
  167. } else {
  168. size === strings.DEFAULT_SIZE ? (width = 72) : (width = 24);
  169. }
  170. // parse stroke & generate gradients
  171. const _stroke = this.selectStroke(stroke, percent, strokeGradient);
  172. // cx, cy is circle center
  173. const cy = width / 2;
  174. const cx = width / 2;
  175. const radius = (width - strokeWidth) / 2; // radius
  176. const circumference = radius * 2 * Math.PI;
  177. const strokeDashoffset = (1 - perc / 100) * circumference; // Offset
  178. const strokeDasharray = `${circumference} ${circumference}`;
  179. const text = format(percNumber);
  180. return (
  181. <div
  182. id={id}
  183. className={classNames.wrapper}
  184. style={style}
  185. role="progressbar"
  186. aria-valuemin={0}
  187. aria-valuemax={100}
  188. aria-valuenow={percNumber}
  189. aria-labelledby={ariaLabelledBy}
  190. aria-label={ariaLabel}
  191. aria-valuetext={ariaValueText}
  192. {...getDataAttr(rest)}
  193. >
  194. <svg key={size} className={classNames.svg} height={width} width={width} aria-hidden>
  195. <circle
  196. className={classNames.track}
  197. strokeDashoffset={0}
  198. strokeWidth={strokeWidth}
  199. strokeDasharray={strokeDasharray}
  200. strokeLinecap={strokeLinecap}
  201. fill="transparent"
  202. style={{ stroke: orbitStroke }}
  203. r={radius}
  204. cx={cx}
  205. cy={cy}
  206. aria-hidden
  207. />
  208. <circle
  209. className={classNames.circle}
  210. strokeDashoffset={strokeDashoffset}
  211. strokeWidth={strokeWidth}
  212. strokeDasharray={strokeDasharray}
  213. strokeLinecap={strokeLinecap}
  214. fill="transparent"
  215. style={{ stroke: _stroke }}
  216. r={radius}
  217. cx={cx}
  218. cy={cy}
  219. aria-hidden
  220. />
  221. </svg>
  222. {showInfo && size !== 'small' ? <span className={`${prefixCls}-circle-text`}>{text}</span> : null}
  223. </div>
  224. );
  225. }
  226. calcPercent(percent: number): number {
  227. let perc;
  228. if (percent > 100) {
  229. perc = 100;
  230. } else if (percent < 0) {
  231. perc = 0;
  232. } else {
  233. perc = percent;
  234. }
  235. return perc;
  236. }
  237. selectStroke(stroke: string | StrokeArr, percent: number, strokeGradient): string {
  238. if (typeof stroke === 'string') {
  239. return stroke;
  240. }
  241. const color = generateColor(stroke, percent, strokeGradient);
  242. if (typeof color !== 'undefined') {
  243. return color;
  244. }
  245. return null;
  246. }
  247. renderLineProgress(): ReactNode {
  248. const {
  249. className,
  250. style,
  251. stroke,
  252. strokeGradient,
  253. direction,
  254. format,
  255. showInfo,
  256. size,
  257. percent,
  258. orbitStroke,
  259. id,
  260. ...rest
  261. } = this.props;
  262. const ariaLabel = this.props['aria-label'];
  263. const ariaLabelledBy = this.props['aria-labelledby'];
  264. const ariaValueText = this.props['aria-valuetext'];
  265. const { percentNumber } = this.state;
  266. const progressWrapperCls = cls(prefixCls, className, {
  267. [`${prefixCls}-horizontal`]: direction === strings.DEFAULT_DIRECTION,
  268. [`${prefixCls}-vertical`]: direction !== strings.DEFAULT_DIRECTION,
  269. [`${prefixCls}-large`]: size === 'large',
  270. });
  271. const progressTrackCls = cls({
  272. [`${prefixCls}-track`]: true,
  273. });
  274. const innerCls = cls(`${prefixCls}-track-inner`);
  275. const perc = this.calcPercent(percent);
  276. const percNumber = this.calcPercent(percentNumber);
  277. // parse stroke & generate gradients
  278. const _stroke = this.selectStroke(stroke, percent, strokeGradient);
  279. const innerStyle: Record<string, any> = {
  280. background: _stroke,
  281. };
  282. if (direction === strings.DEFAULT_DIRECTION) {
  283. innerStyle.width = `${perc}%`;
  284. } else {
  285. innerStyle.height = `${perc}%`;
  286. }
  287. const text = format(percNumber);
  288. return (
  289. <div
  290. id={id}
  291. className={progressWrapperCls}
  292. style={style}
  293. role="progressbar"
  294. aria-valuemin={0}
  295. aria-valuemax={100}
  296. aria-valuenow={perc}
  297. aria-labelledby={ariaLabelledBy}
  298. aria-label={ariaLabel}
  299. aria-valuetext={ariaValueText}
  300. {...getDataAttr(rest)}
  301. >
  302. <div
  303. className={progressTrackCls}
  304. style={orbitStroke ? { backgroundColor: orbitStroke } : {}}
  305. aria-hidden
  306. >
  307. <div className={innerCls} style={innerStyle} aria-hidden />
  308. </div>
  309. {showInfo ? <div className={`${prefixCls}-line-text`}>{text}</div> : null}
  310. </div>
  311. );
  312. }
  313. render(): ReactNode {
  314. const { type } = this.props;
  315. if (type === 'line') {
  316. return this.renderLineProgress();
  317. } else {
  318. return this.renderCircleProgress();
  319. }
  320. }
  321. }
  322. export default Progress;