This commit is contained in:
Katharina 2026-07-10 10:54:05 +02:00
commit 28a45440aa
18 changed files with 4276 additions and 0 deletions

252
public/app.js Normal file
View file

@ -0,0 +1,252 @@
"use strict";
let datalistCounter = 0;
let lastResults = [];
let arriveBy = false;
function addStationRow(container, values = {}) {
const row = document.createElement("div");
row.className = "station-row";
const input = document.createElement("input");
input.type = "text";
input.required = true;
input.placeholder = "Station name";
input.autocomplete = "off";
input.value = values.query ?? "";
const datalist = document.createElement("datalist");
datalist.id = `stations-${datalistCounter++}`;
input.setAttribute("list", datalist.id);
wireAutocomplete(input, datalist);
const penalty = document.createElement("input");
penalty.type = "number";
penalty.className = "penalty";
penalty.min = "0";
penalty.step = "1";
penalty.value = values.penalty ?? "0";
penalty.title = "Penalty in minutes (added to this station's journeys for ranking)";
const unit = document.createElement("span");
unit.className = "unit";
unit.textContent = "min";
const remove = document.createElement("button");
remove.type = "button";
remove.className = "remove";
remove.textContent = "×";
remove.title = "Remove station";
remove.addEventListener("click", () => {
if (container.querySelectorAll(".station-row").length > 1) row.remove();
});
row.append(input, penalty, unit, remove, datalist);
container.appendChild(row);
return input;
}
function wireAutocomplete(input, datalist) {
let timer;
input.addEventListener("input", () => {
clearTimeout(timer);
const query = input.value.trim();
if (query.length < 2) return;
timer = setTimeout(async () => {
try {
const res = await fetch(`/api/locations?query=${encodeURIComponent(query)}`);
if (!res.ok) return;
const stations = await res.json();
datalist.replaceChildren(
...stations.map((s) => {
const option = document.createElement("option");
option.value = s.name;
return option;
}),
);
} catch {
/* autocomplete is best-effort */
}
}, 250);
});
}
function collectSide(containerId) {
return [...document.querySelectorAll(`#${containerId} .station-row`)]
.map((row) => ({
query: row.querySelector("input[type=text]").value.trim(),
penalty: Number(row.querySelector(".penalty").value) || 0,
}))
.filter((s) => s.query !== "");
}
async function runSearch(event) {
event.preventDefault();
const button = document.getElementById("search-button");
const feedback = document.getElementById("feedback");
const resultsSection = document.getElementById("results-section");
const body = { from: collectSide("from-rows"), to: collectSide("to-rows") };
const mode = document.getElementById("time-mode").value;
const timeValue = document.getElementById("time-value").value;
if (mode !== "now") {
if (!timeValue) {
showFeedback([`Please pick a ${mode === "departure" ? "departure" : "arrival"} time.`], "error");
return;
}
body[mode] = new Date(timeValue).toISOString();
}
arriveBy = mode === "arrival";
button.disabled = true;
button.textContent = "Searching…";
feedback.hidden = true;
try {
const res = await fetch("/api/search", {
method: "POST",
headers: { "content-type": "application/json" },
body: JSON.stringify(body),
});
const data = await res.json();
if (!res.ok) {
showFeedback([data.error ?? `Search failed (${res.status})`], "error");
resultsSection.hidden = true;
return;
}
lastResults = data.journeys;
const notes = [...(data.warnings ?? []), ...resolutionNotes(data.resolved)];
if (notes.length > 0) showFeedback(notes, "warning");
renderResults();
resultsSection.hidden = false;
} catch (error) {
showFeedback([`Search failed: ${error.message}`], "error");
} finally {
button.disabled = false;
button.textContent = "Search";
}
}
function resolutionNotes(resolved) {
const notes = [];
for (const side of ["from", "to"]) {
for (const r of resolved?.[side] ?? []) {
if (r.station && r.station.name.toLowerCase() !== r.query.toLowerCase()) {
notes.push(`"${r.query}" was interpreted as "${r.station.name}"`);
}
}
}
return notes;
}
function showFeedback(messages, kind) {
const feedback = document.getElementById("feedback");
feedback.className = kind;
feedback.replaceChildren(
...messages.map((m) => {
const p = document.createElement("p");
p.textContent = m;
return p;
}),
);
feedback.hidden = false;
}
function renderResults() {
const sortMode = document.getElementById("sort-mode").value;
const sorted = [...lastResults].sort((a, b) => {
if (sortMode === "time") {
return arriveBy ? b.arrival.localeCompare(a.arrival) : a.departure.localeCompare(b.departure);
}
return a.score - b.score;
});
const list = document.getElementById("results");
list.replaceChildren(...sorted.map(journeyCard));
if (sorted.length === 0) {
const empty = document.createElement("p");
empty.textContent = "No connections found.";
list.replaceChildren(empty);
}
}
function journeyCard(j) {
const item = document.createElement("li");
item.className = "journey";
const head = document.createElement("div");
head.className = "journey-head";
const times = document.createElement("span");
times.className = "times";
times.textContent = `${fmtTime(j.departure)}${fmtTime(j.arrival)}`;
const meta = document.createElement("span");
meta.className = "meta";
const penalty = j.fromPenalty + j.toPenalty;
meta.textContent =
`${fmtDuration(j.durationMinutes)} · ${j.transfers} transfer${j.transfers === 1 ? "" : "s"}` +
(penalty > 0 ? ` · +${penalty} min penalty → score ${j.score}` : "");
head.append(times, meta);
const route = document.createElement("div");
route.className = "route";
route.textContent = `${j.fromStation.name}${j.toStation.name}`;
const lines = document.createElement("div");
lines.className = "lines";
lines.replaceChildren(
...j.journey.legs
.filter((leg) => !leg.walking && leg.line)
.map((leg) => {
const badge = document.createElement("span");
badge.className = "line";
badge.textContent = leg.line.name;
return badge;
}),
);
const details = document.createElement("details");
const summary = document.createElement("summary");
summary.textContent = "Legs";
details.appendChild(summary);
for (const leg of j.journey.legs) {
const p = document.createElement("p");
p.className = "leg";
const what = leg.walking
? "walk"
: `${leg.line?.name ?? "?"}${leg.direction ? `${leg.direction}` : ""}`;
p.textContent = `${fmtTime(leg.departure)} ${leg.origin.name}${what}${fmtTime(leg.arrival)} ${leg.destination.name}`;
details.appendChild(p);
}
item.append(head, route, lines, details);
return item;
}
function fmtTime(iso) {
const date = new Date(iso);
const time = date.toLocaleTimeString([], { hour: "2-digit", minute: "2-digit" });
const today = new Date();
const sameDay =
date.getFullYear() === today.getFullYear() &&
date.getMonth() === today.getMonth() &&
date.getDate() === today.getDate();
return sameDay ? time : `${date.toLocaleDateString([], { day: "numeric", month: "numeric" })} ${time}`;
}
function fmtDuration(minutes) {
const h = Math.floor(minutes / 60);
const m = minutes % 60;
return h > 0 ? `${h} h ${m} min` : `${m} min`;
}
document.getElementById("search-form").addEventListener("submit", runSearch);
document.getElementById("sort-mode").addEventListener("change", renderResults);
document.getElementById("time-mode").addEventListener("change", (event) => {
document.getElementById("time-value").hidden = event.target.value === "now";
});
for (const button of document.querySelectorAll("button.add")) {
button.addEventListener("click", () =>
addStationRow(document.getElementById(button.dataset.target)),
);
}
addStationRow(document.getElementById("from-rows"));
addStationRow(document.getElementById("to-rows"));

