first commit

This commit is contained in:
Joren de Graaf
2026-09-30 17:25:25 +02:00
commit 6baa19f11b
4271 changed files with 716371 additions and 0 deletions
+197
View File
@@ -0,0 +1,197 @@
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');
});
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 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);