276 lines
10 KiB
JavaScript
276 lines
10 KiB
JavaScript
import htmx from 'htmx.org';
|
|
import './styles/main.scss';
|
|
|
|
window.htmx = htmx;
|
|
|
|
function getCookie(name) {
|
|
const value = `; ${document.cookie}`;
|
|
const parts = value.split(`; ${name}=`);
|
|
return parts.length === 2 ? parts.pop().split(';').shift() : '';
|
|
}
|
|
|
|
htmx.on('htmx:configRequest', (event) => {
|
|
event.detail.headers['X-CSRFToken'] = getCookie('csrftoken');
|
|
});
|
|
|
|
function initialiseMobileNavigation() {
|
|
const toggle = document.querySelector('[data-nav-toggle]');
|
|
const closeButton = document.querySelector('[data-nav-close]');
|
|
const nav = document.querySelector('#primary-navigation');
|
|
const backdrop = document.querySelector('[data-nav-backdrop]');
|
|
if (!toggle || !closeButton || !nav || !backdrop) return;
|
|
|
|
const mobile = window.matchMedia('(max-width: 700px)');
|
|
document.body.classList.add('js-nav-ready');
|
|
|
|
function closeMenu(restoreFocus = true) {
|
|
if (!document.body.classList.contains('mobile-nav-open')) return;
|
|
document.body.classList.remove('mobile-nav-open');
|
|
toggle.setAttribute('aria-expanded', 'false');
|
|
toggle.setAttribute('aria-label', 'Open menu');
|
|
backdrop.hidden = true;
|
|
nav.inert = mobile.matches;
|
|
if (restoreFocus) toggle.focus();
|
|
}
|
|
|
|
function openMenu() {
|
|
if (!mobile.matches) return;
|
|
document.body.classList.add('mobile-nav-open');
|
|
toggle.setAttribute('aria-expanded', 'true');
|
|
toggle.setAttribute('aria-label', 'Close menu');
|
|
backdrop.hidden = false;
|
|
nav.inert = false;
|
|
closeButton.focus();
|
|
}
|
|
|
|
function syncViewport() {
|
|
closeMenu(false);
|
|
nav.inert = mobile.matches;
|
|
}
|
|
|
|
toggle.addEventListener('click', () => {
|
|
if (document.body.classList.contains('mobile-nav-open')) closeMenu();
|
|
else openMenu();
|
|
});
|
|
closeButton.addEventListener('click', () => closeMenu());
|
|
backdrop.addEventListener('click', () => closeMenu());
|
|
document.addEventListener('keydown', (event) => {
|
|
if (!document.body.classList.contains('mobile-nav-open')) return;
|
|
if (event.key === 'Escape') {
|
|
event.preventDefault();
|
|
closeMenu();
|
|
} else if (event.key === 'Tab') {
|
|
const focusable = Array.from(nav.querySelectorAll('a, button:not([disabled])'));
|
|
const first = focusable[0];
|
|
const last = focusable[focusable.length - 1];
|
|
if (event.shiftKey && document.activeElement === first) {
|
|
event.preventDefault();
|
|
last.focus();
|
|
} else if (!event.shiftKey && document.activeElement === last) {
|
|
event.preventDefault();
|
|
first.focus();
|
|
}
|
|
}
|
|
});
|
|
mobile.addEventListener('change', syncViewport);
|
|
syncViewport();
|
|
}
|
|
|
|
document.addEventListener('DOMContentLoaded', initialiseMobileNavigation);
|
|
|
|
|
|
let fastingTimerInterval;
|
|
|
|
function formatElapsed(milliseconds) {
|
|
const totalSeconds = Math.max(0, Math.floor(milliseconds / 1000));
|
|
const hours = Math.floor(totalSeconds / 3600);
|
|
const minutes = Math.floor((totalSeconds % 3600) / 60);
|
|
const seconds = totalSeconds % 60;
|
|
return [hours, minutes, seconds].map((value) => String(value).padStart(2, '0')).join(':');
|
|
}
|
|
|
|
function updateFastingTimers() {
|
|
document.querySelectorAll('[data-fasting-timer]').forEach((timer) => {
|
|
const cycleStart = Date.parse(timer.dataset.cycleStart);
|
|
const cycleEnd = Date.parse(timer.dataset.cycleEnd);
|
|
if (!Number.isFinite(cycleStart) || !Number.isFinite(cycleEnd) || cycleEnd <= cycleStart) {
|
|
return;
|
|
}
|
|
|
|
const now = Date.now();
|
|
const progress = Math.max(0, Math.min(100, ((now - cycleStart) / (cycleEnd - cycleStart)) * 100));
|
|
const elapsed = timer.querySelector('[data-fasting-elapsed]');
|
|
const ring = timer.querySelector('[data-fasting-progress]');
|
|
if (elapsed) elapsed.textContent = formatElapsed(now - cycleStart);
|
|
if (ring) ring.style.strokeDashoffset = String(100 - progress);
|
|
timer.setAttribute('aria-label', `${timer.dataset.phase} progress: ${Math.floor(progress)} percent`);
|
|
|
|
// A server refresh switches to the next phase and synchronizes completion history.
|
|
if (now >= cycleEnd && !timer.dataset.refreshing) {
|
|
timer.dataset.refreshing = 'true';
|
|
htmx.ajax('GET', timer.dataset.refreshUrl, {target: '#fasting-widget', swap: 'outerHTML'});
|
|
}
|
|
});
|
|
}
|
|
|
|
function initialiseFastingTimers() {
|
|
window.clearInterval(fastingTimerInterval);
|
|
updateFastingTimers();
|
|
if (document.querySelector('[data-fasting-timer]')) {
|
|
fastingTimerInterval = window.setInterval(updateFastingTimers, 1000);
|
|
}
|
|
}
|
|
|
|
document.addEventListener('DOMContentLoaded', initialiseFastingTimers);
|
|
htmx.on('htmx:afterSwap', initialiseFastingTimers);
|
|
|
|
|
|
function initialiseGeolocation() {
|
|
const button = document.querySelector('[data-use-location]');
|
|
if (!button || button.dataset.ready) return;
|
|
button.dataset.ready = 'true';
|
|
button.addEventListener('click', () => {
|
|
const status = document.querySelector('[data-location-status]');
|
|
const latitude = document.querySelector('[name="latitude"]');
|
|
const longitude = document.querySelector('[name="longitude"]');
|
|
if (!navigator.geolocation) {
|
|
if (status) status.textContent = 'Location is unavailable in this browser. You can enter coordinates manually.';
|
|
return;
|
|
}
|
|
if (status) status.textContent = 'Requesting your location…';
|
|
navigator.geolocation.getCurrentPosition((position) => {
|
|
if (latitude) latitude.value = position.coords.latitude.toFixed(5);
|
|
if (longitude) longitude.value = position.coords.longitude.toFixed(5);
|
|
if (status) status.textContent = 'Location added. Save settings to confirm it.';
|
|
}, () => {
|
|
if (status) status.textContent = 'Location was unavailable. You can enter coordinates manually.';
|
|
}, {enableHighAccuracy: false, timeout: 10000, maximumAge: 0});
|
|
});
|
|
}
|
|
|
|
document.addEventListener('DOMContentLoaded', initialiseGeolocation);
|
|
htmx.on('htmx:afterSwap', initialiseGeolocation);
|
|
|
|
function initialiseNtfyForm() {
|
|
document.querySelectorAll('[data-ntfy-form]').forEach((form) => {
|
|
if (form.dataset.ready) return;
|
|
form.dataset.ready = 'true';
|
|
form.querySelector('[name="ntfy_url"]')?.addEventListener('input', () => {
|
|
form.querySelector('#ntfy-test-result')?.replaceChildren();
|
|
});
|
|
});
|
|
}
|
|
|
|
document.addEventListener('DOMContentLoaded', initialiseNtfyForm);
|
|
htmx.on('htmx:afterSwap', initialiseNtfyForm);
|
|
|
|
|
|
function initialiseCategoryPickers() {
|
|
document.querySelectorAll("[data-category-picker]").forEach((picker) => {
|
|
if (picker.dataset.ready) return;
|
|
picker.dataset.ready = "true";
|
|
|
|
const input = picker.querySelector("[data-category-input]");
|
|
const clearButton = picker.querySelector("[data-category-clear]");
|
|
const suggestions = picker.querySelector("[role=listbox]");
|
|
const suggestionUrl = input?.dataset.suggestionsUrl;
|
|
if (!input || !clearButton || !suggestions || !suggestionUrl) return;
|
|
|
|
let activeIndex = -1;
|
|
let requestSequence = 0;
|
|
|
|
const options = () => Array.from(suggestions.querySelectorAll("[role=option]"));
|
|
const updateClearButton = () => { clearButton.hidden = !input.value; };
|
|
const closeSuggestions = () => {
|
|
activeIndex = -1;
|
|
suggestions.hidden = true;
|
|
suggestions.replaceChildren();
|
|
input.setAttribute("aria-expanded", "false");
|
|
input.removeAttribute("aria-activedescendant");
|
|
};
|
|
const setActiveOption = (index) => {
|
|
const availableOptions = options();
|
|
if (!availableOptions.length) return;
|
|
activeIndex = (index + availableOptions.length) % availableOptions.length;
|
|
availableOptions.forEach((option, optionIndex) => {
|
|
option.setAttribute("aria-selected", String(optionIndex === activeIndex));
|
|
});
|
|
const activeOption = availableOptions[activeIndex];
|
|
input.setAttribute("aria-activedescendant", activeOption.id);
|
|
activeOption.scrollIntoView({ block: "nearest" });
|
|
};
|
|
const choose = (category) => {
|
|
input.value = category;
|
|
updateClearButton();
|
|
closeSuggestions();
|
|
input.focus();
|
|
};
|
|
const showSuggestions = (categories) => {
|
|
suggestions.replaceChildren();
|
|
activeIndex = -1;
|
|
input.removeAttribute("aria-activedescendant");
|
|
categories.forEach((category, index) => {
|
|
const option = document.createElement("li");
|
|
option.id = input.id + "-option-" + index;
|
|
option.setAttribute("role", "option");
|
|
option.setAttribute("aria-selected", "false");
|
|
option.dataset.categoryValue = category;
|
|
option.textContent = category;
|
|
suggestions.append(option);
|
|
});
|
|
suggestions.hidden = categories.length === 0;
|
|
input.setAttribute("aria-expanded", String(categories.length > 0));
|
|
};
|
|
const loadSuggestions = async () => {
|
|
const requestId = ++requestSequence;
|
|
const url = new URL(suggestionUrl, window.location.origin);
|
|
url.searchParams.set("q", input.value);
|
|
try {
|
|
const response = await fetch(url, { headers: { Accept: "application/json" } });
|
|
if (!response.ok || requestId !== requestSequence) return;
|
|
const payload = await response.json();
|
|
showSuggestions(payload.categories || []);
|
|
} catch {
|
|
if (requestId === requestSequence) closeSuggestions();
|
|
}
|
|
};
|
|
|
|
input.addEventListener("input", () => {
|
|
updateClearButton();
|
|
loadSuggestions();
|
|
});
|
|
input.addEventListener("focus", () => {
|
|
if (input.value) loadSuggestions();
|
|
});
|
|
input.addEventListener("keydown", (event) => {
|
|
const availableOptions = options();
|
|
if (event.key === "ArrowDown") {
|
|
event.preventDefault();
|
|
if (suggestions.hidden) loadSuggestions();
|
|
else setActiveOption(activeIndex + 1);
|
|
} else if (event.key === "ArrowUp" && !suggestions.hidden) {
|
|
event.preventDefault();
|
|
setActiveOption(activeIndex - 1);
|
|
} else if (event.key === "Enter" && activeIndex >= 0 && availableOptions[activeIndex]) {
|
|
event.preventDefault();
|
|
choose(availableOptions[activeIndex].dataset.categoryValue);
|
|
} else if (event.key === "Escape") {
|
|
closeSuggestions();
|
|
}
|
|
});
|
|
suggestions.addEventListener("click", (event) => {
|
|
const option = event.target.closest("[role=option]");
|
|
if (option) choose(option.dataset.categoryValue);
|
|
});
|
|
clearButton.addEventListener("click", () => {
|
|
input.value = "";
|
|
updateClearButton();
|
|
closeSuggestions();
|
|
input.focus();
|
|
});
|
|
});
|
|
}
|
|
|
|
document.addEventListener("DOMContentLoaded", initialiseCategoryPickers);
|
|
htmx.on("htmx:afterSwap", initialiseCategoryPickers);
|