56
public/index.html Normal file
View file

@ -0,0 +1,56 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>MultiTrain</title>
<link rel="stylesheet" href="/style.css">
</head>
<body>
<main>
<h1>MultiTrain</h1>
<p class="subtitle">Train connections from many starts to many destinations, ranked with station penalties.</p>
<form id="search-form">
<div class="stations">
<fieldset>
<legend>From</legend>
<div id="from-rows" class="rows" data-side="from"></div>
<button type="button" class="add" data-target="from-rows">+ add start</button>
</fieldset>
<fieldset>
<legend>To</legend>
<div id="to-rows" class="rows" data-side="to"></div>
<button type="button" class="add" data-target="to-rows">+ add destination</button>
</fieldset>
</div>
<div class="time-row">
<select id="time-mode">
<option value="now" selected>Depart now</option>
<option value="departure">Depart at</option>
<option value="arrival">Arrive by</option>
</select>
<input type="datetime-local" id="time-value" hidden>
<button type="submit" id="search-button">Search</button>
</div>
</form>
<section id="feedback" hidden></section>
<section id="results-section" hidden>
<div class="results-header">
<h2>Connections</h2>
<label>Sort by
<select id="sort-mode">
<option value="score" selected>best (incl. penalty)</option>
<option value="time">departure time</option>
</select>
</label>
</div>
<ol id="results"></ol>
</section>
</main>
<script src="/app.js"></script>
</body>
</html>

