1
0

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. orbitStroke: 'var(--semi-color-fill-0)',
  72. percent: 0,
  73. showInfo: false,
  74. size: strings.DEFAULT_SIZE,
  75. stroke: strings.STROKE_DEFAULT,
  76. strokeGradient: false,
  77. strokeLinecap: strings.DEFAULT_LINECAP,
  78. strokeWidth: 4,
  79. style: {},
  80. type: strings.DEFAULT_TYPE,
  81. };
  82. _mounted: boolean = true;
  83. animation: Animation;
  84. constructor(props: ProgressProps) {
  85. super(props);
  86. this._mounted = true;
  87. this.state = {
  88. percentNumber: this.props.percent, // Specially used for animation of numbers
  89. };
  90. }
  91. componentDidUpdate(prevProps: ProgressProps): void {
  92. if (isNaN(this.props.percent) || isNaN(prevProps.percent)) {
  93. throw new Error('[Semi Progress]:percent can not be NaN');
  94. return;
  95. }
  96. if (prevProps.percent !== this.props.percent) {
  97. if (!this.props.motion) {
  98. this.setState({ percentNumber: this.props.percent });
  99. return;
  100. }
  101. if (this.animation && this.animation.destroy) {
  102. this.animation.destroy();
  103. }
  104. this.animation = new Animation(
  105. {
  106. from: { value: prevProps.percent },
  107. to: { value: this.props.percent },
  108. },
  109. {
  110. // easing: 'cubic-bezier(0, .68, .3, 1)'
  111. easing: 'linear',
  112. duration: 300,
  113. }
  114. );
  115. this.animation.on('frame', (props: any) => {
  116. // prevent setState while component is unmounted but this timer is called
  117. if (this._mounted === false) {
  118. return;
  119. }
  120. // let percentNumber = Number.isInteger(props.value) ? props.value : Math.floor(props.value * 100) / 100;
  121. const percentNumber = parseInt(props.value);
  122. this.setState({ percentNumber });
  123. });
  124. this.animation.on('rest', () => {
  125. // prevent setState while component is unmounted but this timer is called
  126. if (this._mounted === false) {
  127. return;
  128. }
  129. this.setState({ percentNumber: this.props.percent });
  130. });
  131. this.animation.start();
  132. }
  133. }
  134. componentWillUnmount(): void {
  135. this.animation && this.animation.destroy();
  136. this._mounted = false;
  137. }
  138. renderCircleProgress(): ReactNode {
  139. const {
  140. strokeLinecap,
  141. style,
  142. className,
  143. strokeWidth,
  144. format,
  145. size,
  146. stroke,
  147. strokeGradient,
  148. showInfo,
  149. percent,
  150. orbitStroke,
  151. id,
  152. ...rest
  153. } = this.props;
  154. const ariaLabel = this.props['aria-label'];
  155. const ariaLabelledBy = this.props['aria-labelledby'];
  156. const ariaValueText = this.props['aria-valuetext'];
  157. const { percentNumber } = this.state;
  158. const classNames = {
  159. wrapper: cls(`${prefixCls}-circle`, className),
  160. svg: cls(`${prefixCls}-circle-ring`),
  161. circle: cls(`${prefixCls}-circle-ring-inner`),
  162. };
  163. const perc = this.calcPercent(percent);
  164. const percNumber = this.calcPercent(percentNumber);
  165. let width;
  166. if (this.props.width) {
  167. width = this.props.width;
  168. } else {
  169. size === strings.DEFAULT_SIZE ? (width = 72) : (width = 24);
  170. }
  171. // parse stroke & generate gradients
  172. const _stroke = this.selectStroke(stroke, percent, strokeGradient);
  173. // cx, cy is circle center
  174. const cy = width / 2;
  175. const cx = width / 2;
  176. const radius = (width - strokeWidth) / 2; // radius
  177. const circumference = radius * 2 * Math.PI;
  178. const strokeDashoffset = (1 - perc / 100) * circumference; // Offset
  179. const strokeDasharray = `${circumference} ${circumference}`;
  180. const text = format(percNumber);
  181. return (
  182. <div
  183. id={id}
  184. className={classNames.wrapper}
  185. style={style}
  186. role="progressbar"
  187. aria-valuemin={0}
  188. aria-valuemax={100}
  189. aria-valuenow={percNumber}
  190. aria-labelledby={ariaLabelledBy}
  191. aria-label={ariaLabel}
  192. aria-valuetext={ariaValueText}
  193. {...getDataAttr(rest)}
  194. >
  195. <svg key={size} className={classNames.svg} height={width} width={width} aria-hidden>
  196. <circle
  197. strokeDashoffset={0}
  198. strokeWidth={strokeWidth}
  199. strokeDasharray={strokeDasharray}
  200. strokeLinecap={strokeLinecap}
  201. fill="transparent"
  202. 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. 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 strings.STROKE_DEFAULT;
  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;