Skip to content

Commit

Permalink
Merge pull request #10 from winglang/improvements
Browse files Browse the repository at this point in the history
  • Loading branch information
Chriscbr authored Aug 11, 2023
2 parents 191ba12 + 02ceb92 commit 119e10a
Show file tree
Hide file tree
Showing 15 changed files with 406 additions and 154 deletions.
2 changes: 1 addition & 1 deletion package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

9 changes: 9 additions & 0 deletions website/package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

4 changes: 4 additions & 0 deletions website/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@
"@types/node": "^20.4.8",
"@types/react": "^18.2.18",
"@types/react-dom": "^18.2.7",
"classnames": "^2.3.2",
"react": "^18.2.0",
"react-dom": "^18.2.0",
"react-scripts": "5.0.1",
Expand Down Expand Up @@ -39,5 +40,8 @@
"last 1 firefox version",
"last 1 safari version"
]
},
"devDependencies": {
"tailwindcss": "^3.3.3"
}
}
185 changes: 32 additions & 153 deletions website/src/App.tsx
Original file line number Diff line number Diff line change
@@ -1,165 +1,44 @@
import React, { useState, useEffect } from "react";

interface Config {
apiUrl: string;
}

interface Entry {
name: string;
score: number;
}

const fetchConfig = async () => {
const response = await fetch("./config.json");
if (!response.ok) {
throw new Error('Failed to fetch config');
}
const config: Config = await response.json();
return config;
}

const fetchLeaderboard = async () => {
const apiUrl = (await fetchConfig()).apiUrl;
const response = await fetch(apiUrl + "/leaderboard");
if (!response.ok) {
throw new Error('Failed to fetch leaderboard data');
}
const jsonData: Entry[] = await response.json();
return jsonData;
}

const fetchChoices = async () => {
const apiUrl = (await fetchConfig()).apiUrl;
const response = await fetch(apiUrl + "/requestChoices", {
method: "POST",
});
if (!response.ok) {
throw new Error('Failed to request choices');
}
const jsonData: string[] = await response.json();
return jsonData;
}

const submitVote = async (winner: string, loser: string) => {
const apiUrl = (await fetchConfig()).apiUrl;
const response = await fetch(apiUrl + "/selectWinner", {
method: "POST",
body: JSON.stringify({ winner, loser }),
});
if (!response.ok) {
console.error('Failed to submit vote');
}
const jsonData: { winner: number; loser: number; } = await response.json();
return jsonData;
}

interface LeaderboardProps {
swapViews: () => void;
}

const Leaderboard = (props: LeaderboardProps) => {
const [entries, setEntries] = useState<Entry[]>([]);
useEffect(() => {
fetchLeaderboard().then((items) => setEntries(items));
}, []);

return (
<div>
<h2>Leaderboard</h2>
<table>
<thead>
<tr>
<th>Name</th>
<th>Score</th>
</tr>
</thead>
<tbody>
{entries.sort((a, b) => b.score - a.score).map((item) => (
<tr key={item.name}>
<td>{item.name}</td>
<td>{item.score}</td>
</tr>
))}
</tbody>
</table>
<button onClick={props.swapViews}>Back</button>
</div>
);
};

interface VotingProps {
swapViews: () => void;
}

const Voting = (props: VotingProps) => {
const [choices, setChoices] = useState<string[]>([]);
const [scores, setScores] = useState<(number | null)[]>([null, null]);
useEffect(() => {
fetchChoices().then((choices) => setChoices(choices));
}, []);

const [winner, setWinner] = useState<string | null>(null);
const selectWinner = async (winner: string, loser: string) => {
const { winner: winnerScore, loser: loserScore } = await submitVote(winner, loser);
if (winner === choices[0]) {
setScores([winnerScore, loserScore]);
} else {
setScores([loserScore, winnerScore]);
}
setWinner(winner);
};

const reset = async () => {
setWinner(null);
setScores([null, null]);
const choices = await fetchChoices();
setChoices(choices);
};

const renderVoteButtonOrOutcome = (idx: number) => {
if (winner === null) {
return <button onClick={() => selectWinner(choices[idx], choices[1 - idx])}>Vote</button>;
}
return <p>{winner === choices[idx] ? "Winner" : "Loser"} (new score: {scores[idx]})</p>
}

return (
<div>
<h2>Which is better?</h2>
<div className="choices">
<div className="choice1">
<h3 className="name">{choices[0]}</h3>
{renderVoteButtonOrOutcome(0)}
</div>
<div className="choice2">
<h3 className="name">{choices[1]}</h3>
{renderVoteButtonOrOutcome(0)}
</div>
{
winner !== null && (
<button onClick={() => reset()}>Next matchup</button>
)
}
</div>
<button onClick={props.swapViews}>Leaderboard</button>
</div>
)
}
import { useState } from "react";
import { LeaderboardView } from "./views/LeaderboardView";
import { VotingView } from "./views/VotingView";
import { Button } from "./components/Button";

type View = "voting" | "leaderboard";