153
public/style.css Normal file
View file

@ -0,0 +1,153 @@
:root {
color-scheme: light dark;
--bg: #fafafa;
--card: #ffffff;
--text: #1a1a1a;
--muted: #666;
--accent: #c8102e;
--border: #ddd;
--warning-bg: #fff6e0;
--error-bg: #ffe5e5;
}
@media (prefers-color-scheme: dark) {
:root {
--bg: #16181c;
--card: #1f2228;
--text: #eceff4;
--muted: #9aa2ad;
--accent: #ff5a70;
--border: #34383f;
--warning-bg: #3a3323;
--error-bg: #40272b;
}
}
* { box-sizing: border-box; }
body {
margin: 0;
background: var(--bg);
color: var(--text);
font-family: system-ui, sans-serif;
line-height: 1.45;
}
main {
max-width: 44rem;
margin: 0 auto;
padding: 1.5rem 1rem 4rem;
}
h1 { margin-bottom: 0.2rem; }
.subtitle { margin-top: 0; color: var(--muted); }
.stations {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 1rem;
}
@media (max-width: 38rem) {
.stations { grid-template-columns: 1fr; }
}
fieldset {
border: 1px solid var(--border);
border-radius: 8px;
padding: 0.75rem;
background: var(--card);
}
.station-row {
display: flex;
align-items: center;
gap: 0.4rem;
margin-bottom: 0.5rem;
}
.station-row input[type="text"] { flex: 1; min-width: 0; }
input, select, button {
font: inherit;
color: inherit;
background: var(--bg);
border: 1px solid var(--border);
border-radius: 6px;
padding: 0.45rem 0.6rem;
}
.penalty { width: 4.2rem; }
.unit { color: var(--muted); font-size: 0.85rem; }
button { cursor: pointer; }
button.add { background: none; border: 1px dashed var(--border); width: 100%; color: var(--muted); }
button.remove { padding: 0.2rem 0.55rem; color: var(--muted); }
.time-row {
display: flex;
gap: 0.5rem;
margin-top: 1rem;
flex-wrap: wrap;
}
#search-button {
background: var(--accent);
border-color: var(--accent);
color: #fff;
font-weight: 600;
padding: 0.45rem 1.4rem;
margin-left: auto;
}
#search-button:disabled { opacity: 0.6; }
#feedback { border-radius: 8px; padding: 0.6rem 0.9rem; margin-top: 1rem; }
#feedback.warning { background: var(--warning-bg); }
#feedback.error { background: var(--error-bg); }
#feedback p { margin: 0.2rem 0; }
.results-header {
display: flex;
justify-content: space-between;
align-items: baseline;
margin-top: 1.5rem;
}
.results-header label { color: var(--muted); font-size: 0.9rem; }
#results { list-style: none; padding: 0; margin: 0; }
.journey {
background: var(--card);
border: 1px solid var(--border);
border-radius: 8px;
padding: 0.8rem 1rem;
margin-bottom: 0.7rem;
}
.journey-head {
display: flex;
justify-content: space-between;
flex-wrap: wrap;
gap: 0.3rem;
}
.times { font-weight: 700; font-variant-numeric: tabular-nums; }
.meta { color: var(--muted); font-size: 0.9rem; }
.route { color: var(--muted); font-size: 0.9rem; margin-top: 0.15rem; }
.lines { margin-top: 0.4rem; display: flex; flex-wrap: wrap; gap: 0.3rem; }
.line {
background: var(--accent);
color: #fff;
border-radius: 4px;
font-size: 0.8rem;
font-weight: 600;
padding: 0.1rem 0.45rem;
}
details { margin-top: 0.5rem; }
summary { cursor: pointer; color: var(--muted); font-size: 0.9rem; }
.leg { margin: 0.25rem 0 0.25rem 1rem; font-size: 0.9rem; }