added light/dark mode toggle v1, unified menu

This commit is contained in:
Joren de Graaf
2026-10-01 17:14:19 +02:00
parent 8f838715dd
commit 7d538b774d
102 changed files with 1870 additions and 1365 deletions
@@ -0,0 +1 @@
document.querySelectorAll('.audio-preview').forEach(function(box){var button=box.querySelector('.audio-play'),audio=box.querySelector('audio'),label=box.querySelector('.audio-play__label'),status=box.querySelector('.audio-status');button.addEventListener('click',function(){if(!audio.src){audio.src=button.dataset.audioUrl;button.classList.add('is-loading');status.textContent='Loading recording…';}if(audio.paused){audio.play().catch(function(){button.classList.remove('is-loading');status.textContent='Could not play this recording.';});}else{audio.pause();}});audio.addEventListener('playing',function(){button.classList.remove('is-loading');label.textContent='Pause recording';status.textContent='Playing now';});audio.addEventListener('pause',function(){if(!audio.ended){label.textContent='Resume recording';status.textContent='Paused';}});audio.addEventListener('ended',function(){label.textContent='Replay recording';status.textContent='Finished';});audio.addEventListener('waiting',function(){button.classList.add('is-loading');status.textContent='Buffering…';});audio.addEventListener('canplay',function(){button.classList.remove('is-loading');});audio.addEventListener('error',function(){button.classList.remove('is-loading');status.textContent='Could not load this recording.';});});
+30
View File
@@ -0,0 +1,30 @@
const form = document.querySelector('.upload-form');
const dropZone = document.querySelector('#drop-zone');
const fileInput = document.querySelector('#audio-file');
const fileName = document.querySelector('#file-name');
const status = document.querySelector('#upload-status');
const showFile = (file) => { fileName.textContent = file ? file.name : 'No file selected'; };
fileInput.addEventListener('change', () => showFile(fileInput.files[0]));
['dragenter', 'dragover'].forEach((eventName) => dropZone.addEventListener(eventName, (event) => { event.preventDefault(); dropZone.classList.add('dragging'); }));
['dragleave', 'drop'].forEach((eventName) => dropZone.addEventListener(eventName, (event) => { event.preventDefault(); dropZone.classList.remove('dragging'); }));
dropZone.addEventListener('drop', (event) => { const [file] = event.dataTransfer.files; if (!file) return; fileInput.files = event.dataTransfer.files; showFile(file); });
form.addEventListener('htmx:beforeRequest', () => { status.textContent = 'Analysing your recording…'; form.setAttribute('aria-busy', 'true'); });
form.addEventListener('htmx:afterRequest', () => { status.textContent = ''; form.removeAttribute('aria-busy'); });
form.addEventListener('htmx:responseError', () => { status.textContent = 'Analysis could not be completed.'; });
document.body.addEventListener('htmx:beforeSwap', (event) => {
if (event.detail.xhr.status >= 400) {
event.detail.shouldSwap = true;
event.detail.isError = false;
}
});
window.addEventListener('pageshow', (event) => {
if (event.persisted) {
fileInput.value = '';
showFile();
status.textContent = '';
document.querySelector('#classification-results').replaceChildren();
}
});
+98
View File
@@ -0,0 +1,98 @@
const mapElement = document.getElementById("event-map");
const h3Resolution = mapElement.dataset.h3Resolution;
const map = L.map(mapElement, { zoomControl: false, scrollWheelZoom: false }).setView([52.1326, 5.2913], 7);
L.control.zoom({ position: "bottomleft" }).addTo(map);
const compassControl = L.control({ position: "topright" });
compassControl.onAdd = () => {
const compass = L.DomUtil.create("div", "map-compass");
compass.setAttribute("role", "img");
compass.setAttribute("aria-label", "Map compass: north is up");
compass.innerHTML = "<span class=\"compass-n\">N</span><span class=\"compass-e\">E</span><span class=\"compass-s\">S</span><span class=\"compass-w\">W</span><span class=\"compass-needle\">↑</span>";
L.DomEvent.disableClickPropagation(compass);
return compass;
};
compassControl.addTo(map);
L.tileLayer("https://{s}.tile.openstreetmap.de/{z}/{x}/{y}.png", {
maxZoom: 18,
attribution: "&copy; OpenStreetMap contributors",
}).addTo(map);
const h3Cells = JSON.parse(document.getElementById("h3-cells-data").textContent);
const reports = JSON.parse(document.getElementById("map-events-data").textContent);
const bounds = L.latLngBounds([]);
h3Cells.forEach((cell) => {
const polygon = L.polygon(cell.boundary, {
color: "#f59e0b", weight: 2, fillColor: "#f59e0b", fillOpacity: 0.25,
}).addTo(map);
polygon.bindPopup(
"<span class=\"popup-title\">H3 " + cell.cell + "</span>" +
"<span class=\"popup-meta\">" + cell.reports + " reports · " + cell.occurrences +
" occurrences · resolution " + h3Resolution + "</span>"
);
bounds.extend(L.latLngBounds(cell.boundary));
});
function cardinalDirection(degrees) {
const directions = ["N", "NE", "E", "SE", "S", "SW", "W", "NW"];
return directions[Math.floor(((degrees + 22.5) % 360) / 45)];
}
function destinationPoint(origin, bearingDegrees, distanceMetres) {
const earthRadius = 6378137;
const bearing = bearingDegrees * Math.PI / 180;
const latitude = origin[0] * Math.PI / 180;
const longitude = origin[1] * Math.PI / 180;
const angularDistance = distanceMetres / earthRadius;
const targetLatitude = Math.asin(
Math.sin(latitude) * Math.cos(angularDistance) +
Math.cos(latitude) * Math.sin(angularDistance) * Math.cos(bearing)
);
const targetLongitude = longitude + Math.atan2(
Math.sin(bearing) * Math.sin(angularDistance) * Math.cos(latitude),
Math.cos(angularDistance) - Math.sin(latitude) * Math.sin(targetLatitude)
);
return [targetLatitude * 180 / Math.PI, targetLongitude * 180 / Math.PI];
}
const reportIcon = L.divIcon({
className: "", html: "<div class=\"report-icon\">✦</div>", iconSize: [37, 37], iconAnchor: [19, 19],
});
reports.forEach((report) => {
const visualStatus = report.visually_confirmed ? "Visually confirmed" : "Not visually confirmed";
let detail = report.occurrences + " occurrence" + (report.occurrences === 1 ? "" : "s") +
" · " + visualStatus + "<br>Reported " + report.reported_on;
if (report.direction_degrees !== null) {
detail += "<br>Compass direction " + Math.round(report.direction_degrees) + "° (" + cardinalDirection(report.direction_degrees) + ")";
if (report.direction_accuracy_degrees !== null) {
detail += " (±" + Math.round(report.direction_accuracy_degrees) + "°)";
}
}
L.marker(report.center, { icon: reportIcon }).addTo(map).bindPopup(
"<span class=\"popup-title\">Manual report · H3 " + report.cell + "</span>" +
"<span class=\"popup-meta\">" + detail + "</span>"
);
if (report.direction_degrees !== null) {
const arrowEnd = destinationPoint(report.center, report.direction_degrees, 900);
L.polyline([report.center, arrowEnd], { color: "#fff7e6", weight: 9, opacity: 0.8 }).addTo(map);
L.polyline([report.center, arrowEnd], { color: "#6d45a0", weight: 5, opacity: 1 }).addTo(map);
const arrowIcon = L.divIcon({
className: "",
html: "<div class=\"direction-marker\"><span style=\"transform:rotate(" + report.direction_degrees + "deg)\">↑</span></div>",
iconSize: [56, 56], iconAnchor: [28, 28],
});
L.marker(arrowEnd, { icon: arrowIcon, interactive: false }).addTo(map);
}
});
if (bounds.isValid()) {
map.fitBounds(bounds.pad(0.18));
}
const range = document.getElementById("range");
document.querySelectorAll("#from-date, #to-date").forEach((input) => {
input.addEventListener("change", () => { range.value = "custom"; });
});
@@ -0,0 +1,16 @@
const form = document.querySelector('.upload-form');
const dropZone = document.querySelector('#drop-zone');
const fileInput = document.querySelector('#audio-file');
const fileName = document.querySelector('#file-name');
const status = document.querySelector('#upload-status');
const showFile = (file) => { fileName.textContent = file ? file.name : 'No file selected'; };
fileInput.addEventListener('change', () => showFile(fileInput.files[0]));
['dragenter', 'dragover'].forEach((eventName) => dropZone.addEventListener(eventName, (event) => { event.preventDefault(); dropZone.classList.add('dragging'); }));
['dragleave', 'drop'].forEach((eventName) => dropZone.addEventListener(eventName, (event) => { event.preventDefault(); dropZone.classList.remove('dragging'); }));
dropZone.addEventListener('drop', (event) => { const [file] = event.dataTransfer.files; if (!file) return; fileInput.files = event.dataTransfer.files; showFile(file); });
form.addEventListener('htmx:beforeRequest', () => { status.textContent = 'Analysing your recording…'; form.setAttribute('aria-busy', 'true'); });
form.addEventListener('htmx:afterRequest', () => { status.textContent = ''; form.removeAttribute('aria-busy'); });
form.addEventListener('htmx:responseError', () => { status.textContent = 'Analysis could not be completed.'; });
+126
View File
@@ -0,0 +1,126 @@
const manualForm = document.querySelector("#manual-report-form");
const manualSubmit = document.querySelector("#manual-submit");
const manualStatus = document.querySelector("#manual-submission");
const latitude = document.querySelector("#manual-latitude");
const longitude = document.querySelector("#manual-longitude");
const directionDegrees = document.querySelector("#manual-direction-degrees");
const directionAccuracy = document.querySelector("#manual-direction-accuracy");
const captureDirectionButton = document.querySelector("#manual-capture-direction");
const directionStatus = document.querySelector("#manual-direction-status");
const directionPanel = document.querySelector("#manual-direction-panel");
const isMobileDevice = /Android|iPhone|iPad|iPod|IEMobile|Opera Mini/.test(navigator.userAgent)
|| (navigator.userAgent.includes("Macintosh") && navigator.maxTouchPoints > 1);
if (isMobileDevice) directionPanel.hidden = false;
let orientationListener;
let compassUnavailableTimeout;
const isUsableNumber = (value) => Number.isFinite(value);
const cardinalDirection = (heading) => ["N", "NE", "E", "SE", "S", "SW", "W", "NW"][Math.floor(((heading + 22.5) % 360) / 45)];
const displayDegrees = (value) => Number(value.toFixed(1)).toString();
const stopCompassReading = () => {
if (orientationListener) window.removeEventListener("deviceorientation", orientationListener);
window.clearTimeout(compassUnavailableTimeout);
orientationListener = null;
compassUnavailableTimeout = null;
};
const showCapturedDirection = (heading, accuracy) => {
const accuracyText = accuracy === null ? "Accuracy unavailable" : "Accuracy: ±" + displayDegrees(accuracy) + "°";
directionStatus.innerHTML = "<strong>" + displayDegrees(heading) + "° · " + cardinalDirection(heading) + "</strong><br>" + accuracyText;
captureDirectionButton.textContent = "Stop direction capture";
};
const listenForCompassReading = () => {
stopCompassReading();
directionStatus.textContent = "Point the top of your phone toward the sound — direction will update live.";
orientationListener = (event) => {
const isWebKitCompass = "webkitCompassHeading" in event;
const heading = isUsableNumber(event.webkitCompassHeading)
? event.webkitCompassHeading
: !isWebKitCompass && event.absolute && isUsableNumber(event.alpha)
? (360 - event.alpha) % 360
: null;
if (heading === null || heading < 0 || heading >= 360) return;
const accuracy = isUsableNumber(event.webkitCompassAccuracy) && event.webkitCompassAccuracy >= 0
? event.webkitCompassAccuracy
: null;
directionDegrees.value = heading;
directionAccuracy.value = accuracy === null ? "" : accuracy;
showCapturedDirection(heading, accuracy);
window.clearTimeout(compassUnavailableTimeout);
};
window.addEventListener("deviceorientation", orientationListener);
compassUnavailableTimeout = window.setTimeout(() => {
stopCompassReading();
captureDirectionButton.textContent = "Capture direction";
directionStatus.textContent = "Compass unavailable on this device.";
}, 15000);
};
const captureDirection = async () => {
if (orientationListener) {
stopCompassReading();
captureDirectionButton.textContent = "Capture again";
return;
}
if (!window.isSecureContext) {
directionStatus.textContent = "Compass capture requires a secure HTTPS connection.";
return;
}
if (typeof window.DeviceOrientationEvent === "undefined") {
directionStatus.textContent = "Compass unavailable on this device.";
return;
}
if (typeof DeviceOrientationEvent.requestPermission === "function") {
directionStatus.textContent = "Requesting compass permission…";
try {
if (await DeviceOrientationEvent.requestPermission(true) !== "granted") {
directionStatus.textContent = "Compass permission denied.";
return;
}
} catch (error) {
directionStatus.textContent = "Compass permission denied.";
return;
}
}
listenForCompassReading();
};
const submitManualReport = () => {
stopCompassReading();
manualSubmit.disabled = true;
if (window.htmx) {
htmx.ajax("POST", manualForm.action, {
source: manualForm,
target: "#manual-submission",
swap: "outerHTML",
});
} else {
manualForm.submit();
}
};
captureDirectionButton.addEventListener("click", captureDirection);
manualSubmit.addEventListener("click", () => {
if (!navigator.geolocation) {
submitManualReport();
return;
}
manualStatus.textContent = "Requesting your optional location…";
navigator.geolocation.getCurrentPosition(
(position) => {
latitude.value = position.coords.latitude;
longitude.value = position.coords.longitude;
submitManualReport();
},
() => submitManualReport(),
{ enableHighAccuracy: false, maximumAge: 300000, timeout: 10000 },
);
});
document.body.addEventListener("htmx:afterRequest", (event) => {
if (event.detail.elt === manualForm) manualSubmit.disabled = false;
});
+42
View File
@@ -0,0 +1,42 @@
const storageKey = "sound-signal-theme";
const themes = new Set(["dark", "light"]);
function savedTheme() {
try {
const value = window.localStorage.getItem(storageKey);
return themes.has(value) ? value : "dark";
} catch {
return "dark";
}
}
function applyTheme(theme, button) {
document.documentElement.dataset.theme = theme;
if (!button) return;
const nextTheme = theme === "dark" ? "light" : "dark";
button.textContent = nextTheme === "light" ? "☀ Light mode" : "☾ Dark mode";
button.setAttribute("aria-label", "Switch to " + nextTheme + " mode");
button.setAttribute("aria-pressed", String(theme === "light"));
}
function installThemeToggle() {
const button = document.querySelector(".theme-toggle") ?? document.createElement("button");
if (!button.isConnected) {
button.className = "theme-toggle";
button.type = "button";
document.body.append(button);
}
applyTheme(savedTheme(), button);
button.addEventListener("click", () => {
const nextTheme = document.documentElement.dataset.theme === "dark" ? "light" : "dark";
try { window.localStorage.setItem(storageKey, nextTheme); } catch {}
applyTheme(nextTheme, button);
});
}
applyTheme(savedTheme());
if (document.readyState === "loading") {
document.addEventListener("DOMContentLoaded", installThemeToggle, { once: true });
} else {
installThemeToggle();
}
+1
View File
@@ -0,0 +1 @@
document.querySelector("#ntfy-url").addEventListener("input", () => { document.querySelector("#ntfy-test-result").replaceChildren(); });