feat: add page shell, preferences and translations

Base layout with top bar, role-based menu, profile menu and phone layout; theme, language and German form of address kept in cookies; German formal, German informal and English text; Fluent avatar bundled in the image by a Node build stage; placeholder pages for the Publisher and Admin groups.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01N3t4WL7bd9bdHHNjEsxzqC
This commit is contained in:
2026-10-17 21:05:40 +02:00
co-authored by Claude Sonnet 5.5
parent 3c69c2a156
commit 0dc079a8ac
34 changed files with 2132 additions and 24 deletions
View File
+6
View File
@@ -0,0 +1,6 @@
from django.apps import AppConfig
class ShellConfig(AppConfig):
name = "portal.shell"
label = "shell"
+37
View File
@@ -0,0 +1,37 @@
from django.utils.translation import gettext_lazy as _
from . import menu, preferences
THEME_OPTIONS = (
("light", _("Light")),
("dark", _("Dark")),
("system", _("System")),
)
LANGUAGE_OPTIONS = (("de", "Deutsch"), ("en", "English"))
FORM_OPTIONS = (("sie", "Sie"), ("du", "du"))
def initials(name: str) -> str:
words = [w for w in name.split() if w]
if not words:
return "?"
letters = words[0][0] + (words[-1][0] if len(words) > 1 else "")
return letters.upper()
def shell(request):
"""Menu, preferences and the values the base layout needs."""
prefs = getattr(request, "preferences", preferences.Preferences())
portal_user = getattr(request, "portal_user", None)
context = {
"preferences": prefs,
"html_lang": prefs.language,
"theme_options": THEME_OPTIONS,
"language_options": LANGUAGE_OPTIONS,
"form_options": FORM_OPTIONS,
"portal_user": portal_user,
}
if portal_user is not None:
context["menu_groups"] = menu.for_user(portal_user, request.path)
context["initials"] = initials(portal_user.display_name)
return context
+61
View File
@@ -0,0 +1,61 @@
"""The left menu, declared once. An entry is shown only to users who may open its page."""
from __future__ import annotations
from dataclasses import dataclass
from django.urls import reverse
from django.utils.translation import gettext_lazy as _
@dataclass(frozen=True)
class Entry:
label: object # lazy translated string
url_name: str
@dataclass(frozen=True)
class Group:
title: object | None
role: str | None # None: everyone; otherwise "publisher" or "admin"
entries: tuple[Entry, ...]
MENU = (
Group(None, None, (Entry(_("Home"), "home"),)),
Group(
_("Publishing"),
"publisher",
(Entry(_("Manage announcements"), "publish-announcements"),),
),
Group(
_("Administration"),
"admin",
(
Entry(_("Appearance"), "admin-appearance"),
Entry(_("Settings"), "admin-settings"),
Entry(_("Audit log"), "admin-audit"),
Entry(_("Status"), "admin-status"),
),
),
)
def _allowed(group: Group, portal_user) -> bool:
if group.role is None:
return True
return bool(getattr(portal_user, f"is_{group.role}", False))
def for_user(portal_user, current_path: str) -> list[dict]:
"""The groups this user sees, each entry with its address and whether it is current."""
groups = []
for group in MENU:
if not _allowed(group, portal_user):
continue
entries = []
for entry in group.entries:
url = reverse(entry.url_name)
entries.append({"label": entry.label, "url": url, "current": url == current_path})
groups.append({"title": group.title, "entries": entries})
return groups
+24
View File
@@ -0,0 +1,24 @@
from django.utils import translation
from django.utils.cache import patch_vary_headers
from . import preferences
class PreferencesMiddleware:
"""Read the preference cookies and activate the language for this request (AD-15)."""
def __init__(self, get_response):
self.get_response = get_response
def __call__(self, request):
prefs = preferences.from_request(request)
request.preferences = prefs
request.LANGUAGE_CODE = prefs.language_code
translation.activate(prefs.language_code)
try:
response = self.get_response(request)
finally:
translation.deactivate()
response.headers.setdefault("Content-Language", prefs.language)
patch_vary_headers(response, ("Cookie", "Accept-Language"))
return response
+82
View File
@@ -0,0 +1,82 @@
"""Per-device preferences: theme, language and German form of address (AD-15).
They live in cookies and are never stored on the server. Values are checked against fixed
lists, so a forged cookie can only fall back to the default.
"""
from __future__ import annotations
from dataclasses import dataclass
from django.http import HttpRequest, HttpResponse
from django.utils import translation
THEME_COOKIE = "pm_theme"
LANGUAGE_COOKIE = "pm_lang"
FORM_COOKIE = "pm_form"
COOKIE_MAX_AGE = 365 * 24 * 60 * 60
THEMES = ("light", "dark", "system")
LANGUAGES = ("de", "en")
FORMS = ("sie", "du")
DEFAULT_THEME = "system"
DEFAULT_FORM = "sie"
INFORMAL_GERMAN = "de-du" # catalogue with only the informal differences; falls back to "de"
_CHOICES = {
THEME_COOKIE: ("theme", THEMES),
LANGUAGE_COOKIE: ("language", LANGUAGES),
FORM_COOKIE: ("form", FORMS),
}
@dataclass(frozen=True)
class Preferences:
theme: str = DEFAULT_THEME
language: str = "en"
form: str = DEFAULT_FORM
@property
def language_code(self) -> str:
"""The code the translations are activated with."""
if self.language == "de" and self.form == "du":
return INFORMAL_GERMAN
return self.language
def from_request(request: HttpRequest) -> Preferences:
theme = request.COOKIES.get(THEME_COOKIE)
language = request.COOKIES.get(LANGUAGE_COOKIE)
form = request.COOKIES.get(FORM_COOKIE)
if language not in LANGUAGES:
# Default from Accept-Language: German or English, English otherwise.
language = translation.get_language_from_request(request, check_path=False)
language = language if language in LANGUAGES else "en"
return Preferences(
theme=theme if theme in THEMES else DEFAULT_THEME,
language=language,
form=form if form in FORMS else DEFAULT_FORM,
)
def chosen(values) -> dict[str, str]:
"""The cookie name and value for every valid preference in `values` (a POST or a dict)."""
result = {}
for cookie, (field, allowed) in _CHOICES.items():
value = values.get(field)
if value in allowed:
result[cookie] = value
return result
def set_cookies(response: HttpResponse, cookies: dict[str, str], *, secure: bool) -> None:
for name, value in cookies.items():
response.set_cookie(
name,
value,
max_age=COOKIE_MAX_AGE,
secure=secure,
httponly=False, # shell.js applies a change without a reload
samesite="Lax",
)
+12
View File
@@ -0,0 +1,12 @@
from django.urls import path
from . import views
urlpatterns = [
path("preferences", views.set_preferences, name="preferences"),
path("publish/announcements", views.publish_announcements, name="publish-announcements"),
path("administration/appearance", views.admin_appearance, name="admin-appearance"),
path("administration/settings", views.admin_settings, name="admin-settings"),
path("administration/audit", views.admin_audit, name="admin-audit"),
path("administration/status", views.admin_status, name="admin-status"),
]
+37
View File
@@ -0,0 +1,37 @@
from django.conf import settings
from django.http import HttpResponseRedirect
from django.shortcuts import render
from django.utils.http import url_has_allowed_host_and_scheme
from django.utils.translation import gettext_lazy as _
from django.views.decorators.http import require_POST
from portal.accounts.decorators import admin_required, publisher_required
from . import preferences
@require_POST
def set_preferences(request):
"""Store the chosen preferences in cookies (the no-JavaScript path of the profile menu)."""
target = request.POST.get("next", "")
if not (target.startswith("/") and url_has_allowed_host_and_scheme(target, None)):
target = "/"
response = HttpResponseRedirect(target)
preferences.set_cookies(
response, preferences.chosen(request.POST), secure=not settings.DEBUG
)
return response
def _placeholder(title):
def view(request):
return render(request, "shell/placeholder.html", {"title": title})
return view
publish_announcements = publisher_required(_placeholder(_("Manage announcements")))
admin_appearance = admin_required(_placeholder(_("Appearance")))
admin_settings = admin_required(_placeholder(_("Settings")))
admin_audit = admin_required(_placeholder(_("Audit log")))
admin_status = admin_required(_placeholder(_("Status")))