six-degs-of-f1/src/pages/index.astro

91 lines
2.1 KiB
Plaintext

---
import BaseLayout from '@/layouts/BaseLayout.astro';
import ShortestPathsGraph from '@/components/ShortestPathsGraph.astro';
import { getDriverNames } from '@/db/getDriverNames';
import { getShortestPaths } from '@/db/getShortestPaths';
const source = Astro.url.searchParams.get('source')?.trim() || '';
const dest = Astro.url.searchParams.get('dest')?.trim() || '';
const noEmptyParams = source !== '' && dest !== '';
const paramsNotEqual = source !== dest;
let driverNames: string[] = [];
let graphProps: Awaited<ReturnType<typeof getShortestPaths>> = {
nodes: [],
edges: [],
numPaths: 0,
degsOfSeparation: 0
};
try {
driverNames = await getDriverNames();
if (noEmptyParams && paramsNotEqual)
graphProps = await getShortestPaths(source, dest);
} catch (error) {
return Astro.redirect('/error');
}
---
<BaseLayout>
<hgroup>
<h1>Six Degrees of Formula 1</h1>
<p>Find out who's the sport's Kevin Bacon</p>
</hgroup>
<p id="prompt">Get all the shortest paths from/to:</p>
<form action="/" method="GET">
<fieldset class="grid">
<input
type="text"
name="source"
value={source}
placeholder="Source"
aria-label="Source"
list="drivers"
autocomplete="off"
required
/>
<input
type="text"
name="dest"
value={dest}
placeholder="Destination"
aria-label="Destination"
list="drivers"
autocomplete="off"
required
/>
<datalist id="drivers">
{driverNames.map((name) => <option value={name} />)}
</datalist>
</fieldset>
<button type="submit">Search</button>
</form>
{
noEmptyParams &&
(paramsNotEqual ? (
<ShortestPathsGraph {...graphProps} />
) : (
"There's nothing wrong with the inputs, except they're identical."
))
}
</BaseLayout>
<style>
#prompt {
margin-top: 1.75rem;
}
fieldset.grid {
margin-bottom: 0.25rem;
}
button[type='submit'] {
margin-bottom: 2rem;
padding: 0.5rem 0.75rem;
width: unset;
}
</style>