latest changes

This commit is contained in:
Joren de Graaf
2026-10-15 20:38:02 +02:00
parent 21f3cf09b7
commit 109ca6ef2a
45 changed files with 1463 additions and 22 deletions
View File
+6
View File
@@ -0,0 +1,6 @@
from django.apps import AppConfig
class DashboardConfig(AppConfig):
default_auto_field = "django.db.models.BigAutoField"
name = "dashboard"
+114
View File
@@ -0,0 +1,114 @@
"""Buienradar's documented coordinate-based two-hour rain forecast feed."""
import hashlib
import re
from datetime import datetime, time as clock_time, timedelta, timezone
from urllib.parse import urlencode
from urllib.request import Request, urlopen
from zoneinfo import ZoneInfo
from django.core.cache import caches
from .weather import coordinates
ENDPOINT = "https://gps.buienradar.nl/getrr.php"
FRESH_SECONDS = 300
STALE_SECONDS = 900
AMSTERDAM = ZoneInfo("Europe/Amsterdam")
LINE = re.compile(r"^(\d{3})\|([01]\d|2[0-3]):([0-5]\d)$")
class RainUnavailable(Exception):
pass
def rain_label(intensity):
# UI categories; Buienradar supplies the raw rain code, not these labels.
if intensity < 0.1:
return "None"
if intensity < 2.5:
return "Light"
if intensity < 10:
return "Moderate"
return "Heavy"
def parse_forecast(text, now=None):
now = now or datetime.now(AMSTERDAM)
if now.tzinfo is None:
raise ValueError("Timezone-aware now required")
rows = [line.strip() for line in text.splitlines() if line.strip()]
if not 1 <= len(rows) <= 36:
raise RainUnavailable("Rain forecast format is unavailable")
points = []
previous = None
base_date = now.date()
day_offset = 0
for row in rows:
match = LINE.fullmatch(row)
if not match:
raise RainUnavailable("Rain forecast format is unavailable")
code, hour, minute = map(int, match.groups())
if code > 255:
raise RainUnavailable("Rain forecast format is unavailable")
time = datetime.combine(base_date + timedelta(days=day_offset), clock_time(hour, minute), AMSTERDAM)
if previous is None:
if time - now > timedelta(hours=12):
time -= timedelta(days=1)
day_offset -= 1
elif now - time > timedelta(hours=12):
time += timedelta(days=1)
day_offset += 1
elif time <= previous:
day_offset += 1
time += timedelta(days=1)
if previous is not None and not timedelta(minutes=0) < time - previous <= timedelta(minutes=10):
raise RainUnavailable("Rain forecast timing is unavailable")
previous = time
intensity = 0 if code == 0 else 10 ** ((code - 109) / 32)
# The upper end of the 0-255 scale is saturated; an exact rate would imply false precision.
points.append({"time": time.isoformat(), "mm_per_hour": round(intensity, 2) if intensity < 100 else None, "label": rain_label(intensity)})
return points
def request_rain(lat, lon):
url = f"{ENDPOINT}?{urlencode({'lat': lat, 'lon': lon})}"
request = Request(url, headers={"User-Agent": "CommonGroundDashboard/1.0"})
with urlopen(request, timeout=8) as response:
if response.status != 200:
raise RainUnavailable("Rain service is temporarily unavailable")
body = response.read(10000)
try:
points = parse_forecast(body.decode("ascii"))
except UnicodeDecodeError as exc:
raise RainUnavailable("Rain forecast format is unavailable") from exc
return {"points": points, "fetched_at": datetime.now(timezone.utc).isoformat()}
def get_rain(latitude, longitude):
lat, lon = coordinates(latitude, longitude)
# The documented feed covers the Netherlands; avoid meaningless global requests.
if not (50.5 <= lat <= 53.7 and 3.0 <= lon <= 7.3):
raise ValueError("Buienradar's local rain forecast is available for locations in the Netherlands")
key = hashlib.sha256(f"buienradar:v1:{lat:.2f}:{lon:.2f}".encode()).hexdigest()
cache = caches["weather"]
fresh = cache.get(f"fresh:{key}")
if fresh is not None:
return {**fresh, "stale": False}
stale = cache.get(f"stale:{key}")
lock = f"lock:{key}"
if not cache.add(lock, True, timeout=20):
if stale is not None:
return {**stale, "stale": True}
raise RainUnavailable("Rain forecast is being refreshed. Try again shortly")
try:
payload = request_rain(lat, lon)
cache.set(f"fresh:{key}", payload, timeout=FRESH_SECONDS)
cache.set(f"stale:{key}", payload, timeout=STALE_SECONDS)
return {**payload, "stale": False}
except (OSError, RainUnavailable) as exc:
if stale is not None:
return {**stale, "stale": True}
raise RainUnavailable("Rain service is temporarily unavailable") from exc
finally:
cache.delete(lock)
+19
View File
@@ -0,0 +1,19 @@
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [migrations.swappable_dependency(settings.AUTH_USER_MODEL)]
operations = [
migrations.CreateModel(name="DashboardLayout", fields=[
("id", models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name="ID")),
("page", models.SlugField(max_length=80)),
("revision", models.PositiveIntegerField(default=0)),
("widgets", models.JSONField(default=list)),
("updated_at", models.DateTimeField(auto_now=True)),
("user", models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL)),
]),
migrations.AddConstraint(model_name="dashboardlayout", constraint=models.UniqueConstraint(fields=("user", "page"), name="unique_dashboard_user_page")),
]
View File
+13
View File
@@ -0,0 +1,13 @@
from django.conf import settings
from django.db import models
class DashboardLayout(models.Model):
user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
page = models.SlugField(max_length=80)
revision = models.PositiveIntegerField(default=0)
widgets = models.JSONField(default=list)
updated_at = models.DateTimeField(auto_now=True)
class Meta:
constraints = [models.UniqueConstraint(fields=["user", "page"], name="unique_dashboard_user_page")]
+24
View File
@@ -0,0 +1,24 @@
from dataclasses import dataclass
@dataclass(frozen=True)
class WidgetType:
id: str
title: str
description: str
icon: str
template: str
default_span: int = 1
multiple: bool = False
settings_keys: tuple = ()
WIDGETS = {
widget.id: widget for widget in (
WidgetType("welcome", "Welcome", "A starting point for your space", "bi-sun", "dashboard/widgets/welcome.html", 2),
WidgetType("notes", "Quick notes", "A short personal note", "bi-sticky", "dashboard/widgets/notes.html", 1, True, ("text",)),
WidgetType("shortcuts", "Shortcuts", "Links to useful pages", "bi-grid", "dashboard/widgets/shortcuts.html"),
WidgetType("open_meteo", "Weather forecast", "Current weather and hourly outlook from Open-Meteo", "bi-cloud-sun", "dashboard/widgets/open_meteo.html", 2),
WidgetType("buienradar", "Rain radar", "Netherlands radar and local rain forecast from Buienradar", "bi-cloud-rain", "dashboard/widgets/buienradar.html", 2),
)
}
@@ -0,0 +1 @@
.rain-widget{color:var(--text)}.rain-location{display:flex;align-items:center;justify-content:space-between;gap:12px;flex-wrap:wrap}.rain-location strong,.rain-location small{display:block}.rain-location small{font-size:11px;color:var(--text-muted)}.rain-location>div:last-child{display:flex;gap:6px;flex-wrap:wrap}.rain-manual{margin:12px 0;color:var(--text-secondary)}.rain-manual summary{cursor:pointer;font-size:11px;font-weight:700}.rain-manual form{display:flex;gap:8px;align-items:end;flex-wrap:wrap;padding:12px 0}.rain-manual label{display:grid;gap:4px;font-size:11px;font-weight:700}.rain-manual input{max-width:130px;padding:8px;border:1px solid var(--border);border-radius:7px;background:var(--surface);color:var(--text)}.rain-manual p{font-size:11px}.rain-layout{display:grid;grid-template-columns:minmax(240px,320px) minmax(0,1fr);gap:22px;margin-top:15px;border-top:1px solid var(--border);padding-top:18px}.rain-radar-heading,.rain-forecast-heading{display:flex;align-items:baseline;justify-content:space-between;gap:8px}.rain-radar-heading h3,.rain-forecast-heading h3{font-size:13px;margin:0 0 9px}.rain-radar-heading span,.rain-forecast-heading span{font-size:10px;color:var(--text-muted)}.rain-radar-frame{min-height:230px;border:1px solid var(--border);border-radius:var(--radius-sm);overflow:hidden;background:var(--surface-secondary);display:grid;place-items:center}.rain-radar-frame img{display:block;width:100%;height:auto}.rain-radar-frame iframe{display:block;max-width:100%;border:0}.rain-radar-frame [hidden],.rain-dialog [hidden],.rain-widget [hidden]{display:none}.rain-radar-actions,.rain-step-actions{display:flex;gap:6px;flex-wrap:wrap;margin-top:9px}.rain-caveat{font-size:10px;color:var(--text-muted);margin:9px 0 0!important}.rain-status{font-size:11px;color:var(--text-secondary);margin:4px 0 12px!important}.rain-status.stale{color:var(--warning)}.rain-reading{display:grid;gap:3px;padding:12px;background:var(--surface-secondary);border-radius:var(--radius-sm)}.rain-reading strong{font-size:16px}.rain-reading span{font:800 25px Manrope,sans-serif}.rain-reading small{color:var(--text-muted)}.rain-bars{display:flex;align-items:end;gap:3px;height:85px;margin:18px 0 9px;border-bottom:1px solid var(--border)}.rain-bar{flex:1;min-width:3px;background:var(--accent);border-radius:3px 3px 0 0;opacity:.55}.rain-bar.selected{opacity:1;background:var(--positive);outline:2px solid var(--focus);outline-offset:1px}.rain-scrubber-label{display:block;font-size:11px;font-weight:700;margin-bottom:4px}.rain-widget input[type=range]{display:block;width:100%;accent-color:var(--accent);min-height:32px}.rain-step-actions .button{font-size:10px}.rain-credit{margin-top:17px;padding-top:9px;border-top:1px solid var(--border);font-size:10px;color:var(--text-muted)}.rain-credit a{text-decoration:underline;text-underline-offset:2px}.rain-dialog{border:1px solid var(--border);border-radius:var(--radius-md);background:var(--surface);color:var(--text);padding:15px;max-width:min(96vw,600px);max-height:96vh;overflow:auto}.rain-dialog::backdrop{background:rgba(0,0,0,.72)}.rain-dialog-head{display:flex;align-items:center;justify-content:space-between;gap:20px;margin-bottom:10px}.rain-dialog img{display:block;width:min(100%,500px);height:auto}.rain-dialog iframe{display:block;max-width:100%;border:0;margin:auto}@media(max-width:900px){.rain-layout{grid-template-columns:1fr}.rain-radar-frame{max-width:360px}.rain-radar-frame img{max-width:360px}.rain-radar-frame iframe{max-width:256px}}@media(max-width:760px){.rain-widget .button{min-height:44px}.rain-dialog{width:100vw;height:100dvh;max-width:100vw;max-height:100dvh;border-radius:0;margin:0}.rain-radar-frame{max-width:100%}}
+124
View File
@@ -0,0 +1,124 @@
(() => {
const gadget = 'https://gadgets.buienradar.nl/gadget/radarfivedays';
const csrf = () => decodeURIComponent(document.cookie.match(/(?:^|; )csrftoken=([^;]+)/)?.[1] || '');
const time = iso => new Intl.DateTimeFormat(undefined, { timeZone: 'Europe/Amsterdam', weekday: 'short', hour: '2-digit', minute: '2-digit' }).format(new Date(iso));
function mount(card) {
const root = card.querySelector('.rain-widget');
if (!root) return () => {};
const controller = new AbortController();
const status = root.querySelector('[data-rain-status]');
const content = root.querySelector('[data-rain-content]');
const slider = root.querySelector('[data-rain-slider]');
const bars = root.querySelector('[data-rain-bars]');
const play = root.querySelector('[data-rain-play]');
const image = root.querySelector('[data-rain-image]');
const animation = root.querySelector('[data-rain-animation]');
const dialog = root.querySelector('[data-rain-dialog]');
const dialogImage = root.querySelector('[data-rain-dialog-image]');
const dialogAnimation = root.querySelector('[data-rain-dialog-animation]');
let request = null;
let latest = null;
let playing = false;
let lastFocus = null;
function setPlaying(next) {
playing = next;
play.textContent = next ? 'Pause animation' : 'Play animation';
play.setAttribute('aria-pressed', String(next));
image.hidden = next; animation.hidden = !next;
dialogImage.hidden = next; dialogAnimation.hidden = !next;
if (next) {
animation.src = gadget;
if (dialog.open) dialogAnimation.src = gadget;
} else {
animation.removeAttribute('src');
dialogAnimation.removeAttribute('src');
}
}
function select(index) {
if (!latest?.points?.length) return;
index = Math.max(0, Math.min(latest.points.length - 1, Number(index)));
slider.value = String(index);
const point = latest.points[index];
const at = time(point.time);
const description = point.label === 'None' ? 'No rain' : `${point.label} rain`;
root.querySelector('[data-rain-class]').textContent = description;
const amount = point.mm_per_hour == null ? 'Very heavy · rate above chart scale' : `${Number(point.mm_per_hour).toFixed(2)} mm/h`;
root.querySelector('[data-rain-amount]').textContent = amount;
root.querySelector('[data-rain-time]').textContent = `${at} · forecast`;
slider.setAttribute('aria-valuetext', `${at}, ${description.toLowerCase()}, ${point.mm_per_hour == null ? 'rate above chart scale' : `${Number(point.mm_per_hour).toFixed(2)} millimetres per hour`}, forecast`);
bars.querySelectorAll('.rain-bar').forEach((bar, position) => bar.classList.toggle('selected', position === index));
root.querySelector('[data-rain-prev]').disabled = index === 0;
root.querySelector('[data-rain-next]').disabled = index === latest.points.length - 1;
}
function render(data) {
latest = data;
bars.replaceChildren();
const points = data.points || [];
if (!points.length) throw new Error('Rain forecast has no time points');
const peak = Math.max(2.5, ...points.map(point => point.mm_per_hour == null ? 100 : Number(point.mm_per_hour) || 0));
points.forEach(point => {
const bar = document.createElement('span');
bar.className = 'rain-bar';
bar.style.height = `${Math.max(3, Math.min(100, (point.mm_per_hour == null ? 100 : Number(point.mm_per_hour)) / peak * 100))}%`;
bars.append(bar);
});
slider.max = String(points.length - 1);
content.hidden = false;
select(Math.min(Number(slider.value), points.length - 1));
root.querySelector('[data-rain-updated]').textContent = `Forecast fetched ${new Date(data.fetched_at).toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' })}`;
status.textContent = data.stale ? 'Showing an older rain forecast. Live refresh is unavailable.' : 'Rain forecast ready';
status.classList.toggle('stale', data.stale);
}
async function load() {
request?.abort();
request = new AbortController();
const location = window.DashboardLocation.get();
root.querySelector('[data-rain-location]').textContent = location.name;
status.textContent = latest ? 'Refreshing rain forecast…' : 'Loading rain forecast…';
try {
const response = await fetch(root.dataset.rainUrl, { method: 'POST', credentials: 'same-origin', headers: { 'Content-Type': 'application/json', 'X-CSRFToken': csrf() }, body: JSON.stringify(location), signal: request.signal });
const data = await response.json();
if (!response.ok) throw new Error(data.error || 'Rain forecast unavailable');
render(data);
} catch (error) {
if (error.name === 'AbortError') return;
status.textContent = `${error.message}. ${latest ? 'Showing the last loaded forecast.' : 'Try again later.'}`;
status.classList.add('stale');
content.hidden = !latest;
}
}
play.addEventListener('click', () => setPlaying(!playing), { signal: controller.signal });
root.querySelector('[data-rain-fullscreen]').addEventListener('click', () => {
lastFocus = document.activeElement;
if (typeof dialog.showModal === 'function') {
dialog.showModal();
if (playing) dialogAnimation.src = gadget;
root.querySelector('[data-rain-close]').focus();
} else {
window.open('https://www.buienradar.nl/', '_blank', 'noopener,noreferrer');
}
}, { signal: controller.signal });
function closeDialog() { dialog.close(); dialogAnimation.removeAttribute('src'); lastFocus?.focus(); }
root.querySelector('[data-rain-close]').addEventListener('click', closeDialog, { signal: controller.signal });
dialog.addEventListener('close', () => { dialogAnimation.removeAttribute('src'); lastFocus?.focus(); }, { signal: controller.signal });
dialog.addEventListener('click', event => { if (event.target === dialog) closeDialog(); }, { signal: controller.signal });
slider.addEventListener('input', () => select(slider.value), { signal: controller.signal });
root.querySelector('[data-rain-prev]').addEventListener('click', () => select(Number(slider.value) - 1), { signal: controller.signal });
root.querySelector('[data-rain-next]').addEventListener('click', () => select(Number(slider.value) + 1), { signal: controller.signal });
root.querySelector('[data-rain-geolocate]').addEventListener('click', async () => {
status.textContent = 'Requesting browser location…';
try { await window.DashboardLocation.locate(); } catch (error) { status.textContent = error.message; }
}, { signal: controller.signal });
root.querySelector('[data-rain-manual]').addEventListener('submit', event => {
event.preventDefault();
try { window.DashboardLocation.set(Object.fromEntries(new FormData(event.target))); } catch (error) { status.textContent = error.message; }
}, { signal: controller.signal });
root.querySelector('[data-rain-refresh]').addEventListener('click', load, { signal: controller.signal });
image.addEventListener('error', () => { image.alt = 'Radar image unavailable. Use the Buienradar link below.'; }, { signal: controller.signal });
const unsubscribe = window.DashboardLocation.subscribe(load);
const timer = setInterval(load, 300000);
load();
return () => { controller.abort(); request?.abort(); clearInterval(timer); unsubscribe(); setPlaying(false); if (dialog.open) dialog.close(); };
}
window.DashboardBuienradar = { mount };
})();
File diff suppressed because one or more lines are too long
+219
View File
@@ -0,0 +1,219 @@
(() => {
const grid = document.querySelector('#widget-grid');
if (!grid) return;
const editButton = document.querySelector('#edit-layout');
const resetButton = document.querySelector('#reset-layout');
const status = document.querySelector('#layout-status');
const catalogue = document.querySelector('#widget-catalogue');
const backdrop = document.querySelector('#catalogue-backdrop');
const search = document.querySelector('#widget-search');
let editing = false;
let dirty = false;
let dragged = null;
let catalogueDraggedType = null;
let dropBefore = null;
let dropAfter = null;
let saving = false;
let previousFocus = null;
const lifecycle = new WeakMap();
const indicator = document.createElement('div');
indicator.className = 'widget-drop-indicator';
indicator.setAttribute('aria-hidden', 'true');
grid.append(indicator);
const icons = { welcome: 'bi-sun', notes: 'bi-sticky', shortcuts: 'bi-grid', open_meteo: 'bi-cloud-sun', buienradar: 'bi-cloud-rain' };
const titles = { welcome: 'Welcome', notes: 'Quick notes', shortcuts: 'Shortcuts', open_meteo: 'Weather forecast', buienradar: 'Rain radar' };
const spans = { welcome: 2, notes: 1, shortcuts: 1, open_meteo: 2, buienradar: 2 };
const multiple = { welcome: false, notes: true, shortcuts: false, open_meteo: false, buienradar: false };
function setStatus(message, error = false) {
status.textContent = message;
status.classList.toggle('error', error);
}
function cards() { return [...grid.querySelectorAll(':scope > .widget-card')]; }
function updateEmpty() { document.querySelector('#empty-layout').hidden = cards().length > 0; }
function markDirty() { dirty = true; setStatus('Unsaved layout changes'); updateEmpty(); }
function mount(root) {
const targets = root.matches?.('.widget-card') ? [root] : [...root.querySelectorAll('.widget-card')];
targets.forEach(card => {
if (lifecycle.has(card)) return;
const controller = new AbortController();
if (card.dataset.widgetType === 'notes') {
card.querySelector('[data-setting="text"]')?.addEventListener('input', event => {
card.querySelector('.note-preview').textContent = event.target.value || 'Add a note in widget settings.';
markDirty();
}, { signal: controller.signal });
}
const widgetCleanup = card.dataset.widgetType === 'open_meteo' ? window.DashboardOpenMeteo?.mount(card) : card.dataset.widgetType === 'buienradar' ? window.DashboardBuienradar?.mount(card) : null;
lifecycle.set(card, () => { controller.abort(); widgetCleanup?.(); });
card.dispatchEvent(new CustomEvent('dashboard:widget-mounted', { bubbles: true }));
});
}
function unmount(root) {
const targets = root.matches?.('.widget-card') ? [root] : [...root.querySelectorAll('.widget-card')];
targets.forEach(card => { lifecycle.get(card)?.(); lifecycle.delete(card); card.dispatchEvent(new CustomEvent('dashboard:widget-unmounted', { bubbles: true })); });
}
document.addEventListener('htmx:beforeCleanupElement', event => unmount(event.detail.elt));
document.addEventListener('htmx:afterSwap', event => mount(event.detail.elt));
document.addEventListener('dashboard:mount', event => mount(event.target));
document.addEventListener('dashboard:unmount', event => unmount(event.target));
function clearDrop() {
dropBefore = dropAfter = null;
indicator.classList.remove('visible', 'invalid');
cards().forEach(card => card.classList.remove('drop-target'));
}
function showDrop(target, before, type) {
const valid = !type || multiple[type] || !cards().some(card => card.dataset.widgetType === type);
const rect = target?.getBoundingClientRect() || grid.getBoundingClientRect();
const parent = grid.getBoundingClientRect();
const top = target ? rect.top - parent.top + (before ? 0 : rect.height) : grid.scrollHeight;
indicator.style.top = `${top}px`;
indicator.style.left = `${target ? rect.left - parent.left : 0}px`;
indicator.style.width = `${target ? rect.width : grid.clientWidth}px`;
indicator.textContent = valid ? (target ? `Insert ${before ? 'before' : 'after'} ${target.querySelector('h2')?.textContent}` : 'Add at end') : 'Already on this page';
indicator.classList.add('visible');
indicator.classList.toggle('invalid', !valid);
cards().forEach(card => card.classList.toggle('drop-target', card === target && valid));
dropBefore = valid && before ? target : null;
dropAfter = valid && !before ? target : null;
if (!valid) { dropBefore = dropAfter = null; }
return valid;
}
function insertAtDrop(card) {
if (dropBefore) grid.insertBefore(card, dropBefore);
else if (dropAfter) grid.insertBefore(card, dropAfter.nextElementSibling);
else grid.insertBefore(card, indicator);
clearDrop();
}
function openCatalogue() {
previousFocus = document.activeElement;
catalogue.removeAttribute('inert');
catalogue.setAttribute('aria-hidden', 'false');
catalogue.classList.add('open');
backdrop.hidden = false;
document.querySelector('#catalogue-toggle').setAttribute('aria-expanded', 'true');
search.focus();
}
function closeCatalogue() {
catalogue.classList.remove('open');
catalogue.setAttribute('aria-hidden', 'true');
catalogue.setAttribute('inert', '');
backdrop.hidden = true;
document.querySelector('#catalogue-toggle').setAttribute('aria-expanded', 'false');
previousFocus?.focus();
}
function widgetMarkup(type) {
const icon = icons[type], title = titles[type];
const body = type === 'open_meteo' ? document.querySelector('#open-meteo-widget-template').innerHTML : type === 'buienradar' ? document.querySelector('#buienradar-widget-template').innerHTML : type === 'notes' ? '<p class="note-preview">Add a note in widget settings.</p>' : type === 'welcome' ? '<p>Welcome to your dashboard. Arrange the cards to fit your day.</p><p class="widget-muted">This is a placeholder widget. Live data widgets will be added separately.</p>' : '<nav class="widget-shortcuts" aria-label="Quick links"><a href="/projects/">Projects ↗</a><a href="/examples/today/">Design examples ↗</a></nav>';
return `<header class="widget-card-head"><div><i class="bi ${icon}" aria-hidden="true"></i><h2>${title}</h2></div><div class="widget-controls"><button type="button" data-move="left" aria-label="Move ${title} earlier" title="Move earlier">←</button><button type="button" data-move="right" aria-label="Move ${title} later" title="Move later">→</button><button type="button" data-span-toggle aria-label="Resize ${title}" title="Resize">↔</button><button type="button" data-settings-toggle aria-label="Settings for ${title}" title="Settings"><i class="bi bi-sliders"></i></button><button type="button" data-remove aria-label="Remove ${title}" title="Remove"><i class="bi bi-x-lg"></i></button><span class="drag-handle" draggable="true" aria-hidden="true"><i class="bi bi-grip-vertical"></i></span></div></header><div class="widget-body">${body}</div><div class="widget-settings" hidden>${type === 'notes' ? '<label>Note text <textarea data-setting="text" maxlength="1000"></textarea></label>' : '<p>No settings for this widget.</p>'}</div>`;
}
function add(type, before = null) {
if (!editing || !titles[type]) return;
if (!multiple[type] && cards().some(card => card.dataset.widgetType === type)) {
setStatus(`${titles[type]} is already on this page.`, true); return;
}
const card = document.createElement('article');
card.className = 'widget-card content-card';
card.dataset.widgetPlatform = 'bottom';
card.dataset.instanceId = crypto.randomUUID();
card.dataset.widgetType = type;
card.dataset.span = String(spans[type]);
card.innerHTML = widgetMarkup(type);
grid.insertBefore(card, before || indicator);
mount(card);
markDirty();
card.querySelector('[data-move]').focus();
}
function enterEdit() {
editing = true; grid.classList.add('editing');
resetButton.hidden = false;
editButton.textContent = 'Done';
setStatus('Editing layout. Drag cards or use their move controls.');
}
async function finishEdit() {
if (saving) return;
if (dirty) {
saving = true;
editButton.disabled = true;
setStatus('Saving layout…');
const widgets = cards().map((card, order) => ({
id: card.dataset.instanceId, type: card.dataset.widgetType, order,
span: Number(card.dataset.span), visible: true,
settings: card.dataset.widgetType === 'notes' ? { text: card.querySelector('textarea')?.value || '' } : {},
}));
try {
const response = await fetch(grid.dataset.saveUrl, { method: 'PUT', credentials: 'same-origin', headers: { 'Content-Type': 'application/json', 'X-CSRFToken': decodeURIComponent(document.cookie.match(/(?:^|; )csrftoken=([^;]+)/)?.[1] || '') }, body: JSON.stringify({ revision: Number(grid.dataset.revision), widgets }) });
const result = await response.json();
if (!response.ok) throw new Error(result.error || 'Could not save layout');
grid.dataset.revision = result.revision;
dirty = false;
} catch (error) { setStatus(`${error.message} Your edits are still here. Try Done again.`, true); return; }
finally { saving = false; editButton.disabled = false; }
}
editing = false; grid.classList.remove('editing', 'dragging');
resetButton.hidden = true;
clearDrop();
cards().forEach(card => { card.querySelector('.widget-settings').hidden = true; });
editButton.textContent = 'Edit layout';
setStatus('Layout saved');
closeCatalogueIfOpen();
}
function closeCatalogueIfOpen() { if (catalogue.classList.contains('open')) closeCatalogue(); }
editButton.addEventListener('click', () => editing ? finishEdit() : enterEdit());
resetButton.addEventListener('click', () => {
if (!confirm('Reset this page to its default widgets? This replaces your layout.')) return;
unmount(grid);
cards().forEach(card => card.remove());
add('welcome'); add('shortcuts');
setStatus('Default layout ready. Select Done to save.');
});
document.querySelector('#catalogue-toggle').addEventListener('click', openCatalogue);
document.querySelector('#catalogue-close').addEventListener('click', closeCatalogue);
backdrop.addEventListener('click', closeCatalogue);
document.addEventListener('keydown', event => {
if (event.key === 'Escape' && catalogue.classList.contains('open')) closeCatalogue();
if (event.key === 'Tab' && catalogue.classList.contains('open')) {
const focusable = [...catalogue.querySelectorAll('button:not([disabled]), input')].filter(el => !el.closest('[hidden]'));
const first = focusable[0], last = focusable.at(-1);
if (event.shiftKey && document.activeElement === first) { event.preventDefault(); last.focus(); }
else if (!event.shiftKey && document.activeElement === last) { event.preventDefault(); first.focus(); }
}
});
search.addEventListener('input', () => {
const query = search.value.trim().toLowerCase();
catalogue.querySelectorAll('.catalogue-entry').forEach(entry => { entry.hidden = !(entry.dataset.title.includes(query) || entry.dataset.description.includes(query)); });
});
catalogue.addEventListener('click', event => { const button = event.target.closest('[data-add]'); if (button) { if (!editing) enterEdit(); add(button.dataset.add); closeCatalogue(); } });
grid.addEventListener('click', event => {
const button = event.target.closest('button');
const card = button?.closest('.widget-card');
if (!editing || !card) return;
if (button.hasAttribute('data-remove')) { unmount(card); card.remove(); markDirty(); setStatus(`${card.querySelector('h2').textContent} removed. Unsaved layout changes.`); editButton.focus(); }
else if (button.hasAttribute('data-span-toggle')) { card.dataset.span = card.dataset.span === '2' ? '1' : '2'; markDirty(); setStatus(`${card.querySelector('h2').textContent} now spans ${card.dataset.span} ${card.dataset.span === '1' ? 'column' : 'columns'}. Unsaved layout changes.`); }
else if (button.hasAttribute('data-settings-toggle')) { const panel = card.querySelector('.widget-settings'); panel.hidden = !panel.hidden; if (!panel.hidden) panel.querySelector('textarea')?.focus(); }
else if (button.hasAttribute('data-move')) { const list = cards(); const index = list.indexOf(card); const next = index + (button.dataset.move === 'left' ? -1 : 1); if (next >= 0 && next < list.length) { grid.insertBefore(card, button.dataset.move === 'left' ? list[next] : list[next].nextSibling); markDirty(); setStatus(`${card.querySelector('h2').textContent} moved to position ${next + 1} of ${list.length}. Unsaved layout changes.`); button.focus(); } }
});
grid.addEventListener('dragstart', event => { if (!editing || !event.target.closest('.drag-handle')) { event.preventDefault(); return; } dragged = event.target.closest('.widget-card'); grid.classList.add('dragging'); event.dataTransfer.effectAllowed = 'move'; event.dataTransfer.setData('text/plain', dragged.dataset.instanceId); });
grid.addEventListener('dragover', event => {
if (!editing || (!dragged && !event.dataTransfer.types.includes('application/widget-type'))) return;
event.preventDefault();
const target = event.target.closest('.widget-card');
const type = catalogueDraggedType;
const before = target ? event.clientY < target.getBoundingClientRect().top + target.getBoundingClientRect().height / 2 : false;
showDrop(target, before, type);
});
grid.addEventListener('drop', event => {
if (!editing) return;
const type = catalogueDraggedType || event.dataTransfer.getData('application/widget-type');
if (!dragged && !type) return;
event.preventDefault();
if (type) { if (!indicator.classList.contains('invalid')) { const before = dropBefore; const after = dropAfter; clearDrop(); add(type, before || after?.nextElementSibling || null); } }
else if (dragged) { insertAtDrop(dragged); markDirty(); setStatus(`${dragged.querySelector('h2').textContent} moved to position ${cards().indexOf(dragged) + 1}. Unsaved layout changes.`); }
dragged = null; catalogueDraggedType = null; grid.classList.remove('dragging'); closeCatalogueIfOpen();
});
grid.addEventListener('dragleave', event => { if (!grid.contains(event.relatedTarget)) clearDrop(); });
grid.addEventListener('dragend', () => { dragged = null; grid.classList.remove('dragging'); clearDrop(); });
catalogue.addEventListener('dragstart', event => { const entry = event.target.closest('.catalogue-entry'); if (entry) { if (!editing) enterEdit(); catalogueDraggedType = entry.dataset.widgetType; event.dataTransfer.setData('application/widget-type', catalogueDraggedType); backdrop.hidden = true; } });
catalogue.addEventListener('dragend', () => { catalogueDraggedType = null; clearDrop(); if (catalogue.classList.contains('open')) backdrop.hidden = false; });
mount(grid);
updateEmpty();
})();
+26
View File
@@ -0,0 +1,26 @@
(() => {
let location = { latitude: 52.96, longitude: 5.92, name: 'Heerenveen' };
let permissionDenied = false;
const listeners = new Set();
function set(next) {
const latitude = Number(next.latitude), longitude = Number(next.longitude);
if (!Number.isFinite(latitude) || !Number.isFinite(longitude) || Math.abs(latitude) > 90 || Math.abs(longitude) > 180) throw new Error('Choose valid coordinates.');
location = { latitude: Math.round(latitude * 100) / 100, longitude: Math.round(longitude * 100) / 100, name: next.name || 'Chosen location' };
listeners.forEach(listener => listener({ ...location }));
}
function locate() {
if (permissionDenied) return Promise.reject(new Error('Location permission was denied. Enter coordinates manually or change browser permissions.'));
if (!navigator.geolocation) return Promise.reject(new Error('Browser location is unavailable. Enter coordinates manually.'));
return new Promise((resolve, reject) => navigator.geolocation.getCurrentPosition(position => {
set({ latitude: position.coords.latitude, longitude: position.coords.longitude, name: 'Your approximate location' });
resolve({ ...location });
}, error => {
if (error.code === 1) permissionDenied = true;
reject(new Error(error.code === 1 ? 'Location permission was denied. Enter coordinates manually or change browser permissions.' : 'Could not determine your location. Enter coordinates manually.'));
}, { enableHighAccuracy: false, timeout: 10000, maximumAge: 900000 }));
}
window.DashboardLocation = {
get: () => ({ ...location }), set, locate,
subscribe(listener) { listeners.add(listener); return () => listeners.delete(listener); },
};
})();
@@ -0,0 +1 @@
.weather-widget{color:var(--text)}.weather-location{display:flex;align-items:center;justify-content:space-between;gap:14px;flex-wrap:wrap}.weather-location>div:last-child{display:flex;gap:6px;flex-wrap:wrap}.weather-location strong,.weather-location small{display:block}.weather-location small{color:var(--text-muted);font-size:11px}.weather-manual{margin:12px 0;color:var(--text-secondary)}.weather-manual summary{cursor:pointer;font-weight:700;font-size:11px}.weather-manual form{display:flex;gap:8px;align-items:end;flex-wrap:wrap;padding:12px 0}.weather-manual label{display:grid;gap:4px;font-size:11px;font-weight:700}.weather-manual input{max-width:130px;padding:8px;border:1px solid var(--border);border-radius:7px;background:var(--surface);color:var(--text)}.weather-manual p{font-size:11px}.weather-status{margin:12px 0!important;font-size:11px;color:var(--text-secondary)}.weather-status.stale{color:var(--warning)}.weather-current{display:flex;justify-content:space-between;gap:20px;flex-wrap:wrap;border-top:1px solid var(--border);padding:20px 0}.weather-current>div:first-child{display:grid;gap:1px}.weather-temperature{font:800 clamp(35px,5vw,56px)/1.1 Manrope,sans-serif;color:var(--text)}.weather-current strong{font-size:14px}.weather-current small{color:var(--text-muted)}.weather-current dl,.weather-summary dl{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:8px 18px;margin:0}.weather-current dl{min-width:min(100%,290px)}.weather-current dt,.weather-summary dt{font-size:10px;color:var(--text-muted);font-weight:700}.weather-current dd,.weather-summary dd{margin:0;font-size:12px;font-weight:700}.weather-summary{background:var(--surface-secondary);border-radius:var(--radius-sm);padding:15px}.weather-summary h3,.weather-hours-heading h3{font-size:13px;margin:0 0 10px}.weather-hours-heading{display:flex;align-items:center;justify-content:space-between;gap:10px;margin:18px 0 8px}.weather-hours-heading h3{margin:0}.weather-hours{display:flex;gap:7px;overflow-x:auto;scroll-snap-type:x proximity;padding:5px 3px 12px}.weather-hour{flex:0 0 84px;display:grid;justify-items:center;gap:3px;scroll-snap-align:start;padding:9px 5px;border:1px solid var(--border);border-radius:var(--radius-sm);background:var(--surface);color:var(--text)}.weather-hour:hover{background:var(--surface-secondary)}.weather-hour[aria-pressed=true]{border:2px solid var(--accent);background:var(--hero)}.weather-hour-icon{font-size:21px;line-height:1.2}.weather-hour small{font-size:10px;color:var(--text-secondary)}.weather-hour-detail{border-top:1px solid var(--border);padding-top:10px;font-size:11px;color:var(--text-secondary);line-height:1.7}.weather-credit{margin-top:17px;border-top:1px solid var(--border);padding-top:9px;font-size:10px;color:var(--text-muted)}.weather-credit a{text-decoration:underline;text-underline-offset:2px}.weather-widget [hidden]{display:none}@media(max-width:760px){.weather-location .button,.weather-manual .button,.weather-hour{min-height:44px}.weather-current dl,.weather-summary dl{grid-template-columns:repeat(2,minmax(0,1fr))}}@media(prefers-reduced-motion:reduce){.weather-hours{scroll-behavior:auto}}
+132
View File
@@ -0,0 +1,132 @@
(() => {
const weather = code => {
if (code === 0) return ['Clear sky', '☀'];
if ([1, 2].includes(code)) return ['Partly cloudy', '⛅'];
if (code === 3) return ['Overcast', '☁'];
if ([45, 48].includes(code)) return ['Fog', '≋'];
if ([51, 53, 55, 56, 57].includes(code)) return ['Drizzle', '☂'];
if ([61, 63, 65, 66, 67, 80, 81, 82].includes(code)) return ['Rain', '☔'];
if ([71, 73, 75, 77, 85, 86].includes(code)) return ['Snow', '❄'];
if ([95, 96, 97, 99].includes(code)) return ['Thunderstorm', '⚡'];
return ['Conditions unavailable', '○'];
};
const value = (number, unit = '', digits = 0) => number == null || !Number.isFinite(Number(number)) ? '—' : `${Number(number).toFixed(digits)}${unit}`;
const clock = timestamp => typeof timestamp === 'string' && timestamp.includes('T') ? timestamp.split('T')[1].slice(0, 5) : '—';
const day = timestamp => typeof timestamp === 'string' ? timestamp.slice(5, 10) : '';
const csrf = () => decodeURIComponent(document.cookie.match(/(?:^|; )csrftoken=([^;]+)/)?.[1] || '');
function metric(list, label, content) {
const item = document.createElement('div');
const term = document.createElement('dt'); term.textContent = label;
const definition = document.createElement('dd'); definition.textContent = content;
item.append(term, definition); list.append(item);
}
function mount(card) {
const root = card.querySelector('.weather-widget');
if (!root) return () => {};
const status = root.querySelector('[data-weather-status]');
const content = root.querySelector('[data-weather-content]');
const hours = root.querySelector('[data-hours]');
const detail = root.querySelector('[data-hour-detail]');
const toggle = root.querySelector('[data-hours-toggle]');
const controller = new AbortController();
let request = null;
let forecast = null;
let expanded = false;
let selected = 0;
function renderHour(index) {
selected = index;
const hourly = forecast.hourly;
const parts = [
`${day(hourly.time[index])} ${clock(hourly.time[index])} ${forecast.timezone}`,
weather(hourly.weather_code?.[index])[0],
`Temperature ${value(hourly.temperature_2m?.[index], '°C', 1)}`,
`Feels like ${value(hourly.apparent_temperature?.[index], '°C', 1)}`,
`Precipitation ${value(hourly.precipitation?.[index], ' mm', 1)}`,
`Chance ${value(hourly.precipitation_probability?.[index], '%')}`,
`Wind ${value(hourly.wind_speed_10m?.[index], ' km/h')}, gusts ${value(hourly.wind_gusts_10m?.[index], ' km/h')}, direction ${value(hourly.wind_direction_10m?.[index], '°')}`,
`Humidity ${value(hourly.relative_humidity_2m?.[index], '%')}`,
`Cloud ${value(hourly.cloud_cover?.[index], '%')}`,
`UV ${value(hourly.uv_index?.[index], '', 1)}`,
];
detail.textContent = parts.join(' · ');
hours.querySelectorAll('button').forEach(button => button.setAttribute('aria-pressed', String(Number(button.dataset.hour) === index)));
}
function renderHours() {
hours.replaceChildren();
const hourly = forecast.hourly;
const limit = Math.min(hourly.time.length, expanded ? 48 : 24);
for (let index = 0; index < limit; index++) {
const button = document.createElement('button');
button.type = 'button'; button.className = 'weather-hour'; button.dataset.hour = index;
button.setAttribute('aria-label', `${day(hourly.time[index])} ${clock(hourly.time[index])}, ${weather(hourly.weather_code?.[index])[0]}, ${value(hourly.temperature_2m?.[index], ' degrees Celsius')}, precipitation chance ${value(hourly.precipitation_probability?.[index], '%')}`);
const icon = document.createElement('span'); icon.className = 'weather-hour-icon'; icon.setAttribute('aria-hidden', 'true'); icon.textContent = weather(hourly.weather_code?.[index])[1];
const time = document.createElement('strong'); time.textContent = clock(hourly.time[index]);
const temp = document.createElement('span'); temp.textContent = value(hourly.temperature_2m?.[index], '°');
const rain = document.createElement('small'); rain.textContent = value(hourly.precipitation_probability?.[index], '% rain');
button.append(time, icon, temp, rain); hours.append(button);
}
if (selected >= limit) selected = 0;
if (limit) renderHour(selected);
}
function render(data) {
forecast = data;
content.hidden = false;
const current = data.current, daily = data.daily;
root.querySelector('[data-current-temp]').textContent = value(current.temperature_2m, '°C', 1);
root.querySelector('[data-current-condition]').textContent = weather(current.weather_code)[0];
root.querySelector('[data-current-feels]').textContent = `Feels like ${value(current.apparent_temperature, '°C', 1)}`;
const currentDetails = root.querySelector('[data-current-details]'); currentDetails.replaceChildren();
metric(currentDetails, 'Precipitation', value(current.precipitation, ' mm', 1));
metric(currentDetails, 'Wind', `${value(current.wind_speed_10m, ' km/h')} · ${value(current.wind_direction_10m, '°')}`);
metric(currentDetails, 'Humidity', value(current.relative_humidity_2m, '%'));
metric(currentDetails, 'Cloud cover', value(current.cloud_cover, '%'));
const summary = root.querySelector('[data-daily-summary]'); summary.replaceChildren();
const first = key => daily[key]?.[0];
metric(summary, 'High / low', `${value(first('temperature_2m_max'), '°C')} / ${value(first('temperature_2m_min'), '°C')}`);
metric(summary, 'Sunrise / sunset', `${clock(first('sunrise'))} / ${clock(first('sunset'))}`);
const daylight = first('daylight_duration');
metric(summary, 'Daylight', daylight == null ? '—' : `${Math.floor(daylight / 3600)} h ${Math.round(daylight % 3600 / 60)} m`);
metric(summary, 'Precipitation', `${value(first('precipitation_sum'), ' mm', 1)} · up to ${value(first('precipitation_probability_max'), '%')} chance`);
metric(summary, 'Peak gust / UV', `${value(first('wind_gusts_10m_max'), ' km/h')} / ${value(first('uv_index_max'), '', 1)}`);
if (Number(first('snowfall_sum')) > 0) metric(summary, 'Snowfall', value(first('snowfall_sum'), ' cm', 1));
renderHours();
root.querySelector('[data-weather-updated]').textContent = `Conditions valid ${clock(current.time)} ${data.timezone} · fetched ${new Date(data.fetched_at).toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' })}`;
status.textContent = data.stale ? 'Showing cached forecast. Live refresh is unavailable.' : 'Forecast ready';
status.classList.toggle('stale', data.stale);
}
async function load() {
request?.abort();
request = new AbortController();
const location = window.DashboardLocation.get();
root.querySelector('[data-location-name]').textContent = location.name;
status.textContent = forecast ? 'Refreshing forecast…' : 'Loading forecast…';
try {
const response = await fetch(root.dataset.weatherUrl, { method: 'POST', credentials: 'same-origin', headers: { 'Content-Type': 'application/json', 'X-CSRFToken': csrf() }, body: JSON.stringify(location), signal: request.signal });
const data = await response.json();
if (!response.ok) throw new Error(data.error || 'Forecast unavailable');
render(data);
} catch (error) {
if (error.name === 'AbortError') return;
status.textContent = `${error.message}. ${forecast ? 'Showing the last loaded forecast.' : 'Try again later.'}`;
status.classList.add('stale');
content.hidden = !forecast;
}
}
root.querySelector('[data-use-location]').addEventListener('click', async () => {
status.textContent = 'Requesting browser location…';
try { await window.DashboardLocation.locate(); } catch (error) { status.textContent = error.message; }
}, { signal: controller.signal });
root.querySelector('[data-weather-refresh]').addEventListener('click', load, { signal: controller.signal });
root.querySelector('[data-manual-location]').addEventListener('submit', event => {
event.preventDefault();
try { window.DashboardLocation.set(Object.fromEntries(new FormData(event.target))); } catch (error) { status.textContent = error.message; }
}, { signal: controller.signal });
toggle.addEventListener('click', () => { expanded = !expanded; toggle.setAttribute('aria-expanded', String(expanded)); toggle.textContent = expanded ? 'Show 24 hours' : 'Show 48 hours'; renderHours(); }, { signal: controller.signal });
hours.addEventListener('click', event => { const button = event.target.closest('button[data-hour]'); if (button) renderHour(Number(button.dataset.hour)); }, { signal: controller.signal });
const unsubscribe = window.DashboardLocation.subscribe(load);
const timer = setInterval(load, 900000);
load();
return () => { controller.abort(); request?.abort(); clearInterval(timer); unsubscribe(); };
}
window.DashboardOpenMeteo = { mount };
})();
+14
View File
@@ -0,0 +1,14 @@
{% extends 'core/base.html' %}{% load static %}{% block content %}<link rel="stylesheet" href="{% static 'dashboard/builder.css' %}"><link rel="stylesheet" href="{% static 'dashboard/open_meteo.css' %}"><link rel="stylesheet" href="{% static 'dashboard/buienradar.css' %}">
<div class="page-heading dashboard-heading"><div><div class="eyebrow"><span class="eyebrow-line"></span> YOUR WORKSPACE</div><h1>{{ title }}<span class="heading-period">.</span></h1><p>Make this space your own with a few useful widgets.</p></div><div class="dashboard-actions"><button class="button secondary" id="catalogue-toggle" type="button" aria-controls="widget-catalogue" aria-expanded="false" aria-label="Open widget catalogue"><i class="bi bi-gear"></i> Widgets</button><button class="button secondary" id="reset-layout" type="button" hidden>Reset</button><button class="button primary" id="edit-layout" type="button">Edit layout</button></div></div>
<div id="layout-status" class="layout-status" role="status" aria-live="polite">Layout saved</div>
<div class="dashboard-pages" aria-label="Dashboard pages"><a href="{% url 'dashboard:index' %}" {% if dashboard_page == 'overview' %}aria-current="page"{% endif %}>Overview</a><a href="{% url 'dashboard:page' 'personal' %}" {% if dashboard_page == 'personal' %}aria-current="page"{% endif %}>Personal</a></div>
<div id="widget-grid" class="widget-grid" data-page="{{ dashboard_page }}" data-revision="{{ layout.revision }}" data-save-url="{% url 'dashboard:layout' dashboard_page %}">
{% for instance in instances %}{% include 'dashboard/widget_card.html' %}{% endfor %}
</div>
<p id="empty-layout" class="empty-layout" {% if instances %}hidden{% endif %}>This page is empty. Choose <strong>Edit layout</strong>, then add a widget.</p>
<template id="open-meteo-widget-template">{% include 'dashboard/widgets/open_meteo.html' %}</template>
<template id="buienradar-widget-template">{% include 'dashboard/widgets/buienradar.html' %}</template>
<aside id="widget-catalogue" class="widget-catalogue" aria-label="Widget catalogue" aria-hidden="true" inert><div class="catalogue-head"><div><span class="eyebrow">BUILD YOUR PAGE</span><h2>Widgets</h2></div><button type="button" id="catalogue-close" class="button ghost" aria-label="Close widget catalogue"><i class="bi bi-x-lg"></i></button></div><label for="widget-search">Search widgets</label><input id="widget-search" type="search" placeholder="Search by name or description"><div class="catalogue-list">{% for widget in catalogue %}<div class="catalogue-entry" draggable="true" data-widget-type="{{ widget.id }}" data-title="{{ widget.title|lower }}" data-description="{{ widget.description|lower }}"><i class="bi {{ widget.icon }}" aria-hidden="true"></i><div><strong>{{ widget.title }}</strong><small>{{ widget.description }}</small></div><button type="button" class="button secondary" data-add="{{ widget.id }}">Add</button></div>{% endfor %}</div><p class="catalogue-hint">Drag onto a dashed slot, or use Add and the Move controls. Changes save when you select Done.</p></aside><div id="catalogue-backdrop" class="catalogue-backdrop" hidden></div>
{{ catalogue|length|json_script:"widget-count" }}
<script src="{% static 'dashboard/location.js' %}" defer></script><script src="{% static 'dashboard/open_meteo.js' %}" defer></script><script src="{% static 'dashboard/buienradar.js' %}" defer></script><script src="{% static 'dashboard/builder.js' %}" defer></script>
{% endblock %}
@@ -0,0 +1 @@
<article class="widget-card content-card" data-widget-platform="bottom" data-instance-id="{{ instance.id }}" data-widget-type="{{ instance.type }}" data-span="{{ instance.span }}"><header class="widget-card-head"><div><i class="bi {{ instance.kind.icon }}" aria-hidden="true"></i><h2>{{ instance.kind.title }}</h2></div><div class="widget-controls"><button type="button" data-move="left" aria-label="Move {{ instance.kind.title }} earlier" title="Move earlier">←</button><button type="button" data-move="right" aria-label="Move {{ instance.kind.title }} later" title="Move later">→</button><button type="button" data-span-toggle aria-label="Resize {{ instance.kind.title }}" title="Resize">↔</button><button type="button" data-settings-toggle aria-label="Settings for {{ instance.kind.title }}" title="Settings"><i class="bi bi-sliders"></i></button><button type="button" data-remove aria-label="Remove {{ instance.kind.title }}" title="Remove"><i class="bi bi-x-lg"></i></button><span class="drag-handle" draggable="true" aria-hidden="true"><i class="bi bi-grip-vertical"></i></span></div></header><div class="widget-body">{% include instance.kind.template %}</div><div class="widget-settings" hidden>{% if instance.type == 'notes' %}<label>Note text <textarea data-setting="text" maxlength="1000">{{ instance.settings.text|default:'' }}</textarea></label>{% else %}<p>No settings for this widget.</p>{% endif %}</div></article>
@@ -0,0 +1,8 @@
<section class="rain-widget" data-rain-url="{% url 'dashboard:buienradar' %}" aria-label="Buienradar rain radar">
<div class="rain-location"><div><strong data-rain-location>Heerenveen</strong><small data-rain-updated>Waiting for rain forecast</small></div><div><button type="button" class="button secondary" data-rain-geolocate>Use my location</button><button type="button" class="button ghost" data-rain-refresh>Refresh</button></div></div>
<details class="rain-manual"><summary>Choose coordinates manually</summary><form data-rain-manual><label>Latitude <input name="latitude" type="number" min="-90" max="90" step="any" required placeholder="52.96"></label><label>Longitude <input name="longitude" type="number" min="-180" max="180" step="any" required placeholder="5.92"></label><button class="button secondary" type="submit">Use coordinates</button></form><p>Shared with weather widgets on this page. Coordinates are not saved.</p></details>
<div class="rain-layout"><div class="rain-radar"><div class="rain-radar-heading"><h3>Netherlands radar</h3><span>Latest image</span></div><div class="rain-radar-frame"><img data-rain-image src="https://image.buienradar.nl/2.0/image/single/RadarMapRainNL?height=512&amp;width=500&amp;renderBackground=True&amp;renderBranding=True&amp;renderText=True" width="500" height="512" alt="Latest Buienradar rain radar image of the Netherlands. Location is not marked."><iframe data-rain-animation title="Buienradar official animated radar gadget" width="256" height="406" loading="lazy" hidden></iframe></div><div class="rain-radar-actions"><button type="button" class="button secondary" data-rain-play aria-pressed="false">Play animation</button><button type="button" class="button ghost" data-rain-fullscreen>Full screen</button></div><p class="rain-caveat">Animation is managed by Buienradar. Frame times and seeking are not available from this embed.</p></div>
<div class="rain-forecast"><div class="rain-forecast-heading"><h3>Rain at this location</h3><span>Forecast · next 2 hours</span></div><p class="rain-status" data-rain-status role="status" aria-live="polite">Loading rain forecast…</p><div data-rain-content hidden><div class="rain-reading"><strong data-rain-class>—</strong><span data-rain-amount>—</span><small data-rain-time>—</small></div><div class="rain-bars" data-rain-bars aria-hidden="true"></div><label class="rain-scrubber-label" for="rain-scrubber-{{ instance.id|default:'template' }}">Choose forecast time</label><input id="rain-scrubber-{{ instance.id|default:'template' }}" data-rain-slider type="range" min="0" max="0" value="0" aria-label="Forecast time"><div class="rain-step-actions"><button type="button" class="button ghost" data-rain-prev>Previous forecast time</button><button type="button" class="button ghost" data-rain-next>Next forecast time</button></div></div><p class="rain-caveat">Forecast values are separate from the radar image; their times are not synchronized.</p></div></div>
<dialog class="rain-dialog" data-rain-dialog aria-label="Buienradar full screen"><div class="rain-dialog-head"><strong>Buienradar · Netherlands</strong><button type="button" class="button secondary" data-rain-close>Close</button></div><img data-rain-dialog-image src="https://image.buienradar.nl/2.0/image/single/RadarMapRainNL?height=512&amp;width=500&amp;renderBackground=True&amp;renderBranding=True&amp;renderText=True" width="500" height="512" alt="Latest Buienradar rain radar image of the Netherlands. Location is not marked."><iframe data-rain-dialog-animation title="Buienradar official animated radar gadget in full screen" width="256" height="406" loading="lazy" hidden></iframe></dialog>
<footer class="rain-credit">Radar and precipitation data: <a href="https://www.buienradar.nl/" target="_blank" rel="noopener noreferrer">Buienradar.nl</a> · Rain intensity categories adapted for display.</footer>
</section>
@@ -0,0 +1 @@
<p class="note-preview">{{ instance.settings.text|default:'Add a note in widget settings.' }}</p>
@@ -0,0 +1,10 @@
<section class="weather-widget" data-weather-url="{% url 'dashboard:open_meteo' %}" aria-label="Open-Meteo forecast">
<div class="weather-location"><div><strong data-location-name>Heerenveen</strong><small data-weather-updated>Waiting for forecast</small></div><div><button class="button secondary" type="button" data-use-location>Use my location</button><button class="button ghost" type="button" data-weather-refresh>Refresh</button></div></div>
<details class="weather-manual"><summary>Choose coordinates manually</summary><form data-manual-location><label>Latitude <input name="latitude" type="number" min="-90" max="90" step="any" required placeholder="52.96"></label><label>Longitude <input name="longitude" type="number" min="-180" max="180" step="any" required placeholder="5.92"></label><button class="button secondary" type="submit">Use coordinates</button></form><p>Coordinates stay in this browser session and are rounded before the weather request.</p></details>
<p class="weather-status" data-weather-status role="status" aria-live="polite">Loading forecast…</p>
<div data-weather-content hidden><div class="weather-current"><div><span class="weather-temperature" data-current-temp></span><strong data-current-condition></strong><small data-current-feels></small></div><dl data-current-details></dl></div>
<div class="weather-summary"><h3>Today</h3><dl data-daily-summary></dl></div>
<div class="weather-hours-heading"><h3>Hourly forecast</h3><button class="button ghost" type="button" data-hours-toggle aria-expanded="false">Show 48 hours</button></div><div class="weather-hours" data-hours role="group" aria-label="Hourly forecast"></div><div class="weather-hour-detail" data-hour-detail aria-live="polite"></div>
</div>
<footer class="weather-credit">Weather data: <a href="https://open-meteo.com/" target="_blank" rel="noopener noreferrer">Open-Meteo</a> · Forecast data adapted for display · <a href="https://open-meteo.com/en/licence" target="_blank" rel="noopener noreferrer">CC BY 4.0</a></footer>
</section>
@@ -0,0 +1 @@
<nav class="widget-shortcuts" aria-label="Quick links"><a href="{% url 'projects:list' %}">Projects <i class="bi bi-arrow-up-right"></i></a><a href="{% url 'today' %}">Design examples <i class="bi bi-arrow-up-right"></i></a></nav>
@@ -0,0 +1 @@
<p>Welcome to your dashboard. Arrange the cards to fit your day.</p><p class="widget-muted">This is a placeholder widget. Live data widgets will be added separately.</p>
+138
View File
@@ -0,0 +1,138 @@
import json
import uuid
import hashlib
from unittest.mock import patch
from django.contrib.auth import get_user_model
from django.core.cache import caches
from datetime import datetime
from zoneinfo import ZoneInfo
from django.test import TestCase
from django.urls import reverse
from .models import DashboardLayout
from .views import validate_widgets
from .weather import ForecastUnavailable, coordinates, get_forecast
from .buienradar import RainUnavailable, get_rain, parse_forecast
class DashboardTests(TestCase):
def setUp(self):
self.one = get_user_model().objects.create_user(username="one", password="password")
self.two = get_user_model().objects.create_user(username="two", password="password")
def test_registry_rejects_duplicate_single_instance(self):
item = {"id": str(uuid.uuid4()), "type": "welcome", "span": 2, "settings": {}, "visible": True}
with self.assertRaises(ValueError):
validate_widgets([item, {**item, "id": str(uuid.uuid4())}])
def test_user_and_page_layouts_are_independent(self):
self.client.force_login(self.one)
self.client.get(reverse("dashboard:index"))
self.client.get(reverse("dashboard:page", args=["personal"]))
self.client.force_login(self.two)
self.client.get(reverse("dashboard:index"))
self.assertEqual(DashboardLayout.objects.count(), 3)
ids = [widget["id"] for layout in DashboardLayout.objects.all() for widget in layout.widgets]
self.assertEqual(len(ids), len(set(ids)))
def test_layout_update_is_scoped_to_authenticated_user(self):
self.client.force_login(self.one)
self.client.get(reverse("dashboard:index"))
original = DashboardLayout.objects.get(user=self.one, page="overview")
self.client.force_login(self.two)
response = self.client.put(
reverse("dashboard:layout", args=["overview"]),
json.dumps({"revision": 0, "widgets": []}),
content_type="application/json",
)
self.assertEqual(response.status_code, 200)
original.refresh_from_db()
self.assertEqual(original.revision, 0)
self.assertEqual(len(original.widgets), 2)
def test_reorder_persists_and_revision_conflict(self):
self.client.force_login(self.one)
self.client.get(reverse("dashboard:index"))
layout = DashboardLayout.objects.get(user=self.one, page="overview")
widgets = list(reversed(layout.widgets))
url = reverse("dashboard:layout", args=["overview"])
response = self.client.put(url, json.dumps({"revision": 0, "widgets": widgets}), content_type="application/json")
self.assertEqual(response.status_code, 200)
layout.refresh_from_db()
self.assertEqual([item["type"] for item in layout.widgets], ["shortcuts", "welcome"])
self.assertEqual(self.client.put(url, json.dumps({"revision": 0, "widgets": widgets}), content_type="application/json").status_code, 409)
def test_open_meteo_registry_and_authenticated_endpoint(self):
self.assertEqual(self.client.post(reverse("dashboard:open_meteo"), data="{}", content_type="application/json").status_code, 302)
self.client.force_login(self.one)
with patch("dashboard.views.get_forecast", return_value={"current": {}, "hourly": {}, "daily": {}, "stale": False}):
response = self.client.post(reverse("dashboard:open_meteo"), json.dumps({"latitude": 52.96, "longitude": 5.92}), content_type="application/json")
self.assertEqual(response.status_code, 200)
self.assertIn("open_meteo", __import__("dashboard.registry", fromlist=["WIDGETS"]).WIDGETS)
def test_weather_coordinate_validation_and_shared_cache(self):
with self.assertRaises(ValueError):
coordinates("nan", 5)
caches["weather"].clear()
payload = {"current": {"temperature_2m": 10}, "hourly": {"time": ["2026-10-14T12:00"]}, "daily": {}, "fetched_at": "2026-10-14T10:00:00+00:00"}
with patch("dashboard.weather.request_forecast", return_value=payload) as fetch:
first = get_forecast(52.961, 5.919)
second = get_forecast(52.96, 5.92)
self.assertFalse(first["stale"])
self.assertEqual(second["current"]["temperature_2m"], 10)
fetch.assert_called_once()
caches["weather"].clear()
def test_weather_provider_failure_is_isolated(self):
self.client.force_login(self.one)
with patch("dashboard.views.get_forecast", side_effect=ForecastUnavailable("Weather service is temporarily unavailable")):
response = self.client.post(reverse("dashboard:open_meteo"), json.dumps({"latitude": 52.96, "longitude": 5.92}), content_type="application/json")
self.assertEqual(response.status_code, 503)
def test_weather_stale_cache_is_labeled_after_provider_failure(self):
cache = caches["weather"]
cache.clear()
key = hashlib.sha256(b"open-meteo:v1:52.96:5.92").hexdigest()
cache.set(f"stale:{key}", {"current": {"temperature_2m": 8}, "hourly": {"time": ["2026-10-14T12:00"]}, "daily": {}, "fetched_at": "2026-10-14T10:00:00+00:00"}, 60)
with patch("dashboard.weather.request_forecast", side_effect=OSError("provider offline")):
result = get_forecast(52.96, 5.92)
self.assertTrue(result["stale"])
self.assertEqual(result["current"]["temperature_2m"], 8)
cache.clear()
def test_buienradar_feed_parsing_crosses_midnight(self):
now = datetime(2026, 10, 14, 23, 54, tzinfo=ZoneInfo("Europe/Amsterdam"))
points = parse_forecast("000|23:55\n077|00:00\n125|00:05\n", now=now)
self.assertEqual(points[0]["label"], "None")
self.assertAlmostEqual(points[1]["mm_per_hour"], 0.1)
self.assertEqual(points[1]["time"][:10], "2026-10-15")
self.assertEqual(points[2]["label"], "Moderate")
self.assertIsNone(parse_forecast("255|23:55\n", now=now)[0]["mm_per_hour"])
with self.assertRaises(RainUnavailable):
parse_forecast("not a feed", now=now)
def test_buienradar_endpoint_auth_range_and_cache(self):
url = reverse("dashboard:buienradar")
self.assertEqual(self.client.post(url, data="{}", content_type="application/json").status_code, 302)
self.client.force_login(self.one)
self.assertEqual(self.client.post(url, json.dumps({"latitude": 40, "longitude": 5}), content_type="application/json").status_code, 400)
caches["weather"].clear()
payload = {"points": [{"time": "2026-10-14T23:55:00+02:00", "mm_per_hour": 0, "label": "None"}], "fetched_at": "2026-10-14T21:55:00+00:00"}
with patch("dashboard.buienradar.request_rain", return_value=payload) as fetch:
first = get_rain(52.961, 5.919)
second = get_rain(52.96, 5.92)
self.assertFalse(first["stale"])
self.assertEqual(second["points"], first["points"])
fetch.assert_called_once()
caches["weather"].clear()
def test_buienradar_stale_fallback(self):
cache = caches["weather"]
cache.clear()
key = hashlib.sha256(b"buienradar:v1:52.96:5.92").hexdigest()
cache.set(f"stale:{key}", {"points": [{"time": "2026-10-14T23:55:00+02:00", "mm_per_hour": 0, "label": "None"}], "fetched_at": "2026-10-14T21:55:00+00:00"}, 60)
with patch("dashboard.buienradar.request_rain", side_effect=OSError("offline")):
result = get_rain(52.96, 5.92)
self.assertTrue(result["stale"])
cache.clear()
+11
View File
@@ -0,0 +1,11 @@
from django.urls import path
from . import views
app_name = "dashboard"
urlpatterns = [
path("", views.index, name="index"),
path("dashboard/<slug:page>/", views.page, name="page"),
path("dashboard/<slug:page>/layout/", views.layout_api, name="layout"),
path("dashboard/weather/open-meteo/", views.open_meteo_api, name="open_meteo"),
path("dashboard/weather/buienradar/", views.buienradar_api, name="buienradar"),
]
+122
View File
@@ -0,0 +1,122 @@
import json
import uuid
from django.contrib.auth.decorators import login_required
from django.db import transaction
from django.http import JsonResponse
from django.shortcuts import render
from django.views.decorators.http import require_http_methods
from django.views.decorators.csrf import ensure_csrf_cookie
from .models import DashboardLayout
from .registry import WIDGETS
from .weather import ForecastUnavailable, get_forecast
from .buienradar import RainUnavailable, get_rain
PAGES = {"overview": "Overview", "personal": "Personal"}
def default_widgets():
return [
{"id": str(uuid.uuid4()), "type": "welcome", "order": 0, "span": 2, "settings": {}, "visible": True},
{"id": str(uuid.uuid4()), "type": "shortcuts", "order": 1, "span": 1, "settings": {}, "visible": True},
]
def validate_widgets(items):
if not isinstance(items, list) or len(items) > 40:
raise ValueError("Invalid widget list")
seen_ids, seen_types, cleaned = set(), set(), []
for order, item in enumerate(items):
if not isinstance(item, dict) or item.get("type") not in WIDGETS:
raise ValueError("Unknown widget type")
kind = WIDGETS[item["type"]]
try:
identifier = str(uuid.UUID(item["id"]))
except (KeyError, TypeError, ValueError):
raise ValueError("Invalid widget ID") from None
if identifier in seen_ids or (not kind.multiple and kind.id in seen_types):
raise ValueError("Duplicate widget")
span = item.get("span")
settings = item.get("settings", {})
if type(span) is not int or span not in (1, 2) or not isinstance(settings, dict) or set(settings) - set(kind.settings_keys):
raise ValueError("Invalid widget settings or span")
if any(not isinstance(value, str) or len(value) > 1000 for value in settings.values()):
raise ValueError("Invalid widget setting value")
if type(item.get("visible")) is not bool:
raise ValueError("Invalid visibility")
seen_ids.add(identifier)
seen_types.add(kind.id)
cleaned.append({"id": identifier, "type": kind.id, "order": order, "span": span, "settings": settings, "visible": item["visible"]})
return cleaned
def render_page(request, page):
if page not in PAGES:
return JsonResponse({"error": "Unknown dashboard page"}, status=404)
layout, _ = DashboardLayout.objects.get_or_create(user=request.user, page=page, defaults={"widgets": default_widgets()})
instances = [{**item, "kind": WIDGETS[item["type"]]} for item in layout.widgets if item["type"] in WIDGETS and item.get("visible", True)]
return render(request, "dashboard/index.html", {"title": PAGES[page], "section": "dashboard", "dashboard_page": page, "layout": layout, "instances": instances, "catalogue": WIDGETS.values()})
@login_required
@ensure_csrf_cookie
def index(request):
return render_page(request, "overview")
@login_required
@ensure_csrf_cookie
def page(request, page):
return render_page(request, page)
@login_required
@require_http_methods(["PUT"])
def layout_api(request, page):
if page not in PAGES:
return JsonResponse({"error": "Unknown dashboard page"}, status=404)
try:
body = json.loads(request.body)
if not isinstance(body, dict) or type(body.get("revision")) is not int:
raise ValueError("Invalid revision")
widgets = validate_widgets(body.get("widgets"))
except (ValueError, UnicodeDecodeError) as exc:
return JsonResponse({"error": str(exc)}, status=400)
with transaction.atomic():
layout = DashboardLayout.objects.select_for_update().get_or_create(user=request.user, page=page, defaults={"widgets": default_widgets()})[0]
if layout.revision != body["revision"]:
return JsonResponse({"error": "Layout changed in another tab. Reload before saving.", "revision": layout.revision}, status=409)
layout.widgets = widgets
layout.revision += 1
layout.save(update_fields=["widgets", "revision", "updated_at"])
return JsonResponse({"revision": layout.revision, "widgets": widgets})
@login_required
@require_http_methods(["POST"])
def open_meteo_api(request):
try:
body = json.loads(request.body)
if not isinstance(body, dict):
raise ValueError("Invalid location")
forecast = get_forecast(body.get("latitude"), body.get("longitude"))
except (ValueError, UnicodeDecodeError):
return JsonResponse({"error": "Choose a valid location"}, status=400)
except ForecastUnavailable as exc:
return JsonResponse({"error": str(exc)}, status=503)
return JsonResponse(forecast)
@login_required
@require_http_methods(["POST"])
def buienradar_api(request):
try:
body = json.loads(request.body)
if not isinstance(body, dict):
raise ValueError("Invalid location")
rain = get_rain(body.get("latitude"), body.get("longitude"))
except (ValueError, UnicodeDecodeError) as exc:
return JsonResponse({"error": str(exc) or "Choose a valid location"}, status=400)
except RainUnavailable as exc:
return JsonResponse({"error": str(exc)}, status=503)
return JsonResponse(rain)
+90
View File
@@ -0,0 +1,90 @@
"""Open-Meteo adapter. No user location is persisted or logged."""
import hashlib
import json
import math
from datetime import datetime, timezone
from urllib.parse import urlencode
from urllib.request import Request, urlopen
from django.core.cache import caches
ENDPOINT = "https://api.open-meteo.com/v1/forecast"
CURRENT = (
"temperature_2m", "apparent_temperature", "relative_humidity_2m", "weather_code",
"precipitation", "wind_speed_10m", "wind_direction_10m", "cloud_cover", "is_day",
)
HOURLY = (
"temperature_2m", "apparent_temperature", "precipitation", "precipitation_probability",
"wind_speed_10m", "wind_gusts_10m", "wind_direction_10m", "relative_humidity_2m",
"cloud_cover", "uv_index", "weather_code", "is_day",
)
DAILY = (
"temperature_2m_max", "temperature_2m_min", "sunrise", "sunset", "daylight_duration",
"precipitation_sum", "precipitation_probability_max", "wind_gusts_10m_max", "uv_index_max", "snowfall_sum",
)
FRESH_SECONDS = 900
STALE_SECONDS = 3600
class ForecastUnavailable(Exception):
pass
def coordinates(latitude, longitude):
try:
lat, lon = float(latitude), float(longitude)
except (TypeError, ValueError):
raise ValueError("Invalid coordinates") from None
if not math.isfinite(lat) or not math.isfinite(lon) or not (-90 <= lat <= 90) or not (-180 <= lon <= 180):
raise ValueError("Invalid coordinates")
return round(lat, 2), round(lon, 2)
def request_forecast(lat, lon):
params = {
"latitude": lat, "longitude": lon, "timezone": "auto", "forecast_hours": 48,
"forecast_days": 2, "temperature_unit": "celsius", "wind_speed_unit": "kmh",
"precipitation_unit": "mm", "current": ",".join(CURRENT),
"hourly": ",".join(HOURLY), "daily": ",".join(DAILY),
}
request = Request(f"{ENDPOINT}?{urlencode(params)}", headers={"User-Agent": "CommonGroundDashboard/1.0"})
with urlopen(request, timeout=8) as response:
if response.status != 200:
raise ForecastUnavailable("Weather service is temporarily unavailable")
payload = json.load(response)
if payload.get("error") or not all(isinstance(payload.get(key), dict) for key in ("current", "hourly", "daily")):
raise ForecastUnavailable("Weather data could not be read")
if not isinstance(payload["hourly"].get("time"), list) or not payload["hourly"]["time"]:
raise ForecastUnavailable("Hourly forecast is unavailable")
return {
"current": payload["current"], "hourly": payload["hourly"], "daily": payload["daily"],
"timezone": payload.get("timezone_abbreviation") or payload.get("timezone") or "local time",
"fetched_at": datetime.now(timezone.utc).isoformat(),
}
def get_forecast(latitude, longitude):
lat, lon = coordinates(latitude, longitude)
key = hashlib.sha256(f"open-meteo:v1:{lat:.2f}:{lon:.2f}".encode()).hexdigest()
cache = caches["weather"]
fresh = cache.get(f"fresh:{key}")
if fresh is not None:
return {**fresh, "stale": False}
stale = cache.get(f"stale:{key}")
lock = f"lock:{key}"
if not cache.add(lock, True, timeout=20):
if stale is not None:
return {**stale, "stale": True}
raise ForecastUnavailable("Forecast is being refreshed. Try again shortly")
try:
payload = request_forecast(lat, lon)
cache.set(f"fresh:{key}", payload, timeout=FRESH_SECONDS)
cache.set(f"stale:{key}", payload, timeout=STALE_SECONDS)
return {**payload, "stale": False}
except (OSError, ValueError, json.JSONDecodeError, ForecastUnavailable) as exc:
if stale is not None:
return {**stale, "stale": True}
raise ForecastUnavailable("Weather service is temporarily unavailable") from exc
finally:
cache.delete(lock)