Files
rose-ash/shared/sexp/page.py
giles 838ec982eb Phase 7: Replace render_template() with s-expression rendering in all POST/PUT/DELETE routes
Eliminates all render_template() calls from POST/PUT/DELETE handlers across
all 7 services. Moves sexp_components.py into sexp/ packages per service.

- Blog: like toggle, snippets, cache clear, features/sumup/entry panels,
  create/delete market, WYSIWYG editor panel (render_editor_panel)
- Federation: like/unlike/boost/unboost, follow/unfollow, actor card,
  interaction buttons
- Events: ticket widget, checkin, confirm/decline/provisional, tickets
  config, posts CRUD, description edit/save, calendar/slot/ticket_type
  CRUD, payments, buy tickets, day main panel, entry page
- Market: like toggle, cart add response
- Account: newsletter toggle
- Cart: checkout error pages (3 handlers)
- Orders: checkout error page (1 handler)

Remaining render_template() calls are exclusively in GET handlers and
internal services (email templates, fragment endpoints).

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-28 01:15:29 +00:00

106 lines
3.7 KiB
Python

"""
Full-page s-expression rendering.
Provides ``render_page()`` for rendering a complete HTML page from an
s-expression, bypassing Jinja entirely. Used by error handlers and
(eventually) by route handlers for fully-migrated pages.
``render_sexp_response()`` is the main entry point for GET route handlers:
it calls the app's context processor, merges in route-specific kwargs,
renders the s-expression to HTML, and returns a Quart ``Response``.
Usage::
from shared.sexp.page import render_page, render_sexp_response
# Error pages (no context needed)
html = render_page(
'(~error-page :title "Not Found" :message "NOT FOUND" :image img :asset-url aurl)',
image="/static/errors/404.gif",
asset_url="/static",
)
# GET route handlers (auto-injects app context)
resp = await render_sexp_response('(~orders-page :orders orders)', orders=orders)
"""
from __future__ import annotations
from typing import Any
from .jinja_bridge import sexp
# HTML constants used by layout components — kept here to avoid
# s-expression parser issues with embedded quotes in SVG.
HAMBURGER_HTML = (
'<div class="md:hidden bg-stone-200 rounded">'
'<svg class="h-12 w-12 transition-transform group-open/root:hidden block self-start"'
' viewBox="0 0 24 24" fill="none" stroke="currentColor">'
'<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2"'
' d="M4 6h16M4 12h16M4 18h16"/></svg>'
'<svg aria-hidden="true" viewBox="0 0 24 24"'
' class="w-12 h-12 rotate-180 transition-transform group-open/root:block hidden self-start">'
'<path d="M6 9l6 6 6-6" fill="currentColor"/></svg></div>'
)
SEARCH_HEADERS_MOBILE = '{"X-Origin":"search-mobile","X-Search":"true"}'
SEARCH_HEADERS_DESKTOP = '{"X-Origin":"search-desktop","X-Search":"true"}'
def render_page(source: str, **kwargs: Any) -> str:
"""Render a full HTML page from an s-expression string.
This is a thin wrapper around ``sexp()`` — it exists to make the
intent explicit in call sites (rendering a whole page, not a fragment).
"""
return sexp(source, **kwargs)
async def get_template_context(**kwargs: Any) -> dict[str, Any]:
"""Gather the full template context from all registered context processors.
Returns a dict with all context variables that would normally be
available in a Jinja template, merged with any extra kwargs.
"""
import asyncio
from quart import current_app, request
ctx: dict[str, Any] = {}
# App-level context processors
for proc in current_app.template_context_processors.get(None, []):
rv = proc()
if asyncio.iscoroutine(rv):
rv = await rv
ctx.update(rv)
# Blueprint-scoped context processors
for bp_name in (request.blueprints or []):
for proc in current_app.template_context_processors.get(bp_name, []):
rv = proc()
if asyncio.iscoroutine(rv):
rv = await rv
ctx.update(rv)
# Inject Jinja globals that s-expression components need (URL helpers,
# asset_url, styles, etc.) — these aren't provided by context processors.
for key, val in current_app.jinja_env.globals.items():
if key not in ctx:
ctx[key] = val
ctx.update(kwargs)
return ctx
async def render_sexp_response(source: str, **kwargs: Any) -> str:
"""Render an s-expression with the full app template context.
Calls the app's registered context processors (which provide
cart_mini_html, auth_menu_html, nav_tree_html, asset_url, etc.)
and merges them with the caller's kwargs before rendering.
Returns the rendered HTML string (caller wraps in Response as needed).
"""
ctx = await get_template_context(**kwargs)
return sexp(source, **ctx)