function App() {
let [view, setView] = useState<View>("voting");

const swapViews = () => {
setView(view === "voting" ? "leaderboard" : "voting");
};

switch (view) {
case "voting":
return <Voting swapViews={swapViews} />;
case "leaderboard":
return <Leaderboard swapViews={swapViews} />;
}
return (
<div className="App font-mono absolute inset-0">
<div className="w-full h-full flex flex-col items-center justify-center">
<div className="w-[30rem] min-h-[35rem] px-10 pt-10 pb-4 bg-sky-200 rounded-lg shadow-xl flex flex-col">
<div className="text-slate-700 font-bold text-3xl text-center">
{view === "voting" ? "Which is better?" : "Leaderboard"}
</div>

<div className="grow pt-8">
{view === "voting" && <VotingView />}
{view === "leaderboard" && <LeaderboardView />}
</div>

<div className="w-full h-px bg-slate-300 my-4" />

<div className="w-full flex justify-center truncate">
{view === "voting" && (
<Button primary onClick={swapViews} label="Leaderboard" />
)}
{view === "leaderboard" && (
<Button primary onClick={swapViews} label="Back" />
)}
</div>
</div>
</div>
</div>
);
}

export default App;
39 changes: 39 additions & 0 deletions website/src/components/Button.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
import classnames from "classnames";
import { SpinnerLoader } from "./SpinnerLoader";

export interface ButtonProps {
label: string;
primary?: boolean;
onClick: () => void;
loading?: boolean;
disabled?: boolean;
className?: string;
}

export const Button = ({
label,
primary = false,
onClick,
loading = false,
disabled = false,
className,
}: ButtonProps) => {
return (
<button
className={classnames(
primary && "bg-sky-600 hover:bg-sky-700 text-white font-bold",
!primary && "bg-sky-100 hover:bg-sky-300 text-slate-700",
"py-1 px-3 rounded shadow",
{ "opacity-50 cursor-not-allowed": loading || disabled },
className
)}
onClick={onClick}
disabled={disabled || loading}
>
<div className="flex gap-x-2">
{label}
{loading && <SpinnerLoader />}
</div>
</button>
);
};
33 changes: 33 additions & 0 deletions website/src/components/SpinnerLoader.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
import classNames from "classnames";

export interface SpinnerLoaderProps {
className?: string;
}

export const SpinnerLoader = ({ className }: SpinnerLoaderProps) => {
return (
<div className="self-center">
<svg
aria-hidden="true"
className={classNames(
"animate-spin fill-slate-300 text-slate-500",
className,
"w-4 h-4"
)}
viewBox="0 0 100 101"
fill="none"
xmlns="http://www.w3.org/2000/svg"
>
<path
d="M100 50.5908C100 78.2051 77.6142 100.591 50 100.591C22.3858 100.591 0 78.2051 0 50.5908C0 22.9766 22.3858 0.59082 50 0.59082C77.6142 0.59082 100 22.9766 100 50.5908ZM9.08144 50.5908C9.08144 73.1895 27.4013 91.5094 50 91.5094C72.5987 91.5094 90.9186 73.1895 90.9186 50.5908C90.9186 27.9921 72.5987 9.67226 50 9.67226C27.4013 9.67226 9.08144 27.9921 9.08144 50.5908Z"
fill="currentColor"
/>
<path
d="M93.9676 39.0409C96.393 38.4038 97.8624 35.9116 97.0079 33.5539C95.2932 28.8227 92.871 24.3692 89.8167 20.348C85.8452 15.1192 80.8826 10.7238 75.2124 7.41289C69.5422 4.10194 63.2754 1.94025 56.7698 1.05124C51.7666 0.367541 46.6976 0.446843 41.7345 1.27873C39.2613 1.69328 37.813 4.19778 38.4501 6.62326C39.0873 9.04874 41.5694 10.4717 44.0505 10.1071C47.8511 9.54855 51.7191 9.52689 55.5402 10.0491C60.8642 10.7766 65.9928 12.5457 70.6331 15.2552C75.2735 17.9648 79.3347 21.5619 82.5849 25.841C84.9175 28.9121 86.7997 32.2913 88.1811 35.8758C89.083 38.2158 91.5421 39.6781 93.9676 39.0409Z"
fill="currentFill"
/>
</svg>
<span className="sr-only">Loading...</span>
</div>
);
};
61 changes: 61 additions & 0 deletions website/src/components/VoteItem.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
import { Button } from "./Button";
import classnames from "classnames";
import { SpinnerLoader } from "./SpinnerLoader";

export interface VoteItemProps {
name: string;
imageUrl: string;
onClick: () => void;
disabled?: boolean;
loading?: boolean;
winner?: string;
score?: number;
}

export const VoteItem = ({
name,
onClick,
imageUrl,
disabled,
loading,
winner,
score,
}: VoteItemProps) => {
return (
<div className="text-center">
<h3 className="text-lg truncate h-8 text-slate-700">{name}</h3>
<div className="relative w-32 h-32 mx-auto rounded-lg truncate">
<div className="w-full h-full bg-sky-100 animate-pulse absolute shadow items-center justify-center flex opacity-50">
<SpinnerLoader />
</div>
{imageUrl !== "" && (
<img
className="w-full h-full object-fill absolute z-10"
src={imageUrl}
alt={name}
/>
)}
</div>
<div className="pt-3">
{!winner && (
<Button
onClick={onClick}
label="Vote"
loading={loading}
disabled={disabled}
/>
)}
{winner && (
<div
className={classnames(
"h-8",
winner === name ? "text-green-600" : "text-red-600"
)}
>
{winner === name ? "🥇" : "👎"} (Score: {Math.max(score!, 0)})
</div>
)}
</div>
</div>
);
};
4 changes: 4 additions & 0 deletions website/src/index.css
Original file line number Diff line number Diff line change
@@ -1,3 +1,7 @@
@tailwind base;
@tailwind components;
@tailwind utilities;

body {
margin: 0;
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', 'Roboto', 'Oxygen',
Expand Down
Loading

0 comments on commit 119e10a

Please sign in to comment.