Skip to content

Commit

Permalink
hookify Frame Loading
Browse files Browse the repository at this point in the history
  • Loading branch information
sijad committed Oct 17, 2019
1 parent 8aaac7a commit a8b2e26
Showing 1 changed file with 44 additions and 61 deletions.
105 changes: 44 additions & 61 deletions src/components/Frame/components/Loading/Loading.tsx
Original file line number Diff line number Diff line change
@@ -1,78 +1,61 @@
import React from 'react';
import debounce from 'lodash/debounce';
import React, {useEffect, useState} from 'react';
import styles from './Loading.scss';

export interface LoadingProps {}

interface State {
progress: number;
step: number;
animation: number | null;
}

const INITIAL_STEP = 10;
const STUCK_THRESHOLD = 99;

export class Loading extends React.Component<LoadingProps, State> {
state: State = {
progress: 0,
step: INITIAL_STEP,
animation: null,
};

private ariaValuenow = debounce(() => {
const {progress} = this.state;
return Math.floor(progress / 10) * 10;
}, 15);
export interface LoadingProps {}

componentDidMount() {
this.increment();
}
export function Loading(_props: LoadingProps) {
const [progress, setProgress] = useState(0);

componentWillUnmount() {
const {animation} = this.state;
useEffect(() => {
let animation: number | undefined;
let step = INITIAL_STEP;
let currentProgress = 0;
let previousProgress = 0;

if (animation != null) {
cancelAnimationFrame(animation);
}
}
const increment = () => {
if (currentProgress >= STUCK_THRESHOLD) {
return;
}

render() {
const {progress} = this.state;
currentProgress = Math.min(currentProgress + step, 100);
const nextProgress = Math.floor(currentProgress) / 100;

const customStyles = {
transform: `scaleX(${Math.floor(progress) / 100})`,
};
if (nextProgress !== previousProgress) {
setProgress(nextProgress);
previousProgress = nextProgress;
}

const ariaValuenow = this.ariaValuenow();
step = INITIAL_STEP ** -(currentProgress / 25);

return (
<div className={styles.Loading}>
<div
className={styles.Level}
style={customStyles}
aria-valuenow={ariaValuenow}
aria-valuemin={0}
aria-valuemax={100}
role="progressbar"
/>
</div>
);
}
animation = requestAnimationFrame(increment);
};

private increment() {
const {progress, step} = this.state;
increment();

if (progress >= STUCK_THRESHOLD) {
return;
}
return () => {
if (animation) {
cancelAnimationFrame(animation);
}
};
}, []);

const animation = requestAnimationFrame(() => this.increment());
const customStyles = {
transform: `scaleX(${progress})`,
};

this.setState({
progress: Math.min(progress + step, 100),
step: INITIAL_STEP ** -(progress / 25),
animation,
});
}
return (
<div className={styles.Loading}>
<div
className={styles.Level}
style={customStyles}
aria-valuenow={progress * 100}
aria-valuemin={0}
aria-valuemax={100}
role="progressbar"
/>
</div>
);
}

0 comments on commit a8b2e26

Please sign in to comment.