Skip to content
This repository was archived by the owner on Sep 11, 2024. It is now read-only.

Commit 877fa9c

Browse files
RiotRobott3chguy
andauthored
Fix progress bar regression throughout the app (#9219) (#9221)
* Fix useSmoothAnimation enablement not working properly by getting rid of it Passing duration=0 is more logical and less superfluous * Refactor UploadBar to handle state more correctly * Change ProgressBar to new useSmoothAnimation signature and default animated to true for consistency * Add type guard * Make types stricter * Write tests for the ProgressBar component * Make the new test conform to tsc --strict * Update UploadBar.tsx * Update UploadBar.tsx * Update UploadBar.tsx (cherry picked from commit 9b99c96) Co-authored-by: Michael Telatynski <[email protected]>
1 parent 0a0a46c commit 877fa9c

File tree

5 files changed

+105
-37
lines changed

5 files changed

+105
-37
lines changed

src/components/structures/UploadBar.tsx

Lines changed: 46 additions & 29 deletions
Original file line numberDiff line numberDiff line change
@@ -17,41 +17,55 @@ limitations under the License.
1717
import React from 'react';
1818
import { Room } from "matrix-js-sdk/src/models/room";
1919
import filesize from "filesize";
20-
import { IEventRelation } from 'matrix-js-sdk/src/matrix';
20+
import { IAbortablePromise, IEventRelation } from 'matrix-js-sdk/src/matrix';
21+
import { Optional } from "matrix-events-sdk";
2122

2223
import ContentMessages from '../../ContentMessages';
2324
import dis from "../../dispatcher/dispatcher";
2425
import { _t } from '../../languageHandler';
25-
import { ActionPayload } from "../../dispatcher/payloads";
2626
import { Action } from "../../dispatcher/actions";
2727
import ProgressBar from "../views/elements/ProgressBar";
28-
import AccessibleButton from "../views/elements/AccessibleButton";
28+
import AccessibleButton, { ButtonEvent } from "../views/elements/AccessibleButton";
2929
import { IUpload } from "../../models/IUpload";
3030
import MatrixClientContext from "../../contexts/MatrixClientContext";
31+
import { ActionPayload } from '../../dispatcher/payloads';
32+
import { UploadPayload } from "../../dispatcher/payloads/UploadPayload";
3133

3234
interface IProps {
3335
room: Room;
3436
relation?: IEventRelation;
3537
}
3638

3739
interface IState {
38-
currentUpload?: IUpload;
39-
uploadsHere: IUpload[];
40+
currentFile?: string;
41+
currentPromise?: IAbortablePromise<any>;
42+
currentLoaded?: number;
43+
currentTotal?: number;
44+
countFiles: number;
4045
}
4146

42-
export default class UploadBar extends React.Component<IProps, IState> {
47+
function isUploadPayload(payload: ActionPayload): payload is UploadPayload {
48+
return [
49+
Action.UploadStarted,
50+
Action.UploadProgress,
51+
Action.UploadFailed,
52+
Action.UploadFinished,
53+
Action.UploadCanceled,
54+
].includes(payload.action as Action);
55+
}
56+
57+
export default class UploadBar extends React.PureComponent<IProps, IState> {
4358
static contextType = MatrixClientContext;
4459

45-
private dispatcherRef: string;
46-
private mounted: boolean;
60+
private dispatcherRef: Optional<string>;
61+
private mounted = false;
4762

4863
constructor(props) {
4964
super(props);
5065

5166
// Set initial state to any available upload in this room - we might be mounting
5267
// earlier than the first progress event, so should show something relevant.
53-
const uploadsHere = this.getUploadsInRoom();
54-
this.state = { currentUpload: uploadsHere[0], uploadsHere };
68+
this.state = this.calculateState();
5569
}
5670

5771
componentDidMount() {
@@ -61,53 +75,56 @@ export default class UploadBar extends React.Component<IProps, IState> {
6175

6276
componentWillUnmount() {
6377
this.mounted = false;
64-
dis.unregister(this.dispatcherRef);
78+
dis.unregister(this.dispatcherRef!);
6579
}
6680

6781
private getUploadsInRoom(): IUpload[] {
6882
const uploads = ContentMessages.sharedInstance().getCurrentUploads(this.props.relation);
6983
return uploads.filter(u => u.roomId === this.props.room.roomId);
7084
}
7185

86+
private calculateState(): IState {
87+
const [currentUpload, ...otherUploads] = this.getUploadsInRoom();
88+
return {
89+
currentFile: currentUpload?.fileName,
90+
currentPromise: currentUpload?.promise,
91+
currentLoaded: currentUpload?.loaded,
92+
currentTotal: currentUpload?.total,
93+
countFiles: otherUploads.length + 1,
94+
};
95+
}
96+
7297
private onAction = (payload: ActionPayload) => {
73-
switch (payload.action) {
74-
case Action.UploadStarted:
75-
case Action.UploadProgress:
76-
case Action.UploadFinished:
77-
case Action.UploadCanceled:
78-
case Action.UploadFailed: {
79-
if (!this.mounted) return;
80-
const uploadsHere = this.getUploadsInRoom();
81-
this.setState({ currentUpload: uploadsHere[0], uploadsHere });
82-
break;
83-
}
98+
if (!this.mounted) return;
99+
if (isUploadPayload(payload)) {
100+
this.setState(this.calculateState());
84101
}
85102
};
86103

87-
private onCancelClick = (ev) => {
104+
private onCancelClick = (ev: ButtonEvent) => {
88105
ev.preventDefault();
89-
ContentMessages.sharedInstance().cancelUpload(this.state.currentUpload.promise, this.context);
106+
ContentMessages.sharedInstance().cancelUpload(this.state.currentPromise!, this.context);
90107
};
91108

92109
render() {
93-
if (!this.state.currentUpload) {
110+
if (!this.state.currentFile) {
94111
return null;
95112
}
96113

97114
// MUST use var name 'count' for pluralization to kick in
98115
const uploadText = _t(
99116
"Uploading %(filename)s and %(count)s others", {
100-
filename: this.state.currentUpload.fileName,
101-
count: this.state.uploadsHere.length - 1,
117+
filename: this.state.currentFile,
118+
count: this.state.countFiles - 1,
102119
},
103120
);
104121

105-
const uploadSize = filesize(this.state.currentUpload.total);
122+
const uploadSize = filesize(this.state.currentTotal!);
106123
return (
107124
<div className="mx_UploadBar">
108125
<div className="mx_UploadBar_filename">{ uploadText } ({ uploadSize })</div>
109126
<AccessibleButton onClick={this.onCancelClick} className='mx_UploadBar_cancel' />
110-
<ProgressBar value={this.state.currentUpload.loaded} max={this.state.currentUpload.total} />
127+
<ProgressBar value={this.state.currentLoaded!} max={this.state.currentTotal!} />
111128
</div>
112129
);
113130
}

src/components/views/elements/ProgressBar.tsx

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -25,10 +25,10 @@ interface IProps {
2525
}
2626

2727
const PROGRESS_BAR_ANIMATION_DURATION = 300;
28-
const ProgressBar: React.FC<IProps> = ({ value, max, animated }) => {
28+
const ProgressBar: React.FC<IProps> = ({ value, max, animated = true }) => {
2929
// Animating progress bars via CSS transition isn’t possible in all of our supported browsers yet.
3030
// As workaround, we’re using animations through JS requestAnimationFrame
31-
const currentValue = useSmoothAnimation(0, value, PROGRESS_BAR_ANIMATION_DURATION, animated);
31+
const currentValue = useSmoothAnimation(0, value, animated ? PROGRESS_BAR_ANIMATION_DURATION : 0);
3232
return <progress className="mx_ProgressBar" max={max} value={currentValue} />;
3333
};
3434

src/dispatcher/payloads/UploadPayload.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -18,7 +18,7 @@ import { ActionPayload } from "../payloads";
1818
import { Action } from "../actions";
1919
import { IUpload } from "../../models/IUpload";
2020

21-
interface UploadPayload extends ActionPayload {
21+
export interface UploadPayload extends ActionPayload {
2222
/**
2323
* The upload with fields representing the new upload state.
2424
*/

src/hooks/useSmoothAnimation.ts

Lines changed: 3 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -30,14 +30,12 @@ const debuglog = (...args: any[]) => {
3030
* Utility function to smoothly animate to a certain target value
3131
* @param initialValue Initial value to be used as initial starting point
3232
* @param targetValue Desired value to animate to (can be changed repeatedly to whatever is current at that time)
33-
* @param duration Duration that each animation should take
34-
* @param enabled Whether the animation should run or not
33+
* @param duration Duration that each animation should take, specify 0 to skip animating
3534
*/
3635
export function useSmoothAnimation(
3736
initialValue: number,
3837
targetValue: number,
3938
duration: number,
40-
enabled: boolean,
4139
): number {
4240
const state = useRef<{ timestamp: DOMHighResTimeStamp | null, value: number }>({
4341
timestamp: null,
@@ -79,7 +77,7 @@ export function useSmoothAnimation(
7977
[currentStepSize, targetValue],
8078
);
8179

82-
useAnimation(enabled, update);
80+
useAnimation(duration > 0, update);
8381

84-
return currentValue;
82+
return duration > 0 ? currentValue : targetValue;
8583
}
Lines changed: 53 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,53 @@
1+
/*
2+
Copyright 2022 The Matrix.org Foundation C.I.C.
3+
4+
Licensed under the Apache License, Version 2.0 (the "License");
5+
you may not use this file except in compliance with the License.
6+
You may obtain a copy of the License at
7+
http://www.apache.org/licenses/LICENSE-2.0
8+
Unless required by applicable law or agreed to in writing, software
9+
distributed under the License is distributed on an "AS IS" BASIS,
10+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
11+
See the License for the specific language governing permissions and
12+
limitations under the License.
13+
*/
14+
15+
import React from "react";
16+
import { act, render } from "@testing-library/react";
17+
18+
import ProgressBar from "../../../../src/components/views/elements/ProgressBar";
19+
20+
jest.useFakeTimers();
21+
22+
describe("<ProgressBar/>", () => {
23+
it("works when animated", () => {
24+
const { container, rerender } = render(<ProgressBar max={100} value={50} animated={true} />);
25+
const progress = container.querySelector<HTMLProgressElement>("progress")!;
26+
27+
// The animation always starts from 0
28+
expect(progress.value).toBe(0);
29+
30+
// Await the animation to conclude to our initial value of 50
31+
act(() => { jest.runAllTimers(); });
32+
expect(progress.position).toBe(0.5);
33+
34+
// Move the needle to 80%
35+
rerender(<ProgressBar max={100} value={80} animated={true} />);
36+
expect(progress.position).toBe(0.5);
37+
38+
// Let the animaiton run a tiny bit, assert it has moved from where it was to where it needs to go
39+
act(() => { jest.advanceTimersByTime(150); });
40+
expect(progress.position).toBeGreaterThan(0.5);
41+
expect(progress.position).toBeLessThan(0.8);
42+
});
43+
44+
it("works when not animated", () => {
45+
const { container, rerender } = render(<ProgressBar max={100} value={50} animated={false} />);
46+
const progress = container.querySelector<HTMLProgressElement>("progress")!;
47+
48+
// Without animation all positional updates are immediate, not requiring timers to run
49+
expect(progress.position).toBe(0.5);
50+
rerender(<ProgressBar max={100} value={80} animated={false} />);
51+
expect(progress.position).toBe(0.8);
52+
});
53+
});

0 commit comments

Comments
 (0)