Add macros, declarative handlers (defhandler), and convert all fragment routes to sx
Phase 1 — Macros: defmacro + quasiquote syntax (`, ,, ,@) in parser,
evaluator, HTML renderer, and JS mirror. Macro type, expansion, and
round-trip serialization.
Phase 2 — Expanded primitives: app-url, url-for, asset-url, config,
format-date, parse-int (pure); service, request-arg, request-path,
nav-tree, get-children (I/O); jinja-global, relations-from (pure).
Updated _io_service to accept (service "registry-name" "method" :kwargs)
with auto kebab→snake conversion. DTO-to-dict now expands datetime fields
into year/month/day convenience keys. Tuple returns converted to lists.
Phase 3 — Declarative handlers: HandlerDef type, defhandler special form,
handler registry (service → name → HandlerDef), async evaluator+renderer
(async_eval.py) that awaits I/O primitives inline within control flow.
Handler loading from .sx files, execute_handler, blueprint factory.
Phase 4 — Convert all fragment routes: 13 Python fragment handlers across
8 services replaced with declarative .sx handler files. All routes.py
simplified to uniform sx dispatch pattern. Two Jinja HTML handlers
(events/container-cards, events/account-page) kept as Python.
New files: shared/sx/async_eval.py, shared/sx/handlers.py,
shared/sx/tests/test_handlers.py, plus 13 handler .sx files under
{service}/sx/handlers/. MarketService.product_by_slug() added.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
This commit is contained in:
@@ -2,21 +2,22 @@
|
||||
|
||||
Exposes sx fragments at ``/internal/fragments/<type>`` for consumption
|
||||
by other coop apps via the fragment client.
|
||||
|
||||
All handlers are defined declaratively in .sx files under
|
||||
``blog/sx/handlers/`` and dispatched via the sx handler registry.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from quart import Blueprint, Response, g, render_template, request
|
||||
from quart import Blueprint, Response, request
|
||||
|
||||
from shared.infrastructure.fragments import FRAGMENT_HEADER
|
||||
from shared.services.navigation import get_navigation_tree
|
||||
from shared.sx.handlers import get_handler, execute_handler
|
||||
|
||||
|
||||
def register():
|
||||
bp = Blueprint("fragments", __name__, url_prefix="/internal/fragments")
|
||||
|
||||
_handlers: dict[str, object] = {}
|
||||
|
||||
@bp.before_request
|
||||
async def _require_fragment_header():
|
||||
if not request.headers.get(FRAGMENT_HEADER):
|
||||
@@ -24,138 +25,12 @@ def register():
|
||||
|
||||
@bp.get("/<fragment_type>")
|
||||
async def get_fragment(fragment_type: str):
|
||||
handler = _handlers.get(fragment_type)
|
||||
if handler is None:
|
||||
return Response("", status=200, content_type="text/sx")
|
||||
result = await handler()
|
||||
return Response(result, status=200, content_type="text/sx")
|
||||
|
||||
# --- nav-tree fragment — returns sx source ---
|
||||
async def _nav_tree_handler():
|
||||
from shared.sx.helpers import sx_call, SxExpr
|
||||
from shared.infrastructure.urls import (
|
||||
blog_url, cart_url, market_url, events_url,
|
||||
federation_url, account_url, artdag_url,
|
||||
)
|
||||
|
||||
app_name = request.args.get("app_name", "")
|
||||
path = request.args.get("path", "/")
|
||||
first_seg = path.strip("/").split("/")[0]
|
||||
menu_items = list(await get_navigation_tree(g.s))
|
||||
|
||||
app_slugs = {
|
||||
"cart": cart_url("/"),
|
||||
"market": market_url("/"),
|
||||
"events": events_url("/"),
|
||||
"federation": federation_url("/"),
|
||||
"account": account_url("/"),
|
||||
"artdag": artdag_url("/"),
|
||||
}
|
||||
|
||||
nav_cls = "whitespace-nowrap flex items-center gap-2 rounded p-2 text-sm"
|
||||
|
||||
item_sxs = []
|
||||
for item in menu_items:
|
||||
href = app_slugs.get(item.slug, blog_url(f"/{item.slug}/"))
|
||||
selected = "true" if (item.slug == first_seg
|
||||
or item.slug == app_name) else "false"
|
||||
img = sx_call("img-or-placeholder",
|
||||
src=getattr(item, "feature_image", None),
|
||||
alt=getattr(item, "label", item.slug),
|
||||
size_cls="w-8 h-8 rounded-full object-cover flex-shrink-0")
|
||||
item_sxs.append(sx_call(
|
||||
"blog-nav-item-link",
|
||||
href=href, hx_get=href, selected=selected, nav_cls=nav_cls,
|
||||
img=SxExpr(img), label=getattr(item, "label", item.slug),
|
||||
))
|
||||
|
||||
# artdag link
|
||||
href = artdag_url("/")
|
||||
selected = "true" if ("artdag" == first_seg
|
||||
or "artdag" == app_name) else "false"
|
||||
img = sx_call("img-or-placeholder", src=None, alt="art-dag",
|
||||
size_cls="w-8 h-8 rounded-full object-cover flex-shrink-0")
|
||||
item_sxs.append(sx_call(
|
||||
"blog-nav-item-link",
|
||||
href=href, hx_get=href, selected=selected, nav_cls=nav_cls,
|
||||
img=SxExpr(img), label="art-dag",
|
||||
))
|
||||
|
||||
if not item_sxs:
|
||||
return sx_call("blog-nav-empty",
|
||||
wrapper_id="menu-items-nav-wrapper")
|
||||
|
||||
items_frag = "(<> " + " ".join(item_sxs) + ")"
|
||||
|
||||
arrow_cls = "scrolling-menu-arrow-menu-items-container"
|
||||
container_id = "menu-items-container"
|
||||
left_hs = ("on click set #" + container_id
|
||||
+ ".scrollLeft to #" + container_id + ".scrollLeft - 200")
|
||||
scroll_hs = ("on scroll "
|
||||
"set cls to '" + arrow_cls + "' "
|
||||
"set arrows to document.getElementsByClassName(cls) "
|
||||
"set show to (window.innerWidth >= 640 and "
|
||||
"my.scrollWidth > my.clientWidth) "
|
||||
"repeat for arrow in arrows "
|
||||
"if show remove .hidden from arrow add .flex to arrow "
|
||||
"else add .hidden to arrow remove .flex from arrow end "
|
||||
"end")
|
||||
right_hs = ("on click set #" + container_id
|
||||
+ ".scrollLeft to #" + container_id + ".scrollLeft + 200")
|
||||
|
||||
return sx_call("scroll-nav-wrapper",
|
||||
wrapper_id="menu-items-nav-wrapper",
|
||||
container_id=container_id,
|
||||
arrow_cls=arrow_cls,
|
||||
left_hs=left_hs,
|
||||
scroll_hs=scroll_hs,
|
||||
right_hs=right_hs,
|
||||
items=SxExpr(items_frag),
|
||||
oob=True)
|
||||
|
||||
_handlers["nav-tree"] = _nav_tree_handler
|
||||
|
||||
# --- link-card fragment — returns sx source ---
|
||||
def _blog_link_card_sx(post, link: str) -> str:
|
||||
from shared.sx.helpers import sx_call
|
||||
published = post.published_at.strftime("%d %b %Y") if post.published_at else None
|
||||
return sx_call("link-card",
|
||||
link=link,
|
||||
title=post.title,
|
||||
image=post.feature_image,
|
||||
icon="fas fa-file-alt",
|
||||
subtitle=post.custom_excerpt or post.excerpt,
|
||||
detail=published,
|
||||
data_app="blog")
|
||||
|
||||
async def _link_card_handler():
|
||||
from services import blog_service
|
||||
from shared.infrastructure.urls import blog_url
|
||||
|
||||
slug = request.args.get("slug", "")
|
||||
keys_raw = request.args.get("keys", "")
|
||||
|
||||
# Batch mode
|
||||
if keys_raw:
|
||||
slugs = [k.strip() for k in keys_raw.split(",") if k.strip()]
|
||||
parts = []
|
||||
for s in slugs:
|
||||
parts.append(f"<!-- fragment:{s} -->")
|
||||
post = await blog_service.get_post_by_slug(g.s, s)
|
||||
if post:
|
||||
parts.append(_blog_link_card_sx(post, blog_url(f"/{post.slug}")))
|
||||
return "\n".join(parts)
|
||||
|
||||
# Single mode
|
||||
if not slug:
|
||||
return ""
|
||||
post = await blog_service.get_post_by_slug(g.s, slug)
|
||||
if not post:
|
||||
return ""
|
||||
return _blog_link_card_sx(post, blog_url(f"/{post.slug}"))
|
||||
|
||||
_handlers["link-card"] = _link_card_handler
|
||||
|
||||
bp._fragment_handlers = _handlers
|
||||
handler_def = get_handler("blog", fragment_type)
|
||||
if handler_def is not None:
|
||||
result = await execute_handler(
|
||||
handler_def, "blog", args=dict(request.args),
|
||||
)
|
||||
return Response(result, status=200, content_type="text/sx")
|
||||
return Response("", status=200, content_type="text/sx")
|
||||
|
||||
return bp
|
||||
|
||||
31
blog/sx/handlers/link-card.sx
Normal file
31
blog/sx/handlers/link-card.sx
Normal file
@@ -0,0 +1,31 @@
|
||||
;; Blog link-card fragment handler
|
||||
;;
|
||||
;; Renders link-card(s) for blog posts by slug.
|
||||
;; Supports single mode (?slug=x) and batch mode (?keys=x,y,z).
|
||||
|
||||
(defhandler link-card (&key slug keys)
|
||||
(if keys
|
||||
(let ((slugs (split keys ",")))
|
||||
(<> (map (fn (s)
|
||||
(let ((post (query "blog" "post-by-slug" :slug (trim s))))
|
||||
(when post
|
||||
(<> (str "<!-- fragment:" (trim s) " -->")
|
||||
(~link-card
|
||||
:link (app-url "blog" (str "/" (get post "slug") "/"))
|
||||
:title (get post "title")
|
||||
:image (get post "feature_image")
|
||||
:icon "fas fa-file-alt"
|
||||
:subtitle (or (get post "custom_excerpt") (get post "excerpt"))
|
||||
:detail (get post "published_at_display")
|
||||
:data-app "blog"))))) slugs)))
|
||||
(when slug
|
||||
(let ((post (query "blog" "post-by-slug" :slug slug)))
|
||||
(when post
|
||||
(~link-card
|
||||
:link (app-url "blog" (str "/" (get post "slug") "/"))
|
||||
:title (get post "title")
|
||||
:image (get post "feature_image")
|
||||
:icon "fas fa-file-alt"
|
||||
:subtitle (or (get post "custom_excerpt") (get post "excerpt"))
|
||||
:detail (get post "published_at_display")
|
||||
:data-app "blog"))))))
|
||||
80
blog/sx/handlers/nav-tree.sx
Normal file
80
blog/sx/handlers/nav-tree.sx
Normal file
@@ -0,0 +1,80 @@
|
||||
;; Blog nav-tree fragment handler
|
||||
;;
|
||||
;; Renders the full scrollable navigation menu bar with app icons.
|
||||
;; Uses nav-tree I/O primitive to fetch menu nodes from the blog DB.
|
||||
|
||||
(defhandler nav-tree (&key app_name path)
|
||||
(let ((app (or app_name ""))
|
||||
(cur-path (or path "/"))
|
||||
(first-seg (first (filter (fn (s) (not (empty? s)))
|
||||
(split (trim cur-path) "/"))))
|
||||
(items (nav-tree))
|
||||
(nav-cls "whitespace-nowrap flex items-center gap-2 rounded p-2 text-sm")
|
||||
|
||||
;; App slug → URL mapping
|
||||
(app-slugs (dict
|
||||
:cart (app-url "cart" "/")
|
||||
:market (app-url "market" "/")
|
||||
:events (app-url "events" "/")
|
||||
:federation (app-url "federation" "/")
|
||||
:account (app-url "account" "/")
|
||||
:artdag (app-url "artdag" "/"))))
|
||||
|
||||
(let ((item-sxs
|
||||
(<>
|
||||
;; Nav items from DB
|
||||
(map (fn (item)
|
||||
(let ((item-slug (or (get item "slug") ""))
|
||||
(href (or (get app-slugs item-slug)
|
||||
(app-url "blog" (str "/" item-slug "/"))))
|
||||
(selected (or (= item-slug (or first-seg ""))
|
||||
(= item-slug app))))
|
||||
(~blog-nav-item-link
|
||||
:href href
|
||||
:hx-get href
|
||||
:selected (if selected "true" "false")
|
||||
:nav-cls nav-cls
|
||||
:img (~img-or-placeholder
|
||||
:src (get item "feature_image")
|
||||
:alt (or (get item "label") item-slug)
|
||||
:size-cls "w-8 h-8 rounded-full object-cover flex-shrink-0")
|
||||
:label (or (get item "label") item-slug)))) items)
|
||||
|
||||
;; Hardcoded artdag link
|
||||
(~blog-nav-item-link
|
||||
:href (app-url "artdag" "/")
|
||||
:hx-get (app-url "artdag" "/")
|
||||
:selected (if (or (= "artdag" (or first-seg ""))
|
||||
(= "artdag" app)) "true" "false")
|
||||
:nav-cls nav-cls
|
||||
:img (~img-or-placeholder
|
||||
:src nil :alt "art-dag"
|
||||
:size-cls "w-8 h-8 rounded-full object-cover flex-shrink-0")
|
||||
:label "art-dag")))
|
||||
|
||||
;; Scroll wrapper IDs + hyperscript
|
||||
(arrow-cls "scrolling-menu-arrow-menu-items-container")
|
||||
(cid "menu-items-container")
|
||||
(left-hs (str "on click set #" cid ".scrollLeft to #" cid ".scrollLeft - 200"))
|
||||
(scroll-hs (str "on scroll "
|
||||
"set cls to '" arrow-cls "' "
|
||||
"set arrows to document.getElementsByClassName(cls) "
|
||||
"set show to (window.innerWidth >= 640 and "
|
||||
"my.scrollWidth > my.clientWidth) "
|
||||
"repeat for arrow in arrows "
|
||||
"if show remove .hidden from arrow add .flex to arrow "
|
||||
"else add .hidden to arrow remove .flex from arrow end "
|
||||
"end"))
|
||||
(right-hs (str "on click set #" cid ".scrollLeft to #" cid ".scrollLeft + 200")))
|
||||
|
||||
(if (empty? items)
|
||||
(~blog-nav-empty :wrapper-id "menu-items-nav-wrapper")
|
||||
(~scroll-nav-wrapper
|
||||
:wrapper-id "menu-items-nav-wrapper"
|
||||
:container-id cid
|
||||
:arrow-cls arrow-cls
|
||||
:left-hs left-hs
|
||||
:scroll-hs scroll-hs
|
||||
:right-hs right-hs
|
||||
:items item-sxs
|
||||
:oob true)))))
|
||||
@@ -28,8 +28,8 @@ from shared.sx.helpers import (
|
||||
full_page_sx,
|
||||
)
|
||||
|
||||
# Load blog service .sx component definitions
|
||||
load_service_components(os.path.dirname(os.path.dirname(__file__)))
|
||||
# Load blog service .sx component definitions + handler definitions
|
||||
load_service_components(os.path.dirname(os.path.dirname(__file__)), service_name="blog")
|
||||
|
||||
|
||||
def _ctx_csrf(ctx: dict) -> str:
|
||||
|
||||
Reference in New Issue
Block a user