From a0c53ea3f91a07ccac65e868448d492ba7afb3be Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 3 Nov 2026 12:26:53 +0000 Subject: [PATCH 1/3] Add a static recipe book to the Sheet section /recipes lists recipes as picture cards; /recipes/ shows the picture, an ingredient checklist and numbered steps. Recipes are plain data in src/safe_family/urls/recipes_data.py (copy a block to add one), pictures in static/recipes/. One example recipe with its own SVG picture. The Sheet page gets a separate Recipes section below Calculators, and the Sheet nav item stays active on the recipe pages. tests/test_recipes.py validates the hand-edited data (fields, unique slugs, pictures exist) and the pages (login, list, detail, 404, no picture, empty list). Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01CKZWtPcMA8pSrVvGGwno21 --- src/safe_family/static/css/styles.css | 249 ++++++++++++++++++ .../static/recipes/tomato-egg-stir-fry.svg | 29 ++ src/safe_family/templates/base.html | 2 +- .../templates/miscellaneous/calc_guide.html | 11 + .../miscellaneous/recipe_detail.html | 53 ++++ .../templates/miscellaneous/recipes.html | 41 +++ src/safe_family/urls/miscellaneous.py | 23 +- src/safe_family/urls/recipes_data.py | 48 ++++ tests/test_recipes.py | 115 ++++++++ tests/test_routes.py | 2 + 10 files changed, 571 insertions(+), 2 deletions(-) create mode 100644 src/safe_family/static/recipes/tomato-egg-stir-fry.svg create mode 100644 src/safe_family/templates/miscellaneous/recipe_detail.html create mode 100644 src/safe_family/templates/miscellaneous/recipes.html create mode 100644 src/safe_family/urls/recipes_data.py create mode 100644 tests/test_recipes.py diff --git a/src/safe_family/static/css/styles.css b/src/safe_family/static/css/styles.css index 3175d7d..576ca14 100644 --- a/src/safe_family/static/css/styles.css +++ b/src/safe_family/static/css/styles.css @@ -1365,3 +1365,252 @@ td form button { .codehilite .nf, .codehilite .fm, .codehilite .nc { color: #d2a8ff; } .codehilite .nb, .codehilite .bp, .codehilite .nd { color: #ffa657; } .codehilite .o, .codehilite .p { color: #e6edf3; } + +/* Recipes (Sheet section) */ +/* Two classes: base.html's inline styles (loaded after this file) reset + .card-header margins. */ +.card-header.recipe-section-header { + margin-top: 3rem; +} + +.recipe-page { + max-width: 72rem; + margin: 0 auto; +} + +.recipe-toolbar { + display: flex; + justify-content: space-between; + align-items: center; + gap: 12px; + flex-wrap: wrap; + margin-block: 12px; +} + +.recipe-back { + color: var(--sf-ink-muted); + text-decoration: none; +} + +.recipe-back:hover { + color: var(--sf-accent); +} + +.recipe-grid { + display: grid; + grid-template-columns: repeat(auto-fill, minmax(16rem, 1fr)); + gap: 20px; +} + +.recipe-card { + display: flex; + flex-direction: column; + overflow: hidden; + border: 1px solid var(--sf-border); + border-radius: var(--sf-radius); + background: var(--sf-surface); + color: var(--sf-ink); + text-decoration: none; + transition: transform 0.15s ease, box-shadow 0.15s ease; +} + +.recipe-card:hover { + transform: translateY(-2px); + box-shadow: 0 6px 18px rgba(0, 0, 0, 0.12); +} + +.recipe-card-img { + width: 100%; + aspect-ratio: 4 / 3; + object-fit: cover; + display: block; + background: var(--sf-accent-soft); +} + +.recipe-card-img--empty { + display: flex; + align-items: center; + justify-content: center; + font-size: 3rem; +} + +.recipe-card-body { + display: flex; + flex-direction: column; + gap: 8px; + padding: 14px 16px 16px; +} + +.recipe-card-title { + font-family: var(--sf-display); + font-size: 1.2rem; + font-weight: 700; + line-height: 1.3; +} + +.recipe-card-summary { + color: var(--sf-ink-muted); + font-size: 0.92rem; + line-height: 1.5; +} + +.recipe-meta { + display: flex; + flex-wrap: wrap; + gap: 4px 14px; + font-size: 0.82rem; + color: var(--sf-ink-muted); +} + +.recipe-tags { + display: flex; + flex-wrap: wrap; + gap: 6px; +} + +.recipe-tag { + font-size: 0.75rem; + padding: 2px 10px; + border-radius: 999px; + background: var(--sf-accent-soft); + color: var(--sf-accent); +} + +.recipe-detail { + padding: 0; + overflow: hidden; +} + +.recipe-hero { + display: grid; + grid-template-columns: minmax(0, 1fr); +} + +@media (min-width: 48rem) { + .recipe-hero { + grid-template-columns: minmax(0, 5fr) minmax(0, 6fr); + } +} + +.recipe-hero-img { + width: 100%; + height: 100%; + max-height: 22rem; + aspect-ratio: 4 / 3; + object-fit: cover; + display: block; + background: var(--sf-accent-soft); +} + +.recipe-hero-text { + display: flex; + flex-direction: column; + justify-content: center; + gap: 10px; + padding: 24px clamp(16px, 4vw, 32px); +} + +.recipe-title { + font-family: var(--sf-display); + font-size: clamp(1.6rem, 4vw, 2.2rem); + font-weight: 700; + line-height: 1.2; + color: var(--sf-ink); +} + +.recipe-summary { + color: var(--sf-ink-muted); + line-height: 1.6; +} + +.recipe-columns { + display: grid; + grid-template-columns: minmax(0, 1fr); + gap: 28px; + padding: 24px clamp(16px, 4vw, 32px) 32px; + border-top: 1px solid var(--sf-border); +} + +@media (min-width: 48rem) { + .recipe-columns { + grid-template-columns: minmax(0, 2fr) minmax(0, 3fr); + } +} + +.recipe-section-title { + font-family: var(--sf-display); + font-size: 1.2rem; + font-weight: 700; + margin-bottom: 12px; + color: var(--sf-ink); +} + +.recipe-ingredients { + display: flex; + flex-direction: column; + gap: 8px; +} + +.recipe-ingredients label { + display: flex; + align-items: flex-start; + gap: 10px; + cursor: pointer; + font-size: 1rem; + line-height: 1.5; + color: var(--sf-ink); +} + +.recipe-ingredients input { + width: 1.1rem; + height: 1.1rem; + margin-top: 0.2em; + flex-shrink: 0; + accent-color: var(--sf-accent); +} + +.recipe-ingredients input:checked + span { + color: var(--sf-ink-dim); + text-decoration: line-through; +} + +.recipe-steps { + counter-reset: recipe-step; + display: flex; + flex-direction: column; + gap: 14px; +} + +.recipe-steps li { + counter-increment: recipe-step; + position: relative; + padding-left: 2.4rem; + line-height: 1.6; + color: var(--sf-ink); +} + +.recipe-steps li::before { + content: counter(recipe-step); + position: absolute; + left: 0; + top: 0; + width: 1.7rem; + height: 1.7rem; + border-radius: 50%; + display: flex; + align-items: center; + justify-content: center; + font-size: 0.85rem; + font-weight: 700; + background: var(--sf-accent); + color: #fff; +} + +.recipe-notes { + margin-top: 18px; + padding: 12px 14px; + border-left: 3px solid var(--sf-accent); + border-radius: var(--sf-radius-sm); + background: var(--sf-accent-soft); + color: var(--sf-ink); +} diff --git a/src/safe_family/static/recipes/tomato-egg-stir-fry.svg b/src/safe_family/static/recipes/tomato-egg-stir-fry.svg new file mode 100644 index 0000000..ba70741 --- /dev/null +++ b/src/safe_family/static/recipes/tomato-egg-stir-fry.svg @@ -0,0 +1,29 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/src/safe_family/templates/base.html b/src/safe_family/templates/base.html index 407e18e..2d6357d 100644 --- a/src/safe_family/templates/base.html +++ b/src/safe_family/templates/base.html @@ -542,7 +542,7 @@ Schedule Sheet + class="{% if request.endpoint in ('index.calc_guide', 'index.recipes', 'index.recipe_detail') %}active{% endif %}">Sheet Logout {% else %} Login diff --git a/src/safe_family/templates/miscellaneous/calc_guide.html b/src/safe_family/templates/miscellaneous/calc_guide.html index 40f8b14..7b95636 100644 --- a/src/safe_family/templates/miscellaneous/calc_guide.html +++ b/src/safe_family/templates/miscellaneous/calc_guide.html @@ -27,5 +27,16 @@

Days remaining until your saved event.

+ +

Recipes

+ + {% endblock %} diff --git a/src/safe_family/templates/miscellaneous/recipe_detail.html b/src/safe_family/templates/miscellaneous/recipe_detail.html new file mode 100644 index 0000000..1118970 --- /dev/null +++ b/src/safe_family/templates/miscellaneous/recipe_detail.html @@ -0,0 +1,53 @@ +{% extends "base.html" %} + +{% block content %} +
+ + +
+
+ {% if recipe.image %} + {{ recipe.title }} + {% endif %} +
+

{{ recipe.title }}

+ {% if recipe.summary %}

{{ recipe.summary }}

{% endif %} +
+ {% if recipe.time %}⏱ {{ recipe.time }}{% endif %} + {% if recipe.servings %}🍽 {{ recipe.servings }} servings{% endif %} +
+ {% if recipe.tags %} +
+ {% for tag in recipe.tags %}{{ tag }}{% endfor %} +
+ {% endif %} +
+
+ +
+
+

Ingredients

+
    + {% for item in recipe.ingredients %} +
  • + {% endfor %} +
+
+
+

Steps

+
    + {% for step in recipe.steps %} +
  1. {{ step }}
  2. + {% endfor %} +
+ {% if recipe.notes %} +

Tip: {{ recipe.notes }}

+ {% endif %} +
+
+
+
+{% endblock %} diff --git a/src/safe_family/templates/miscellaneous/recipes.html b/src/safe_family/templates/miscellaneous/recipes.html new file mode 100644 index 0000000..91cfcd9 --- /dev/null +++ b/src/safe_family/templates/miscellaneous/recipes.html @@ -0,0 +1,41 @@ +{% extends "base.html" %} + +{% block content %} +
+
+

Recipes

+ « Sheet +
+ + {% if recipes %} + + {% else %} +
No recipes yet. Add one in src/safe_family/urls/recipes_data.py.
+ {% endif %} +
+{% endblock %} diff --git a/src/safe_family/urls/miscellaneous.py b/src/safe_family/urls/miscellaneous.py index bdbced0..0939d4f 100644 --- a/src/safe_family/urls/miscellaneous.py +++ b/src/safe_family/urls/miscellaneous.py @@ -2,12 +2,13 @@ from datetime import datetime -from flask import Blueprint, flash, redirect, render_template, request +from flask import Blueprint, abort, flash, redirect, render_template, request from config.settings import settings from src.safe_family.core.auth import get_current_username, login_required from src.safe_family.core.extensions import db from src.safe_family.core.models import CountdownConfig +from src.safe_family.urls.recipes_data import RECIPES root_bp = Blueprint("index", __name__) @@ -41,6 +42,26 @@ def calc_guide(): return render_template("miscellaneous/calc_guide.html") +@root_bp.route("/recipes") +@login_required +def recipes(): + """Render the recipe list. + + Recipes are static data in recipes_data.py, edited by hand. + """ + return render_template("miscellaneous/recipes.html", recipes=RECIPES) + + +@root_bp.route("/recipes/") +@login_required +def recipe_detail(slug: str): + """Render one recipe with its ingredients and steps.""" + recipe = next((r for r in RECIPES if r["slug"] == slug), None) + if recipe is None: + abort(404) + return render_template("miscellaneous/recipe_detail.html", recipe=recipe) + + @root_bp.route("/yaw_calc") @login_required def yaw_calc(): diff --git a/src/safe_family/urls/recipes_data.py b/src/safe_family/urls/recipes_data.py new file mode 100644 index 0000000..9dd35dd --- /dev/null +++ b/src/safe_family/urls/recipes_data.py @@ -0,0 +1,48 @@ +"""Recipes shown on the /recipes page (Sheet section). Edit by hand. + +To add a recipe, copy one whole ``{...},`` block below, paste it under the +last one and change the values: + +- ``slug``: short unique id used in the page address (/recipes/), only + lowercase letters, digits and dashes. +- ``image``: a file in src/safe_family/static/recipes/ (JPG, PNG, WEBP or + SVG). Leave it as "" for no picture. +- ``ingredients`` and ``steps``: one string per line, in order. +- ``servings``, ``time``, ``tags`` and ``notes`` are optional; use "" or []. + +``tests/test_recipes.py`` checks this file (required fields, unique slugs, +pictures that exist), so run ``pytest -q tests/test_recipes.py --no-cov`` +after editing. The app reads it at startup: rebuild with +``docker compose up -d --build app``. +""" + +RECIPES = [ + { + "slug": "tomato-egg-stir-fry", + "title": "Tomato and Egg Stir-Fry", + "summary": "Soft scrambled eggs in a sweet-sour tomato sauce. Ready in 15 minutes, great over rice.", + "image": "tomato-egg-stir-fry.svg", + "servings": "2", + "time": "15 min", + "tags": ["dinner", "quick", "vegetarian"], + "ingredients": [ + "4 eggs", + "3 ripe tomatoes, cut into wedges", + "2 green onions, sliced (white and green parts apart)", + "1 tbsp ketchup", + "1 tsp sugar", + "1/2 tsp salt", + "3 tbsp cooking oil", + "2 tbsp water", + ], + "steps": [ + "Beat the eggs with a pinch of salt until smooth.", + "Heat 2 tbsp oil in a wok over medium-high heat. Pour in the eggs, stir gently until just set but still soft, then move them to a plate.", + "Add the remaining oil, fry the white parts of the green onion for 10 seconds, then add the tomatoes.", + "Cook the tomatoes for 2-3 minutes, pressing them a little, until they turn saucy. Stir in the ketchup, sugar, salt and water.", + "Return the eggs, fold them through the sauce for 30 seconds, and top with the green onion tops.", + "Serve right away with steamed rice.", + ], + "notes": "Very ripe tomatoes give the best sauce; in winter add 1 extra tbsp ketchup.", + }, +] diff --git a/tests/test_recipes.py b/tests/test_recipes.py new file mode 100644 index 0000000..3fe84dd --- /dev/null +++ b/tests/test_recipes.py @@ -0,0 +1,115 @@ +"""Tests for the static recipe pages and the hand-edited recipe data.""" + +import re +from pathlib import Path + +import pytest + +from src.safe_family.urls.recipes_data import RECIPES + +STATIC_RECIPES = Path(__file__).resolve().parents[1] / "src" / "safe_family" / "static" / "recipes" +REQUIRED_TEXT = ("slug", "title", "summary") +OPTIONAL_TEXT = ("image", "servings", "time", "notes") + + +def _article(html): + """The recipe article only, without the shared page layout.""" + return html.split('
', 1)[1].split("
", 1)[0] + + +def _login(client, monkeypatch): + monkeypatch.setattr( + "src.safe_family.core.auth.decode_token", + lambda token: {"sub": "user"}, + ) + with client.session_transaction() as sess: + sess["access_token"] = "token" + + +def test_recipes_data_has_an_example(): + assert RECIPES, "keep at least one recipe so the page has an example to copy" + + +@pytest.mark.parametrize("recipe", RECIPES, ids=lambda r: r.get("slug", "?")) +def test_recipe_entry_is_well_formed(recipe): + allowed = set(REQUIRED_TEXT) | set(OPTIONAL_TEXT) | {"tags", "ingredients", "steps"} + assert set(recipe) <= allowed, f"unknown keys: {set(recipe) - allowed}" + for key in REQUIRED_TEXT: + assert isinstance(recipe.get(key), str), f"{key} must be text" + assert recipe[key].strip(), f"{key} is empty" + for key in OPTIONAL_TEXT: + assert isinstance(recipe.get(key, ""), str), f"{key} must be text" + assert re.fullmatch(r"[a-z0-9]+(-[a-z0-9]+)*", recipe["slug"]), "slug: lowercase letters, digits, dashes" + for key in ("ingredients", "steps"): + items = recipe.get(key) + assert isinstance(items, list), f"{key} must be a list of lines" + assert items, f"{key} is empty" + assert all(isinstance(i, str) and i.strip() for i in items), f"{key} has an empty or non-text line" + tags = recipe.get("tags", []) + assert isinstance(tags, list), "tags must be a list" + assert all(isinstance(t, str) for t in tags), "tags must be text" + if recipe.get("image"): + assert (STATIC_RECIPES / recipe["image"]).is_file(), f"picture not found: static/recipes/{recipe['image']}" + + +def test_recipe_slugs_are_unique(): + slugs = [r["slug"] for r in RECIPES] + assert len(slugs) == len(set(slugs)), "two recipes share a slug" + + +def test_recipes_require_login(client): + resp = client.get("/recipes") + assert resp.status_code == 302 + assert resp.location.endswith("/auth/login-ui") + + +def test_recipes_list_renders_cards(client, monkeypatch): + _login(client, monkeypatch) + resp = client.get("/recipes") + html = resp.get_data(as_text=True) + assert resp.status_code == 200 + for recipe in RECIPES: + assert recipe["title"] in html + assert f'/recipes/{recipe["slug"]}' in html + + +def test_recipe_detail_shows_ingredients_steps_and_picture(client, monkeypatch): + _login(client, monkeypatch) + recipe = RECIPES[0] + resp = client.get(f"/recipes/{recipe['slug']}") + assert resp.status_code == 200 + article = _article(resp.get_data(as_text=True)) + assert recipe["title"] in article + assert article.count('type="checkbox"') == len(recipe["ingredients"]) + steps = article.split('
    ', 1)[1].split("
", 1)[0] + assert steps.count("
  • ") == len(recipe["steps"]) + if recipe.get("image"): + assert f"/static/recipes/{recipe['image']}" in article + + +def test_recipe_detail_unknown_slug_is_404(client, monkeypatch): + _login(client, monkeypatch) + assert client.get("/recipes/no-such-recipe").status_code == 404 + + +def test_recipe_without_picture_or_optional_fields(client, monkeypatch): + _login(client, monkeypatch) + bare = { + "slug": "bare", + "title": "Bare Recipe", + "summary": "No picture.", + "ingredients": ["water"], + "steps": ["boil"], + } + monkeypatch.setattr("src.safe_family.urls.miscellaneous.RECIPES", [bare]) + listing = client.get("/recipes").get_data(as_text=True) + assert "recipe-card-img--empty" in listing + detail = client.get("/recipes/bare") + assert detail.status_code == 200 + assert " Date: Tue, 3 Nov 2026 12:41:09 +0000 Subject: [PATCH 2/3] Fit the top navigation bar on phones The bar was one fixed row (brand, eight links, user), so on a phone it made every page about 660px wide and scroll sideways. - Up to 900px: brand and user stay on the first row; the links move to a full-width second row that wraps. - Up to 480px: the links form a balanced grid (4 + 3) and the ZZUSE mark and user name text are hidden (the avatar shows the initial), keeping the first row on one line. Desktop is unchanged. Checked at 320, 360, 390, 430, 768 and 1280px on the Sheet, recipe, notes, blog and calculator pages, logged in as admin and logged out: no page is wider than the screen. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01CKZWtPcMA8pSrVvGGwno21 --- src/safe_family/templates/base.html | 50 ++++++++++++++++++++++++++++- 1 file changed, 49 insertions(+), 1 deletion(-) diff --git a/src/safe_family/templates/base.html b/src/safe_family/templates/base.html index 2d6357d..0b956ea 100644 --- a/src/safe_family/templates/base.html +++ b/src/safe_family/templates/base.html @@ -219,6 +219,54 @@ font-weight: 700; } + /* Phones and narrow windows: brand and user on the first row, the + links on their own full-width row that wraps, so the bar never + makes the page wider than the screen. */ + @media (max-width: 900px) { + .sf-shell { + padding: 0 16px 48px; + } + + .sf-topbar { + flex-wrap: wrap; + row-gap: 10px; + } + + .sf-nav { + order: 3; + width: 100%; + flex-wrap: wrap; + justify-content: center; + gap: 4px; + } + + .sf-nav a { + padding: 6px 8px; + } + } + + /* Small phones: keep the first row to one line. The avatar shows the + user's initial, so the name text can go. */ + @media (max-width: 480px) { + .sf-brand-tm, + .sf-user-name { + display: none; + } + + /* Balanced rows (4 + 3) instead of one link left alone. */ + .sf-nav { + display: grid; + grid-template-columns: repeat(4, max-content); + justify-content: center; + gap: 4px 6px; + } + + .sf-nav a { + padding: 6px 8px; + text-align: center; + } + } + /* ===== flash ===== */ .flash { padding: 10px 14px; @@ -552,7 +600,7 @@
    {% if session.access_token %} {% if session.role == 'admin' %}GAME MASTER{% endif %} - {{ session.user_name or '' }} + {{ session.user_name or '' }}
    {{ (session.user_name or 'M')[:1]|upper }}
    {% endif %}
    From 884461c07b158d1f094fc96c55192bb3189e0a6d Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 3 Nov 2026 21:16:58 +0000 Subject: [PATCH 3/3] Top bar: real user initial and name, Logout beside the avatar The avatar always showed 'M' and the name was empty: the template read session.user_name, which login never sets (same for session.role, so the GAME MASTER badge never appeared). A context processor now looks up the logged-in user per request (get_current_username) and gives the template their username, initial and admin flag; admin still requires the configured ADMIN_IDENTITY, as elsewhere. A missing user or a database error falls back to '?' instead of failing the page. Logout moves from the menu to the user area. On phones the six links fit on one row from 320px up (tighter spacing under 340px), the badge gives way to an accent ring on the admin's avatar, and the 4-column grid is gone. Checked at 320-1280px as admin and as a normal user. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01CKZWtPcMA8pSrVvGGwno21 --- src/safe_family/app.py | 27 +++++++- src/safe_family/templates/base.html | 48 +++++++++---- tests/test_nav_user.py | 101 ++++++++++++++++++++++++++++ 3 files changed, 161 insertions(+), 15 deletions(-) create mode 100644 tests/test_nav_user.py diff --git a/src/safe_family/app.py b/src/safe_family/app.py index 33ba210..ed0e947 100644 --- a/src/safe_family/app.py +++ b/src/safe_family/app.py @@ -2,13 +2,14 @@ from datetime import timedelta -from flask import Flask, jsonify +from flask import Flask, jsonify, session +from sqlalchemy.exc import SQLAlchemyError from config.logging import setup_logging from config.settings import settings from src.safe_family.api.routes import api_bp from src.safe_family.auto_git.auto_git import auto_git_bp -from src.safe_family.core.auth import auth_bp +from src.safe_family.core.auth import auth_bp, get_current_username from src.safe_family.core.extensions import db, jwt, mail from src.safe_family.core.models import User from src.safe_family.rules.scheduler import schedule_rules_bp @@ -38,6 +39,26 @@ def _require_strong_secret(name: str, value: str | None) -> None: raise RuntimeError(msg) +def inject_nav_user() -> dict: + """Give the top bar the logged-in user's name, initial and admin flag.""" + if not session.get("access_token"): + return {"nav_user": None} + try: + user = get_current_username() + except SQLAlchemyError: + return {"nav_user": None} + if user is None: + return {"nav_user": None} + name = (user.username or "").strip() + return { + "nav_user": { + "name": name, + "initial": name[:1].upper() or "?", + "is_admin": user.role == "admin", + }, + } + + def create_app(): """Create and configure the Flask application.""" _require_strong_secret("FLASK_APP_SECRET_KEY", settings.APP_SECRET_KEY) @@ -72,6 +93,8 @@ def inject_motto() -> dict: """Inject the app motto into all templates.""" return {"motto": settings.APP_MOTTO} + app.context_processor(inject_nav_user) + app.register_blueprint(root_bp) app.register_blueprint(notes_bp) app.register_blueprint(blog_bp) diff --git a/src/safe_family/templates/base.html b/src/safe_family/templates/base.html index 0b956ea..13e2e28 100644 --- a/src/safe_family/templates/base.html +++ b/src/safe_family/templates/base.html @@ -219,6 +219,19 @@ font-weight: 700; } + .sf-user-logout { + padding: 4px 10px; + border: 1px solid var(--sf-border-strong); + border-radius: 6px; + color: var(--sf-ink-muted); + text-decoration: none; + } + + .sf-user-logout:hover { + color: var(--sf-ink); + background: var(--sf-surface); + } + /* Phones and narrow windows: brand and user on the first row, the links on their own full-width row that wraps, so the bar never makes the page wider than the screen. */ @@ -246,24 +259,32 @@ } /* Small phones: keep the first row to one line. The avatar shows the - user's initial, so the name text can go. */ + user's initial and, for the admin, a ring in place of the badge. */ @media (max-width: 480px) { .sf-brand-tm, - .sf-user-name { + .sf-user-name, + .sf-user-badge { display: none; } - /* Balanced rows (4 + 3) instead of one link left alone. */ + .sf-avatar.is-admin { + box-shadow: 0 0 0 2px var(--sf-bg), 0 0 0 4px var(--sf-accent); + } + .sf-nav { - display: grid; - grid-template-columns: repeat(4, max-content); - justify-content: center; - gap: 4px 6px; + gap: 2px; } .sf-nav a { - padding: 6px 8px; - text-align: center; + padding: 6px 7px; + } + } + + /* Smallest phones (320px): tighter links keep the menu on one row. */ + @media (max-width: 340px) { + .sf-nav a { + padding: 6px 4px; + font-size: 12px; } } @@ -591,7 +612,6 @@ class="{% if request.endpoint == 'schedule_rules.schedule_rules' %}active{% endif %}">Schedule Sheet - Logout {% else %} Login Register @@ -599,9 +619,11 @@
    {% if session.access_token %} - {% if session.role == 'admin' %}GAME MASTER{% endif %} - {{ session.user_name or '' }} -
    {{ (session.user_name or 'M')[:1]|upper }}
    + {% if nav_user and nav_user.is_admin %}GAME MASTER{% endif %} + {% if nav_user %}{{ nav_user.name }}{% endif %} + + Logout {% endif %}
    diff --git a/tests/test_nav_user.py b/tests/test_nav_user.py new file mode 100644 index 0000000..0b86190 --- /dev/null +++ b/tests/test_nav_user.py @@ -0,0 +1,101 @@ +"""Tests for the top bar: the logged-in user's avatar, name, badge and Logout.""" + +import re + +from flask_jwt_extended import create_access_token +from sqlalchemy.exc import OperationalError + +from src.safe_family.core.extensions import db +from src.safe_family.core.models import User + + +def _user(user_id, username): + user = User(id=user_id, username=username, email=f"{username}@example.com", role="user") + user.set_password("secret") + db.session.add(user) + db.session.commit() + + +def _login(app, client, user_id, **claims): + with app.app_context(): + token = create_access_token(identity=user_id, additional_claims=claims or None) + with client.session_transaction() as sess: + sess["access_token"] = token + + +def _topbar(client): + html = client.get("/calc_guide").get_data(as_text=True) + return html.split('
    ', 1)[1].split("
    ", 1)[0] + + +def _avatar(topbar): + return re.search(r'
    ]*>([^<]*)
    ', topbar).group(1).strip() + + +def test_avatar_shows_each_users_own_initial(notesync_app, notesync_client): + _user("u-a", "alice") + _user("u-b", "bob") + _login(notesync_app, notesync_client, "u-a") + topbar = _topbar(notesync_client) + assert _avatar(topbar) == "A" + assert 'alice' in topbar + assert "GAME MASTER" not in topbar + + _login(notesync_app, notesync_client, "u-b") + assert _avatar(_topbar(notesync_client)) == "B" + + +def test_logout_sits_by_the_avatar_not_in_the_menu(notesync_app, notesync_client): + _user("u-a", "alice") + _login(notesync_app, notesync_client, "u-a") + topbar = _topbar(notesync_client) + nav = topbar.split('", 1)[0] + user_area = topbar.split('
    ', 1)[1] + assert "Logout" not in nav + assert 'class="sf-user-logout"' in user_area + + +def test_admin_gets_badge_and_ring(notesync_app, notesync_client, monkeypatch): + monkeypatch.setattr("config.settings.settings.ADMIN_IDENTITY", "u-admin") + _user("u-admin", "zzuse") + _login(notesync_app, notesync_client, "u-admin", is_admin="admin") + topbar = _topbar(notesync_client) + assert "GAME MASTER" in topbar + assert 'class="sf-avatar is-admin"' in topbar + assert _avatar(topbar) == "Z" + + +def test_admin_claim_for_another_identity_is_not_trusted(notesync_app, notesync_client, monkeypatch): + monkeypatch.setattr("config.settings.settings.ADMIN_IDENTITY", "u-admin") + _user("u-a", "alice") + _login(notesync_app, notesync_client, "u-a", is_admin="admin") + assert "GAME MASTER" not in _topbar(notesync_client) + + +def test_token_for_missing_user_shows_placeholder(notesync_app, notesync_client): + _login(notesync_app, notesync_client, "no-such-user") + topbar = _topbar(notesync_client) + assert _avatar(topbar) == "?" + assert "sf-user-name" not in topbar + + +def test_database_error_still_renders_the_page(notesync_app, notesync_client, monkeypatch): + _user("u-a", "alice") + _login(notesync_app, notesync_client, "u-a") + + def broken(): + msg = "select" + raise OperationalError(msg, {}, Exception("db down")) + + monkeypatch.setattr("src.safe_family.app.get_current_username", broken) + resp = notesync_client.get("/calc_guide") + assert resp.status_code == 200 + assert _avatar(resp.get_data(as_text=True).split('
    ', 1)[1]) == "?" + + +def test_logged_out_shows_login_links_and_no_avatar(notesync_client): + html = notesync_client.get("/auth/login-ui").get_data(as_text=True) + topbar = html.split('
    ', 1)[1].split("
    ", 1)[0] + assert "Login" in topbar + assert "Register" in topbar + assert "sf-avatar" not in topbar