248 lines
13 KiB
JavaScript
248 lines
13 KiB
JavaScript
import { createBurstListener } from "./burst-listener.js";
|
|
const t = window.BOOMCAST_I18N || {};
|
|
|
|
const manualForm = document.querySelector("#manual-report-form");
|
|
const manualSubmit = document.querySelector("#manual-submit");
|
|
const submitLabel = document.querySelector("#manual-submit-label");
|
|
const occurrences = document.querySelector("#manual-occurrences");
|
|
const decrease = document.querySelector("#manual-decrease");
|
|
const increase = document.querySelector("#manual-increase");
|
|
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 compass = document.querySelector("#manual-compass");
|
|
const compassRose = document.querySelector("#manual-compass-rose");
|
|
const compassHeading = document.querySelector("#manual-compass-heading");
|
|
let orientationListener;
|
|
let compassUnavailableTimeout;
|
|
let compassRotation = null;
|
|
const burstListener = createBurstListener();
|
|
|
|
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 idleSubmitLabel = submitLabel?.textContent || "I heard fireworks";
|
|
|
|
const setSubmissionState = (next, message = "") => {
|
|
manualForm.dataset.state = next;
|
|
manualSubmit.disabled = next === "submitting";
|
|
if (submitLabel) submitLabel.textContent = next === "submitting" ? (t.sendingReport || "Sending…") : idleSubmitLabel;
|
|
if (message) {
|
|
const status = document.querySelector("#manual-submission");
|
|
status.className = "manual-report__submission";
|
|
status.textContent = message;
|
|
}
|
|
};
|
|
|
|
const showResponse = (html, successful) => {
|
|
const parsed = new DOMParser().parseFromString(html, "text/html").querySelector("#manual-submission");
|
|
if (!parsed) {
|
|
setSubmissionState("error", t.reportFailed || "Could not send the report. Please try again.");
|
|
return false;
|
|
}
|
|
document.querySelector("#manual-submission").replaceWith(parsed);
|
|
setSubmissionState(successful ? "submitted" : "error");
|
|
return successful;
|
|
};
|
|
|
|
const setCount = (value) => {
|
|
const count = Number.parseInt(value, 10);
|
|
occurrences.value = String(Math.min(1000, Math.max(1, Number.isFinite(count) ? count : 1)));
|
|
decrease.disabled = occurrences.value === "1";
|
|
increase.disabled = occurrences.value === "1000";
|
|
};
|
|
setCount(occurrences.value);
|
|
decrease.addEventListener("click", () => setCount(Number(occurrences.value) - 1));
|
|
increase.addEventListener("click", () => setCount(Number(occurrences.value) + 1));
|
|
occurrences.addEventListener("change", () => setCount(occurrences.value));
|
|
|
|
const stopCompassReading = () => {
|
|
if (orientationListener) window.removeEventListener("deviceorientation", orientationListener);
|
|
window.clearTimeout(compassUnavailableTimeout);
|
|
orientationListener = null;
|
|
compassUnavailableTimeout = null;
|
|
compass.hidden = true;
|
|
compassRotation = null;
|
|
};
|
|
|
|
const updateCompass = (heading) => {
|
|
const targetRotation = -heading;
|
|
if (compassRotation === null) {
|
|
compassRotation = targetRotation;
|
|
compassRose.style.transition = "none";
|
|
compassRose.style.transform = `rotate(${compassRotation}deg)`;
|
|
// Restore the short rotation animation after the initial reading.
|
|
compassRose.offsetWidth;
|
|
compassRose.style.transition = "";
|
|
} else {
|
|
const change = ((targetRotation - compassRotation + 540) % 360) - 180;
|
|
compassRotation += change;
|
|
compassRose.style.transform = `rotate(${compassRotation}deg)`;
|
|
}
|
|
compassHeading.textContent = `${displayDegrees(heading)}° · ${cardinalDirection(heading)}`;
|
|
compass.setAttribute("aria-label", `${t.compassDirection || "Compass direction"} ${displayDegrees(heading)}° ${cardinalDirection(heading)}`);
|
|
compass.hidden = false;
|
|
};
|
|
|
|
const showCapturedDirection = (heading, accuracy) => {
|
|
const accuracyText = accuracy === null ? (t.accuracyUnavailable || "Accuracy unavailable") : (t.accuracy || "Accuracy") + ": ±" + displayDegrees(accuracy) + "°";
|
|
const status = directionStatus();
|
|
if (status) status.innerHTML = "<strong>" + cardinalDirection(heading) + " · " + displayDegrees(heading) + "°</strong><br>" + accuracyText;
|
|
const button = captureDirectionButton();
|
|
if (button) button.textContent = (t.stopCapture || "Stop measuring direction");
|
|
};
|
|
|
|
const listenForCompassReading = () => {
|
|
if (!directionStatus()) return;
|
|
stopCompassReading();
|
|
if (directionPanel()) directionPanel().dataset.state = "measuring";
|
|
directionStatus().textContent = (t.pointPhone || "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);
|
|
updateCompass(heading);
|
|
window.clearTimeout(compassUnavailableTimeout);
|
|
};
|
|
window.addEventListener("deviceorientation", orientationListener);
|
|
compassUnavailableTimeout = window.setTimeout(() => {
|
|
stopCompassReading();
|
|
const button = captureDirectionButton();
|
|
const status = directionStatus();
|
|
if (button) button.textContent = (t.captureDirection || "Start measuring direction");
|
|
if (status) status.textContent = (t.compassUnavailable || "Compass unavailable on this device.");
|
|
if (directionPanel()) directionPanel().dataset.state = "unavailable";
|
|
}, 15000);
|
|
};
|
|
|
|
const captureDirection = async () => {
|
|
if (orientationListener) {
|
|
stopCompassReading();
|
|
captureDirectionButton().textContent = (t.captureAgain || "Measure again");
|
|
if (directionPanel()) directionPanel().dataset.state = directionDegrees.value ? "captured" : "ready";
|
|
return;
|
|
}
|
|
if (!window.isSecureContext) {
|
|
directionStatus().textContent = (t.secureCompass || "Compass capture requires a secure HTTPS connection.");
|
|
if (directionPanel()) directionPanel().dataset.state = "unavailable";
|
|
return;
|
|
}
|
|
if (typeof window.DeviceOrientationEvent === "undefined") {
|
|
directionStatus().textContent = (t.compassUnavailable || "Compass unavailable on this device.");
|
|
if (directionPanel()) directionPanel().dataset.state = "unavailable";
|
|
return;
|
|
}
|
|
if (typeof DeviceOrientationEvent.requestPermission === "function") {
|
|
directionStatus().textContent = (t.compassPermission || "Requesting compass permission…");
|
|
try {
|
|
if (await DeviceOrientationEvent.requestPermission(true) !== "granted") {
|
|
if (directionStatus()) directionStatus().textContent = (t.compassDenied || "Compass permission denied.");
|
|
if (directionPanel()) directionPanel().dataset.state = "unavailable";
|
|
return;
|
|
}
|
|
} catch (error) {
|
|
if (directionStatus()) directionStatus().textContent = (t.compassDenied || "Compass permission denied.");
|
|
if (directionPanel()) directionPanel().dataset.state = "unavailable";
|
|
return;
|
|
}
|
|
}
|
|
listenForCompassReading();
|
|
};
|
|
|
|
const submitManualReport = async () => {
|
|
setCount(occurrences.value);
|
|
stopCompassReading();
|
|
setSubmissionState("submitting", t.sendingReport || "Sending…");
|
|
if (burstListener?.active) {
|
|
try {
|
|
const audio = await burstListener.clipForSubmission();
|
|
const data = new FormData(manualForm);
|
|
if (audio) data.append("audio", audio);
|
|
const response = await fetch(manualForm.action, { method: "POST", body: data, credentials: "same-origin" });
|
|
const html = await response.text();
|
|
if (showResponse(html, response.ok)) burstListener.submissionSucceeded();
|
|
} catch (error) {
|
|
setSubmissionState("error", t.reportFailed || "Could not send the report. Please try again.");
|
|
}
|
|
return;
|
|
}
|
|
if (window.htmx) {
|
|
try {
|
|
htmx.ajax("POST", manualForm.action, {
|
|
source: manualForm,
|
|
target: "#manual-submission",
|
|
swap: "outerHTML",
|
|
});
|
|
} catch (error) {
|
|
setSubmissionState("error", t.reportFailed || "Could not send the report. Please try again.");
|
|
}
|
|
} else {
|
|
manualForm.submit();
|
|
}
|
|
};
|
|
|
|
manualForm.addEventListener("click", (event) => {
|
|
if (event.target.closest("#manual-capture-direction")) captureDirection();
|
|
if (event.target.closest(".manual-direction-panel__close")) stopCompassReading();
|
|
});
|
|
document.body.addEventListener("htmx:afterSwap", (event) => {
|
|
if (event.detail.target?.id !== "manual-direction-panel") return;
|
|
const summary = document.querySelector("#manual-direction-summary");
|
|
if (summary && directionDegrees.value !== "") {
|
|
const heading = Number(directionDegrees.value);
|
|
summary.textContent = `${cardinalDirection(heading)} · ${displayDegrees(heading)}°`;
|
|
directionPanel().dataset.state = "captured";
|
|
}
|
|
});
|
|
manualSubmit.addEventListener("click", () => {
|
|
if (manualSubmit.disabled) return;
|
|
setSubmissionState("submitting", t.requestingLocation || "Requesting your optional location…");
|
|
if (!navigator.geolocation) {
|
|
submitManualReport();
|
|
return;
|
|
}
|
|
navigator.geolocation.getCurrentPosition(
|
|
(position) => {
|
|
latitude.value = position.coords.latitude;
|
|
longitude.value = position.coords.longitude;
|
|
submitManualReport();
|
|
},
|
|
() => submitManualReport(),
|
|
{ enableHighAccuracy: false, maximumAge: 300000, timeout: 10000 },
|
|
);
|
|
});
|
|
manualForm.addEventListener("submit", (event) => {
|
|
event.preventDefault();
|
|
if (!manualSubmit.disabled) manualSubmit.click();
|
|
});
|
|
document.body.addEventListener("htmx:afterRequest", (event) => {
|
|
if (event.detail.elt !== manualForm) return;
|
|
const response = event.detail.xhr;
|
|
if (!response) {
|
|
setSubmissionState("error", t.reportFailed || "Could not send the report. Please try again.");
|
|
} else if (response.status >= 400) {
|
|
showResponse(response.responseText, false);
|
|
} else {
|
|
setSubmissionState("submitted");
|
|
}
|
|
});
|
|
document.body.addEventListener("htmx:sendError", (event) => {
|
|
if (event.detail.elt === manualForm) setSubmissionState("error", t.reportFailed || "Could not send the report. Please try again.");
|
|
});
|
|
|