Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Misc Frontend Improvements #53

Closed
wants to merge 8 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
99 changes: 79 additions & 20 deletions apps/frontend/src/app/matching/MatchingModal.tsx
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
import React, { useState, useEffect } from 'react';
import {
Form,
Button,
Modal,
} from 'antd';
import 'typeface-montserrat';
Expand All @@ -11,17 +13,42 @@ import JoinedMatchContent from './modalContent/JoinedMatchContent';
import MatchNotFoundContent from './modalContent/MatchNotFoundContent';
import MatchCancelledContent from './modalContent/MatchCancelledContent';
import useMatching from '../services/use-matching';
import { ValidateUser } from '../services/user';
import { useTimer } from 'react-timer-hook';

interface MatchingModalProps {
isOpen: boolean;
close: () => void;
}

export interface MatchParams {
topics: string[],
difficulties: string[],
}
const MATCH_TIMEOUT = 30;
const JOIN_TIMEOUT = 5;

const MatchingModal: React.FC<MatchingModalProps> = ({ isOpen, close: _close }) => {
const matchingState = useMatching();
const [closedType, setClosedType] = useState<"finding" | "cancelled" | "joined">("finding");
const [timeoutAfter, setTimeoutAfter] = useState<number>(9999);
const isClosable = ["timeout", "closed"].includes(matchingState.state);
const { totalSeconds, pause: pauseTimer, restart: restartTimer } = useTimer({
expiryTimestamp: new Date(Date.now() + MATCH_TIMEOUT * 1000),
autoStart: false,
onExpire() {
if (matchingState.state === "matching") {
matchingState.timeout();
return;
}
if (matchingState.state === "found") {
matchingState.ok();
setClosedType("joined");
return;
}
console.warn(`matching is in ${matchingState.state}`)
},
});
const passed = MATCH_TIMEOUT - totalSeconds;

function close() {
// clean up matching and closedType State
Expand All @@ -32,47 +59,70 @@ const MatchingModal: React.FC<MatchingModalProps> = ({ isOpen, close: _close })
_close();
}

const startMatch = matchingState.state == "closed" || matchingState.state == "timeout" ? async (params: MatchParams): Promise<void> => {
const user = await ValidateUser();

restartTimer(
new Date(Date.now() + MATCH_TIMEOUT * 1000),
);

matchingState.start({
email: user.data.email,
username: user.data.username,
type: "match_request",
...params
});
} : undefined;

useEffect(() => {
if (matchingState.state === "cancelling" || matchingState.state === "timeout") {
pauseTimer();
return;
}
if (matchingState.state === "found") {
restartTimer(
new Date(Date.now() + JOIN_TIMEOUT * 1000),
)
}
}, [matchingState])

const renderModalContent = () => {
switch (matchingState.state) {
case 'closed':
switch (closedType) {
case "finding":
return <FindMatchContent beginMatch={matchingState.start}/>;
return <FindMatchContent beginMatch={params => {}}/>;
case "cancelled":
return <MatchCancelledContent
reselect={() => {
setClosedType("finding");
}}
retry={() => {}}
canceledIn={timeoutAfter}
canceledIn={passed}
/>;
case "joined":
return <JoinedMatchContent
cancel={() => {
setClosedType("cancelled");
}}
name1={matchingState.info?.myName || ""}
name2={matchingState.info?.partnerName || ""}
cancel={() => {
setClosedType("cancelled");
}}
name1={matchingState.info?.myName ?? ""}
name2={matchingState.info?.partnerName ??""}
/>;
}
case 'matching':
return <MatchingInProgressContent
cancelMatch={(timeoutAfter: number) => {
cancelMatch={() => {
setClosedType("cancelled");
setTimeoutAfter(timeoutAfter);
matchingState.cancel();
pauseTimer();
}}
timeout={(timeoutAfter: number) => {
matchingState.timeout()
setTimeoutAfter(timeoutAfter);
}}
timePassed={passed}
/>;
case 'cancelling':
return <MatchingInProgressContent cancelMatch={() => {}} timeout={() => {}}/>;
return <MatchingInProgressContent cancelMatch={() => {}} timePassed={passed}/>;
case 'starting':
return <FindMatchContent beginMatch={() => {}}/>
case 'found':
return <MatchFoundContent
return <MatchFoundContent
cancel={() => {
matchingState.ok();
setClosedType("cancelled");
Expand All @@ -83,9 +133,10 @@ const MatchingModal: React.FC<MatchingModalProps> = ({ isOpen, close: _close })
}}
name1={matchingState.info.myName}
name2={matchingState.info.partnerName}
/>
joiningIn={totalSeconds}
/>
case 'timeout':
return <MatchNotFoundContent reselect={matchingState.ok} retry={() => {}} timedOutIn={10}/>;
return <MatchNotFoundContent reselect={matchingState.ok} timedOutIn={passed}/>;
default:
throw new Error('Invalid matching state.');
}
Expand All @@ -99,7 +150,15 @@ const MatchingModal: React.FC<MatchingModalProps> = ({ isOpen, close: _close })
maskClosable={false}
className="modal"
>
{renderModalContent()}
<Form<MatchParams>
name="match"
onFinish={startMatch}
initialValues={{
topics: [],
difficulties: [],
}}>
{renderModalContent()}
</Form>
{isClosable && (
<button className="close-button" onClick={close}>Close</button>
)}
Expand Down
129 changes: 36 additions & 93 deletions apps/frontend/src/app/matching/modalContent/FindMatchContent.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,8 @@ import {
Tag,
Select,
Space,
Form,
Button,
} from 'antd';
import {
DifficultyOption,
Expand All @@ -13,119 +15,60 @@ import 'typeface-montserrat';
import './styles.scss';
import { ValidateUser } from "@/app/services/user"
import { type MatchRequestParams } from '@/app/services/use-matching';

interface DifficultySelectorProps {
className?: string;
selectedDifficulties: string[];
onChange: (difficulties: string[]) => void;
}

interface TopicSelectorProps {
className?: string;
selectedTopics: string[];
onChange: (topics: string[]) => void;
}
import { MatchParams } from '../MatchingModal';

interface Props {
beginMatch(request: MatchRequestParams): void
}

const FindMatchContent: React.FC<Props> = ({ beginMatch }) => {
const [selectedDifficulties, setSelectedDifficulties] = useState<string[]>([]);
const [selectedTopics, setSelectedTopics] = useState<string[]>([]);
const [isLoading, setIsLoading] = useState(false);

const handleDifficultyChange = (difficulties: string[]) => {
setSelectedDifficulties(difficulties);
};

const handleTopicChange = (topics: string[]) => {
setSelectedTopics(topics);
};

return (
<div>
<div className="find-match-title">Find Match</div>
<div className="difficulty-label">Difficulty</div>
<div className="difficulty-selector">
<DifficultySelector
selectedDifficulties={selectedDifficulties}
onChange={handleDifficultyChange}
/>
<Form.Item<MatchParams> name="difficulties">
{/* @ts-ignore Not required to pass value and onChange as since this is handled by Form.Item wrapper*/}
<TagInput/>
</Form.Item>
</div>
<div className="topic-label">Topic</div>
<div className="topic-selector">
<TopicSelector
selectedTopics={selectedTopics}
onChange={handleTopicChange}
/>
<Form.Item<MatchParams>
name="topics"
>
<Select mode="multiple" allowClear placeholder="Select Topic(s)" options={CategoriesOption}/>
</Form.Item>
</div>
<button className="find-match-button"
onClick={async () => {
setIsLoading(true);
const user = await ValidateUser();
beginMatch({
email: user.data.email,
username: user.data.username,
type: "match_request",
difficulties: selectedDifficulties,
topics: selectedTopics,
})
}}
disabled={isLoading}
>
Find Match
<button className="find-match-button" type="submit">
FIND MATCH
</button>
</div>
)
}

const DifficultySelector: React.FC<DifficultySelectorProps> = ({ selectedDifficulties, onChange}) => {
const handleChange = (difficulty: string) => {
const newSelectedDifficulties = selectedDifficulties.includes(difficulty)
? selectedDifficulties.filter(selectedDifficulty => selectedDifficulty !== difficulty)
: [...selectedDifficulties, difficulty];
onChange(newSelectedDifficulties);
}

return (
<div>
{DifficultyOption.map(difficultyOption => (
<Tag.CheckableTag
className={`difficulty-tag ${difficultyOption.value}-tag`}
key={difficultyOption.value}
checked={selectedDifficulties.includes(difficultyOption.label)}
onChange={() => handleChange(difficultyOption.label)}
>
{difficultyOption.label}
</Tag.CheckableTag>
))}
</div>
)
}

const TopicSelector: React.FC<TopicSelectorProps> = ({ selectedTopics, onChange}) => {
const topicOptions: SelectProps[] = CategoriesOption;

const handleChange = (topics: string[]) => {
onChange(topics);
}

return (
<div className="find-match-content">
<Space className="select-space" direction="vertical">
<Select
className="select-topic"
mode="multiple"
allowClear
style={{ width: '100%' }}
placeholder="Select Topic(s)"
onChange={handleChange}
options={topicOptions}
/>
</Space>
</div>
)
const TagInput: React.FC<{
value: string[],
onChange(value: string[]): void,
}> = ({ value, onChange }) => {
return <>
{DifficultyOption.map(difficultyOption => (
<Tag.CheckableTag
className={`difficulty-tag ${difficultyOption.value}-tag`}
key={difficultyOption.value}
checked={value.includes(difficultyOption.label)}
onChange={(enabled) => {
onChange(
enabled
? [...value, difficultyOption.label]
: value.filter(diff => diff !== difficultyOption.label)
)
}}
>
{difficultyOption.label}
</Tag.CheckableTag>
))}
</>
}

export default FindMatchContent;
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ import 'typeface-montserrat';
import './styles.scss';
import { handleCancelMatch } from '../handlers';
import { formatTime } from '@/utils/DateTime';
import { useStopwatch } from 'react-timer-hook';


interface Props {
Expand All @@ -21,6 +22,9 @@ const JoinedMatchContent: React.FC<Props> = ({cancel, name1: me, name2: you}) =>
const matchAlreadyJoined = () => {
throw new Error('Match already joined.');
}
const { totalSeconds } = useStopwatch({
autoStart: true
})

return (
<div className="joined-match-content">
Expand All @@ -45,18 +49,13 @@ const JoinedMatchContent: React.FC<Props> = ({cancel, name1: me, name2: you}) =>
</div>
<div className="match-status-label">Match Found!</div>
<div className="match-status-message">
Waiting for others... {formatTime(83)}
Waiting for others... {formatTime(totalSeconds)}
</div>
<button className="joined-match-deactivated-button"
disabled
>
Joined
</button>
<button className="cancel-match-button"
onClick={cancel}
>
Cancel
</button>
</div>
)
}
Expand Down
Loading